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