blob: ef213e4347fd0ee477cfe3096933d1ecd28a6fcd [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
46// if it loads to virtual registers and the virtual register defined has
47// 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
Bill Wendling66284312010-08-27 20:39:09 +0000101STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000102STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000103STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000104STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000105STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000106STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
107STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000108
109namespace {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000110 class ValueTrackerResult;
111
Bill Wendlingca678352010-08-09 23:59:04 +0000112 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000113 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000114 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000115 MachineRegisterInfo *MRI;
116 MachineDominatorTree *DT; // Machine dominator tree
117
118 public:
119 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000120 PeepholeOptimizer() : MachineFunctionPass(ID) {
121 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
122 }
Bill Wendlingca678352010-08-09 23:59:04 +0000123
Craig Topper4584cd52014-03-07 09:26:03 +0000124 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000125
Craig Topper4584cd52014-03-07 09:26:03 +0000126 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000127 AU.setPreservesCFG();
128 MachineFunctionPass::getAnalysisUsage(AU);
129 if (Aggressive) {
130 AU.addRequired<MachineDominatorTree>();
131 AU.addPreserved<MachineDominatorTree>();
132 }
133 }
134
135 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000136 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
137 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000138 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000139 bool optimizeSelect(MachineInstr *MI,
140 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000141 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000142 bool optimizeCopyOrBitcast(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000143 bool optimizeCoalescableCopy(MachineInstr *MI);
144 bool optimizeUncoalescableCopy(MachineInstr *MI,
145 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000146 bool findNextSource(unsigned &Reg, unsigned &SubReg);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000147 bool isMoveImmediate(MachineInstr *MI,
148 SmallSet<unsigned, 4> &ImmDefRegs,
149 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000150 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000151 SmallSet<unsigned, 4> &ImmDefRegs,
152 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Lang Hames5dc14bd2014-04-02 22:59:58 +0000153 bool isLoadFoldable(MachineInstr *MI,
154 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000155
156 /// \brief Check whether \p MI is understood by the register coalescer
157 /// but may require some rewriting.
158 bool isCoalescableCopy(const MachineInstr &MI) {
159 // SubregToRegs are not interesting, because they are already register
160 // coalescer friendly.
161 return MI.isCopy() || (!DisableAdvCopyOpt &&
162 (MI.isRegSequence() || MI.isInsertSubreg() ||
163 MI.isExtractSubreg()));
164 }
165
166 /// \brief Check whether \p MI is a copy like instruction that is
167 /// not recognized by the register coalescer.
168 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000169 return MI.isBitcast() ||
170 (!DisableAdvCopyOpt &&
171 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
172 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000173 }
Bill Wendlingca678352010-08-09 23:59:04 +0000174 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000175
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000176 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
177 /// returned sources for a given search and the instructions where the sources
178 /// were tracked from.
179 class ValueTrackerResult {
180 private:
181 /// Track all sources found by one ValueTracker query.
182 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
183
184 /// Instruction using the sources in 'RegSrcs'.
185 const MachineInstr *Inst;
186
187 public:
188 ValueTrackerResult() : Inst(nullptr) {}
189 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
190 addSource(Reg, SubReg);
191 }
192
193 bool isValid() const { return getNumSources() > 0; }
194
195 void setInst(const MachineInstr *I) { Inst = I; }
196 const MachineInstr *getInst() const { return Inst; }
197
198 void clear() {
199 RegSrcs.clear();
200 Inst = nullptr;
201 }
202
203 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
204 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
205 }
206
207 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
208 assert(Idx < getNumSources() && "Reg pair source out of index");
209 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
210 }
211
212 int getNumSources() const { return RegSrcs.size(); }
213
214 unsigned getSrcReg(int Idx) const {
215 assert(Idx < getNumSources() && "Reg source out of index");
216 return RegSrcs[Idx].Reg;
217 }
218
219 unsigned getSrcSubReg(int Idx) const {
220 assert(Idx < getNumSources() && "SubReg source out of index");
221 return RegSrcs[Idx].SubReg;
222 }
223 };
224
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000225 /// \brief Helper class to track the possible sources of a value defined by
226 /// a (chain of) copy related instructions.
227 /// Given a definition (instruction and definition index), this class
228 /// follows the use-def chain to find successive suitable sources.
229 /// The given source can be used to rewrite the definition into
230 /// def = COPY src.
231 ///
232 /// For instance, let us consider the following snippet:
233 /// v0 =
234 /// v2 = INSERT_SUBREG v1, v0, sub0
235 /// def = COPY v2.sub0
236 ///
237 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
238 /// suitable sources:
239 /// v2.sub0 and v0.
240 /// Then, def can be rewritten into def = COPY v0.
241 class ValueTracker {
242 private:
243 /// The current point into the use-def chain.
244 const MachineInstr *Def;
245 /// The index of the definition in Def.
246 unsigned DefIdx;
247 /// The sub register index of the definition.
248 unsigned DefSubReg;
249 /// The register where the value can be found.
250 unsigned Reg;
251 /// Specifiy whether or not the value tracking looks through
252 /// complex instructions. When this is false, the value tracker
253 /// bails on everything that is not a copy or a bitcast.
254 ///
255 /// Note: This could have been implemented as a specialized version of
256 /// the ValueTracker class but that would have complicated the code of
257 /// the users of this class.
258 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000259 /// MachineRegisterInfo used to perform tracking.
260 const MachineRegisterInfo &MRI;
261 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000262 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000263 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000264
265 /// \brief Dispatcher to the right underlying implementation of
266 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000267 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000268 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000269 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000270 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000271 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000272 /// \brief Specialized version of getNextSource for RegSequence
273 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000274 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000275 /// \brief Specialized version of getNextSource for InsertSubreg
276 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000277 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000278 /// \brief Specialized version of getNextSource for ExtractSubreg
279 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000280 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000281 /// \brief Specialized version of getNextSource for SubregToReg
282 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000283 ValueTrackerResult getNextSourceFromSubregToReg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000284
285 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000286 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000287 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000288 /// track. It does not need to match the sub register index used in the
289 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000290 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
291 /// through complex instructions. By default (false), it handles only copy
292 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000293 /// If \p Reg is a physical register, a value tracker constructed with
294 /// this constructor will not find any alternative source.
295 /// Indeed, when \p Reg is a physical register that constructor does not
296 /// know which definition of \p Reg it should track.
297 /// Use the next constructor to track a physical register.
298 ValueTracker(unsigned Reg, unsigned DefSubReg,
299 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000300 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000301 const TargetInstrInfo *TII = nullptr)
302 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
303 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
304 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
305 Def = MRI.getVRegDef(Reg);
306 DefIdx = MRI.def_begin(Reg).getOperandNo();
307 }
308 }
309
310 /// \brief Create a ValueTracker instance for the value defined by
311 /// the pair \p MI, \p DefIdx.
312 /// Unlike the other constructor, the value tracker produced by this one
313 /// may be able to find a new source when the definition is a physical
314 /// register.
315 /// This could be useful to rewrite target specific instructions into
316 /// generic copy instructions.
317 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
318 const MachineRegisterInfo &MRI,
319 bool UseAdvancedTracking = false,
320 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000321 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000322 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
323 assert(DefIdx < Def->getDesc().getNumDefs() &&
324 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000325 Reg = Def->getOperand(DefIdx).getReg();
326 }
327
328 /// \brief Following the use-def chain, get the next available source
329 /// for the tracked value.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000330 /// \return A ValueTrackerResult containing the a set of registers
331 /// and sub registers with tracked values. A ValueTrackerResult with
332 /// an empty set of registers means no source was found.
333 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000334
335 /// \brief Get the last register where the initial value can be found.
336 /// Initially this is the register of the definition.
337 /// Then, after each successful call to getNextSource, this is the
338 /// register of the last source.
339 unsigned getReg() const { return Reg; }
340 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000341}
Bill Wendlingca678352010-08-09 23:59:04 +0000342
343char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000344char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000345INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
346 "Peephole Optimizations", false, false)
347INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
348INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000349 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000350
Jim Grosbachedcb8682012-05-01 23:21:41 +0000351/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000352/// a single register and writes a single register and it does not modify the
353/// source, and if the source value is preserved as a sub-register of the
354/// result, then replace all reachable uses of the source with the subreg of the
355/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000356///
Bill Wendlingca678352010-08-09 23:59:04 +0000357/// Do not generate an EXTRACT that is used only in a debug use, as this changes
358/// the code. Since this code does not currently share EXTRACTs, just ignore all
359/// debug uses.
360bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000361optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000362 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000363 unsigned SrcReg, DstReg, SubIdx;
364 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
365 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000366
Bill Wendlingca678352010-08-09 23:59:04 +0000367 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
368 TargetRegisterInfo::isPhysicalRegister(SrcReg))
369 return false;
370
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000371 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000372 // No other uses.
373 return false;
374
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000375 // Ensure DstReg can get a register class that actually supports
376 // sub-registers. Don't change the class until we commit.
377 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000378 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000379 if (!DstRC)
380 return false;
381
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000382 // The ext instr may be operating on a sub-register of SrcReg as well.
383 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
384 // register.
385 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
386 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000387 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000388 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000389
Bill Wendlingca678352010-08-09 23:59:04 +0000390 // The source has other uses. See if we can replace the other uses with use of
391 // the result of the extension.
392 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000393 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
394 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000395
396 // Uses that are in the same BB of uses of the result of the instruction.
397 SmallVector<MachineOperand*, 8> Uses;
398
399 // Uses that the result of the instruction can reach.
400 SmallVector<MachineOperand*, 8> ExtendedUses;
401
402 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000403 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000404 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000405 if (UseMI == MI)
406 continue;
407
408 if (UseMI->isPHI()) {
409 ExtendLife = false;
410 continue;
411 }
412
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000413 // Only accept uses of SrcReg:SubIdx.
414 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
415 continue;
416
Bill Wendlingca678352010-08-09 23:59:04 +0000417 // It's an error to translate this:
418 //
419 // %reg1025 = <sext> %reg1024
420 // ...
421 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
422 //
423 // into this:
424 //
425 // %reg1025 = <sext> %reg1024
426 // ...
427 // %reg1027 = COPY %reg1025:4
428 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
429 //
430 // The problem here is that SUBREG_TO_REG is there to assert that an
431 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
432 // the COPY here, it will give us the value after the <sext>, not the
433 // original value of %reg1024 before <sext>.
434 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
435 continue;
436
437 MachineBasicBlock *UseMBB = UseMI->getParent();
438 if (UseMBB == MBB) {
439 // Local uses that come after the extension.
440 if (!LocalMIs.count(UseMI))
441 Uses.push_back(&UseMO);
442 } else if (ReachedBBs.count(UseMBB)) {
443 // Non-local uses where the result of the extension is used. Always
444 // replace these unless it's a PHI.
445 Uses.push_back(&UseMO);
446 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
447 // We may want to extend the live range of the extension result in order
448 // to replace these uses.
449 ExtendedUses.push_back(&UseMO);
450 } else {
451 // Both will be live out of the def MBB anyway. Don't extend live range of
452 // the extension result.
453 ExtendLife = false;
454 break;
455 }
456 }
457
458 if (ExtendLife && !ExtendedUses.empty())
459 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000460 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000461
462 // Now replace all uses.
463 bool Changed = false;
464 if (!Uses.empty()) {
465 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
466
467 // Look for PHI uses of the extended result, we don't want to extend the
468 // liveness of a PHI input. It breaks all kinds of assumptions down
469 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000470 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
471 if (UI.isPHI())
472 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000473
474 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
475 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
476 MachineOperand *UseMO = Uses[i];
477 MachineInstr *UseMI = UseMO->getParent();
478 MachineBasicBlock *UseMBB = UseMI->getParent();
479 if (PHIBBs.count(UseMBB))
480 continue;
481
Lang Hamesd5862ce2012-02-25 02:01:00 +0000482 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000483 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000484 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000485 MRI->constrainRegClass(DstReg, DstRC);
486 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000487
Bill Wendlingca678352010-08-09 23:59:04 +0000488 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000489 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
490 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000491 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000492 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
493 if (UseSrcSubIdx) {
494 Copy->getOperand(0).setSubReg(SubIdx);
495 Copy->getOperand(0).setIsUndef();
496 }
Bill Wendlingca678352010-08-09 23:59:04 +0000497 UseMO->setReg(NewVR);
498 ++NumReuse;
499 Changed = true;
500 }
501 }
502
503 return Changed;
504}
505
Jim Grosbachedcb8682012-05-01 23:21:41 +0000506/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000507/// instruction it's comparing against all ready sets (or could be modified to
508/// set) the same flag as the compare, then we can remove the comparison and use
509/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000510bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000511 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000512 // If this instruction is a comparison against zero and isn't comparing a
513 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000514 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000515 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000516 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
517 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
518 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000519 return false;
520
Bill Wendling27dddd12010-09-11 00:13:50 +0000521 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000522 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000523 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000524 return true;
525 }
526
527 return false;
528}
529
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000530/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000531bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
532 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000533 unsigned TrueOp = 0;
534 unsigned FalseOp = 0;
535 bool Optimizable = false;
536 SmallVector<MachineOperand, 4> Cond;
537 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
538 return false;
539 if (!Optimizable)
540 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000541 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000542 return false;
543 MI->eraseFromParent();
544 ++NumSelects;
545 return true;
546}
547
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000548/// \brief Check if a simpler conditional branch can be
549// generated
550bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
551 return TII->optimizeCondBranch(MI);
552}
553
Quentin Colombetcf71c632013-09-13 18:26:31 +0000554/// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
555/// share the same register file.
556static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
557 const TargetRegisterClass *DefRC,
558 unsigned DefSubReg,
559 const TargetRegisterClass *SrcRC,
560 unsigned SrcSubReg) {
561 // Same register class.
562 if (DefRC == SrcRC)
563 return true;
564
565 // Both operands are sub registers. Check if they share a register class.
566 unsigned SrcIdx, DefIdx;
567 if (SrcSubReg && DefSubReg)
568 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
Craig Topperc0196b12014-04-14 00:51:57 +0000569 SrcIdx, DefIdx) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000570 // At most one of the register is a sub register, make it Src to avoid
571 // duplicating the test.
572 if (!SrcSubReg) {
573 std::swap(DefSubReg, SrcSubReg);
574 std::swap(DefRC, SrcRC);
575 }
576
577 // One of the register is a sub register, check if we can get a superclass.
578 if (SrcSubReg)
Craig Topperc0196b12014-04-14 00:51:57 +0000579 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000580 // Plain copy.
Craig Topperc0196b12014-04-14 00:51:57 +0000581 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000582}
583
Quentin Colombet03e43f82014-08-20 17:41:48 +0000584/// \brief Try to find the next source that share the same register file
585/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000586/// When true is returned, \p Reg and \p SubReg are updated with the
587/// register number and sub-register index of the new source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000588/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000589bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000590 // Do not try to find a new source for a physical register.
591 // So far we do not have any motivating example for doing that.
592 // Thus, instead of maintaining untested code, we will revisit that if
593 // that changes at some point.
594 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000595 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000596
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000597 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
598 unsigned DefSubReg = SubReg;
599
600 unsigned Src;
601 unsigned SrcSubReg;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000602 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000603
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000604 // Follow the chain of copies until we reach the top of the use-def chain
605 // or find a more suitable source.
606 ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
607 do {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000608 ValueTrackerResult Res = ValTracker.getNextSource();
609 if (!Res.isValid())
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000610 break;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000611 Src = Res.getSrcReg(0);
612 SrcSubReg = Res.getSrcSubReg(0);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000613
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000614 // Do not extend the live-ranges of physical registers as they add
615 // constraints to the register allocator.
616 // Moreover, if we want to extend the live-range of a physical register,
617 // unlike SSA virtual register, we will have to check that they are not
618 // redefine before the related use.
619 if (TargetRegisterInfo::isPhysicalRegister(Src))
620 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000621
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000622 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000623
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000624 // If this source does not incur a cross register bank copy, use it.
625 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, DefSubReg, SrcRC,
626 SrcSubReg);
627 } while (!ShouldRewrite);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000628
629 // If we did not find a more suitable source, there is nothing to optimize.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000630 if (!ShouldRewrite || Src == Reg)
Quentin Colombetcf71c632013-09-13 18:26:31 +0000631 return false;
632
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000633 Reg = Src;
634 SubReg = SrcSubReg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000635 return true;
636}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000637
Quentin Colombet03e43f82014-08-20 17:41:48 +0000638namespace {
639/// \brief Helper class to rewrite the arguments of a copy-like instruction.
640class CopyRewriter {
641protected:
642 /// The copy-like instruction.
643 MachineInstr &CopyLike;
644 /// The index of the source being rewritten.
645 unsigned CurrentSrcIdx;
646
647public:
648 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
649
650 virtual ~CopyRewriter() {}
651
652 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
653 /// the related value that it affects (TrackReg, TrackSubReg).
654 /// A source is considered rewritable if its register class and the
655 /// register class of the related TrackReg may not be register
656 /// coalescer friendly. In other words, given a copy-like instruction
657 /// not all the arguments may be returned at rewritable source, since
658 /// some arguments are none to be register coalescer friendly.
659 ///
660 /// Each call of this method moves the current source to the next
661 /// rewritable source.
662 /// For instance, let CopyLike be the instruction to rewrite.
663 /// CopyLike has one definition and one source:
664 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
665 ///
666 /// The first call will give the first rewritable source, i.e.,
667 /// the only source this instruction has:
668 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
669 /// This source defines the whole definition, i.e.,
670 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
671 ///
672 /// The second and subsequent calls will return false, has there is only one
673 /// rewritable source.
674 ///
675 /// \return True if a rewritable source has been found, false otherwise.
676 /// The output arguments are valid if and only if true is returned.
677 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
678 unsigned &TrackReg,
679 unsigned &TrackSubReg) {
680 // If CurrentSrcIdx == 1, this means this function has already been
681 // called once. CopyLike has one defintiion and one argument, thus,
682 // there is nothing else to rewrite.
683 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
684 return false;
685 // This is the first call to getNextRewritableSource.
686 // Move the CurrentSrcIdx to remember that we made that call.
687 CurrentSrcIdx = 1;
688 // The rewritable source is the argument.
689 const MachineOperand &MOSrc = CopyLike.getOperand(1);
690 SrcReg = MOSrc.getReg();
691 SrcSubReg = MOSrc.getSubReg();
692 // What we track are the alternative sources of the definition.
693 const MachineOperand &MODef = CopyLike.getOperand(0);
694 TrackReg = MODef.getReg();
695 TrackSubReg = MODef.getSubReg();
696 return true;
697 }
698
699 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
700 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000701 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000702 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
703 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
704 return false;
705 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
706 MOSrc.setReg(NewReg);
707 MOSrc.setSubReg(NewSubReg);
708 return true;
709 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000710
711 /// \brief Rewrite the current source with \p NewSrcReg and \p NewSecSubReg
712 /// by creating a new COPY instruction. \p DefReg and \p DefSubReg contain the
713 /// definition to be rewritten from the original copylike instruction.
714 /// \return The new COPY if the rewriting was possible, nullptr otherwise.
715 /// This is needed to handle Uncoalescable copies, since they are copy
716 /// like instructions that aren't recognized by the register allocator.
717 virtual MachineInstr *RewriteCurrentSource(unsigned DefReg,
718 unsigned DefSubReg,
719 unsigned NewSrcReg,
720 unsigned NewSrcSubReg) {
721 return nullptr;
722 }
723};
724
725/// \brief Helper class to rewrite uncoalescable copy like instructions
726/// into new COPY (coalescable friendly) instructions.
727class UncoalescableRewriter : public CopyRewriter {
728protected:
729 const TargetInstrInfo &TII;
730 MachineRegisterInfo &MRI;
731 /// The number of defs in the bitcast
732 unsigned NumDefs;
733
734public:
735 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
736 MachineRegisterInfo &MRI)
737 : CopyRewriter(MI), TII(TII), MRI(MRI) {
738 NumDefs = MI.getDesc().getNumDefs();
739 }
740
741 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
742 /// All such sources need to be considered rewritable in order to
743 /// rewrite a uncoalescable copy-like instruction. This method return
744 /// each definition that must be checked if rewritable.
745 ///
746 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
747 unsigned &TrackReg,
748 unsigned &TrackSubReg) override {
749 // Find the next non-dead definition and continue from there.
750 if (CurrentSrcIdx == NumDefs)
751 return false;
752
753 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
754 ++CurrentSrcIdx;
755 if (CurrentSrcIdx == NumDefs)
756 return false;
757 }
758
759 // What we track are the alternative sources of the definition.
760 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
761 TrackReg = MODef.getReg();
762 TrackSubReg = MODef.getSubReg();
763
764 CurrentSrcIdx++;
765 return true;
766 }
767
768 /// \brief Rewrite the current source with \p NewSrcReg and \p NewSrcSubReg
769 /// by creating a new COPY instruction. \p DefReg and \p DefSubReg contain the
770 /// definition to be rewritten from the original copylike instruction.
771 /// \return The new COPY if the rewriting was possible, nullptr otherwise.
772 MachineInstr *RewriteCurrentSource(unsigned DefReg, unsigned DefSubReg,
773 unsigned NewSrcReg,
774 unsigned NewSrcSubReg) override {
775 assert(!TargetRegisterInfo::isPhysicalRegister(DefReg) &&
776 "We do not rewrite physical registers");
777
778 const TargetRegisterClass *DefRC = MRI.getRegClass(DefReg);
779 unsigned NewVR = MRI.createVirtualRegister(DefRC);
780
781 MachineInstr *NewCopy =
782 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
783 TII.get(TargetOpcode::COPY), NewVR)
784 .addReg(NewSrcReg, 0, NewSrcSubReg);
785
786 NewCopy->getOperand(0).setSubReg(DefSubReg);
787 if (DefSubReg)
788 NewCopy->getOperand(0).setIsUndef();
789
790 MRI.replaceRegWith(DefReg, NewVR);
791 MRI.clearKillFlags(NewVR);
792
793 return NewCopy;
794 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000795};
796
797/// \brief Specialized rewriter for INSERT_SUBREG instruction.
798class InsertSubregRewriter : public CopyRewriter {
799public:
800 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
801 assert(MI.isInsertSubreg() && "Invalid instruction");
802 }
803
804 /// \brief See CopyRewriter::getNextRewritableSource.
805 /// Here CopyLike has the following form:
806 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
807 /// Src1 has the same register class has dst, hence, there is
808 /// nothing to rewrite.
809 /// Src2.src2SubIdx, may not be register coalescer friendly.
810 /// Therefore, the first call to this method returns:
811 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
812 /// (TrackReg, TrackSubReg) = (dst, subIdx).
813 ///
814 /// Subsequence calls will return false.
815 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
816 unsigned &TrackReg,
817 unsigned &TrackSubReg) override {
818 // If we already get the only source we can rewrite, return false.
819 if (CurrentSrcIdx == 2)
820 return false;
821 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
822 CurrentSrcIdx = 2;
823 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
824 SrcReg = MOInsertedReg.getReg();
825 SrcSubReg = MOInsertedReg.getSubReg();
826 const MachineOperand &MODef = CopyLike.getOperand(0);
827
828 // We want to track something that is compatible with the
829 // partial definition.
830 TrackReg = MODef.getReg();
831 if (MODef.getSubReg())
832 // Bails if we have to compose sub-register indices.
833 return false;
834 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
835 return true;
836 }
837 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
838 if (CurrentSrcIdx != 2)
839 return false;
840 // We are rewriting the inserted reg.
841 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
842 MO.setReg(NewReg);
843 MO.setSubReg(NewSubReg);
844 return true;
845 }
846};
847
848/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
849class ExtractSubregRewriter : public CopyRewriter {
850 const TargetInstrInfo &TII;
851
852public:
853 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
854 : CopyRewriter(MI), TII(TII) {
855 assert(MI.isExtractSubreg() && "Invalid instruction");
856 }
857
858 /// \brief See CopyRewriter::getNextRewritableSource.
859 /// Here CopyLike has the following form:
860 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
861 /// There is only one rewritable source: Src.subIdx,
862 /// which defines dst.dstSubIdx.
863 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
864 unsigned &TrackReg,
865 unsigned &TrackSubReg) override {
866 // If we already get the only source we can rewrite, return false.
867 if (CurrentSrcIdx == 1)
868 return false;
869 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
870 CurrentSrcIdx = 1;
871 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
872 SrcReg = MOExtractedReg.getReg();
873 // If we have to compose sub-register indices, bails out.
874 if (MOExtractedReg.getSubReg())
875 return false;
876
877 SrcSubReg = CopyLike.getOperand(2).getImm();
878
879 // We want to track something that is compatible with the definition.
880 const MachineOperand &MODef = CopyLike.getOperand(0);
881 TrackReg = MODef.getReg();
882 TrackSubReg = MODef.getSubReg();
883 return true;
884 }
885
886 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
887 // The only source we can rewrite is the input register.
888 if (CurrentSrcIdx != 1)
889 return false;
890
891 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
892
893 // If we find a source that does not require to extract something,
894 // rewrite the operation with a copy.
895 if (!NewSubReg) {
896 // Move the current index to an invalid position.
897 // We do not want another call to this method to be able
898 // to do any change.
899 CurrentSrcIdx = -1;
900 // Rewrite the operation as a COPY.
901 // Get rid of the sub-register index.
902 CopyLike.RemoveOperand(2);
903 // Morph the operation into a COPY.
904 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
905 return true;
906 }
907 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
908 return true;
909 }
910};
911
912/// \brief Specialized rewriter for REG_SEQUENCE instruction.
913class RegSequenceRewriter : public CopyRewriter {
914public:
915 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
916 assert(MI.isRegSequence() && "Invalid instruction");
917 }
918
919 /// \brief See CopyRewriter::getNextRewritableSource.
920 /// Here CopyLike has the following form:
921 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
922 /// Each call will return a different source, walking all the available
923 /// source.
924 ///
925 /// The first call returns:
926 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
927 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
928 ///
929 /// The second call returns:
930 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
931 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
932 ///
933 /// And so on, until all the sources have been traversed, then
934 /// it returns false.
935 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
936 unsigned &TrackReg,
937 unsigned &TrackSubReg) override {
938 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
939
940 // If this is the first call, move to the first argument.
941 if (CurrentSrcIdx == 0) {
942 CurrentSrcIdx = 1;
943 } else {
944 // Otherwise, move to the next argument and check that it is valid.
945 CurrentSrcIdx += 2;
946 if (CurrentSrcIdx >= CopyLike.getNumOperands())
947 return false;
948 }
949 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
950 SrcReg = MOInsertedReg.getReg();
951 // If we have to compose sub-register indices, bails out.
952 if ((SrcSubReg = MOInsertedReg.getSubReg()))
953 return false;
954
955 // We want to track something that is compatible with the related
956 // partial definition.
957 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
958
959 const MachineOperand &MODef = CopyLike.getOperand(0);
960 TrackReg = MODef.getReg();
961 // If we have to compose sub-registers, bails.
962 return MODef.getSubReg() == 0;
963 }
964
965 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
966 // We cannot rewrite out of bound operands.
967 // Moreover, rewritable sources are at odd positions.
968 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
969 return false;
970
971 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
972 MO.setReg(NewReg);
973 MO.setSubReg(NewSubReg);
974 return true;
975 }
976};
977} // End namespace.
978
979/// \brief Get the appropriated CopyRewriter for \p MI.
980/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
981/// if no rewriter works for \p MI.
982static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000983 const TargetInstrInfo &TII,
984 MachineRegisterInfo &MRI) {
985 // Handle uncoalescable copy-like instructions.
986 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
987 MI.isExtractSubregLike()))
988 return new UncoalescableRewriter(MI, TII, MRI);
989
Quentin Colombet03e43f82014-08-20 17:41:48 +0000990 switch (MI.getOpcode()) {
991 default:
992 return nullptr;
993 case TargetOpcode::COPY:
994 return new CopyRewriter(MI);
995 case TargetOpcode::INSERT_SUBREG:
996 return new InsertSubregRewriter(MI);
997 case TargetOpcode::EXTRACT_SUBREG:
998 return new ExtractSubregRewriter(MI, TII);
999 case TargetOpcode::REG_SEQUENCE:
1000 return new RegSequenceRewriter(MI);
1001 }
1002 llvm_unreachable(nullptr);
1003}
1004
1005/// \brief Optimize generic copy instructions to avoid cross
1006/// register bank copy. The optimization looks through a chain of
1007/// copies and tries to find a source that has a compatible register
1008/// class.
1009/// Two register classes are considered to be compatible if they share
1010/// the same register bank.
1011/// New copies issued by this optimization are register allocator
1012/// friendly. This optimization does not remove any copy as it may
1013/// overconstraint the register allocator, but replaces some operands
1014/// when possible.
1015/// \pre isCoalescableCopy(*MI) is true.
1016/// \return True, when \p MI has been rewritten. False otherwise.
1017bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1018 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1019 assert(MI->getDesc().getNumDefs() == 1 &&
1020 "Coalescer can understand multiple defs?!");
1021 const MachineOperand &MODef = MI->getOperand(0);
1022 // Do not rewrite physical definitions.
1023 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1024 return false;
1025
1026 bool Changed = false;
1027 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001028 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Quentin Colombet03e43f82014-08-20 17:41:48 +00001029 // If none exists, bails out.
1030 if (!CpyRewriter)
1031 return false;
1032 // Rewrite each rewritable source.
1033 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1034 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1035 TrackSubReg)) {
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001036 unsigned NewSrc = TrackReg;
1037 unsigned NewSubReg = TrackSubReg;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001038 // Try to find a more suitable source. If we failed to do so, or get the
1039 // actual source, move to the next source.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001040 if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
Quentin Colombet03e43f82014-08-20 17:41:48 +00001041 continue;
1042 // Rewrite source.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001043 if (CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001044 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001045 MRI->clearKillFlags(NewSrc);
Quentin Colombet6b363372014-08-21 21:34:06 +00001046 Changed = true;
1047 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001048 }
1049 // TODO: We could have a clean-up method to tidy the instruction.
1050 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1051 // => v0 = COPY v1
1052 // Currently we haven't seen motivating example for that and we
1053 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001054 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001055 return Changed;
1056}
1057
1058/// \brief Optimize copy-like instructions to create
1059/// register coalescer friendly instruction.
1060/// The optimization tries to kill-off the \p MI by looking
1061/// through a chain of copies to find a source that has a compatible
1062/// register class.
1063/// If such a source is found, it replace \p MI by a generic COPY
1064/// operation.
1065/// \pre isUncoalescableCopy(*MI) is true.
1066/// \return True, when \p MI has been optimized. In that case, \p MI has
1067/// been removed from its parent.
1068/// All COPY instructions created, are inserted in \p LocalMIs.
1069bool PeepholeOptimizer::optimizeUncoalescableCopy(
1070 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1071 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1072
1073 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001074 SmallVector<
1075 std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
1076 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001077 // Get the right rewriter for the current copy.
1078 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1079 // If none exists, bails out.
1080 if (!CpyRewriter)
1081 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001082
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001083 // Rewrite each rewritable source by generating new COPYs. This works
1084 // differently from optimizeCoalescableCopy since it first makes sure that all
1085 // definitions can be rewritten.
1086 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1087 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1088 TrackSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001089 // If a physical register is here, this is probably for a good reason.
1090 // Do not rewrite that.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001091 if (TargetRegisterInfo::isPhysicalRegister(TrackReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001092 return false;
1093
1094 // If we do not know how to rewrite this definition, there is no point
1095 // in trying to kill this instruction.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001096 TargetInstrInfo::RegSubRegPair Def(TrackReg, TrackSubReg);
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001097 TargetInstrInfo::RegSubRegPair Src = Def;
1098 if (!findNextSource(Src.Reg, Src.SubReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001099 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001100
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001101 RewritePairs.push_back(std::make_pair(Def, Src));
Quentin Colombet03e43f82014-08-20 17:41:48 +00001102 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001103
Quentin Colombet03e43f82014-08-20 17:41:48 +00001104 // The change is possible for all defs, do it.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +00001105 for (const auto &PairDefSrc : RewritePairs) {
1106 const auto &Def = PairDefSrc.first;
1107 const auto &Src = PairDefSrc.second;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001108
Quentin Colombet03e43f82014-08-20 17:41:48 +00001109 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001110 MachineInstr *NewCopy = CpyRewriter->RewriteCurrentSource(
1111 Def.Reg, Def.SubReg, Src.Reg, Src.SubReg);
1112 assert(NewCopy && "Should be able to always generate a new copy");
1113
1114 // We extended the lifetime of Src and clear the kill flags to
1115 // account for that.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001116 MRI->clearKillFlags(Src.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001117 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001118 }
1119 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001120 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001121 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001122 return true;
1123}
1124
Manman Ren5759d012012-08-02 00:56:42 +00001125/// isLoadFoldable - Check whether MI is a candidate for folding into a later
1126/// instruction. We only fold loads to virtual registers and the virtual
1127/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001128bool PeepholeOptimizer::isLoadFoldable(
1129 MachineInstr *MI,
1130 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001131 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1132 return false;
1133 const MCInstrDesc &MCID = MI->getDesc();
1134 if (MCID.getNumDefs() != 1)
1135 return false;
1136
1137 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001138 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001139 // loads. It should be checked when processing uses of the load, since
1140 // uses can be removed during peephole.
1141 if (!MI->getOperand(0).getSubReg() &&
1142 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001143 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001144 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001145 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001146 }
1147 return false;
1148}
1149
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001150bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1151 SmallSet<unsigned, 4> &ImmDefRegs,
1152 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001153 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001154 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001155 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001156 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001157 return false;
1158 unsigned Reg = MI->getOperand(0).getReg();
1159 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1160 ImmDefMIs.insert(std::make_pair(Reg, MI));
1161 ImmDefRegs.insert(Reg);
1162 return true;
1163 }
Andrew Trick9e761992012-02-08 21:22:43 +00001164
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001165 return false;
1166}
1167
Jim Grosbachedcb8682012-05-01 23:21:41 +00001168/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001169/// immediate instructions, i.e. a trivial constant folding optimization, if
1170/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001171bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001172 SmallSet<unsigned, 4> &ImmDefRegs,
1173 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1174 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1175 MachineOperand &MO = MI->getOperand(i);
1176 if (!MO.isReg() || MO.isDef())
1177 continue;
1178 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001179 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001180 continue;
1181 if (ImmDefRegs.count(Reg) == 0)
1182 continue;
1183 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1184 assert(II != ImmDefMIs.end());
1185 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1186 ++NumImmFold;
1187 return true;
1188 }
1189 }
1190 return false;
1191}
1192
Eric Christopher2181fb22014-10-15 21:06:25 +00001193bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1194 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001195 return false;
1196
Craig Topper588ceec2012-12-17 03:56:00 +00001197 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001198 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001199
Evan Cheng2ce016c2010-11-15 21:20:45 +00001200 if (DisablePeephole)
1201 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001202
Eric Christopher2181fb22014-10-15 21:06:25 +00001203 TII = MF.getSubtarget().getInstrInfo();
1204 TRI = MF.getSubtarget().getRegisterInfo();
1205 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001206 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001207
1208 bool Changed = false;
1209
Eric Christopher2181fb22014-10-15 21:06:25 +00001210 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001211 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001212
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001213 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001214
1215 // During this forward scan, at some point it needs to answer the question
1216 // "given a pointer to an MI in the current BB, is it located before or
1217 // after the current instruction".
1218 // To perform this, the following set keeps track of the MIs already seen
1219 // during the scan, if a MI is not in the set, it is assumed to be located
1220 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001221 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001222 SmallSet<unsigned, 4> ImmDefRegs;
1223 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1224 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001225
1226 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001227 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001228 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001229 // We may be erasing MI below, increment MII now.
1230 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001231 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001232
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001233 // Skip debug values. They should not affect this peephole optimization.
1234 if (MI->isDebugValue())
1235 continue;
1236
Manman Ren5759d012012-08-02 00:56:42 +00001237 // If there exists an instruction which belongs to the following
Lang Hames5dc14bd2014-04-02 22:59:58 +00001238 // categories, we will discard the load candidates.
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001239 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001240 MI->isKill() || MI->isInlineAsm() ||
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001241 MI->hasUnmodeledSideEffects()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001242 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001243 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001244 }
Manman Ren5759d012012-08-02 00:56:42 +00001245 if (MI->mayStore() || MI->isCall())
Lang Hames5dc14bd2014-04-02 22:59:58 +00001246 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001247
Quentin Colombet03e43f82014-08-20 17:41:48 +00001248 if ((isUncoalescableCopy(*MI) &&
1249 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001250 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001251 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001252 // MI is deleted.
1253 LocalMIs.erase(MI);
1254 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001255 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001256 }
1257
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001258 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1259 Changed = true;
1260 continue;
1261 }
1262
Quentin Colombet03e43f82014-08-20 17:41:48 +00001263 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1264 // MI is just rewritten.
1265 Changed = true;
1266 continue;
1267 }
1268
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001269 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001270 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001271 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001272 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001273 // optimizeExtInstr might have created new instructions after MI
1274 // and before the already incremented MII. Adjust MII so that the
1275 // next iteration sees the new instructions.
1276 MII = MI;
1277 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001278 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001279 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001280 }
Evan Cheng98196b42011-02-15 05:00:24 +00001281
Manman Ren5759d012012-08-02 00:56:42 +00001282 // Check whether MI is a load candidate for folding into a later
1283 // instruction. If MI is not a candidate, check whether we can fold an
1284 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001285 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1286 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001287 const MCInstrDesc &MIDesc = MI->getDesc();
1288 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1289 ++i) {
1290 const MachineOperand &MOp = MI->getOperand(i);
1291 if (!MOp.isReg())
1292 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001293 unsigned FoldAsLoadDefReg = MOp.getReg();
1294 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1295 // We need to fold load after optimizeCmpInstr, since
1296 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1297 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1298 // we need it for markUsesInDebugValueAsUndef().
1299 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001300 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001301 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1302 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001303 DefMI);
1304 if (FoldMI) {
1305 // Update LocalMIs since we replaced MI with FoldMI and deleted
1306 // DefMI.
1307 DEBUG(dbgs() << "Replacing: " << *MI);
1308 DEBUG(dbgs() << " With: " << *FoldMI);
1309 LocalMIs.erase(MI);
1310 LocalMIs.erase(DefMI);
1311 LocalMIs.insert(FoldMI);
1312 MI->eraseFromParent();
1313 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001314 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1315 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001316 ++NumLoadFold;
1317 // MI is replaced with FoldMI.
1318 Changed = true;
1319 break;
1320 }
1321 }
Manman Ren5759d012012-08-02 00:56:42 +00001322 }
1323 }
Bill Wendlingca678352010-08-09 23:59:04 +00001324 }
1325 }
1326
1327 return Changed;
1328}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001329
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001330ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001331 assert(Def->isCopy() && "Invalid definition");
1332 // Copy instruction are supposed to be: Def = Src.
1333 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001334 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001335
1336 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1337 // If we look for a different subreg, it means we want a subreg of src.
1338 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001339 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001340 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001341 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001342 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001343}
1344
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001345ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001346 assert(Def->isBitcast() && "Invalid definition");
1347
1348 // Bail if there are effects that a plain copy will not expose.
1349 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001350 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001351
1352 // Bitcasts with more than one def are not supported.
1353 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001354 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001355 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1356 // If we look for a different subreg, it means we want a subreg of the src.
1357 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001358 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001359
Quentin Colombet03e43f82014-08-20 17:41:48 +00001360 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001361 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1362 ++OpIdx) {
1363 const MachineOperand &MO = Def->getOperand(OpIdx);
1364 if (!MO.isReg() || !MO.getReg())
1365 continue;
1366 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1367 if (SrcIdx != EndOpIdx)
1368 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001369 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001370 SrcIdx = OpIdx;
1371 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001372 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001373 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001374}
1375
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001376ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001377 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1378 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001379
1380 if (Def->getOperand(DefIdx).getSubReg())
1381 // If we are composing subreg, bails out.
1382 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1383 // This should almost never happen as the SSA property is tracked at
1384 // the register level (as opposed to the subreg level).
1385 // I.e.,
1386 // Def.sub0 =
1387 // Def.sub1 =
1388 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1389 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001390 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001391 // Def.sub0 (i.e, not defining the other subregs) and we would
1392 // have this case.
1393 // If we can ascertain (or force) that this never happens, we could
1394 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001395 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001396
Quentin Colombet03e43f82014-08-20 17:41:48 +00001397 if (!TII)
1398 // We could handle the REG_SEQUENCE here, but we do not want to
1399 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001400 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001401
1402 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1403 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001404 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001405
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001406 // We are looking at:
1407 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1408 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001409 for (auto &RegSeqInput : RegSeqInputRegs) {
1410 if (RegSeqInput.SubIdx == DefSubReg) {
1411 if (RegSeqInput.SubReg)
1412 // Bails if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001413 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001414
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001415 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001416 }
1417 }
1418
1419 // If the subreg we are tracking is super-defined by another subreg,
1420 // we could follow this value. However, this would require to compose
1421 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001422 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001423}
1424
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001425ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001426 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1427 "Invalid definition");
1428
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001429 if (Def->getOperand(DefIdx).getSubReg())
1430 // If we are composing subreg, bails out.
1431 // Same remark as getNextSourceFromRegSequence.
1432 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001433 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001434
Quentin Colombet68962302014-08-21 00:19:16 +00001435 if (!TII)
1436 // We could handle the REG_SEQUENCE here, but we do not want to
1437 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001438 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001439
Quentin Colombet03e43f82014-08-20 17:41:48 +00001440 TargetInstrInfo::RegSubRegPair BaseReg;
1441 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001442 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001443 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001444
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001445 // We are looking at:
1446 // Def = INSERT_SUBREG v0, v1, sub1
1447 // There are two cases:
1448 // 1. DefSubReg == sub1, get v1.
1449 // 2. DefSubReg != sub1, the value may be available through v0.
1450
Quentin Colombet03e43f82014-08-20 17:41:48 +00001451 // #1 Check if the inserted register matches the required sub index.
1452 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001453 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001454 }
1455 // #2 Otherwise, if the sub register we are looking for is not partial
1456 // defined by the inserted element, we can look through the main
1457 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001458 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001459 // If the result register (Def) and the base register (v0) do not
1460 // have the same register class or if we have to compose
1461 // subregisters, bails out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001462 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1463 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001464 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001465
Quentin Colombet03e43f82014-08-20 17:41:48 +00001466 // Get the TRI and check if the inserted sub-register overlaps with the
1467 // sub-register we are tracking.
1468 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001469 if (!TRI ||
1470 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001471 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001472 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001473 // At this point, the value is available in v0 via the same subreg
1474 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001475 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001476}
1477
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001478ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001479 assert((Def->isExtractSubreg() ||
1480 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001481 // We are looking at:
1482 // Def = EXTRACT_SUBREG v0, sub0
1483
1484 // Bails if we have to compose sub registers.
1485 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1486 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001487 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001488
Quentin Colombet67639df2014-08-20 23:13:02 +00001489 if (!TII)
1490 // We could handle the EXTRACT_SUBREG here, but we do not want to
1491 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001492 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001493
Quentin Colombet03e43f82014-08-20 17:41:48 +00001494 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001495 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001496 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001497
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001498 // Bails if we have to compose sub registers.
1499 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001500 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001501 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001502 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001503 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001504}
1505
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001506ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001507 assert(Def->isSubregToReg() && "Invalid definition");
1508 // We are looking at:
1509 // Def = SUBREG_TO_REG Imm, v0, sub0
1510
1511 // Bails if we have to compose sub registers.
1512 // If DefSubReg != sub0, we would have to check that all the bits
1513 // we track are included in sub0 and if yes, we would have to
1514 // determine the right subreg in v0.
1515 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001516 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001517 // Bails if we have to compose sub registers.
1518 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1519 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001520 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001521
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001522 return ValueTrackerResult(Def->getOperand(2).getReg(),
1523 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001524}
1525
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001526ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001527 assert(Def && "This method needs a valid definition");
1528
1529 assert(
1530 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1531 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1532 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001533 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001534 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001535 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001536 // All the remaining cases involve "complex" instructions.
1537 // Bails if we did not ask for the advanced tracking.
1538 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001539 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001540 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001541 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001542 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001543 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001544 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001545 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001546 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001547 return getNextSourceFromSubregToReg();
1548 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001549}
1550
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001551ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001552 // If we reach a point where we cannot move up in the use-def chain,
1553 // there is nothing we can get.
1554 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001555 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001556
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001557 ValueTrackerResult Res = getNextSourceImpl();
1558 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001559 // Update definition, definition index, and subregister for the
1560 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001561 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001562 bool OneRegSrc = Res.getNumSources() == 1;
1563 if (OneRegSrc)
1564 Reg = Res.getSrcReg(0);
1565 // Update the result before moving up in the use-def chain
1566 // with the instruction containing the last found sources.
1567 Res.setInst(Def);
1568
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001569 // If we can still move up in the use-def chain, move to the next
1570 // defintion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001571 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001572 Def = MRI.getVRegDef(Reg);
1573 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001574 DefSubReg = Res.getSrcSubReg(0);
1575 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001576 }
1577 }
1578 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001579 // for the next iteration. Make sure any new call to getNextSource bails out
1580 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001581 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001582 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001583}