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