blob: 1320f9985553e9f232e629b9bf400768c2cba70b [file] [log] [blame]
Eugene Zelenko32a40562017-09-11 23:00:48 +00001//===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
Bill Wendlingca678352010-08-09 23:59:04 +00002//
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
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000069#include "llvm/ADT/DenseMap.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000070#include "llvm/ADT/Optional.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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000073#include "llvm/ADT/SmallVector.h"
Bill Wendlingca678352010-08-09 23:59:04 +000074#include "llvm/ADT/Statistic.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000075#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000076#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000077#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000078#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000079#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000080#include "llvm/CodeGen/MachineInstrBuilder.h"
Taewook Oh0e35ea32017-06-29 23:11:24 +000081#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000082#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000083#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000084#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000085#include "llvm/CodeGen/TargetOpcodes.h"
86#include "llvm/CodeGen/TargetRegisterInfo.h"
87#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000088#include "llvm/MC/LaneBitmask.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000089#include "llvm/MC/MCInstrDesc.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000090#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000091#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000092#include "llvm/Support/Debug.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000093#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000094#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000095#include <cassert>
96#include <cstdint>
97#include <memory>
Quentin Colombet03e43f82014-08-20 17:41:48 +000098#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000099
Bill Wendlingca678352010-08-09 23:59:04 +0000100using namespace llvm;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000101using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
102using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
Bill Wendlingca678352010-08-09 23:59:04 +0000103
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000104#define DEBUG_TYPE "peephole-opt"
105
Bill Wendlingca678352010-08-09 23:59:04 +0000106// Optimize Extensions
107static cl::opt<bool>
108Aggressive("aggressive-ext-opt", cl::Hidden,
109 cl::desc("Aggressive extension optimization"));
110
Bill Wendlingc6627ee2010-11-01 20:41:43 +0000111static cl::opt<bool>
112DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
113 cl::desc("Disable the peephole optimizer"));
114
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000115/// Specifiy whether or not the value tracking looks through
116/// complex instructions. When this is true, the value tracker
117/// bails on everything that is not a copy or a bitcast.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000118static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +0000119DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000120 cl::desc("Disable advanced copy optimization"));
121
JF Bastien1ac69942015-12-03 23:43:56 +0000122static cl::opt<bool> DisableNAPhysCopyOpt(
123 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
124 cl::desc("Disable non-allocatable physical register copy optimization"));
125
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000126// Limit the number of PHI instructions to process
127// in PeepholeOptimizer::getNextSource.
128static cl::opt<unsigned> RewritePHILimit(
129 "rewrite-phi-limit", cl::Hidden, cl::init(10),
130 cl::desc("Limit the length of PHI chains to lookup"));
131
Taewook Oh0e35ea32017-06-29 23:11:24 +0000132// Limit the length of recurrence chain when evaluating the benefit of
133// commuting operands.
134static cl::opt<unsigned> MaxRecurrenceChain(
135 "recurrence-chain-limit", cl::Hidden, cl::init(3),
136 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
137 "of commuting operands"));
138
139
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000140STATISTIC(NumReuse, "Number of extension results reused");
141STATISTIC(NumCmps, "Number of compares eliminated");
142STATISTIC(NumImmFold, "Number of move immediate folded");
143STATISTIC(NumLoadFold, "Number of loads folded");
144STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000145STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
146STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
JF Bastien1ac69942015-12-03 23:43:56 +0000147STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
Bill Wendlingca678352010-08-09 23:59:04 +0000148
149namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000150
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000151 class ValueTrackerResult;
Taewook Oh0e35ea32017-06-29 23:11:24 +0000152 class RecurrenceInstr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000153
Bill Wendlingca678352010-08-09 23:59:04 +0000154 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000155 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000156 const TargetRegisterInfo *TRI;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000157 MachineRegisterInfo *MRI;
158 MachineDominatorTree *DT; // Machine dominator tree
159 MachineLoopInfo *MLI;
Bill Wendlingca678352010-08-09 23:59:04 +0000160
161 public:
162 static char ID; // Pass identification
Eugene Zelenko1804a772016-08-25 00:45:04 +0000163
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000164 PeepholeOptimizer() : MachineFunctionPass(ID) {
165 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
166 }
Bill Wendlingca678352010-08-09 23:59:04 +0000167
Craig Topper4584cd52014-03-07 09:26:03 +0000168 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000169
Craig Topper4584cd52014-03-07 09:26:03 +0000170 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000171 AU.setPreservesCFG();
172 MachineFunctionPass::getAnalysisUsage(AU);
Taewook Oh0e35ea32017-06-29 23:11:24 +0000173 AU.addRequired<MachineLoopInfo>();
174 AU.addPreserved<MachineLoopInfo>();
Bill Wendlingca678352010-08-09 23:59:04 +0000175 if (Aggressive) {
176 AU.addRequired<MachineDominatorTree>();
177 AU.addPreserved<MachineDominatorTree>();
178 }
179 }
180
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000181 /// Track Def -> Use info used for rewriting copies.
182 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000183
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000184 /// Sequence of instructions that formulate recurrence cycle.
Eugene Zelenko32a40562017-09-11 23:00:48 +0000185 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
Taewook Oh0e35ea32017-06-29 23:11:24 +0000186
Bill Wendlingca678352010-08-09 23:59:04 +0000187 private:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000188 bool optimizeCmpInstr(MachineInstr &MI);
189 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000190 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000191 bool optimizeSelect(MachineInstr &MI,
Mehdi Amini22e59742015-01-13 07:07:13 +0000192 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000193 bool optimizeCondBranch(MachineInstr &MI);
194 bool optimizeCoalescableCopy(MachineInstr &MI);
195 bool optimizeUncoalescableCopy(MachineInstr &MI,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000196 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Taewook Oh0e35ea32017-06-29 23:11:24 +0000197 bool optimizeRecurrence(MachineInstr &PHI);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000198 bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
199 bool isMoveImmediate(MachineInstr &MI,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000200 SmallSet<unsigned, 4> &ImmDefRegs,
201 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000202 bool foldImmediate(MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000203 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Eugene Zelenko32a40562017-09-11 23:00:48 +0000204
Taewook Oh0e35ea32017-06-29 23:11:24 +0000205 /// \brief Finds recurrence cycles, but only ones that formulated around
206 /// a def operand and a use operand that are tied. If there is a use
207 /// operand commutable with the tied use operand, find recurrence cycle
208 /// along that operand as well.
209 bool findTargetRecurrence(unsigned Reg,
210 const SmallSet<unsigned, 2> &TargetReg,
211 RecurrenceCycle &RC);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000212
213 /// \brief If copy instruction \p MI is a virtual register copy, track it in
JF Bastien1ac69942015-12-03 23:43:56 +0000214 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
Matt Arsenault10aa8072015-09-25 20:22:12 +0000215 /// previously seen as a copy, replace the uses of this copy with the
216 /// previously seen copy's destination register.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000217 bool foldRedundantCopy(MachineInstr &MI,
JF Bastien1ac69942015-12-03 23:43:56 +0000218 SmallSet<unsigned, 4> &CopySrcRegs,
219 DenseMap<unsigned, MachineInstr *> &CopyMIs);
220
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000221 /// Is the register \p Reg a non-allocatable physical register?
JF Bastien1ac69942015-12-03 23:43:56 +0000222 bool isNAPhysCopy(unsigned Reg);
223
224 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
225 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
226 /// non-allocatable physical register was previously copied to a virtual
227 /// registered and hasn't been clobbered, the virt->phys copy can be
228 /// deleted.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000229 bool foldRedundantNAPhysCopy(MachineInstr &MI,
JF Bastien1ac69942015-12-03 23:43:56 +0000230 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000231
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000232 bool isLoadFoldable(MachineInstr &MI,
Lang Hames5dc14bd2014-04-02 22:59:58 +0000233 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000234
235 /// \brief Check whether \p MI is understood by the register coalescer
236 /// but may require some rewriting.
237 bool isCoalescableCopy(const MachineInstr &MI) {
238 // SubregToRegs are not interesting, because they are already register
239 // coalescer friendly.
240 return MI.isCopy() || (!DisableAdvCopyOpt &&
241 (MI.isRegSequence() || MI.isInsertSubreg() ||
242 MI.isExtractSubreg()));
243 }
244
245 /// \brief Check whether \p MI is a copy like instruction that is
246 /// not recognized by the register coalescer.
247 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000248 return MI.isBitcast() ||
249 (!DisableAdvCopyOpt &&
250 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
251 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000252 }
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000253
254 MachineInstr &rewriteSource(MachineInstr &CopyLike,
255 RegSubRegPair Def, RewriteMapTy &RewriteMap);
Bill Wendlingca678352010-08-09 23:59:04 +0000256 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000257
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000258 /// Helper class to hold instructions that are inside recurrence cycles.
259 /// The recurrence cycle is formulated around 1) a def operand and its
Taewook Oh0e35ea32017-06-29 23:11:24 +0000260 /// tied use operand, or 2) a def operand and a use operand that is commutable
261 /// with another use operand which is tied to the def operand. In the latter
262 /// case, index of the tied use operand and the commutable use operand are
263 /// maintained with CommutePair.
264 class RecurrenceInstr {
265 public:
Eugene Zelenko32a40562017-09-11 23:00:48 +0000266 using IndexPair = std::pair<unsigned, unsigned>;
Taewook Oh0e35ea32017-06-29 23:11:24 +0000267
268 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
269 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
270 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
271
272 MachineInstr *getMI() const { return MI; }
273 Optional<IndexPair> getCommutePair() const { return CommutePair; }
274
275 private:
276 MachineInstr *MI;
277 Optional<IndexPair> CommutePair;
278 };
279
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000280 /// Helper class to hold a reply for ValueTracker queries.
281 /// Contains the returned sources for a given search and the instructions
282 /// where the sources were tracked from.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000283 class ValueTrackerResult {
284 private:
285 /// Track all sources found by one ValueTracker query.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000286 SmallVector<RegSubRegPair, 2> RegSrcs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000287
288 /// Instruction using the sources in 'RegSrcs'.
Eugene Zelenko32a40562017-09-11 23:00:48 +0000289 const MachineInstr *Inst = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000290
291 public:
Eugene Zelenko32a40562017-09-11 23:00:48 +0000292 ValueTrackerResult() = default;
293
294 ValueTrackerResult(unsigned Reg, unsigned SubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000295 addSource(Reg, SubReg);
296 }
297
298 bool isValid() const { return getNumSources() > 0; }
299
300 void setInst(const MachineInstr *I) { Inst = I; }
301 const MachineInstr *getInst() const { return Inst; }
302
303 void clear() {
304 RegSrcs.clear();
305 Inst = nullptr;
306 }
307
308 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000309 RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000310 }
311
312 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
313 assert(Idx < getNumSources() && "Reg pair source out of index");
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000314 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000315 }
316
317 int getNumSources() const { return RegSrcs.size(); }
318
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000319 RegSubRegPair getSrc(int Idx) const {
320 return RegSrcs[Idx];
321 }
322
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000323 unsigned getSrcReg(int Idx) const {
324 assert(Idx < getNumSources() && "Reg source out of index");
325 return RegSrcs[Idx].Reg;
326 }
327
328 unsigned getSrcSubReg(int Idx) const {
329 assert(Idx < getNumSources() && "SubReg source out of index");
330 return RegSrcs[Idx].SubReg;
331 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000332
333 bool operator==(const ValueTrackerResult &Other) {
334 if (Other.getInst() != getInst())
335 return false;
336
337 if (Other.getNumSources() != getNumSources())
338 return false;
339
340 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
341 if (Other.getSrcReg(i) != getSrcReg(i) ||
342 Other.getSrcSubReg(i) != getSrcSubReg(i))
343 return false;
344 return true;
345 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000346 };
347
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000348 /// \brief Helper class to track the possible sources of a value defined by
349 /// a (chain of) copy related instructions.
350 /// Given a definition (instruction and definition index), this class
351 /// follows the use-def chain to find successive suitable sources.
352 /// The given source can be used to rewrite the definition into
353 /// def = COPY src.
354 ///
355 /// For instance, let us consider the following snippet:
356 /// v0 =
357 /// v2 = INSERT_SUBREG v1, v0, sub0
358 /// def = COPY v2.sub0
359 ///
360 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
361 /// suitable sources:
362 /// v2.sub0 and v0.
363 /// Then, def can be rewritten into def = COPY v0.
364 class ValueTracker {
365 private:
366 /// The current point into the use-def chain.
Eugene Zelenko32a40562017-09-11 23:00:48 +0000367 const MachineInstr *Def = nullptr;
368
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000369 /// The index of the definition in Def.
Eugene Zelenko32a40562017-09-11 23:00:48 +0000370 unsigned DefIdx = 0;
371
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000372 /// The sub register index of the definition.
373 unsigned DefSubReg;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000374
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000375 /// The register where the value can be found.
376 unsigned Reg;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000377
Quentin Colombet03e43f82014-08-20 17:41:48 +0000378 /// MachineRegisterInfo used to perform tracking.
379 const MachineRegisterInfo &MRI;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000380
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000381 /// Optional TargetInstrInfo used to perform some complex tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000382 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000383
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000384 /// Dispatcher to the right underlying implementation of getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000385 ValueTrackerResult getNextSourceImpl();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000386
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000387 /// Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000388 ValueTrackerResult getNextSourceFromCopy();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000389
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000390 /// Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000391 ValueTrackerResult getNextSourceFromBitcast();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000392
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000393 /// Specialized version of getNextSource for RegSequence instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000394 ValueTrackerResult getNextSourceFromRegSequence();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000395
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000396 /// Specialized version of getNextSource for InsertSubreg instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000397 ValueTrackerResult getNextSourceFromInsertSubreg();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000398
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000399 /// Specialized version of getNextSource for ExtractSubreg instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000400 ValueTrackerResult getNextSourceFromExtractSubreg();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000401
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000402 /// Specialized version of getNextSource for SubregToReg instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000403 ValueTrackerResult getNextSourceFromSubregToReg();
Eugene Zelenko32a40562017-09-11 23:00:48 +0000404
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000405 /// Specialized version of getNextSource for PHI instructions.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000406 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000407
408 public:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000409 /// Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000410 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000411 /// track. It does not need to match the sub register index used in the
412 /// definition of \p Reg.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000413 /// If \p Reg is a physical register, a value tracker constructed with
414 /// this constructor will not find any alternative source.
415 /// Indeed, when \p Reg is a physical register that constructor does not
416 /// know which definition of \p Reg it should track.
417 /// Use the next constructor to track a physical register.
418 ValueTracker(unsigned Reg, unsigned DefSubReg,
419 const MachineRegisterInfo &MRI,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000420 const TargetInstrInfo *TII = nullptr)
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000421 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000422 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
423 Def = MRI.getVRegDef(Reg);
424 DefIdx = MRI.def_begin(Reg).getOperandNo();
425 }
426 }
427
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000428 /// \brief Following the use-def chain, get the next available source
429 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000430 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000431 /// and sub registers with tracked values. A ValueTrackerResult with
432 /// an empty set of registers means no source was found.
433 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000434 };
Eugene Zelenko1804a772016-08-25 00:45:04 +0000435
436} // end anonymous namespace
Bill Wendlingca678352010-08-09 23:59:04 +0000437
438char PeepholeOptimizer::ID = 0;
Eugene Zelenko32a40562017-09-11 23:00:48 +0000439
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000440char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Eugene Zelenko1804a772016-08-25 00:45:04 +0000441
Matt Arsenault44540a32016-07-08 16:29:11 +0000442INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000443 "Peephole Optimizations", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000444INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Taewook Oh0e35ea32017-06-29 23:11:24 +0000445INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matt Arsenault44540a32016-07-08 16:29:11 +0000446INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000447 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000448
Sanjay Patel59309cc2015-12-29 18:14:06 +0000449/// If instruction is a copy-like instruction, i.e. it reads a single register
450/// and writes a single register and it does not modify the source, and if the
451/// source value is preserved as a sub-register of the result, then replace all
452/// reachable uses of the source with the subreg of the result.
Andrew Trick9e761992012-02-08 21:22:43 +0000453///
Bill Wendlingca678352010-08-09 23:59:04 +0000454/// Do not generate an EXTRACT that is used only in a debug use, as this changes
455/// the code. Since this code does not currently share EXTRACTs, just ignore all
456/// debug uses.
457bool PeepholeOptimizer::
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000458optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000459 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000460 unsigned SrcReg, DstReg, SubIdx;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000461 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
Bill Wendlingca678352010-08-09 23:59:04 +0000462 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000463
Bill Wendlingca678352010-08-09 23:59:04 +0000464 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
465 TargetRegisterInfo::isPhysicalRegister(SrcReg))
466 return false;
467
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000468 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000469 // No other uses.
470 return false;
471
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000472 // Ensure DstReg can get a register class that actually supports
473 // sub-registers. Don't change the class until we commit.
474 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000475 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000476 if (!DstRC)
477 return false;
478
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000479 // The ext instr may be operating on a sub-register of SrcReg as well.
480 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
481 // register.
482 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
483 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000484 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000485 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000486
Bill Wendlingca678352010-08-09 23:59:04 +0000487 // The source has other uses. See if we can replace the other uses with use of
488 // the result of the extension.
489 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000490 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
491 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000492
493 // Uses that are in the same BB of uses of the result of the instruction.
494 SmallVector<MachineOperand*, 8> Uses;
495
496 // Uses that the result of the instruction can reach.
497 SmallVector<MachineOperand*, 8> ExtendedUses;
498
499 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000500 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000501 MachineInstr *UseMI = UseMO.getParent();
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000502 if (UseMI == &MI)
Bill Wendlingca678352010-08-09 23:59:04 +0000503 continue;
504
505 if (UseMI->isPHI()) {
506 ExtendLife = false;
507 continue;
508 }
509
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000510 // Only accept uses of SrcReg:SubIdx.
511 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
512 continue;
513
Bill Wendlingca678352010-08-09 23:59:04 +0000514 // It's an error to translate this:
515 //
516 // %reg1025 = <sext> %reg1024
517 // ...
518 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
519 //
520 // into this:
521 //
522 // %reg1025 = <sext> %reg1024
523 // ...
524 // %reg1027 = COPY %reg1025:4
525 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
526 //
527 // The problem here is that SUBREG_TO_REG is there to assert that an
528 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
529 // the COPY here, it will give us the value after the <sext>, not the
530 // original value of %reg1024 before <sext>.
531 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
532 continue;
533
534 MachineBasicBlock *UseMBB = UseMI->getParent();
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000535 if (UseMBB == &MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000536 // Local uses that come after the extension.
537 if (!LocalMIs.count(UseMI))
538 Uses.push_back(&UseMO);
539 } else if (ReachedBBs.count(UseMBB)) {
540 // Non-local uses where the result of the extension is used. Always
541 // replace these unless it's a PHI.
542 Uses.push_back(&UseMO);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000543 } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
Bill Wendlingca678352010-08-09 23:59:04 +0000544 // We may want to extend the live range of the extension result in order
545 // to replace these uses.
546 ExtendedUses.push_back(&UseMO);
547 } else {
548 // Both will be live out of the def MBB anyway. Don't extend live range of
549 // the extension result.
550 ExtendLife = false;
551 break;
552 }
553 }
554
555 if (ExtendLife && !ExtendedUses.empty())
556 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000557 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000558
559 // Now replace all uses.
560 bool Changed = false;
561 if (!Uses.empty()) {
562 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
563
564 // Look for PHI uses of the extended result, we don't want to extend the
565 // liveness of a PHI input. It breaks all kinds of assumptions down
566 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000567 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
568 if (UI.isPHI())
569 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000570
571 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
572 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
573 MachineOperand *UseMO = Uses[i];
574 MachineInstr *UseMI = UseMO->getParent();
575 MachineBasicBlock *UseMBB = UseMI->getParent();
576 if (PHIBBs.count(UseMBB))
577 continue;
578
Lang Hamesd5862ce2012-02-25 02:01:00 +0000579 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000580 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000581 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000582 MRI->constrainRegClass(DstReg, DstRC);
583 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000584
Bill Wendlingca678352010-08-09 23:59:04 +0000585 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000586 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
587 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000588 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000589 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
590 if (UseSrcSubIdx) {
591 Copy->getOperand(0).setSubReg(SubIdx);
592 Copy->getOperand(0).setIsUndef();
593 }
Bill Wendlingca678352010-08-09 23:59:04 +0000594 UseMO->setReg(NewVR);
595 ++NumReuse;
596 Changed = true;
597 }
598 }
599
600 return Changed;
601}
602
Sanjay Patel59309cc2015-12-29 18:14:06 +0000603/// If the instruction is a compare and the previous instruction it's comparing
604/// against already sets (or could be modified to set) the same flag as the
605/// compare, then we can remove the comparison and use the flag from the
606/// previous instruction.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000607bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
Bill Wendlingca678352010-08-09 23:59:04 +0000608 // If this instruction is a comparison against zero and isn't comparing a
609 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000610 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000611 int CmpMask, CmpValue;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000612 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
Manman Ren6fa76dc2012-06-29 21:33:59 +0000613 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
614 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000615 return false;
616
Bill Wendling27dddd12010-09-11 00:13:50 +0000617 // Attempt to optimize the comparison instruction.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000618 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000619 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000620 return true;
621 }
622
623 return false;
624}
625
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000626/// Optimize a select instruction.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000627bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
Mehdi Amini22e59742015-01-13 07:07:13 +0000628 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000629 unsigned TrueOp = 0;
630 unsigned FalseOp = 0;
631 bool Optimizable = false;
632 SmallVector<MachineOperand, 4> Cond;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000633 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000634 return false;
635 if (!Optimizable)
636 return false;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000637 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000638 return false;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000639 MI.eraseFromParent();
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000640 ++NumSelects;
641 return true;
642}
643
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000644/// Check if a simpler conditional branch can be generated.
645bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
646 return TII->optimizeCondBranch(MI);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000647}
648
Quentin Colombet03e43f82014-08-20 17:41:48 +0000649/// \brief Try to find the next source that share the same register file
650/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000651/// When true is returned, the \p RewriteMap can be used by the client to
652/// retrieve all Def -> Use along the way up to the next source. Any found
653/// Use that is not itself a key for another entry, is the next source to
654/// use. During the search for the next source, multiple sources can be found
655/// given multiple incoming sources of a PHI instruction. In this case, we
656/// look in each PHI source for the next source; all found next sources must
657/// share the same register file as \p Reg and \p SubReg. The client should
658/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000659/// \return False if no alternative sources are available. True otherwise.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000660bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000661 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000662 // Do not try to find a new source for a physical register.
663 // So far we do not have any motivating example for doing that.
664 // Thus, instead of maintaining untested code, we will revisit that if
665 // that changes at some point.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000666 unsigned Reg = RegSubReg.Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000667 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000668 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000669 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000670
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000671 SmallVector<RegSubRegPair, 4> SrcToLook;
672 RegSubRegPair CurSrcPair = RegSubReg;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000673 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000674
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000675 unsigned PHICount = 0;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000676 do {
677 CurSrcPair = SrcToLook.pop_back_val();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000678 // As explained above, do not handle physical registers
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000679 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000680 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000681
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000682 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000683
Matthias Braun08abcac2018-01-11 21:57:03 +0000684 // Follow the chain of copies until we find a more suitable source, a phi
685 // or have to abort.
686 while (true) {
687 ValueTrackerResult Res = ValTracker.getNextSource();
688 // Abort at the end of a chain (without finding a suitable source).
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000689 if (!Res.isValid())
Matthias Braun08abcac2018-01-11 21:57:03 +0000690 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000691
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000692 // Insert the Def -> Use entry for the recently found source.
693 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
694 if (CurSrcRes.isValid()) {
695 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
696 // An existent entry with multiple sources is a PHI cycle we must avoid.
697 // Otherwise it's an entry with a valid next source we already found.
698 if (CurSrcRes.getNumSources() > 1) {
699 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
700 return false;
701 }
702 break;
703 }
704 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
705
706 // ValueTrackerResult usually have one source unless it's the result from
707 // a PHI instruction. Add the found PHI edges to be looked up further.
708 unsigned NumSrcs = Res.getNumSources();
709 if (NumSrcs > 1) {
710 PHICount++;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000711 if (PHICount >= RewritePHILimit) {
712 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
713 return false;
714 }
715
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000716 for (unsigned i = 0; i < NumSrcs; ++i)
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000717 SrcToLook.push_back(Res.getSrc(i));
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000718 break;
719 }
720
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000721 CurSrcPair = Res.getSrc(0);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000722 // Do not extend the live-ranges of physical registers as they add
723 // constraints to the register allocator. Moreover, if we want to extend
724 // the live-range of a physical register, unlike SSA virtual register,
725 // we will have to check that they aren't redefine before the related use.
726 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
727 return false;
728
Matthias Braun08abcac2018-01-11 21:57:03 +0000729 // Keep following the chain if the value isn't any better yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000730 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000731 if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
732 CurSrcPair.SubReg))
Matthias Braun08abcac2018-01-11 21:57:03 +0000733 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000734
Matthias Braun08abcac2018-01-11 21:57:03 +0000735 // We currently cannot deal with subreg operands on PHI instructions
736 // (see insertPHI()).
737 if (PHICount > 0 && CurSrcPair.SubReg != 0)
738 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000739
Matthias Braun08abcac2018-01-11 21:57:03 +0000740 // We found a suitable source, and are done with this chain.
741 break;
742 }
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000743 } while (!SrcToLook.empty());
Quentin Colombetcf71c632013-09-13 18:26:31 +0000744
745 // If we did not find a more suitable source, there is nothing to optimize.
Rafael Espindola84921b92015-10-24 23:11:13 +0000746 return CurSrcPair.Reg != Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000747}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000748
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000749/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
750/// guaranteed to have the same register class. This is necessary whenever we
751/// successfully traverse a PHI instruction and find suitable sources coming
752/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
753/// suitable to be used in a new COPY instruction.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000754static MachineInstr &
755insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
756 const SmallVectorImpl<RegSubRegPair> &SrcRegs,
757 MachineInstr &OrigPHI) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000758 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
759
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000760 const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
Matthias Braun08abcac2018-01-11 21:57:03 +0000761 // NewRC is only correct if no subregisters are involved. findNextSource()
762 // should have rejected those cases already.
763 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000764 unsigned NewVR = MRI.createVirtualRegister(NewRC);
765 MachineBasicBlock *MBB = OrigPHI.getParent();
766 MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
767 TII.get(TargetOpcode::PHI), NewVR);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000768
769 unsigned MBBOpIdx = 2;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000770 for (const RegSubRegPair &RegPair : SrcRegs) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000771 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000772 MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000773 // Since we're extended the lifetime of RegPair.Reg, clear the
774 // kill flags to account for that and make RegPair.Reg reaches
775 // the new PHI.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000776 MRI.clearKillFlags(RegPair.Reg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000777 MBBOpIdx += 2;
778 }
779
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000780 return *MIB;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000781}
782
Quentin Colombet03e43f82014-08-20 17:41:48 +0000783namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000784
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000785/// Interface to query instructions amenable to copy rewriting.
786class Rewriter {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000787protected:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000788 MachineInstr &CopyLike;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000789 unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000790public:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000791 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
792 virtual ~Rewriter() {}
Quentin Colombet03e43f82014-08-20 17:41:48 +0000793
794 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000795 /// the related value that it affects (DstReg, DstSubReg).
Quentin Colombet03e43f82014-08-20 17:41:48 +0000796 /// A source is considered rewritable if its register class and the
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000797 /// register class of the related DstReg may not be register
Quentin Colombet03e43f82014-08-20 17:41:48 +0000798 /// coalescer friendly. In other words, given a copy-like instruction
799 /// not all the arguments may be returned at rewritable source, since
800 /// some arguments are none to be register coalescer friendly.
801 ///
802 /// Each call of this method moves the current source to the next
803 /// rewritable source.
804 /// For instance, let CopyLike be the instruction to rewrite.
805 /// CopyLike has one definition and one source:
806 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
807 ///
808 /// The first call will give the first rewritable source, i.e.,
809 /// the only source this instruction has:
810 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
811 /// This source defines the whole definition, i.e.,
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000812 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
Quentin Colombet03e43f82014-08-20 17:41:48 +0000813 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000814 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000815 /// rewritable source.
816 ///
817 /// \return True if a rewritable source has been found, false otherwise.
818 /// The output arguments are valid if and only if true is returned.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000819 virtual bool getNextRewritableSource(RegSubRegPair &Src,
820 RegSubRegPair &Dst) = 0;
821
822 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
823 /// \return True if the rewriting was possible, false otherwise.
824 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) = 0;
825};
826
827/// Rewriter for COPY instructions.
828class CopyRewriter : public Rewriter {
829public:
830 CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
831 assert(MI.isCopy() && "Expected copy instruction");
832 }
833 virtual ~CopyRewriter() = default;
834
835 bool getNextRewritableSource(RegSubRegPair &Src,
836 RegSubRegPair &Dst) override {
837 // CurrentSrcIdx > 0 means this function has already been called.
838 if (CurrentSrcIdx > 0)
Quentin Colombet03e43f82014-08-20 17:41:48 +0000839 return false;
840 // This is the first call to getNextRewritableSource.
841 // Move the CurrentSrcIdx to remember that we made that call.
842 CurrentSrcIdx = 1;
843 // The rewritable source is the argument.
844 const MachineOperand &MOSrc = CopyLike.getOperand(1);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000845 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000846 // What we track are the alternative sources of the definition.
847 const MachineOperand &MODef = CopyLike.getOperand(0);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000848 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000849 return true;
850 }
851
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000852 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
853 if (CurrentSrcIdx != 1)
Quentin Colombet03e43f82014-08-20 17:41:48 +0000854 return false;
855 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
856 MOSrc.setReg(NewReg);
857 MOSrc.setSubReg(NewSubReg);
858 return true;
859 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000860};
861
862/// \brief Helper class to rewrite uncoalescable copy like instructions
863/// into new COPY (coalescable friendly) instructions.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000864class UncoalescableRewriter : public Rewriter {
865 unsigned NumDefs; ///< Number of defs in the bitcast.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000866
867public:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000868 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000869 NumDefs = MI.getDesc().getNumDefs();
870 }
871
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000872 /// \see See Rewriter::getNextRewritableSource()
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000873 /// All such sources need to be considered rewritable in order to
874 /// rewrite a uncoalescable copy-like instruction. This method return
875 /// each definition that must be checked if rewritable.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000876 bool getNextRewritableSource(RegSubRegPair &Src,
877 RegSubRegPair &Dst) override {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000878 // Find the next non-dead definition and continue from there.
879 if (CurrentSrcIdx == NumDefs)
880 return false;
881
882 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
883 ++CurrentSrcIdx;
884 if (CurrentSrcIdx == NumDefs)
885 return false;
886 }
887
888 // What we track are the alternative sources of the definition.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000889 Src = RegSubRegPair(0, 0);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000890 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000891 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000892
893 CurrentSrcIdx++;
894 return true;
895 }
896
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000897 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
898 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000899 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000900};
901
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000902/// Specialized rewriter for INSERT_SUBREG instruction.
903class InsertSubregRewriter : public Rewriter {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000904public:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000905 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000906 assert(MI.isInsertSubreg() && "Invalid instruction");
907 }
908
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000909 /// \see See Rewriter::getNextRewritableSource()
Quentin Colombet03e43f82014-08-20 17:41:48 +0000910 /// Here CopyLike has the following form:
911 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
912 /// Src1 has the same register class has dst, hence, there is
913 /// nothing to rewrite.
914 /// Src2.src2SubIdx, may not be register coalescer friendly.
915 /// Therefore, the first call to this method returns:
916 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000917 /// (DstReg, DstSubReg) = (dst, subIdx).
Quentin Colombet03e43f82014-08-20 17:41:48 +0000918 ///
919 /// Subsequence calls will return false.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000920 bool getNextRewritableSource(RegSubRegPair &Src,
921 RegSubRegPair &Dst) override {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000922 // If we already get the only source we can rewrite, return false.
923 if (CurrentSrcIdx == 2)
924 return false;
925 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
926 CurrentSrcIdx = 2;
927 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000928 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000929 const MachineOperand &MODef = CopyLike.getOperand(0);
930
931 // We want to track something that is compatible with the
932 // partial definition.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000933 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +0000934 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000935 return false;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000936 Dst = RegSubRegPair(MODef.getReg(),
937 (unsigned)CopyLike.getOperand(3).getImm());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000938 return true;
939 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000940
Quentin Colombet03e43f82014-08-20 17:41:48 +0000941 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
942 if (CurrentSrcIdx != 2)
943 return false;
944 // We are rewriting the inserted reg.
945 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
946 MO.setReg(NewReg);
947 MO.setSubReg(NewSubReg);
948 return true;
949 }
950};
951
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000952/// Specialized rewriter for EXTRACT_SUBREG instruction.
953class ExtractSubregRewriter : public Rewriter {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000954 const TargetInstrInfo &TII;
955
956public:
957 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000958 : Rewriter(MI), TII(TII) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000959 assert(MI.isExtractSubreg() && "Invalid instruction");
960 }
961
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000962 /// \see Rewriter::getNextRewritableSource()
Quentin Colombet03e43f82014-08-20 17:41:48 +0000963 /// Here CopyLike has the following form:
964 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
965 /// There is only one rewritable source: Src.subIdx,
966 /// which defines dst.dstSubIdx.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000967 bool getNextRewritableSource(RegSubRegPair &Src,
968 RegSubRegPair &Dst) override {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000969 // If we already get the only source we can rewrite, return false.
970 if (CurrentSrcIdx == 1)
971 return false;
972 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
973 CurrentSrcIdx = 1;
974 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
Matt Arsenault30991562015-09-09 00:38:33 +0000975 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000976 if (MOExtractedReg.getSubReg())
977 return false;
978
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000979 Src = RegSubRegPair(MOExtractedReg.getReg(),
980 CopyLike.getOperand(2).getImm());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000981
982 // We want to track something that is compatible with the definition.
983 const MachineOperand &MODef = CopyLike.getOperand(0);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +0000984 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
Quentin Colombet03e43f82014-08-20 17:41:48 +0000985 return true;
986 }
987
988 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
989 // The only source we can rewrite is the input register.
990 if (CurrentSrcIdx != 1)
991 return false;
992
993 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
994
995 // If we find a source that does not require to extract something,
996 // rewrite the operation with a copy.
997 if (!NewSubReg) {
998 // Move the current index to an invalid position.
999 // We do not want another call to this method to be able
1000 // to do any change.
1001 CurrentSrcIdx = -1;
1002 // Rewrite the operation as a COPY.
1003 // Get rid of the sub-register index.
1004 CopyLike.RemoveOperand(2);
1005 // Morph the operation into a COPY.
1006 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1007 return true;
1008 }
1009 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1010 return true;
1011 }
1012};
1013
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001014/// Specialized rewriter for REG_SEQUENCE instruction.
1015class RegSequenceRewriter : public Rewriter {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001016public:
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001017 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001018 assert(MI.isRegSequence() && "Invalid instruction");
1019 }
1020
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001021 /// \see Rewriter::getNextRewritableSource()
Quentin Colombet03e43f82014-08-20 17:41:48 +00001022 /// Here CopyLike has the following form:
1023 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1024 /// Each call will return a different source, walking all the available
1025 /// source.
1026 ///
1027 /// The first call returns:
1028 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001029 /// (DstReg, DstSubReg) = (dst, subIdx1).
Quentin Colombet03e43f82014-08-20 17:41:48 +00001030 ///
1031 /// The second call returns:
1032 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001033 /// (DstReg, DstSubReg) = (dst, subIdx2).
Quentin Colombet03e43f82014-08-20 17:41:48 +00001034 ///
1035 /// And so on, until all the sources have been traversed, then
1036 /// it returns false.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001037 bool getNextRewritableSource(RegSubRegPair &Src,
1038 RegSubRegPair &Dst) override {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001039 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1040
1041 // If this is the first call, move to the first argument.
1042 if (CurrentSrcIdx == 0) {
1043 CurrentSrcIdx = 1;
1044 } else {
1045 // Otherwise, move to the next argument and check that it is valid.
1046 CurrentSrcIdx += 2;
1047 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1048 return false;
1049 }
1050 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001051 Src.Reg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001052 // If we have to compose sub-register indices, bail out.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001053 if ((Src.SubReg = MOInsertedReg.getSubReg()))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001054 return false;
1055
1056 // We want to track something that is compatible with the related
1057 // partial definition.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001058 Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001059
1060 const MachineOperand &MODef = CopyLike.getOperand(0);
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001061 Dst.Reg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001062 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001063 return MODef.getSubReg() == 0;
1064 }
1065
1066 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1067 // We cannot rewrite out of bound operands.
1068 // Moreover, rewritable sources are at odd positions.
1069 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1070 return false;
1071
1072 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1073 MO.setReg(NewReg);
1074 MO.setSubReg(NewSubReg);
1075 return true;
1076 }
1077};
Eugene Zelenko1804a772016-08-25 00:45:04 +00001078
Eugene Zelenko32a40562017-09-11 23:00:48 +00001079} // end anonymous namespace
Quentin Colombet03e43f82014-08-20 17:41:48 +00001080
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001081/// Get the appropriated Rewriter for \p MI.
1082/// \return A pointer to a dynamically allocated Rewriter or nullptr if no
1083/// rewriter works for \p MI.
1084static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001085 // Handle uncoalescable copy-like instructions.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001086 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1087 MI.isExtractSubregLike())
1088 return new UncoalescableRewriter(MI);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001089
Quentin Colombet03e43f82014-08-20 17:41:48 +00001090 switch (MI.getOpcode()) {
1091 default:
1092 return nullptr;
1093 case TargetOpcode::COPY:
1094 return new CopyRewriter(MI);
1095 case TargetOpcode::INSERT_SUBREG:
1096 return new InsertSubregRewriter(MI);
1097 case TargetOpcode::EXTRACT_SUBREG:
1098 return new ExtractSubregRewriter(MI, TII);
1099 case TargetOpcode::REG_SEQUENCE:
1100 return new RegSequenceRewriter(MI);
1101 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001102}
1103
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001104/// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1105/// the new source to use for rewrite. If \p HandleMultipleSources is true and
1106/// multiple sources for a given \p Def are found along the way, we found a
1107/// PHI instructions that needs to be rewritten.
1108/// TODO: HandleMultipleSources should be removed once we test PHI handling
1109/// with coalescable copies.
1110static RegSubRegPair
1111getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
1112 RegSubRegPair Def,
1113 const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1114 bool HandleMultipleSources = true) {
1115 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1116 while (true) {
1117 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1118 // If there are no entries on the map, LookupSrc is the new source.
1119 if (!Res.isValid())
1120 return LookupSrc;
1121
1122 // There's only one source for this definition, keep searching...
1123 unsigned NumSrcs = Res.getNumSources();
1124 if (NumSrcs == 1) {
1125 LookupSrc.Reg = Res.getSrcReg(0);
1126 LookupSrc.SubReg = Res.getSrcSubReg(0);
1127 continue;
1128 }
1129
1130 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1131 if (!HandleMultipleSources)
1132 break;
1133
1134 // Multiple sources, recurse into each source to find a new source
1135 // for it. Then, rewrite the PHI accordingly to its new edges.
1136 SmallVector<RegSubRegPair, 4> NewPHISrcs;
1137 for (unsigned i = 0; i < NumSrcs; ++i) {
1138 RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1139 NewPHISrcs.push_back(
1140 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1141 }
1142
1143 // Build the new PHI node and return its def register as the new source.
1144 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1145 MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1146 DEBUG(dbgs() << "-- getNewSource\n");
1147 DEBUG(dbgs() << " Replacing: " << OrigPHI);
1148 DEBUG(dbgs() << " With: " << NewPHI);
1149 const MachineOperand &MODef = NewPHI.getOperand(0);
1150 return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1151 }
1152
1153 return RegSubRegPair(0, 0);
1154}
1155
1156/// Optimize generic copy instructions to avoid cross register bank copy.
1157/// The optimization looks through a chain of copies and tries to find a source
1158/// that has a compatible register class.
1159/// Two register classes are considered to be compatible if they share the same
1160/// register bank.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001161/// New copies issued by this optimization are register allocator
1162/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001163/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001164/// when possible.
1165/// \pre isCoalescableCopy(*MI) is true.
1166/// \return True, when \p MI has been rewritten. False otherwise.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001167bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1168 assert(isCoalescableCopy(MI) && "Invalid argument");
1169 assert(MI.getDesc().getNumDefs() == 1 &&
Quentin Colombet03e43f82014-08-20 17:41:48 +00001170 "Coalescer can understand multiple defs?!");
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001171 const MachineOperand &MODef = MI.getOperand(0);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001172 // Do not rewrite physical definitions.
1173 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1174 return false;
1175
1176 bool Changed = false;
1177 // Get the right rewriter for the current copy.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001178 std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
Matt Arsenault30991562015-09-09 00:38:33 +00001179 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001180 if (!CpyRewriter)
1181 return false;
1182 // Rewrite each rewritable source.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001183 RegSubRegPair Src;
1184 RegSubRegPair TrackPair;
1185 while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001186 // Keep track of PHI nodes and its incoming edges when looking for sources.
1187 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001188 // Try to find a more suitable source. If we failed to do so, or get the
1189 // actual source, move to the next source.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001190 if (!findNextSource(TrackPair, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001191 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001192
1193 // Get the new source to rewrite. TODO: Only enable handling of multiple
1194 // sources (PHIs) once we have a motivating example and testcases for it.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001195 RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1196 /*HandleMultipleSources=*/false);
1197 if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001198 continue;
1199
Quentin Colombet03e43f82014-08-20 17:41:48 +00001200 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001201 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001202 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001203 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001204 Changed = true;
1205 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001206 }
1207 // TODO: We could have a clean-up method to tidy the instruction.
1208 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1209 // => v0 = COPY v1
1210 // Currently we haven't seen motivating example for that and we
1211 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001212 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001213 return Changed;
1214}
1215
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001216/// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
1217/// and create a new COPY instruction. More info about RewriteMap in
1218/// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1219/// Uncoalescable copies, since they are copy like instructions that aren't
1220/// recognized by the register allocator.
1221MachineInstr &
1222PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1223 RegSubRegPair Def, RewriteMapTy &RewriteMap) {
1224 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
1225 "We do not rewrite physical registers");
1226
1227 // Find the new source to use in the COPY rewrite.
1228 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1229
1230 // Insert the COPY.
1231 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1232 unsigned NewVReg = MRI->createVirtualRegister(DefRC);
1233
1234 MachineInstr *NewCopy =
1235 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1236 TII->get(TargetOpcode::COPY), NewVReg)
1237 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
1238
1239 if (Def.SubReg) {
1240 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1241 NewCopy->getOperand(0).setIsUndef();
1242 }
1243
1244 DEBUG(dbgs() << "-- RewriteSource\n");
1245 DEBUG(dbgs() << " Replacing: " << CopyLike);
1246 DEBUG(dbgs() << " With: " << *NewCopy);
1247 MRI->replaceRegWith(Def.Reg, NewVReg);
1248 MRI->clearKillFlags(NewVReg);
1249
1250 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1251 // account for that.
1252 MRI->clearKillFlags(NewSrc.Reg);
1253
1254 return *NewCopy;
1255}
1256
Quentin Colombet03e43f82014-08-20 17:41:48 +00001257/// \brief Optimize copy-like instructions to create
1258/// register coalescer friendly instruction.
1259/// The optimization tries to kill-off the \p MI by looking
1260/// through a chain of copies to find a source that has a compatible
1261/// register class.
1262/// If such a source is found, it replace \p MI by a generic COPY
1263/// operation.
1264/// \pre isUncoalescableCopy(*MI) is true.
1265/// \return True, when \p MI has been optimized. In that case, \p MI has
1266/// been removed from its parent.
1267/// All COPY instructions created, are inserted in \p LocalMIs.
1268bool PeepholeOptimizer::optimizeUncoalescableCopy(
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001269 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1270 assert(isUncoalescableCopy(MI) && "Invalid argument");
1271 UncoalescableRewriter CpyRewriter(MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001272
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001273 // Rewrite each rewritable source by generating new COPYs. This works
1274 // differently from optimizeCoalescableCopy since it first makes sure that all
1275 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001276 RewriteMapTy RewriteMap;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001277 RegSubRegPair Src;
1278 RegSubRegPair Def;
1279 SmallVector<RegSubRegPair, 4> RewritePairs;
1280 while (CpyRewriter.getNextRewritableSource(Src, Def)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001281 // If a physical register is here, this is probably for a good reason.
1282 // Do not rewrite that.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001283 if (TargetRegisterInfo::isPhysicalRegister(Def.Reg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001284 return false;
1285
1286 // If we do not know how to rewrite this definition, there is no point
1287 // in trying to kill this instruction.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001288 if (!findNextSource(Def, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001289 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001290
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001291 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001292 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001293
Quentin Colombet03e43f82014-08-20 17:41:48 +00001294 // The change is possible for all defs, do it.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001295 for (const RegSubRegPair &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001296 // Rewrite the "copy" in a way the register coalescer understands.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001297 MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1298 LocalMIs.insert(&NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001299 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001300
Quentin Colombet03e43f82014-08-20 17:41:48 +00001301 // MI is now dead.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001302 MI.eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001303 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001304 return true;
1305}
1306
Sanjay Patel59309cc2015-12-29 18:14:06 +00001307/// Check whether MI is a candidate for folding into a later instruction.
1308/// We only fold loads to virtual registers and the virtual register defined
1309/// has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001310bool PeepholeOptimizer::isLoadFoldable(
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001311 MachineInstr &MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1312 if (!MI.canFoldAsLoad() || !MI.mayLoad())
Manman Renba8122c2012-08-02 19:37:32 +00001313 return false;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001314 const MCInstrDesc &MCID = MI.getDesc();
Manman Renba8122c2012-08-02 19:37:32 +00001315 if (MCID.getNumDefs() != 1)
1316 return false;
1317
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001318 unsigned Reg = MI.getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001319 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001320 // loads. It should be checked when processing uses of the load, since
1321 // uses can be removed during peephole.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001322 if (!MI.getOperand(0).getSubReg() &&
Manman Renba8122c2012-08-02 19:37:32 +00001323 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001324 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001325 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001326 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001327 }
1328 return false;
1329}
1330
Sanjay Patelb120ae92015-12-29 19:34:53 +00001331bool PeepholeOptimizer::isMoveImmediate(
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001332 MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
Sanjay Patelb120ae92015-12-29 19:34:53 +00001333 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001334 const MCInstrDesc &MCID = MI.getDesc();
1335 if (!MI.isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001336 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001337 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001338 return false;
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001339 unsigned Reg = MI.getOperand(0).getReg();
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001340 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001341 ImmDefMIs.insert(std::make_pair(Reg, &MI));
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001342 ImmDefRegs.insert(Reg);
1343 return true;
1344 }
Andrew Trick9e761992012-02-08 21:22:43 +00001345
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001346 return false;
1347}
1348
Sanjay Patel59309cc2015-12-29 18:14:06 +00001349/// Try folding register operands that are defined by move immediate
1350/// instructions, i.e. a trivial constant folding optimization, if
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001351/// and only if the def and use are in the same BB.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001352bool PeepholeOptimizer::foldImmediate(MachineInstr &MI,
1353 SmallSet<unsigned, 4> &ImmDefRegs,
Sanjay Patelb120ae92015-12-29 19:34:53 +00001354 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001355 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1356 MachineOperand &MO = MI.getOperand(i);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001357 if (!MO.isReg() || MO.isDef())
1358 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001359 // Ignore dead implicit defs.
1360 if (MO.isImplicit() && MO.isDead())
1361 continue;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001362 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001363 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001364 continue;
1365 if (ImmDefRegs.count(Reg) == 0)
1366 continue;
1367 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
JF Bastien1ac69942015-12-03 23:43:56 +00001368 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001369 if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001370 ++NumImmFold;
1371 return true;
1372 }
1373 }
1374 return false;
1375}
1376
Matt Arsenault10aa8072015-09-25 20:22:12 +00001377// FIXME: This is very simple and misses some cases which should be handled when
1378// motivating examples are found.
1379//
1380// The copy rewriting logic should look at uses as well as defs and be able to
1381// eliminate copies across blocks.
1382//
1383// Later copies that are subregister extracts will also not be eliminated since
1384// only the first copy is considered.
1385//
1386// e.g.
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001387// %1 = COPY %0
1388// %2 = COPY %0:sub1
Matt Arsenault10aa8072015-09-25 20:22:12 +00001389//
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001390// Should replace %2 uses with %1:sub1
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001391bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI,
1392 SmallSet<unsigned, 4> &CopySrcRegs,
JF Bastien1ac69942015-12-03 23:43:56 +00001393 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001394 assert(MI.isCopy() && "expected a COPY machine instruction");
Matt Arsenault10aa8072015-09-25 20:22:12 +00001395
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001396 unsigned SrcReg = MI.getOperand(1).getReg();
Matt Arsenault10aa8072015-09-25 20:22:12 +00001397 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1398 return false;
1399
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001400 unsigned DstReg = MI.getOperand(0).getReg();
Matt Arsenault10aa8072015-09-25 20:22:12 +00001401 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1402 return false;
1403
1404 if (CopySrcRegs.insert(SrcReg).second) {
1405 // First copy of this reg seen.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001406 CopyMIs.insert(std::make_pair(SrcReg, &MI));
Matt Arsenault10aa8072015-09-25 20:22:12 +00001407 return false;
1408 }
1409
1410 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1411
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001412 unsigned SrcSubReg = MI.getOperand(1).getSubReg();
Matt Arsenault10aa8072015-09-25 20:22:12 +00001413 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1414
1415 // Can't replace different subregister extracts.
1416 if (SrcSubReg != PrevSrcSubReg)
1417 return false;
1418
1419 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1420
1421 // Only replace if the copy register class is the same.
1422 //
1423 // TODO: If we have multiple copies to different register classes, we may want
1424 // to track multiple copies of the same source register.
1425 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1426 return false;
1427
1428 MRI->replaceRegWith(DstReg, PrevDstReg);
1429
1430 // Lifetime of the previous copy has been extended.
1431 MRI->clearKillFlags(PrevDstReg);
1432 return true;
1433}
1434
JF Bastien1ac69942015-12-03 23:43:56 +00001435bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1436 return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1437 !MRI->isAllocatable(Reg);
1438}
1439
1440bool PeepholeOptimizer::foldRedundantNAPhysCopy(
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001441 MachineInstr &MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1442 assert(MI.isCopy() && "expected a COPY machine instruction");
JF Bastien1ac69942015-12-03 23:43:56 +00001443
1444 if (DisableNAPhysCopyOpt)
1445 return false;
1446
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001447 unsigned DstReg = MI.getOperand(0).getReg();
1448 unsigned SrcReg = MI.getOperand(1).getReg();
JF Bastien1ac69942015-12-03 23:43:56 +00001449 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001450 // %vreg = COPY %physreg
JF Bastien1ac69942015-12-03 23:43:56 +00001451 // Avoid using a datastructure which can track multiple live non-allocatable
1452 // phys->virt copies since LLVM doesn't seem to do this.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001453 NAPhysToVirtMIs.insert({SrcReg, &MI});
JF Bastien1ac69942015-12-03 23:43:56 +00001454 return false;
1455 }
1456
1457 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1458 return false;
1459
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001460 // %physreg = COPY %vreg
JF Bastien1ac69942015-12-03 23:43:56 +00001461 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1462 if (PrevCopy == NAPhysToVirtMIs.end()) {
1463 // We can't remove the copy: there was an intervening clobber of the
1464 // non-allocatable physical register after the copy to virtual.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001465 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001466 return false;
1467 }
1468
1469 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1470 if (PrevDstReg == SrcReg) {
1471 // Remove the virt->phys copy: we saw the virtual register definition, and
1472 // the non-allocatable physical register's state hasn't changed since then.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001473 DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001474 ++NumNAPhysCopies;
1475 return true;
1476 }
1477
1478 // Potential missed optimization opportunity: we saw a different virtual
1479 // register get a copy of the non-allocatable physical register, and we only
1480 // track one such copy. Avoid getting confused by this new non-allocatable
1481 // physical register definition, and remove it from the tracked copies.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001482 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001483 NAPhysToVirtMIs.erase(PrevCopy);
1484 return false;
1485}
1486
Taewook Oh0e35ea32017-06-29 23:11:24 +00001487/// \bried Returns true if \p MO is a virtual register operand.
1488static bool isVirtualRegisterOperand(MachineOperand &MO) {
1489 if (!MO.isReg())
1490 return false;
1491 return TargetRegisterInfo::isVirtualRegister(MO.getReg());
1492}
1493
1494bool PeepholeOptimizer::findTargetRecurrence(
1495 unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1496 RecurrenceCycle &RC) {
1497 // Recurrence found if Reg is in TargetRegs.
1498 if (TargetRegs.count(Reg))
1499 return true;
1500
1501 // TODO: Curerntly, we only allow the last instruction of the recurrence
1502 // cycle (the instruction that feeds the PHI instruction) to have more than
1503 // one uses to guarantee that commuting operands does not tie registers
1504 // with overlapping live range. Once we have actual live range info of
1505 // each register, this constraint can be relaxed.
1506 if (!MRI->hasOneNonDBGUse(Reg))
1507 return false;
1508
1509 // Give up if the reccurrence chain length is longer than the limit.
1510 if (RC.size() >= MaxRecurrenceChain)
1511 return false;
1512
1513 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1514 unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1515
1516 // Only interested in recurrences whose instructions have only one def, which
1517 // is a virtual register.
1518 if (MI.getDesc().getNumDefs() != 1)
1519 return false;
1520
1521 MachineOperand &DefOp = MI.getOperand(0);
1522 if (!isVirtualRegisterOperand(DefOp))
1523 return false;
1524
1525 // Check if def operand of MI is tied to any use operand. We are only
1526 // interested in the case that all the instructions in the recurrence chain
1527 // have there def operand tied with one of the use operand.
1528 unsigned TiedUseIdx;
1529 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1530 return false;
1531
1532 if (Idx == TiedUseIdx) {
1533 RC.push_back(RecurrenceInstr(&MI));
1534 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1535 } else {
1536 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1537 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1538 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1539 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1540 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1541 }
1542 }
1543
1544 return false;
1545}
1546
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001547/// Phi instructions will eventually be lowered to copy instructions.
1548/// If phi is in a loop header, a recurrence may formulated around the source
1549/// and destination of the phi. For such case commuting operands of the
1550/// instructions in the recurrence may enable coalescing of the copy instruction
1551/// generated from the phi. For example, if there is a recurrence of
Taewook Oh0e35ea32017-06-29 23:11:24 +00001552///
1553/// LoopHeader:
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001554/// %1 = phi(%0, %100)
Taewook Oh0e35ea32017-06-29 23:11:24 +00001555/// LoopLatch:
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001556/// %0<def, tied1> = ADD %2<def, tied0>, %1
Taewook Oh0e35ea32017-06-29 23:11:24 +00001557///
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001558/// , the fact that %0 and %2 are in the same tied operands set makes
Taewook Oh0e35ea32017-06-29 23:11:24 +00001559/// the coalescing of copy instruction generated from the phi in
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +00001560/// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1561/// %2 have overlapping live range. This introduces additional move
1562/// instruction to the final assembly. However, if we commute %2 and
1563/// %1 of ADD instruction, the redundant move instruction can be
Taewook Oh0e35ea32017-06-29 23:11:24 +00001564/// avoided.
1565bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1566 SmallSet<unsigned, 2> TargetRegs;
1567 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1568 MachineOperand &MO = PHI.getOperand(Idx);
1569 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1570 TargetRegs.insert(MO.getReg());
1571 }
1572
1573 bool Changed = false;
1574 RecurrenceCycle RC;
1575 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1576 // Commutes operands of instructions in RC if necessary so that the copy to
1577 // be generated from PHI can be coalesced.
1578 DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1579 for (auto &RI : RC) {
1580 DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1581 auto CP = RI.getCommutePair();
1582 if (CP) {
1583 Changed = true;
1584 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1585 (*CP).second);
1586 DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1587 }
1588 }
1589 }
1590
1591 return Changed;
1592}
1593
Eric Christopher2181fb22014-10-15 21:06:25 +00001594bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001595 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001596 return false;
1597
Craig Topper588ceec2012-12-17 03:56:00 +00001598 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001599 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001600
Evan Cheng2ce016c2010-11-15 21:20:45 +00001601 if (DisablePeephole)
1602 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001603
Eric Christopher2181fb22014-10-15 21:06:25 +00001604 TII = MF.getSubtarget().getInstrInfo();
1605 TRI = MF.getSubtarget().getRegisterInfo();
1606 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001607 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Taewook Oh0e35ea32017-06-29 23:11:24 +00001608 MLI = &getAnalysis<MachineLoopInfo>();
Bill Wendlingca678352010-08-09 23:59:04 +00001609
1610 bool Changed = false;
1611
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001612 for (MachineBasicBlock &MBB : MF) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001613 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001614
1615 // During this forward scan, at some point it needs to answer the question
1616 // "given a pointer to an MI in the current BB, is it located before or
1617 // after the current instruction".
1618 // To perform this, the following set keeps track of the MIs already seen
1619 // during the scan, if a MI is not in the set, it is assumed to be located
1620 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001621 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001622 SmallSet<unsigned, 4> ImmDefRegs;
1623 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1624 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001625
JF Bastien1ac69942015-12-03 23:43:56 +00001626 // Track when a non-allocatable physical register is copied to a virtual
1627 // register so that useless moves can be removed.
1628 //
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001629 // %physreg is the map index; MI is the last valid `%vreg = COPY %physreg`
1630 // without any intervening re-definition of %physreg.
JF Bastien1ac69942015-12-03 23:43:56 +00001631 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1632
Matt Arsenault10aa8072015-09-25 20:22:12 +00001633 // Set of virtual registers that are copied from.
1634 SmallSet<unsigned, 4> CopySrcRegs;
1635 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1636
Taewook Oh0e35ea32017-06-29 23:11:24 +00001637 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1638
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001639 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1640 MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001641 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001642 // We may be erasing MI below, increment MII now.
1643 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001644 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001645
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001646 // Skip debug values. They should not affect this peephole optimization.
1647 if (MI->isDebugValue())
1648 continue;
1649
Taewook Oh0e35ea32017-06-29 23:11:24 +00001650 if (MI->isPosition())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001651 continue;
1652
Taewook Oh0e35ea32017-06-29 23:11:24 +00001653 if (IsLoopHeader && MI->isPHI()) {
1654 if (optimizeRecurrence(*MI)) {
1655 Changed = true;
1656 continue;
1657 }
1658 }
1659
JF Bastien1ac69942015-12-03 23:43:56 +00001660 if (!MI->isCopy()) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001661 for (const MachineOperand &MO : MI->operands()) {
JF Bastien1ac69942015-12-03 23:43:56 +00001662 // Visit all operands: definitions can be implicit or explicit.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001663 if (MO.isReg()) {
1664 unsigned Reg = MO.getReg();
1665 if (MO.isDef() && isNAPhysCopy(Reg)) {
JF Bastien1ac69942015-12-03 23:43:56 +00001666 const auto &Def = NAPhysToVirtMIs.find(Reg);
1667 if (Def != NAPhysToVirtMIs.end()) {
1668 // A new definition of the non-allocatable physical register
1669 // invalidates previous copies.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001670 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001671 NAPhysToVirtMIs.erase(Def);
1672 }
1673 }
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001674 } else if (MO.isRegMask()) {
1675 const uint32_t *RegMask = MO.getRegMask();
JF Bastien1ac69942015-12-03 23:43:56 +00001676 for (auto &RegMI : NAPhysToVirtMIs) {
1677 unsigned Def = RegMI.first;
1678 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001679 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001680 NAPhysToVirtMIs.erase(Def);
1681 }
1682 }
1683 }
1684 }
1685 }
1686
1687 if (MI->isImplicitDef() || MI->isKill())
1688 continue;
1689
1690 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1691 // Blow away all non-allocatable physical registers knowledge since we
1692 // don't know what's correct anymore.
1693 //
1694 // FIXME: handle explicit asm clobbers.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001695 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI);
JF Bastien1ac69942015-12-03 23:43:56 +00001696 NAPhysToVirtMIs.clear();
JF Bastien1ac69942015-12-03 23:43:56 +00001697 }
1698
Quentin Colombet03e43f82014-08-20 17:41:48 +00001699 if ((isUncoalescableCopy(*MI) &&
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001700 optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1701 (MI->isCompare() && optimizeCmpInstr(*MI)) ||
1702 (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001703 // MI is deleted.
1704 LocalMIs.erase(MI);
1705 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001706 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001707 }
1708
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001709 if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001710 Changed = true;
1711 continue;
1712 }
1713
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001714 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001715 // MI is just rewritten.
1716 Changed = true;
1717 continue;
1718 }
1719
JF Bastien1ac69942015-12-03 23:43:56 +00001720 if (MI->isCopy() &&
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001721 (foldRedundantCopy(*MI, CopySrcRegs, CopySrcMIs) ||
1722 foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
Matt Arsenault10aa8072015-09-25 20:22:12 +00001723 LocalMIs.erase(MI);
1724 MI->eraseFromParent();
1725 Changed = true;
1726 continue;
1727 }
1728
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001729 if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001730 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001731 } else {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001732 Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001733 // optimizeExtInstr might have created new instructions after MI
1734 // and before the already incremented MII. Adjust MII so that the
1735 // next iteration sees the new instructions.
1736 MII = MI;
1737 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001738 if (SeenMoveImm)
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001739 Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001740 }
Evan Cheng98196b42011-02-15 05:00:24 +00001741
Manman Ren5759d012012-08-02 00:56:42 +00001742 // Check whether MI is a load candidate for folding into a later
1743 // instruction. If MI is not a candidate, check whether we can fold an
1744 // earlier load into MI.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001745 if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
Lang Hames5dc14bd2014-04-02 22:59:58 +00001746 !FoldAsLoadDefCandidates.empty()) {
Philip Reames1f1bbac2016-12-13 01:38:41 +00001747
1748 // We visit each operand even after successfully folding a previous
1749 // one. This allows us to fold multiple loads into a single
1750 // instruction. We do assume that optimizeLoadInstr doesn't insert
1751 // foldable uses earlier in the argument list. Since we don't restart
1752 // iteration, we'd miss such cases.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001753 const MCInstrDesc &MIDesc = MI->getDesc();
Philip Reames1f1bbac2016-12-13 01:38:41 +00001754 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
Lang Hames5dc14bd2014-04-02 22:59:58 +00001755 ++i) {
1756 const MachineOperand &MOp = MI->getOperand(i);
1757 if (!MOp.isReg())
1758 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001759 unsigned FoldAsLoadDefReg = MOp.getReg();
1760 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1761 // We need to fold load after optimizeCmpInstr, since
1762 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1763 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1764 // we need it for markUsesInDebugValueAsUndef().
1765 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001766 MachineInstr *DefMI = nullptr;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001767 if (MachineInstr *FoldMI =
1768 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001769 // Update LocalMIs since we replaced MI with FoldMI and deleted
1770 // DefMI.
1771 DEBUG(dbgs() << "Replacing: " << *MI);
1772 DEBUG(dbgs() << " With: " << *FoldMI);
1773 LocalMIs.erase(MI);
1774 LocalMIs.erase(DefMI);
1775 LocalMIs.insert(FoldMI);
1776 MI->eraseFromParent();
1777 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001778 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1779 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001780 ++NumLoadFold;
Taewook Oh0e35ea32017-06-29 23:11:24 +00001781
Philip Reames1f1bbac2016-12-13 01:38:41 +00001782 // MI is replaced with FoldMI so we can continue trying to fold
Lang Hames5dc14bd2014-04-02 22:59:58 +00001783 Changed = true;
Philip Reames1f1bbac2016-12-13 01:38:41 +00001784 MI = FoldMI;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001785 }
1786 }
Manman Ren5759d012012-08-02 00:56:42 +00001787 }
1788 }
Taewook Oh0e35ea32017-06-29 23:11:24 +00001789
Philip Reames1f1bbac2016-12-13 01:38:41 +00001790 // If we run into an instruction we can't fold across, discard
1791 // the load candidates. Note: We might be able to fold *into* this
1792 // instruction, so this needs to be after the folding logic.
1793 if (MI->isLoadFoldBarrier()) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001794 DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
Philip Reames1f1bbac2016-12-13 01:38:41 +00001795 FoldAsLoadDefCandidates.clear();
1796 }
Bill Wendlingca678352010-08-09 23:59:04 +00001797 }
1798 }
1799
1800 return Changed;
1801}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001802
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001803ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001804 assert(Def->isCopy() && "Invalid definition");
1805 // Copy instruction are supposed to be: Def = Src.
1806 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001807 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001808
1809 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1810 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001811 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001812 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001813 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001814 const MachineOperand &Src = Def->getOperand(1);
Matthias Braunea4359e2018-01-11 22:30:43 +00001815 if (Src.isUndef())
1816 return ValueTrackerResult();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001817 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001818}
1819
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001820ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001821 assert(Def->isBitcast() && "Invalid definition");
1822
1823 // Bail if there are effects that a plain copy will not expose.
1824 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001825 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001826
1827 // Bitcasts with more than one def are not supported.
1828 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001829 return ValueTrackerResult();
Matthias Braunba7d95d2017-01-09 21:38:17 +00001830 const MachineOperand DefOp = Def->getOperand(DefIdx);
1831 if (DefOp.getSubReg() != DefSubReg)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001832 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001833 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001834 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001835
Quentin Colombet03e43f82014-08-20 17:41:48 +00001836 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001837 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1838 ++OpIdx) {
1839 const MachineOperand &MO = Def->getOperand(OpIdx);
1840 if (!MO.isReg() || !MO.getReg())
1841 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001842 // Ignore dead implicit defs.
1843 if (MO.isImplicit() && MO.isDead())
1844 continue;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001845 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1846 if (SrcIdx != EndOpIdx)
1847 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001848 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001849 SrcIdx = OpIdx;
1850 }
Matthias Braunba7d95d2017-01-09 21:38:17 +00001851
1852 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1853 // will break the assumed guarantees for the upper bits.
1854 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1855 if (UseMI.isSubregToReg())
1856 return ValueTrackerResult();
1857 }
1858
Quentin Colombet03e43f82014-08-20 17:41:48 +00001859 const MachineOperand &Src = Def->getOperand(SrcIdx);
Matthias Braunea4359e2018-01-11 22:30:43 +00001860 if (Src.isUndef())
1861 return ValueTrackerResult();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001862 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001863}
1864
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001865ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001866 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1867 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001868
1869 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001870 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001871 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1872 // This should almost never happen as the SSA property is tracked at
1873 // the register level (as opposed to the subreg level).
1874 // I.e.,
1875 // Def.sub0 =
1876 // Def.sub1 =
1877 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1878 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001879 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001880 // Def.sub0 (i.e, not defining the other subregs) and we would
1881 // have this case.
1882 // If we can ascertain (or force) that this never happens, we could
1883 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001884 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001885
Quentin Colombet03e43f82014-08-20 17:41:48 +00001886 if (!TII)
1887 // We could handle the REG_SEQUENCE here, but we do not want to
1888 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001889 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001890
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001891 SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001892 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001893 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001894
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001895 // We are looking at:
1896 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1897 // Check if one of the operand defines the subreg we are interested in.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001898 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001899 if (RegSeqInput.SubIdx == DefSubReg) {
1900 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001901 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001902 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001903
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001904 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001905 }
1906 }
1907
1908 // If the subreg we are tracking is super-defined by another subreg,
1909 // we could follow this value. However, this would require to compose
1910 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001911 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001912}
1913
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001914ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001915 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1916 "Invalid definition");
1917
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001918 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001919 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001920 // Same remark as getNextSourceFromRegSequence.
1921 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001922 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001923
Quentin Colombet68962302014-08-21 00:19:16 +00001924 if (!TII)
1925 // We could handle the REG_SEQUENCE here, but we do not want to
1926 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001927 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001928
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001929 RegSubRegPair BaseReg;
1930 RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001931 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001932 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001933
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001934 // We are looking at:
1935 // Def = INSERT_SUBREG v0, v1, sub1
1936 // There are two cases:
1937 // 1. DefSubReg == sub1, get v1.
1938 // 2. DefSubReg != sub1, the value may be available through v0.
1939
Quentin Colombet03e43f82014-08-20 17:41:48 +00001940 // #1 Check if the inserted register matches the required sub index.
1941 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001942 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001943 }
1944 // #2 Otherwise, if the sub register we are looking for is not partial
1945 // defined by the inserted element, we can look through the main
1946 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001947 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001948 // If the result register (Def) and the base register (v0) do not
1949 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00001950 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001951 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1952 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001953 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001954
Quentin Colombet03e43f82014-08-20 17:41:48 +00001955 // Get the TRI and check if the inserted sub-register overlaps with the
1956 // sub-register we are tracking.
1957 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001958 if (!TRI ||
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001959 !(TRI->getSubRegIndexLaneMask(DefSubReg) &
1960 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001961 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001962 // At this point, the value is available in v0 via the same subreg
1963 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001964 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001965}
1966
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001967ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001968 assert((Def->isExtractSubreg() ||
1969 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001970 // We are looking at:
1971 // Def = EXTRACT_SUBREG v0, sub0
1972
Matt Arsenault30991562015-09-09 00:38:33 +00001973 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001974 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1975 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001976 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001977
Quentin Colombet67639df2014-08-20 23:13:02 +00001978 if (!TII)
1979 // We could handle the EXTRACT_SUBREG here, but we do not want to
1980 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001981 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001982
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00001983 RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001984 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001985 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001986
Matt Arsenault30991562015-09-09 00:38:33 +00001987 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001988 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001989 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001990 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001991 // Otherwise, the value is available in the v0.sub0.
Sanjay Patelb120ae92015-12-29 19:34:53 +00001992 return ValueTrackerResult(ExtractSubregInputReg.Reg,
1993 ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001994}
1995
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001996ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001997 assert(Def->isSubregToReg() && "Invalid definition");
1998 // We are looking at:
1999 // Def = SUBREG_TO_REG Imm, v0, sub0
2000
Matt Arsenault30991562015-09-09 00:38:33 +00002001 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002002 // If DefSubReg != sub0, we would have to check that all the bits
2003 // we track are included in sub0 and if yes, we would have to
2004 // determine the right subreg in v0.
2005 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002006 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00002007 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002008 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2009 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002010 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002011
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002012 return ValueTrackerResult(Def->getOperand(2).getReg(),
2013 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002014}
2015
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00002016/// Explore each PHI incoming operand and return its sources.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002017ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2018 assert(Def->isPHI() && "Invalid definition");
2019 ValueTrackerResult Res;
2020
Matt Arsenault30991562015-09-09 00:38:33 +00002021 // If we look for a different subreg, bail as we do not support composing
2022 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002023 if (Def->getOperand(0).getSubReg() != DefSubReg)
2024 return ValueTrackerResult();
2025
2026 // Return all register sources for PHI instructions.
2027 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00002028 const MachineOperand &MO = Def->getOperand(i);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002029 assert(MO.isReg() && "Invalid PHI instruction");
Matthias Braunea4359e2018-01-11 22:30:43 +00002030 // We have no code to deal with undef operands. They shouldn't happen in
2031 // normal programs anyway.
2032 if (MO.isUndef())
2033 return ValueTrackerResult();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002034 Res.addSource(MO.getReg(), MO.getSubReg());
2035 }
2036
2037 return Res;
2038}
2039
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002040ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002041 assert(Def && "This method needs a valid definition");
2042
Eric Liue617ade2016-07-04 12:10:08 +00002043 assert(((Def->getOperand(DefIdx).isDef() &&
2044 (DefIdx < Def->getDesc().getNumDefs() ||
2045 Def->getDesc().isVariadic())) ||
2046 Def->getOperand(DefIdx).isImplicit()) &&
2047 "Invalid DefIdx");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002048 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002049 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002050 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002051 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002052 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00002053 // Bail if we did not ask for the advanced tracking.
Matthias Braunbfd9c4a2018-01-11 22:59:33 +00002054 if (DisableAdvCopyOpt)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002055 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00002056 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002057 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00002058 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002059 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00002060 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002061 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002062 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002063 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00002064 if (Def->isPHI())
2065 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002066 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002067}
2068
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002069ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002070 // If we reach a point where we cannot move up in the use-def chain,
2071 // there is nothing we can get.
2072 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002073 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002074
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002075 ValueTrackerResult Res = getNextSourceImpl();
2076 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002077 // Update definition, definition index, and subregister for the
2078 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002079 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002080 bool OneRegSrc = Res.getNumSources() == 1;
2081 if (OneRegSrc)
2082 Reg = Res.getSrcReg(0);
2083 // Update the result before moving up in the use-def chain
2084 // with the instruction containing the last found sources.
2085 Res.setInst(Def);
2086
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002087 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002088 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002089 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Matthias Braunea4359e2018-01-11 22:30:43 +00002090 MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
2091 if (DI != MRI.def_end()) {
2092 Def = DI->getParent();
2093 DefIdx = DI.getOperandNo();
2094 DefSubReg = Res.getSrcSubReg(0);
2095 } else {
2096 Def = nullptr;
2097 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002098 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002099 }
2100 }
2101 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002102 // for the next iteration. Make sure any new call to getNextSource bails out
2103 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002104 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00002105 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00002106}