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