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