blob: 7c3a260947727d0f5242a5dcfb3135409c7bba33 [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
Craig Topperf40110f2014-04-25 05:29:35 +0000121 ConstantHoisting() : FunctionPass(ID), TTI(nullptr), DT(nullptr),
122 Entry(nullptr) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000123 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
124 }
125
Juergen Ributzka5429c062014-03-21 06:04:36 +0000126 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000127
Craig Topper3e4c6972014-03-05 09:10:37 +0000128 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000129
Craig Topper3e4c6972014-03-05 09:10:37 +0000130 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000131 AU.setPreservesCFG();
132 AU.addRequired<DominatorTreeWrapperPass>();
133 AU.addRequired<TargetTransformInfo>();
134 }
135
136private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000137 /// \brief Initialize the pass.
138 void setup(Function &Fn) {
139 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
140 TTI = &getAnalysis<TargetTransformInfo>();
141 Entry = &Fn.getEntryBlock();
142 }
143
144 /// \brief Cleanup.
145 void cleanup() {
146 ConstantVec.clear();
147 ClonedCastMap.clear();
148 ConstCandVec.clear();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000149
150 TTI = nullptr;
151 DT = nullptr;
152 Entry = nullptr;
153 }
154
155 Instruction *findMatInsertPt(Instruction *Inst, unsigned Idx = ~0U) const;
156 Instruction *findConstantInsertionPoint(const ConstantInfo &ConstInfo) const;
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000157 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
158 Instruction *Inst, unsigned Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000159 ConstantInt *ConstInt);
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000160 void collectConstantCandidates(ConstCandMapType &ConstCandMap,
161 Instruction *Inst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000162 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000163 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000164 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000165 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000166 void emitBaseConstants(Instruction *Base, Constant *Offset,
167 const ConstantUser &ConstUser);
168 bool emitBaseConstants();
169 void deleteDeadCastInst() const;
170 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000171};
172}
173
174char ConstantHoisting::ID = 0;
175INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
176 false, false)
177INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
178INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
179INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
180 false, false)
181
182FunctionPass *llvm::createConstantHoistingPass() {
183 return new ConstantHoisting();
184}
185
186/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000187bool ConstantHoisting::runOnFunction(Function &Fn) {
188 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
189 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000190
Juergen Ributzka5429c062014-03-21 06:04:36 +0000191 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000192
Juergen Ributzka5429c062014-03-21 06:04:36 +0000193 bool MadeChange = optimizeConstants(Fn);
194
195 if (MadeChange) {
196 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
197 << Fn.getName() << '\n');
198 DEBUG(dbgs() << Fn);
199 }
200 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
201
202 cleanup();
203
204 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000205}
206
Juergen Ributzka5429c062014-03-21 06:04:36 +0000207
208/// \brief Find the constant materialization insertion point.
209Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
210 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000211 // If the operand is a cast instruction, then we have to materialize the
212 // constant before the cast instruction.
213 if (Idx != ~0U) {
214 Value *Opnd = Inst->getOperand(Idx);
215 if (auto CastInst = dyn_cast<Instruction>(Opnd))
216 if (CastInst->isCast())
217 return CastInst;
218 }
219
220 // The simple and common case. This also includes constant expressions.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000221 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
222 return Inst;
223
224 // We can't insert directly before a phi node or landing pad. Insert before
225 // the terminator of the incoming or dominating block.
226 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
227 if (Idx != ~0U && isa<PHINode>(Inst))
228 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
229
230 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
231 return IDom->getTerminator();
232}
233
234/// \brief Find an insertion point that dominates all uses.
235Instruction *ConstantHoisting::
236findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
237 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000238 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000239 SmallPtrSet<BasicBlock *, 8> BBs;
240 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000241 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000242 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000243
244 if (BBs.count(Entry))
245 return &Entry->front();
246
247 while (BBs.size() >= 2) {
248 BasicBlock *BB, *BB1, *BB2;
249 BB1 = *BBs.begin();
250 BB2 = *std::next(BBs.begin());
251 BB = DT->findNearestCommonDominator(BB1, BB2);
252 if (BB == Entry)
253 return &Entry->front();
254 BBs.erase(BB1);
255 BBs.erase(BB2);
256 BBs.insert(BB);
257 }
258 assert((BBs.size() == 1) && "Expected only one element.");
259 Instruction &FirstInst = (*BBs.begin())->front();
260 return findMatInsertPt(&FirstInst);
261}
262
263
264/// \brief Record constant integer ConstInt for instruction Inst at operand
265/// index Idx.
266///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000267/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000268/// could also be a cast instruction or a constant expression that uses the
269// constant integer.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000270void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
271 Instruction *Inst,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000272 unsigned Idx,
273 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000274 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000275 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000276 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000277 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000278 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000279 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000280 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000281 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000282 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000283
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000284 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000285 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000286 ConstCandMapType::iterator Itr;
287 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000288 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000289 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000290 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000291 Itr->second = ConstCandVec.size() - 1;
292 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000293 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
294 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
295 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
296 << " with cost " << Cost << '\n';
297 else
298 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
299 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
300 << Cost << '\n';
301 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000302 }
303}
304
Juergen Ributzka5429c062014-03-21 06:04:36 +0000305/// \brief Scan the instruction for expensive integer constants and record them
306/// in the constant candidate vector.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000307void ConstantHoisting::collectConstantCandidates(ConstCandMapType &ConstCandMap,
308 Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000309 // Skip all cast instructions. They are visited indirectly later on.
310 if (Inst->isCast())
311 return;
312
313 // Can't handle inline asm. Skip it.
314 if (auto Call = dyn_cast<CallInst>(Inst))
315 if (isa<InlineAsm>(Call->getCalledValue()))
316 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000317
318 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000319 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
320 Value *Opnd = Inst->getOperand(Idx);
321
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000322 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000323 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000324 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000325 continue;
326 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000327
328 // Visit cast instructions that have constant integers.
329 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
330 // Only visit cast instructions, which have been skipped. All other
331 // instructions should have already been visited.
332 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000333 continue;
334
Juergen Ributzka5429c062014-03-21 06:04:36 +0000335 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
336 // Pretend the constant is directly used by the instruction and ignore
337 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000338 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000339 continue;
340 }
341 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000342
343 // Visit constant expressions that have constant integers.
344 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
345 // Only visit constant cast expressions.
346 if (!ConstExpr->isCast())
347 continue;
348
349 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
350 // Pretend the constant is directly used by the instruction and ignore
351 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000352 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000353 continue;
354 }
355 }
356 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000357}
358
359/// \brief Collect all integer constants in the function that cannot be folded
360/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000361void ConstantHoisting::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000362 ConstCandMapType ConstCandMap;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000363 for (Function::iterator BB : Fn)
364 for (BasicBlock::iterator Inst : *BB)
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000365 collectConstantCandidates(ConstCandMap, Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000366}
367
368/// \brief Find the base constant within the given range and rebase all other
369/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000370void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000371 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000372 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000373 unsigned NumUses = 0;
374 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000375 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
376 NumUses += ConstCand->Uses.size();
377 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
378 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000379 }
380
381 // Don't hoist constants that have only one use.
382 if (NumUses <= 1)
383 return;
384
Juergen Ributzka5429c062014-03-21 06:04:36 +0000385 ConstantInfo ConstInfo;
386 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
387 Type *Ty = ConstInfo.BaseConstant->getType();
388
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000389 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000390 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
391 APInt Diff = ConstCand->ConstInt->getValue() -
392 ConstInfo.BaseConstant->getValue();
393 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
394 ConstInfo.RebasedConstants.push_back(
395 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000396 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000397 ConstantVec.push_back(ConstInfo);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000398}
399
Juergen Ributzka5429c062014-03-21 06:04:36 +0000400/// \brief Finds and combines constant candidates that can be easily
401/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000402void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000403 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000404 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
405 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
406 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
407 return LHS.ConstInt->getType()->getBitWidth() <
408 RHS.ConstInt->getType()->getBitWidth();
409 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000410 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000411
Juergen Ributzka5429c062014-03-21 06:04:36 +0000412 // Simple linear scan through the sorted constant candidate vector for viable
413 // merge candidates.
414 auto MinValItr = ConstCandVec.begin();
415 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
416 CC != E; ++CC) {
417 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000418 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000419 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000420 if ((Diff.getBitWidth() <= 64) &&
421 TTI->isLegalAddImmediate(Diff.getSExtValue()))
422 continue;
423 }
424 // We either have now a different constant type or the constant is not in
425 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000426 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000427 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000428 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000429 }
430 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000431 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000432}
433
Juergen Ributzkae802d502014-03-22 01:49:27 +0000434/// \brief Updates the operand at Idx in instruction Inst with the result of
435/// instruction Mat. If the instruction is a PHI node then special
436/// handling for duplicate values form the same incomming basic block is
437/// required.
438/// \return The update will always succeed, but the return value indicated if
439/// Mat was used for the update or not.
440static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
441 if (auto PHI = dyn_cast<PHINode>(Inst)) {
442 // Check if any previous operand of the PHI node has the same incoming basic
443 // block. This is a very odd case that happens when the incoming basic block
444 // has a switch statement. In this case use the same value as the previous
445 // operand(s), otherwise we will fail verification due to different values.
446 // The values are actually the same, but the variable names are different
447 // and the verifier doesn't like that.
448 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
449 for (unsigned i = 0; i < Idx; ++i) {
450 if (PHI->getIncomingBlock(i) == IncomingBB) {
451 Value *IncomingVal = PHI->getIncomingValue(i);
452 Inst->setOperand(Idx, IncomingVal);
453 return false;
454 }
455 }
456 }
457
458 Inst->setOperand(Idx, Mat);
459 return true;
460}
461
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000462/// \brief Emit materialization code for all rebased constants and update their
463/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000464void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
465 const ConstantUser &ConstUser) {
466 Instruction *Mat = Base;
467 if (Offset) {
468 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
469 ConstUser.OpndIdx);
470 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
471 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000472
Juergen Ributzka5429c062014-03-21 06:04:36 +0000473 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
474 << " + " << *Offset << ") in BB "
475 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
476 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
477 }
478 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000479
Juergen Ributzka5429c062014-03-21 06:04:36 +0000480 // Visit constant integer.
481 if (isa<ConstantInt>(Opnd)) {
482 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000483 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
484 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000485 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000486 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000487 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000488
Juergen Ributzka5429c062014-03-21 06:04:36 +0000489 // Visit cast instruction.
490 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
491 assert(CastInst->isCast() && "Expected an cast instruction!");
492 // Check if we already have visited this cast instruction before to avoid
493 // unnecessary cloning.
494 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
495 if (!ClonedCastInst) {
496 ClonedCastInst = CastInst->clone();
497 ClonedCastInst->setOperand(0, Mat);
498 ClonedCastInst->insertAfter(CastInst);
499 // Use the same debug location as the original cast instruction.
500 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000501 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
502 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000503 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000504
505 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000506 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000507 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
508 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000509 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000510
511 // Visit constant expression.
512 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
513 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
514 ConstExprInst->setOperand(0, Mat);
515 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
516 ConstUser.OpndIdx));
517
518 // Use the same debug location as the instruction we are about to update.
519 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
520
521 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
522 << "From : " << *ConstExpr << '\n');
523 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000524 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
525 ConstExprInst->eraseFromParent();
526 if (Offset)
527 Mat->eraseFromParent();
528 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000529 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
530 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000531 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000532}
533
534/// \brief Hoist and hide the base constant behind a bitcast and emit
535/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000536bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000537 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000538 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000539 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000540 Instruction *IP = findConstantInsertionPoint(ConstInfo);
541 IntegerType *Ty = ConstInfo.BaseConstant->getType();
542 Instruction *Base =
543 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
544 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
545 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000546 NumConstantsHoisted++;
547
548 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000549 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000550 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000551 for (auto const &U : RCI.Uses)
552 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000553 }
554
555 // Use the same debug location as the last user of the constant.
556 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000557 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000558 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000559 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000560
561 // Correct for base constant, which we counted above too.
562 NumConstantsRebased--;
563 MadeChange = true;
564 }
565 return MadeChange;
566}
567
Juergen Ributzka5429c062014-03-21 06:04:36 +0000568/// \brief Check all cast instructions we made a copy of and remove them if they
569/// have no more users.
570void ConstantHoisting::deleteDeadCastInst() const {
571 for (auto const &I : ClonedCastMap)
572 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000573 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000574}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000575
Juergen Ributzka5429c062014-03-21 06:04:36 +0000576/// \brief Optimize expensive integer constants in the given function.
577bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000578 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000579 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000580
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000581 // There are no constant candidates to worry about.
582 if (ConstCandVec.empty())
583 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000584
585 // Combine constants that can be easily materialized with an add from a common
586 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000587 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000588
Juergen Ributzka5429c062014-03-21 06:04:36 +0000589 // There are no constants to emit.
590 if (ConstantVec.empty())
591 return false;
592
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000593 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000594 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000595 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000596
Juergen Ributzka5429c062014-03-21 06:04:36 +0000597 // Cleanup dead instructions.
598 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000599
600 return MadeChange;
601}