blob: 1af14ea73b8a7dc9851c51fd4f064ee91ae77d78 [file] [log] [blame]
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00001//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass identifies expensive constants to hoist and coalesces them to
10// better prepare it for SelectionDAG-based code generation. This works around
11// the limitations of the basic-block-at-a-time approach.
12//
13// First it scans all instructions for integer constants and calculates its
14// cost. If the constant can be folded into the instruction (the cost is
15// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
16// consider it expensive and leave it alone. This is the default behavior and
17// the default implementation of getIntImmCost will always return TCC_Free.
18//
19// If the cost is more than TCC_BASIC, then the integer constant can't be folded
20// into the instruction and it might be beneficial to hoist the constant.
21// Similar constants are coalesced to reduce register pressure and
22// materialization code.
23//
24// When a constant is hoisted, it is also hidden behind a bitcast to force it to
25// be live-out of the basic block. Otherwise the constant would be just
26// duplicated and each basic block would have its own copy in the SelectionDAG.
27// The SelectionDAG recognizes such constants as opaque and doesn't perform
28// certain transformations on them, which would create a new expensive constant.
29//
30// This optimization is only applied to integer constants in instructions and
Juergen Ributzkaf0dff492014-03-21 06:04:45 +000031// simple (this means not nested) constant cast expressions. For example:
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000032// %0 = load i64* inttoptr (i64 big_constant to i64*)
33//===----------------------------------------------------------------------===//
34
Michael Kuperstein071d8302016-07-02 00:16:47 +000035#include "llvm/Transforms/Scalar/ConstantHoisting.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000036#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/None.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/SmallPtrSet.h"
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +000041#include "llvm/ADT/SmallVector.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000042#include "llvm/ADT/Statistic.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000043#include "llvm/Analysis/BlockFrequencyInfo.h"
44#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000045#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000046#include "llvm/IR/BasicBlock.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000047#include "llvm/IR/Constants.h"
David Blaikie2be39222018-03-21 22:34:23 +000048#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000049#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000054#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000055#include "llvm/IR/Value.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000056#include "llvm/Pass.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000057#include "llvm/Support/BlockFrequency.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/CommandLine.h"
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000060#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Support/raw_ostream.h"
Michael Kuperstein071d8302016-07-02 00:16:47 +000062#include "llvm/Transforms/Scalar.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000063#include <algorithm>
64#include <cassert>
65#include <cstdint>
66#include <iterator>
NAKAMURA Takumi99aa6e12014-04-30 06:44:50 +000067#include <tuple>
Eugene Zelenko8002c502017-09-13 21:43:53 +000068#include <utility>
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000069
70using namespace llvm;
Michael Kuperstein071d8302016-07-02 00:16:47 +000071using namespace consthoist;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000072
Chandler Carruth964daaa2014-04-22 02:55:47 +000073#define DEBUG_TYPE "consthoist"
74
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000075STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
76STATISTIC(NumConstantsRebased, "Number of constants rebased");
77
Wei Mi337d4d92017-04-21 15:50:16 +000078static cl::opt<bool> ConstHoistWithBlockFrequency(
Wei Mi75867552017-07-07 00:11:05 +000079 "consthoist-with-block-frequency", cl::init(true), cl::Hidden,
Wei Mi337d4d92017-04-21 15:50:16 +000080 cl::desc("Enable the use of the block frequency analysis to reduce the "
81 "chance to execute const materialization more frequently than "
82 "without hoisting."));
83
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +000084static cl::opt<bool> ConstHoistGEP(
85 "consthoist-gep", cl::init(false), cl::Hidden,
86 cl::desc("Try hoisting constant gep expressions"));
87
Zhaoshi Zheng95710332018-09-26 00:59:09 +000088static cl::opt<unsigned>
89MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
90 cl::desc("Do not rebase if number of dependent constants of a Base is less "
91 "than this number."),
92 cl::init(0), cl::Hidden);
93
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000094namespace {
Eugene Zelenko8002c502017-09-13 21:43:53 +000095
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000096/// The constant hoisting pass.
Michael Kuperstein071d8302016-07-02 00:16:47 +000097class ConstantHoistingLegacyPass : public FunctionPass {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +000098public:
99 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +0000100
Michael Kuperstein071d8302016-07-02 00:16:47 +0000101 ConstantHoistingLegacyPass() : FunctionPass(ID) {
102 initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000103 }
104
Juergen Ributzka5429c062014-03-21 06:04:36 +0000105 bool runOnFunction(Function &Fn) override;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000106
Mehdi Amini117296c2016-10-01 02:56:57 +0000107 StringRef getPassName() const override { return "Constant Hoisting"; }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000108
Craig Topper3e4c6972014-03-05 09:10:37 +0000109 void getAnalysisUsage(AnalysisUsage &AU) const override {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000110 AU.setPreservesCFG();
Wei Mi337d4d92017-04-21 15:50:16 +0000111 if (ConstHoistWithBlockFrequency)
112 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000113 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000114 AU.addRequired<TargetTransformInfoWrapperPass>();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000115 }
116
117private:
Michael Kuperstein071d8302016-07-02 00:16:47 +0000118 ConstantHoistingPass Impl;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000119};
Eugene Zelenko8002c502017-09-13 21:43:53 +0000120
121} // end anonymous namespace
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000122
Michael Kuperstein071d8302016-07-02 00:16:47 +0000123char ConstantHoistingLegacyPass::ID = 0;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000124
Michael Kuperstein071d8302016-07-02 00:16:47 +0000125INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
126 "Constant Hoisting", false, false)
Wei Mi337d4d92017-04-21 15:50:16 +0000127INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000128INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth705b1852015-01-31 03:43:40 +0000129INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Michael Kuperstein071d8302016-07-02 00:16:47 +0000130INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
131 "Constant Hoisting", false, false)
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000132
133FunctionPass *llvm::createConstantHoistingPass() {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000134 return new ConstantHoistingLegacyPass();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000135}
136
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000137/// Perform the constant hoisting optimization for the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000138bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000139 if (skipFunction(Fn))
Andrea Di Biagiof54432382015-02-14 15:11:48 +0000140 return false;
141
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000142 LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
143 LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000144
Wei Mi337d4d92017-04-21 15:50:16 +0000145 bool MadeChange =
146 Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
147 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
148 ConstHoistWithBlockFrequency
149 ? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
150 : nullptr,
151 Fn.getEntryBlock());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000152
153 if (MadeChange) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000154 LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
155 << Fn.getName() << '\n');
156 LLVM_DEBUG(dbgs() << Fn);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000157 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000158 LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000159
Juergen Ributzka5429c062014-03-21 06:04:36 +0000160 return MadeChange;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000161}
162
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000163/// Find the constant materialization insertion point.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000164Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
165 unsigned Idx) const {
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000166 // If the operand is a cast instruction, then we have to materialize the
167 // constant before the cast instruction.
168 if (Idx != ~0U) {
169 Value *Opnd = Inst->getOperand(Idx);
170 if (auto CastInst = dyn_cast<Instruction>(Opnd))
171 if (CastInst->isCast())
172 return CastInst;
173 }
174
175 // The simple and common case. This also includes constant expressions.
David Majnemerba275f92015-08-19 19:54:02 +0000176 if (!isa<PHINode>(Inst) && !Inst->isEHPad())
Juergen Ributzka5429c062014-03-21 06:04:36 +0000177 return Inst;
178
David Majnemerba275f92015-08-19 19:54:02 +0000179 // We can't insert directly before a phi node or an eh pad. Insert before
Juergen Ributzka5429c062014-03-21 06:04:36 +0000180 // the terminator of the incoming or dominating block.
181 assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
182 if (Idx != ~0U && isa<PHINode>(Inst))
183 return cast<PHINode>(Inst)->getIncomingBlock(Idx)->getTerminator();
184
Reid Klecknerd80b69f2017-03-01 22:41:12 +0000185 // This must be an EH pad. Iterate over immediate dominators until we find a
186 // non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
187 // and terminators.
188 auto IDom = DT->getNode(Inst->getParent())->getIDom();
189 while (IDom->getBlock()->isEHPad()) {
190 assert(Entry != IDom->getBlock() && "eh pad in entry block");
191 IDom = IDom->getIDom();
192 }
193
194 return IDom->getBlock()->getTerminator();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000195}
196
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000197/// Given \p BBs as input, find another set of BBs which collectively
Wei Mi337d4d92017-04-21 15:50:16 +0000198/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
199/// set found in \p BBs.
Benjamin Kramerdebb3c32017-05-26 20:09:00 +0000200static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
201 BasicBlock *Entry,
202 SmallPtrSet<BasicBlock *, 8> &BBs) {
Wei Mi337d4d92017-04-21 15:50:16 +0000203 assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
204 // Nodes on the current path to the root.
205 SmallPtrSet<BasicBlock *, 8> Path;
206 // Candidates includes any block 'BB' in set 'BBs' that is not strictly
207 // dominated by any other blocks in set 'BBs', and all nodes in the path
208 // in the dominator tree from Entry to 'BB'.
209 SmallPtrSet<BasicBlock *, 16> Candidates;
210 for (auto BB : BBs) {
211 Path.clear();
212 // Walk up the dominator tree until Entry or another BB in BBs
213 // is reached. Insert the nodes on the way to the Path.
214 BasicBlock *Node = BB;
215 // The "Path" is a candidate path to be added into Candidates set.
216 bool isCandidate = false;
217 do {
218 Path.insert(Node);
219 if (Node == Entry || Candidates.count(Node)) {
220 isCandidate = true;
221 break;
222 }
223 assert(DT.getNode(Node)->getIDom() &&
224 "Entry doens't dominate current Node");
225 Node = DT.getNode(Node)->getIDom()->getBlock();
226 } while (!BBs.count(Node));
227
228 // If isCandidate is false, Node is another Block in BBs dominating
229 // current 'BB'. Drop the nodes on the Path.
230 if (!isCandidate)
231 continue;
232
233 // Add nodes on the Path into Candidates.
234 Candidates.insert(Path.begin(), Path.end());
235 }
236
237 // Sort the nodes in Candidates in top-down order and save the nodes
238 // in Orders.
239 unsigned Idx = 0;
240 SmallVector<BasicBlock *, 16> Orders;
241 Orders.push_back(Entry);
242 while (Idx != Orders.size()) {
243 BasicBlock *Node = Orders[Idx++];
244 for (auto ChildDomNode : DT.getNode(Node)->getChildren()) {
245 if (Candidates.count(ChildDomNode->getBlock()))
246 Orders.push_back(ChildDomNode->getBlock());
247 }
248 }
249
250 // Visit Orders in bottom-up order.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000251 using InsertPtsCostPair =
252 std::pair<SmallPtrSet<BasicBlock *, 16>, BlockFrequency>;
253
Wei Mi337d4d92017-04-21 15:50:16 +0000254 // InsertPtsMap is a map from a BB to the best insertion points for the
255 // subtree of BB (subtree not including the BB itself).
256 DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
257 InsertPtsMap.reserve(Orders.size() + 1);
258 for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
259 BasicBlock *Node = *RIt;
260 bool NodeInBBs = BBs.count(Node);
261 SmallPtrSet<BasicBlock *, 16> &InsertPts = InsertPtsMap[Node].first;
262 BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
263
264 // Return the optimal insert points in BBs.
265 if (Node == Entry) {
266 BBs.clear();
Wei Mi20526b22017-07-06 22:32:27 +0000267 if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
268 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
Wei Mi337d4d92017-04-21 15:50:16 +0000269 BBs.insert(Entry);
270 else
271 BBs.insert(InsertPts.begin(), InsertPts.end());
272 break;
273 }
274
275 BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
276 // Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
277 // will update its parent's ParentInsertPts and ParentPtsFreq.
278 SmallPtrSet<BasicBlock *, 16> &ParentInsertPts = InsertPtsMap[Parent].first;
279 BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
280 // Choose to insert in Node or in subtree of Node.
Wei Mi20526b22017-07-06 22:32:27 +0000281 // Don't hoist to EHPad because we may not find a proper place to insert
282 // in EHPad.
283 // If the total frequency of InsertPts is the same as the frequency of the
284 // target Node, and InsertPts contains more than one nodes, choose hoisting
285 // to reduce code size.
286 if (NodeInBBs ||
287 (!Node->isEHPad() &&
288 (InsertPtsFreq > BFI.getBlockFreq(Node) ||
289 (InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
Wei Mi337d4d92017-04-21 15:50:16 +0000290 ParentInsertPts.insert(Node);
291 ParentPtsFreq += BFI.getBlockFreq(Node);
292 } else {
293 ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
294 ParentPtsFreq += InsertPtsFreq;
295 }
296 }
297}
298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299/// Find an insertion point that dominates all uses.
Wei Mi337d4d92017-04-21 15:50:16 +0000300SmallPtrSet<Instruction *, 8> ConstantHoistingPass::findConstantInsertionPoint(
Michael Kuperstein071d8302016-07-02 00:16:47 +0000301 const ConstantInfo &ConstInfo) const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000302 assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000303 // Collect all basic blocks.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000304 SmallPtrSet<BasicBlock *, 8> BBs;
Wei Mi337d4d92017-04-21 15:50:16 +0000305 SmallPtrSet<Instruction *, 8> InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000306 for (auto const &RCI : ConstInfo.RebasedConstants)
Juergen Ributzkac81000b2014-04-03 01:38:47 +0000307 for (auto const &U : RCI.Uses)
Juergen Ributzka575bcb72014-04-22 18:06:58 +0000308 BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
Juergen Ributzka5429c062014-03-21 06:04:36 +0000309
Wei Mi337d4d92017-04-21 15:50:16 +0000310 if (BBs.count(Entry)) {
311 InsertPts.insert(&Entry->front());
312 return InsertPts;
313 }
314
315 if (BFI) {
316 findBestInsertionSet(*DT, *BFI, Entry, BBs);
317 for (auto BB : BBs) {
318 BasicBlock::iterator InsertPt = BB->begin();
319 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
320 ;
321 InsertPts.insert(&*InsertPt);
322 }
323 return InsertPts;
324 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000325
326 while (BBs.size() >= 2) {
327 BasicBlock *BB, *BB1, *BB2;
328 BB1 = *BBs.begin();
329 BB2 = *std::next(BBs.begin());
330 BB = DT->findNearestCommonDominator(BB1, BB2);
Wei Mi337d4d92017-04-21 15:50:16 +0000331 if (BB == Entry) {
332 InsertPts.insert(&Entry->front());
333 return InsertPts;
334 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000335 BBs.erase(BB1);
336 BBs.erase(BB2);
337 BBs.insert(BB);
338 }
339 assert((BBs.size() == 1) && "Expected only one element.");
340 Instruction &FirstInst = (*BBs.begin())->front();
Wei Mi337d4d92017-04-21 15:50:16 +0000341 InsertPts.insert(findMatInsertPt(&FirstInst));
342 return InsertPts;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000343}
344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000345/// Record constant integer ConstInt for instruction Inst at operand
Juergen Ributzka5429c062014-03-21 06:04:36 +0000346/// index Idx.
347///
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000348/// The operand at index Idx is not necessarily the constant integer itself. It
Juergen Ributzka5429c062014-03-21 06:04:36 +0000349/// could also be a cast instruction or a constant expression that uses the
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000350/// constant integer.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000351void ConstantHoistingPass::collectConstantCandidates(
352 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
353 ConstantInt *ConstInt) {
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000354 unsigned Cost;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000355 // Ask the target about the cost of materializing the constant for the given
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000356 // instruction and operand index.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000357 if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000358 Cost = TTI->getIntImmCost(IntrInst->getIntrinsicID(), Idx,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000359 ConstInt->getValue(), ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000360 else
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000361 Cost = TTI->getIntImmCost(Inst->getOpcode(), Idx, ConstInt->getValue(),
Juergen Ributzka5429c062014-03-21 06:04:36 +0000362 ConstInt->getType());
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000363
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000364 // Ignore cheap integer constants.
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000365 if (Cost > TargetTransformInfo::TCC_Basic) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000366 ConstCandMapType::iterator Itr;
367 bool Inserted;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000368 ConstPtrUnionType Cand = ConstInt;
369 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000370 if (Inserted) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000371 ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
372 Itr->second = ConstIntCandVec.size() - 1;
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000373 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000374 ConstIntCandVec[Itr->second].addUser(Inst, Idx, Cost);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000375 LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
376 << "Collect constant " << *ConstInt << " from " << *Inst
Juergen Ributzka5429c062014-03-21 06:04:36 +0000377 << " with cost " << Cost << '\n';
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000378 else dbgs() << "Collect constant " << *ConstInt
379 << " indirectly from " << *Inst << " via "
380 << *Inst->getOperand(Idx) << " with cost " << Cost
381 << '\n';);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000382 }
383}
384
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000385/// Record constant GEP expression for instruction Inst at operand index Idx.
386void ConstantHoistingPass::collectConstantCandidates(
387 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
388 ConstantExpr *ConstExpr) {
389 // TODO: Handle vector GEPs
390 if (ConstExpr->getType()->isVectorTy())
391 return;
392
393 GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
394 if (!BaseGV)
395 return;
396
397 // Get offset from the base GV.
398 PointerType *GVPtrTy = dyn_cast<PointerType>(BaseGV->getType());
399 IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
400 APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
401 auto *GEPO = cast<GEPOperator>(ConstExpr);
402 if (!GEPO->accumulateConstantOffset(*DL, Offset))
403 return;
404
405 if (!Offset.isIntN(32))
406 return;
407
408 // A constant GEP expression that has a GlobalVariable as base pointer is
409 // usually lowered to a load from constant pool. Such operation is unlikely
410 // to be cheaper than compute it by <Base + Offset>, which can be lowered to
411 // an ADD instruction or folded into Load/Store instruction.
412 int Cost = TTI->getIntImmCost(Instruction::Add, 1, Offset, PtrIntTy);
413 ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
414 ConstCandMapType::iterator Itr;
415 bool Inserted;
416 ConstPtrUnionType Cand = ConstExpr;
417 std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
418 if (Inserted) {
419 ExprCandVec.push_back(ConstantCandidate(
420 ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
421 ConstExpr));
422 Itr->second = ExprCandVec.size() - 1;
423 }
424 ExprCandVec[Itr->second].addUser(Inst, Idx, Cost);
425}
426
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000427/// Check the operand for instruction Inst at index Idx.
Leo Li20fbad92017-06-29 17:03:34 +0000428void ConstantHoistingPass::collectConstantCandidates(
429 ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
430 Value *Opnd = Inst->getOperand(Idx);
431
432 // Visit constant integers.
433 if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
434 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
435 return;
436 }
437
438 // Visit cast instructions that have constant integers.
439 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
440 // Only visit cast instructions, which have been skipped. All other
441 // instructions should have already been visited.
442 if (!CastInst->isCast())
443 return;
444
445 if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
446 // Pretend the constant is directly used by the instruction and ignore
447 // the cast instruction.
448 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
449 return;
450 }
451 }
452
453 // Visit constant expressions that have constant integers.
454 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000455 // Handle constant gep expressions.
456 if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
457 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
458
Leo Li20fbad92017-06-29 17:03:34 +0000459 // Only visit constant cast expressions.
460 if (!ConstExpr->isCast())
461 return;
462
463 if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
464 // Pretend the constant is directly used by the instruction and ignore
465 // the constant expression.
466 collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
467 return;
468 }
469 }
470}
471
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000472/// Scan the instruction for expensive integer constants and record them
Juergen Ributzka5429c062014-03-21 06:04:36 +0000473/// in the constant candidate vector.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000474void ConstantHoistingPass::collectConstantCandidates(
475 ConstCandMapType &ConstCandMap, Instruction *Inst) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000476 // Skip all cast instructions. They are visited indirectly later on.
477 if (Inst->isCast())
478 return;
479
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000480 // Scan all operands.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000481 for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
Leo Li93abd7d2017-07-10 20:45:34 +0000482 // The cost of materializing the constants (defined in
483 // `TargetTransformInfo::getIntImmCost`) for instructions which only take
484 // constant variables is lower than `TargetTransformInfo::TCC_Basic`. So
485 // it's safe for us to collect constant candidates from all IntrinsicInsts.
486 if (canReplaceOperandWithVariable(Inst, Idx) || isa<IntrinsicInst>(Inst)) {
487 collectConstantCandidates(ConstCandMap, Inst, Idx);
488 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000489 } // end of for all operands
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000490}
491
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000492/// Collect all integer constants in the function that cannot be folded
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000493/// into an instruction itself.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000494void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
Juergen Ributzka7be410f2014-03-25 21:21:10 +0000495 ConstCandMapType ConstCandMap;
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000496 for (BasicBlock &BB : Fn)
497 for (Instruction &Inst : BB)
498 collectConstantCandidates(ConstCandMap, &Inst);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000499}
500
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000501// This helper function is necessary to deal with values that have different
502// bit widths (APInt Operator- does not like that). If the value cannot be
503// represented in uint64 we return an "empty" APInt. This is then interpreted
504// as the value is not in range.
Eugene Zelenko8002c502017-09-13 21:43:53 +0000505static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
506 Optional<APInt> Res = None;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000507 unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
508 V1.getBitWidth() : V2.getBitWidth();
509 uint64_t LimVal1 = V1.getLimitedValue();
510 uint64_t LimVal2 = V2.getLimitedValue();
511
512 if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
513 return Res;
514
515 uint64_t Diff = LimVal1 - LimVal2;
516 return APInt(BW, Diff, true);
517}
518
519// From a list of constants, one needs to picked as the base and the other
520// constants will be transformed into an offset from that base constant. The
521// question is which we can pick best? For example, consider these constants
522// and their number of uses:
523//
524// Constants| 2 | 4 | 12 | 42 |
525// NumUses | 3 | 2 | 8 | 7 |
526//
527// Selecting constant 12 because it has the most uses will generate negative
528// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
529// offsets lead to less optimal code generation, then there might be better
530// solutions. Suppose immediates in the range of 0..35 are most optimally
531// supported by the architecture, then selecting constant 2 is most optimal
532// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
533// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
534// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
535// selecting the base constant the range of the offsets is a very important
536// factor too that we take into account here. This algorithm calculates a total
537// costs for selecting a constant as the base and substract the costs if
538// immediates are out of range. It has quadratic complexity, so we call this
539// function only when we're optimising for size and there are less than 100
540// constants, we fall back to the straightforward algorithm otherwise
541// which does not do all the offset calculations.
542unsigned
543ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
544 ConstCandVecType::iterator E,
545 ConstCandVecType::iterator &MaxCostItr) {
546 unsigned NumUses = 0;
547
548 if(!Entry->getParent()->optForSize() || std::distance(S,E) > 100) {
549 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
550 NumUses += ConstCand->Uses.size();
551 if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
552 MaxCostItr = ConstCand;
553 }
554 return NumUses;
555 }
556
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000557 LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000558 int MaxCost = -1;
559 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
560 auto Value = ConstCand->ConstInt->getValue();
561 Type *Ty = ConstCand->ConstInt->getType();
562 int Cost = 0;
563 NumUses += ConstCand->Uses.size();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
565 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000566
567 for (auto User : ConstCand->Uses) {
568 unsigned Opcode = User.Inst->getOpcode();
569 unsigned OpndIdx = User.OpndIdx;
570 Cost += TTI->getIntImmCost(Opcode, OpndIdx, Value, Ty);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000572
573 for (auto C2 = S; C2 != E; ++C2) {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000574 Optional<APInt> Diff = calculateOffsetDiff(
575 C2->ConstInt->getValue(),
576 ConstCand->ConstInt->getValue());
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000577 if (Diff) {
578 const int ImmCosts =
579 TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
580 Cost -= ImmCosts;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
582 << "has penalty: " << ImmCosts << "\n"
583 << "Adjusted cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000584 }
585 }
586 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000587 LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000588 if (Cost > MaxCost) {
589 MaxCost = Cost;
590 MaxCostItr = ConstCand;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
592 << "\n");
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000593 }
594 }
595 return NumUses;
596}
597
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000598/// Find the base constant within the given range and rebase all other
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000599/// constants with respect to the base constant.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000600void ConstantHoistingPass::findAndMakeBaseConstant(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000601 ConstCandVecType::iterator S, ConstCandVecType::iterator E,
602 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000603 auto MaxCostItr = S;
Sjoerd Meijer38c2cd02016-07-14 07:44:20 +0000604 unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000605
606 // Don't hoist constants that have only one use.
607 if (NumUses <= 1)
608 return;
609
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000610 ConstantInt *ConstInt = MaxCostItr->ConstInt;
611 ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000612 ConstantInfo ConstInfo;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000613 ConstInfo.BaseInt = ConstInt;
614 ConstInfo.BaseExpr = ConstExpr;
615 Type *Ty = ConstInt->getType();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000616
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000617 // Rebase the constants with respect to the base constant.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000618 for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000619 APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000620 Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000621 Type *ConstTy =
622 ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
Juergen Ributzka5429c062014-03-21 06:04:36 +0000623 ConstInfo.RebasedConstants.push_back(
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000624 RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000625 }
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000626 ConstInfoVec.push_back(std::move(ConstInfo));
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000627}
628
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000629/// Finds and combines constant candidates that can be easily
Juergen Ributzka5429c062014-03-21 06:04:36 +0000630/// rematerialized with an add from a common base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000631void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
632 // If BaseGV is nullptr, find base among candidate constant integers;
633 // Otherwise find base among constant GEPs that share the same BaseGV.
634 ConstCandVecType &ConstCandVec = BaseGV ?
635 ConstGEPCandMap[BaseGV] : ConstIntCandVec;
636 ConstInfoVecType &ConstInfoVec = BaseGV ?
637 ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
638
Juergen Ributzka5429c062014-03-21 06:04:36 +0000639 // Sort the constants by value and type. This invalidates the mapping!
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000640 std::stable_sort(ConstCandVec.begin(), ConstCandVec.end(),
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000641 [](const ConstantCandidate &LHS, const ConstantCandidate &RHS) {
Juergen Ributzkaa29a5b82014-03-21 06:04:30 +0000642 if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
643 return LHS.ConstInt->getType()->getBitWidth() <
644 RHS.ConstInt->getType()->getBitWidth();
645 return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
Juergen Ributzka46357932014-03-20 20:17:13 +0000646 });
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000647
Juergen Ributzka5429c062014-03-21 06:04:36 +0000648 // Simple linear scan through the sorted constant candidate vector for viable
649 // merge candidates.
650 auto MinValItr = ConstCandVec.begin();
651 for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
652 CC != E; ++CC) {
653 if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000654 Type *MemUseValTy = nullptr;
655 for (auto &U : CC->Uses) {
656 auto *UI = U.Inst;
657 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
658 MemUseValTy = LI->getType();
659 break;
660 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
661 // Make sure the constant is used as pointer operand of the StoreInst.
662 if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
663 MemUseValTy = SI->getValueOperand()->getType();
664 break;
665 }
666 }
667 }
668
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000669 // Check if the constant is in range of an add with immediate.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000670 APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000671 if ((Diff.getBitWidth() <= 64) &&
Zhaoshi Zheng35818e22018-08-28 23:00:59 +0000672 TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
673 // Check if Diff can be used as offset in addressing mode of the user
674 // memory instruction.
675 (!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
676 /*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
677 /*HasBaseReg*/true, /*Scale*/0)))
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000678 continue;
679 }
680 // We either have now a different constant type or the constant is not in
681 // range of an add with immediate anymore.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000682 findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000683 // Start a new base constant search.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000684 MinValItr = CC;
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000685 }
686 // Finalize the last base constant search.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000687 findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
Juergen Ributzka46357932014-03-20 20:17:13 +0000688}
689
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000690/// Updates the operand at Idx in instruction Inst with the result of
Juergen Ributzkae802d502014-03-22 01:49:27 +0000691/// instruction Mat. If the instruction is a PHI node then special
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000692/// handling for duplicate values form the same incoming basic block is
Juergen Ributzkae802d502014-03-22 01:49:27 +0000693/// required.
694/// \return The update will always succeed, but the return value indicated if
695/// Mat was used for the update or not.
696static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
697 if (auto PHI = dyn_cast<PHINode>(Inst)) {
698 // Check if any previous operand of the PHI node has the same incoming basic
699 // block. This is a very odd case that happens when the incoming basic block
700 // has a switch statement. In this case use the same value as the previous
701 // operand(s), otherwise we will fail verification due to different values.
702 // The values are actually the same, but the variable names are different
703 // and the verifier doesn't like that.
704 BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
705 for (unsigned i = 0; i < Idx; ++i) {
706 if (PHI->getIncomingBlock(i) == IncomingBB) {
707 Value *IncomingVal = PHI->getIncomingValue(i);
708 Inst->setOperand(Idx, IncomingVal);
709 return false;
710 }
711 }
712 }
713
714 Inst->setOperand(Idx, Mat);
715 return true;
716}
717
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000718/// Emit materialization code for all rebased constants and update their
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000719/// users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000720void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
721 Constant *Offset,
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000722 Type *Ty,
Michael Kuperstein071d8302016-07-02 00:16:47 +0000723 const ConstantUser &ConstUser) {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000724 Instruction *Mat = Base;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000725
726 // The same offset can be dereferenced to different types in nested struct.
727 if (!Offset && Ty && Ty != Base->getType())
728 Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
729
Juergen Ributzka5429c062014-03-21 06:04:36 +0000730 if (Offset) {
731 Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
732 ConstUser.OpndIdx);
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000733 if (Ty) {
734 // Constant being rebased is a ConstantExpr.
735 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
736 cast<PointerType>(Ty)->getAddressSpace());
737 Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
738 Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
739 Offset, "mat_gep", InsertionPt);
740 Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
741 } else
742 // Constant being rebased is a ConstantInt.
743 Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
Juergen Ributzka5429c062014-03-21 06:04:36 +0000744 "const_mat", InsertionPt);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000745
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000746 LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
747 << " + " << *Offset << ") in BB "
748 << Mat->getParent()->getName() << '\n'
749 << *Mat << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000750 Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
751 }
752 Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000753
Juergen Ributzka5429c062014-03-21 06:04:36 +0000754 // Visit constant integer.
755 if (isa<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000756 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000757 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
758 Mat->eraseFromParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000760 return;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000761 }
Juergen Ributzka6dab5202014-03-20 19:55:52 +0000762
Juergen Ributzka5429c062014-03-21 06:04:36 +0000763 // Visit cast instruction.
764 if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
765 assert(CastInst->isCast() && "Expected an cast instruction!");
766 // Check if we already have visited this cast instruction before to avoid
767 // unnecessary cloning.
768 Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
769 if (!ClonedCastInst) {
770 ClonedCastInst = CastInst->clone();
771 ClonedCastInst->setOperand(0, Mat);
772 ClonedCastInst->insertAfter(CastInst);
773 // Use the same debug location as the original cast instruction.
774 ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000775 LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
776 << "To : " << *ClonedCastInst << '\n');
Juergen Ributzka46357932014-03-20 20:17:13 +0000777 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000778
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000779 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000780 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000781 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000782 return;
Juergen Ributzka46357932014-03-20 20:17:13 +0000783 }
Juergen Ributzka5429c062014-03-21 06:04:36 +0000784
785 // Visit constant expression.
786 if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000787 if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
788 // Operand is a ConstantGEP, replace it.
789 updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
790 return;
791 }
792
793 // Aside from constant GEPs, only constant cast expressions are collected.
794 assert(ConstExpr->isCast() && "ConstExpr should be a cast");
Juergen Ributzka5429c062014-03-21 06:04:36 +0000795 Instruction *ConstExprInst = ConstExpr->getAsInstruction();
796 ConstExprInst->setOperand(0, Mat);
797 ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
798 ConstUser.OpndIdx));
799
800 // Use the same debug location as the instruction we are about to update.
801 ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
802
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
804 << "From : " << *ConstExpr << '\n');
805 LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
Juergen Ributzkae802d502014-03-22 01:49:27 +0000806 if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
807 ConstExprInst->eraseFromParent();
808 if (Offset)
809 Mat->eraseFromParent();
810 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000811 LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
Juergen Ributzka5429c062014-03-21 06:04:36 +0000812 return;
Juergen Ributzka4c8a0252014-02-08 00:20:45 +0000813 }
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000814}
815
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000816/// Hoist and hide the base constant behind a bitcast and emit
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000817/// materialization code for derived constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000818bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000819 bool MadeChange = false;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000820 SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
821 BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
822 for (auto const &ConstInfo : ConstInfoVec) {
Wei Mi337d4d92017-04-21 15:50:16 +0000823 SmallPtrSet<Instruction *, 8> IPSet = findConstantInsertionPoint(ConstInfo);
824 assert(!IPSet.empty() && "IPSet is empty");
825
826 unsigned UsesNum = 0;
827 unsigned ReBasesNum = 0;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000828 unsigned NotRebasedNum = 0;
Wei Mi337d4d92017-04-21 15:50:16 +0000829 for (Instruction *IP : IPSet) {
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000830 // First, collect constants depending on this IP of the base.
831 unsigned Uses = 0;
832 using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
833 SmallVector<RebasedUse, 4> ToBeRebased;
834 for (auto const &RCI : ConstInfo.RebasedConstants) {
835 for (auto const &U : RCI.Uses) {
836 Uses++;
837 BasicBlock *OrigMatInsertBB =
838 findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
839 // If Base constant is to be inserted in multiple places,
840 // generate rebase for U using the Base dominating U.
841 if (IPSet.size() == 1 ||
842 DT->dominates(IP->getParent(), OrigMatInsertBB))
843 ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
844 }
845 }
846 UsesNum = Uses;
847
848 // If only few constants depend on this IP of base, skip rebasing,
849 // assuming the base and the rebased have the same materialization cost.
850 if (ToBeRebased.size() < MinNumOfDependentToRebase) {
851 NotRebasedNum += ToBeRebased.size();
852 continue;
853 }
854
855 // Emit an instance of the base at this IP.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000856 Instruction *Base = nullptr;
857 // Hoist and hide the base constant behind a bitcast.
858 if (ConstInfo.BaseExpr) {
859 assert(BaseGV && "A base constant expression must have an base GV");
860 Type *Ty = ConstInfo.BaseExpr->getType();
861 Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
862 } else {
863 IntegerType *Ty = ConstInfo.BaseInt->getType();
864 Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
865 }
Paul Robinsonb46256b2017-11-09 20:01:31 +0000866
867 Base->setDebugLoc(IP->getDebugLoc());
868
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000869 LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000870 << ") to BB " << IP->getParent()->getName() << '\n'
871 << *Base << '\n');
Wei Mi337d4d92017-04-21 15:50:16 +0000872
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000873 // Emit materialization code for rebased constants depending on this IP.
874 for (auto const &R : ToBeRebased) {
875 Constant *Off = std::get<0>(R);
876 Type *Ty = std::get<1>(R);
877 ConstantUser U = std::get<2>(R);
878 emitBaseConstants(Base, Off, Ty, U);
879 ReBasesNum++;
880 // Use the same debug location as the last user of the constant.
881 Base->setDebugLoc(DILocation::getMergedLocation(
882 Base->getDebugLoc(), U.Inst->getDebugLoc()));
Wei Mi337d4d92017-04-21 15:50:16 +0000883 }
Wei Mi337d4d92017-04-21 15:50:16 +0000884 assert(!Base->use_empty() && "The use list is empty!?");
885 assert(isa<Instruction>(Base->user_back()) &&
886 "All uses should be instructions.");
Wei Mi337d4d92017-04-21 15:50:16 +0000887 }
888 (void)UsesNum;
889 (void)ReBasesNum;
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000890 (void)NotRebasedNum;
Wei Mi337d4d92017-04-21 15:50:16 +0000891 // Expect all uses are rebased after rebase is done.
Zhaoshi Zheng95710332018-09-26 00:59:09 +0000892 assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
893 "Not all uses are rebased");
Wei Mi337d4d92017-04-21 15:50:16 +0000894
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000895 NumConstantsHoisted++;
896
Wei Mi337d4d92017-04-21 15:50:16 +0000897 // Base constant is also included in ConstInfo.RebasedConstants, so
898 // deduct 1 from ConstInfo.RebasedConstants.size().
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000899 NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000900
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000901 MadeChange = true;
902 }
903 return MadeChange;
904}
905
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000906/// Check all cast instructions we made a copy of and remove them if they
Juergen Ributzka5429c062014-03-21 06:04:36 +0000907/// have no more users.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000908void ConstantHoistingPass::deleteDeadCastInst() const {
Juergen Ributzka5429c062014-03-21 06:04:36 +0000909 for (auto const &I : ClonedCastMap)
910 if (I.first->use_empty())
Juergen Ributzkae4747522014-03-22 01:49:30 +0000911 I.first->eraseFromParent();
Juergen Ributzka5429c062014-03-21 06:04:36 +0000912}
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000913
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000914/// Optimize expensive integer constants in the given function.
Michael Kuperstein071d8302016-07-02 00:16:47 +0000915bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
Wei Mi337d4d92017-04-21 15:50:16 +0000916 DominatorTree &DT, BlockFrequencyInfo *BFI,
917 BasicBlock &Entry) {
Michael Kuperstein071d8302016-07-02 00:16:47 +0000918 this->TTI = &TTI;
919 this->DT = &DT;
Wei Mi337d4d92017-04-21 15:50:16 +0000920 this->BFI = BFI;
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000921 this->DL = &Fn.getParent()->getDataLayout();
922 this->Ctx = &Fn.getContext();
Fangrui Songf78650a2018-07-30 19:41:25 +0000923 this->Entry = &Entry;
Juergen Ributzka46357932014-03-20 20:17:13 +0000924 // Collect all constant candidates.
Juergen Ributzka5429c062014-03-21 06:04:36 +0000925 collectConstantCandidates(Fn);
Juergen Ributzka46357932014-03-20 20:17:13 +0000926
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000927 // Combine constants that can be easily materialized with an add from a common
928 // base constant.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000929 if (!ConstIntCandVec.empty())
930 findBaseConstants(nullptr);
931 for (auto &MapEntry : ConstGEPCandMap)
932 if (!MapEntry.second.empty())
933 findBaseConstants(MapEntry.first);
Juergen Ributzka5429c062014-03-21 06:04:36 +0000934
Juergen Ributzkaf0dff492014-03-21 06:04:45 +0000935 // Finally hoist the base constant and emit materialization code for dependent
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000936 // constants.
Zhaoshi Zhenga0aa41d2018-09-04 22:17:03 +0000937 bool MadeChange = false;
938 if (!ConstIntInfoVec.empty())
939 MadeChange = emitBaseConstants(nullptr);
940 for (auto MapEntry : ConstGEPInfoMap)
941 if (!MapEntry.second.empty())
942 MadeChange |= emitBaseConstants(MapEntry.first);
943
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000944
Juergen Ributzka5429c062014-03-21 06:04:36 +0000945 // Cleanup dead instructions.
946 deleteDeadCastInst();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000947
Fangrui Songf4b25f72019-03-01 05:27:01 +0000948 cleanup();
949
Juergen Ributzkaf26beda2014-01-25 02:02:55 +0000950 return MadeChange;
951}
Michael Kuperstein071d8302016-07-02 00:16:47 +0000952
953PreservedAnalyses ConstantHoistingPass::run(Function &F,
954 FunctionAnalysisManager &AM) {
955 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
956 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
Wei Mi337d4d92017-04-21 15:50:16 +0000957 auto BFI = ConstHoistWithBlockFrequency
958 ? &AM.getResult<BlockFrequencyAnalysis>(F)
959 : nullptr;
960 if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock()))
Michael Kuperstein071d8302016-07-02 00:16:47 +0000961 return PreservedAnalyses::all();
962
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000963 PreservedAnalyses PA;
964 PA.preserveSet<CFGAnalyses>();
965 return PA;
Michael Kuperstein071d8302016-07-02 00:16:47 +0000966}