ConstantHoisting.cpp 39 KB

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