blob: ebe35aac0986197727d462db6027472ab387e5f1 [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
Michael Kuperstein071d8302016-07-02 00:16:47 +000036#include "llvm/Transforms/Scalar/ConstantHoisting.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"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000040#include "llvm/IR/Constants.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000041#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/Pass.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Support/raw_ostream.h"
Michael Kuperstein071d8302016-07-02 00:16:47 +000045#include "llvm/Transforms/Scalar.h"
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000046#include <tuple>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000047
48using namespace llvm;
Michael Kuperstein071d8302016-07-02 00:16:47 +000049using namespace consthoist;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000050
Chandler Carruth964daaa2014-04-22 02:55:47 +000051#define DEBUG_TYPE "consthoist"
52
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000053STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
54STATISTIC(NumConstantsRebased, "Number of constants rebased");
55
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000056namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000057/// \brief The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000058class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000059public:
60 static char ID; // Pass identification, replacement for typeid
Michael Kuperstein071d8302016-07-02 00:16:47 +000061 ConstantHoistingLegacyPass() : FunctionPass(ID) {
62 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000063 }
64
Juergen Ributzka5429c062014-03-21 06:04:36 +000065 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000066
Mehdi Amini117296c2016-10-01 02:56:57 +000067 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000068
Craig Topper3e4c6972014-03-05 09:10:37 +000069 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000070 AU.setPreservesCFG();
71 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +000072 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000073 }
74
Michael Kuperstein071d8302016-07-02 00:16:47 +000075 void releaseMemory() override { Impl.releaseMemory(); }
76
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000077private:
Michael Kuperstein071d8302016-07-02 00:16:47 +000078 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000079};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000080}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000081
Michael Kuperstein071d8302016-07-02 00:16:47 +000082char ConstantHoistingLegacyPass::ID = 0;
83INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
84 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000085INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +000086INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +000087INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
88 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000089
90FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +000091 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000092}
93
94/// \brief Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +000095bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +000096 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +000097 return false;
98
Juergen Ributzka5429c062014-03-21 06:04:36 +000099 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
100 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000101
Michael Kuperstein071d8302016-07-02 00:16:47 +0000102 bool MadeChange = Impl.runImpl(
103 Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
104 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000105
106 if (MadeChange) {
107 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
108 << Fn.getName() << '\n');
109 DEBUG(dbgs() << Fn);
110 }
111 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
112
Juergen Ributzka5429c062014-03-21 06:04:36 +0000113 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000114}
115
Juergen Ributzka5429c062014-03-21 06:04:36 +0000116
117/// \brief Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000118Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
119 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000120 // If the operand is a cast instruction, then we have to materialize the
121 // constant before the cast instruction.
122 if (Idx != ~0U) {
123 Value *Opnd = Inst->getOperand(Idx);
124 if (auto CastInst = dyn_cast<Instruction>(Opnd))
125 if (CastInst->isCast())
126 return CastInst;
127 }
128
129 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000130 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000131 return Inst;
132
David Majnemerba275f92015-08-19 19:54:02 +0000133 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000134 // the terminator of the incoming or dominating block.
135 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
136 if (Idx != ~0U && isa<PHINode>(Inst))
137 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
138
139 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
140 return IDom->getTerminator();
141}
142
143/// \brief Find an insertion point that dominates all uses.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000144Instruction *ConstantHoistingPass::findConstantInsertionPoint(
145 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000146 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000147 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000148 SmallPtrSet<BasicBlock *, 8> BBs;
149 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000150 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000151 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000152
153 if (BBs.count(Entry))
154 return &Entry->front();
155
156 while (BBs.size() >= 2) {
157 BasicBlock *BB, *BB1, *BB2;
158 BB1 = *BBs.begin();
159 BB2 = *std::next(BBs.begin());
160 BB = DT->findNearestCommonDominator(BB1, BB2);
161 if (BB == Entry)
162 return &Entry->front();
163 BBs.erase(BB1);
164 BBs.erase(BB2);
165 BBs.insert(BB);
166 }
167 assert((BBs.size() == 1) && "Expected only one element.");
168 Instruction &FirstInst = (*BBs.begin())->front();
169 return findMatInsertPt(&FirstInst);
170}
171
172
173/// \brief Record constant integer ConstInt for instruction Inst at operand
174/// index Idx.
175///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000176/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000177/// could also be a cast instruction or a constant expression that uses the
178// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000179void ConstantHoistingPass::collectConstantCandidates(
180 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
181 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000182 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000183 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000184 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000185 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000186 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000187 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000188 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000189 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000190 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000191
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000192 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000193 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000194 ConstCandMapType::iterator Itr;
195 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000196 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000197 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000198 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000199 Itr->second = ConstCandVec.size() - 1;
200 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000201 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
202 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
203 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
204 << " with cost " << Cost << '\n';
205 else
206 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
207 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
208 << Cost << '\n';
209 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000210 }
211}
212
Juergen Ributzka5429c062014-03-21 06:04:36 +0000213/// \brief Scan the instruction for expensive integer constants and record them
214/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000215void ConstantHoistingPass::collectConstantCandidates(
216 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000217 // Skip all cast instructions. They are visited indirectly later on.
218 if (Inst->isCast())
219 return;
220
221 // Can't handle inline asm. Skip it.
222 if (auto Call = dyn_cast<CallInst>(Inst))
223 if (isa<InlineAsm>(Call->getCalledValue()))
224 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000225
Tim Northover5c02f9a2016-04-13 23:08:27 +0000226 // Switch cases must remain constant, and if the value being tested is
227 // constant the entire thing should disappear.
228 if (isa<SwitchInst>(Inst))
229 return;
230
231 // Static allocas (constant size in the entry block) are handled by
232 // prologue/epilogue insertion so they're free anyway. We definitely don't
233 // want to make them non-constant.
234 auto AI = dyn_cast<AllocaInst>(Inst);
235 if (AI && AI->isStaticAlloca())
236 return;
237
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000238 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000239 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
240 Value *Opnd = Inst->getOperand(Idx);
241
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000242 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000243 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000244 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000245 continue;
246 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000247
248 // Visit cast instructions that have constant integers.
249 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
250 // Only visit cast instructions, which have been skipped. All other
251 // instructions should have already been visited.
252 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000253 continue;
254
Juergen Ributzka5429c062014-03-21 06:04:36 +0000255 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
256 // Pretend the constant is directly used by the instruction and ignore
257 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000258 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000259 continue;
260 }
261 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000262
263 // Visit constant expressions that have constant integers.
264 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
265 // Only visit constant cast expressions.
266 if (!ConstExpr->isCast())
267 continue;
268
269 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
270 // Pretend the constant is directly used by the instruction and ignore
271 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000272 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000273 continue;
274 }
275 }
276 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000277}
278
279/// \brief Collect all integer constants in the function that cannot be folded
280/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000281void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000282 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000283 for (BasicBlock &BB : Fn)
284 for (Instruction &Inst : BB)
285 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000286}
287
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000288// This helper function is necessary to deal with values that have different
289// bit widths (APInt Operator- does not like that). If the value cannot be
290// represented in uint64 we return an "empty" APInt. This is then interpreted
291// as the value is not in range.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000292static llvm::Optional<APInt> calculateOffsetDiff(const APInt &V1,
293 const APInt &V2) {
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000294 llvm::Optional<APInt> Res = None;
295 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
296 V1.getBitWidth() : V2.getBitWidth();
297 uint64_t LimVal1 = V1.getLimitedValue();
298 uint64_t LimVal2 = V2.getLimitedValue();
299
300 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
301 return Res;
302
303 uint64_t Diff = LimVal1 - LimVal2;
304 return APInt(BW, Diff, true);
305}
306
307// From a list of constants, one needs to picked as the base and the other
308// constants will be transformed into an offset from that base constant. The
309// question is which we can pick best? For example, consider these constants
310// and their number of uses:
311//
312// Constants| 2 | 4 | 12 | 42 |
313// NumUses | 3 | 2 | 8 | 7 |
314//
315// Selecting constant 12 because it has the most uses will generate negative
316// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
317// offsets lead to less optimal code generation, then there might be better
318// solutions. Suppose immediates in the range of 0..35 are most optimally
319// supported by the architecture, then selecting constant 2 is most optimal
320// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
321// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
322// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
323// selecting the base constant the range of the offsets is a very important
324// factor too that we take into account here. This algorithm calculates a total
325// costs for selecting a constant as the base and substract the costs if
326// immediates are out of range. It has quadratic complexity, so we call this
327// function only when we're optimising for size and there are less than 100
328// constants, we fall back to the straightforward algorithm otherwise
329// which does not do all the offset calculations.
330unsigned
331ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
332 ConstCandVecType::iterator E,
333 ConstCandVecType::iterator &MaxCostItr) {
334 unsigned NumUses = 0;
335
336 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
337 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
338 NumUses += ConstCand->Uses.size();
339 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
340 MaxCostItr = ConstCand;
341 }
342 return NumUses;
343 }
344
345 DEBUG(dbgs() << "== Maximize constants in range ==\n");
346 int MaxCost = -1;
347 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
348 auto Value = ConstCand->ConstInt->getValue();
349 Type *Ty = ConstCand->ConstInt->getType();
350 int Cost = 0;
351 NumUses += ConstCand->Uses.size();
352 DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
353
354 for (auto User : ConstCand->Uses) {
355 unsigned Opcode = User.Inst->getOpcode();
356 unsigned OpndIdx = User.OpndIdx;
357 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
358 DEBUG(dbgs() << "Cost: " << Cost << "\n");
359
360 for (auto C2 = S; C2 != E; ++C2) {
361 llvm::Optional<APInt> Diff = calculateOffsetDiff(
362 C2->ConstInt->getValue(),
363 ConstCand->ConstInt->getValue());
364 if (Diff) {
365 const int ImmCosts =
366 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
367 Cost -= ImmCosts;
368 DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
369 << "has penalty: " << ImmCosts << "\n"
370 << "Adjusted cost: " << Cost << "\n");
371 }
372 }
373 }
374 DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
375 if (Cost > MaxCost) {
376 MaxCost = Cost;
377 MaxCostItr = ConstCand;
378 DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
379 << "\n");
380 }
381 }
382 return NumUses;
383}
384
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000385/// \brief Find the base constant within the given range and rebase all other
386/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000387void ConstantHoistingPass::findAndMakeBaseConstant(
388 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000389 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000390 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000391
392 // Don't hoist constants that have only one use.
393 if (NumUses <= 1)
394 return;
395
Juergen Ributzka5429c062014-03-21 06:04:36 +0000396 ConstantInfo ConstInfo;
397 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
398 Type *Ty = ConstInfo.BaseConstant->getType();
399
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000400 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000401 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
402 APInt Diff = ConstCand->ConstInt->getValue() -
403 ConstInfo.BaseConstant->getValue();
404 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
405 ConstInfo.RebasedConstants.push_back(
406 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000407 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000408 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000409}
410
Juergen Ributzka5429c062014-03-21 06:04:36 +0000411/// \brief Finds and combines constant candidates that can be easily
412/// rematerialized with an add from a common base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000413void ConstantHoistingPass::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000414 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000415 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
416 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
417 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
418 return LHS.ConstInt->getType()->getBitWidth() <
419 RHS.ConstInt->getType()->getBitWidth();
420 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000421 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000422
Juergen Ributzka5429c062014-03-21 06:04:36 +0000423 // Simple linear scan through the sorted constant candidate vector for viable
424 // merge candidates.
425 auto MinValItr = ConstCandVec.begin();
426 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
427 CC != E; ++CC) {
428 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000429 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000430 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000431 if ((Diff.getBitWidth() <= 64) &&
432 TTI->isLegalAddImmediate(Diff.getSExtValue()))
433 continue;
434 }
435 // We either have now a different constant type or the constant is not in
436 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000437 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000438 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000439 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000440 }
441 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000442 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000443}
444
Juergen Ributzkae802d502014-03-22 01:49:27 +0000445/// \brief Updates the operand at Idx in instruction Inst with the result of
446/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000447/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000448/// required.
449/// \return The update will always succeed, but the return value indicated if
450/// Mat was used for the update or not.
451static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
452 if (auto PHI = dyn_cast<PHINode>(Inst)) {
453 // Check if any previous operand of the PHI node has the same incoming basic
454 // block. This is a very odd case that happens when the incoming basic block
455 // has a switch statement. In this case use the same value as the previous
456 // operand(s), otherwise we will fail verification due to different values.
457 // The values are actually the same, but the variable names are different
458 // and the verifier doesn't like that.
459 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
460 for (unsigned i = 0; i < Idx; ++i) {
461 if (PHI->getIncomingBlock(i) == IncomingBB) {
462 Value *IncomingVal = PHI->getIncomingValue(i);
463 Inst->setOperand(Idx, IncomingVal);
464 return false;
465 }
466 }
467 }
468
469 Inst->setOperand(Idx, Mat);
470 return true;
471}
472
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000473/// \brief Emit materialization code for all rebased constants and update their
474/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000475void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
476 Constant *Offset,
477 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000478 Instruction *Mat = Base;
479 if (Offset) {
480 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
481 ConstUser.OpndIdx);
482 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
483 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000484
Juergen Ributzka5429c062014-03-21 06:04:36 +0000485 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
486 << " + " << *Offset << ") in BB "
487 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
488 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
489 }
490 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000491
Juergen Ributzka5429c062014-03-21 06:04:36 +0000492 // Visit constant integer.
493 if (isa<ConstantInt>(Opnd)) {
494 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000495 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
496 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000497 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000498 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000499 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000500
Juergen Ributzka5429c062014-03-21 06:04:36 +0000501 // Visit cast instruction.
502 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
503 assert(CastInst->isCast() && "Expected an cast instruction!");
504 // Check if we already have visited this cast instruction before to avoid
505 // unnecessary cloning.
506 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
507 if (!ClonedCastInst) {
508 ClonedCastInst = CastInst->clone();
509 ClonedCastInst->setOperand(0, Mat);
510 ClonedCastInst->insertAfter(CastInst);
511 // Use the same debug location as the original cast instruction.
512 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000513 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
514 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000515 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000516
517 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000518 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000519 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
520 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000521 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000522
523 // Visit constant expression.
524 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
525 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
526 ConstExprInst->setOperand(0, Mat);
527 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
528 ConstUser.OpndIdx));
529
530 // Use the same debug location as the instruction we are about to update.
531 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
532
533 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
534 << "From : " << *ConstExpr << '\n');
535 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000536 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
537 ConstExprInst->eraseFromParent();
538 if (Offset)
539 Mat->eraseFromParent();
540 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000541 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
542 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000543 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000544}
545
546/// \brief Hoist and hide the base constant behind a bitcast and emit
547/// materialization code for derived constants.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000548bool ConstantHoistingPass::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000549 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000550 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000551 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000552 Instruction *IP = findConstantInsertionPoint(ConstInfo);
553 IntegerType *Ty = ConstInfo.BaseConstant->getType();
554 Instruction *Base =
555 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
556 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
557 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000558 NumConstantsHoisted++;
559
560 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000561 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000562 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000563 for (auto const &U : RCI.Uses)
564 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000565 }
566
567 // Use the same debug location as the last user of the constant.
568 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000569 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000570 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000571 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000572
573 // Correct for base constant, which we counted above too.
574 NumConstantsRebased--;
575 MadeChange = true;
576 }
577 return MadeChange;
578}
579
Juergen Ributzka5429c062014-03-21 06:04:36 +0000580/// \brief Check all cast instructions we made a copy of and remove them if they
581/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000582void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000583 for (auto const &I : ClonedCastMap)
584 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000585 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000586}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000587
Juergen Ributzka5429c062014-03-21 06:04:36 +0000588/// \brief Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000589bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
590 DominatorTree &DT, BasicBlock &Entry) {
591 this->TTI = &TTI;
592 this->DT = &DT;
593 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000594 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000595 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000596
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000597 // There are no constant candidates to worry about.
598 if (ConstCandVec.empty())
599 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000600
601 // Combine constants that can be easily materialized with an add from a common
602 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000603 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000604
Juergen Ributzka5429c062014-03-21 06:04:36 +0000605 // There are no constants to emit.
606 if (ConstantVec.empty())
607 return false;
608
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000609 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000610 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000611 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000612
Juergen Ributzka5429c062014-03-21 06:04:36 +0000613 // Cleanup dead instructions.
614 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000615
616 return MadeChange;
617}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000618
619PreservedAnalyses ConstantHoistingPass::run(Function &F,
620 FunctionAnalysisManager &AM) {
621 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
622 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
623 if (!runImpl(F, TTI, DT, F.getEntryBlock()))
624 return PreservedAnalyses::all();
625
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000626 PreservedAnalyses PA;
627 PA.preserveSet<CFGAnalyses>();
628 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000629}