LLVM 23.0.0git
ConstantHoisting.cpp
Go to the documentation of this file.
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 getIntImmCostInst 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
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/DenseMap.h"
40#include "llvm/ADT/Statistic.h"
44#include "llvm/IR/BasicBlock.h"
45#include "llvm/IR/Constants.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Dominators.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/InstrTypes.h"
50#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Value.h"
56#include "llvm/Pass.h"
60#include "llvm/Support/Debug.h"
65#include <cassert>
66#include <iterator>
67#include <tuple>
68#include <utility>
69
70using namespace llvm;
71using namespace consthoist;
72
73#define DEBUG_TYPE "consthoist"
74
75STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
76STATISTIC(NumConstantsRebased, "Number of constants rebased");
77
79 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
80 cl::desc("Enable the use of the block frequency analysis to reduce the "
81 "chance to execute const materialization more frequently than "
82 "without hoisting."));
83
85 "consthoist-gep", cl::init(false), cl::Hidden,
86 cl::desc("Try hoisting constant gep expressions"));
87
89MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
90 cl::desc("Do not rebase if number of dependent constants of a Base is less "
91 "than this number."),
93
94namespace {
95
96/// The constant hoisting pass.
97class ConstantHoistingLegacyPass : public FunctionPass {
98public:
99 static char ID; // Pass identification, replacement for typeid
100
101 ConstantHoistingLegacyPass() : FunctionPass(ID) {
103 }
104
105 bool runOnFunction(Function &Fn) override;
106
107 StringRef getPassName() const override { return "Constant Hoisting"; }
108
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 AU.setPreservesCFG();
112 AU.addRequired<BlockFrequencyInfoWrapperPass>();
113 AU.addRequired<DominatorTreeWrapperPass>();
114 AU.addRequired<ProfileSummaryInfoWrapperPass>();
115 AU.addRequired<TargetTransformInfoWrapperPass>();
116 }
117
118private:
119 ConstantHoistingPass Impl;
120};
121
122} // end anonymous namespace
123
124char ConstantHoistingLegacyPass::ID = 0;
125
126INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
127 "Constant Hoisting", false, false)
132INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
133 "Constant Hoisting", false, false)
134
136 return new ConstantHoistingLegacyPass();
137}
138
139/// Perform the constant hoisting optimization for the given function.
140bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
141 if (skipFunction(Fn))
142 return false;
143
144 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
145 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
146
147 bool MadeChange =
148 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
149 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
151 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
152 : nullptr,
153 Fn.getEntryBlock(),
154 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
155
156 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
157
158 return MadeChange;
159}
160
161void ConstantHoistingPass::collectMatInsertPts(
162 const RebasedConstantListType &RebasedConstants,
163 SmallVectorImpl<BasicBlock::iterator> &MatInsertPts) const {
164 for (const RebasedConstantInfo &RCI : RebasedConstants)
165 for (const ConstantUser &U : RCI.Uses)
166 MatInsertPts.emplace_back(findMatInsertPt(U.Inst, U.OpndIdx));
167}
168
169/// Find the constant materialization insertion point.
170BasicBlock::iterator 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->getIterator();
179 }
180
181 // The simple and common case. This also includes constant expressions.
182 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
183 return Inst->getIterator();
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 BasicBlock *InsertionBlock = nullptr;
189 if (Idx != ~0U && isa<PHINode>(Inst)) {
190 InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
191 if (!InsertionBlock->isEHPad()) {
192 return InsertionBlock->getTerminator()->getIterator();
193 }
194 } else {
195 InsertionBlock = Inst->getParent();
196 }
197
198 // This must be an EH pad. Iterate over immediate dominators until we find a
199 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
200 // and terminators.
201 auto *IDom = DT->getNode(InsertionBlock)->getIDom();
202 while (IDom->getBlock()->isEHPad()) {
203 assert(Entry != IDom->getBlock() && "eh pad in entry block");
204 IDom = IDom->getIDom();
205 }
206
207 return IDom->getBlock()->getTerminator()->getIterator();
208}
209
210/// Given \p BBs as input, find another set of BBs which collectively
211/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
212/// set found in \p BBs.
214 BasicBlock *Entry,
216 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
217 // Nodes on the current path to the root.
219 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
220 // dominated by any other blocks in set 'BBs', and all nodes in the path
221 // in the dominator tree from Entry to 'BB'.
223 for (auto *BB : BBs) {
224 // Ignore unreachable basic blocks.
225 if (!DT.isReachableFromEntry(BB))
226 continue;
227 Path.clear();
228 // Walk up the dominator tree until Entry or another BB in BBs
229 // is reached. Insert the nodes on the way to the Path.
230 BasicBlock *Node = BB;
231 // The "Path" is a candidate path to be added into Candidates set.
232 bool isCandidate = false;
233 do {
234 Path.insert(Node);
235 if (Node == Entry || Candidates.count(Node)) {
236 isCandidate = true;
237 break;
238 }
239 assert(DT.getNode(Node)->getIDom() &&
240 "Entry doens't dominate current Node");
241 Node = DT.getNode(Node)->getIDom()->getBlock();
242 } while (!BBs.count(Node));
243
244 // If isCandidate is false, Node is another Block in BBs dominating
245 // current 'BB'. Drop the nodes on the Path.
246 if (!isCandidate)
247 continue;
248
249 // Add nodes on the Path into Candidates.
250 Candidates.insert_range(Path);
251 }
252
253 // Sort the nodes in Candidates in top-down order and save the nodes
254 // in Orders.
255 unsigned Idx = 0;
257 Orders.push_back(Entry);
258 while (Idx != Orders.size()) {
259 BasicBlock *Node = Orders[Idx++];
260 for (auto *ChildDomNode : DT.getNode(Node)->children()) {
261 if (Candidates.count(ChildDomNode->getBlock()))
262 Orders.push_back(ChildDomNode->getBlock());
263 }
264 }
265
266 // Visit Orders in bottom-up order.
267 using InsertPtsCostPair =
268 std::pair<SetVector<BasicBlock *>, BlockFrequency>;
269
270 // InsertPtsMap is a map from a BB to the best insertion points for the
271 // subtree of BB (subtree not including the BB itself). Pre-populate every
272 // node so that loop below only uses find().
274 for (BasicBlock *Node : Orders)
275 InsertPtsMap.try_emplace(Node);
276 for (BasicBlock *Node : llvm::reverse(Orders)) {
277 bool NodeInBBs = BBs.count(Node);
278 auto &[InsertPts, InsertPtsFreq] = InsertPtsMap.find(Node)->second;
279
280 // Return the optimal insert points in BBs.
281 if (Node == Entry) {
282 BBs.clear();
283 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
284 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
285 BBs.insert(Entry);
286 else
287 BBs.insert_range(InsertPts);
288 break;
289 }
290
291 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
292 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
293 // will update its parent's ParentInsertPts and ParentPtsFreq.
294 auto &[ParentInsertPts, ParentPtsFreq] = InsertPtsMap.find(Parent)->second;
295 // Choose to insert in Node or in subtree of Node.
296 // Don't hoist to EHPad because we may not find a proper place to insert
297 // in EHPad.
298 // If the total frequency of InsertPts is the same as the frequency of the
299 // target Node, and InsertPts contains more than one nodes, choose hoisting
300 // to reduce code size.
301 if (NodeInBBs ||
302 (!Node->isEHPad() &&
303 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
304 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
305 ParentInsertPts.insert(Node);
306 ParentPtsFreq += BFI.getBlockFreq(Node);
307 } else {
308 ParentInsertPts.insert_range(InsertPts);
309 ParentPtsFreq += InsertPtsFreq;
310 }
311 }
312}
313
314/// Find an insertion point that dominates all uses.
315SetVector<BasicBlock::iterator>
316ConstantHoistingPass::findConstantInsertionPoint(
317 const ConstantInfo &ConstInfo,
318 const ArrayRef<BasicBlock::iterator> MatInsertPts) const {
319 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
320 // Collect all basic blocks.
321 SetVector<BasicBlock *> BBs;
322 SetVector<BasicBlock::iterator> InsertPts;
323
324 for (BasicBlock::iterator MatInsertPt : MatInsertPts)
325 BBs.insert(MatInsertPt->getParent());
326
327 if (BBs.count(Entry)) {
328 InsertPts.insert(Entry->begin());
329 return InsertPts;
330 }
331
332 if (BFI) {
333 findBestInsertionSet(*DT, *BFI, Entry, BBs);
334 for (BasicBlock *BB : BBs)
335 InsertPts.insert(BB->getFirstInsertionPt());
336 return InsertPts;
337 }
338
339 while (BBs.size() >= 2) {
340 BasicBlock *BB, *BB1, *BB2;
341 BB1 = BBs.pop_back_val();
342 BB2 = BBs.pop_back_val();
343 BB = DT->findNearestCommonDominator(BB1, BB2);
344 if (BB == Entry) {
345 InsertPts.insert(Entry->begin());
346 return InsertPts;
347 }
348 BBs.insert(BB);
349 }
350 assert((BBs.size() == 1) && "Expected only one element.");
351 Instruction &FirstInst = (*BBs.begin())->front();
352 InsertPts.insert(findMatInsertPt(&FirstInst));
353 return InsertPts;
354}
355
356/// Record constant integer ConstInt for instruction Inst at operand
357/// index Idx.
358///
359/// The operand at index Idx is not necessarily the constant integer itself. It
360/// could also be a cast instruction or a constant expression that uses the
361/// constant integer.
362void ConstantHoistingPass::collectConstantCandidates(
363 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
364 ConstantInt *ConstInt) {
365 if (ConstInt->getType()->isVectorTy())
366 return;
367
369 // Ask the target about the cost of materializing the constant for the given
370 // instruction and operand index.
371 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
372 Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
373 ConstInt->getValue(), ConstInt->getType(),
375 else
377 Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
379
380 // Ignore cheap integer constants.
382 ConstCandMapType::iterator Itr;
383 bool Inserted;
384 ConstPtrUnionType Cand = ConstInt;
385 std::tie(Itr, Inserted) = ConstCandMap.try_emplace(Cand);
386 if (Inserted) {
387 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
388 Itr->second = ConstIntCandVec.size() - 1;
389 }
390 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost.getValue());
391 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
392 << "Collect constant " << *ConstInt << " from " << *Inst
393 << " with cost " << Cost << '\n';
394 else dbgs() << "Collect constant " << *ConstInt
395 << " indirectly from " << *Inst << " via "
396 << *Inst->getOperand(Idx) << " with cost " << Cost
397 << '\n';);
398 }
399}
400
401/// Record constant GEP expression for instruction Inst at operand index Idx.
402void ConstantHoistingPass::collectConstantCandidates(
403 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
404 ConstantExpr *ConstExpr) {
405 // TODO: Handle vector GEPs
406 if (ConstExpr->getType()->isVectorTy())
407 return;
408
409 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
410 if (!BaseGV)
411 return;
412
413 // Get offset from the base GV.
414 PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
415 IntegerType *OffsetTy = DL->getIndexType(*Ctx, GVPtrTy->getAddressSpace());
416 APInt Offset(DL->getTypeSizeInBits(OffsetTy), /*val*/ 0, /*isSigned*/ true);
417 auto *GEPO = cast<GEPOperator>(ConstExpr);
418
419 // TODO: If we have a mix of inbounds and non-inbounds GEPs, then basing a
420 // non-inbounds GEP on an inbounds GEP is potentially incorrect. Restrict to
421 // inbounds GEP for now -- alternatively, we could drop inbounds from the
422 // constant expression,
423 if (!GEPO->isInBounds())
424 return;
425
426 if (!GEPO->accumulateConstantOffset(*DL, Offset))
427 return;
428
429 if (!Offset.isIntN(32))
430 return;
431
432 // A constant GEP expression that has a GlobalVariable as base pointer is
433 // usually lowered to a load from constant pool. Such operation is unlikely
434 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
435 // an ADD instruction or folded into Load/Store instruction.
437 TTI->getIntImmCostInst(Instruction::Add, 1, Offset, OffsetTy,
439 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
440 ConstCandMapType::iterator Itr;
441 bool Inserted;
442 ConstPtrUnionType Cand = ConstExpr;
443 std::tie(Itr, Inserted) = ConstCandMap.try_emplace(Cand);
444 if (Inserted) {
445 ExprCandVec.push_back(ConstantCandidate(
446 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
447 ConstExpr));
448 Itr->second = ExprCandVec.size() - 1;
449 }
450 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost.getValue());
451}
452
453/// Check the operand for instruction Inst at index Idx.
454void ConstantHoistingPass::collectConstantCandidates(
455 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
456 Value *Opnd = Inst->getOperand(Idx);
457
458 // Visit constant integers.
459 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
460 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
461 return;
462 }
463
464 // Visit cast instructions that have constant integers.
465 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
466 // Only visit cast instructions, which have been skipped. All other
467 // instructions should have already been visited.
468 if (!CastInst->isCast())
469 return;
470
471 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
472 // Pretend the constant is directly used by the instruction and ignore
473 // the cast instruction.
474 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
475 return;
476 }
477 }
478
479 // Visit constant expressions that have constant integers.
480 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
481 // Handle constant gep expressions.
482 if (ConstHoistGEP && isa<GEPOperator>(ConstExpr))
483 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
484
485 // Only visit constant cast expressions.
486 if (!ConstExpr->isCast())
487 return;
488
489 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
490 // Pretend the constant is directly used by the instruction and ignore
491 // the constant expression.
492 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
493 return;
494 }
495 }
496}
497
498/// Scan the instruction for expensive integer constants and record them
499/// in the constant candidate vector.
500void ConstantHoistingPass::collectConstantCandidates(
501 ConstCandMapType &ConstCandMap, Instruction *Inst) {
502 // Skip all cast instructions. They are visited indirectly later on.
503 if (Inst->isCast())
504 return;
505
506 // Scan all operands.
507 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
508 // The cost of materializing the constants (defined in
509 // `TargetTransformInfo::getIntImmCostInst`) for instructions which only
510 // take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
511 // So it's safe for us to collect constant candidates from all
512 // IntrinsicInsts.
513 if (canReplaceOperandWithVariable(Inst, Idx)) {
514 collectConstantCandidates(ConstCandMap, Inst, Idx);
515 }
516 } // end of for all operands
517}
518
519/// Collect all integer constants in the function that cannot be folded
520/// into an instruction itself.
521void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
522 ConstCandMapType ConstCandMap;
523 for (BasicBlock &BB : Fn) {
524 // Ignore unreachable basic blocks.
525 if (!DT->isReachableFromEntry(&BB))
526 continue;
527 for (Instruction &Inst : BB)
528 if (!TTI->preferToKeepConstantsAttached(Inst, Fn))
529 collectConstantCandidates(ConstCandMap, &Inst);
530 }
531}
532
533// From a list of constants, one needs to picked as the base and the other
534// constants will be transformed into an offset from that base constant. The
535// question is which we can pick best? For example, consider these constants
536// and their number of uses:
537//
538// Constants| 2 | 4 | 12 | 42 |
539// NumUses | 3 | 2 | 8 | 7 |
540//
541// Selecting constant 12 because it has the most uses will generate negative
542// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
543// offsets lead to less optimal code generation, then there might be better
544// solutions. Suppose immediates in the range of 0..35 are most optimally
545// supported by the architecture, then selecting constant 2 is most optimal
546// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
547// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
548// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
549// selecting the base constant the range of the offsets is a very important
550// factor too that we take into account here. This algorithm calculates a total
551// costs for selecting a constant as the base and substract the costs if
552// immediates are out of range. It has quadratic complexity, so we call this
553// function only when we're optimising for size and there are less than 100
554// constants, we fall back to the straightforward algorithm otherwise
555// which does not do all the offset calculations.
556unsigned
557ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
558 ConstCandVecType::iterator E,
559 ConstCandVecType::iterator &MaxCostItr) {
560 unsigned NumUses = 0;
561
562 if (!OptForSize || std::distance(S,E) > 100) {
563 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
564 NumUses += ConstCand->Uses.size();
565 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
566 MaxCostItr = ConstCand;
567 }
568 return NumUses;
569 }
570
571 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
572 InstructionCost MaxCost = -1;
573 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
574 auto Value = ConstCand->ConstInt->getValue();
575 Type *Ty = ConstCand->ConstInt->getType();
577 NumUses += ConstCand->Uses.size();
578 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
579 << "\n");
580
581 for (auto User : ConstCand->Uses) {
582 unsigned Opcode = User.Inst->getOpcode();
583 unsigned OpndIdx = User.OpndIdx;
584 Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
586 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
587
588 for (auto C2 = S; C2 != E; ++C2) {
589 APInt Diff = C2->ConstInt->getValue() - ConstCand->ConstInt->getValue();
590 const InstructionCost ImmCosts =
591 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff, Ty);
592 Cost -= ImmCosts;
593 LLVM_DEBUG(dbgs() << "Offset " << Diff << " "
594 << "has penalty: " << ImmCosts << "\n"
595 << "Adjusted cost: " << Cost << "\n");
596 }
597 }
598 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
599 if (Cost > MaxCost) {
600 MaxCost = Cost;
601 MaxCostItr = ConstCand;
602 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
603 << "\n");
604 }
605 }
606 return NumUses;
607}
608
609/// Find the base constant within the given range and rebase all other
610/// constants with respect to the base constant.
611void ConstantHoistingPass::findAndMakeBaseConstant(
612 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
613 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
614 auto MaxCostItr = S;
615 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
616
617 // Don't hoist constants that have only one use.
618 if (NumUses <= 1)
619 return;
620
621 ConstantInt *ConstInt = MaxCostItr->ConstInt;
622 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
623 ConstantInfo ConstInfo;
624 ConstInfo.BaseInt = ConstInt;
625 ConstInfo.BaseExpr = ConstExpr;
626 Type *Ty = ConstInt->getType();
627
628 // Rebase the constants with respect to the base constant.
629 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
630 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
631 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
632 Type *ConstTy =
633 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
634 ConstInfo.RebasedConstants.push_back(
635 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
636 }
637 ConstInfoVec.push_back(std::move(ConstInfo));
638}
639
640/// Finds and combines constant candidates that can be easily
641/// rematerialized with an add from a common base constant.
642void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
643 // If BaseGV is nullptr, find base among candidate constant integers;
644 // Otherwise find base among constant GEPs that share the same BaseGV.
645 ConstCandVecType &ConstCandVec = BaseGV ?
646 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
647 ConstInfoVecType &ConstInfoVec = BaseGV ?
648 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
649
650 // Sort the constants by value and type. This invalidates the mapping!
651 llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
652 const ConstantCandidate &RHS) {
653 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
654 return LHS.ConstInt->getBitWidth() < RHS.ConstInt->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) &&
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 from 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.
706static 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.
730void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
731 UserAdjustment *Adj) {
732 Instruction *Mat = Base;
733
734 // The same offset can be dereferenced to different types in nested struct.
735 if (!Adj->Offset && Adj->Ty && Adj->Ty != Base->getType())
736 Adj->Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
737
738 if (Adj->Offset) {
739 if (Adj->Ty) {
740 // Constant being rebased is a ConstantExpr.
741 Mat = GetElementPtrInst::Create(Type::getInt8Ty(*Ctx), Base, Adj->Offset,
742 "mat_gep", Adj->MatInsertPt);
743 // Hide it behind a bitcast.
744 Mat = new BitCastInst(Mat, Adj->Ty, "mat_bitcast",
745 Adj->MatInsertPt->getIterator());
746 } else
747 // Constant being rebased is a ConstantInt.
748 Mat =
749 BinaryOperator::Create(Instruction::Add, Base, Adj->Offset,
750 "const_mat", Adj->MatInsertPt->getIterator());
751
752 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
753 << " + " << *Adj->Offset << ") in BB "
754 << Mat->getParent()->getName() << '\n'
755 << *Mat << '\n');
756 Mat->setDebugLoc(Adj->User.Inst->getDebugLoc());
757 }
758 Value *Opnd = Adj->User.Inst->getOperand(Adj->User.OpndIdx);
759
760 // Visit constant integer.
761 if (isa<ConstantInt>(Opnd)) {
762 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
763 if (!updateOperand(Adj->User.Inst, Adj->User.OpndIdx, Mat) && Adj->Offset)
764 Mat->eraseFromParent();
765 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
766 return;
767 }
768
769 // Visit cast instruction.
770 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
771 assert(CastInst->isCast() && "Expected an cast instruction!");
772 // Check if we already have visited this cast instruction before to avoid
773 // unnecessary cloning.
774 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
775 if (!ClonedCastInst) {
776 ClonedCastInst = CastInst->clone();
777 ClonedCastInst->setOperand(0, Mat);
778 ClonedCastInst->insertAfter(CastInst->getIterator());
779 // Use the same debug location as the original cast instruction.
780 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
781 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
782 << "To : " << *ClonedCastInst << '\n');
783 }
784
785 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
786 updateOperand(Adj->User.Inst, Adj->User.OpndIdx, ClonedCastInst);
787 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
788 return;
789 }
790
791 // Visit constant expression.
792 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
793 if (isa<GEPOperator>(ConstExpr)) {
794 // Operand is a ConstantGEP, replace it.
795 updateOperand(Adj->User.Inst, Adj->User.OpndIdx, Mat);
796 return;
797 }
798
799 // Aside from constant GEPs, only constant cast expressions are collected.
800 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
801 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
802 ConstExprInst->insertBefore(Adj->MatInsertPt);
803 ConstExprInst->setOperand(0, Mat);
804
805 // Use the same debug location as the instruction we are about to update.
806 ConstExprInst->setDebugLoc(Adj->User.Inst->getDebugLoc());
807
808 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
809 << "From : " << *ConstExpr << '\n');
810 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
811 if (!updateOperand(Adj->User.Inst, Adj->User.OpndIdx, ConstExprInst)) {
812 ConstExprInst->eraseFromParent();
813 if (Adj->Offset)
814 Mat->eraseFromParent();
815 }
816 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
817 return;
818 }
819}
820
821/// Hoist and hide the base constant behind a bitcast and emit
822/// materialization code for derived constants.
823bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
824 bool MadeChange = false;
825 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
826 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
827 for (const consthoist::ConstantInfo &ConstInfo : ConstInfoVec) {
829 collectMatInsertPts(ConstInfo.RebasedConstants, MatInsertPts);
830 SetVector<BasicBlock::iterator> IPSet =
831 findConstantInsertionPoint(ConstInfo, MatInsertPts);
832 // We can have an empty set if the function contains unreachable blocks.
833 if (IPSet.empty())
834 continue;
835
836 unsigned UsesNum = 0;
837 unsigned ReBasesNum = 0;
838 unsigned NotRebasedNum = 0;
839 for (const BasicBlock::iterator &IP : IPSet) {
840 // First, collect constants depending on this IP of the base.
841 UsesNum = 0;
843 unsigned MatCtr = 0;
844 for (auto const &RCI : ConstInfo.RebasedConstants) {
845 UsesNum += RCI.Uses.size();
846 for (auto const &U : RCI.Uses) {
847 const BasicBlock::iterator &MatInsertPt = MatInsertPts[MatCtr++];
848 BasicBlock *OrigMatInsertBB = MatInsertPt->getParent();
849 // If Base constant is to be inserted in multiple places,
850 // generate rebase for U using the Base dominating U.
851 if (IPSet.size() == 1 ||
852 DT->dominates(IP->getParent(), OrigMatInsertBB))
853 ToBeRebased.emplace_back(RCI.Offset, RCI.Ty, MatInsertPt, U);
854 }
855 }
856
857 // If only few constants depend on this IP of base, skip rebasing,
858 // assuming the base and the rebased have the same materialization cost.
859 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
860 NotRebasedNum += ToBeRebased.size();
861 continue;
862 }
863
864 // Emit an instance of the base at this IP.
865 Instruction *Base = nullptr;
866 // Hoist and hide the base constant behind a bitcast.
867 if (ConstInfo.BaseExpr) {
868 assert(BaseGV && "A base constant expression must have an base GV");
869 Type *Ty = ConstInfo.BaseExpr->getType();
870 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
871 } else {
872 IntegerType *Ty = ConstInfo.BaseInt->getIntegerType();
873 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
874 }
875
876 Base->setDebugLoc(IP->getDebugLoc());
877
878 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
879 << ") to BB " << IP->getParent()->getName() << '\n'
880 << *Base << '\n');
881
882 // Emit materialization code for rebased constants depending on this IP.
883 for (UserAdjustment &R : ToBeRebased) {
884 emitBaseConstants(Base, &R);
885 ReBasesNum++;
886 // Use the same debug location as the last user of the constant.
888 Base->getDebugLoc(), R.User.Inst->getDebugLoc()));
889 }
890 assert(!Base->use_empty() && "The use list is empty!?");
891 assert(isa<Instruction>(Base->user_back()) &&
892 "All uses should be instructions.");
893 }
894 (void)UsesNum;
895 (void)ReBasesNum;
896 (void)NotRebasedNum;
897 // Expect all uses are rebased after rebase is done.
898 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
899 "Not all uses are rebased");
900
901 NumConstantsHoisted++;
902
903 // Base constant is also included in ConstInfo.RebasedConstants, so
904 // deduct 1 from ConstInfo.RebasedConstants.size().
905 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
906
907 MadeChange = true;
908 }
909 return MadeChange;
910}
911
912/// Check all cast instructions we made a copy of and remove them if they
913/// have no more users.
914void ConstantHoistingPass::deleteDeadCastInst() const {
915 for (auto const &I : ClonedCastMap)
916 if (I.first->use_empty())
917 I.first->eraseFromParent();
918}
919
920/// Optimize expensive integer constants in the given function.
923 BasicBlock &Entry, ProfileSummaryInfo *PSI) {
924 this->TTI = &TTI;
925 this->DT = &DT;
926 this->BFI = BFI;
927 this->DL = &Fn.getDataLayout();
928 this->Ctx = &Fn.getContext();
929 this->Entry = &Entry;
930 this->PSI = PSI;
931 this->OptForSize = llvm::shouldOptimizeForSize(Entry.getParent(), PSI, BFI,
933
934 // Collect all constant candidates.
935 collectConstantCandidates(Fn);
936
937 // Combine constants that can be easily materialized with an add from a common
938 // base constant.
939 if (!ConstIntCandVec.empty())
940 findBaseConstants(nullptr);
941 for (const auto &MapEntry : ConstGEPCandMap)
942 if (!MapEntry.second.empty())
943 findBaseConstants(MapEntry.first);
944
945 // Finally hoist the base constant and emit materialization code for dependent
946 // constants.
947 bool MadeChange = false;
948 if (!ConstIntInfoVec.empty())
949 MadeChange = emitBaseConstants(nullptr);
950 for (const auto &MapEntry : ConstGEPInfoMap)
951 if (!MapEntry.second.empty())
952 MadeChange |= emitBaseConstants(MapEntry.first);
953
954
955 // Cleanup dead instructions.
956 deleteDeadCastInst();
957
958 cleanup();
959
960 return MadeChange;
961}
962
965 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
966 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
969 : nullptr;
970 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
971 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
972 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
973 return PreservedAnalyses::all();
974
977 return PA;
978}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI, BasicBlock *Entry, SetVector< BasicBlock * > &BBs)
Given BBs as input, find another set of BBs which collectively dominates BBs and have the minimal sum...
static cl::opt< unsigned > MinNumOfDependentToRebase("consthoist-min-num-to-rebase", cl::desc("Do not rebase if number of dependent constants of a Base is less " "than this number."), cl::init(0), cl::Hidden)
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."))
static cl::opt< bool > ConstHoistGEP("consthoist-gep", cl::init(false), cl::Hidden, cl::desc("Try hoisting constant gep expressions"))
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
static bool runImpl(Function &F, const TargetLowering &TLI, const LibcallLoweringInfo &Libcalls, AssumptionCache *AC)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static DominatorTree getDomTree(Function &F)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1511
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:704
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
LLVM_ABI bool isCast() const
Return true if this is a convert constant expression.
LLVM_ABI Instruction * getAsInstruction() const
Returns an Instruction which implements the same operation as this ConstantExpr.
LLVM_ABI bool runImpl(Function &F, TargetTransformInfo &TTI, DominatorTree &DT, BlockFrequencyInfo *BFI, BasicBlock &Entry, ProfileSummaryInfo *PSI)
Optimize expensive integer constants in the given function.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
IntegerType * getIntegerType() const
Variant of the getType() method to always return an IntegerType, which reduces the amount of casting ...
Definition Constants.h:198
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:179
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:254
iterator_range< iterator > children()
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:278
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:314
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:809
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:362
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
PointerType * getType() const
Global values are always pointers.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
bool isCast() const
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
A vector that has set insertion semantics.
Definition SetVector.h:57
void insert_range(Range &&R)
Definition SetVector.h:176
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:262
void clear()
Completely clear the SetVector.
Definition SetVector.h:267
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0, Instruction *I=nullptr, int64_t ScalableOffset=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
LLVM_ABI InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
LLVM_ABI bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) const
It can be advantageous to detach complex constants from their uses to make their generation cheaper.
LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty) const
Return the expected cost for the given integer when optimising for size.
@ TCC_Basic
The cost of a typical 'add' instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
A private "module" namespace for types and utilities used by ConstantHoisting.
SmallVector< RebasedConstantInfo, 4 > RebasedConstantListType
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void stable_sort(R &&Range)
Definition STLExtras.h:2115
InstructionCost Cost
LLVM_ABI FunctionPass * createConstantHoistingPass()
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
LLVM_ABI void initializeConstantHoistingLegacyPassPass(PassRegistry &)
LLVM_ABI 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:3921
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
RebasedConstantListType RebasedConstants