ConstantHoisting.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
  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 pass identifies expensive constants to hoist and coalesces them to
  10. // better prepare it for SelectionDAG-based code generation. This works around
  11. // the limitations of the basic-block-at-a-time approach.
  12. //
  13. // First it scans all instructions for integer constants and calculates its
  14. // cost. If the constant can be folded into the instruction (the cost is
  15. // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
  16. // consider it expensive and leave it alone. This is the default behavior and
  17. // the default implementation of getIntImmCostInst will always return TCC_Free.
  18. //
  19. // If the cost is more than TCC_BASIC, then the integer constant can't be folded
  20. // into the instruction and it might be beneficial to hoist the constant.
  21. // Similar constants are coalesced to reduce register pressure and
  22. // materialization code.
  23. //
  24. // When a constant is hoisted, it is also hidden behind a bitcast to force it to
  25. // be live-out of the basic block. Otherwise the constant would be just
  26. // duplicated and each basic block would have its own copy in the SelectionDAG.
  27. // The SelectionDAG recognizes such constants as opaque and doesn't perform
  28. // certain transformations on them, which would create a new expensive constant.
  29. //
  30. // This optimization is only applied to integer constants in instructions and
  31. // simple (this means not nested) constant cast expressions. For example:
  32. // %0 = load i64* inttoptr (i64 big_constant to i64*)
  33. //===----------------------------------------------------------------------===//
  34. #include "llvm/Transforms/Scalar/ConstantHoisting.h"
  35. #include "llvm/ADT/APInt.h"
  36. #include "llvm/ADT/DenseMap.h"
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. #include "llvm/ADT/Statistic.h"
  40. #include "llvm/Analysis/BlockFrequencyInfo.h"
  41. #include "llvm/Analysis/ProfileSummaryInfo.h"
  42. #include "llvm/Analysis/TargetTransformInfo.h"
  43. #include "llvm/IR/BasicBlock.h"
  44. #include "llvm/IR/Constants.h"
  45. #include "llvm/IR/DebugInfoMetadata.h"
  46. #include "llvm/IR/Dominators.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/InstrTypes.h"
  49. #include "llvm/IR/Instruction.h"
  50. #include "llvm/IR/Instructions.h"
  51. #include "llvm/IR/IntrinsicInst.h"
  52. #include "llvm/IR/Operator.h"
  53. #include "llvm/IR/Value.h"
  54. #include "llvm/InitializePasses.h"
  55. #include "llvm/Pass.h"
  56. #include "llvm/Support/BlockFrequency.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Debug.h"
  60. #include "llvm/Support/raw_ostream.h"
  61. #include "llvm/Transforms/Scalar.h"
  62. #include "llvm/Transforms/Utils/Local.h"
  63. #include "llvm/Transforms/Utils/SizeOpts.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cstdint>
  67. #include <iterator>
  68. #include <tuple>
  69. #include <utility>
  70. using namespace llvm;
  71. using namespace consthoist;
  72. #define DEBUG_TYPE "consthoist"
  73. STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
  74. STATISTIC(NumConstantsRebased, "Number of constants rebased");
  75. static cl::opt<bool> ConstHoistWithBlockFrequency(
  76. "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
  77. cl::desc("Enable the use of the block frequency analysis to reduce the "
  78. "chance to execute const materialization more frequently than "
  79. "without hoisting."));
  80. static cl::opt<bool> ConstHoistGEP(
  81. "consthoist-gep", cl::init(false), cl::Hidden,
  82. cl::desc("Try hoisting constant gep expressions"));
  83. static cl::opt<unsigned>
  84. MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
  85. cl::desc("Do not rebase if number of dependent constants of a Base is less "
  86. "than this number."),
  87. cl::init(0), cl::Hidden);
  88. namespace {
  89. /// The constant hoisting pass.
  90. class ConstantHoistingLegacyPass : public FunctionPass {
  91. public:
  92. static char ID; // Pass identification, replacement for typeid
  93. ConstantHoistingLegacyPass() : FunctionPass(ID) {
  94. initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
  95. }
  96. bool runOnFunction(Function &Fn) override;
  97. StringRef getPassName() const override { return "Constant Hoisting"; }
  98. void getAnalysisUsage(AnalysisUsage &AU) const override {
  99. AU.setPreservesCFG();
  100. if (ConstHoistWithBlockFrequency)
  101. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  102. AU.addRequired<DominatorTreeWrapperPass>();
  103. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  104. AU.addRequired<TargetTransformInfoWrapperPass>();
  105. }
  106. private:
  107. ConstantHoistingPass Impl;
  108. };
  109. } // end anonymous namespace
  110. char ConstantHoistingLegacyPass::ID = 0;
  111. INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
  112. "Constant Hoisting", false, false)
  113. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  114. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  115. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  116. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  117. INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
  118. "Constant Hoisting", false, false)
  119. FunctionPass *llvm::createConstantHoistingPass() {
  120. return new ConstantHoistingLegacyPass();
  121. }
  122. /// Perform the constant hoisting optimization for the given function.
  123. bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
  124. if (skipFunction(Fn))
  125. return false;
  126. LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
  127. LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
  128. bool MadeChange =
  129. Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
  130. getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  131. ConstHoistWithBlockFrequency
  132. ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
  133. : nullptr,
  134. Fn.getEntryBlock(),
  135. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
  136. if (MadeChange) {
  137. LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
  138. << Fn.getName() << '\n');
  139. LLVM_DEBUG(dbgs() << Fn);
  140. }
  141. LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
  142. return MadeChange;
  143. }
  144. /// Find the constant materialization insertion point.
  145. Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
  146. unsigned Idx) const {
  147. // If the operand is a cast instruction, then we have to materialize the
  148. // constant before the cast instruction.
  149. if (Idx != ~0U) {
  150. Value *Opnd = Inst->getOperand(Idx);
  151. if (auto CastInst = dyn_cast<Instruction>(Opnd))
  152. if (CastInst->isCast())
  153. return CastInst;
  154. }
  155. // The simple and common case. This also includes constant expressions.
  156. if (!isa<PHINode>(Inst) && !Inst->isEHPad())
  157. return Inst;
  158. // We can't insert directly before a phi node or an eh pad. Insert before
  159. // the terminator of the incoming or dominating block.
  160. assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
  161. BasicBlock *InsertionBlock = nullptr;
  162. if (Idx != ~0U && isa<PHINode>(Inst)) {
  163. InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
  164. if (!InsertionBlock->isEHPad()) {
  165. return InsertionBlock->getTerminator();
  166. }
  167. } else {
  168. InsertionBlock = Inst->getParent();
  169. }
  170. // This must be an EH pad. Iterate over immediate dominators until we find a
  171. // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
  172. // and terminators.
  173. auto *IDom = DT->getNode(InsertionBlock)->getIDom();
  174. while (IDom->getBlock()->isEHPad()) {
  175. assert(Entry != IDom->getBlock() && "eh pad in entry block");
  176. IDom = IDom->getIDom();
  177. }
  178. return IDom->getBlock()->getTerminator();
  179. }
  180. /// Given \p BBs as input, find another set of BBs which collectively
  181. /// dominates \p BBs and have the minimal sum of frequencies. Return the BB
  182. /// set found in \p BBs.
  183. static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
  184. BasicBlock *Entry,
  185. SetVector<BasicBlock *> &BBs) {
  186. assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
  187. // Nodes on the current path to the root.
  188. SmallPtrSet<BasicBlock *, 8> Path;
  189. // Candidates includes any block 'BB' in set 'BBs' that is not strictly
  190. // dominated by any other blocks in set 'BBs', and all nodes in the path
  191. // in the dominator tree from Entry to 'BB'.
  192. SmallPtrSet<BasicBlock *, 16> Candidates;
  193. for (auto *BB : BBs) {
  194. // Ignore unreachable basic blocks.
  195. if (!DT.isReachableFromEntry(BB))
  196. continue;
  197. Path.clear();
  198. // Walk up the dominator tree until Entry or another BB in BBs
  199. // is reached. Insert the nodes on the way to the Path.
  200. BasicBlock *Node = BB;
  201. // The "Path" is a candidate path to be added into Candidates set.
  202. bool isCandidate = false;
  203. do {
  204. Path.insert(Node);
  205. if (Node == Entry || Candidates.count(Node)) {
  206. isCandidate = true;
  207. break;
  208. }
  209. assert(DT.getNode(Node)->getIDom() &&
  210. "Entry doens't dominate current Node");
  211. Node = DT.getNode(Node)->getIDom()->getBlock();
  212. } while (!BBs.count(Node));
  213. // If isCandidate is false, Node is another Block in BBs dominating
  214. // current 'BB'. Drop the nodes on the Path.
  215. if (!isCandidate)
  216. continue;
  217. // Add nodes on the Path into Candidates.
  218. Candidates.insert(Path.begin(), Path.end());
  219. }
  220. // Sort the nodes in Candidates in top-down order and save the nodes
  221. // in Orders.
  222. unsigned Idx = 0;
  223. SmallVector<BasicBlock *, 16> Orders;
  224. Orders.push_back(Entry);
  225. while (Idx != Orders.size()) {
  226. BasicBlock *Node = Orders[Idx++];
  227. for (auto *ChildDomNode : DT.getNode(Node)->children()) {
  228. if (Candidates.count(ChildDomNode->getBlock()))
  229. Orders.push_back(ChildDomNode->getBlock());
  230. }
  231. }
  232. // Visit Orders in bottom-up order.
  233. using InsertPtsCostPair =
  234. std::pair<SetVector<BasicBlock *>, BlockFrequency>;
  235. // InsertPtsMap is a map from a BB to the best insertion points for the
  236. // subtree of BB (subtree not including the BB itself).
  237. DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
  238. InsertPtsMap.reserve(Orders.size() + 1);
  239. for (BasicBlock *Node : llvm::reverse(Orders)) {
  240. bool NodeInBBs = BBs.count(Node);
  241. auto &InsertPts = InsertPtsMap[Node].first;
  242. BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
  243. // Return the optimal insert points in BBs.
  244. if (Node == Entry) {
  245. BBs.clear();
  246. if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
  247. (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
  248. BBs.insert(Entry);
  249. else
  250. BBs.insert(InsertPts.begin(), InsertPts.end());
  251. break;
  252. }
  253. BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
  254. // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
  255. // will update its parent's ParentInsertPts and ParentPtsFreq.
  256. auto &ParentInsertPts = InsertPtsMap[Parent].first;
  257. BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
  258. // Choose to insert in Node or in subtree of Node.
  259. // Don't hoist to EHPad because we may not find a proper place to insert
  260. // in EHPad.
  261. // If the total frequency of InsertPts is the same as the frequency of the
  262. // target Node, and InsertPts contains more than one nodes, choose hoisting
  263. // to reduce code size.
  264. if (NodeInBBs ||
  265. (!Node->isEHPad() &&
  266. (InsertPtsFreq > BFI.getBlockFreq(Node) ||
  267. (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
  268. ParentInsertPts.insert(Node);
  269. ParentPtsFreq += BFI.getBlockFreq(Node);
  270. } else {
  271. ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
  272. ParentPtsFreq += InsertPtsFreq;
  273. }
  274. }
  275. }
  276. /// Find an insertion point that dominates all uses.
  277. SetVector<Instruction *> ConstantHoistingPass::findConstantInsertionPoint(
  278. const ConstantInfo &ConstInfo) const {
  279. assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
  280. // Collect all basic blocks.
  281. SetVector<BasicBlock *> BBs;
  282. SetVector<Instruction *> InsertPts;
  283. for (auto const &RCI : ConstInfo.RebasedConstants)
  284. for (auto const &U : RCI.Uses)
  285. BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
  286. if (BBs.count(Entry)) {
  287. InsertPts.insert(&Entry->front());
  288. return InsertPts;
  289. }
  290. if (BFI) {
  291. findBestInsertionSet(*DT, *BFI, Entry, BBs);
  292. for (auto *BB : BBs) {
  293. BasicBlock::iterator InsertPt = BB->begin();
  294. for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
  295. ;
  296. InsertPts.insert(&*InsertPt);
  297. }
  298. return InsertPts;
  299. }
  300. while (BBs.size() >= 2) {
  301. BasicBlock *BB, *BB1, *BB2;
  302. BB1 = BBs.pop_back_val();
  303. BB2 = BBs.pop_back_val();
  304. BB = DT->findNearestCommonDominator(BB1, BB2);
  305. if (BB == Entry) {
  306. InsertPts.insert(&Entry->front());
  307. return InsertPts;
  308. }
  309. BBs.insert(BB);
  310. }
  311. assert((BBs.size() == 1) && "Expected only one element.");
  312. Instruction &FirstInst = (*BBs.begin())->front();
  313. InsertPts.insert(findMatInsertPt(&FirstInst));
  314. return InsertPts;
  315. }
  316. /// Record constant integer ConstInt for instruction Inst at operand
  317. /// index Idx.
  318. ///
  319. /// The operand at index Idx is not necessarily the constant integer itself. It
  320. /// could also be a cast instruction or a constant expression that uses the
  321. /// constant integer.
  322. void ConstantHoistingPass::collectConstantCandidates(
  323. ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
  324. ConstantInt *ConstInt) {
  325. InstructionCost Cost;
  326. // Ask the target about the cost of materializing the constant for the given
  327. // instruction and operand index.
  328. if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
  329. Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
  330. ConstInt->getValue(), ConstInt->getType(),
  331. TargetTransformInfo::TCK_SizeAndLatency);
  332. else
  333. Cost = TTI->getIntImmCostInst(
  334. Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
  335. TargetTransformInfo::TCK_SizeAndLatency, Inst);
  336. // Ignore cheap integer constants.
  337. if (Cost > TargetTransformInfo::TCC_Basic) {
  338. ConstCandMapType::iterator Itr;
  339. bool Inserted;
  340. ConstPtrUnionType Cand = ConstInt;
  341. std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
  342. if (Inserted) {
  343. ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
  344. Itr->second = ConstIntCandVec.size() - 1;
  345. }
  346. ConstIntCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
  347. LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
  348. << "Collect constant " << *ConstInt << " from " << *Inst
  349. << " with cost " << Cost << '\n';
  350. else dbgs() << "Collect constant " << *ConstInt
  351. << " indirectly from " << *Inst << " via "
  352. << *Inst->getOperand(Idx) << " with cost " << Cost
  353. << '\n';);
  354. }
  355. }
  356. /// Record constant GEP expression for instruction Inst at operand index Idx.
  357. void ConstantHoistingPass::collectConstantCandidates(
  358. ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
  359. ConstantExpr *ConstExpr) {
  360. // TODO: Handle vector GEPs
  361. if (ConstExpr->getType()->isVectorTy())
  362. return;
  363. GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
  364. if (!BaseGV)
  365. return;
  366. // Get offset from the base GV.
  367. PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
  368. IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
  369. APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
  370. auto *GEPO = cast<GEPOperator>(ConstExpr);
  371. // TODO: If we have a mix of inbounds and non-inbounds GEPs, then basing a
  372. // non-inbounds GEP on an inbounds GEP is potentially incorrect. Restrict to
  373. // inbounds GEP for now -- alternatively, we could drop inbounds from the
  374. // constant expression,
  375. if (!GEPO->isInBounds())
  376. return;
  377. if (!GEPO->accumulateConstantOffset(*DL, Offset))
  378. return;
  379. if (!Offset.isIntN(32))
  380. return;
  381. // A constant GEP expression that has a GlobalVariable as base pointer is
  382. // usually lowered to a load from constant pool. Such operation is unlikely
  383. // to be cheaper than compute it by <Base + Offset>, which can be lowered to
  384. // an ADD instruction or folded into Load/Store instruction.
  385. InstructionCost Cost =
  386. TTI->getIntImmCostInst(Instruction::Add, 1, Offset, PtrIntTy,
  387. TargetTransformInfo::TCK_SizeAndLatency, Inst);
  388. ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
  389. ConstCandMapType::iterator Itr;
  390. bool Inserted;
  391. ConstPtrUnionType Cand = ConstExpr;
  392. std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
  393. if (Inserted) {
  394. ExprCandVec.push_back(ConstantCandidate(
  395. ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
  396. ConstExpr));
  397. Itr->second = ExprCandVec.size() - 1;
  398. }
  399. ExprCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
  400. }
  401. /// Check the operand for instruction Inst at index Idx.
  402. void ConstantHoistingPass::collectConstantCandidates(
  403. ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
  404. Value *Opnd = Inst->getOperand(Idx);
  405. // Visit constant integers.
  406. if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
  407. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  408. return;
  409. }
  410. // Visit cast instructions that have constant integers.
  411. if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
  412. // Only visit cast instructions, which have been skipped. All other
  413. // instructions should have already been visited.
  414. if (!CastInst->isCast())
  415. return;
  416. if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
  417. // Pretend the constant is directly used by the instruction and ignore
  418. // the cast instruction.
  419. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  420. return;
  421. }
  422. }
  423. // Visit constant expressions that have constant integers.
  424. if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
  425. // Handle constant gep expressions.
  426. if (ConstHoistGEP && isa<GEPOperator>(ConstExpr))
  427. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
  428. // Only visit constant cast expressions.
  429. if (!ConstExpr->isCast())
  430. return;
  431. if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
  432. // Pretend the constant is directly used by the instruction and ignore
  433. // the constant expression.
  434. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  435. return;
  436. }
  437. }
  438. }
  439. /// Scan the instruction for expensive integer constants and record them
  440. /// in the constant candidate vector.
  441. void ConstantHoistingPass::collectConstantCandidates(
  442. ConstCandMapType &ConstCandMap, Instruction *Inst) {
  443. // Skip all cast instructions. They are visited indirectly later on.
  444. if (Inst->isCast())
  445. return;
  446. // Scan all operands.
  447. for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
  448. // The cost of materializing the constants (defined in
  449. // `TargetTransformInfo::getIntImmCostInst`) for instructions which only
  450. // take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
  451. // So it's safe for us to collect constant candidates from all
  452. // IntrinsicInsts.
  453. if (canReplaceOperandWithVariable(Inst, Idx)) {
  454. collectConstantCandidates(ConstCandMap, Inst, Idx);
  455. }
  456. } // end of for all operands
  457. }
  458. /// Collect all integer constants in the function that cannot be folded
  459. /// into an instruction itself.
  460. void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
  461. ConstCandMapType ConstCandMap;
  462. for (BasicBlock &BB : Fn) {
  463. // Ignore unreachable basic blocks.
  464. if (!DT->isReachableFromEntry(&BB))
  465. continue;
  466. for (Instruction &Inst : BB)
  467. collectConstantCandidates(ConstCandMap, &Inst);
  468. }
  469. }
  470. // This helper function is necessary to deal with values that have different
  471. // bit widths (APInt Operator- does not like that). If the value cannot be
  472. // represented in uint64 we return an "empty" APInt. This is then interpreted
  473. // as the value is not in range.
  474. static std::optional<APInt> calculateOffsetDiff(const APInt &V1,
  475. const APInt &V2) {
  476. std::optional<APInt> Res;
  477. unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
  478. V1.getBitWidth() : V2.getBitWidth();
  479. uint64_t LimVal1 = V1.getLimitedValue();
  480. uint64_t LimVal2 = V2.getLimitedValue();
  481. if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
  482. return Res;
  483. uint64_t Diff = LimVal1 - LimVal2;
  484. return APInt(BW, Diff, true);
  485. }
  486. // From a list of constants, one needs to picked as the base and the other
  487. // constants will be transformed into an offset from that base constant. The
  488. // question is which we can pick best? For example, consider these constants
  489. // and their number of uses:
  490. //
  491. // Constants| 2 | 4 | 12 | 42 |
  492. // NumUses | 3 | 2 | 8 | 7 |
  493. //
  494. // Selecting constant 12 because it has the most uses will generate negative
  495. // offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
  496. // offsets lead to less optimal code generation, then there might be better
  497. // solutions. Suppose immediates in the range of 0..35 are most optimally
  498. // supported by the architecture, then selecting constant 2 is most optimal
  499. // because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
  500. // range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
  501. // have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
  502. // selecting the base constant the range of the offsets is a very important
  503. // factor too that we take into account here. This algorithm calculates a total
  504. // costs for selecting a constant as the base and substract the costs if
  505. // immediates are out of range. It has quadratic complexity, so we call this
  506. // function only when we're optimising for size and there are less than 100
  507. // constants, we fall back to the straightforward algorithm otherwise
  508. // which does not do all the offset calculations.
  509. unsigned
  510. ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
  511. ConstCandVecType::iterator E,
  512. ConstCandVecType::iterator &MaxCostItr) {
  513. unsigned NumUses = 0;
  514. bool OptForSize = Entry->getParent()->hasOptSize() ||
  515. llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI,
  516. PGSOQueryType::IRPass);
  517. if (!OptForSize || std::distance(S,E) > 100) {
  518. for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
  519. NumUses += ConstCand->Uses.size();
  520. if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
  521. MaxCostItr = ConstCand;
  522. }
  523. return NumUses;
  524. }
  525. LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
  526. InstructionCost MaxCost = -1;
  527. for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
  528. auto Value = ConstCand->ConstInt->getValue();
  529. Type *Ty = ConstCand->ConstInt->getType();
  530. InstructionCost Cost = 0;
  531. NumUses += ConstCand->Uses.size();
  532. LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
  533. << "\n");
  534. for (auto User : ConstCand->Uses) {
  535. unsigned Opcode = User.Inst->getOpcode();
  536. unsigned OpndIdx = User.OpndIdx;
  537. Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
  538. TargetTransformInfo::TCK_SizeAndLatency);
  539. LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
  540. for (auto C2 = S; C2 != E; ++C2) {
  541. std::optional<APInt> Diff = calculateOffsetDiff(
  542. C2->ConstInt->getValue(), ConstCand->ConstInt->getValue());
  543. if (Diff) {
  544. const InstructionCost ImmCosts =
  545. TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, *Diff, Ty);
  546. Cost -= ImmCosts;
  547. LLVM_DEBUG(dbgs() << "Offset " << *Diff << " "
  548. << "has penalty: " << ImmCosts << "\n"
  549. << "Adjusted cost: " << Cost << "\n");
  550. }
  551. }
  552. }
  553. LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
  554. if (Cost > MaxCost) {
  555. MaxCost = Cost;
  556. MaxCostItr = ConstCand;
  557. LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
  558. << "\n");
  559. }
  560. }
  561. return NumUses;
  562. }
  563. /// Find the base constant within the given range and rebase all other
  564. /// constants with respect to the base constant.
  565. void ConstantHoistingPass::findAndMakeBaseConstant(
  566. ConstCandVecType::iterator S, ConstCandVecType::iterator E,
  567. SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
  568. auto MaxCostItr = S;
  569. unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
  570. // Don't hoist constants that have only one use.
  571. if (NumUses <= 1)
  572. return;
  573. ConstantInt *ConstInt = MaxCostItr->ConstInt;
  574. ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
  575. ConstantInfo ConstInfo;
  576. ConstInfo.BaseInt = ConstInt;
  577. ConstInfo.BaseExpr = ConstExpr;
  578. Type *Ty = ConstInt->getType();
  579. // Rebase the constants with respect to the base constant.
  580. for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
  581. APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
  582. Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
  583. Type *ConstTy =
  584. ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
  585. ConstInfo.RebasedConstants.push_back(
  586. RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
  587. }
  588. ConstInfoVec.push_back(std::move(ConstInfo));
  589. }
  590. /// Finds and combines constant candidates that can be easily
  591. /// rematerialized with an add from a common base constant.
  592. void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
  593. // If BaseGV is nullptr, find base among candidate constant integers;
  594. // Otherwise find base among constant GEPs that share the same BaseGV.
  595. ConstCandVecType &ConstCandVec = BaseGV ?
  596. ConstGEPCandMap[BaseGV] : ConstIntCandVec;
  597. ConstInfoVecType &ConstInfoVec = BaseGV ?
  598. ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
  599. // Sort the constants by value and type. This invalidates the mapping!
  600. llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
  601. const ConstantCandidate &RHS) {
  602. if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
  603. return LHS.ConstInt->getType()->getBitWidth() <
  604. RHS.ConstInt->getType()->getBitWidth();
  605. return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
  606. });
  607. // Simple linear scan through the sorted constant candidate vector for viable
  608. // merge candidates.
  609. auto MinValItr = ConstCandVec.begin();
  610. for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
  611. CC != E; ++CC) {
  612. if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
  613. Type *MemUseValTy = nullptr;
  614. for (auto &U : CC->Uses) {
  615. auto *UI = U.Inst;
  616. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  617. MemUseValTy = LI->getType();
  618. break;
  619. } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  620. // Make sure the constant is used as pointer operand of the StoreInst.
  621. if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
  622. MemUseValTy = SI->getValueOperand()->getType();
  623. break;
  624. }
  625. }
  626. }
  627. // Check if the constant is in range of an add with immediate.
  628. APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
  629. if ((Diff.getBitWidth() <= 64) &&
  630. TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
  631. // Check if Diff can be used as offset in addressing mode of the user
  632. // memory instruction.
  633. (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
  634. /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
  635. /*HasBaseReg*/true, /*Scale*/0)))
  636. continue;
  637. }
  638. // We either have now a different constant type or the constant is not in
  639. // range of an add with immediate anymore.
  640. findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
  641. // Start a new base constant search.
  642. MinValItr = CC;
  643. }
  644. // Finalize the last base constant search.
  645. findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
  646. }
  647. /// Updates the operand at Idx in instruction Inst with the result of
  648. /// instruction Mat. If the instruction is a PHI node then special
  649. /// handling for duplicate values from the same incoming basic block is
  650. /// required.
  651. /// \return The update will always succeed, but the return value indicated if
  652. /// Mat was used for the update or not.
  653. static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
  654. if (auto PHI = dyn_cast<PHINode>(Inst)) {
  655. // Check if any previous operand of the PHI node has the same incoming basic
  656. // block. This is a very odd case that happens when the incoming basic block
  657. // has a switch statement. In this case use the same value as the previous
  658. // operand(s), otherwise we will fail verification due to different values.
  659. // The values are actually the same, but the variable names are different
  660. // and the verifier doesn't like that.
  661. BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
  662. for (unsigned i = 0; i < Idx; ++i) {
  663. if (PHI->getIncomingBlock(i) == IncomingBB) {
  664. Value *IncomingVal = PHI->getIncomingValue(i);
  665. Inst->setOperand(Idx, IncomingVal);
  666. return false;
  667. }
  668. }
  669. }
  670. Inst->setOperand(Idx, Mat);
  671. return true;
  672. }
  673. /// Emit materialization code for all rebased constants and update their
  674. /// users.
  675. void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
  676. Constant *Offset,
  677. Type *Ty,
  678. const ConstantUser &ConstUser) {
  679. Instruction *Mat = Base;
  680. // The same offset can be dereferenced to different types in nested struct.
  681. if (!Offset && Ty && Ty != Base->getType())
  682. Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
  683. if (Offset) {
  684. Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
  685. ConstUser.OpndIdx);
  686. if (Ty) {
  687. // Constant being rebased is a ConstantExpr.
  688. PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
  689. cast<PointerType>(Ty)->getAddressSpace());
  690. Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
  691. Mat = GetElementPtrInst::Create(Type::getInt8Ty(*Ctx), Base,
  692. Offset, "mat_gep", InsertionPt);
  693. Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
  694. } else
  695. // Constant being rebased is a ConstantInt.
  696. Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
  697. "const_mat", InsertionPt);
  698. LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
  699. << " + " << *Offset << ") in BB "
  700. << Mat->getParent()->getName() << '\n'
  701. << *Mat << '\n');
  702. Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
  703. }
  704. Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
  705. // Visit constant integer.
  706. if (isa<ConstantInt>(Opnd)) {
  707. LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  708. if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
  709. Mat->eraseFromParent();
  710. LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  711. return;
  712. }
  713. // Visit cast instruction.
  714. if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
  715. assert(CastInst->isCast() && "Expected an cast instruction!");
  716. // Check if we already have visited this cast instruction before to avoid
  717. // unnecessary cloning.
  718. Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
  719. if (!ClonedCastInst) {
  720. ClonedCastInst = CastInst->clone();
  721. ClonedCastInst->setOperand(0, Mat);
  722. ClonedCastInst->insertAfter(CastInst);
  723. // Use the same debug location as the original cast instruction.
  724. ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
  725. LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
  726. << "To : " << *ClonedCastInst << '\n');
  727. }
  728. LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  729. updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
  730. LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  731. return;
  732. }
  733. // Visit constant expression.
  734. if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
  735. if (isa<GEPOperator>(ConstExpr)) {
  736. // Operand is a ConstantGEP, replace it.
  737. updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
  738. return;
  739. }
  740. // Aside from constant GEPs, only constant cast expressions are collected.
  741. assert(ConstExpr->isCast() && "ConstExpr should be a cast");
  742. Instruction *ConstExprInst = ConstExpr->getAsInstruction(
  743. findMatInsertPt(ConstUser.Inst, ConstUser.OpndIdx));
  744. ConstExprInst->setOperand(0, Mat);
  745. // Use the same debug location as the instruction we are about to update.
  746. ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
  747. LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
  748. << "From : " << *ConstExpr << '\n');
  749. LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  750. if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
  751. ConstExprInst->eraseFromParent();
  752. if (Offset)
  753. Mat->eraseFromParent();
  754. }
  755. LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  756. return;
  757. }
  758. }
  759. /// Hoist and hide the base constant behind a bitcast and emit
  760. /// materialization code for derived constants.
  761. bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
  762. bool MadeChange = false;
  763. SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
  764. BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
  765. for (auto const &ConstInfo : ConstInfoVec) {
  766. SetVector<Instruction *> IPSet = findConstantInsertionPoint(ConstInfo);
  767. // We can have an empty set if the function contains unreachable blocks.
  768. if (IPSet.empty())
  769. continue;
  770. unsigned UsesNum = 0;
  771. unsigned ReBasesNum = 0;
  772. unsigned NotRebasedNum = 0;
  773. for (Instruction *IP : IPSet) {
  774. // First, collect constants depending on this IP of the base.
  775. unsigned Uses = 0;
  776. using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
  777. SmallVector<RebasedUse, 4> ToBeRebased;
  778. for (auto const &RCI : ConstInfo.RebasedConstants) {
  779. for (auto const &U : RCI.Uses) {
  780. Uses++;
  781. BasicBlock *OrigMatInsertBB =
  782. findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
  783. // If Base constant is to be inserted in multiple places,
  784. // generate rebase for U using the Base dominating U.
  785. if (IPSet.size() == 1 ||
  786. DT->dominates(IP->getParent(), OrigMatInsertBB))
  787. ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
  788. }
  789. }
  790. UsesNum = Uses;
  791. // If only few constants depend on this IP of base, skip rebasing,
  792. // assuming the base and the rebased have the same materialization cost.
  793. if (ToBeRebased.size() < MinNumOfDependentToRebase) {
  794. NotRebasedNum += ToBeRebased.size();
  795. continue;
  796. }
  797. // Emit an instance of the base at this IP.
  798. Instruction *Base = nullptr;
  799. // Hoist and hide the base constant behind a bitcast.
  800. if (ConstInfo.BaseExpr) {
  801. assert(BaseGV && "A base constant expression must have an base GV");
  802. Type *Ty = ConstInfo.BaseExpr->getType();
  803. Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
  804. } else {
  805. IntegerType *Ty = ConstInfo.BaseInt->getType();
  806. Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
  807. }
  808. Base->setDebugLoc(IP->getDebugLoc());
  809. LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
  810. << ") to BB " << IP->getParent()->getName() << '\n'
  811. << *Base << '\n');
  812. // Emit materialization code for rebased constants depending on this IP.
  813. for (auto const &R : ToBeRebased) {
  814. Constant *Off = std::get<0>(R);
  815. Type *Ty = std::get<1>(R);
  816. ConstantUser U = std::get<2>(R);
  817. emitBaseConstants(Base, Off, Ty, U);
  818. ReBasesNum++;
  819. // Use the same debug location as the last user of the constant.
  820. Base->setDebugLoc(DILocation::getMergedLocation(
  821. Base->getDebugLoc(), U.Inst->getDebugLoc()));
  822. }
  823. assert(!Base->use_empty() && "The use list is empty!?");
  824. assert(isa<Instruction>(Base->user_back()) &&
  825. "All uses should be instructions.");
  826. }
  827. (void)UsesNum;
  828. (void)ReBasesNum;
  829. (void)NotRebasedNum;
  830. // Expect all uses are rebased after rebase is done.
  831. assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
  832. "Not all uses are rebased");
  833. NumConstantsHoisted++;
  834. // Base constant is also included in ConstInfo.RebasedConstants, so
  835. // deduct 1 from ConstInfo.RebasedConstants.size().
  836. NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
  837. MadeChange = true;
  838. }
  839. return MadeChange;
  840. }
  841. /// Check all cast instructions we made a copy of and remove them if they
  842. /// have no more users.
  843. void ConstantHoistingPass::deleteDeadCastInst() const {
  844. for (auto const &I : ClonedCastMap)
  845. if (I.first->use_empty())
  846. I.first->eraseFromParent();
  847. }
  848. /// Optimize expensive integer constants in the given function.
  849. bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
  850. DominatorTree &DT, BlockFrequencyInfo *BFI,
  851. BasicBlock &Entry, ProfileSummaryInfo *PSI) {
  852. this->TTI = &TTI;
  853. this->DT = &DT;
  854. this->BFI = BFI;
  855. this->DL = &Fn.getParent()->getDataLayout();
  856. this->Ctx = &Fn.getContext();
  857. this->Entry = &Entry;
  858. this->PSI = PSI;
  859. // Collect all constant candidates.
  860. collectConstantCandidates(Fn);
  861. // Combine constants that can be easily materialized with an add from a common
  862. // base constant.
  863. if (!ConstIntCandVec.empty())
  864. findBaseConstants(nullptr);
  865. for (const auto &MapEntry : ConstGEPCandMap)
  866. if (!MapEntry.second.empty())
  867. findBaseConstants(MapEntry.first);
  868. // Finally hoist the base constant and emit materialization code for dependent
  869. // constants.
  870. bool MadeChange = false;
  871. if (!ConstIntInfoVec.empty())
  872. MadeChange = emitBaseConstants(nullptr);
  873. for (const auto &MapEntry : ConstGEPInfoMap)
  874. if (!MapEntry.second.empty())
  875. MadeChange |= emitBaseConstants(MapEntry.first);
  876. // Cleanup dead instructions.
  877. deleteDeadCastInst();
  878. cleanup();
  879. return MadeChange;
  880. }
  881. PreservedAnalyses ConstantHoistingPass::run(Function &F,
  882. FunctionAnalysisManager &AM) {
  883. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  884. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  885. auto BFI = ConstHoistWithBlockFrequency
  886. ? &AM.getResult<BlockFrequencyAnalysis>(F)
  887. : nullptr;
  888. auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
  889. auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  890. if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
  891. return PreservedAnalyses::all();
  892. PreservedAnalyses PA;
  893. PA.preserveSet<CFGAnalyses>();
  894. return PA;
  895. }