blob: 4ad7041d329ff7da447b65fbbedd7dcd80fef2bf [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
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// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
Matt Arsenault30991562015-09-09 00:38:33 +000046// if it loads to virtual registers and the virtual register defined has
Joel Jones24e440d2012-12-11 16:10:25 +000047// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Bill Wendlingca678352010-08-09 23:59:04 +000069#include "llvm/CodeGen/Passes.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000070#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000071#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000072#include "llvm/ADT/SmallSet.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/CodeGen/MachineDominators.h"
75#include "llvm/CodeGen/MachineInstrBuilder.h"
76#include "llvm/CodeGen/MachineRegisterInfo.h"
77#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000078#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000079#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000080#include "llvm/Target/TargetInstrInfo.h"
81#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000082#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet03e43f82014-08-20 17:41:48 +000083#include <utility>
Bill Wendlingca678352010-08-09 23:59:04 +000084using namespace llvm;
85
Chandler Carruth1b9dde02014-04-22 02:02:50 +000086#define DEBUG_TYPE "peephole-opt"
87
Bill Wendlingca678352010-08-09 23:59:04 +000088// Optimize Extensions
89static cl::opt<bool>
90Aggressive("aggressive-ext-opt", cl::Hidden,
91 cl::desc("Aggressive extension optimization"));
92
Bill Wendlingc6627ee2010-11-01 20:41:43 +000093static cl::opt<bool>
94DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95 cl::desc("Disable the peephole optimizer"));
96
Quentin Colombet1111e6f2014-07-01 14:33:36 +000097static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +000098DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +000099 cl::desc("Disable advanced copy optimization"));
100
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000101// Limit the number of PHI instructions to process
102// in PeepholeOptimizer::getNextSource.
103static cl::opt<unsigned> RewritePHILimit(
104 "rewrite-phi-limit", cl::Hidden, cl::init(10),
105 cl::desc("Limit the length of PHI chains to lookup"));
106
Bill Wendling66284312010-08-27 20:39:09 +0000107STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000108STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000109STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000110STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000111STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000112STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
113STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000114
115namespace {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000116 class ValueTrackerResult;
117
Bill Wendlingca678352010-08-09 23:59:04 +0000118 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000119 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000120 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000121 MachineRegisterInfo *MRI;
122 MachineDominatorTree *DT; // Machine dominator tree
123
124 public:
125 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 PeepholeOptimizer() : MachineFunctionPass(ID) {
127 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
128 }
Bill Wendlingca678352010-08-09 23:59:04 +0000129
Craig Topper4584cd52014-03-07 09:26:03 +0000130 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000131
Craig Topper4584cd52014-03-07 09:26:03 +0000132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
135 if (Aggressive) {
136 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineDominatorTree>();
138 }
139 }
140
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000141 /// \brief Track Def -> Use info used for rewriting copies.
142 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
143 RewriteMapTy;
144
Bill Wendlingca678352010-08-09 23:59:04 +0000145 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000146 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
147 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000148 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000149 bool optimizeSelect(MachineInstr *MI,
150 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000151 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000152 bool optimizeCoalescableCopy(MachineInstr *MI);
153 bool optimizeUncoalescableCopy(MachineInstr *MI,
154 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000155 bool findNextSource(unsigned Reg, unsigned SubReg,
156 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000157 bool isMoveImmediate(MachineInstr *MI,
158 SmallSet<unsigned, 4> &ImmDefRegs,
159 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000160 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000161 SmallSet<unsigned, 4> &ImmDefRegs,
162 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Lang Hames5dc14bd2014-04-02 22:59:58 +0000163 bool isLoadFoldable(MachineInstr *MI,
164 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000165
166 /// \brief Check whether \p MI is understood by the register coalescer
167 /// but may require some rewriting.
168 bool isCoalescableCopy(const MachineInstr &MI) {
169 // SubregToRegs are not interesting, because they are already register
170 // coalescer friendly.
171 return MI.isCopy() || (!DisableAdvCopyOpt &&
172 (MI.isRegSequence() || MI.isInsertSubreg() ||
173 MI.isExtractSubreg()));
174 }
175
176 /// \brief Check whether \p MI is a copy like instruction that is
177 /// not recognized by the register coalescer.
178 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000179 return MI.isBitcast() ||
180 (!DisableAdvCopyOpt &&
181 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
182 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000183 }
Bill Wendlingca678352010-08-09 23:59:04 +0000184 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000185
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000186 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
187 /// returned sources for a given search and the instructions where the sources
188 /// were tracked from.
189 class ValueTrackerResult {
190 private:
191 /// Track all sources found by one ValueTracker query.
192 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
193
194 /// Instruction using the sources in 'RegSrcs'.
195 const MachineInstr *Inst;
196
197 public:
198 ValueTrackerResult() : Inst(nullptr) {}
199 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
200 addSource(Reg, SubReg);
201 }
202
203 bool isValid() const { return getNumSources() > 0; }
204
205 void setInst(const MachineInstr *I) { Inst = I; }
206 const MachineInstr *getInst() const { return Inst; }
207
208 void clear() {
209 RegSrcs.clear();
210 Inst = nullptr;
211 }
212
213 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
214 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
215 }
216
217 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
218 assert(Idx < getNumSources() && "Reg pair source out of index");
219 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
220 }
221
222 int getNumSources() const { return RegSrcs.size(); }
223
224 unsigned getSrcReg(int Idx) const {
225 assert(Idx < getNumSources() && "Reg source out of index");
226 return RegSrcs[Idx].Reg;
227 }
228
229 unsigned getSrcSubReg(int Idx) const {
230 assert(Idx < getNumSources() && "SubReg source out of index");
231 return RegSrcs[Idx].SubReg;
232 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000233
234 bool operator==(const ValueTrackerResult &Other) {
235 if (Other.getInst() != getInst())
236 return false;
237
238 if (Other.getNumSources() != getNumSources())
239 return false;
240
241 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
242 if (Other.getSrcReg(i) != getSrcReg(i) ||
243 Other.getSrcSubReg(i) != getSrcSubReg(i))
244 return false;
245 return true;
246 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000247 };
248
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000249 /// \brief Helper class to track the possible sources of a value defined by
250 /// a (chain of) copy related instructions.
251 /// Given a definition (instruction and definition index), this class
252 /// follows the use-def chain to find successive suitable sources.
253 /// The given source can be used to rewrite the definition into
254 /// def = COPY src.
255 ///
256 /// For instance, let us consider the following snippet:
257 /// v0 =
258 /// v2 = INSERT_SUBREG v1, v0, sub0
259 /// def = COPY v2.sub0
260 ///
261 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
262 /// suitable sources:
263 /// v2.sub0 and v0.
264 /// Then, def can be rewritten into def = COPY v0.
265 class ValueTracker {
266 private:
267 /// The current point into the use-def chain.
268 const MachineInstr *Def;
269 /// The index of the definition in Def.
270 unsigned DefIdx;
271 /// The sub register index of the definition.
272 unsigned DefSubReg;
273 /// The register where the value can be found.
274 unsigned Reg;
275 /// Specifiy whether or not the value tracking looks through
276 /// complex instructions. When this is false, the value tracker
277 /// bails on everything that is not a copy or a bitcast.
278 ///
279 /// Note: This could have been implemented as a specialized version of
280 /// the ValueTracker class but that would have complicated the code of
281 /// the users of this class.
282 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000283 /// MachineRegisterInfo used to perform tracking.
284 const MachineRegisterInfo &MRI;
285 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000286 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000287 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000288
289 /// \brief Dispatcher to the right underlying implementation of
290 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000291 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000292 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000293 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000294 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000295 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000296 /// \brief Specialized version of getNextSource for RegSequence
297 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000298 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000299 /// \brief Specialized version of getNextSource for InsertSubreg
300 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000301 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000302 /// \brief Specialized version of getNextSource for ExtractSubreg
303 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000304 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000305 /// \brief Specialized version of getNextSource for SubregToReg
306 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000307 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000308 /// \brief Specialized version of getNextSource for PHI instructions.
309 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000310
311 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000312 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000313 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000314 /// track. It does not need to match the sub register index used in the
315 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000316 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
317 /// through complex instructions. By default (false), it handles only copy
318 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000319 /// If \p Reg is a physical register, a value tracker constructed with
320 /// this constructor will not find any alternative source.
321 /// Indeed, when \p Reg is a physical register that constructor does not
322 /// know which definition of \p Reg it should track.
323 /// Use the next constructor to track a physical register.
324 ValueTracker(unsigned Reg, unsigned DefSubReg,
325 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000326 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000327 const TargetInstrInfo *TII = nullptr)
328 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
329 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
330 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
331 Def = MRI.getVRegDef(Reg);
332 DefIdx = MRI.def_begin(Reg).getOperandNo();
333 }
334 }
335
336 /// \brief Create a ValueTracker instance for the value defined by
337 /// the pair \p MI, \p DefIdx.
338 /// Unlike the other constructor, the value tracker produced by this one
339 /// may be able to find a new source when the definition is a physical
340 /// register.
341 /// This could be useful to rewrite target specific instructions into
342 /// generic copy instructions.
343 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
344 const MachineRegisterInfo &MRI,
345 bool UseAdvancedTracking = false,
346 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000347 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000348 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
349 assert(DefIdx < Def->getDesc().getNumDefs() &&
350 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000351 Reg = Def->getOperand(DefIdx).getReg();
352 }
353
354 /// \brief Following the use-def chain, get the next available source
355 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000356 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000357 /// and sub registers with tracked values. A ValueTrackerResult with
358 /// an empty set of registers means no source was found.
359 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000360
361 /// \brief Get the last register where the initial value can be found.
362 /// Initially this is the register of the definition.
363 /// Then, after each successful call to getNextSource, this is the
364 /// register of the last source.
365 unsigned getReg() const { return Reg; }
366 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000367}
Bill Wendlingca678352010-08-09 23:59:04 +0000368
369char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000370char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000371INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
372 "Peephole Optimizations", false, false)
373INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
374INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000375 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000376
Jim Grosbachedcb8682012-05-01 23:21:41 +0000377/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000378/// a single register and writes a single register and it does not modify the
379/// source, and if the source value is preserved as a sub-register of the
380/// result, then replace all reachable uses of the source with the subreg of the
381/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000382///
Bill Wendlingca678352010-08-09 23:59:04 +0000383/// Do not generate an EXTRACT that is used only in a debug use, as this changes
384/// the code. Since this code does not currently share EXTRACTs, just ignore all
385/// debug uses.
386bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000387optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000388 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000389 unsigned SrcReg, DstReg, SubIdx;
390 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
391 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000392
Bill Wendlingca678352010-08-09 23:59:04 +0000393 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
394 TargetRegisterInfo::isPhysicalRegister(SrcReg))
395 return false;
396
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000397 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000398 // No other uses.
399 return false;
400
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000401 // Ensure DstReg can get a register class that actually supports
402 // sub-registers. Don't change the class until we commit.
403 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000404 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000405 if (!DstRC)
406 return false;
407
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000408 // The ext instr may be operating on a sub-register of SrcReg as well.
409 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
410 // register.
411 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
412 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000413 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000414 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000415
Bill Wendlingca678352010-08-09 23:59:04 +0000416 // The source has other uses. See if we can replace the other uses with use of
417 // the result of the extension.
418 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000419 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
420 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000421
422 // Uses that are in the same BB of uses of the result of the instruction.
423 SmallVector<MachineOperand*, 8> Uses;
424
425 // Uses that the result of the instruction can reach.
426 SmallVector<MachineOperand*, 8> ExtendedUses;
427
428 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000429 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000430 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000431 if (UseMI == MI)
432 continue;
433
434 if (UseMI->isPHI()) {
435 ExtendLife = false;
436 continue;
437 }
438
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000439 // Only accept uses of SrcReg:SubIdx.
440 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
441 continue;
442
Bill Wendlingca678352010-08-09 23:59:04 +0000443 // It's an error to translate this:
444 //
445 // %reg1025 = <sext> %reg1024
446 // ...
447 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
448 //
449 // into this:
450 //
451 // %reg1025 = <sext> %reg1024
452 // ...
453 // %reg1027 = COPY %reg1025:4
454 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
455 //
456 // The problem here is that SUBREG_TO_REG is there to assert that an
457 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
458 // the COPY here, it will give us the value after the <sext>, not the
459 // original value of %reg1024 before <sext>.
460 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
461 continue;
462
463 MachineBasicBlock *UseMBB = UseMI->getParent();
464 if (UseMBB == MBB) {
465 // Local uses that come after the extension.
466 if (!LocalMIs.count(UseMI))
467 Uses.push_back(&UseMO);
468 } else if (ReachedBBs.count(UseMBB)) {
469 // Non-local uses where the result of the extension is used. Always
470 // replace these unless it's a PHI.
471 Uses.push_back(&UseMO);
472 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
473 // We may want to extend the live range of the extension result in order
474 // to replace these uses.
475 ExtendedUses.push_back(&UseMO);
476 } else {
477 // Both will be live out of the def MBB anyway. Don't extend live range of
478 // the extension result.
479 ExtendLife = false;
480 break;
481 }
482 }
483
484 if (ExtendLife && !ExtendedUses.empty())
485 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000486 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000487
488 // Now replace all uses.
489 bool Changed = false;
490 if (!Uses.empty()) {
491 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
492
493 // Look for PHI uses of the extended result, we don't want to extend the
494 // liveness of a PHI input. It breaks all kinds of assumptions down
495 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000496 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
497 if (UI.isPHI())
498 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000499
500 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
501 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
502 MachineOperand *UseMO = Uses[i];
503 MachineInstr *UseMI = UseMO->getParent();
504 MachineBasicBlock *UseMBB = UseMI->getParent();
505 if (PHIBBs.count(UseMBB))
506 continue;
507
Lang Hamesd5862ce2012-02-25 02:01:00 +0000508 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000509 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000510 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000511 MRI->constrainRegClass(DstReg, DstRC);
512 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000513
Bill Wendlingca678352010-08-09 23:59:04 +0000514 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000515 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
516 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000517 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000518 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
519 if (UseSrcSubIdx) {
520 Copy->getOperand(0).setSubReg(SubIdx);
521 Copy->getOperand(0).setIsUndef();
522 }
Bill Wendlingca678352010-08-09 23:59:04 +0000523 UseMO->setReg(NewVR);
524 ++NumReuse;
525 Changed = true;
526 }
527 }
528
529 return Changed;
530}
531
Jim Grosbachedcb8682012-05-01 23:21:41 +0000532/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000533/// instruction it's comparing against all ready sets (or could be modified to
534/// set) the same flag as the compare, then we can remove the comparison and use
535/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000536bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000537 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000538 // If this instruction is a comparison against zero and isn't comparing a
539 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000540 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000541 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000542 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
543 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
544 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000545 return false;
546
Bill Wendling27dddd12010-09-11 00:13:50 +0000547 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000548 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000549 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000550 return true;
551 }
552
553 return false;
554}
555
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000556/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000557bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
558 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000559 unsigned TrueOp = 0;
560 unsigned FalseOp = 0;
561 bool Optimizable = false;
562 SmallVector<MachineOperand, 4> Cond;
563 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
564 return false;
565 if (!Optimizable)
566 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000567 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000568 return false;
569 MI->eraseFromParent();
570 ++NumSelects;
571 return true;
572}
573
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000574/// \brief Check if a simpler conditional branch can be
575// generated
576bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
577 return TII->optimizeCondBranch(MI);
578}
579
Quentin Colombet03e43f82014-08-20 17:41:48 +0000580/// \brief Try to find the next source that share the same register file
581/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000582/// When true is returned, the \p RewriteMap can be used by the client to
583/// retrieve all Def -> Use along the way up to the next source. Any found
584/// Use that is not itself a key for another entry, is the next source to
585/// use. During the search for the next source, multiple sources can be found
586/// given multiple incoming sources of a PHI instruction. In this case, we
587/// look in each PHI source for the next source; all found next sources must
588/// share the same register file as \p Reg and \p SubReg. The client should
589/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000590/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000591bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
592 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000593 // Do not try to find a new source for a physical register.
594 // So far we do not have any motivating example for doing that.
595 // Thus, instead of maintaining untested code, we will revisit that if
596 // that changes at some point.
597 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000598 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000599 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000600
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000601 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
602 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
603 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000604
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000605 unsigned PHICount = 0;
606 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
607 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
608 // As explained above, do not handle physical registers
609 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
610 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000611
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000612 CurSrcPair = Pair;
613 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
614 !DisableAdvCopyOpt, TII);
615 ValueTrackerResult Res;
616 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000617
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000618 do {
619 // Follow the chain of copies until we reach the top of the use-def chain
620 // or find a more suitable source.
621 Res = ValTracker.getNextSource();
622 if (!Res.isValid())
623 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000624
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000625 // Insert the Def -> Use entry for the recently found source.
626 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
627 if (CurSrcRes.isValid()) {
628 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
629 // An existent entry with multiple sources is a PHI cycle we must avoid.
630 // Otherwise it's an entry with a valid next source we already found.
631 if (CurSrcRes.getNumSources() > 1) {
632 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
633 return false;
634 }
635 break;
636 }
637 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
638
639 // ValueTrackerResult usually have one source unless it's the result from
640 // a PHI instruction. Add the found PHI edges to be looked up further.
641 unsigned NumSrcs = Res.getNumSources();
642 if (NumSrcs > 1) {
643 PHICount++;
644 for (unsigned i = 0; i < NumSrcs; ++i)
645 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
646 Res.getSrcReg(i), Res.getSrcSubReg(i)));
647 break;
648 }
649
650 CurSrcPair.Reg = Res.getSrcReg(0);
651 CurSrcPair.SubReg = Res.getSrcSubReg(0);
652 // Do not extend the live-ranges of physical registers as they add
653 // constraints to the register allocator. Moreover, if we want to extend
654 // the live-range of a physical register, unlike SSA virtual register,
655 // we will have to check that they aren't redefine before the related use.
656 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
657 return false;
658
659 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matt Arsenault68d93862015-09-24 08:36:14 +0000660 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
661 CurSrcPair.SubReg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000662 } while (!ShouldRewrite);
663
664 // Continue looking for new sources...
665 if (Res.isValid())
666 continue;
667
668 // Do not continue searching for a new source if the there's at least
669 // one use-def which cannot be rewritten.
670 if (!ShouldRewrite)
671 return false;
672 }
673
674 if (PHICount >= RewritePHILimit) {
675 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
676 return false;
677 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000678
679 // If we did not find a more suitable source, there is nothing to optimize.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000680 if (CurSrcPair.Reg == Reg)
Quentin Colombetcf71c632013-09-13 18:26:31 +0000681 return false;
682
Quentin Colombet03e43f82014-08-20 17:41:48 +0000683 return true;
684}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000685
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000686/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
687/// guaranteed to have the same register class. This is necessary whenever we
688/// successfully traverse a PHI instruction and find suitable sources coming
689/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
690/// suitable to be used in a new COPY instruction.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000691static MachineInstr *
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000692insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
693 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
694 MachineInstr *OrigPHI) {
695 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
696
697 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
698 unsigned NewVR = MRI->createVirtualRegister(NewRC);
699 MachineBasicBlock *MBB = OrigPHI->getParent();
700 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
701 TII->get(TargetOpcode::PHI), NewVR);
702
703 unsigned MBBOpIdx = 2;
704 for (auto RegPair : SrcRegs) {
705 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
706 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
707 // Since we're extended the lifetime of RegPair.Reg, clear the
708 // kill flags to account for that and make RegPair.Reg reaches
709 // the new PHI.
710 MRI->clearKillFlags(RegPair.Reg);
711 MBBOpIdx += 2;
712 }
713
714 return MIB;
715}
716
Quentin Colombet03e43f82014-08-20 17:41:48 +0000717namespace {
718/// \brief Helper class to rewrite the arguments of a copy-like instruction.
719class CopyRewriter {
720protected:
721 /// The copy-like instruction.
722 MachineInstr &CopyLike;
723 /// The index of the source being rewritten.
724 unsigned CurrentSrcIdx;
725
726public:
727 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
728
729 virtual ~CopyRewriter() {}
730
731 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
732 /// the related value that it affects (TrackReg, TrackSubReg).
733 /// A source is considered rewritable if its register class and the
734 /// register class of the related TrackReg may not be register
735 /// coalescer friendly. In other words, given a copy-like instruction
736 /// not all the arguments may be returned at rewritable source, since
737 /// some arguments are none to be register coalescer friendly.
738 ///
739 /// Each call of this method moves the current source to the next
740 /// rewritable source.
741 /// For instance, let CopyLike be the instruction to rewrite.
742 /// CopyLike has one definition and one source:
743 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
744 ///
745 /// The first call will give the first rewritable source, i.e.,
746 /// the only source this instruction has:
747 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
748 /// This source defines the whole definition, i.e.,
749 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
750 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000751 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000752 /// rewritable source.
753 ///
754 /// \return True if a rewritable source has been found, false otherwise.
755 /// The output arguments are valid if and only if true is returned.
756 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
757 unsigned &TrackReg,
758 unsigned &TrackSubReg) {
Matt Arsenault30991562015-09-09 00:38:33 +0000759 // If CurrentSrcIdx == 1, this means this function has already been called
760 // once. CopyLike has one definition and one argument, thus, there is
761 // nothing else to rewrite.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000762 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
763 return false;
764 // This is the first call to getNextRewritableSource.
765 // Move the CurrentSrcIdx to remember that we made that call.
766 CurrentSrcIdx = 1;
767 // The rewritable source is the argument.
768 const MachineOperand &MOSrc = CopyLike.getOperand(1);
769 SrcReg = MOSrc.getReg();
770 SrcSubReg = MOSrc.getSubReg();
771 // What we track are the alternative sources of the definition.
772 const MachineOperand &MODef = CopyLike.getOperand(0);
773 TrackReg = MODef.getReg();
774 TrackSubReg = MODef.getSubReg();
775 return true;
776 }
777
778 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
779 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000780 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000781 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
782 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
783 return false;
784 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
785 MOSrc.setReg(NewReg);
786 MOSrc.setSubReg(NewSubReg);
787 return true;
788 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000789
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000790 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
791 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
792 /// multiple sources for a given \p Def are found along the way, we found a
793 /// PHI instructions that needs to be rewritten.
794 /// TODO: HandleMultipleSources should be removed once we test PHI handling
795 /// with coalescable copies.
796 TargetInstrInfo::RegSubRegPair
797 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
798 TargetInstrInfo::RegSubRegPair Def,
799 PeepholeOptimizer::RewriteMapTy &RewriteMap,
800 bool HandleMultipleSources = true) {
801
802 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
803 do {
804 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
805 // If there are no entries on the map, LookupSrc is the new source.
806 if (!Res.isValid())
807 return LookupSrc;
808
809 // There's only one source for this definition, keep searching...
810 unsigned NumSrcs = Res.getNumSources();
811 if (NumSrcs == 1) {
812 LookupSrc.Reg = Res.getSrcReg(0);
813 LookupSrc.SubReg = Res.getSrcSubReg(0);
814 continue;
815 }
816
Matt Arsenault30991562015-09-09 00:38:33 +0000817 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000818 if (!HandleMultipleSources)
819 break;
820
821 // Multiple sources, recurse into each source to find a new source
822 // for it. Then, rewrite the PHI accordingly to its new edges.
823 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
824 for (unsigned i = 0; i < NumSrcs; ++i) {
825 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
826 Res.getSrcSubReg(i));
827 NewPHISrcs.push_back(
828 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
829 }
830
831 // Build the new PHI node and return its def register as the new source.
832 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
833 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
834 DEBUG(dbgs() << "-- getNewSource\n");
835 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
836 DEBUG(dbgs() << " With: " << *NewPHI);
837 const MachineOperand &MODef = NewPHI->getOperand(0);
838 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
839
840 } while (1);
841
842 return TargetInstrInfo::RegSubRegPair(0, 0);
843 }
844
845 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
846 /// and create a new COPY instruction. More info about RewriteMap in
847 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
848 /// Uncoalescable copies, since they are copy like instructions that aren't
849 /// recognized by the register allocator.
850 virtual MachineInstr *
851 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
852 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000853 return nullptr;
854 }
855};
856
857/// \brief Helper class to rewrite uncoalescable copy like instructions
858/// into new COPY (coalescable friendly) instructions.
859class UncoalescableRewriter : public CopyRewriter {
860protected:
861 const TargetInstrInfo &TII;
862 MachineRegisterInfo &MRI;
863 /// The number of defs in the bitcast
864 unsigned NumDefs;
865
866public:
867 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
868 MachineRegisterInfo &MRI)
869 : CopyRewriter(MI), TII(TII), MRI(MRI) {
870 NumDefs = MI.getDesc().getNumDefs();
871 }
872
873 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
874 /// All such sources need to be considered rewritable in order to
875 /// rewrite a uncoalescable copy-like instruction. This method return
876 /// each definition that must be checked if rewritable.
877 ///
878 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
879 unsigned &TrackReg,
880 unsigned &TrackSubReg) override {
881 // Find the next non-dead definition and continue from there.
882 if (CurrentSrcIdx == NumDefs)
883 return false;
884
885 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
886 ++CurrentSrcIdx;
887 if (CurrentSrcIdx == NumDefs)
888 return false;
889 }
890
891 // What we track are the alternative sources of the definition.
892 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
893 TrackReg = MODef.getReg();
894 TrackSubReg = MODef.getSubReg();
895
896 CurrentSrcIdx++;
897 return true;
898 }
899
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000900 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
901 /// and create a new COPY instruction. More info about RewriteMap in
902 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
903 /// Uncoalescable copies, since they are copy like instructions that aren't
904 /// recognized by the register allocator.
905 MachineInstr *
906 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
907 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
908 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000909 "We do not rewrite physical registers");
910
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000911 // Find the new source to use in the COPY rewrite.
912 TargetInstrInfo::RegSubRegPair NewSrc =
913 getNewSource(&MRI, &TII, Def, RewriteMap);
914
915 // Insert the COPY.
916 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000917 unsigned NewVR = MRI.createVirtualRegister(DefRC);
918
919 MachineInstr *NewCopy =
920 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
921 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000922 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000923
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000924 NewCopy->getOperand(0).setSubReg(Def.SubReg);
925 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000926 NewCopy->getOperand(0).setIsUndef();
927
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000928 DEBUG(dbgs() << "-- RewriteSource\n");
929 DEBUG(dbgs() << " Replacing: " << CopyLike);
930 DEBUG(dbgs() << " With: " << *NewCopy);
931 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000932 MRI.clearKillFlags(NewVR);
933
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000934 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
935 // account for that.
936 MRI.clearKillFlags(NewSrc.Reg);
937
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000938 return NewCopy;
939 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000940};
941
942/// \brief Specialized rewriter for INSERT_SUBREG instruction.
943class InsertSubregRewriter : public CopyRewriter {
944public:
945 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
946 assert(MI.isInsertSubreg() && "Invalid instruction");
947 }
948
949 /// \brief See CopyRewriter::getNextRewritableSource.
950 /// Here CopyLike has the following form:
951 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
952 /// Src1 has the same register class has dst, hence, there is
953 /// nothing to rewrite.
954 /// Src2.src2SubIdx, may not be register coalescer friendly.
955 /// Therefore, the first call to this method returns:
956 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
957 /// (TrackReg, TrackSubReg) = (dst, subIdx).
958 ///
959 /// Subsequence calls will return false.
960 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
961 unsigned &TrackReg,
962 unsigned &TrackSubReg) override {
963 // If we already get the only source we can rewrite, return false.
964 if (CurrentSrcIdx == 2)
965 return false;
966 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
967 CurrentSrcIdx = 2;
968 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
969 SrcReg = MOInsertedReg.getReg();
970 SrcSubReg = MOInsertedReg.getSubReg();
971 const MachineOperand &MODef = CopyLike.getOperand(0);
972
973 // We want to track something that is compatible with the
974 // partial definition.
975 TrackReg = MODef.getReg();
976 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +0000977 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000978 return false;
979 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
980 return true;
981 }
982 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
983 if (CurrentSrcIdx != 2)
984 return false;
985 // We are rewriting the inserted reg.
986 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
987 MO.setReg(NewReg);
988 MO.setSubReg(NewSubReg);
989 return true;
990 }
991};
992
993/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
994class ExtractSubregRewriter : public CopyRewriter {
995 const TargetInstrInfo &TII;
996
997public:
998 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
999 : CopyRewriter(MI), TII(TII) {
1000 assert(MI.isExtractSubreg() && "Invalid instruction");
1001 }
1002
1003 /// \brief See CopyRewriter::getNextRewritableSource.
1004 /// Here CopyLike has the following form:
1005 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1006 /// There is only one rewritable source: Src.subIdx,
1007 /// which defines dst.dstSubIdx.
1008 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1009 unsigned &TrackReg,
1010 unsigned &TrackSubReg) override {
1011 // If we already get the only source we can rewrite, return false.
1012 if (CurrentSrcIdx == 1)
1013 return false;
1014 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1015 CurrentSrcIdx = 1;
1016 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1017 SrcReg = MOExtractedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001018 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001019 if (MOExtractedReg.getSubReg())
1020 return false;
1021
1022 SrcSubReg = CopyLike.getOperand(2).getImm();
1023
1024 // We want to track something that is compatible with the definition.
1025 const MachineOperand &MODef = CopyLike.getOperand(0);
1026 TrackReg = MODef.getReg();
1027 TrackSubReg = MODef.getSubReg();
1028 return true;
1029 }
1030
1031 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1032 // The only source we can rewrite is the input register.
1033 if (CurrentSrcIdx != 1)
1034 return false;
1035
1036 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1037
1038 // If we find a source that does not require to extract something,
1039 // rewrite the operation with a copy.
1040 if (!NewSubReg) {
1041 // Move the current index to an invalid position.
1042 // We do not want another call to this method to be able
1043 // to do any change.
1044 CurrentSrcIdx = -1;
1045 // Rewrite the operation as a COPY.
1046 // Get rid of the sub-register index.
1047 CopyLike.RemoveOperand(2);
1048 // Morph the operation into a COPY.
1049 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1050 return true;
1051 }
1052 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1053 return true;
1054 }
1055};
1056
1057/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1058class RegSequenceRewriter : public CopyRewriter {
1059public:
1060 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1061 assert(MI.isRegSequence() && "Invalid instruction");
1062 }
1063
1064 /// \brief See CopyRewriter::getNextRewritableSource.
1065 /// Here CopyLike has the following form:
1066 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1067 /// Each call will return a different source, walking all the available
1068 /// source.
1069 ///
1070 /// The first call returns:
1071 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1072 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1073 ///
1074 /// The second call returns:
1075 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1076 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1077 ///
1078 /// And so on, until all the sources have been traversed, then
1079 /// it returns false.
1080 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1081 unsigned &TrackReg,
1082 unsigned &TrackSubReg) override {
1083 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1084
1085 // If this is the first call, move to the first argument.
1086 if (CurrentSrcIdx == 0) {
1087 CurrentSrcIdx = 1;
1088 } else {
1089 // Otherwise, move to the next argument and check that it is valid.
1090 CurrentSrcIdx += 2;
1091 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1092 return false;
1093 }
1094 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1095 SrcReg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001096 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001097 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1098 return false;
1099
1100 // We want to track something that is compatible with the related
1101 // partial definition.
1102 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1103
1104 const MachineOperand &MODef = CopyLike.getOperand(0);
1105 TrackReg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001106 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001107 return MODef.getSubReg() == 0;
1108 }
1109
1110 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1111 // We cannot rewrite out of bound operands.
1112 // Moreover, rewritable sources are at odd positions.
1113 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1114 return false;
1115
1116 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1117 MO.setReg(NewReg);
1118 MO.setSubReg(NewSubReg);
1119 return true;
1120 }
1121};
1122} // End namespace.
1123
1124/// \brief Get the appropriated CopyRewriter for \p MI.
1125/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1126/// if no rewriter works for \p MI.
1127static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001128 const TargetInstrInfo &TII,
1129 MachineRegisterInfo &MRI) {
1130 // Handle uncoalescable copy-like instructions.
1131 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1132 MI.isExtractSubregLike()))
1133 return new UncoalescableRewriter(MI, TII, MRI);
1134
Quentin Colombet03e43f82014-08-20 17:41:48 +00001135 switch (MI.getOpcode()) {
1136 default:
1137 return nullptr;
1138 case TargetOpcode::COPY:
1139 return new CopyRewriter(MI);
1140 case TargetOpcode::INSERT_SUBREG:
1141 return new InsertSubregRewriter(MI);
1142 case TargetOpcode::EXTRACT_SUBREG:
1143 return new ExtractSubregRewriter(MI, TII);
1144 case TargetOpcode::REG_SEQUENCE:
1145 return new RegSequenceRewriter(MI);
1146 }
1147 llvm_unreachable(nullptr);
1148}
1149
1150/// \brief Optimize generic copy instructions to avoid cross
1151/// register bank copy. The optimization looks through a chain of
1152/// copies and tries to find a source that has a compatible register
1153/// class.
1154/// Two register classes are considered to be compatible if they share
1155/// the same register bank.
1156/// New copies issued by this optimization are register allocator
1157/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001158/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001159/// when possible.
1160/// \pre isCoalescableCopy(*MI) is true.
1161/// \return True, when \p MI has been rewritten. False otherwise.
1162bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1163 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1164 assert(MI->getDesc().getNumDefs() == 1 &&
1165 "Coalescer can understand multiple defs?!");
1166 const MachineOperand &MODef = MI->getOperand(0);
1167 // Do not rewrite physical definitions.
1168 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1169 return false;
1170
1171 bool Changed = false;
1172 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001173 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001174 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001175 if (!CpyRewriter)
1176 return false;
1177 // Rewrite each rewritable source.
1178 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1179 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1180 TrackSubReg)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001181 // Keep track of PHI nodes and its incoming edges when looking for sources.
1182 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001183 // Try to find a more suitable source. If we failed to do so, or get the
1184 // actual source, move to the next source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001185 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001186 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001187
1188 // Get the new source to rewrite. TODO: Only enable handling of multiple
1189 // sources (PHIs) once we have a motivating example and testcases for it.
1190 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1191 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1192 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1193 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1194 continue;
1195
Quentin Colombet03e43f82014-08-20 17:41:48 +00001196 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001197 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001198 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001199 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001200 Changed = true;
1201 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001202 }
1203 // TODO: We could have a clean-up method to tidy the instruction.
1204 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1205 // => v0 = COPY v1
1206 // Currently we haven't seen motivating example for that and we
1207 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001208 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001209 return Changed;
1210}
1211
1212/// \brief Optimize copy-like instructions to create
1213/// register coalescer friendly instruction.
1214/// The optimization tries to kill-off the \p MI by looking
1215/// through a chain of copies to find a source that has a compatible
1216/// register class.
1217/// If such a source is found, it replace \p MI by a generic COPY
1218/// operation.
1219/// \pre isUncoalescableCopy(*MI) is true.
1220/// \return True, when \p MI has been optimized. In that case, \p MI has
1221/// been removed from its parent.
1222/// All COPY instructions created, are inserted in \p LocalMIs.
1223bool PeepholeOptimizer::optimizeUncoalescableCopy(
1224 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1225 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1226
1227 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001228 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001229 // Get the right rewriter for the current copy.
1230 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001231 // If none exists, bail out.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001232 if (!CpyRewriter)
1233 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001234
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001235 // Rewrite each rewritable source by generating new COPYs. This works
1236 // differently from optimizeCoalescableCopy since it first makes sure that all
1237 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001238 RewriteMapTy RewriteMap;
1239 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1240 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1241 CopyDefSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001242 // If a physical register is here, this is probably for a good reason.
1243 // Do not rewrite that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001244 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001245 return false;
1246
1247 // If we do not know how to rewrite this definition, there is no point
1248 // in trying to kill this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001249 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1250 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001251 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001252
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001253 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001254 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001255
Quentin Colombet03e43f82014-08-20 17:41:48 +00001256 // The change is possible for all defs, do it.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001257 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001258 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001259 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001260 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001261 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001262 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001263
Quentin Colombet03e43f82014-08-20 17:41:48 +00001264 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001265 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001266 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001267 return true;
1268}
1269
Manman Ren5759d012012-08-02 00:56:42 +00001270/// isLoadFoldable - Check whether MI is a candidate for folding into a later
1271/// instruction. We only fold loads to virtual registers and the virtual
1272/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001273bool PeepholeOptimizer::isLoadFoldable(
1274 MachineInstr *MI,
1275 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001276 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1277 return false;
1278 const MCInstrDesc &MCID = MI->getDesc();
1279 if (MCID.getNumDefs() != 1)
1280 return false;
1281
1282 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001283 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001284 // loads. It should be checked when processing uses of the load, since
1285 // uses can be removed during peephole.
1286 if (!MI->getOperand(0).getSubReg() &&
1287 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001288 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001289 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001290 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001291 }
1292 return false;
1293}
1294
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001295bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1296 SmallSet<unsigned, 4> &ImmDefRegs,
1297 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001298 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001299 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001300 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001301 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001302 return false;
1303 unsigned Reg = MI->getOperand(0).getReg();
1304 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1305 ImmDefMIs.insert(std::make_pair(Reg, MI));
1306 ImmDefRegs.insert(Reg);
1307 return true;
1308 }
Andrew Trick9e761992012-02-08 21:22:43 +00001309
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001310 return false;
1311}
1312
Jim Grosbachedcb8682012-05-01 23:21:41 +00001313/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001314/// immediate instructions, i.e. a trivial constant folding optimization, if
1315/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001316bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001317 SmallSet<unsigned, 4> &ImmDefRegs,
1318 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1319 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1320 MachineOperand &MO = MI->getOperand(i);
1321 if (!MO.isReg() || MO.isDef())
1322 continue;
1323 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001324 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001325 continue;
1326 if (ImmDefRegs.count(Reg) == 0)
1327 continue;
1328 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1329 assert(II != ImmDefMIs.end());
1330 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1331 ++NumImmFold;
1332 return true;
1333 }
1334 }
1335 return false;
1336}
1337
Eric Christopher2181fb22014-10-15 21:06:25 +00001338bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1339 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001340 return false;
1341
Craig Topper588ceec2012-12-17 03:56:00 +00001342 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001343 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001344
Evan Cheng2ce016c2010-11-15 21:20:45 +00001345 if (DisablePeephole)
1346 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001347
Eric Christopher2181fb22014-10-15 21:06:25 +00001348 TII = MF.getSubtarget().getInstrInfo();
1349 TRI = MF.getSubtarget().getRegisterInfo();
1350 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001351 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001352
1353 bool Changed = false;
1354
Eric Christopher2181fb22014-10-15 21:06:25 +00001355 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001356 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001357
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001358 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001359
1360 // During this forward scan, at some point it needs to answer the question
1361 // "given a pointer to an MI in the current BB, is it located before or
1362 // after the current instruction".
1363 // To perform this, the following set keeps track of the MIs already seen
1364 // during the scan, if a MI is not in the set, it is assumed to be located
1365 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001366 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001367 SmallSet<unsigned, 4> ImmDefRegs;
1368 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1369 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001370
1371 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001372 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001373 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001374 // We may be erasing MI below, increment MII now.
1375 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001376 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001377
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001378 // Skip debug values. They should not affect this peephole optimization.
1379 if (MI->isDebugValue())
1380 continue;
1381
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +00001382 // If we run into an instruction we can't fold across, discard
1383 // the load candidates.
1384 if (MI->isLoadFoldBarrier())
Michael Kuperstein82814f62015-08-11 08:19:43 +00001385 FoldAsLoadDefCandidates.clear();
1386
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001387 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001388 MI->isKill() || MI->isInlineAsm() ||
Michael Kuperstein82814f62015-08-11 08:19:43 +00001389 MI->hasUnmodeledSideEffects())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001390 continue;
1391
Quentin Colombet03e43f82014-08-20 17:41:48 +00001392 if ((isUncoalescableCopy(*MI) &&
1393 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001394 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001395 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001396 // MI is deleted.
1397 LocalMIs.erase(MI);
1398 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001399 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001400 }
1401
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001402 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1403 Changed = true;
1404 continue;
1405 }
1406
Quentin Colombet03e43f82014-08-20 17:41:48 +00001407 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1408 // MI is just rewritten.
1409 Changed = true;
1410 continue;
1411 }
1412
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001413 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001414 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001415 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001416 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001417 // optimizeExtInstr might have created new instructions after MI
1418 // and before the already incremented MII. Adjust MII so that the
1419 // next iteration sees the new instructions.
1420 MII = MI;
1421 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001422 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001423 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001424 }
Evan Cheng98196b42011-02-15 05:00:24 +00001425
Manman Ren5759d012012-08-02 00:56:42 +00001426 // Check whether MI is a load candidate for folding into a later
1427 // instruction. If MI is not a candidate, check whether we can fold an
1428 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001429 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1430 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001431 const MCInstrDesc &MIDesc = MI->getDesc();
1432 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1433 ++i) {
1434 const MachineOperand &MOp = MI->getOperand(i);
1435 if (!MOp.isReg())
1436 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001437 unsigned FoldAsLoadDefReg = MOp.getReg();
1438 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1439 // We need to fold load after optimizeCmpInstr, since
1440 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1441 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1442 // we need it for markUsesInDebugValueAsUndef().
1443 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001444 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001445 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1446 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001447 DefMI);
1448 if (FoldMI) {
1449 // Update LocalMIs since we replaced MI with FoldMI and deleted
1450 // DefMI.
1451 DEBUG(dbgs() << "Replacing: " << *MI);
1452 DEBUG(dbgs() << " With: " << *FoldMI);
1453 LocalMIs.erase(MI);
1454 LocalMIs.erase(DefMI);
1455 LocalMIs.insert(FoldMI);
1456 MI->eraseFromParent();
1457 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001458 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1459 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001460 ++NumLoadFold;
1461 // MI is replaced with FoldMI.
1462 Changed = true;
1463 break;
1464 }
1465 }
Manman Ren5759d012012-08-02 00:56:42 +00001466 }
1467 }
Bill Wendlingca678352010-08-09 23:59:04 +00001468 }
1469 }
1470
1471 return Changed;
1472}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001473
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001474ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001475 assert(Def->isCopy() && "Invalid definition");
1476 // Copy instruction are supposed to be: Def = Src.
1477 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001478 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001479
1480 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1481 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001482 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001483 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001484 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001485 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001486 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001487}
1488
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001489ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001490 assert(Def->isBitcast() && "Invalid definition");
1491
1492 // Bail if there are effects that a plain copy will not expose.
1493 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001494 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001495
1496 // Bitcasts with more than one def are not supported.
1497 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001498 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001499 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1500 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001501 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001502 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001503
Quentin Colombet03e43f82014-08-20 17:41:48 +00001504 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001505 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1506 ++OpIdx) {
1507 const MachineOperand &MO = Def->getOperand(OpIdx);
1508 if (!MO.isReg() || !MO.getReg())
1509 continue;
1510 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1511 if (SrcIdx != EndOpIdx)
1512 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001513 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001514 SrcIdx = OpIdx;
1515 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001516 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001517 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001518}
1519
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001520ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001521 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1522 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001523
1524 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001525 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001526 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1527 // This should almost never happen as the SSA property is tracked at
1528 // the register level (as opposed to the subreg level).
1529 // I.e.,
1530 // Def.sub0 =
1531 // Def.sub1 =
1532 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1533 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001534 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001535 // Def.sub0 (i.e, not defining the other subregs) and we would
1536 // have this case.
1537 // If we can ascertain (or force) that this never happens, we could
1538 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001539 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001540
Quentin Colombet03e43f82014-08-20 17:41:48 +00001541 if (!TII)
1542 // We could handle the REG_SEQUENCE here, but we do not want to
1543 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001544 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001545
1546 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1547 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001548 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001549
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001550 // We are looking at:
1551 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1552 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001553 for (auto &RegSeqInput : RegSeqInputRegs) {
1554 if (RegSeqInput.SubIdx == DefSubReg) {
1555 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001556 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001557 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001558
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001559 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001560 }
1561 }
1562
1563 // If the subreg we are tracking is super-defined by another subreg,
1564 // we could follow this value. However, this would require to compose
1565 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001566 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001567}
1568
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001569ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001570 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1571 "Invalid definition");
1572
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001573 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001574 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001575 // Same remark as getNextSourceFromRegSequence.
1576 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001577 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001578
Quentin Colombet68962302014-08-21 00:19:16 +00001579 if (!TII)
1580 // We could handle the REG_SEQUENCE here, but we do not want to
1581 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001582 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001583
Quentin Colombet03e43f82014-08-20 17:41:48 +00001584 TargetInstrInfo::RegSubRegPair BaseReg;
1585 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001586 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001587 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001588
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001589 // We are looking at:
1590 // Def = INSERT_SUBREG v0, v1, sub1
1591 // There are two cases:
1592 // 1. DefSubReg == sub1, get v1.
1593 // 2. DefSubReg != sub1, the value may be available through v0.
1594
Quentin Colombet03e43f82014-08-20 17:41:48 +00001595 // #1 Check if the inserted register matches the required sub index.
1596 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001597 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001598 }
1599 // #2 Otherwise, if the sub register we are looking for is not partial
1600 // defined by the inserted element, we can look through the main
1601 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001602 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001603 // If the result register (Def) and the base register (v0) do not
1604 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00001605 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001606 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1607 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001608 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001609
Quentin Colombet03e43f82014-08-20 17:41:48 +00001610 // Get the TRI and check if the inserted sub-register overlaps with the
1611 // sub-register we are tracking.
1612 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001613 if (!TRI ||
1614 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001615 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001616 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001617 // At this point, the value is available in v0 via the same subreg
1618 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001619 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001620}
1621
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001622ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001623 assert((Def->isExtractSubreg() ||
1624 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001625 // We are looking at:
1626 // Def = EXTRACT_SUBREG v0, sub0
1627
Matt Arsenault30991562015-09-09 00:38:33 +00001628 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001629 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1630 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001631 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001632
Quentin Colombet67639df2014-08-20 23:13:02 +00001633 if (!TII)
1634 // We could handle the EXTRACT_SUBREG here, but we do not want to
1635 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001636 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001637
Quentin Colombet03e43f82014-08-20 17:41:48 +00001638 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001639 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001640 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001641
Matt Arsenault30991562015-09-09 00:38:33 +00001642 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001643 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001644 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001645 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001646 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001647 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001648}
1649
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001650ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001651 assert(Def->isSubregToReg() && "Invalid definition");
1652 // We are looking at:
1653 // Def = SUBREG_TO_REG Imm, v0, sub0
1654
Matt Arsenault30991562015-09-09 00:38:33 +00001655 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001656 // If DefSubReg != sub0, we would have to check that all the bits
1657 // we track are included in sub0 and if yes, we would have to
1658 // determine the right subreg in v0.
1659 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001660 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00001661 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001662 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1663 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001664 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001665
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001666 return ValueTrackerResult(Def->getOperand(2).getReg(),
1667 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001668}
1669
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001670/// \brief Explore each PHI incoming operand and return its sources
1671ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1672 assert(Def->isPHI() && "Invalid definition");
1673 ValueTrackerResult Res;
1674
Matt Arsenault30991562015-09-09 00:38:33 +00001675 // If we look for a different subreg, bail as we do not support composing
1676 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001677 if (Def->getOperand(0).getSubReg() != DefSubReg)
1678 return ValueTrackerResult();
1679
1680 // Return all register sources for PHI instructions.
1681 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1682 auto &MO = Def->getOperand(i);
1683 assert(MO.isReg() && "Invalid PHI instruction");
1684 Res.addSource(MO.getReg(), MO.getSubReg());
1685 }
1686
1687 return Res;
1688}
1689
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001690ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001691 assert(Def && "This method needs a valid definition");
1692
1693 assert(
1694 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1695 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1696 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001697 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001698 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001699 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001700 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00001701 // Bail if we did not ask for the advanced tracking.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001702 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001703 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001704 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001705 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001706 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001707 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001708 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001709 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001710 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001711 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001712 if (Def->isPHI())
1713 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001714 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001715}
1716
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001717ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001718 // If we reach a point where we cannot move up in the use-def chain,
1719 // there is nothing we can get.
1720 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001721 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001722
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001723 ValueTrackerResult Res = getNextSourceImpl();
1724 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001725 // Update definition, definition index, and subregister for the
1726 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001727 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001728 bool OneRegSrc = Res.getNumSources() == 1;
1729 if (OneRegSrc)
1730 Reg = Res.getSrcReg(0);
1731 // Update the result before moving up in the use-def chain
1732 // with the instruction containing the last found sources.
1733 Res.setInst(Def);
1734
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001735 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001736 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001737 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001738 Def = MRI.getVRegDef(Reg);
1739 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001740 DefSubReg = Res.getSrcSubReg(0);
1741 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001742 }
1743 }
1744 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001745 // for the next iteration. Make sure any new call to getNextSource bails out
1746 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001747 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001748 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001749}