blob: 25fef5f500ff9d168eb4de86048744e8d247a897 [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
32// simple (this means not nested) constant cast experessions. For example:
33// %0 = load i64* inttoptr (i64 big_constant to i64*)
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "consthoist"
37#include "llvm/Transforms/Scalar.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000038#include "llvm/ADT/SmallSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000039#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/Analysis/TargetTransformInfo.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/Dominators.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/Pass.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000046#include "llvm/Support/Debug.h"
47
48using namespace llvm;
49
50STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
51STATISTIC(NumConstantsRebased, "Number of constants rebased");
52
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000053namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000054struct ConstantUser;
55struct RebasedConstantInfo;
56
57typedef SmallVector<ConstantUser, 8> ConstantUseListType;
58typedef SmallVector<RebasedConstantInfo, 4> RebasedConstantListType;
59
60/// \brief Keeps track of the user of a constant and the operand index where the
61/// constant is used.
62struct ConstantUser {
63 Instruction *Inst;
64 unsigned OpndIdx;
65
66 ConstantUser(Instruction *Inst, unsigned Idx) : Inst(Inst), OpndIdx(Idx) { }
67};
68
69/// \brief Keeps track of a constant candidate and its usees.
Juergen Ributzka6dab5202014-03-20 19:55:52 +000070struct ConstantCandidate {
Juergen Ributzka6dab5202014-03-20 19:55:52 +000071 ConstantUseListType Uses;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000072 ConstantInt *ConstInt;
73 unsigned CumulativeCost;
74
75 ConstantCandidate(ConstantInt *ConstInt)
76 : ConstInt(ConstInt), CumulativeCost(0) { }
Juergen Ributzka5429c062014-03-21 06:04:36 +000077
78 /// \brief Add the user to the use list and update the cost.
79 void addUser(Instruction *Inst, unsigned Idx, unsigned Cost) {
80 CumulativeCost += Cost;
81 Uses.push_back(ConstantUser(Inst, Idx));
82 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +000083};
84
Juergen Ributzka5429c062014-03-21 06:04:36 +000085/// \brief This represents a constant that has been rebased with respect to a
86/// base constant. The difference to the base constant is recorded in Offset.
87struct RebasedConstantInfo {
88 ConstantUseListType Uses;
89 Constant *Offset;
90
91 RebasedConstantInfo(ConstantUseListType &&Uses, Constant *Offset)
92 : Uses(Uses), Offset(Offset) { }
93};
94
95/// \brief A base constant and all its rebased constants.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000096struct ConstantInfo {
97 ConstantInt *BaseConstant;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098 RebasedConstantListType RebasedConstants;
99};
100
Juergen Ributzka5429c062014-03-21 06:04:36 +0000101/// \brief The constant hoisting pass.
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000102class ConstantHoisting : public FunctionPass {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000103 typedef DenseMap<ConstantInt *, unsigned> ConstCandMapType;
104 typedef std::vector<ConstantCandidate> ConstCandVecType;
105
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000106 const TargetTransformInfo *TTI;
107 DominatorTree *DT;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000108 BasicBlock *Entry;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000109
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000110 /// Keeps track of constant candidates found in the function.
111 ConstCandMapType ConstCandMap;
112 ConstCandVecType ConstCandVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000113
Juergen Ributzka5429c062014-03-21 06:04:36 +0000114 /// Keep track of cast instructions we already cloned.
115 SmallDenseMap<Instruction *, Instruction *> ClonedCastMap;
116
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000117 /// These are the final constants we decided to hoist.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000118 SmallVector<ConstantInfo, 8> ConstantVec;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000119public:
120 static char ID; // Pass identification, replacement for typeid
Juergen Ributzka5429c062014-03-21 06:04:36 +0000121 ConstantHoisting() : FunctionPass(ID), TTI(0), DT(0), Entry(0) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000122 initializeConstantHoistingPass(*PassRegistry::getPassRegistry());
123 }
124
Juergen Ributzka5429c062014-03-21 06:04:36 +0000125 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000126
Craig Topper3e4c6972014-03-05 09:10:37 +0000127 const char *getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000128
Craig Topper3e4c6972014-03-05 09:10:37 +0000129 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000130 AU.setPreservesCFG();
131 AU.addRequired<DominatorTreeWrapperPass>();
132 AU.addRequired<TargetTransformInfo>();
133 }
134
135private:
Juergen Ributzka5429c062014-03-21 06:04:36 +0000136 /// \brief Initialize the pass.
137 void setup(Function &Fn) {
138 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
139 TTI = &getAnalysis<TargetTransformInfo>();
140 Entry = &Fn.getEntryBlock();
141 }
142
143 /// \brief Cleanup.
144 void cleanup() {
145 ConstantVec.clear();
146 ClonedCastMap.clear();
147 ConstCandVec.clear();
148 ConstCandMap.clear();
149
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;
157 void collectConstantCandidates(Instruction *Inst, unsigned Idx,
158 ConstantInt *ConstInt);
159 void collectConstantCandidates(Instruction *Inst);
160 void collectConstantCandidates(Function &Fn);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000161 void findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000162 ConstCandVecType::iterator E);
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000163 void findBaseConstants();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000164 void emitBaseConstants(Instruction *Base, Constant *Offset,
165 const ConstantUser &ConstUser);
166 bool emitBaseConstants();
167 void deleteDeadCastInst() const;
168 bool optimizeConstants(Function &Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000169};
170}
171
172char ConstantHoisting::ID = 0;
173INITIALIZE_PASS_BEGIN(ConstantHoisting, "consthoist", "Constant Hoisting",
174 false, false)
175INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
176INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
177INITIALIZE_PASS_END(ConstantHoisting, "consthoist", "Constant Hoisting",
178 false, false)
179
180FunctionPass *llvm::createConstantHoistingPass() {
181 return new ConstantHoisting();
182}
183
184/// \brief Perform the constant hoisting optimization for the given function.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000185bool ConstantHoisting::runOnFunction(Function &Fn) {
186 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
187 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000188
Juergen Ributzka5429c062014-03-21 06:04:36 +0000189 setup(Fn);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000190
Juergen Ributzka5429c062014-03-21 06:04:36 +0000191 bool MadeChange = optimizeConstants(Fn);
192
193 if (MadeChange) {
194 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
195 << Fn.getName() << '\n');
196 DEBUG(dbgs() << Fn);
197 }
198 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
199
200 cleanup();
201
202 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000203}
204
Juergen Ributzka5429c062014-03-21 06:04:36 +0000205
206/// \brief Find the constant materialization insertion point.
207Instruction *ConstantHoisting::findMatInsertPt(Instruction *Inst,
208 unsigned Idx) const {
209 // The simple and common case.
210 if (!isa<PHINode>(Inst) && !isa<LandingPadInst>(Inst))
211 return Inst;
212
213 // We can't insert directly before a phi node or landing pad. Insert before
214 // the terminator of the incoming or dominating block.
215 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
216 if (Idx != ~0U && isa<PHINode>(Inst))
217 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
218
219 BasicBlock *IDom = DT->getNode(Inst->getParent())->getIDom()->getBlock();
220 return IDom->getTerminator();
221}
222
223/// \brief Find an insertion point that dominates all uses.
224Instruction *ConstantHoisting::
225findConstantInsertionPoint(const ConstantInfo &ConstInfo) const {
226 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
227 // Collect all basic blocks.
228 SmallPtrSet<BasicBlock *, 8> BBs;
229 for (auto const &RCI : ConstInfo.RebasedConstants)
230 for (auto const &U : RCI.Uses)
231 BBs.insert(U.Inst->getParent());
232
233 if (BBs.count(Entry))
234 return &Entry->front();
235
236 while (BBs.size() >= 2) {
237 BasicBlock *BB, *BB1, *BB2;
238 BB1 = *BBs.begin();
239 BB2 = *std::next(BBs.begin());
240 BB = DT->findNearestCommonDominator(BB1, BB2);
241 if (BB == Entry)
242 return &Entry->front();
243 BBs.erase(BB1);
244 BBs.erase(BB2);
245 BBs.insert(BB);
246 }
247 assert((BBs.size() == 1) && "Expected only one element.");
248 Instruction &FirstInst = (*BBs.begin())->front();
249 return findMatInsertPt(&FirstInst);
250}
251
252
253/// \brief Record constant integer ConstInt for instruction Inst at operand
254/// index Idx.
255///
256/// The operand at index Idx is not necessarily the constant inetger itself. It
257/// could also be a cast instruction or a constant expression that uses the
258// constant integer.
259void ConstantHoisting::collectConstantCandidates(Instruction *Inst,
260 unsigned Idx,
261 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000262 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000263 // Ask the target about the cost of materializing the constant for the given
264 // instruction.
265 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
266 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(),
267 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000268 else
Juergen Ributzka5429c062014-03-21 06:04:36 +0000269 Cost = TTI->getIntImmCost(Inst->getOpcode(), ConstInt->getValue(),
270 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000271
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000272 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000273 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000274 ConstCandMapType::iterator Itr;
275 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000276 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000277 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000278 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000279 Itr->second = ConstCandVec.size() - 1;
280 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000281 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
282 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
283 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
284 << " with cost " << Cost << '\n';
285 else
286 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
287 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
288 << Cost << '\n';
289 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000290 }
291}
292
Juergen Ributzka5429c062014-03-21 06:04:36 +0000293/// \brief Scan the instruction for expensive integer constants and record them
294/// in the constant candidate vector.
295void ConstantHoisting::collectConstantCandidates(Instruction *Inst) {
296 // Skip all cast instructions. They are visited indirectly later on.
297 if (Inst->isCast())
298 return;
299
300 // Can't handle inline asm. Skip it.
301 if (auto Call = dyn_cast<CallInst>(Inst))
302 if (isa<InlineAsm>(Call->getCalledValue()))
303 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000304
305 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000306 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
307 Value *Opnd = Inst->getOperand(Idx);
308
309 // Vist constant integers.
310 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
311 collectConstantCandidates(Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000312 continue;
313 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000314
315 // Visit cast instructions that have constant integers.
316 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
317 // Only visit cast instructions, which have been skipped. All other
318 // instructions should have already been visited.
319 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000320 continue;
321
Juergen Ributzka5429c062014-03-21 06:04:36 +0000322 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
323 // Pretend the constant is directly used by the instruction and ignore
324 // the cast instruction.
325 collectConstantCandidates(Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000326 continue;
327 }
328 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000329
330 // Visit constant expressions that have constant integers.
331 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
332 // Only visit constant cast expressions.
333 if (!ConstExpr->isCast())
334 continue;
335
336 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
337 // Pretend the constant is directly used by the instruction and ignore
338 // the constant expression.
339 collectConstantCandidates(Inst, Idx, ConstInt);
340 continue;
341 }
342 }
343 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000344}
345
346/// \brief Collect all integer constants in the function that cannot be folded
347/// into an instruction itself.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000348void ConstantHoisting::collectConstantCandidates(Function &Fn) {
349 for (Function::iterator BB : Fn)
350 for (BasicBlock::iterator Inst : *BB)
351 collectConstantCandidates(Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000352}
353
354/// \brief Find the base constant within the given range and rebase all other
355/// constants with respect to the base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000356void ConstantHoisting::findAndMakeBaseConstant(ConstCandVecType::iterator S,
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000357 ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000358 auto MaxCostItr = S;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000359 unsigned NumUses = 0;
360 // Use the constant that has the maximum cost as base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000361 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
362 NumUses += ConstCand->Uses.size();
363 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
364 MaxCostItr = ConstCand;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000365 }
366
367 // Don't hoist constants that have only one use.
368 if (NumUses <= 1)
369 return;
370
Juergen Ributzka5429c062014-03-21 06:04:36 +0000371 ConstantInfo ConstInfo;
372 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
373 Type *Ty = ConstInfo.BaseConstant->getType();
374
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000375 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000376 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
377 APInt Diff = ConstCand->ConstInt->getValue() -
378 ConstInfo.BaseConstant->getValue();
379 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
380 ConstInfo.RebasedConstants.push_back(
381 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000382 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000383 ConstantVec.push_back(ConstInfo);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000384}
385
Juergen Ributzka5429c062014-03-21 06:04:36 +0000386/// \brief Finds and combines constant candidates that can be easily
387/// rematerialized with an add from a common base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000388void ConstantHoisting::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000389 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000390 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
391 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
392 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
393 return LHS.ConstInt->getType()->getBitWidth() <
394 RHS.ConstInt->getType()->getBitWidth();
395 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000396 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000397
Juergen Ributzka5429c062014-03-21 06:04:36 +0000398 // Simple linear scan through the sorted constant candidate vector for viable
399 // merge candidates.
400 auto MinValItr = ConstCandVec.begin();
401 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
402 CC != E; ++CC) {
403 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000404 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000405 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000406 if ((Diff.getBitWidth() <= 64) &&
407 TTI->isLegalAddImmediate(Diff.getSExtValue()))
408 continue;
409 }
410 // We either have now a different constant type or the constant is not in
411 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000412 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000413 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000414 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000415 }
416 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000417 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000418}
419
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000420/// \brief Emit materialization code for all rebased constants and update their
421/// users.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000422void ConstantHoisting::emitBaseConstants(Instruction *Base, Constant *Offset,
423 const ConstantUser &ConstUser) {
424 Instruction *Mat = Base;
425 if (Offset) {
426 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
427 ConstUser.OpndIdx);
428 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
429 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000430
Juergen Ributzka5429c062014-03-21 06:04:36 +0000431 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
432 << " + " << *Offset << ") in BB "
433 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
434 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
435 }
436 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000437
Juergen Ributzka5429c062014-03-21 06:04:36 +0000438 // Visit constant integer.
439 if (isa<ConstantInt>(Opnd)) {
440 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
441 ConstUser.Inst->setOperand(ConstUser.OpndIdx, Mat);
442 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000443 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000444 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000445
Juergen Ributzka5429c062014-03-21 06:04:36 +0000446 // Visit cast instruction.
447 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
448 assert(CastInst->isCast() && "Expected an cast instruction!");
449 // Check if we already have visited this cast instruction before to avoid
450 // unnecessary cloning.
451 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
452 if (!ClonedCastInst) {
453 ClonedCastInst = CastInst->clone();
454 ClonedCastInst->setOperand(0, Mat);
455 ClonedCastInst->insertAfter(CastInst);
456 // Use the same debug location as the original cast instruction.
457 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
458 DEBUG(dbgs() << "Clone instruction: " << *ClonedCastInst << '\n'
459 << "To : " << *CastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000460 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000461
462 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
463 ConstUser.Inst->setOperand(ConstUser.OpndIdx, ClonedCastInst);
464 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
465 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000466 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000467
468 // Visit constant expression.
469 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
470 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
471 ConstExprInst->setOperand(0, Mat);
472 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
473 ConstUser.OpndIdx));
474
475 // Use the same debug location as the instruction we are about to update.
476 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
477
478 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
479 << "From : " << *ConstExpr << '\n');
480 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
481 ConstUser.Inst->setOperand(ConstUser.OpndIdx, ConstExprInst);
482 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
483 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000484 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000485}
486
487/// \brief Hoist and hide the base constant behind a bitcast and emit
488/// materialization code for derived constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000489bool ConstantHoisting::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000490 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000491 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000492 // Hoist and hide the base constant behind a bitcast.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000493 Instruction *IP = findConstantInsertionPoint(ConstInfo);
494 IntegerType *Ty = ConstInfo.BaseConstant->getType();
495 Instruction *Base =
496 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
497 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant << ") to BB "
498 << IP->getParent()->getName() << '\n' << *Base << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000499 NumConstantsHoisted++;
500
501 // Emit materialization code for all rebased constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000502 for (auto const &RCI : ConstInfo.RebasedConstants) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000503 NumConstantsRebased++;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000504 for (auto const &U : RCI.Uses)
505 emitBaseConstants(Base, RCI.Offset, U);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000506 }
507
508 // Use the same debug location as the last user of the constant.
509 assert(!Base->use_empty() && "The use list is empty!?");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000510 assert(isa<Instruction>(Base->user_back()) &&
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000511 "All uses should be instructions.");
Chandler Carruthcdf47882014-03-09 03:16:01 +0000512 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000513
514 // Correct for base constant, which we counted above too.
515 NumConstantsRebased--;
516 MadeChange = true;
517 }
518 return MadeChange;
519}
520
Juergen Ributzka5429c062014-03-21 06:04:36 +0000521/// \brief Check all cast instructions we made a copy of and remove them if they
522/// have no more users.
523void ConstantHoisting::deleteDeadCastInst() const {
524 for (auto const &I : ClonedCastMap)
525 if (I.first->use_empty())
526 I.first->removeFromParent();
527}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000528
Juergen Ributzka5429c062014-03-21 06:04:36 +0000529/// \brief Optimize expensive integer constants in the given function.
530bool ConstantHoisting::optimizeConstants(Function &Fn) {
Juergen Ributzka46357932014-03-20 20:17:13 +0000531 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000532 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000533
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000534 // There are no constant candidates to worry about.
535 if (ConstCandVec.empty())
536 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000537
538 // Combine constants that can be easily materialized with an add from a common
539 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000540 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000541
Juergen Ributzka5429c062014-03-21 06:04:36 +0000542 // There are no constants to emit.
543 if (ConstantVec.empty())
544 return false;
545
Alp Toker70b36992014-02-25 04:21:15 +0000546 // Finally hoist the base constant and emit materializating code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000547 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000548 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000549
Juergen Ributzka5429c062014-03-21 06:04:36 +0000550 // Cleanup dead instructions.
551 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000552
553 return MadeChange;
554}