1 //===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass identifies expensive constants to hoist and coalesces them to
11 // better prepare it for SelectionDAG-based code generation. This works around
12 // the limitations of the basic-block-at-a-time approach.
14 // First it scans all instructions for integer constants and calculates its
15 // cost. If the constant can be folded into the instruction (the cost is
16 // TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
17 // consider it expensive and leave it alone. This is the default behavior and
18 // the default implementation of getIntImmCost will always return TCC_Free.
20 // If the cost is more than TCC_BASIC, then the integer constant can't be folded
21 // into the instruction and it might be beneficial to hoist the constant.
22 // Similar constants are coalesced to reduce register pressure and
23 // materialization code.
25 // When a constant is hoisted, it is also hidden behind a bitcast to force it to
26 // be live-out of the basic block. Otherwise the constant would be just
27 // duplicated and each basic block would have its own copy in the SelectionDAG.
28 // The SelectionDAG recognizes such constants as opaque and doesn't perform
29 // certain transformations on them, which would create a new expensive constant.
31 // This optimization is only applied to integer constants in instructions and
32 // simple (this means not nested) constant cast expressions. For example:
33 // %0 = load i64* inttoptr (i64 big_constant to i64*)
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "consthoist"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Analysis/TargetTransformInfo.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Debug.h"
50 STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51 STATISTIC(NumConstantsRebased, "Number of constants rebased");
55 struct RebasedConstantInfo;
57 typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58 typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
60 /// \brief Keeps track of the user of a constant and the operand index where the
66 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
69 /// \brief Keeps track of a constant candidate and its uses.
70 struct ConstantCandidate {
71 ConstantUseListType Uses;
72 ConstantInt *ConstInt;
73 unsigned CumulativeCost;
75 ConstantCandidate(ConstantInt *ConstInt)
76 : ConstInt(ConstInt), CumulativeCost(0) { }
78 /// \brief Add the user to the use list and update the cost.
79 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
80 CumulativeCost += Cost;
81 Uses.push_back(ConstantUser(Inst, Idx));
85 /// \brief This represents a constant that has been rebased with respect to a
86 /// base constant. The difference to the base constant is recorded in Offset.
87 struct RebasedConstantInfo {
88 ConstantUseListType Uses;
91 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
92 : Uses(Uses), Offset(Offset) { }
95 /// \brief A base constant and all its rebased constants.
97 ConstantInt *BaseConstant;
98 RebasedConstantListType RebasedConstants;
101 /// \brief The constant hoisting pass.
102 class ConstantHoisting : public FunctionPass {
103 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104 typedef std::vector<ConstantCandidate> ConstCandVecType;
106 const TargetTransformInfo *TTI;
110 /// Keeps track of constant candidates found in the function.
111 ConstCandVecType ConstCandVec;
113 /// Keep track of cast instructions we already cloned.
114 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
116 /// These are the final constants we decided to hoist.
117 SmallVector<ConstantInfo, 8> ConstantVec;
119 static char ID; // Pass identification, replacement for typeid
120 ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
121 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
124 bool runOnFunction(Function &Fn) override;
126 const char *getPassName() const override { return "Constant Hoisting"; }
128 void getAnalysisUsage(AnalysisUsage &AU) const override {
129 AU.setPreservesCFG();
130 AU.addRequired<DominatorTreeWrapperPass>();
131 AU.addRequired<TargetTransformInfo>();
135 /// \brief Initialize the pass.
136 void setup(Function &Fn) {
137 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
138 TTI = &getAnalysis<TargetTransformInfo>();
139 Entry = &Fn.getEntryBlock();
145 ClonedCastMap.clear();
146 ConstCandVec.clear();
153 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
154 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
155 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
156 Instruction *Inst, unsigned Idx,
157 ConstantInt *ConstInt);
158 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
160 void collectConstantCandidates(Function &Fn);
161 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
162 ConstCandVecType::iterator E);
163 void findBaseConstants();
164 void emitBaseConstants(Instruction *Base, Constant *Offset,
165 const ConstantUser &ConstUser);
166 bool emitBaseConstants();
167 void deleteDeadCastInst() const;
168 bool optimizeConstants(Function &Fn);
172 char ConstantHoisting::ID = 0;
173 INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
175 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177 INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
180 FunctionPass *llvm::createConstantHoistingPass() {
181 return new ConstantHoisting();
184 /// \brief Perform the constant hoisting optimization for the given function.
185 bool ConstantHoisting::runOnFunction(Function &Fn) {
186 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
187 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
191 bool MadeChange = optimizeConstants(Fn);
194 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
195 << Fn.getName() << '\n');
198 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
206 /// \brief Find the constant materialization insertion point.
207 Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
208 unsigned Idx) const {
209 // The simple and common case.
210 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
213 // We can't insert directly before a phi node or landing pad. Insert before
214 // the terminator of the incoming or dominating block.
215 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
216 if (Idx != ~0U && isa<PHINode>(Inst))
217 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
219 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
220 return IDom->getTerminator();
223 /// \brief Find an insertion point that dominates all uses.
224 Instruction *ConstantHoisting::
225 findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
226 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
227 // Collect all basic blocks.
228 SmallPtrSet<BasicBlock *, 8> BBs;
229 for (auto const &RCI : ConstInfo.RebasedConstants)
230 for (auto const &U : RCI.Uses)
231 BBs.insert(U.Inst->getParent());
233 if (BBs.count(Entry))
234 return &Entry->front();
236 while (BBs.size() >= 2) {
237 BasicBlock *BB, *BB1, *BB2;
239 BB2 = *std::next(BBs.begin());
240 BB = DT->findNearestCommonDominator(BB1, BB2);
242 return &Entry->front();
247 assert((BBs.size() == 1) && "Expected only one element.");
248 Instruction &FirstInst = (*BBs.begin())->front();
249 return findMatInsertPt(&FirstInst);
253 /// \brief Record constant integer ConstInt for instruction Inst at operand
256 /// The operand at index Idx is not necessarily the constant integer itself. It
257 /// could also be a cast instruction or a constant expression that uses the
259 void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
262 ConstantInt *ConstInt) {
264 // Ask the target about the cost of materializing the constant for the given
265 // instruction and operand index.
266 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
267 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
268 ConstInt->getValue(), ConstInt->getType());
270 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
271 ConstInt->getType());
273 // Ignore cheap integer constants.
274 if (Cost > TargetTransformInfo::TCC_Basic) {
275 ConstCandMapType::iterator Itr;
277 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
279 ConstCandVec.push_back(ConstantCandidate(ConstInt));
280 Itr->second = ConstCandVec.size() - 1;
282 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
283 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
284 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
285 << " with cost " << Cost << '\n';
287 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
288 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
294 /// \brief Scan the instruction for expensive integer constants and record them
295 /// in the constant candidate vector.
296 void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
298 // Skip all cast instructions. They are visited indirectly later on.
302 // Can't handle inline asm. Skip it.
303 if (auto Call = dyn_cast<CallInst>(Inst))
304 if (isa<InlineAsm>(Call->getCalledValue()))
307 // Scan all operands.
308 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
309 Value *Opnd = Inst->getOperand(Idx);
311 // Visit constant integers.
312 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
313 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
317 // Visit cast instructions that have constant integers.
318 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
319 // Only visit cast instructions, which have been skipped. All other
320 // instructions should have already been visited.
321 if (!CastInst->isCast())
324 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
325 // Pretend the constant is directly used by the instruction and ignore
326 // the cast instruction.
327 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
332 // Visit constant expressions that have constant integers.
333 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
334 // Only visit constant cast expressions.
335 if (!ConstExpr->isCast())
338 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
339 // Pretend the constant is directly used by the instruction and ignore
340 // the constant expression.
341 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
345 } // end of for all operands
348 /// \brief Collect all integer constants in the function that cannot be folded
349 /// into an instruction itself.
350 void ConstantHoisting::collectConstantCandidates(Function &Fn) {
351 ConstCandMapType ConstCandMap;
352 for (Function::iterator BB : Fn)
353 for (BasicBlock::iterator Inst : *BB)
354 collectConstantCandidates(ConstCandMap, Inst);
357 /// \brief Find the base constant within the given range and rebase all other
358 /// constants with respect to the base constant.
359 void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
360 ConstCandVecType::iterator E) {
362 unsigned NumUses = 0;
363 // Use the constant that has the maximum cost as base constant.
364 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
365 NumUses += ConstCand->Uses.size();
366 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
367 MaxCostItr = ConstCand;
370 // Don't hoist constants that have only one use.
374 ConstantInfo ConstInfo;
375 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
376 Type *Ty = ConstInfo.BaseConstant->getType();
378 // Rebase the constants with respect to the base constant.
379 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
380 APInt Diff = ConstCand->ConstInt->getValue() -
381 ConstInfo.BaseConstant->getValue();
382 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
383 ConstInfo.RebasedConstants.push_back(
384 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
386 ConstantVec.push_back(ConstInfo);
389 /// \brief Finds and combines constant candidates that can be easily
390 /// rematerialized with an add from a common base constant.
391 void ConstantHoisting::findBaseConstants() {
392 // Sort the constants by value and type. This invalidates the mapping!
393 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
394 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
395 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
396 return LHS.ConstInt->getType()->getBitWidth() <
397 RHS.ConstInt->getType()->getBitWidth();
398 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
401 // Simple linear scan through the sorted constant candidate vector for viable
403 auto MinValItr = ConstCandVec.begin();
404 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
406 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
407 // Check if the constant is in range of an add with immediate.
408 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
409 if ((Diff.getBitWidth() <= 64) &&
410 TTI->isLegalAddImmediate(Diff.getSExtValue()))
413 // We either have now a different constant type or the constant is not in
414 // range of an add with immediate anymore.
415 findAndMakeBaseConstant(MinValItr, CC);
416 // Start a new base constant search.
419 // Finalize the last base constant search.
420 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
423 /// \brief Updates the operand at Idx in instruction Inst with the result of
424 /// instruction Mat. If the instruction is a PHI node then special
425 /// handling for duplicate values form the same incomming basic block is
427 /// \return The update will always succeed, but the return value indicated if
428 /// Mat was used for the update or not.
429 static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
430 if (auto PHI = dyn_cast<PHINode>(Inst)) {
431 // Check if any previous operand of the PHI node has the same incoming basic
432 // block. This is a very odd case that happens when the incoming basic block
433 // has a switch statement. In this case use the same value as the previous
434 // operand(s), otherwise we will fail verification due to different values.
435 // The values are actually the same, but the variable names are different
436 // and the verifier doesn't like that.
437 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
438 for (unsigned i = 0; i < Idx; ++i) {
439 if (PHI->getIncomingBlock(i) == IncomingBB) {
440 Value *IncomingVal = PHI->getIncomingValue(i);
441 Inst->setOperand(Idx, IncomingVal);
447 Inst->setOperand(Idx, Mat);
451 /// \brief Emit materialization code for all rebased constants and update their
453 void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
454 const ConstantUser &ConstUser) {
455 Instruction *Mat = Base;
457 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
459 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
460 "const_mat", InsertionPt);
462 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
463 << " + " << *Offset << ") in BB "
464 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
465 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
467 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
469 // Visit constant integer.
470 if (isa<ConstantInt>(Opnd)) {
471 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
472 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
473 Mat->eraseFromParent();
474 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
478 // Visit cast instruction.
479 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
480 assert(CastInst->isCast() && "Expected an cast instruction!");
481 // Check if we already have visited this cast instruction before to avoid
482 // unnecessary cloning.
483 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
484 if (!ClonedCastInst) {
485 ClonedCastInst = CastInst->clone();
486 ClonedCastInst->setOperand(0, Mat);
487 ClonedCastInst->insertAfter(CastInst);
488 // Use the same debug location as the original cast instruction.
489 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
490 DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
491 << "To : " << *CastInst << '\n');
494 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
495 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
496 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
500 // Visit constant expression.
501 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
502 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
503 ConstExprInst->setOperand(0, Mat);
504 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
507 // Use the same debug location as the instruction we are about to update.
508 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
510 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
511 << "From : " << *ConstExpr << '\n');
512 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
513 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
514 ConstExprInst->eraseFromParent();
516 Mat->eraseFromParent();
518 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
523 /// \brief Hoist and hide the base constant behind a bitcast and emit
524 /// materialization code for derived constants.
525 bool ConstantHoisting::emitBaseConstants() {
526 bool MadeChange = false;
527 for (auto const &ConstInfo : ConstantVec) {
528 // Hoist and hide the base constant behind a bitcast.
529 Instruction *IP = findConstantInsertionPoint(ConstInfo);
530 IntegerType *Ty = ConstInfo.BaseConstant->getType();
532 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
533 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
534 << IP->getParent()->getName() << '\n' << *Base << '\n');
535 NumConstantsHoisted++;
537 // Emit materialization code for all rebased constants.
538 for (auto const &RCI : ConstInfo.RebasedConstants) {
539 NumConstantsRebased++;
540 for (auto const &U : RCI.Uses)
541 emitBaseConstants(Base, RCI.Offset, U);
544 // Use the same debug location as the last user of the constant.
545 assert(!Base->use_empty() && "The use list is empty!?");
546 assert(isa<Instruction>(Base->user_back()) &&
547 "All uses should be instructions.");
548 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
550 // Correct for base constant, which we counted above too.
551 NumConstantsRebased--;
557 /// \brief Check all cast instructions we made a copy of and remove them if they
558 /// have no more users.
559 void ConstantHoisting::deleteDeadCastInst() const {
560 for (auto const &I : ClonedCastMap)
561 if (I.first->use_empty())
562 I.first->eraseFromParent();
565 /// \brief Optimize expensive integer constants in the given function.
566 bool ConstantHoisting::optimizeConstants(Function &Fn) {
567 // Collect all constant candidates.
568 collectConstantCandidates(Fn);
570 // There are no constant candidates to worry about.
571 if (ConstCandVec.empty())
574 // Combine constants that can be easily materialized with an add from a common
578 // There are no constants to emit.
579 if (ConstantVec.empty())
582 // Finally hoist the base constant and emit materialization code for dependent
584 bool MadeChange = emitBaseConstants();
586 // Cleanup dead instructions.
587 deleteDeadCastInst();