blob: ee6333e88716b8920cdb94402b0c8d8d6958c03b [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
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000139 // This must be an EH pad. Iterate over immediate dominators until we find a
140 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
141 // and terminators.
142 auto IDom = DT->getNode(Inst->getParent())->getIDom();
143 while (IDom->getBlock()->isEHPad()) {
144 assert(Entry != IDom->getBlock() && "eh pad in entry block");
145 IDom = IDom->getIDom();
146 }
147
148 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000149}
150
151/// \brief Find an insertion point that dominates all uses.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000152Instruction *ConstantHoistingPass::findConstantInsertionPoint(
153 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000154 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000155 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000156 SmallPtrSet<BasicBlock *, 8> BBs;
157 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000158 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000159 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000160
161 if (BBs.count(Entry))
162 return &Entry->front();
163
164 while (BBs.size() >= 2) {
165 BasicBlock *BB, *BB1, *BB2;
166 BB1 = *BBs.begin();
167 BB2 = *std::next(BBs.begin());
168 BB = DT->findNearestCommonDominator(BB1, BB2);
169 if (BB == Entry)
170 return &Entry->front();
171 BBs.erase(BB1);
172 BBs.erase(BB2);
173 BBs.insert(BB);
174 }
175 assert((BBs.size() == 1) && "Expected only one element.");
176 Instruction &FirstInst = (*BBs.begin())->front();
177 return findMatInsertPt(&FirstInst);
178}
179
180
181/// \brief Record constant integer ConstInt for instruction Inst at operand
182/// index Idx.
183///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000184/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000185/// could also be a cast instruction or a constant expression that uses the
186// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000187void ConstantHoistingPass::collectConstantCandidates(
188 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
189 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000190 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000191 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000192 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000193 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000194 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000195 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000196 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000197 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000198 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000199
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000200 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000201 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000202 ConstCandMapType::iterator Itr;
203 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000204 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000205 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000206 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000207 Itr->second = ConstCandVec.size() - 1;
208 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000209 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
210 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
211 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
212 << " with cost " << Cost << '\n';
213 else
214 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
215 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
216 << Cost << '\n';
217 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000218 }
219}
220
Juergen Ributzka5429c062014-03-21 06:04:36 +0000221/// \brief Scan the instruction for expensive integer constants and record them
222/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000223void ConstantHoistingPass::collectConstantCandidates(
224 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000225 // Skip all cast instructions. They are visited indirectly later on.
226 if (Inst->isCast())
227 return;
228
229 // Can't handle inline asm. Skip it.
230 if (auto Call = dyn_cast<CallInst>(Inst))
231 if (isa<InlineAsm>(Call->getCalledValue()))
232 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000233
Tim Northover5c02f9a2016-04-13 23:08:27 +0000234 // Switch cases must remain constant, and if the value being tested is
235 // constant the entire thing should disappear.
236 if (isa<SwitchInst>(Inst))
237 return;
238
239 // Static allocas (constant size in the entry block) are handled by
240 // prologue/epilogue insertion so they're free anyway. We definitely don't
241 // want to make them non-constant.
242 auto AI = dyn_cast<AllocaInst>(Inst);
243 if (AI && AI->isStaticAlloca())
244 return;
245
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000246 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000247 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
248 Value *Opnd = Inst->getOperand(Idx);
249
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000250 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000251 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000252 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000253 continue;
254 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000255
256 // Visit cast instructions that have constant integers.
257 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
258 // Only visit cast instructions, which have been skipped. All other
259 // instructions should have already been visited.
260 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000261 continue;
262
Juergen Ributzka5429c062014-03-21 06:04:36 +0000263 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
264 // Pretend the constant is directly used by the instruction and ignore
265 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000266 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000267 continue;
268 }
269 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000270
271 // Visit constant expressions that have constant integers.
272 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
273 // Only visit constant cast expressions.
274 if (!ConstExpr->isCast())
275 continue;
276
277 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
278 // Pretend the constant is directly used by the instruction and ignore
279 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000280 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000281 continue;
282 }
283 }
284 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000285}
286
287/// \brief Collect all integer constants in the function that cannot be folded
288/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000289void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000290 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000291 for (BasicBlock &BB : Fn)
292 for (Instruction &Inst : BB)
293 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000294}
295
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000296// This helper function is necessary to deal with values that have different
297// bit widths (APInt Operator- does not like that). If the value cannot be
298// represented in uint64 we return an "empty" APInt. This is then interpreted
299// as the value is not in range.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000300static llvm::Optional<APInt> calculateOffsetDiff(const APInt &V1,
301 const APInt &V2) {
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000302 llvm::Optional<APInt> Res = None;
303 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
304 V1.getBitWidth() : V2.getBitWidth();
305 uint64_t LimVal1 = V1.getLimitedValue();
306 uint64_t LimVal2 = V2.getLimitedValue();
307
308 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
309 return Res;
310
311 uint64_t Diff = LimVal1 - LimVal2;
312 return APInt(BW, Diff, true);
313}
314
315// From a list of constants, one needs to picked as the base and the other
316// constants will be transformed into an offset from that base constant. The
317// question is which we can pick best? For example, consider these constants
318// and their number of uses:
319//
320// Constants| 2 | 4 | 12 | 42 |
321// NumUses | 3 | 2 | 8 | 7 |
322//
323// Selecting constant 12 because it has the most uses will generate negative
324// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
325// offsets lead to less optimal code generation, then there might be better
326// solutions. Suppose immediates in the range of 0..35 are most optimally
327// supported by the architecture, then selecting constant 2 is most optimal
328// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
329// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
330// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
331// selecting the base constant the range of the offsets is a very important
332// factor too that we take into account here. This algorithm calculates a total
333// costs for selecting a constant as the base and substract the costs if
334// immediates are out of range. It has quadratic complexity, so we call this
335// function only when we're optimising for size and there are less than 100
336// constants, we fall back to the straightforward algorithm otherwise
337// which does not do all the offset calculations.
338unsigned
339ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
340 ConstCandVecType::iterator E,
341 ConstCandVecType::iterator &MaxCostItr) {
342 unsigned NumUses = 0;
343
344 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
345 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
346 NumUses += ConstCand->Uses.size();
347 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
348 MaxCostItr = ConstCand;
349 }
350 return NumUses;
351 }
352
353 DEBUG(dbgs() << "== Maximize constants in range ==\n");
354 int MaxCost = -1;
355 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
356 auto Value = ConstCand->ConstInt->getValue();
357 Type *Ty = ConstCand->ConstInt->getType();
358 int Cost = 0;
359 NumUses += ConstCand->Uses.size();
360 DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
361
362 for (auto User : ConstCand->Uses) {
363 unsigned Opcode = User.Inst->getOpcode();
364 unsigned OpndIdx = User.OpndIdx;
365 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
366 DEBUG(dbgs() << "Cost: " << Cost << "\n");
367
368 for (auto C2 = S; C2 != E; ++C2) {
369 llvm::Optional<APInt> Diff = calculateOffsetDiff(
370 C2->ConstInt->getValue(),
371 ConstCand->ConstInt->getValue());
372 if (Diff) {
373 const int ImmCosts =
374 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
375 Cost -= ImmCosts;
376 DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
377 << "has penalty: " << ImmCosts << "\n"
378 << "Adjusted cost: " << Cost << "\n");
379 }
380 }
381 }
382 DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
383 if (Cost > MaxCost) {
384 MaxCost = Cost;
385 MaxCostItr = ConstCand;
386 DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
387 << "\n");
388 }
389 }
390 return NumUses;
391}
392
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000393/// \brief Find the base constant within the given range and rebase all other
394/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000395void ConstantHoistingPass::findAndMakeBaseConstant(
396 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000397 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000398 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000399
400 // Don't hoist constants that have only one use.
401 if (NumUses <= 1)
402 return;
403
Juergen Ributzka5429c062014-03-21 06:04:36 +0000404 ConstantInfo ConstInfo;
405 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
406 Type *Ty = ConstInfo.BaseConstant->getType();
407
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000408 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000409 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
410 APInt Diff = ConstCand->ConstInt->getValue() -
411 ConstInfo.BaseConstant->getValue();
412 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
413 ConstInfo.RebasedConstants.push_back(
414 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000415 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000416 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000417}
418
Juergen Ributzka5429c062014-03-21 06:04:36 +0000419/// \brief Finds and combines constant candidates that can be easily
420/// rematerialized with an add from a common base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000421void ConstantHoistingPass::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000422 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000423 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
424 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
425 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
426 return LHS.ConstInt->getType()->getBitWidth() <
427 RHS.ConstInt->getType()->getBitWidth();
428 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000429 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000430
Juergen Ributzka5429c062014-03-21 06:04:36 +0000431 // Simple linear scan through the sorted constant candidate vector for viable
432 // merge candidates.
433 auto MinValItr = ConstCandVec.begin();
434 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
435 CC != E; ++CC) {
436 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000437 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000438 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000439 if ((Diff.getBitWidth() <= 64) &&
440 TTI->isLegalAddImmediate(Diff.getSExtValue()))
441 continue;
442 }
443 // We either have now a different constant type or the constant is not in
444 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000445 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000446 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000447 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000448 }
449 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000450 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000451}
452
Juergen Ributzkae802d502014-03-22 01:49:27 +0000453/// \brief Updates the operand at Idx in instruction Inst with the result of
454/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000455/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000456/// required.
457/// \return The update will always succeed, but the return value indicated if
458/// Mat was used for the update or not.
459static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
460 if (auto PHI = dyn_cast<PHINode>(Inst)) {
461 // Check if any previous operand of the PHI node has the same incoming basic
462 // block. This is a very odd case that happens when the incoming basic block
463 // has a switch statement. In this case use the same value as the previous
464 // operand(s), otherwise we will fail verification due to different values.
465 // The values are actually the same, but the variable names are different
466 // and the verifier doesn't like that.
467 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
468 for (unsigned i = 0; i < Idx; ++i) {
469 if (PHI->getIncomingBlock(i) == IncomingBB) {
470 Value *IncomingVal = PHI->getIncomingValue(i);
471 Inst->setOperand(Idx, IncomingVal);
472 return false;
473 }
474 }
475 }
476
477 Inst->setOperand(Idx, Mat);
478 return true;
479}
480
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000481/// \brief Emit materialization code for all rebased constants and update their
482/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000483void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
484 Constant *Offset,
485 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000486 Instruction *Mat = Base;
487 if (Offset) {
488 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
489 ConstUser.OpndIdx);
490 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
491 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000492
Juergen Ributzka5429c062014-03-21 06:04:36 +0000493 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
494 << " + " << *Offset << ") in BB "
495 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
496 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
497 }
498 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000499
Juergen Ributzka5429c062014-03-21 06:04:36 +0000500 // Visit constant integer.
501 if (isa<ConstantInt>(Opnd)) {
502 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000503 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
504 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000505 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000506 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000507 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000508
Juergen Ributzka5429c062014-03-21 06:04:36 +0000509 // Visit cast instruction.
510 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
511 assert(CastInst->isCast() && "Expected an cast instruction!");
512 // Check if we already have visited this cast instruction before to avoid
513 // unnecessary cloning.
514 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
515 if (!ClonedCastInst) {
516 ClonedCastInst = CastInst->clone();
517 ClonedCastInst->setOperand(0, Mat);
518 ClonedCastInst->insertAfter(CastInst);
519 // Use the same debug location as the original cast instruction.
520 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000521 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
522 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000523 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000524
525 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000526 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000527 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
528 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000529 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000530
531 // Visit constant expression.
532 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
533 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
534 ConstExprInst->setOperand(0, Mat);
535 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
536 ConstUser.OpndIdx));
537
538 // Use the same debug location as the instruction we are about to update.
539 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
540
541 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
542 << "From : " << *ConstExpr << '\n');
543 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000544 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
545 ConstExprInst->eraseFromParent();
546 if (Offset)
547 Mat->eraseFromParent();
548 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000549 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
550 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000551 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000552}
553
554/// \brief Hoist and hide the base constant behind a bitcast and emit
555/// materialization code for derived constants.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000556bool ConstantHoistingPass::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000557 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000558 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000559 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000560 Instruction *IP = findConstantInsertionPoint(ConstInfo);
561 IntegerType *Ty = ConstInfo.BaseConstant->getType();
562 Instruction *Base =
563 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
564 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
565 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000566 NumConstantsHoisted++;
567
568 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000569 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000570 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000571 for (auto const &U : RCI.Uses)
572 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000573 }
574
575 // Use the same debug location as the last user of the constant.
576 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000577 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000578 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000579 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000580
581 // Correct for base constant, which we counted above too.
582 NumConstantsRebased--;
583 MadeChange = true;
584 }
585 return MadeChange;
586}
587
Juergen Ributzka5429c062014-03-21 06:04:36 +0000588/// \brief Check all cast instructions we made a copy of and remove them if they
589/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000590void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000591 for (auto const &I : ClonedCastMap)
592 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000593 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000594}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000595
Juergen Ributzka5429c062014-03-21 06:04:36 +0000596/// \brief Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000597bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
598 DominatorTree &DT, BasicBlock &Entry) {
599 this->TTI = &TTI;
600 this->DT = &DT;
601 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000602 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000603 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000604
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000605 // There are no constant candidates to worry about.
606 if (ConstCandVec.empty())
607 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000608
609 // Combine constants that can be easily materialized with an add from a common
610 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000611 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000612
Juergen Ributzka5429c062014-03-21 06:04:36 +0000613 // There are no constants to emit.
614 if (ConstantVec.empty())
615 return false;
616
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000617 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000618 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000619 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000620
Juergen Ributzka5429c062014-03-21 06:04:36 +0000621 // Cleanup dead instructions.
622 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000623
624 return MadeChange;
625}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000626
627PreservedAnalyses ConstantHoistingPass::run(Function &F,
628 FunctionAnalysisManager &AM) {
629 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
630 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
631 if (!runImpl(F, TTI, DT, F.getEntryBlock()))
632 return PreservedAnalyses::all();
633
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000634 PreservedAnalyses PA;
635 PA.preserveSet<CFGAnalyses>();
636 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000637}