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