ConstantHoisting.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass identifies expensive constants to hoist and coalesces them to
  11. // better prepare it for SelectionDAG-based code generation. This works around
  12. // the limitations of the basic-block-at-a-time approach.
  13. //
  14. // First it scans all instructions for integer constants and calculates its
  15. // cost. If the constant can be folded into the instruction (the cost is
  16. // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
  17. // consider it expensive and leave it alone. This is the default behavior and
  18. // the default implementation of getIntImmCost will always return TCC_Free.
  19. //
  20. // If the cost is more than TCC_BASIC, then the integer constant can't be folded
  21. // into the instruction and it might be beneficial to hoist the constant.
  22. // Similar constants are coalesced to reduce register pressure and
  23. // materialization code.
  24. //
  25. // When a constant is hoisted, it is also hidden behind a bitcast to force it to
  26. // be live-out of the basic block. Otherwise the constant would be just
  27. // duplicated and each basic block would have its own copy in the SelectionDAG.
  28. // The SelectionDAG recognizes such constants as opaque and doesn't perform
  29. // certain transformations on them, which would create a new expensive constant.
  30. //
  31. // This optimization is only applied to integer constants in instructions and
  32. // simple (this means not nested) constant cast expressions. For example:
  33. // %0 = load i64* inttoptr (i64 big_constant to i64*)
  34. //===----------------------------------------------------------------------===//
  35. #include "llvm/Transforms/Scalar.h"
  36. #include "llvm/ADT/SmallSet.h"
  37. #include "llvm/ADT/SmallVector.h"
  38. #include "llvm/ADT/Statistic.h"
  39. #include "llvm/Analysis/TargetTransformInfo.h"
  40. #include "llvm/IR/Constants.h"
  41. #include "llvm/IR/Dominators.h"
  42. #include "llvm/IR/IntrinsicInst.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/Debug.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <tuple>
  47. using namespace llvm;
  48. #define DEBUG_TYPE "consthoist"
  49. STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
  50. STATISTIC(NumConstantsRebased, "Number of constants rebased");
  51. namespace {
  52. struct ConstantUser;
  53. struct RebasedConstantInfo;
  54. typedef SmallVector<ConstantUser, 8> ConstantUseListType;
  55. typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
  56. /// \brief Keeps track of the user of a constant and the operand index where the
  57. /// constant is used.
  58. struct ConstantUser {
  59. Instruction *Inst;
  60. unsigned OpndIdx;
  61. ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
  62. };
  63. /// \brief Keeps track of a constant candidate and its uses.
  64. struct ConstantCandidate {
  65. ConstantUseListType Uses;
  66. ConstantInt *ConstInt;
  67. unsigned CumulativeCost;
  68. ConstantCandidate(ConstantInt *ConstInt)
  69. : ConstInt(ConstInt), CumulativeCost(0) { }
  70. /// \brief Add the user to the use list and update the cost.
  71. void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
  72. CumulativeCost += Cost;
  73. Uses.push_back(ConstantUser(Inst, Idx));
  74. }
  75. };
  76. /// \brief This represents a constant that has been rebased with respect to a
  77. /// base constant. The difference to the base constant is recorded in Offset.
  78. struct RebasedConstantInfo {
  79. ConstantUseListType Uses;
  80. Constant *Offset;
  81. RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
  82. : Uses(std::move(Uses)), Offset(Offset) { }
  83. };
  84. /// \brief A base constant and all its rebased constants.
  85. struct ConstantInfo {
  86. ConstantInt *BaseConstant;
  87. RebasedConstantListType RebasedConstants;
  88. };
  89. /// \brief The constant hoisting pass.
  90. class ConstantHoisting : public FunctionPass {
  91. typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
  92. typedef std::vector<ConstantCandidate> ConstCandVecType;
  93. const TargetTransformInfo *TTI;
  94. DominatorTree *DT;
  95. BasicBlock *Entry;
  96. /// Keeps track of constant candidates found in the function.
  97. ConstCandVecType ConstCandVec;
  98. /// Keep track of cast instructions we already cloned.
  99. SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
  100. /// These are the final constants we decided to hoist.
  101. SmallVector<ConstantInfo, 8> ConstantVec;
  102. public:
  103. static char ID; // Pass identification, replacement for typeid
  104. ConstantHoisting() : FunctionPass(ID), TTI(nullptr), DT(nullptr),
  105. Entry(nullptr) {
  106. initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
  107. }
  108. bool runOnFunction(Function &Fn) override;
  109. const char *getPassName() const override { return "Constant Hoisting"; }
  110. void getAnalysisUsage(AnalysisUsage &AU) const override {
  111. AU.setPreservesCFG();
  112. AU.addRequired<DominatorTreeWrapperPass>();
  113. AU.addRequired<TargetTransformInfoWrapperPass>();
  114. }
  115. private:
  116. /// \brief Initialize the pass.
  117. void setup(Function &Fn) {
  118. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  119. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn);
  120. Entry = &Fn.getEntryBlock();
  121. }
  122. /// \brief Cleanup.
  123. void cleanup() {
  124. ConstantVec.clear();
  125. ClonedCastMap.clear();
  126. ConstCandVec.clear();
  127. TTI = nullptr;
  128. DT = nullptr;
  129. Entry = nullptr;
  130. }
  131. Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
  132. Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
  133. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  134. Instruction *Inst, unsigned Idx,
  135. ConstantInt *ConstInt);
  136. void collectConstantCandidates(ConstCandMapType &ConstCandMap,
  137. Instruction *Inst);
  138. void collectConstantCandidates(Function &Fn);
  139. void findAndMakeBaseConstant(ConstCandVecType::iterator S,
  140. ConstCandVecType::iterator E);
  141. void findBaseConstants();
  142. void emitBaseConstants(Instruction *Base, Constant *Offset,
  143. const ConstantUser &ConstUser);
  144. bool emitBaseConstants();
  145. void deleteDeadCastInst() const;
  146. bool optimizeConstants(Function &Fn);
  147. };
  148. }
  149. char ConstantHoisting::ID = 0;
  150. INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
  151. false, false)
  152. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  153. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  154. INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
  155. false, false)
  156. FunctionPass *llvm::createConstantHoistingPass() {
  157. return new ConstantHoisting();
  158. }
  159. /// \brief Perform the constant hoisting optimization for the given function.
  160. bool ConstantHoisting::runOnFunction(Function &Fn) {
  161. if (skipOptnoneFunction(Fn))
  162. return false;
  163. DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
  164. DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
  165. setup(Fn);
  166. bool MadeChange = optimizeConstants(Fn);
  167. if (MadeChange) {
  168. DEBUG(dbgs() << "********** Function after Constant Hoisting: "
  169. << Fn.getName() << '\n');
  170. DEBUG(dbgs() << Fn);
  171. }
  172. DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
  173. cleanup();
  174. return MadeChange;
  175. }
  176. /// \brief Find the constant materialization insertion point.
  177. Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
  178. unsigned Idx) const {
  179. // If the operand is a cast instruction, then we have to materialize the
  180. // constant before the cast instruction.
  181. if (Idx != ~0U) {
  182. Value *Opnd = Inst->getOperand(Idx);
  183. if (auto CastInst = dyn_cast<Instruction>(Opnd))
  184. if (CastInst->isCast())
  185. return CastInst;
  186. }
  187. // The simple and common case. This also includes constant expressions.
  188. if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
  189. return Inst;
  190. // We can't insert directly before a phi node or landing pad. Insert before
  191. // the terminator of the incoming or dominating block.
  192. assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
  193. if (Idx != ~0U && isa<PHINode>(Inst))
  194. return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
  195. BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
  196. return IDom->getTerminator();
  197. }
  198. /// \brief Find an insertion point that dominates all uses.
  199. Instruction *ConstantHoisting::
  200. findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
  201. assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
  202. // Collect all basic blocks.
  203. SmallPtrSet<BasicBlock *, 8> BBs;
  204. for (auto const &RCI : ConstInfo.RebasedConstants)
  205. for (auto const &U : RCI.Uses)
  206. BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
  207. if (BBs.count(Entry))
  208. return &Entry->front();
  209. while (BBs.size() >= 2) {
  210. BasicBlock *BB, *BB1, *BB2;
  211. BB1 = *BBs.begin();
  212. BB2 = *std::next(BBs.begin());
  213. BB = DT->findNearestCommonDominator(BB1, BB2);
  214. if (BB == Entry)
  215. return &Entry->front();
  216. BBs.erase(BB1);
  217. BBs.erase(BB2);
  218. BBs.insert(BB);
  219. }
  220. assert((BBs.size() == 1) && "Expected only one element.");
  221. Instruction &FirstInst = (*BBs.begin())->front();
  222. return findMatInsertPt(&FirstInst);
  223. }
  224. /// \brief Record constant integer ConstInt for instruction Inst at operand
  225. /// index Idx.
  226. ///
  227. /// The operand at index Idx is not necessarily the constant integer itself. It
  228. /// could also be a cast instruction or a constant expression that uses the
  229. // constant integer.
  230. void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
  231. Instruction *Inst,
  232. unsigned Idx,
  233. ConstantInt *ConstInt) {
  234. unsigned Cost;
  235. // Ask the target about the cost of materializing the constant for the given
  236. // instruction and operand index.
  237. if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
  238. Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
  239. ConstInt->getValue(), ConstInt->getType());
  240. else
  241. Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
  242. ConstInt->getType());
  243. // Ignore cheap integer constants.
  244. if (Cost > TargetTransformInfo::TCC_Basic) {
  245. ConstCandMapType::iterator Itr;
  246. bool Inserted;
  247. std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
  248. if (Inserted) {
  249. ConstCandVec.push_back(ConstantCandidate(ConstInt));
  250. Itr->second = ConstCandVec.size() - 1;
  251. }
  252. ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
  253. DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
  254. dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
  255. << " with cost " << Cost << '\n';
  256. else
  257. dbgs() << "Collect constant " << *ConstInt << " indirectly from "
  258. << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
  259. << Cost << '\n';
  260. );
  261. }
  262. }
  263. /// \brief Scan the instruction for expensive integer constants and record them
  264. /// in the constant candidate vector.
  265. void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
  266. Instruction *Inst) {
  267. // Skip all cast instructions. They are visited indirectly later on.
  268. if (Inst->isCast())
  269. return;
  270. // Can't handle inline asm. Skip it.
  271. if (auto Call = dyn_cast<CallInst>(Inst))
  272. if (isa<InlineAsm>(Call->getCalledValue()))
  273. return;
  274. // Scan all operands.
  275. for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
  276. Value *Opnd = Inst->getOperand(Idx);
  277. // Visit constant integers.
  278. if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
  279. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  280. continue;
  281. }
  282. // Visit cast instructions that have constant integers.
  283. if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
  284. // Only visit cast instructions, which have been skipped. All other
  285. // instructions should have already been visited.
  286. if (!CastInst->isCast())
  287. continue;
  288. if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
  289. // Pretend the constant is directly used by the instruction and ignore
  290. // the cast instruction.
  291. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  292. continue;
  293. }
  294. }
  295. // Visit constant expressions that have constant integers.
  296. if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
  297. // Only visit constant cast expressions.
  298. if (!ConstExpr->isCast())
  299. continue;
  300. if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
  301. // Pretend the constant is directly used by the instruction and ignore
  302. // the constant expression.
  303. collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
  304. continue;
  305. }
  306. }
  307. } // end of for all operands
  308. }
  309. /// \brief Collect all integer constants in the function that cannot be folded
  310. /// into an instruction itself.
  311. void ConstantHoisting::collectConstantCandidates(Function &Fn) {
  312. ConstCandMapType ConstCandMap;
  313. for (Function::iterator BB : Fn)
  314. for (BasicBlock::iterator Inst : *BB)
  315. collectConstantCandidates(ConstCandMap, Inst);
  316. }
  317. /// \brief Find the base constant within the given range and rebase all other
  318. /// constants with respect to the base constant.
  319. void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
  320. ConstCandVecType::iterator E) {
  321. auto MaxCostItr = S;
  322. unsigned NumUses = 0;
  323. // Use the constant that has the maximum cost as base constant.
  324. for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
  325. NumUses += ConstCand->Uses.size();
  326. if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
  327. MaxCostItr = ConstCand;
  328. }
  329. // Don't hoist constants that have only one use.
  330. if (NumUses <= 1)
  331. return;
  332. ConstantInfo ConstInfo;
  333. ConstInfo.BaseConstant = MaxCostItr->ConstInt;
  334. Type *Ty = ConstInfo.BaseConstant->getType();
  335. // Rebase the constants with respect to the base constant.
  336. for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
  337. APInt Diff = ConstCand->ConstInt->getValue() -
  338. ConstInfo.BaseConstant->getValue();
  339. Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
  340. ConstInfo.RebasedConstants.push_back(
  341. RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
  342. }
  343. ConstantVec.push_back(std::move(ConstInfo));
  344. }
  345. /// \brief Finds and combines constant candidates that can be easily
  346. /// rematerialized with an add from a common base constant.
  347. void ConstantHoisting::findBaseConstants() {
  348. // Sort the constants by value and type. This invalidates the mapping!
  349. std::sort(ConstCandVec.begin(), ConstCandVec.end(),
  350. [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
  351. if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
  352. return LHS.ConstInt->getType()->getBitWidth() <
  353. RHS.ConstInt->getType()->getBitWidth();
  354. return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
  355. });
  356. // Simple linear scan through the sorted constant candidate vector for viable
  357. // merge candidates.
  358. auto MinValItr = ConstCandVec.begin();
  359. for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
  360. CC != E; ++CC) {
  361. if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
  362. // Check if the constant is in range of an add with immediate.
  363. APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
  364. if ((Diff.getBitWidth() <= 64) &&
  365. TTI->isLegalAddImmediate(Diff.getSExtValue()))
  366. continue;
  367. }
  368. // We either have now a different constant type or the constant is not in
  369. // range of an add with immediate anymore.
  370. findAndMakeBaseConstant(MinValItr, CC);
  371. // Start a new base constant search.
  372. MinValItr = CC;
  373. }
  374. // Finalize the last base constant search.
  375. findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
  376. }
  377. /// \brief Updates the operand at Idx in instruction Inst with the result of
  378. /// instruction Mat. If the instruction is a PHI node then special
  379. /// handling for duplicate values form the same incomming basic block is
  380. /// required.
  381. /// \return The update will always succeed, but the return value indicated if
  382. /// Mat was used for the update or not.
  383. static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
  384. if (auto PHI = dyn_cast<PHINode>(Inst)) {
  385. // Check if any previous operand of the PHI node has the same incoming basic
  386. // block. This is a very odd case that happens when the incoming basic block
  387. // has a switch statement. In this case use the same value as the previous
  388. // operand(s), otherwise we will fail verification due to different values.
  389. // The values are actually the same, but the variable names are different
  390. // and the verifier doesn't like that.
  391. BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
  392. for (unsigned i = 0; i < Idx; ++i) {
  393. if (PHI->getIncomingBlock(i) == IncomingBB) {
  394. Value *IncomingVal = PHI->getIncomingValue(i);
  395. Inst->setOperand(Idx, IncomingVal);
  396. return false;
  397. }
  398. }
  399. }
  400. Inst->setOperand(Idx, Mat);
  401. return true;
  402. }
  403. /// \brief Emit materialization code for all rebased constants and update their
  404. /// users.
  405. void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
  406. const ConstantUser &ConstUser) {
  407. Instruction *Mat = Base;
  408. if (Offset) {
  409. Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
  410. ConstUser.OpndIdx);
  411. Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
  412. "const_mat", InsertionPt);
  413. DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
  414. << " + " << *Offset << ") in BB "
  415. << Mat->getParent()->getName() << '\n' << *Mat << '\n');
  416. Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
  417. }
  418. Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
  419. // Visit constant integer.
  420. if (isa<ConstantInt>(Opnd)) {
  421. DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  422. if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
  423. Mat->eraseFromParent();
  424. DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  425. return;
  426. }
  427. // Visit cast instruction.
  428. if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
  429. assert(CastInst->isCast() && "Expected an cast instruction!");
  430. // Check if we already have visited this cast instruction before to avoid
  431. // unnecessary cloning.
  432. Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
  433. if (!ClonedCastInst) {
  434. ClonedCastInst = CastInst->clone();
  435. ClonedCastInst->setOperand(0, Mat);
  436. ClonedCastInst->insertAfter(CastInst);
  437. // Use the same debug location as the original cast instruction.
  438. ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
  439. DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
  440. << "To : " << *ClonedCastInst << '\n');
  441. }
  442. DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  443. updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
  444. DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  445. return;
  446. }
  447. // Visit constant expression.
  448. if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
  449. Instruction *ConstExprInst = ConstExpr->getAsInstruction();
  450. ConstExprInst->setOperand(0, Mat);
  451. ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
  452. ConstUser.OpndIdx));
  453. // Use the same debug location as the instruction we are about to update.
  454. ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
  455. DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
  456. << "From : " << *ConstExpr << '\n');
  457. DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
  458. if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
  459. ConstExprInst->eraseFromParent();
  460. if (Offset)
  461. Mat->eraseFromParent();
  462. }
  463. DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
  464. return;
  465. }
  466. }
  467. /// \brief Hoist and hide the base constant behind a bitcast and emit
  468. /// materialization code for derived constants.
  469. bool ConstantHoisting::emitBaseConstants() {
  470. bool MadeChange = false;
  471. for (auto const &ConstInfo : ConstantVec) {
  472. // Hoist and hide the base constant behind a bitcast.
  473. Instruction *IP = findConstantInsertionPoint(ConstInfo);
  474. IntegerType *Ty = ConstInfo.BaseConstant->getType();
  475. Instruction *Base =
  476. new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
  477. DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
  478. << IP->getParent()->getName() << '\n' << *Base << '\n');
  479. NumConstantsHoisted++;
  480. // Emit materialization code for all rebased constants.
  481. for (auto const &RCI : ConstInfo.RebasedConstants) {
  482. NumConstantsRebased++;
  483. for (auto const &U : RCI.Uses)
  484. emitBaseConstants(Base, RCI.Offset, U);
  485. }
  486. // Use the same debug location as the last user of the constant.
  487. assert(!Base->use_empty() && "The use list is empty!?");
  488. assert(isa<Instruction>(Base->user_back()) &&
  489. "All uses should be instructions.");
  490. Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
  491. // Correct for base constant, which we counted above too.
  492. NumConstantsRebased--;
  493. MadeChange = true;
  494. }
  495. return MadeChange;
  496. }
  497. /// \brief Check all cast instructions we made a copy of and remove them if they
  498. /// have no more users.
  499. void ConstantHoisting::deleteDeadCastInst() const {
  500. for (auto const &I : ClonedCastMap)
  501. if (I.first->use_empty())
  502. I.first->eraseFromParent();
  503. }
  504. /// \brief Optimize expensive integer constants in the given function.
  505. bool ConstantHoisting::optimizeConstants(Function &Fn) {
  506. // Collect all constant candidates.
  507. collectConstantCandidates(Fn);
  508. // There are no constant candidates to worry about.
  509. if (ConstCandVec.empty())
  510. return false;
  511. // Combine constants that can be easily materialized with an add from a common
  512. // base constant.
  513. findBaseConstants();
  514. // There are no constants to emit.
  515. if (ConstantVec.empty())
  516. return false;
  517. // Finally hoist the base constant and emit materialization code for dependent
  518. // constants.
  519. bool MadeChange = emitBaseConstants();
  520. // Cleanup dead instructions.
  521. deleteDeadCastInst();
  522. return MadeChange;
  523. }