blob: e4b08c5ed305a5ffcb61eb195b83b20a2b232648 [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"
Eugene Zelenko8002c502017-09-13 21:43:53 +000037#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/Optional.h"
41#include "llvm/ADT/SmallPtrSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000042#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000043#include "llvm/ADT/Statistic.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000044#include "llvm/Analysis/BlockFrequencyInfo.h"
45#include "llvm/Analysis/TargetTransformInfo.h"
46#include "llvm/IR/BasicBlock.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000047#include "llvm/IR/Constants.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000048#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000053#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000054#include "llvm/IR/Value.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000055#include "llvm/Pass.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000056#include "llvm/Support/BlockFrequency.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/CommandLine.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000059#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000060#include "llvm/Support/raw_ostream.h"
Michael Kuperstein071d8302016-07-02 00:16:47 +000061#include "llvm/Transforms/Scalar.h"
Leo Li93abd7d2017-07-10 20:45:34 +000062#include "llvm/Transforms/Utils/Local.h"
Paul Robinsonb46256b2017-11-09 20:01:31 +000063#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000064#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <iterator>
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000068#include <tuple>
Eugene Zelenko8002c502017-09-13 21:43:53 +000069#include <utility>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000070
71using namespace llvm;
Michael Kuperstein071d8302016-07-02 00:16:47 +000072using namespace consthoist;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "consthoist"
75
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000076STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
77STATISTIC(NumConstantsRebased, "Number of constants rebased");
78
Wei Mi337d4d92017-04-21 15:50:16 +000079static cl::opt<bool> ConstHoistWithBlockFrequency(
Wei Mi75867552017-07-07 00:11:05 +000080 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
Wei Mi337d4d92017-04-21 15:50:16 +000081 cl::desc("Enable the use of the block frequency analysis to reduce the "
82 "chance to execute const materialization more frequently than "
83 "without hoisting."));
84
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000085namespace {
Eugene Zelenko8002c502017-09-13 21:43:53 +000086
Juergen Ributzka5429c062014-03-21 06:04:36 +000087/// \brief The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000088class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000089public:
90 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +000091
Michael Kuperstein071d8302016-07-02 00:16:47 +000092 ConstantHoistingLegacyPass() : FunctionPass(ID) {
93 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000094 }
95
Juergen Ributzka5429c062014-03-21 06:04:36 +000096 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000097
Mehdi Amini117296c2016-10-01 02:56:57 +000098 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000099
Craig Topper3e4c6972014-03-05 09:10:37 +0000100 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000101 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +0000102 if (ConstHoistWithBlockFrequency)
103 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000104 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000105 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000106 }
107
Michael Kuperstein071d8302016-07-02 00:16:47 +0000108 void releaseMemory() override { Impl.releaseMemory(); }
109
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110private:
Michael Kuperstein071d8302016-07-02 00:16:47 +0000111 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000112};
Eugene Zelenko8002c502017-09-13 21:43:53 +0000113
114} // end anonymous namespace
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000115
Michael Kuperstein071d8302016-07-02 00:16:47 +0000116char ConstantHoistingLegacyPass::ID = 0;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000117
Michael Kuperstein071d8302016-07-02 00:16:47 +0000118INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
119 "Constant Hoisting", false, false)
Wei Mi337d4d92017-04-21 15:50:16 +0000120INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000121INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000122INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +0000123INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
124 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000125
126FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000127 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000128}
129
130/// \brief Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000131bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000132 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000133 return false;
134
Juergen Ributzka5429c062014-03-21 06:04:36 +0000135 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
136 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000137
Wei Mi337d4d92017-04-21 15:50:16 +0000138 bool MadeChange =
139 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
140 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
141 ConstHoistWithBlockFrequency
142 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
143 : nullptr,
144 Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000145
146 if (MadeChange) {
147 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
148 << Fn.getName() << '\n');
149 DEBUG(dbgs() << Fn);
150 }
151 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
152
Juergen Ributzka5429c062014-03-21 06:04:36 +0000153 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000154}
155
Juergen Ributzka5429c062014-03-21 06:04:36 +0000156/// \brief Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000157Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
158 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000159 // If the operand is a cast instruction, then we have to materialize the
160 // constant before the cast instruction.
161 if (Idx != ~0U) {
162 Value *Opnd = Inst->getOperand(Idx);
163 if (auto CastInst = dyn_cast<Instruction>(Opnd))
164 if (CastInst->isCast())
165 return CastInst;
166 }
167
168 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000169 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000170 return Inst;
171
David Majnemerba275f92015-08-19 19:54:02 +0000172 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000173 // the terminator of the incoming or dominating block.
174 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
175 if (Idx != ~0U && isa<PHINode>(Inst))
176 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
177
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000178 // This must be an EH pad. Iterate over immediate dominators until we find a
179 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
180 // and terminators.
181 auto IDom = DT->getNode(Inst->getParent())->getIDom();
182 while (IDom->getBlock()->isEHPad()) {
183 assert(Entry != IDom->getBlock() && "eh pad in entry block");
184 IDom = IDom->getIDom();
185 }
186
187 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000188}
189
Wei Mi337d4d92017-04-21 15:50:16 +0000190/// \brief Given \p BBs as input, find another set of BBs which collectively
191/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
192/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000193static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
194 BasicBlock *Entry,
195 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000196 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
197 // Nodes on the current path to the root.
198 SmallPtrSet<BasicBlock *, 8> Path;
199 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
200 // dominated by any other blocks in set 'BBs', and all nodes in the path
201 // in the dominator tree from Entry to 'BB'.
202 SmallPtrSet<BasicBlock *, 16> Candidates;
203 for (auto BB : BBs) {
204 Path.clear();
205 // Walk up the dominator tree until Entry or another BB in BBs
206 // is reached. Insert the nodes on the way to the Path.
207 BasicBlock *Node = BB;
208 // The "Path" is a candidate path to be added into Candidates set.
209 bool isCandidate = false;
210 do {
211 Path.insert(Node);
212 if (Node == Entry || Candidates.count(Node)) {
213 isCandidate = true;
214 break;
215 }
216 assert(DT.getNode(Node)->getIDom() &&
217 "Entry doens't dominate current Node");
218 Node = DT.getNode(Node)->getIDom()->getBlock();
219 } while (!BBs.count(Node));
220
221 // If isCandidate is false, Node is another Block in BBs dominating
222 // current 'BB'. Drop the nodes on the Path.
223 if (!isCandidate)
224 continue;
225
226 // Add nodes on the Path into Candidates.
227 Candidates.insert(Path.begin(), Path.end());
228 }
229
230 // Sort the nodes in Candidates in top-down order and save the nodes
231 // in Orders.
232 unsigned Idx = 0;
233 SmallVector<BasicBlock *, 16> Orders;
234 Orders.push_back(Entry);
235 while (Idx != Orders.size()) {
236 BasicBlock *Node = Orders[Idx++];
237 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
238 if (Candidates.count(ChildDomNode->getBlock()))
239 Orders.push_back(ChildDomNode->getBlock());
240 }
241 }
242
243 // Visit Orders in bottom-up order.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000244 using InsertPtsCostPair =
245 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
246
Wei Mi337d4d92017-04-21 15:50:16 +0000247 // InsertPtsMap is a map from a BB to the best insertion points for the
248 // subtree of BB (subtree not including the BB itself).
249 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
250 InsertPtsMap.reserve(Orders.size() + 1);
251 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
252 BasicBlock *Node = *RIt;
253 bool NodeInBBs = BBs.count(Node);
254 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
255 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
256
257 // Return the optimal insert points in BBs.
258 if (Node == Entry) {
259 BBs.clear();
Wei Mi20526b22017-07-06 22:32:27 +0000260 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
261 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
Wei Mi337d4d92017-04-21 15:50:16 +0000262 BBs.insert(Entry);
263 else
264 BBs.insert(InsertPts.begin(), InsertPts.end());
265 break;
266 }
267
268 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
269 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
270 // will update its parent's ParentInsertPts and ParentPtsFreq.
271 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
272 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
273 // Choose to insert in Node or in subtree of Node.
Wei Mi20526b22017-07-06 22:32:27 +0000274 // Don't hoist to EHPad because we may not find a proper place to insert
275 // in EHPad.
276 // If the total frequency of InsertPts is the same as the frequency of the
277 // target Node, and InsertPts contains more than one nodes, choose hoisting
278 // to reduce code size.
279 if (NodeInBBs ||
280 (!Node->isEHPad() &&
281 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
282 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
Wei Mi337d4d92017-04-21 15:50:16 +0000283 ParentInsertPts.insert(Node);
284 ParentPtsFreq += BFI.getBlockFreq(Node);
285 } else {
286 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
287 ParentPtsFreq += InsertPtsFreq;
288 }
289 }
290}
291
Juergen Ributzka5429c062014-03-21 06:04:36 +0000292/// \brief Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000293SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000294 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000295 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000296 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000297 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000298 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000299 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000300 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000301 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000302
Wei Mi337d4d92017-04-21 15:50:16 +0000303 if (BBs.count(Entry)) {
304 InsertPts.insert(&Entry->front());
305 return InsertPts;
306 }
307
308 if (BFI) {
309 findBestInsertionSet(*DT, *BFI, Entry, BBs);
310 for (auto BB : BBs) {
311 BasicBlock::iterator InsertPt = BB->begin();
312 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
313 ;
314 InsertPts.insert(&*InsertPt);
315 }
316 return InsertPts;
317 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000318
319 while (BBs.size() >= 2) {
320 BasicBlock *BB, *BB1, *BB2;
321 BB1 = *BBs.begin();
322 BB2 = *std::next(BBs.begin());
323 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000324 if (BB == Entry) {
325 InsertPts.insert(&Entry->front());
326 return InsertPts;
327 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000328 BBs.erase(BB1);
329 BBs.erase(BB2);
330 BBs.insert(BB);
331 }
332 assert((BBs.size() == 1) && "Expected only one element.");
333 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000334 InsertPts.insert(findMatInsertPt(&FirstInst));
335 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000336}
337
Juergen Ributzka5429c062014-03-21 06:04:36 +0000338/// \brief Record constant integer ConstInt for instruction Inst at operand
339/// index Idx.
340///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000341/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000342/// could also be a cast instruction or a constant expression that uses the
343// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000344void ConstantHoistingPass::collectConstantCandidates(
345 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
346 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000347 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000348 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000349 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000350 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000351 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000352 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000353 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000354 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000355 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000356
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000357 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000358 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000359 ConstCandMapType::iterator Itr;
360 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000361 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000362 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000363 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000364 Itr->second = ConstCandVec.size() - 1;
365 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000366 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
367 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
368 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
369 << " with cost " << Cost << '\n';
370 else
371 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
372 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
373 << Cost << '\n';
374 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000375 }
376}
377
Leo Li20fbad92017-06-29 17:03:34 +0000378/// \brief Check the operand for instruction Inst at index Idx.
379void ConstantHoistingPass::collectConstantCandidates(
380 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
381 Value *Opnd = Inst->getOperand(Idx);
382
383 // Visit constant integers.
384 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
385 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
386 return;
387 }
388
389 // Visit cast instructions that have constant integers.
390 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
391 // Only visit cast instructions, which have been skipped. All other
392 // instructions should have already been visited.
393 if (!CastInst->isCast())
394 return;
395
396 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
397 // Pretend the constant is directly used by the instruction and ignore
398 // the cast instruction.
399 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
400 return;
401 }
402 }
403
404 // Visit constant expressions that have constant integers.
405 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
406 // Only visit constant cast expressions.
407 if (!ConstExpr->isCast())
408 return;
409
410 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
411 // Pretend the constant is directly used by the instruction and ignore
412 // the constant expression.
413 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
414 return;
415 }
416 }
417}
418
Juergen Ributzka5429c062014-03-21 06:04:36 +0000419/// \brief Scan the instruction for expensive integer constants and record them
420/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000421void ConstantHoistingPass::collectConstantCandidates(
422 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000423 // Skip all cast instructions. They are visited indirectly later on.
424 if (Inst->isCast())
425 return;
426
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000427 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000428 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Leo Li93abd7d2017-07-10 20:45:34 +0000429 // The cost of materializing the constants (defined in
430 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
431 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
432 // it's safe for us to collect constant candidates from all IntrinsicInsts.
433 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
434 collectConstantCandidates(ConstCandMap, Inst, Idx);
435 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000436 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000437}
438
439/// \brief Collect all integer constants in the function that cannot be folded
440/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000441void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000442 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000443 for (BasicBlock &BB : Fn)
444 for (Instruction &Inst : BB)
445 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000446}
447
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000448// This helper function is necessary to deal with values that have different
449// bit widths (APInt Operator- does not like that). If the value cannot be
450// represented in uint64 we return an "empty" APInt. This is then interpreted
451// as the value is not in range.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000452static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
453 Optional<APInt> Res = None;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000454 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
455 V1.getBitWidth() : V2.getBitWidth();
456 uint64_t LimVal1 = V1.getLimitedValue();
457 uint64_t LimVal2 = V2.getLimitedValue();
458
459 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
460 return Res;
461
462 uint64_t Diff = LimVal1 - LimVal2;
463 return APInt(BW, Diff, true);
464}
465
466// From a list of constants, one needs to picked as the base and the other
467// constants will be transformed into an offset from that base constant. The
468// question is which we can pick best? For example, consider these constants
469// and their number of uses:
470//
471// Constants| 2 | 4 | 12 | 42 |
472// NumUses | 3 | 2 | 8 | 7 |
473//
474// Selecting constant 12 because it has the most uses will generate negative
475// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
476// offsets lead to less optimal code generation, then there might be better
477// solutions. Suppose immediates in the range of 0..35 are most optimally
478// supported by the architecture, then selecting constant 2 is most optimal
479// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
480// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
481// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
482// selecting the base constant the range of the offsets is a very important
483// factor too that we take into account here. This algorithm calculates a total
484// costs for selecting a constant as the base and substract the costs if
485// immediates are out of range. It has quadratic complexity, so we call this
486// function only when we're optimising for size and there are less than 100
487// constants, we fall back to the straightforward algorithm otherwise
488// which does not do all the offset calculations.
489unsigned
490ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
491 ConstCandVecType::iterator E,
492 ConstCandVecType::iterator &MaxCostItr) {
493 unsigned NumUses = 0;
494
495 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
496 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
497 NumUses += ConstCand->Uses.size();
498 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
499 MaxCostItr = ConstCand;
500 }
501 return NumUses;
502 }
503
504 DEBUG(dbgs() << "== Maximize constants in range ==\n");
505 int MaxCost = -1;
506 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
507 auto Value = ConstCand->ConstInt->getValue();
508 Type *Ty = ConstCand->ConstInt->getType();
509 int Cost = 0;
510 NumUses += ConstCand->Uses.size();
511 DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
512
513 for (auto User : ConstCand->Uses) {
514 unsigned Opcode = User.Inst->getOpcode();
515 unsigned OpndIdx = User.OpndIdx;
516 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
517 DEBUG(dbgs() << "Cost: " << Cost << "\n");
518
519 for (auto C2 = S; C2 != E; ++C2) {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000520 Optional<APInt> Diff = calculateOffsetDiff(
521 C2->ConstInt->getValue(),
522 ConstCand->ConstInt->getValue());
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000523 if (Diff) {
524 const int ImmCosts =
525 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
526 Cost -= ImmCosts;
527 DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
528 << "has penalty: " << ImmCosts << "\n"
529 << "Adjusted cost: " << Cost << "\n");
530 }
531 }
532 }
533 DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
534 if (Cost > MaxCost) {
535 MaxCost = Cost;
536 MaxCostItr = ConstCand;
537 DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
538 << "\n");
539 }
540 }
541 return NumUses;
542}
543
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000544/// \brief Find the base constant within the given range and rebase all other
545/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000546void ConstantHoistingPass::findAndMakeBaseConstant(
547 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000548 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000549 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000550
551 // Don't hoist constants that have only one use.
552 if (NumUses <= 1)
553 return;
554
Juergen Ributzka5429c062014-03-21 06:04:36 +0000555 ConstantInfo ConstInfo;
556 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
557 Type *Ty = ConstInfo.BaseConstant->getType();
558
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000559 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000560 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
561 APInt Diff = ConstCand->ConstInt->getValue() -
562 ConstInfo.BaseConstant->getValue();
563 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
564 ConstInfo.RebasedConstants.push_back(
565 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000566 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000567 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000568}
569
Juergen Ributzka5429c062014-03-21 06:04:36 +0000570/// \brief Finds and combines constant candidates that can be easily
571/// rematerialized with an add from a common base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000572void ConstantHoistingPass::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000573 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000574 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
575 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
576 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
577 return LHS.ConstInt->getType()->getBitWidth() <
578 RHS.ConstInt->getType()->getBitWidth();
579 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000580 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000581
Juergen Ributzka5429c062014-03-21 06:04:36 +0000582 // Simple linear scan through the sorted constant candidate vector for viable
583 // merge candidates.
584 auto MinValItr = ConstCandVec.begin();
585 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
586 CC != E; ++CC) {
587 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000588 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000589 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000590 if ((Diff.getBitWidth() <= 64) &&
591 TTI->isLegalAddImmediate(Diff.getSExtValue()))
592 continue;
593 }
594 // We either have now a different constant type or the constant is not in
595 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000596 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000597 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000598 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000599 }
600 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000601 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000602}
603
Juergen Ributzkae802d502014-03-22 01:49:27 +0000604/// \brief Updates the operand at Idx in instruction Inst with the result of
605/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000606/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000607/// required.
608/// \return The update will always succeed, but the return value indicated if
609/// Mat was used for the update or not.
610static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
611 if (auto PHI = dyn_cast<PHINode>(Inst)) {
612 // Check if any previous operand of the PHI node has the same incoming basic
613 // block. This is a very odd case that happens when the incoming basic block
614 // has a switch statement. In this case use the same value as the previous
615 // operand(s), otherwise we will fail verification due to different values.
616 // The values are actually the same, but the variable names are different
617 // and the verifier doesn't like that.
618 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
619 for (unsigned i = 0; i < Idx; ++i) {
620 if (PHI->getIncomingBlock(i) == IncomingBB) {
621 Value *IncomingVal = PHI->getIncomingValue(i);
622 Inst->setOperand(Idx, IncomingVal);
623 return false;
624 }
625 }
626 }
627
628 Inst->setOperand(Idx, Mat);
629 return true;
630}
631
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000632/// \brief Emit materialization code for all rebased constants and update their
633/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000634void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
635 Constant *Offset,
636 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000637 Instruction *Mat = Base;
638 if (Offset) {
639 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
640 ConstUser.OpndIdx);
641 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
642 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000643
Juergen Ributzka5429c062014-03-21 06:04:36 +0000644 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
645 << " + " << *Offset << ") in BB "
646 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
647 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
648 }
649 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000650
Juergen Ributzka5429c062014-03-21 06:04:36 +0000651 // Visit constant integer.
652 if (isa<ConstantInt>(Opnd)) {
653 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000654 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
655 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000656 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000657 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000658 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000659
Juergen Ributzka5429c062014-03-21 06:04:36 +0000660 // Visit cast instruction.
661 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
662 assert(CastInst->isCast() && "Expected an cast instruction!");
663 // Check if we already have visited this cast instruction before to avoid
664 // unnecessary cloning.
665 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
666 if (!ClonedCastInst) {
667 ClonedCastInst = CastInst->clone();
668 ClonedCastInst->setOperand(0, Mat);
669 ClonedCastInst->insertAfter(CastInst);
670 // Use the same debug location as the original cast instruction.
671 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000672 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
673 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000674 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000675
676 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000677 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000678 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
679 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000680 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000681
682 // Visit constant expression.
683 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
684 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
685 ConstExprInst->setOperand(0, Mat);
686 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
687 ConstUser.OpndIdx));
688
689 // Use the same debug location as the instruction we are about to update.
690 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
691
692 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
693 << "From : " << *ConstExpr << '\n');
694 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000695 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
696 ConstExprInst->eraseFromParent();
697 if (Offset)
698 Mat->eraseFromParent();
699 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000700 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
701 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000702 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000703}
704
705/// \brief Hoist and hide the base constant behind a bitcast and emit
706/// materialization code for derived constants.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000707bool ConstantHoistingPass::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000708 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000709 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000710 // Hoist and hide the base constant behind a bitcast.
Wei Mi337d4d92017-04-21 15:50:16 +0000711 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
712 assert(!IPSet.empty() && "IPSet is empty");
713
714 unsigned UsesNum = 0;
715 unsigned ReBasesNum = 0;
716 for (Instruction *IP : IPSet) {
717 IntegerType *Ty = ConstInfo.BaseConstant->getType();
718 Instruction *Base =
719 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
Paul Robinsonb46256b2017-11-09 20:01:31 +0000720
721 Base->setDebugLoc(IP->getDebugLoc());
722
Wei Mi337d4d92017-04-21 15:50:16 +0000723 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant
724 << ") to BB " << IP->getParent()->getName() << '\n'
725 << *Base << '\n');
726
727 // Emit materialization code for all rebased constants.
728 unsigned Uses = 0;
729 for (auto const &RCI : ConstInfo.RebasedConstants) {
730 for (auto const &U : RCI.Uses) {
731 Uses++;
732 BasicBlock *OrigMatInsertBB =
733 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
734 // If Base constant is to be inserted in multiple places,
735 // generate rebase for U using the Base dominating U.
736 if (IPSet.size() == 1 ||
737 DT->dominates(Base->getParent(), OrigMatInsertBB)) {
738 emitBaseConstants(Base, RCI.Offset, U);
739 ReBasesNum++;
740 }
Paul Robinsonb46256b2017-11-09 20:01:31 +0000741
742 Base->setDebugLoc(DILocation::getMergedLocation(Base->getDebugLoc(), U.Inst->getDebugLoc()));
Wei Mi337d4d92017-04-21 15:50:16 +0000743 }
744 }
745 UsesNum = Uses;
746
747 // Use the same debug location as the last user of the constant.
748 assert(!Base->use_empty() && "The use list is empty!?");
749 assert(isa<Instruction>(Base->user_back()) &&
750 "All uses should be instructions.");
Wei Mi337d4d92017-04-21 15:50:16 +0000751 }
752 (void)UsesNum;
753 (void)ReBasesNum;
754 // Expect all uses are rebased after rebase is done.
755 assert(UsesNum == ReBasesNum && "Not all uses are rebased");
756
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000757 NumConstantsHoisted++;
758
Wei Mi337d4d92017-04-21 15:50:16 +0000759 // Base constant is also included in ConstInfo.RebasedConstants, so
760 // deduct 1 from ConstInfo.RebasedConstants.size().
761 NumConstantsRebased = ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000762
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000763 MadeChange = true;
764 }
765 return MadeChange;
766}
767
Juergen Ributzka5429c062014-03-21 06:04:36 +0000768/// \brief Check all cast instructions we made a copy of and remove them if they
769/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000770void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000771 for (auto const &I : ClonedCastMap)
772 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000773 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000774}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000775
Juergen Ributzka5429c062014-03-21 06:04:36 +0000776/// \brief Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000777bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000778 DominatorTree &DT, BlockFrequencyInfo *BFI,
779 BasicBlock &Entry) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000780 this->TTI = &TTI;
781 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000782 this->BFI = BFI;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000783 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000784 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000785 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000786
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000787 // There are no constant candidates to worry about.
788 if (ConstCandVec.empty())
789 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000790
791 // Combine constants that can be easily materialized with an add from a common
792 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000793 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000794
Juergen Ributzka5429c062014-03-21 06:04:36 +0000795 // There are no constants to emit.
796 if (ConstantVec.empty())
797 return false;
798
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000799 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000800 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000801 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000802
Juergen Ributzka5429c062014-03-21 06:04:36 +0000803 // Cleanup dead instructions.
804 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000805
806 return MadeChange;
807}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000808
809PreservedAnalyses ConstantHoistingPass::run(Function &F,
810 FunctionAnalysisManager &AM) {
811 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
812 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000813 auto BFI = ConstHoistWithBlockFrequency
814 ? &AM.getResult<BlockFrequencyAnalysis>(F)
815 : nullptr;
816 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000817 return PreservedAnalyses::all();
818
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000819 PreservedAnalyses PA;
820 PA.preserveSet<CFGAnalyses>();
821 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000822}