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
35#include "llvm/Transforms/Scalar/ConstantHoisting.h"
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/Analysis/BlockFrequencyInfo.h"
42#include "llvm/Analysis/ProfileSummaryInfo.h"
43#include "llvm/Analysis/TargetTransformInfo.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"
51#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Value.h"
55#include "llvm/InitializePasses.h"
56#include "llvm/Pass.h"
57#include "llvm/Support/BlockFrequency.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/CommandLine.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/raw_ostream.h"
62#include "llvm/Transforms/Scalar.h"
63#include "llvm/Transforms/Utils/Local.h"
64#include "llvm/Transforms/Utils/SizeOpts.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
78static cl::opt<bool> ConstHoistWithBlockFrequency(
79 "consthoist-with-block-frequency", cl::init(Val: 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
84static cl::opt<bool> ConstHoistGEP(
85 "consthoist-gep", cl::init(Val: false), cl::Hidden,
86 cl::desc("Try hoisting constant gep expressions"));
87
88static cl::opt<unsigned>
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."),
92 cl::init(Val: 0), cl::Hidden);
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) {
102 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
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();
111 if (ConstHoistWithBlockFrequency)
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)
128INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
129INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
131INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
132INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
133 "Constant Hoisting", false, false)
134
135FunctionPass *llvm::createConstantHoistingPass() {
136 return new ConstantHoistingLegacyPass();
137}
138
139/// Perform the constant hoisting optimization for the given function.
140bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
141 if (skipFunction(F: 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(F&: Fn, TTI&: getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F: Fn),
149 DT&: getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
150 BFI: ConstHoistWithBlockFrequency
151 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
152 : nullptr,
153 Entry&: Fn.getEntryBlock(),
154 PSI: &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(Args: findMatInsertPt(Inst: U.Inst, Idx: 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(i: Idx);
176 if (auto CastInst = dyn_cast<Instruction>(Val: 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>(Val: 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>(Val: Inst)) {
190 InsertionBlock = cast<PHINode>(Val: Inst)->getIncomingBlock(i: 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(BB: 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.
213static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
214 BasicBlock *Entry,
215 SetVector<BasicBlock *> &BBs) {
216 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
217 // Nodes on the current path to the root.
218 SmallPtrSet<BasicBlock *, 8> Path;
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'.
222 SmallPtrSet<BasicBlock *, 16> Candidates;
223 for (auto *BB : BBs) {
224 // Ignore unreachable basic blocks.
225 if (!DT.isReachableFromEntry(A: 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(Ptr: Node);
235 if (Node == Entry || Candidates.count(Ptr: Node)) {
236 isCandidate = true;
237 break;
238 }
239 assert(DT.getNode(Node)->getIDom() &&
240 "Entry doens't dominate current Node");
241 Node = DT.getNode(BB: Node)->getIDom()->getBlock();
242 } while (!BBs.count(key: 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(R&: Path);
251 }
252
253 // Sort the nodes in Candidates in top-down order and save the nodes
254 // in Orders.
255 unsigned Idx = 0;
256 SmallVector<BasicBlock *, 16> Orders;
257 Orders.push_back(Elt: Entry);
258 while (Idx != Orders.size()) {
259 BasicBlock *Node = Orders[Idx++];
260 for (auto *ChildDomNode : DT.getNode(BB: Node)->children()) {
261 if (Candidates.count(Ptr: ChildDomNode->getBlock()))
262 Orders.push_back(Elt: 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().
273 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
274 for (BasicBlock *Node : Orders)
275 InsertPtsMap.try_emplace(Key: Node);
276 for (BasicBlock *Node : llvm::reverse(C&: Orders)) {
277 bool NodeInBBs = BBs.count(key: Node);
278 auto &[InsertPts, InsertPtsFreq] = InsertPtsMap.find(Val: Node)->second;
279
280 // Return the optimal insert points in BBs.
281 if (Node == Entry) {
282 BBs.clear();
283 if (InsertPtsFreq > BFI.getBlockFreq(BB: Node) ||
284 (InsertPtsFreq == BFI.getBlockFreq(BB: Node) && InsertPts.size() > 1))
285 BBs.insert(X: Entry);
286 else
287 BBs.insert_range(R&: InsertPts);
288 break;
289 }
290
291 BasicBlock *Parent = DT.getNode(BB: 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(Val: 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(BB: Node) ||
304 (InsertPtsFreq == BFI.getBlockFreq(BB: Node) && InsertPts.size() > 1)))) {
305 ParentInsertPts.insert(X: Node);
306 ParentPtsFreq += BFI.getBlockFreq(BB: Node);
307 } else {
308 ParentInsertPts.insert_range(R&: 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(X: MatInsertPt->getParent());
326
327 if (BBs.count(key: Entry)) {
328 InsertPts.insert(X: Entry->begin());
329 return InsertPts;
330 }
331
332 if (BFI) {
333 findBestInsertionSet(DT&: *DT, BFI&: *BFI, Entry, BBs);
334 for (BasicBlock *BB : BBs)
335 InsertPts.insert(X: 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(A: BB1, B: BB2);
344 if (BB == Entry) {
345 InsertPts.insert(X: Entry->begin());
346 return InsertPts;
347 }
348 BBs.insert(X: BB);
349 }
350 assert((BBs.size() == 1) && "Expected only one element.");
351 Instruction &FirstInst = (*BBs.begin())->front();
352 InsertPts.insert(X: findMatInsertPt(Inst: &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
368 InstructionCost Cost;
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>(Val: Inst))
372 Cost = TTI->getIntImmCostIntrin(IID: IntrInst->getIntrinsicID(), Idx,
373 Imm: ConstInt->getValue(), Ty: ConstInt->getType(),
374 CostKind: TargetTransformInfo::TCK_SizeAndLatency);
375 else
376 Cost = TTI->getIntImmCostInst(
377 Opc: Inst->getOpcode(), Idx, Imm: ConstInt->getValue(), Ty: ConstInt->getType(),
378 CostKind: TargetTransformInfo::TCK_SizeAndLatency, Inst);
379
380 // Ignore cheap integer constants.
381 if (Cost > TargetTransformInfo::TCC_Basic) {
382 ConstCandMapType::iterator Itr;
383 bool Inserted;
384 ConstPtrUnionType Cand = ConstInt;
385 std::tie(args&: Itr, args&: Inserted) = ConstCandMap.try_emplace(Key: Cand);
386 if (Inserted) {
387 ConstIntCandVec.push_back(x: ConstantCandidate(ConstInt));
388 Itr->second = ConstIntCandVec.size() - 1;
389 }
390 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost: 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>(Val: ConstExpr->getOperand(i_nocapture: 0));
410 if (!BaseGV)
411 return;
412
413 // Get offset from the base GV.
414 PointerType *GVPtrTy = cast<PointerType>(Val: BaseGV->getType());
415 IntegerType *OffsetTy = DL->getIndexType(C&: *Ctx, AddressSpace: GVPtrTy->getAddressSpace());
416 APInt Offset(DL->getTypeSizeInBits(Ty: OffsetTy), /*val*/ 0, /*isSigned*/ true);
417 auto *GEPO = cast<GEPOperator>(Val: 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: *DL, Offset))
427 return;
428
429 if (!Offset.isIntN(N: 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.
436 InstructionCost Cost =
437 TTI->getIntImmCostInst(Opc: Instruction::Add, Idx: 1, Imm: Offset, Ty: OffsetTy,
438 CostKind: TargetTransformInfo::TCK_SizeAndLatency, Inst);
439 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
440 ConstCandMapType::iterator Itr;
441 bool Inserted;
442 ConstPtrUnionType Cand = ConstExpr;
443 std::tie(args&: Itr, args&: Inserted) = ConstCandMap.try_emplace(Key: Cand);
444 if (Inserted) {
445 ExprCandVec.push_back(x: ConstantCandidate(
446 ConstantInt::get(Ty: Type::getInt32Ty(C&: *Ctx), V: Offset.getLimitedValue()),
447 ConstExpr));
448 Itr->second = ExprCandVec.size() - 1;
449 }
450 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost: 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(i: Idx);
457
458 // Visit constant integers.
459 if (auto ConstInt = dyn_cast<ConstantInt>(Val: 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>(Val: 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>(Val: CastInst->getOperand(i: 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>(Val: Opnd)) {
481 // Handle constant gep expressions.
482 if (ConstHoistGEP && isa<GEPOperator>(Val: 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>(Val: ConstExpr->getOperand(i_nocapture: 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 // Skip analyzing incoming PHI edges from unreachable blocks.
509 if (auto PHI = dyn_cast<PHINode>(Val: Inst)) {
510 BasicBlock *IncomingBB = PHI->getIncomingBlock(i: Idx);
511 if (!DT->isReachableFromEntry(A: IncomingBB))
512 continue;
513 }
514 // The cost of materializing the constants (defined in
515 // `TargetTransformInfo::getIntImmCostInst`) for instructions which only
516 // take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
517 // So it's safe for us to collect constant candidates from all
518 // IntrinsicInsts.
519 if (canReplaceOperandWithVariable(I: Inst, OpIdx: Idx)) {
520 collectConstantCandidates(ConstCandMap, Inst, Idx);
521 }
522 } // end of for all operands
523}
524
525/// Collect all integer constants in the function that cannot be folded
526/// into an instruction itself.
527void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
528 ConstCandMapType ConstCandMap;
529 for (BasicBlock &BB : Fn) {
530 // Ignore unreachable basic blocks.
531 if (!DT->isReachableFromEntry(A: &BB))
532 continue;
533 for (Instruction &Inst : BB)
534 if (!TTI->preferToKeepConstantsAttached(Inst, Fn))
535 collectConstantCandidates(ConstCandMap, Inst: &Inst);
536 }
537}
538
539// From a list of constants, one needs to picked as the base and the other
540// constants will be transformed into an offset from that base constant. The
541// question is which we can pick best? For example, consider these constants
542// and their number of uses:
543//
544// Constants| 2 | 4 | 12 | 42 |
545// NumUses | 3 | 2 | 8 | 7 |
546//
547// Selecting constant 12 because it has the most uses will generate negative
548// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
549// offsets lead to less optimal code generation, then there might be better
550// solutions. Suppose immediates in the range of 0..35 are most optimally
551// supported by the architecture, then selecting constant 2 is most optimal
552// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
553// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
554// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
555// selecting the base constant the range of the offsets is a very important
556// factor too that we take into account here. This algorithm calculates a total
557// costs for selecting a constant as the base and substract the costs if
558// immediates are out of range. It has quadratic complexity, so we call this
559// function only when we're optimising for size and there are less than 100
560// constants, we fall back to the straightforward algorithm otherwise
561// which does not do all the offset calculations.
562unsigned
563ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
564 ConstCandVecType::iterator E,
565 ConstCandVecType::iterator &MaxCostItr) {
566 unsigned NumUses = 0;
567
568 if (!OptForSize || std::distance(first: S,last: E) > 100) {
569 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
570 NumUses += ConstCand->Uses.size();
571 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
572 MaxCostItr = ConstCand;
573 }
574 return NumUses;
575 }
576
577 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
578 InstructionCost MaxCost = -1;
579 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
580 auto Value = ConstCand->ConstInt->getValue();
581 Type *Ty = ConstCand->ConstInt->getType();
582 InstructionCost Cost = 0;
583 NumUses += ConstCand->Uses.size();
584 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
585 << "\n");
586
587 for (auto User : ConstCand->Uses) {
588 unsigned Opcode = User.Inst->getOpcode();
589 unsigned OpndIdx = User.OpndIdx;
590 Cost += TTI->getIntImmCostInst(Opc: Opcode, Idx: OpndIdx, Imm: Value, Ty,
591 CostKind: TargetTransformInfo::TCK_SizeAndLatency);
592 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
593
594 for (auto C2 = S; C2 != E; ++C2) {
595 APInt Diff = C2->ConstInt->getValue() - ConstCand->ConstInt->getValue();
596 const InstructionCost ImmCosts =
597 TTI->getIntImmCodeSizeCost(Opc: Opcode, Idx: OpndIdx, Imm: Diff, Ty);
598 Cost -= ImmCosts;
599 LLVM_DEBUG(dbgs() << "Offset " << Diff << " "
600 << "has penalty: " << ImmCosts << "\n"
601 << "Adjusted cost: " << Cost << "\n");
602 }
603 }
604 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
605 if (Cost > MaxCost) {
606 MaxCost = Cost;
607 MaxCostItr = ConstCand;
608 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
609 << "\n");
610 }
611 }
612 return NumUses;
613}
614
615/// Find the base constant within the given range and rebase all other
616/// constants with respect to the base constant.
617void ConstantHoistingPass::findAndMakeBaseConstant(
618 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
619 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
620 auto MaxCostItr = S;
621 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
622
623 // Don't hoist constants that have only one use.
624 if (NumUses <= 1)
625 return;
626
627 ConstantInt *ConstInt = MaxCostItr->ConstInt;
628 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
629 ConstantInfo ConstInfo;
630 ConstInfo.BaseInt = ConstInt;
631 ConstInfo.BaseExpr = ConstExpr;
632 Type *Ty = ConstInt->getType();
633
634 // Rebase the constants with respect to the base constant.
635 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
636 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
637 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, V: Diff);
638 Type *ConstTy =
639 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
640 ConstInfo.RebasedConstants.push_back(
641 Elt: RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
642 }
643 ConstInfoVec.push_back(Elt: std::move(ConstInfo));
644}
645
646/// Finds and combines constant candidates that can be easily
647/// rematerialized with an add from a common base constant.
648void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
649 // If BaseGV is nullptr, find base among candidate constant integers;
650 // Otherwise find base among constant GEPs that share the same BaseGV.
651 ConstCandVecType &ConstCandVec = BaseGV ?
652 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
653 ConstInfoVecType &ConstInfoVec = BaseGV ?
654 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
655
656 // Sort the constants by value and type. This invalidates the mapping!
657 llvm::stable_sort(Range&: ConstCandVec, C: [](const ConstantCandidate &LHS,
658 const ConstantCandidate &RHS) {
659 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
660 return LHS.ConstInt->getBitWidth() < RHS.ConstInt->getBitWidth();
661 return LHS.ConstInt->getValue().ult(RHS: RHS.ConstInt->getValue());
662 });
663
664 // Simple linear scan through the sorted constant candidate vector for viable
665 // merge candidates.
666 auto MinValItr = ConstCandVec.begin();
667 for (auto CC = std::next(x: ConstCandVec.begin()), E = ConstCandVec.end();
668 CC != E; ++CC) {
669 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
670 Type *MemUseValTy = nullptr;
671 for (auto &U : CC->Uses) {
672 auto *UI = U.Inst;
673 if (LoadInst *LI = dyn_cast<LoadInst>(Val: UI)) {
674 MemUseValTy = LI->getType();
675 break;
676 } else if (StoreInst *SI = dyn_cast<StoreInst>(Val: UI)) {
677 // Make sure the constant is used as pointer operand of the StoreInst.
678 if (SI->getPointerOperand() == SI->getOperand(i_nocapture: U.OpndIdx)) {
679 MemUseValTy = SI->getValueOperand()->getType();
680 break;
681 }
682 }
683 }
684
685 // Check if the constant is in range of an add with immediate.
686 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
687 if ((Diff.getBitWidth() <= 64) &&
688 TTI->isLegalAddImmediate(Imm: Diff.getSExtValue()) &&
689 // Check if Diff can be used as offset in addressing mode of the user
690 // memory instruction.
691 (!MemUseValTy || TTI->isLegalAddressingMode(Ty: MemUseValTy,
692 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
693 /*HasBaseReg*/true, /*Scale*/0)))
694 continue;
695 }
696 // We either have now a different constant type or the constant is not in
697 // range of an add with immediate anymore.
698 findAndMakeBaseConstant(S: MinValItr, E: CC, ConstInfoVec);
699 // Start a new base constant search.
700 MinValItr = CC;
701 }
702 // Finalize the last base constant search.
703 findAndMakeBaseConstant(S: MinValItr, E: ConstCandVec.end(), ConstInfoVec);
704}
705
706/// Updates the operand at Idx in instruction Inst with the result of
707/// instruction Mat. If the instruction is a PHI node then special
708/// handling for duplicate values from the same incoming basic block is
709/// required.
710/// \return The update will always succeed, but the return value indicated if
711/// Mat was used for the update or not.
712static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
713 if (auto PHI = dyn_cast<PHINode>(Val: Inst)) {
714 // Check if any previous operand of the PHI node has the same incoming basic
715 // block. This is a very odd case that happens when the incoming basic block
716 // has a switch statement. In this case use the same value as the previous
717 // operand(s), otherwise we will fail verification due to different values.
718 // The values are actually the same, but the variable names are different
719 // and the verifier doesn't like that.
720 BasicBlock *IncomingBB = PHI->getIncomingBlock(i: Idx);
721 for (unsigned i = 0; i < Idx; ++i) {
722 if (PHI->getIncomingBlock(i) == IncomingBB) {
723 Value *IncomingVal = PHI->getIncomingValue(i);
724 Inst->setOperand(i: Idx, Val: IncomingVal);
725 return false;
726 }
727 }
728 }
729
730 Inst->setOperand(i: Idx, Val: Mat);
731 return true;
732}
733
734/// Emit materialization code for all rebased constants and update their
735/// users.
736void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
737 UserAdjustment *Adj) {
738 Instruction *Mat = Base;
739
740 // The same offset can be dereferenced to different types in nested struct.
741 if (!Adj->Offset && Adj->Ty && Adj->Ty != Base->getType())
742 Adj->Offset = ConstantInt::get(Ty: Type::getInt32Ty(C&: *Ctx), V: 0);
743
744 if (Adj->Offset) {
745 if (Adj->Ty) {
746 // Constant being rebased is a ConstantExpr.
747 Mat = GetElementPtrInst::Create(PointeeType: Type::getInt8Ty(C&: *Ctx), Ptr: Base, IdxList: Adj->Offset,
748 NameStr: "mat_gep", InsertBefore: Adj->MatInsertPt);
749 // Hide it behind a bitcast.
750 Mat = new BitCastInst(Mat, Adj->Ty, "mat_bitcast",
751 Adj->MatInsertPt->getIterator());
752 } else
753 // Constant being rebased is a ConstantInt.
754 Mat =
755 BinaryOperator::Create(Op: Instruction::Add, S1: Base, S2: Adj->Offset,
756 Name: "const_mat", InsertBefore: Adj->MatInsertPt->getIterator());
757
758 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
759 << " + " << *Adj->Offset << ") in BB "
760 << Mat->getParent()->getName() << '\n'
761 << *Mat << '\n');
762 Mat->setDebugLoc(Adj->User.Inst->getDebugLoc());
763 }
764 Value *Opnd = Adj->User.Inst->getOperand(i: Adj->User.OpndIdx);
765
766 // Visit constant integer.
767 if (isa<ConstantInt>(Val: Opnd)) {
768 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
769 if (!updateOperand(Inst: Adj->User.Inst, Idx: Adj->User.OpndIdx, Mat) && Adj->Offset)
770 Mat->eraseFromParent();
771 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
772 return;
773 }
774
775 // Visit cast instruction.
776 if (auto CastInst = dyn_cast<Instruction>(Val: Opnd)) {
777 assert(CastInst->isCast() && "Expected an cast instruction!");
778 // Check if we already have visited this cast instruction before to avoid
779 // unnecessary cloning.
780 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
781 if (!ClonedCastInst) {
782 ClonedCastInst = CastInst->clone();
783 ClonedCastInst->setOperand(i: 0, Val: Mat);
784 ClonedCastInst->insertAfter(InsertPos: CastInst->getIterator());
785 // Use the same debug location as the original cast instruction.
786 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
787 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
788 << "To : " << *ClonedCastInst << '\n');
789 }
790
791 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
792 updateOperand(Inst: Adj->User.Inst, Idx: Adj->User.OpndIdx, Mat: ClonedCastInst);
793 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
794 return;
795 }
796
797 // Visit constant expression.
798 if (auto ConstExpr = dyn_cast<ConstantExpr>(Val: Opnd)) {
799 if (isa<GEPOperator>(Val: ConstExpr)) {
800 // Operand is a ConstantGEP, replace it.
801 updateOperand(Inst: Adj->User.Inst, Idx: Adj->User.OpndIdx, Mat);
802 return;
803 }
804
805 // Aside from constant GEPs, only constant cast expressions are collected.
806 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
807 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
808 ConstExprInst->insertBefore(InsertPos: Adj->MatInsertPt);
809 ConstExprInst->setOperand(i: 0, Val: Mat);
810
811 // Use the same debug location as the instruction we are about to update.
812 ConstExprInst->setDebugLoc(Adj->User.Inst->getDebugLoc());
813
814 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
815 << "From : " << *ConstExpr << '\n');
816 LLVM_DEBUG(dbgs() << "Update: " << *Adj->User.Inst << '\n');
817 if (!updateOperand(Inst: Adj->User.Inst, Idx: Adj->User.OpndIdx, Mat: ConstExprInst)) {
818 ConstExprInst->eraseFromParent();
819 if (Adj->Offset)
820 Mat->eraseFromParent();
821 }
822 LLVM_DEBUG(dbgs() << "To : " << *Adj->User.Inst << '\n');
823 return;
824 }
825}
826
827/// Hoist and hide the base constant behind a bitcast and emit
828/// materialization code for derived constants.
829bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
830 bool MadeChange = false;
831 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
832 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
833 for (const consthoist::ConstantInfo &ConstInfo : ConstInfoVec) {
834 SmallVector<BasicBlock::iterator, 4> MatInsertPts;
835 collectMatInsertPts(RebasedConstants: ConstInfo.RebasedConstants, MatInsertPts);
836 SetVector<BasicBlock::iterator> IPSet =
837 findConstantInsertionPoint(ConstInfo, MatInsertPts);
838 // We can have an empty set if the function contains unreachable blocks.
839 if (IPSet.empty())
840 continue;
841
842 unsigned UsesNum = 0;
843 unsigned ReBasesNum = 0;
844 unsigned NotRebasedNum = 0;
845 for (const BasicBlock::iterator &IP : IPSet) {
846 // First, collect constants depending on this IP of the base.
847 UsesNum = 0;
848 SmallVector<UserAdjustment, 4> ToBeRebased;
849 unsigned MatCtr = 0;
850 for (auto const &RCI : ConstInfo.RebasedConstants) {
851 UsesNum += RCI.Uses.size();
852 for (auto const &U : RCI.Uses) {
853 const BasicBlock::iterator &MatInsertPt = MatInsertPts[MatCtr++];
854 BasicBlock *OrigMatInsertBB = MatInsertPt->getParent();
855 // If Base constant is to be inserted in multiple places,
856 // generate rebase for U using the Base dominating U.
857 if (IPSet.size() == 1 ||
858 DT->dominates(A: IP->getParent(), B: OrigMatInsertBB))
859 ToBeRebased.emplace_back(Args: RCI.Offset, Args: RCI.Ty, Args: MatInsertPt, Args: U);
860 }
861 }
862
863 // If only few constants depend on this IP of base, skip rebasing,
864 // assuming the base and the rebased have the same materialization cost.
865 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
866 NotRebasedNum += ToBeRebased.size();
867 continue;
868 }
869
870 // Emit an instance of the base at this IP.
871 Instruction *Base = nullptr;
872 // Hoist and hide the base constant behind a bitcast.
873 if (ConstInfo.BaseExpr) {
874 assert(BaseGV && "A base constant expression must have an base GV");
875 Type *Ty = ConstInfo.BaseExpr->getType();
876 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
877 } else {
878 IntegerType *Ty = ConstInfo.BaseInt->getIntegerType();
879 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
880 }
881
882 Base->setDebugLoc(IP->getDebugLoc());
883
884 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
885 << ") to BB " << IP->getParent()->getName() << '\n'
886 << *Base << '\n');
887
888 // Emit materialization code for rebased constants depending on this IP.
889 for (UserAdjustment &R : ToBeRebased) {
890 emitBaseConstants(Base, Adj: &R);
891 ReBasesNum++;
892 // Use the same debug location as the last user of the constant.
893 Base->setDebugLoc(DebugLoc::getMergedLocation(
894 LocA: Base->getDebugLoc(), LocB: R.User.Inst->getDebugLoc()));
895 }
896 assert(!Base->use_empty() && "The use list is empty!?");
897 assert(isa<Instruction>(Base->user_back()) &&
898 "All uses should be instructions.");
899 }
900 (void)UsesNum;
901 (void)ReBasesNum;
902 (void)NotRebasedNum;
903 // Expect all uses are rebased after rebase is done.
904 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
905 "Not all uses are rebased");
906
907 NumConstantsHoisted++;
908
909 // Base constant is also included in ConstInfo.RebasedConstants, so
910 // deduct 1 from ConstInfo.RebasedConstants.size().
911 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
912
913 MadeChange = true;
914 }
915 return MadeChange;
916}
917
918/// Check all cast instructions we made a copy of and remove them if they
919/// have no more users.
920void ConstantHoistingPass::deleteDeadCastInst() const {
921 for (auto const &I : ClonedCastMap)
922 if (I.first->use_empty())
923 I.first->eraseFromParent();
924}
925
926/// Optimize expensive integer constants in the given function.
927bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
928 DominatorTree &DT, BlockFrequencyInfo *BFI,
929 BasicBlock &Entry, ProfileSummaryInfo *PSI) {
930 this->TTI = &TTI;
931 this->DT = &DT;
932 this->BFI = BFI;
933 this->DL = &Fn.getDataLayout();
934 this->Ctx = &Fn.getContext();
935 this->Entry = &Entry;
936 this->PSI = PSI;
937 this->OptForSize = llvm::shouldOptimizeForSize(F: Entry.getParent(), PSI, BFI,
938 QueryType: PGSOQueryType::IRPass);
939
940 // Collect all constant candidates.
941 collectConstantCandidates(Fn);
942
943 // Combine constants that can be easily materialized with an add from a common
944 // base constant.
945 if (!ConstIntCandVec.empty())
946 findBaseConstants(BaseGV: nullptr);
947 for (const auto &MapEntry : ConstGEPCandMap)
948 if (!MapEntry.second.empty())
949 findBaseConstants(BaseGV: MapEntry.first);
950
951 // Finally hoist the base constant and emit materialization code for dependent
952 // constants.
953 bool MadeChange = false;
954 if (!ConstIntInfoVec.empty())
955 MadeChange = emitBaseConstants(BaseGV: nullptr);
956 for (const auto &MapEntry : ConstGEPInfoMap)
957 if (!MapEntry.second.empty())
958 MadeChange |= emitBaseConstants(BaseGV: MapEntry.first);
959
960
961 // Cleanup dead instructions.
962 deleteDeadCastInst();
963
964 cleanup();
965
966 return MadeChange;
967}
968
969PreservedAnalyses ConstantHoistingPass::run(Function &F,
970 FunctionAnalysisManager &AM) {
971 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
972 auto &TTI = AM.getResult<TargetIRAnalysis>(IR&: F);
973 auto BFI = ConstHoistWithBlockFrequency
974 ? &AM.getResult<BlockFrequencyAnalysis>(IR&: F)
975 : nullptr;
976 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(IR&: F);
977 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(IR&: *F.getParent());
978 if (!runImpl(Fn&: F, TTI, DT, BFI, Entry&: F.getEntryBlock(), PSI))
979 return PreservedAnalyses::all();
980
981 PreservedAnalyses PA;
982 PA.preserveSet<CFGAnalyses>();
983 return PA;
984}
985