CalledValuePropagation.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. //===- CalledValuePropagation.cpp - Propagate called values -----*- C++ -*-===//
  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. // This file implements a transformation that attaches !callees metadata to
  10. // indirect call sites. For a given call site, the metadata, if present,
  11. // indicates the set of functions the call site could possibly target at
  12. // run-time. This metadata is added to indirect call sites when the set of
  13. // possible targets can be determined by analysis and is known to be small. The
  14. // analysis driving the transformation is similar to constant propagation and
  15. // makes uses of the generic sparse propagation solver.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/IPO/CalledValuePropagation.h"
  19. #include "llvm/Analysis/SparsePropagation.h"
  20. #include "llvm/Analysis/ValueLatticeUtils.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/MDBuilder.h"
  23. #include "llvm/InitializePasses.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Transforms/IPO.h"
  27. using namespace llvm;
  28. #define DEBUG_TYPE "called-value-propagation"
  29. /// The maximum number of functions to track per lattice value. Once the number
  30. /// of functions a call site can possibly target exceeds this threshold, it's
  31. /// lattice value becomes overdefined. The number of possible lattice values is
  32. /// bounded by Ch(F, M), where F is the number of functions in the module and M
  33. /// is MaxFunctionsPerValue. As such, this value should be kept very small. We
  34. /// likely can't do anything useful for call sites with a large number of
  35. /// possible targets, anyway.
  36. static cl::opt<unsigned> MaxFunctionsPerValue(
  37. "cvp-max-functions-per-value", cl::Hidden, cl::init(4),
  38. cl::desc("The maximum number of functions to track per lattice value"));
  39. namespace {
  40. /// To enable interprocedural analysis, we assign LLVM values to the following
  41. /// groups. The register group represents SSA registers, the return group
  42. /// represents the return values of functions, and the memory group represents
  43. /// in-memory values. An LLVM Value can technically be in more than one group.
  44. /// It's necessary to distinguish these groups so we can, for example, track a
  45. /// global variable separately from the value stored at its location.
  46. enum class IPOGrouping { Register, Return, Memory };
  47. /// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.
  48. using CVPLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;
  49. /// The lattice value type used by our custom lattice function. It holds the
  50. /// lattice state, and a set of functions.
  51. class CVPLatticeVal {
  52. public:
  53. /// The states of the lattice values. Only the FunctionSet state is
  54. /// interesting. It indicates the set of functions to which an LLVM value may
  55. /// refer.
  56. enum CVPLatticeStateTy { Undefined, FunctionSet, Overdefined, Untracked };
  57. /// Comparator for sorting the functions set. We want to keep the order
  58. /// deterministic for testing, etc.
  59. struct Compare {
  60. bool operator()(const Function *LHS, const Function *RHS) const {
  61. return LHS->getName() < RHS->getName();
  62. }
  63. };
  64. CVPLatticeVal() = default;
  65. CVPLatticeVal(CVPLatticeStateTy LatticeState) : LatticeState(LatticeState) {}
  66. CVPLatticeVal(std::vector<Function *> &&Functions)
  67. : LatticeState(FunctionSet), Functions(std::move(Functions)) {
  68. assert(llvm::is_sorted(this->Functions, Compare()));
  69. }
  70. /// Get a reference to the functions held by this lattice value. The number
  71. /// of functions will be zero for states other than FunctionSet.
  72. const std::vector<Function *> &getFunctions() const {
  73. return Functions;
  74. }
  75. /// Returns true if the lattice value is in the FunctionSet state.
  76. bool isFunctionSet() const { return LatticeState == FunctionSet; }
  77. bool operator==(const CVPLatticeVal &RHS) const {
  78. return LatticeState == RHS.LatticeState && Functions == RHS.Functions;
  79. }
  80. bool operator!=(const CVPLatticeVal &RHS) const {
  81. return LatticeState != RHS.LatticeState || Functions != RHS.Functions;
  82. }
  83. private:
  84. /// Holds the state this lattice value is in.
  85. CVPLatticeStateTy LatticeState = Undefined;
  86. /// Holds functions indicating the possible targets of call sites. This set
  87. /// is empty for lattice values in the undefined, overdefined, and untracked
  88. /// states. The maximum size of the set is controlled by
  89. /// MaxFunctionsPerValue. Since most LLVM values are expected to be in
  90. /// uninteresting states (i.e., overdefined), CVPLatticeVal objects should be
  91. /// small and efficiently copyable.
  92. // FIXME: This could be a TinyPtrVector and/or merge with LatticeState.
  93. std::vector<Function *> Functions;
  94. };
  95. /// The custom lattice function used by the generic sparse propagation solver.
  96. /// It handles merging lattice values and computing new lattice values for
  97. /// constants, arguments, values returned from trackable functions, and values
  98. /// located in trackable global variables. It also computes the lattice values
  99. /// that change as a result of executing instructions.
  100. class CVPLatticeFunc
  101. : public AbstractLatticeFunction<CVPLatticeKey, CVPLatticeVal> {
  102. public:
  103. CVPLatticeFunc()
  104. : AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined),
  105. CVPLatticeVal(CVPLatticeVal::Overdefined),
  106. CVPLatticeVal(CVPLatticeVal::Untracked)) {}
  107. /// Compute and return a CVPLatticeVal for the given CVPLatticeKey.
  108. CVPLatticeVal ComputeLatticeVal(CVPLatticeKey Key) override {
  109. switch (Key.getInt()) {
  110. case IPOGrouping::Register:
  111. if (isa<Instruction>(Key.getPointer())) {
  112. return getUndefVal();
  113. } else if (auto *A = dyn_cast<Argument>(Key.getPointer())) {
  114. if (canTrackArgumentsInterprocedurally(A->getParent()))
  115. return getUndefVal();
  116. } else if (auto *C = dyn_cast<Constant>(Key.getPointer())) {
  117. return computeConstant(C);
  118. }
  119. return getOverdefinedVal();
  120. case IPOGrouping::Memory:
  121. case IPOGrouping::Return:
  122. if (auto *GV = dyn_cast<GlobalVariable>(Key.getPointer())) {
  123. if (canTrackGlobalVariableInterprocedurally(GV))
  124. return computeConstant(GV->getInitializer());
  125. } else if (auto *F = cast<Function>(Key.getPointer()))
  126. if (canTrackReturnsInterprocedurally(F))
  127. return getUndefVal();
  128. }
  129. return getOverdefinedVal();
  130. }
  131. /// Merge the two given lattice values. The interesting cases are merging two
  132. /// FunctionSet values and a FunctionSet value with an Undefined value. For
  133. /// these cases, we simply union the function sets. If the size of the union
  134. /// is greater than the maximum functions we track, the merged value is
  135. /// overdefined.
  136. CVPLatticeVal MergeValues(CVPLatticeVal X, CVPLatticeVal Y) override {
  137. if (X == getOverdefinedVal() || Y == getOverdefinedVal())
  138. return getOverdefinedVal();
  139. if (X == getUndefVal() && Y == getUndefVal())
  140. return getUndefVal();
  141. std::vector<Function *> Union;
  142. std::set_union(X.getFunctions().begin(), X.getFunctions().end(),
  143. Y.getFunctions().begin(), Y.getFunctions().end(),
  144. std::back_inserter(Union), CVPLatticeVal::Compare{});
  145. if (Union.size() > MaxFunctionsPerValue)
  146. return getOverdefinedVal();
  147. return CVPLatticeVal(std::move(Union));
  148. }
  149. /// Compute the lattice values that change as a result of executing the given
  150. /// instruction. The changed values are stored in \p ChangedValues. We handle
  151. /// just a few kinds of instructions since we're only propagating values that
  152. /// can be called.
  153. void ComputeInstructionState(
  154. Instruction &I, DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  155. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) override {
  156. switch (I.getOpcode()) {
  157. case Instruction::Call:
  158. case Instruction::Invoke:
  159. return visitCallBase(cast<CallBase>(I), ChangedValues, SS);
  160. case Instruction::Load:
  161. return visitLoad(*cast<LoadInst>(&I), ChangedValues, SS);
  162. case Instruction::Ret:
  163. return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);
  164. case Instruction::Select:
  165. return visitSelect(*cast<SelectInst>(&I), ChangedValues, SS);
  166. case Instruction::Store:
  167. return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);
  168. default:
  169. return visitInst(I, ChangedValues, SS);
  170. }
  171. }
  172. /// Print the given CVPLatticeVal to the specified stream.
  173. void PrintLatticeVal(CVPLatticeVal LV, raw_ostream &OS) override {
  174. if (LV == getUndefVal())
  175. OS << "Undefined ";
  176. else if (LV == getOverdefinedVal())
  177. OS << "Overdefined";
  178. else if (LV == getUntrackedVal())
  179. OS << "Untracked ";
  180. else
  181. OS << "FunctionSet";
  182. }
  183. /// Print the given CVPLatticeKey to the specified stream.
  184. void PrintLatticeKey(CVPLatticeKey Key, raw_ostream &OS) override {
  185. if (Key.getInt() == IPOGrouping::Register)
  186. OS << "<reg> ";
  187. else if (Key.getInt() == IPOGrouping::Memory)
  188. OS << "<mem> ";
  189. else if (Key.getInt() == IPOGrouping::Return)
  190. OS << "<ret> ";
  191. if (isa<Function>(Key.getPointer()))
  192. OS << Key.getPointer()->getName();
  193. else
  194. OS << *Key.getPointer();
  195. }
  196. /// We collect a set of indirect calls when visiting call sites. This method
  197. /// returns a reference to that set.
  198. SmallPtrSetImpl<CallBase *> &getIndirectCalls() { return IndirectCalls; }
  199. private:
  200. /// Holds the indirect calls we encounter during the analysis. We will attach
  201. /// metadata to these calls after the analysis indicating the functions the
  202. /// calls can possibly target.
  203. SmallPtrSet<CallBase *, 32> IndirectCalls;
  204. /// Compute a new lattice value for the given constant. The constant, after
  205. /// stripping any pointer casts, should be a Function. We ignore null
  206. /// pointers as an optimization, since calling these values is undefined
  207. /// behavior.
  208. CVPLatticeVal computeConstant(Constant *C) {
  209. if (isa<ConstantPointerNull>(C))
  210. return CVPLatticeVal(CVPLatticeVal::FunctionSet);
  211. if (auto *F = dyn_cast<Function>(C->stripPointerCasts()))
  212. return CVPLatticeVal({F});
  213. return getOverdefinedVal();
  214. }
  215. /// Handle return instructions. The function's return state is the merge of
  216. /// the returned value state and the function's return state.
  217. void visitReturn(ReturnInst &I,
  218. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  219. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  220. Function *F = I.getParent()->getParent();
  221. if (F->getReturnType()->isVoidTy())
  222. return;
  223. auto RegI = CVPLatticeKey(I.getReturnValue(), IPOGrouping::Register);
  224. auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
  225. ChangedValues[RetF] =
  226. MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
  227. }
  228. /// Handle call sites. The state of a called function's formal arguments is
  229. /// the merge of the argument state with the call sites corresponding actual
  230. /// argument state. The call site state is the merge of the call site state
  231. /// with the returned value state of the called function.
  232. void visitCallBase(CallBase &CB,
  233. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  234. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  235. Function *F = CB.getCalledFunction();
  236. auto RegI = CVPLatticeKey(&CB, IPOGrouping::Register);
  237. // If this is an indirect call, save it so we can quickly revisit it when
  238. // attaching metadata.
  239. if (!F)
  240. IndirectCalls.insert(&CB);
  241. // If we can't track the function's return values, there's nothing to do.
  242. if (!F || !canTrackReturnsInterprocedurally(F)) {
  243. // Void return, No need to create and update CVPLattice state as no one
  244. // can use it.
  245. if (CB.getType()->isVoidTy())
  246. return;
  247. ChangedValues[RegI] = getOverdefinedVal();
  248. return;
  249. }
  250. // Inform the solver that the called function is executable, and perform
  251. // the merges for the arguments and return value.
  252. SS.MarkBlockExecutable(&F->front());
  253. auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
  254. for (Argument &A : F->args()) {
  255. auto RegFormal = CVPLatticeKey(&A, IPOGrouping::Register);
  256. auto RegActual =
  257. CVPLatticeKey(CB.getArgOperand(A.getArgNo()), IPOGrouping::Register);
  258. ChangedValues[RegFormal] =
  259. MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));
  260. }
  261. // Void return, No need to create and update CVPLattice state as no one can
  262. // use it.
  263. if (CB.getType()->isVoidTy())
  264. return;
  265. ChangedValues[RegI] =
  266. MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
  267. }
  268. /// Handle select instructions. The select instruction state is the merge the
  269. /// true and false value states.
  270. void visitSelect(SelectInst &I,
  271. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  272. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  273. auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
  274. auto RegT = CVPLatticeKey(I.getTrueValue(), IPOGrouping::Register);
  275. auto RegF = CVPLatticeKey(I.getFalseValue(), IPOGrouping::Register);
  276. ChangedValues[RegI] =
  277. MergeValues(SS.getValueState(RegT), SS.getValueState(RegF));
  278. }
  279. /// Handle load instructions. If the pointer operand of the load is a global
  280. /// variable, we attempt to track the value. The loaded value state is the
  281. /// merge of the loaded value state with the global variable state.
  282. void visitLoad(LoadInst &I,
  283. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  284. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  285. auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
  286. if (auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand())) {
  287. auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
  288. ChangedValues[RegI] =
  289. MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
  290. } else {
  291. ChangedValues[RegI] = getOverdefinedVal();
  292. }
  293. }
  294. /// Handle store instructions. If the pointer operand of the store is a
  295. /// global variable, we attempt to track the value. The global variable state
  296. /// is the merge of the stored value state with the global variable state.
  297. void visitStore(StoreInst &I,
  298. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  299. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  300. auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());
  301. if (!GV)
  302. return;
  303. auto RegI = CVPLatticeKey(I.getValueOperand(), IPOGrouping::Register);
  304. auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
  305. ChangedValues[MemGV] =
  306. MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
  307. }
  308. /// Handle all other instructions. All other instructions are marked
  309. /// overdefined.
  310. void visitInst(Instruction &I,
  311. DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
  312. SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
  313. // Simply bail if this instruction has no user.
  314. if (I.use_empty())
  315. return;
  316. auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
  317. ChangedValues[RegI] = getOverdefinedVal();
  318. }
  319. };
  320. } // namespace
  321. namespace llvm {
  322. /// A specialization of LatticeKeyInfo for CVPLatticeKeys. The generic solver
  323. /// must translate between LatticeKeys and LLVM Values when adding Values to
  324. /// its work list and inspecting the state of control-flow related values.
  325. template <> struct LatticeKeyInfo<CVPLatticeKey> {
  326. static inline Value *getValueFromLatticeKey(CVPLatticeKey Key) {
  327. return Key.getPointer();
  328. }
  329. static inline CVPLatticeKey getLatticeKeyFromValue(Value *V) {
  330. return CVPLatticeKey(V, IPOGrouping::Register);
  331. }
  332. };
  333. } // namespace llvm
  334. static bool runCVP(Module &M) {
  335. // Our custom lattice function and generic sparse propagation solver.
  336. CVPLatticeFunc Lattice;
  337. SparseSolver<CVPLatticeKey, CVPLatticeVal> Solver(&Lattice);
  338. // For each function in the module, if we can't track its arguments, let the
  339. // generic solver assume it is executable.
  340. for (Function &F : M)
  341. if (!F.isDeclaration() && !canTrackArgumentsInterprocedurally(&F))
  342. Solver.MarkBlockExecutable(&F.front());
  343. // Solver our custom lattice. In doing so, we will also build a set of
  344. // indirect call sites.
  345. Solver.Solve();
  346. // Attach metadata to the indirect call sites that were collected indicating
  347. // the set of functions they can possibly target.
  348. bool Changed = false;
  349. MDBuilder MDB(M.getContext());
  350. for (CallBase *C : Lattice.getIndirectCalls()) {
  351. auto RegI = CVPLatticeKey(C->getCalledOperand(), IPOGrouping::Register);
  352. CVPLatticeVal LV = Solver.getExistingValueState(RegI);
  353. if (!LV.isFunctionSet() || LV.getFunctions().empty())
  354. continue;
  355. MDNode *Callees = MDB.createCallees(LV.getFunctions());
  356. C->setMetadata(LLVMContext::MD_callees, Callees);
  357. Changed = true;
  358. }
  359. return Changed;
  360. }
  361. PreservedAnalyses CalledValuePropagationPass::run(Module &M,
  362. ModuleAnalysisManager &) {
  363. runCVP(M);
  364. return PreservedAnalyses::all();
  365. }
  366. namespace {
  367. class CalledValuePropagationLegacyPass : public ModulePass {
  368. public:
  369. static char ID;
  370. void getAnalysisUsage(AnalysisUsage &AU) const override {
  371. AU.setPreservesAll();
  372. }
  373. CalledValuePropagationLegacyPass() : ModulePass(ID) {
  374. initializeCalledValuePropagationLegacyPassPass(
  375. *PassRegistry::getPassRegistry());
  376. }
  377. bool runOnModule(Module &M) override {
  378. if (skipModule(M))
  379. return false;
  380. return runCVP(M);
  381. }
  382. };
  383. } // namespace
  384. char CalledValuePropagationLegacyPass::ID = 0;
  385. INITIALIZE_PASS(CalledValuePropagationLegacyPass, "called-value-propagation",
  386. "Called Value Propagation", false, false)
  387. ModulePass *llvm::createCalledValuePropagationPass() {
  388. return new CalledValuePropagationLegacyPass();
  389. }