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