blob: fc6cd540c47e98bcf9cf95b01c3aceb8eb914213 [file] [log] [blame]
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
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.
19//
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.
24//
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.
30//
31// This optimization is only applied to integer constants in instructions and
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000032// simple (this means not nested) constant cast expressions. For example:
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000033// %0 = load i64* inttoptr (i64 big_constant to i64*)
34//===----------------------------------------------------------------------===//
35
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000036#include "llvm/Transforms/Scalar.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000037#include "llvm/ADT/SmallSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000038#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/Analysis/TargetTransformInfo.h"
41#include "llvm/IR/Constants.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/Pass.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000045#include "llvm/Support/Debug.h"
46
47using namespace llvm;
48
Chandler Carruth964daaa2014-04-22 02:55:47 +000049#define DEBUG_TYPE "consthoist"
50
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000051STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
52STATISTIC(NumConstantsRebased, "Number of constants rebased");
53
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000054namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000055struct ConstantUser;
56struct RebasedConstantInfo;
57
58typedef SmallVector<ConstantUser, 8> ConstantUseListType;
59typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
60
61/// \brief Keeps track of the user of a constant and the operand index where the
62/// constant is used.
63struct ConstantUser {
64 Instruction *Inst;
65 unsigned OpndIdx;
66
67 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
68};
69
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000070/// \brief Keeps track of a constant candidate and its uses.
Juergen Ributzka6dab5202014-03-20 19:55:52 +000071struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000072 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000073 ConstantInt *ConstInt;
74 unsigned CumulativeCost;
75
76 ConstantCandidate(ConstantInt *ConstInt)
77 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000078
79 /// \brief Add the user to the use list and update the cost.
80 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
81 CumulativeCost += Cost;
82 Uses.push_back(ConstantUser(Inst, Idx));
83 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000084};
85
Juergen Ributzka5429c062014-03-21 06:04:36 +000086/// \brief This represents a constant that has been rebased with respect to a
87/// base constant. The difference to the base constant is recorded in Offset.
88struct RebasedConstantInfo {
89 ConstantUseListType Uses;
90 Constant *Offset;
91
92 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
Juergen Ributzkac81000b2014-04-03 01:38:47 +000093 : Uses(Uses), Offset(Offset) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000094};
95
96/// \brief A base constant and all its rebased constants.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000097struct ConstantInfo {
98 ConstantInt *BaseConstant;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000099 RebasedConstantListType RebasedConstants;
100};
101
Juergen Ributzka5429c062014-03-21 06:04:36 +0000102/// \brief The constant hoisting pass.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000103class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000104 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
105 typedef std::vector<ConstantCandidate> ConstCandVecType;
106
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000107 const TargetTransformInfo *TTI;
108 DominatorTree *DT;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000109 BasicBlock *Entry;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000111 /// Keeps track of constant candidates found in the function.
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000112 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000113
Juergen Ributzka5429c062014-03-21 06:04:36 +0000114 /// Keep track of cast instructions we already cloned.
115 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
116
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000117 /// These are the final constants we decided to hoist.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000118 SmallVector<ConstantInfo, 8> ConstantVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000119public:
120 static char ID; // Pass identification, replacement for typeid
Juergen Ributzka5429c062014-03-21 06:04:36 +0000121 ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000122 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
123 }
124
Juergen Ributzka5429c062014-03-21 06:04:36 +0000125 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000126
Craig Topper3e4c6972014-03-05 09:10:37 +0000127 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000128
Craig Topper3e4c6972014-03-05 09:10:37 +0000129 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000130 AU.setPreservesCFG();
131 AU.addRequired<DominatorTreeWrapperPass>();
132 AU.addRequired<TargetTransformInfo>();
133 }
134
135private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000136 /// \brief Initialize the pass.
137 void setup(Function &Fn) {
138 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139 TTI = &getAnalysis<TargetTransformInfo>();
140 Entry = &Fn.getEntryBlock();
141 }
142
143 /// \brief Cleanup.
144 void cleanup() {
145 ConstantVec.clear();
146 ClonedCastMap.clear();
147 ConstCandVec.clear();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000148
149 TTI = nullptr;
150 DT = nullptr;
151 Entry = nullptr;
152 }
153
154 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
155 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000156 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
157 Instruction *Inst, unsigned Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000158 ConstantInt *ConstInt);
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000159 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
160 Instruction *Inst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000161 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000162 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000163 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000164 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000165 void emitBaseConstants(Instruction *Base, Constant *Offset,
166 const ConstantUser &ConstUser);
167 bool emitBaseConstants();
168 void deleteDeadCastInst() const;
169 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000170};
171}
172
173char ConstantHoisting::ID = 0;
174INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
175 false, false)
176INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
177INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
178INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
179 false, false)
180
181FunctionPass *llvm::createConstantHoistingPass() {
182 return new ConstantHoisting();
183}
184
185/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000186bool ConstantHoisting::runOnFunction(Function &Fn) {
187 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
188 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000189
Juergen Ributzka5429c062014-03-21 06:04:36 +0000190 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000191
Juergen Ributzka5429c062014-03-21 06:04:36 +0000192 bool MadeChange = optimizeConstants(Fn);
193
194 if (MadeChange) {
195 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
196 << Fn.getName() << '\n');
197 DEBUG(dbgs() << Fn);
198 }
199 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
200
201 cleanup();
202
203 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000204}
205
Juergen Ributzka5429c062014-03-21 06:04:36 +0000206
207/// \brief Find the constant materialization insertion point.
208Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
209 unsigned Idx) const {
210 // The simple and common case.
211 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
212 return Inst;
213
214 // We can't insert directly before a phi node or landing pad. Insert before
215 // the terminator of the incoming or dominating block.
216 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
217 if (Idx != ~0U && isa<PHINode>(Inst))
218 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
219
220 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
221 return IDom->getTerminator();
222}
223
224/// \brief Find an insertion point that dominates all uses.
225Instruction *ConstantHoisting::
226findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
227 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000228 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000229 SmallPtrSet<BasicBlock *, 8> BBs;
230 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000231 for (auto const &U : RCI.Uses)
232 BBs.insert(U.Inst->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000233
234 if (BBs.count(Entry))
235 return &Entry->front();
236
237 while (BBs.size() >= 2) {
238 BasicBlock *BB, *BB1, *BB2;
239 BB1 = *BBs.begin();
240 BB2 = *std::next(BBs.begin());
241 BB = DT->findNearestCommonDominator(BB1, BB2);
242 if (BB == Entry)
243 return &Entry->front();
244 BBs.erase(BB1);
245 BBs.erase(BB2);
246 BBs.insert(BB);
247 }
248 assert((BBs.size() == 1) && "Expected only one element.");
249 Instruction &FirstInst = (*BBs.begin())->front();
250 return findMatInsertPt(&FirstInst);
251}
252
253
254/// \brief Record constant integer ConstInt for instruction Inst at operand
255/// index Idx.
256///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000257/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000258/// could also be a cast instruction or a constant expression that uses the
259// constant integer.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000260void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
261 Instruction *Inst,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000262 unsigned Idx,
263 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000264 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000265 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000266 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000267 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000268 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000269 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000270 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000271 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000272 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000273
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000274 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000275 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000276 ConstCandMapType::iterator Itr;
277 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000278 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000279 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000280 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000281 Itr->second = ConstCandVec.size() - 1;
282 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000283 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
284 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
285 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
286 << " with cost " << Cost << '\n';
287 else
288 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
289 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
290 << Cost << '\n';
291 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000292 }
293}
294
Juergen Ributzka5429c062014-03-21 06:04:36 +0000295/// \brief Scan the instruction for expensive integer constants and record them
296/// in the constant candidate vector.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000297void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
298 Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000299 // Skip all cast instructions. They are visited indirectly later on.
300 if (Inst->isCast())
301 return;
302
303 // Can't handle inline asm. Skip it.
304 if (auto Call = dyn_cast<CallInst>(Inst))
305 if (isa<InlineAsm>(Call->getCalledValue()))
306 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000307
308 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000309 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
310 Value *Opnd = Inst->getOperand(Idx);
311
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000312 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000313 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000314 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000315 continue;
316 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000317
318 // Visit cast instructions that have constant integers.
319 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
320 // Only visit cast instructions, which have been skipped. All other
321 // instructions should have already been visited.
322 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000323 continue;
324
Juergen Ributzka5429c062014-03-21 06:04:36 +0000325 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
326 // Pretend the constant is directly used by the instruction and ignore
327 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000328 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000329 continue;
330 }
331 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000332
333 // Visit constant expressions that have constant integers.
334 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
335 // Only visit constant cast expressions.
336 if (!ConstExpr->isCast())
337 continue;
338
339 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
340 // Pretend the constant is directly used by the instruction and ignore
341 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000342 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000343 continue;
344 }
345 }
346 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000347}
348
349/// \brief Collect all integer constants in the function that cannot be folded
350/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000351void ConstantHoisting::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000352 ConstCandMapType ConstCandMap;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000353 for (Function::iterator BB : Fn)
354 for (BasicBlock::iterator Inst : *BB)
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000355 collectConstantCandidates(ConstCandMap, Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000356}
357
358/// \brief Find the base constant within the given range and rebase all other
359/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000360void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000361 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000362 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000363 unsigned NumUses = 0;
364 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000365 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
366 NumUses += ConstCand->Uses.size();
367 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
368 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000369 }
370
371 // Don't hoist constants that have only one use.
372 if (NumUses <= 1)
373 return;
374
Juergen Ributzka5429c062014-03-21 06:04:36 +0000375 ConstantInfo ConstInfo;
376 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
377 Type *Ty = ConstInfo.BaseConstant->getType();
378
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000379 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000380 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
381 APInt Diff = ConstCand->ConstInt->getValue() -
382 ConstInfo.BaseConstant->getValue();
383 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
384 ConstInfo.RebasedConstants.push_back(
385 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000386 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000387 ConstantVec.push_back(ConstInfo);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000388}
389
Juergen Ributzka5429c062014-03-21 06:04:36 +0000390/// \brief Finds and combines constant candidates that can be easily
391/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000392void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000393 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000394 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
395 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
396 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
397 return LHS.ConstInt->getType()->getBitWidth() <
398 RHS.ConstInt->getType()->getBitWidth();
399 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000400 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000401
Juergen Ributzka5429c062014-03-21 06:04:36 +0000402 // Simple linear scan through the sorted constant candidate vector for viable
403 // merge candidates.
404 auto MinValItr = ConstCandVec.begin();
405 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
406 CC != E; ++CC) {
407 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000408 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000409 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000410 if ((Diff.getBitWidth() <= 64) &&
411 TTI->isLegalAddImmediate(Diff.getSExtValue()))
412 continue;
413 }
414 // We either have now a different constant type or the constant is not in
415 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000416 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000417 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000418 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000419 }
420 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000421 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000422}
423
Juergen Ributzkae802d502014-03-22 01:49:27 +0000424/// \brief Updates the operand at Idx in instruction Inst with the result of
425/// instruction Mat. If the instruction is a PHI node then special
426/// handling for duplicate values form the same incomming basic block is
427/// required.
428/// \return The update will always succeed, but the return value indicated if
429/// Mat was used for the update or not.
430static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
431 if (auto PHI = dyn_cast<PHINode>(Inst)) {
432 // Check if any previous operand of the PHI node has the same incoming basic
433 // block. This is a very odd case that happens when the incoming basic block
434 // has a switch statement. In this case use the same value as the previous
435 // operand(s), otherwise we will fail verification due to different values.
436 // The values are actually the same, but the variable names are different
437 // and the verifier doesn't like that.
438 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
439 for (unsigned i = 0; i < Idx; ++i) {
440 if (PHI->getIncomingBlock(i) == IncomingBB) {
441 Value *IncomingVal = PHI->getIncomingValue(i);
442 Inst->setOperand(Idx, IncomingVal);
443 return false;
444 }
445 }
446 }
447
448 Inst->setOperand(Idx, Mat);
449 return true;
450}
451
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000452/// \brief Emit materialization code for all rebased constants and update their
453/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000454void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
455 const ConstantUser &ConstUser) {
456 Instruction *Mat = Base;
457 if (Offset) {
458 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
459 ConstUser.OpndIdx);
460 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
461 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000462
Juergen Ributzka5429c062014-03-21 06:04:36 +0000463 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
464 << " + " << *Offset << ") in BB "
465 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
466 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
467 }
468 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000469
Juergen Ributzka5429c062014-03-21 06:04:36 +0000470 // Visit constant integer.
471 if (isa<ConstantInt>(Opnd)) {
472 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000473 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
474 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000475 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000476 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000477 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000478
Juergen Ributzka5429c062014-03-21 06:04:36 +0000479 // Visit cast instruction.
480 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
481 assert(CastInst->isCast() && "Expected an cast instruction!");
482 // Check if we already have visited this cast instruction before to avoid
483 // unnecessary cloning.
484 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
485 if (!ClonedCastInst) {
486 ClonedCastInst = CastInst->clone();
487 ClonedCastInst->setOperand(0, Mat);
488 ClonedCastInst->insertAfter(CastInst);
489 // Use the same debug location as the original cast instruction.
490 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
491 DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
492 << "To : " << *CastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000493 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000494
495 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000496 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000497 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
498 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000499 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000500
501 // Visit constant expression.
502 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
503 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
504 ConstExprInst->setOperand(0, Mat);
505 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
506 ConstUser.OpndIdx));
507
508 // Use the same debug location as the instruction we are about to update.
509 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
510
511 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
512 << "From : " << *ConstExpr << '\n');
513 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000514 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
515 ConstExprInst->eraseFromParent();
516 if (Offset)
517 Mat->eraseFromParent();
518 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000519 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
520 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000521 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000522}
523
524/// \brief Hoist and hide the base constant behind a bitcast and emit
525/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000526bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000527 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000528 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000529 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000530 Instruction *IP = findConstantInsertionPoint(ConstInfo);
531 IntegerType *Ty = ConstInfo.BaseConstant->getType();
532 Instruction *Base =
533 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
534 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
535 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000536 NumConstantsHoisted++;
537
538 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000539 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000540 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000541 for (auto const &U : RCI.Uses)
542 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000543 }
544
545 // Use the same debug location as the last user of the constant.
546 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000547 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000548 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000549 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000550
551 // Correct for base constant, which we counted above too.
552 NumConstantsRebased--;
553 MadeChange = true;
554 }
555 return MadeChange;
556}
557
Juergen Ributzka5429c062014-03-21 06:04:36 +0000558/// \brief Check all cast instructions we made a copy of and remove them if they
559/// have no more users.
560void ConstantHoisting::deleteDeadCastInst() const {
561 for (auto const &I : ClonedCastMap)
562 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000563 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000564}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000565
Juergen Ributzka5429c062014-03-21 06:04:36 +0000566/// \brief Optimize expensive integer constants in the given function.
567bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000568 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000569 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000570
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000571 // There are no constant candidates to worry about.
572 if (ConstCandVec.empty())
573 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000574
575 // Combine constants that can be easily materialized with an add from a common
576 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000577 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000578
Juergen Ributzka5429c062014-03-21 06:04:36 +0000579 // There are no constants to emit.
580 if (ConstantVec.empty())
581 return false;
582
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000583 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000584 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000585 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000586
Juergen Ributzka5429c062014-03-21 06:04:36 +0000587 // Cleanup dead instructions.
588 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000589
590 return MadeChange;
591}