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