blob: c3810366bf22d376adbb1182020c6468cbd24e40 [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
Wei Mi337d4d92017-04-21 15:50:16 +000056static cl::opt<bool> ConstHoistWithBlockFrequency(
57 "consthoist-with-block-frequency", cl::init(false), cl::Hidden,
58 cl::desc("Enable the use of the block frequency analysis to reduce the "
59 "chance to execute const materialization more frequently than "
60 "without hoisting."));
61
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000062namespace {
Juergen Ributzka5429c062014-03-21 06:04:36 +000063/// \brief The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000064class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000065public:
66 static char ID; // Pass identification, replacement for typeid
Michael Kuperstein071d8302016-07-02 00:16:47 +000067 ConstantHoistingLegacyPass() : FunctionPass(ID) {
68 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000069 }
70
Juergen Ributzka5429c062014-03-21 06:04:36 +000071 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000072
Mehdi Amini117296c2016-10-01 02:56:57 +000073 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000074
Craig Topper3e4c6972014-03-05 09:10:37 +000075 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000076 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +000077 if (ConstHoistWithBlockFrequency)
78 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000079 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +000080 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000081 }
82
Michael Kuperstein071d8302016-07-02 00:16:47 +000083 void releaseMemory() override { Impl.releaseMemory(); }
84
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000085private:
Michael Kuperstein071d8302016-07-02 00:16:47 +000086 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000087};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000088}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000089
Michael Kuperstein071d8302016-07-02 00:16:47 +000090char ConstantHoistingLegacyPass::ID = 0;
91INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
92 "Constant Hoisting", false, false)
Wei Mi337d4d92017-04-21 15:50:16 +000093INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000094INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +000095INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +000096INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
97 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098
99FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000100 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000101}
102
103/// \brief Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000104bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000105 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000106 return false;
107
Juergen Ributzka5429c062014-03-21 06:04:36 +0000108 DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
109 DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110
Wei Mi337d4d92017-04-21 15:50:16 +0000111 bool MadeChange =
112 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
113 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
114 ConstHoistWithBlockFrequency
115 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
116 : nullptr,
117 Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000118
119 if (MadeChange) {
120 DEBUG(dbgs() << "********** Function after Constant Hoisting: "
121 << Fn.getName() << '\n');
122 DEBUG(dbgs() << Fn);
123 }
124 DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
125
Juergen Ributzka5429c062014-03-21 06:04:36 +0000126 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000127}
128
Juergen Ributzka5429c062014-03-21 06:04:36 +0000129
130/// \brief Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000131Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
132 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000133 // If the operand is a cast instruction, then we have to materialize the
134 // constant before the cast instruction.
135 if (Idx != ~0U) {
136 Value *Opnd = Inst->getOperand(Idx);
137 if (auto CastInst = dyn_cast<Instruction>(Opnd))
138 if (CastInst->isCast())
139 return CastInst;
140 }
141
142 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000143 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000144 return Inst;
145
David Majnemerba275f92015-08-19 19:54:02 +0000146 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000147 // the terminator of the incoming or dominating block.
148 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
149 if (Idx != ~0U && isa<PHINode>(Inst))
150 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
151
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000152 // This must be an EH pad. Iterate over immediate dominators until we find a
153 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
154 // and terminators.
155 auto IDom = DT->getNode(Inst->getParent())->getIDom();
156 while (IDom->getBlock()->isEHPad()) {
157 assert(Entry != IDom->getBlock() && "eh pad in entry block");
158 IDom = IDom->getIDom();
159 }
160
161 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000162}
163
Wei Mi337d4d92017-04-21 15:50:16 +0000164/// \brief Given \p BBs as input, find another set of BBs which collectively
165/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
166/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000167static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
168 BasicBlock *Entry,
169 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000170 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
171 // Nodes on the current path to the root.
172 SmallPtrSet<BasicBlock *, 8> Path;
173 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
174 // dominated by any other blocks in set 'BBs', and all nodes in the path
175 // in the dominator tree from Entry to 'BB'.
176 SmallPtrSet<BasicBlock *, 16> Candidates;
177 for (auto BB : BBs) {
178 Path.clear();
179 // Walk up the dominator tree until Entry or another BB in BBs
180 // is reached. Insert the nodes on the way to the Path.
181 BasicBlock *Node = BB;
182 // The "Path" is a candidate path to be added into Candidates set.
183 bool isCandidate = false;
184 do {
185 Path.insert(Node);
186 if (Node == Entry || Candidates.count(Node)) {
187 isCandidate = true;
188 break;
189 }
190 assert(DT.getNode(Node)->getIDom() &&
191 "Entry doens't dominate current Node");
192 Node = DT.getNode(Node)->getIDom()->getBlock();
193 } while (!BBs.count(Node));
194
195 // If isCandidate is false, Node is another Block in BBs dominating
196 // current 'BB'. Drop the nodes on the Path.
197 if (!isCandidate)
198 continue;
199
200 // Add nodes on the Path into Candidates.
201 Candidates.insert(Path.begin(), Path.end());
202 }
203
204 // Sort the nodes in Candidates in top-down order and save the nodes
205 // in Orders.
206 unsigned Idx = 0;
207 SmallVector<BasicBlock *, 16> Orders;
208 Orders.push_back(Entry);
209 while (Idx != Orders.size()) {
210 BasicBlock *Node = Orders[Idx++];
211 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
212 if (Candidates.count(ChildDomNode->getBlock()))
213 Orders.push_back(ChildDomNode->getBlock());
214 }
215 }
216
217 // Visit Orders in bottom-up order.
218 typedef std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>
219 InsertPtsCostPair;
220 // InsertPtsMap is a map from a BB to the best insertion points for the
221 // subtree of BB (subtree not including the BB itself).
222 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
223 InsertPtsMap.reserve(Orders.size() + 1);
224 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
225 BasicBlock *Node = *RIt;
226 bool NodeInBBs = BBs.count(Node);
227 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
228 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
229
230 // Return the optimal insert points in BBs.
231 if (Node == Entry) {
232 BBs.clear();
233 if (InsertPtsFreq > BFI.getBlockFreq(Node))
234 BBs.insert(Entry);
235 else
236 BBs.insert(InsertPts.begin(), InsertPts.end());
237 break;
238 }
239
240 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
241 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
242 // will update its parent's ParentInsertPts and ParentPtsFreq.
243 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
244 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
245 // Choose to insert in Node or in subtree of Node.
246 if (InsertPtsFreq > BFI.getBlockFreq(Node) || NodeInBBs) {
247 ParentInsertPts.insert(Node);
248 ParentPtsFreq += BFI.getBlockFreq(Node);
249 } else {
250 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
251 ParentPtsFreq += InsertPtsFreq;
252 }
253 }
254}
255
Juergen Ributzka5429c062014-03-21 06:04:36 +0000256/// \brief Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000257SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000258 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000259 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000260 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000261 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000262 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000263 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000264 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000265 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000266
Wei Mi337d4d92017-04-21 15:50:16 +0000267 if (BBs.count(Entry)) {
268 InsertPts.insert(&Entry->front());
269 return InsertPts;
270 }
271
272 if (BFI) {
273 findBestInsertionSet(*DT, *BFI, Entry, BBs);
274 for (auto BB : BBs) {
275 BasicBlock::iterator InsertPt = BB->begin();
276 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
277 ;
278 InsertPts.insert(&*InsertPt);
279 }
280 return InsertPts;
281 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000282
283 while (BBs.size() >= 2) {
284 BasicBlock *BB, *BB1, *BB2;
285 BB1 = *BBs.begin();
286 BB2 = *std::next(BBs.begin());
287 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000288 if (BB == Entry) {
289 InsertPts.insert(&Entry->front());
290 return InsertPts;
291 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000292 BBs.erase(BB1);
293 BBs.erase(BB2);
294 BBs.insert(BB);
295 }
296 assert((BBs.size() == 1) && "Expected only one element.");
297 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000298 InsertPts.insert(findMatInsertPt(&FirstInst));
299 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000300}
301
302
303/// \brief Record constant integer ConstInt for instruction Inst at operand
304/// index Idx.
305///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000306/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000307/// could also be a cast instruction or a constant expression that uses the
308// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000309void ConstantHoistingPass::collectConstantCandidates(
310 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
311 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000312 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000313 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000314 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000315 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000316 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000317 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000318 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000319 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000320 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000321
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000322 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000323 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000324 ConstCandMapType::iterator Itr;
325 bool Inserted;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000326 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(ConstInt, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000327 if (Inserted) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000328 ConstCandVec.push_back(ConstantCandidate(ConstInt));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000329 Itr->second = ConstCandVec.size() - 1;
330 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000331 ConstCandVec[Itr->second].addUser(Inst, Idx, Cost);
332 DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx)))
333 dbgs() << "Collect constant " << *ConstInt << " from " << *Inst
334 << " with cost " << Cost << '\n';
335 else
336 dbgs() << "Collect constant " << *ConstInt << " indirectly from "
337 << *Inst << " via " << *Inst->getOperand(Idx) << " with cost "
338 << Cost << '\n';
339 );
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000340 }
341}
342
Juergen Ributzka5429c062014-03-21 06:04:36 +0000343/// \brief Scan the instruction for expensive integer constants and record them
344/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000345void ConstantHoistingPass::collectConstantCandidates(
346 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000347 // Skip all cast instructions. They are visited indirectly later on.
348 if (Inst->isCast())
349 return;
350
351 // Can't handle inline asm. Skip it.
352 if (auto Call = dyn_cast<CallInst>(Inst))
353 if (isa<InlineAsm>(Call->getCalledValue()))
354 return;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000355
Tim Northover5c02f9a2016-04-13 23:08:27 +0000356 // Switch cases must remain constant, and if the value being tested is
357 // constant the entire thing should disappear.
358 if (isa<SwitchInst>(Inst))
359 return;
360
361 // Static allocas (constant size in the entry block) are handled by
362 // prologue/epilogue insertion so they're free anyway. We definitely don't
363 // want to make them non-constant.
364 auto AI = dyn_cast<AllocaInst>(Inst);
365 if (AI && AI->isStaticAlloca())
366 return;
367
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000368 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000369 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
370 Value *Opnd = Inst->getOperand(Idx);
371
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000372 // Visit constant integers.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000373 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000374 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000375 continue;
376 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000377
378 // Visit cast instructions that have constant integers.
379 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
380 // Only visit cast instructions, which have been skipped. All other
381 // instructions should have already been visited.
382 if (!CastInst->isCast())
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000383 continue;
384
Juergen Ributzka5429c062014-03-21 06:04:36 +0000385 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
386 // Pretend the constant is directly used by the instruction and ignore
387 // the cast instruction.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000388 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000389 continue;
390 }
391 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000392
393 // Visit constant expressions that have constant integers.
394 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
395 // Only visit constant cast expressions.
396 if (!ConstExpr->isCast())
397 continue;
398
399 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
400 // Pretend the constant is directly used by the instruction and ignore
401 // the constant expression.
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000402 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000403 continue;
404 }
405 }
406 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000407}
408
409/// \brief Collect all integer constants in the function that cannot be folded
410/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000411void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000412 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000413 for (BasicBlock &BB : Fn)
414 for (Instruction &Inst : BB)
415 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000416}
417
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000418// This helper function is necessary to deal with values that have different
419// bit widths (APInt Operator- does not like that). If the value cannot be
420// represented in uint64 we return an "empty" APInt. This is then interpreted
421// as the value is not in range.
Benjamin Kramer061f4a52017-01-13 14:39:03 +0000422static llvm::Optional<APInt> calculateOffsetDiff(const APInt &V1,
423 const APInt &V2) {
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000424 llvm::Optional<APInt> Res = None;
425 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
426 V1.getBitWidth() : V2.getBitWidth();
427 uint64_t LimVal1 = V1.getLimitedValue();
428 uint64_t LimVal2 = V2.getLimitedValue();
429
430 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
431 return Res;
432
433 uint64_t Diff = LimVal1 - LimVal2;
434 return APInt(BW, Diff, true);
435}
436
437// From a list of constants, one needs to picked as the base and the other
438// constants will be transformed into an offset from that base constant. The
439// question is which we can pick best? For example, consider these constants
440// and their number of uses:
441//
442// Constants| 2 | 4 | 12 | 42 |
443// NumUses | 3 | 2 | 8 | 7 |
444//
445// Selecting constant 12 because it has the most uses will generate negative
446// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
447// offsets lead to less optimal code generation, then there might be better
448// solutions. Suppose immediates in the range of 0..35 are most optimally
449// supported by the architecture, then selecting constant 2 is most optimal
450// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
451// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
452// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
453// selecting the base constant the range of the offsets is a very important
454// factor too that we take into account here. This algorithm calculates a total
455// costs for selecting a constant as the base and substract the costs if
456// immediates are out of range. It has quadratic complexity, so we call this
457// function only when we're optimising for size and there are less than 100
458// constants, we fall back to the straightforward algorithm otherwise
459// which does not do all the offset calculations.
460unsigned
461ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
462 ConstCandVecType::iterator E,
463 ConstCandVecType::iterator &MaxCostItr) {
464 unsigned NumUses = 0;
465
466 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
467 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
468 NumUses += ConstCand->Uses.size();
469 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
470 MaxCostItr = ConstCand;
471 }
472 return NumUses;
473 }
474
475 DEBUG(dbgs() << "== Maximize constants in range ==\n");
476 int MaxCost = -1;
477 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
478 auto Value = ConstCand->ConstInt->getValue();
479 Type *Ty = ConstCand->ConstInt->getType();
480 int Cost = 0;
481 NumUses += ConstCand->Uses.size();
482 DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue() << "\n");
483
484 for (auto User : ConstCand->Uses) {
485 unsigned Opcode = User.Inst->getOpcode();
486 unsigned OpndIdx = User.OpndIdx;
487 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
488 DEBUG(dbgs() << "Cost: " << Cost << "\n");
489
490 for (auto C2 = S; C2 != E; ++C2) {
491 llvm::Optional<APInt> Diff = calculateOffsetDiff(
492 C2->ConstInt->getValue(),
493 ConstCand->ConstInt->getValue());
494 if (Diff) {
495 const int ImmCosts =
496 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
497 Cost -= ImmCosts;
498 DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
499 << "has penalty: " << ImmCosts << "\n"
500 << "Adjusted cost: " << Cost << "\n");
501 }
502 }
503 }
504 DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
505 if (Cost > MaxCost) {
506 MaxCost = Cost;
507 MaxCostItr = ConstCand;
508 DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
509 << "\n");
510 }
511 }
512 return NumUses;
513}
514
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000515/// \brief Find the base constant within the given range and rebase all other
516/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000517void ConstantHoistingPass::findAndMakeBaseConstant(
518 ConstCandVecType::iterator S, ConstCandVecType::iterator E) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000519 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000520 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000521
522 // Don't hoist constants that have only one use.
523 if (NumUses <= 1)
524 return;
525
Juergen Ributzka5429c062014-03-21 06:04:36 +0000526 ConstantInfo ConstInfo;
527 ConstInfo.BaseConstant = MaxCostItr->ConstInt;
528 Type *Ty = ConstInfo.BaseConstant->getType();
529
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000530 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000531 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
532 APInt Diff = ConstCand->ConstInt->getValue() -
533 ConstInfo.BaseConstant->getValue();
534 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
535 ConstInfo.RebasedConstants.push_back(
536 RebasedConstantInfo(std::move(ConstCand->Uses), Offset));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000537 }
Benjamin Kramerc6cc58e2014-10-04 16:55:56 +0000538 ConstantVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000539}
540
Juergen Ributzka5429c062014-03-21 06:04:36 +0000541/// \brief Finds and combines constant candidates that can be easily
542/// rematerialized with an add from a common base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000543void ConstantHoistingPass::findBaseConstants() {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000544 // Sort the constants by value and type. This invalidates the mapping!
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000545 std::sort(ConstCandVec.begin(), ConstCandVec.end(),
546 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
547 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
548 return LHS.ConstInt->getType()->getBitWidth() <
549 RHS.ConstInt->getType()->getBitWidth();
550 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000551 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000552
Juergen Ributzka5429c062014-03-21 06:04:36 +0000553 // Simple linear scan through the sorted constant candidate vector for viable
554 // merge candidates.
555 auto MinValItr = ConstCandVec.begin();
556 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
557 CC != E; ++CC) {
558 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000559 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000560 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000561 if ((Diff.getBitWidth() <= 64) &&
562 TTI->isLegalAddImmediate(Diff.getSExtValue()))
563 continue;
564 }
565 // We either have now a different constant type or the constant is not in
566 // range of an add with immediate anymore.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000567 findAndMakeBaseConstant(MinValItr, CC);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000568 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000569 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000570 }
571 // Finalize the last base constant search.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000572 findAndMakeBaseConstant(MinValItr, ConstCandVec.end());
Juergen Ributzka46357932014-03-20 20:17:13 +0000573}
574
Juergen Ributzkae802d502014-03-22 01:49:27 +0000575/// \brief Updates the operand at Idx in instruction Inst with the result of
576/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000577/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000578/// required.
579/// \return The update will always succeed, but the return value indicated if
580/// Mat was used for the update or not.
581static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
582 if (auto PHI = dyn_cast<PHINode>(Inst)) {
583 // Check if any previous operand of the PHI node has the same incoming basic
584 // block. This is a very odd case that happens when the incoming basic block
585 // has a switch statement. In this case use the same value as the previous
586 // operand(s), otherwise we will fail verification due to different values.
587 // The values are actually the same, but the variable names are different
588 // and the verifier doesn't like that.
589 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
590 for (unsigned i = 0; i < Idx; ++i) {
591 if (PHI->getIncomingBlock(i) == IncomingBB) {
592 Value *IncomingVal = PHI->getIncomingValue(i);
593 Inst->setOperand(Idx, IncomingVal);
594 return false;
595 }
596 }
597 }
598
599 Inst->setOperand(Idx, Mat);
600 return true;
601}
602
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000603/// \brief Emit materialization code for all rebased constants and update their
604/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000605void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
606 Constant *Offset,
607 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000608 Instruction *Mat = Base;
609 if (Offset) {
610 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
611 ConstUser.OpndIdx);
612 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
613 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000614
Juergen Ributzka5429c062014-03-21 06:04:36 +0000615 DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
616 << " + " << *Offset << ") in BB "
617 << Mat->getParent()->getName() << '\n' << *Mat << '\n');
618 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
619 }
620 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000621
Juergen Ributzka5429c062014-03-21 06:04:36 +0000622 // Visit constant integer.
623 if (isa<ConstantInt>(Opnd)) {
624 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000625 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
626 Mat->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000627 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000628 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000629 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000630
Juergen Ributzka5429c062014-03-21 06:04:36 +0000631 // Visit cast instruction.
632 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
633 assert(CastInst->isCast() && "Expected an cast instruction!");
634 // Check if we already have visited this cast instruction before to avoid
635 // unnecessary cloning.
636 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
637 if (!ClonedCastInst) {
638 ClonedCastInst = CastInst->clone();
639 ClonedCastInst->setOperand(0, Mat);
640 ClonedCastInst->insertAfter(CastInst);
641 // Use the same debug location as the original cast instruction.
642 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Juergen Ributzkaa1444b32014-04-22 18:06:51 +0000643 DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
644 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000645 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000646
647 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000648 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000649 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
650 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000651 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000652
653 // Visit constant expression.
654 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
655 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
656 ConstExprInst->setOperand(0, Mat);
657 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
658 ConstUser.OpndIdx));
659
660 // Use the same debug location as the instruction we are about to update.
661 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
662
663 DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
664 << "From : " << *ConstExpr << '\n');
665 DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000666 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
667 ConstExprInst->eraseFromParent();
668 if (Offset)
669 Mat->eraseFromParent();
670 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000671 DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
672 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000673 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000674}
675
676/// \brief Hoist and hide the base constant behind a bitcast and emit
677/// materialization code for derived constants.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000678bool ConstantHoistingPass::emitBaseConstants() {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000679 bool MadeChange = false;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000680 for (auto const &ConstInfo : ConstantVec) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000681 // Hoist and hide the base constant behind a bitcast.
Wei Mi337d4d92017-04-21 15:50:16 +0000682 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
683 assert(!IPSet.empty() && "IPSet is empty");
684
685 unsigned UsesNum = 0;
686 unsigned ReBasesNum = 0;
687 for (Instruction *IP : IPSet) {
688 IntegerType *Ty = ConstInfo.BaseConstant->getType();
689 Instruction *Base =
690 new BitCastInst(ConstInfo.BaseConstant, Ty, "const", IP);
691 DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseConstant
692 << ") to BB " << IP->getParent()->getName() << '\n'
693 << *Base << '\n');
694
695 // Emit materialization code for all rebased constants.
696 unsigned Uses = 0;
697 for (auto const &RCI : ConstInfo.RebasedConstants) {
698 for (auto const &U : RCI.Uses) {
699 Uses++;
700 BasicBlock *OrigMatInsertBB =
701 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
702 // If Base constant is to be inserted in multiple places,
703 // generate rebase for U using the Base dominating U.
704 if (IPSet.size() == 1 ||
705 DT->dominates(Base->getParent(), OrigMatInsertBB)) {
706 emitBaseConstants(Base, RCI.Offset, U);
707 ReBasesNum++;
708 }
709 }
710 }
711 UsesNum = Uses;
712
713 // Use the same debug location as the last user of the constant.
714 assert(!Base->use_empty() && "The use list is empty!?");
715 assert(isa<Instruction>(Base->user_back()) &&
716 "All uses should be instructions.");
717 Base->setDebugLoc(cast<Instruction>(Base->user_back())->getDebugLoc());
718 }
719 (void)UsesNum;
720 (void)ReBasesNum;
721 // Expect all uses are rebased after rebase is done.
722 assert(UsesNum == ReBasesNum && "Not all uses are rebased");
723
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000724 NumConstantsHoisted++;
725
Wei Mi337d4d92017-04-21 15:50:16 +0000726 // Base constant is also included in ConstInfo.RebasedConstants, so
727 // deduct 1 from ConstInfo.RebasedConstants.size().
728 NumConstantsRebased = ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000729
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000730 MadeChange = true;
731 }
732 return MadeChange;
733}
734
Juergen Ributzka5429c062014-03-21 06:04:36 +0000735/// \brief Check all cast instructions we made a copy of and remove them if they
736/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000737void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000738 for (auto const &I : ClonedCastMap)
739 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000740 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000741}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000742
Juergen Ributzka5429c062014-03-21 06:04:36 +0000743/// \brief Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000744bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000745 DominatorTree &DT, BlockFrequencyInfo *BFI,
746 BasicBlock &Entry) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000747 this->TTI = &TTI;
748 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000749 this->BFI = BFI;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000750 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000751 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000752 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000753
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000754 // There are no constant candidates to worry about.
755 if (ConstCandVec.empty())
756 return false;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000757
758 // Combine constants that can be easily materialized with an add from a common
759 // base constant.
Juergen Ributzkab8489b32014-03-21 06:04:33 +0000760 findBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000761
Juergen Ributzka5429c062014-03-21 06:04:36 +0000762 // There are no constants to emit.
763 if (ConstantVec.empty())
764 return false;
765
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000766 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000767 // constants.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000768 bool MadeChange = emitBaseConstants();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000769
Juergen Ributzka5429c062014-03-21 06:04:36 +0000770 // Cleanup dead instructions.
771 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000772
773 return MadeChange;
774}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000775
776PreservedAnalyses ConstantHoistingPass::run(Function &F,
777 FunctionAnalysisManager &AM) {
778 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
779 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000780 auto BFI = ConstHoistWithBlockFrequency
781 ? &AM.getResult<BlockFrequencyAnalysis>(F)
782 : nullptr;
783 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000784 return PreservedAnalyses::all();
785
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000786 PreservedAnalyses PA;
787 PA.preserveSet<CFGAnalyses>();
788 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000789}