blob: da8fac6d3834a9486c1d7fd029baf5e067f0eba5 [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
Matt Arsenault30991562015-09-09 00:38:33 +000046// if it loads to virtual registers and the virtual register defined has
Joel Jones24e440d2012-12-11 16:10:25 +000047// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000069#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000070#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000071#include "llvm/ADT/SmallSet.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000072#include "llvm/ADT/SmallVector.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000074#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000075#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000076#include "llvm/CodeGen/MachineFunction.h"
77#include "llvm/CodeGen/MachineInstr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000078#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000079#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000080#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000081#include "llvm/CodeGen/Passes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000082#include "llvm/MC/MCInstrDesc.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000083#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000084#include "llvm/Support/Debug.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000085#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000086#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000087#include "llvm/Target/TargetInstrInfo.h"
88#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000089#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000090#include <cassert>
91#include <cstdint>
92#include <memory>
Quentin Colombet03e43f82014-08-20 17:41:48 +000093#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000094
Bill Wendlingca678352010-08-09 23:59:04 +000095using namespace llvm;
96
Chandler Carruth1b9dde02014-04-22 02:02:50 +000097#define DEBUG_TYPE "peephole-opt"
98
Bill Wendlingca678352010-08-09 23:59:04 +000099// Optimize Extensions
100static cl::opt<bool>
101Aggressive("aggressive-ext-opt", cl::Hidden,
102 cl::desc("Aggressive extension optimization"));
103
Bill Wendlingc6627ee2010-11-01 20:41:43 +0000104static cl::opt<bool>
105DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
106 cl::desc("Disable the peephole optimizer"));
107
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000108static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +0000109DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000110 cl::desc("Disable advanced copy optimization"));
111
JF Bastien1ac69942015-12-03 23:43:56 +0000112static cl::opt<bool> DisableNAPhysCopyOpt(
113 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
114 cl::desc("Disable non-allocatable physical register copy optimization"));
115
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000116// Limit the number of PHI instructions to process
117// in PeepholeOptimizer::getNextSource.
118static cl::opt<unsigned> RewritePHILimit(
119 "rewrite-phi-limit", cl::Hidden, cl::init(10),
120 cl::desc("Limit the length of PHI chains to lookup"));
121
Bill Wendling66284312010-08-27 20:39:09 +0000122STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000123STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000124STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000125STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000126STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000127STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
128STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
JF Bastien1ac69942015-12-03 23:43:56 +0000129STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
Bill Wendlingca678352010-08-09 23:59:04 +0000130
131namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000132
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000133 class ValueTrackerResult;
134
Bill Wendlingca678352010-08-09 23:59:04 +0000135 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000136 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000137 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000138 MachineRegisterInfo *MRI;
139 MachineDominatorTree *DT; // Machine dominator tree
140
141 public:
142 static char ID; // Pass identification
Eugene Zelenko1804a772016-08-25 00:45:04 +0000143
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000144 PeepholeOptimizer() : MachineFunctionPass(ID) {
145 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
146 }
Bill Wendlingca678352010-08-09 23:59:04 +0000147
Craig Topper4584cd52014-03-07 09:26:03 +0000148 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000149
Craig Topper4584cd52014-03-07 09:26:03 +0000150 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000151 AU.setPreservesCFG();
152 MachineFunctionPass::getAnalysisUsage(AU);
153 if (Aggressive) {
154 AU.addRequired<MachineDominatorTree>();
155 AU.addPreserved<MachineDominatorTree>();
156 }
157 }
158
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000159 /// \brief Track Def -> Use info used for rewriting copies.
160 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
161 RewriteMapTy;
162
Bill Wendlingca678352010-08-09 23:59:04 +0000163 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000164 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
165 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000166 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000167 bool optimizeSelect(MachineInstr *MI,
168 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000169 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000170 bool optimizeCoalescableCopy(MachineInstr *MI);
171 bool optimizeUncoalescableCopy(MachineInstr *MI,
172 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000173 bool findNextSource(unsigned Reg, unsigned SubReg,
174 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000175 bool isMoveImmediate(MachineInstr *MI,
176 SmallSet<unsigned, 4> &ImmDefRegs,
177 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000178 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000179 SmallSet<unsigned, 4> &ImmDefRegs,
180 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000181
182 /// \brief If copy instruction \p MI is a virtual register copy, track it in
JF Bastien1ac69942015-12-03 23:43:56 +0000183 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
Matt Arsenault10aa8072015-09-25 20:22:12 +0000184 /// previously seen as a copy, replace the uses of this copy with the
185 /// previously seen copy's destination register.
186 bool foldRedundantCopy(MachineInstr *MI,
JF Bastien1ac69942015-12-03 23:43:56 +0000187 SmallSet<unsigned, 4> &CopySrcRegs,
188 DenseMap<unsigned, MachineInstr *> &CopyMIs);
189
190 /// \brief Is the register \p Reg a non-allocatable physical register?
191 bool isNAPhysCopy(unsigned Reg);
192
193 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
194 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
195 /// non-allocatable physical register was previously copied to a virtual
196 /// registered and hasn't been clobbered, the virt->phys copy can be
197 /// deleted.
198 bool foldRedundantNAPhysCopy(
199 MachineInstr *MI,
200 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000201
Lang Hames5dc14bd2014-04-02 22:59:58 +0000202 bool isLoadFoldable(MachineInstr *MI,
203 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000204
205 /// \brief Check whether \p MI is understood by the register coalescer
206 /// but may require some rewriting.
207 bool isCoalescableCopy(const MachineInstr &MI) {
208 // SubregToRegs are not interesting, because they are already register
209 // coalescer friendly.
210 return MI.isCopy() || (!DisableAdvCopyOpt &&
211 (MI.isRegSequence() || MI.isInsertSubreg() ||
212 MI.isExtractSubreg()));
213 }
214
215 /// \brief Check whether \p MI is a copy like instruction that is
216 /// not recognized by the register coalescer.
217 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000218 return MI.isBitcast() ||
219 (!DisableAdvCopyOpt &&
220 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
221 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000222 }
Bill Wendlingca678352010-08-09 23:59:04 +0000223 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000224
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000225 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
226 /// returned sources for a given search and the instructions where the sources
227 /// were tracked from.
228 class ValueTrackerResult {
229 private:
230 /// Track all sources found by one ValueTracker query.
231 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
232
233 /// Instruction using the sources in 'RegSrcs'.
234 const MachineInstr *Inst;
235
236 public:
237 ValueTrackerResult() : Inst(nullptr) {}
238 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
239 addSource(Reg, SubReg);
240 }
241
242 bool isValid() const { return getNumSources() > 0; }
243
244 void setInst(const MachineInstr *I) { Inst = I; }
245 const MachineInstr *getInst() const { return Inst; }
246
247 void clear() {
248 RegSrcs.clear();
249 Inst = nullptr;
250 }
251
252 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
253 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
254 }
255
256 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
257 assert(Idx < getNumSources() && "Reg pair source out of index");
258 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
259 }
260
261 int getNumSources() const { return RegSrcs.size(); }
262
263 unsigned getSrcReg(int Idx) const {
264 assert(Idx < getNumSources() && "Reg source out of index");
265 return RegSrcs[Idx].Reg;
266 }
267
268 unsigned getSrcSubReg(int Idx) const {
269 assert(Idx < getNumSources() && "SubReg source out of index");
270 return RegSrcs[Idx].SubReg;
271 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000272
273 bool operator==(const ValueTrackerResult &Other) {
274 if (Other.getInst() != getInst())
275 return false;
276
277 if (Other.getNumSources() != getNumSources())
278 return false;
279
280 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
281 if (Other.getSrcReg(i) != getSrcReg(i) ||
282 Other.getSrcSubReg(i) != getSrcSubReg(i))
283 return false;
284 return true;
285 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000286 };
287
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000288 /// \brief Helper class to track the possible sources of a value defined by
289 /// a (chain of) copy related instructions.
290 /// Given a definition (instruction and definition index), this class
291 /// follows the use-def chain to find successive suitable sources.
292 /// The given source can be used to rewrite the definition into
293 /// def = COPY src.
294 ///
295 /// For instance, let us consider the following snippet:
296 /// v0 =
297 /// v2 = INSERT_SUBREG v1, v0, sub0
298 /// def = COPY v2.sub0
299 ///
300 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
301 /// suitable sources:
302 /// v2.sub0 and v0.
303 /// Then, def can be rewritten into def = COPY v0.
304 class ValueTracker {
305 private:
306 /// The current point into the use-def chain.
307 const MachineInstr *Def;
308 /// The index of the definition in Def.
309 unsigned DefIdx;
310 /// The sub register index of the definition.
311 unsigned DefSubReg;
312 /// The register where the value can be found.
313 unsigned Reg;
314 /// Specifiy whether or not the value tracking looks through
315 /// complex instructions. When this is false, the value tracker
316 /// bails on everything that is not a copy or a bitcast.
317 ///
318 /// Note: This could have been implemented as a specialized version of
319 /// the ValueTracker class but that would have complicated the code of
320 /// the users of this class.
321 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000322 /// MachineRegisterInfo used to perform tracking.
323 const MachineRegisterInfo &MRI;
324 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000325 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000326 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000327
328 /// \brief Dispatcher to the right underlying implementation of
329 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000330 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000331 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000332 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000333 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000334 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000335 /// \brief Specialized version of getNextSource for RegSequence
336 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000337 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000338 /// \brief Specialized version of getNextSource for InsertSubreg
339 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000340 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000341 /// \brief Specialized version of getNextSource for ExtractSubreg
342 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000343 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000344 /// \brief Specialized version of getNextSource for SubregToReg
345 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000346 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000347 /// \brief Specialized version of getNextSource for PHI instructions.
348 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000349
350 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000351 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000352 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000353 /// track. It does not need to match the sub register index used in the
354 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000355 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
356 /// through complex instructions. By default (false), it handles only copy
357 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000358 /// If \p Reg is a physical register, a value tracker constructed with
359 /// this constructor will not find any alternative source.
360 /// Indeed, when \p Reg is a physical register that constructor does not
361 /// know which definition of \p Reg it should track.
362 /// Use the next constructor to track a physical register.
363 ValueTracker(unsigned Reg, unsigned DefSubReg,
364 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000365 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000366 const TargetInstrInfo *TII = nullptr)
367 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
368 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
369 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
370 Def = MRI.getVRegDef(Reg);
371 DefIdx = MRI.def_begin(Reg).getOperandNo();
372 }
373 }
374
375 /// \brief Create a ValueTracker instance for the value defined by
376 /// the pair \p MI, \p DefIdx.
377 /// Unlike the other constructor, the value tracker produced by this one
378 /// may be able to find a new source when the definition is a physical
379 /// register.
380 /// This could be useful to rewrite target specific instructions into
381 /// generic copy instructions.
382 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
383 const MachineRegisterInfo &MRI,
384 bool UseAdvancedTracking = false,
385 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000386 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000387 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
388 assert(DefIdx < Def->getDesc().getNumDefs() &&
389 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000390 Reg = Def->getOperand(DefIdx).getReg();
391 }
392
393 /// \brief Following the use-def chain, get the next available source
394 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000395 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000396 /// and sub registers with tracked values. A ValueTrackerResult with
397 /// an empty set of registers means no source was found.
398 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000399
400 /// \brief Get the last register where the initial value can be found.
401 /// Initially this is the register of the definition.
402 /// Then, after each successful call to getNextSource, this is the
403 /// register of the last source.
404 unsigned getReg() const { return Reg; }
405 };
Eugene Zelenko1804a772016-08-25 00:45:04 +0000406
407} // end anonymous namespace
Bill Wendlingca678352010-08-09 23:59:04 +0000408
409char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000410char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Eugene Zelenko1804a772016-08-25 00:45:04 +0000411
Matt Arsenault44540a32016-07-08 16:29:11 +0000412INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
Owen Anderson8ac477f2010-10-12 19:48:12 +0000413 "Peephole Optimizations", false, false)
414INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Matt Arsenault44540a32016-07-08 16:29:11 +0000415INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
Owen Andersondf7a4f22010-10-07 22:25:06 +0000416 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000417
Sanjay Patel59309cc2015-12-29 18:14:06 +0000418/// If instruction is a copy-like instruction, i.e. it reads a single register
419/// and writes a single register and it does not modify the source, and if the
420/// source value is preserved as a sub-register of the result, then replace all
421/// reachable uses of the source with the subreg of the result.
Andrew Trick9e761992012-02-08 21:22:43 +0000422///
Bill Wendlingca678352010-08-09 23:59:04 +0000423/// Do not generate an EXTRACT that is used only in a debug use, as this changes
424/// the code. Since this code does not currently share EXTRACTs, just ignore all
425/// debug uses.
426bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000427optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000428 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000429 unsigned SrcReg, DstReg, SubIdx;
430 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
431 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000432
Bill Wendlingca678352010-08-09 23:59:04 +0000433 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
434 TargetRegisterInfo::isPhysicalRegister(SrcReg))
435 return false;
436
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000437 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000438 // No other uses.
439 return false;
440
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000441 // Ensure DstReg can get a register class that actually supports
442 // sub-registers. Don't change the class until we commit.
443 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000444 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000445 if (!DstRC)
446 return false;
447
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000448 // The ext instr may be operating on a sub-register of SrcReg as well.
449 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
450 // register.
451 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
452 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000453 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000454 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000455
Bill Wendlingca678352010-08-09 23:59:04 +0000456 // The source has other uses. See if we can replace the other uses with use of
457 // the result of the extension.
458 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000459 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
460 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000461
462 // Uses that are in the same BB of uses of the result of the instruction.
463 SmallVector<MachineOperand*, 8> Uses;
464
465 // Uses that the result of the instruction can reach.
466 SmallVector<MachineOperand*, 8> ExtendedUses;
467
468 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000469 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000470 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000471 if (UseMI == MI)
472 continue;
473
474 if (UseMI->isPHI()) {
475 ExtendLife = false;
476 continue;
477 }
478
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000479 // Only accept uses of SrcReg:SubIdx.
480 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
481 continue;
482
Bill Wendlingca678352010-08-09 23:59:04 +0000483 // It's an error to translate this:
484 //
485 // %reg1025 = <sext> %reg1024
486 // ...
487 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
488 //
489 // into this:
490 //
491 // %reg1025 = <sext> %reg1024
492 // ...
493 // %reg1027 = COPY %reg1025:4
494 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
495 //
496 // The problem here is that SUBREG_TO_REG is there to assert that an
497 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
498 // the COPY here, it will give us the value after the <sext>, not the
499 // original value of %reg1024 before <sext>.
500 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
501 continue;
502
503 MachineBasicBlock *UseMBB = UseMI->getParent();
504 if (UseMBB == MBB) {
505 // Local uses that come after the extension.
506 if (!LocalMIs.count(UseMI))
507 Uses.push_back(&UseMO);
508 } else if (ReachedBBs.count(UseMBB)) {
509 // Non-local uses where the result of the extension is used. Always
510 // replace these unless it's a PHI.
511 Uses.push_back(&UseMO);
512 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
513 // We may want to extend the live range of the extension result in order
514 // to replace these uses.
515 ExtendedUses.push_back(&UseMO);
516 } else {
517 // Both will be live out of the def MBB anyway. Don't extend live range of
518 // the extension result.
519 ExtendLife = false;
520 break;
521 }
522 }
523
524 if (ExtendLife && !ExtendedUses.empty())
525 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000526 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000527
528 // Now replace all uses.
529 bool Changed = false;
530 if (!Uses.empty()) {
531 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
532
533 // Look for PHI uses of the extended result, we don't want to extend the
534 // liveness of a PHI input. It breaks all kinds of assumptions down
535 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000536 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
537 if (UI.isPHI())
538 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000539
540 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
541 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
542 MachineOperand *UseMO = Uses[i];
543 MachineInstr *UseMI = UseMO->getParent();
544 MachineBasicBlock *UseMBB = UseMI->getParent();
545 if (PHIBBs.count(UseMBB))
546 continue;
547
Lang Hamesd5862ce2012-02-25 02:01:00 +0000548 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000549 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000550 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000551 MRI->constrainRegClass(DstReg, DstRC);
552 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000553
Bill Wendlingca678352010-08-09 23:59:04 +0000554 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000555 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
556 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000557 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000558 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
559 if (UseSrcSubIdx) {
560 Copy->getOperand(0).setSubReg(SubIdx);
561 Copy->getOperand(0).setIsUndef();
562 }
Bill Wendlingca678352010-08-09 23:59:04 +0000563 UseMO->setReg(NewVR);
564 ++NumReuse;
565 Changed = true;
566 }
567 }
568
569 return Changed;
570}
571
Sanjay Patel59309cc2015-12-29 18:14:06 +0000572/// If the instruction is a compare and the previous instruction it's comparing
573/// against already sets (or could be modified to set) the same flag as the
574/// compare, then we can remove the comparison and use the flag from the
575/// previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000576bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000577 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000578 // If this instruction is a comparison against zero and isn't comparing a
579 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000580 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000581 int CmpMask, CmpValue;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000582 if (!TII->analyzeCompare(*MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
Manman Ren6fa76dc2012-06-29 21:33:59 +0000583 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
584 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000585 return false;
586
Bill Wendling27dddd12010-09-11 00:13:50 +0000587 // Attempt to optimize the comparison instruction.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000588 if (TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000589 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000590 return true;
591 }
592
593 return false;
594}
595
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000596/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000597bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
598 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000599 unsigned TrueOp = 0;
600 unsigned FalseOp = 0;
601 bool Optimizable = false;
602 SmallVector<MachineOperand, 4> Cond;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000603 if (TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000604 return false;
605 if (!Optimizable)
606 return false;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000607 if (!TII->optimizeSelect(*MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000608 return false;
609 MI->eraseFromParent();
610 ++NumSelects;
611 return true;
612}
613
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000614/// \brief Check if a simpler conditional branch can be
615// generated
616bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000617 return TII->optimizeCondBranch(*MI);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000618}
619
Quentin Colombet03e43f82014-08-20 17:41:48 +0000620/// \brief Try to find the next source that share the same register file
621/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000622/// When true is returned, the \p RewriteMap can be used by the client to
623/// retrieve all Def -> Use along the way up to the next source. Any found
624/// Use that is not itself a key for another entry, is the next source to
625/// use. During the search for the next source, multiple sources can be found
626/// given multiple incoming sources of a PHI instruction. In this case, we
627/// look in each PHI source for the next source; all found next sources must
628/// share the same register file as \p Reg and \p SubReg. The client should
629/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000630/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000631bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
632 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000633 // Do not try to find a new source for a physical register.
634 // So far we do not have any motivating example for doing that.
635 // Thus, instead of maintaining untested code, we will revisit that if
636 // that changes at some point.
637 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000638 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000639 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000640
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000641 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
642 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
643 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000644
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000645 unsigned PHICount = 0;
646 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
647 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
648 // As explained above, do not handle physical registers
649 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
650 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000651
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000652 CurSrcPair = Pair;
653 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
654 !DisableAdvCopyOpt, TII);
655 ValueTrackerResult Res;
656 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000657
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000658 do {
659 // Follow the chain of copies until we reach the top of the use-def chain
660 // or find a more suitable source.
661 Res = ValTracker.getNextSource();
662 if (!Res.isValid())
663 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000664
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000665 // Insert the Def -> Use entry for the recently found source.
666 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
667 if (CurSrcRes.isValid()) {
668 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
669 // An existent entry with multiple sources is a PHI cycle we must avoid.
670 // Otherwise it's an entry with a valid next source we already found.
671 if (CurSrcRes.getNumSources() > 1) {
672 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
673 return false;
674 }
675 break;
676 }
677 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
678
679 // ValueTrackerResult usually have one source unless it's the result from
680 // a PHI instruction. Add the found PHI edges to be looked up further.
681 unsigned NumSrcs = Res.getNumSources();
682 if (NumSrcs > 1) {
683 PHICount++;
684 for (unsigned i = 0; i < NumSrcs; ++i)
685 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
686 Res.getSrcReg(i), Res.getSrcSubReg(i)));
687 break;
688 }
689
690 CurSrcPair.Reg = Res.getSrcReg(0);
691 CurSrcPair.SubReg = Res.getSrcSubReg(0);
692 // Do not extend the live-ranges of physical registers as they add
693 // constraints to the register allocator. Moreover, if we want to extend
694 // the live-range of a physical register, unlike SSA virtual register,
695 // we will have to check that they aren't redefine before the related use.
696 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
697 return false;
698
699 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matt Arsenault68d93862015-09-24 08:36:14 +0000700 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
701 CurSrcPair.SubReg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000702 } while (!ShouldRewrite);
703
704 // Continue looking for new sources...
705 if (Res.isValid())
706 continue;
707
708 // Do not continue searching for a new source if the there's at least
709 // one use-def which cannot be rewritten.
710 if (!ShouldRewrite)
711 return false;
712 }
713
714 if (PHICount >= RewritePHILimit) {
715 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
716 return false;
717 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000718
719 // If we did not find a more suitable source, there is nothing to optimize.
Rafael Espindola84921b92015-10-24 23:11:13 +0000720 return CurSrcPair.Reg != Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000721}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000722
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000723/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
724/// guaranteed to have the same register class. This is necessary whenever we
725/// successfully traverse a PHI instruction and find suitable sources coming
726/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
727/// suitable to be used in a new COPY instruction.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000728static MachineInstr *
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000729insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
730 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
731 MachineInstr *OrigPHI) {
732 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
733
734 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
735 unsigned NewVR = MRI->createVirtualRegister(NewRC);
736 MachineBasicBlock *MBB = OrigPHI->getParent();
737 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
738 TII->get(TargetOpcode::PHI), NewVR);
739
740 unsigned MBBOpIdx = 2;
741 for (auto RegPair : SrcRegs) {
742 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
743 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
744 // Since we're extended the lifetime of RegPair.Reg, clear the
745 // kill flags to account for that and make RegPair.Reg reaches
746 // the new PHI.
747 MRI->clearKillFlags(RegPair.Reg);
748 MBBOpIdx += 2;
749 }
750
751 return MIB;
752}
753
Quentin Colombet03e43f82014-08-20 17:41:48 +0000754namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +0000755
Quentin Colombet03e43f82014-08-20 17:41:48 +0000756/// \brief Helper class to rewrite the arguments of a copy-like instruction.
757class CopyRewriter {
758protected:
759 /// The copy-like instruction.
760 MachineInstr &CopyLike;
761 /// The index of the source being rewritten.
762 unsigned CurrentSrcIdx;
763
764public:
765 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
766
767 virtual ~CopyRewriter() {}
768
769 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
770 /// the related value that it affects (TrackReg, TrackSubReg).
771 /// A source is considered rewritable if its register class and the
772 /// register class of the related TrackReg may not be register
773 /// coalescer friendly. In other words, given a copy-like instruction
774 /// not all the arguments may be returned at rewritable source, since
775 /// some arguments are none to be register coalescer friendly.
776 ///
777 /// Each call of this method moves the current source to the next
778 /// rewritable source.
779 /// For instance, let CopyLike be the instruction to rewrite.
780 /// CopyLike has one definition and one source:
781 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
782 ///
783 /// The first call will give the first rewritable source, i.e.,
784 /// the only source this instruction has:
785 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
786 /// This source defines the whole definition, i.e.,
787 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
788 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000789 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000790 /// rewritable source.
791 ///
792 /// \return True if a rewritable source has been found, false otherwise.
793 /// The output arguments are valid if and only if true is returned.
794 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
795 unsigned &TrackReg,
796 unsigned &TrackSubReg) {
Matt Arsenault30991562015-09-09 00:38:33 +0000797 // If CurrentSrcIdx == 1, this means this function has already been called
798 // once. CopyLike has one definition and one argument, thus, there is
799 // nothing else to rewrite.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000800 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
801 return false;
802 // This is the first call to getNextRewritableSource.
803 // Move the CurrentSrcIdx to remember that we made that call.
804 CurrentSrcIdx = 1;
805 // The rewritable source is the argument.
806 const MachineOperand &MOSrc = CopyLike.getOperand(1);
807 SrcReg = MOSrc.getReg();
808 SrcSubReg = MOSrc.getSubReg();
809 // What we track are the alternative sources of the definition.
810 const MachineOperand &MODef = CopyLike.getOperand(0);
811 TrackReg = MODef.getReg();
812 TrackSubReg = MODef.getSubReg();
813 return true;
814 }
815
816 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
817 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000818 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000819 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
820 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
821 return false;
822 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
823 MOSrc.setReg(NewReg);
824 MOSrc.setSubReg(NewSubReg);
825 return true;
826 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000827
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000828 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
829 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
830 /// multiple sources for a given \p Def are found along the way, we found a
831 /// PHI instructions that needs to be rewritten.
832 /// TODO: HandleMultipleSources should be removed once we test PHI handling
833 /// with coalescable copies.
834 TargetInstrInfo::RegSubRegPair
835 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
836 TargetInstrInfo::RegSubRegPair Def,
837 PeepholeOptimizer::RewriteMapTy &RewriteMap,
838 bool HandleMultipleSources = true) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000839 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
840 do {
841 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
842 // If there are no entries on the map, LookupSrc is the new source.
843 if (!Res.isValid())
844 return LookupSrc;
845
846 // There's only one source for this definition, keep searching...
847 unsigned NumSrcs = Res.getNumSources();
848 if (NumSrcs == 1) {
849 LookupSrc.Reg = Res.getSrcReg(0);
850 LookupSrc.SubReg = Res.getSrcSubReg(0);
851 continue;
852 }
853
Matt Arsenault30991562015-09-09 00:38:33 +0000854 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000855 if (!HandleMultipleSources)
856 break;
857
858 // Multiple sources, recurse into each source to find a new source
859 // for it. Then, rewrite the PHI accordingly to its new edges.
860 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
861 for (unsigned i = 0; i < NumSrcs; ++i) {
862 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
863 Res.getSrcSubReg(i));
864 NewPHISrcs.push_back(
865 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
866 }
867
868 // Build the new PHI node and return its def register as the new source.
869 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
870 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
871 DEBUG(dbgs() << "-- getNewSource\n");
872 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
873 DEBUG(dbgs() << " With: " << *NewPHI);
874 const MachineOperand &MODef = NewPHI->getOperand(0);
875 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
876
Eugene Zelenko1804a772016-08-25 00:45:04 +0000877 } while (true);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000878
879 return TargetInstrInfo::RegSubRegPair(0, 0);
880 }
881
882 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
883 /// and create a new COPY instruction. More info about RewriteMap in
884 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
885 /// Uncoalescable copies, since they are copy like instructions that aren't
886 /// recognized by the register allocator.
887 virtual MachineInstr *
888 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
889 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000890 return nullptr;
891 }
892};
893
894/// \brief Helper class to rewrite uncoalescable copy like instructions
895/// into new COPY (coalescable friendly) instructions.
896class UncoalescableRewriter : public CopyRewriter {
897protected:
898 const TargetInstrInfo &TII;
899 MachineRegisterInfo &MRI;
900 /// The number of defs in the bitcast
901 unsigned NumDefs;
902
903public:
904 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
905 MachineRegisterInfo &MRI)
906 : CopyRewriter(MI), TII(TII), MRI(MRI) {
907 NumDefs = MI.getDesc().getNumDefs();
908 }
909
910 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
911 /// All such sources need to be considered rewritable in order to
912 /// rewrite a uncoalescable copy-like instruction. This method return
913 /// each definition that must be checked if rewritable.
914 ///
915 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
916 unsigned &TrackReg,
917 unsigned &TrackSubReg) override {
918 // Find the next non-dead definition and continue from there.
919 if (CurrentSrcIdx == NumDefs)
920 return false;
921
922 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
923 ++CurrentSrcIdx;
924 if (CurrentSrcIdx == NumDefs)
925 return false;
926 }
927
928 // What we track are the alternative sources of the definition.
929 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
930 TrackReg = MODef.getReg();
931 TrackSubReg = MODef.getSubReg();
932
933 CurrentSrcIdx++;
934 return true;
935 }
936
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000937 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
938 /// and create a new COPY instruction. More info about RewriteMap in
939 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
940 /// Uncoalescable copies, since they are copy like instructions that aren't
941 /// recognized by the register allocator.
942 MachineInstr *
943 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
944 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
945 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000946 "We do not rewrite physical registers");
947
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000948 // Find the new source to use in the COPY rewrite.
949 TargetInstrInfo::RegSubRegPair NewSrc =
950 getNewSource(&MRI, &TII, Def, RewriteMap);
951
952 // Insert the COPY.
953 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000954 unsigned NewVR = MRI.createVirtualRegister(DefRC);
955
956 MachineInstr *NewCopy =
957 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
958 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000959 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000960
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000961 NewCopy->getOperand(0).setSubReg(Def.SubReg);
962 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000963 NewCopy->getOperand(0).setIsUndef();
964
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000965 DEBUG(dbgs() << "-- RewriteSource\n");
966 DEBUG(dbgs() << " Replacing: " << CopyLike);
967 DEBUG(dbgs() << " With: " << *NewCopy);
968 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000969 MRI.clearKillFlags(NewVR);
970
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000971 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
972 // account for that.
973 MRI.clearKillFlags(NewSrc.Reg);
974
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000975 return NewCopy;
976 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000977};
978
979/// \brief Specialized rewriter for INSERT_SUBREG instruction.
980class InsertSubregRewriter : public CopyRewriter {
981public:
982 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
983 assert(MI.isInsertSubreg() && "Invalid instruction");
984 }
985
986 /// \brief See CopyRewriter::getNextRewritableSource.
987 /// Here CopyLike has the following form:
988 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
989 /// Src1 has the same register class has dst, hence, there is
990 /// nothing to rewrite.
991 /// Src2.src2SubIdx, may not be register coalescer friendly.
992 /// Therefore, the first call to this method returns:
993 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
994 /// (TrackReg, TrackSubReg) = (dst, subIdx).
995 ///
996 /// Subsequence calls will return false.
997 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
998 unsigned &TrackReg,
999 unsigned &TrackSubReg) override {
1000 // If we already get the only source we can rewrite, return false.
1001 if (CurrentSrcIdx == 2)
1002 return false;
1003 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
1004 CurrentSrcIdx = 2;
1005 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
1006 SrcReg = MOInsertedReg.getReg();
1007 SrcSubReg = MOInsertedReg.getSubReg();
1008 const MachineOperand &MODef = CopyLike.getOperand(0);
1009
1010 // We want to track something that is compatible with the
1011 // partial definition.
1012 TrackReg = MODef.getReg();
1013 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001014 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001015 return false;
1016 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1017 return true;
1018 }
Eugene Zelenko1804a772016-08-25 00:45:04 +00001019
Quentin Colombet03e43f82014-08-20 17:41:48 +00001020 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1021 if (CurrentSrcIdx != 2)
1022 return false;
1023 // We are rewriting the inserted reg.
1024 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1025 MO.setReg(NewReg);
1026 MO.setSubReg(NewSubReg);
1027 return true;
1028 }
1029};
1030
1031/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1032class ExtractSubregRewriter : public CopyRewriter {
1033 const TargetInstrInfo &TII;
1034
1035public:
1036 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1037 : CopyRewriter(MI), TII(TII) {
1038 assert(MI.isExtractSubreg() && "Invalid instruction");
1039 }
1040
1041 /// \brief See CopyRewriter::getNextRewritableSource.
1042 /// Here CopyLike has the following form:
1043 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1044 /// There is only one rewritable source: Src.subIdx,
1045 /// which defines dst.dstSubIdx.
1046 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1047 unsigned &TrackReg,
1048 unsigned &TrackSubReg) override {
1049 // If we already get the only source we can rewrite, return false.
1050 if (CurrentSrcIdx == 1)
1051 return false;
1052 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1053 CurrentSrcIdx = 1;
1054 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1055 SrcReg = MOExtractedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001056 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001057 if (MOExtractedReg.getSubReg())
1058 return false;
1059
1060 SrcSubReg = CopyLike.getOperand(2).getImm();
1061
1062 // We want to track something that is compatible with the definition.
1063 const MachineOperand &MODef = CopyLike.getOperand(0);
1064 TrackReg = MODef.getReg();
1065 TrackSubReg = MODef.getSubReg();
1066 return true;
1067 }
1068
1069 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1070 // The only source we can rewrite is the input register.
1071 if (CurrentSrcIdx != 1)
1072 return false;
1073
1074 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1075
1076 // If we find a source that does not require to extract something,
1077 // rewrite the operation with a copy.
1078 if (!NewSubReg) {
1079 // Move the current index to an invalid position.
1080 // We do not want another call to this method to be able
1081 // to do any change.
1082 CurrentSrcIdx = -1;
1083 // Rewrite the operation as a COPY.
1084 // Get rid of the sub-register index.
1085 CopyLike.RemoveOperand(2);
1086 // Morph the operation into a COPY.
1087 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1088 return true;
1089 }
1090 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1091 return true;
1092 }
1093};
1094
1095/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1096class RegSequenceRewriter : public CopyRewriter {
1097public:
1098 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1099 assert(MI.isRegSequence() && "Invalid instruction");
1100 }
1101
1102 /// \brief See CopyRewriter::getNextRewritableSource.
1103 /// Here CopyLike has the following form:
1104 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1105 /// Each call will return a different source, walking all the available
1106 /// source.
1107 ///
1108 /// The first call returns:
1109 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1110 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1111 ///
1112 /// The second call returns:
1113 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1114 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1115 ///
1116 /// And so on, until all the sources have been traversed, then
1117 /// it returns false.
1118 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1119 unsigned &TrackReg,
1120 unsigned &TrackSubReg) override {
1121 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1122
1123 // If this is the first call, move to the first argument.
1124 if (CurrentSrcIdx == 0) {
1125 CurrentSrcIdx = 1;
1126 } else {
1127 // Otherwise, move to the next argument and check that it is valid.
1128 CurrentSrcIdx += 2;
1129 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1130 return false;
1131 }
1132 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1133 SrcReg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001134 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001135 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1136 return false;
1137
1138 // We want to track something that is compatible with the related
1139 // partial definition.
1140 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1141
1142 const MachineOperand &MODef = CopyLike.getOperand(0);
1143 TrackReg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001144 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001145 return MODef.getSubReg() == 0;
1146 }
1147
1148 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1149 // We cannot rewrite out of bound operands.
1150 // Moreover, rewritable sources are at odd positions.
1151 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1152 return false;
1153
1154 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1155 MO.setReg(NewReg);
1156 MO.setSubReg(NewSubReg);
1157 return true;
1158 }
1159};
Eugene Zelenko1804a772016-08-25 00:45:04 +00001160
1161} // end anonymous namespace
Quentin Colombet03e43f82014-08-20 17:41:48 +00001162
1163/// \brief Get the appropriated CopyRewriter for \p MI.
1164/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1165/// if no rewriter works for \p MI.
1166static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001167 const TargetInstrInfo &TII,
1168 MachineRegisterInfo &MRI) {
1169 // Handle uncoalescable copy-like instructions.
1170 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1171 MI.isExtractSubregLike()))
1172 return new UncoalescableRewriter(MI, TII, MRI);
1173
Quentin Colombet03e43f82014-08-20 17:41:48 +00001174 switch (MI.getOpcode()) {
1175 default:
1176 return nullptr;
1177 case TargetOpcode::COPY:
1178 return new CopyRewriter(MI);
1179 case TargetOpcode::INSERT_SUBREG:
1180 return new InsertSubregRewriter(MI);
1181 case TargetOpcode::EXTRACT_SUBREG:
1182 return new ExtractSubregRewriter(MI, TII);
1183 case TargetOpcode::REG_SEQUENCE:
1184 return new RegSequenceRewriter(MI);
1185 }
1186 llvm_unreachable(nullptr);
1187}
1188
1189/// \brief Optimize generic copy instructions to avoid cross
1190/// register bank copy. The optimization looks through a chain of
1191/// copies and tries to find a source that has a compatible register
1192/// class.
1193/// Two register classes are considered to be compatible if they share
1194/// the same register bank.
1195/// New copies issued by this optimization are register allocator
1196/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001197/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001198/// when possible.
1199/// \pre isCoalescableCopy(*MI) is true.
1200/// \return True, when \p MI has been rewritten. False otherwise.
1201bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1202 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1203 assert(MI->getDesc().getNumDefs() == 1 &&
1204 "Coalescer can understand multiple defs?!");
1205 const MachineOperand &MODef = MI->getOperand(0);
1206 // Do not rewrite physical definitions.
1207 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1208 return false;
1209
1210 bool Changed = false;
1211 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001212 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001213 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001214 if (!CpyRewriter)
1215 return false;
1216 // Rewrite each rewritable source.
1217 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1218 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1219 TrackSubReg)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001220 // Keep track of PHI nodes and its incoming edges when looking for sources.
1221 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001222 // Try to find a more suitable source. If we failed to do so, or get the
1223 // actual source, move to the next source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001224 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001225 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001226
1227 // Get the new source to rewrite. TODO: Only enable handling of multiple
1228 // sources (PHIs) once we have a motivating example and testcases for it.
1229 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1230 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1231 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1232 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1233 continue;
1234
Quentin Colombet03e43f82014-08-20 17:41:48 +00001235 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001236 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001237 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001238 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001239 Changed = true;
1240 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001241 }
1242 // TODO: We could have a clean-up method to tidy the instruction.
1243 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1244 // => v0 = COPY v1
1245 // Currently we haven't seen motivating example for that and we
1246 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001247 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001248 return Changed;
1249}
1250
1251/// \brief Optimize copy-like instructions to create
1252/// register coalescer friendly instruction.
1253/// The optimization tries to kill-off the \p MI by looking
1254/// through a chain of copies to find a source that has a compatible
1255/// register class.
1256/// If such a source is found, it replace \p MI by a generic COPY
1257/// operation.
1258/// \pre isUncoalescableCopy(*MI) is true.
1259/// \return True, when \p MI has been optimized. In that case, \p MI has
1260/// been removed from its parent.
1261/// All COPY instructions created, are inserted in \p LocalMIs.
1262bool PeepholeOptimizer::optimizeUncoalescableCopy(
1263 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1264 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1265
1266 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001267 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001268 // Get the right rewriter for the current copy.
1269 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001270 // If none exists, bail out.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001271 if (!CpyRewriter)
1272 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001273
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001274 // Rewrite each rewritable source by generating new COPYs. This works
1275 // differently from optimizeCoalescableCopy since it first makes sure that all
1276 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001277 RewriteMapTy RewriteMap;
1278 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1279 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1280 CopyDefSubReg)) {
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.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001283 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
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.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001288 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1289 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001290 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001291
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001292 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001293 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001294
Quentin Colombet03e43f82014-08-20 17:41:48 +00001295 // The change is possible for all defs, do it.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001296 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001297 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001298 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001299 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001300 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001301 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001302
Quentin Colombet03e43f82014-08-20 17:41:48 +00001303 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001304 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001305 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001306 return true;
1307}
1308
Sanjay Patel59309cc2015-12-29 18:14:06 +00001309/// Check whether MI is a candidate for folding into a later instruction.
1310/// We only fold loads to virtual registers and the virtual register defined
1311/// has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001312bool PeepholeOptimizer::isLoadFoldable(
Sanjay Patelb120ae92015-12-29 19:34:53 +00001313 MachineInstr *MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001314 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1315 return false;
1316 const MCInstrDesc &MCID = MI->getDesc();
1317 if (MCID.getNumDefs() != 1)
1318 return false;
1319
1320 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001321 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001322 // loads. It should be checked when processing uses of the load, since
1323 // uses can be removed during peephole.
1324 if (!MI->getOperand(0).getSubReg() &&
1325 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001326 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001327 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001328 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001329 }
1330 return false;
1331}
1332
Sanjay Patelb120ae92015-12-29 19:34:53 +00001333bool PeepholeOptimizer::isMoveImmediate(
1334 MachineInstr *MI, SmallSet<unsigned, 4> &ImmDefRegs,
1335 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001336 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001337 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001338 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001339 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001340 return false;
1341 unsigned Reg = MI->getOperand(0).getReg();
1342 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1343 ImmDefMIs.insert(std::make_pair(Reg, MI));
1344 ImmDefRegs.insert(Reg);
1345 return true;
1346 }
Andrew Trick9e761992012-02-08 21:22:43 +00001347
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001348 return false;
1349}
1350
Sanjay Patel59309cc2015-12-29 18:14:06 +00001351/// Try folding register operands that are defined by move immediate
1352/// instructions, i.e. a trivial constant folding optimization, if
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001353/// and only if the def and use are in the same BB.
Sanjay Patelb120ae92015-12-29 19:34:53 +00001354bool PeepholeOptimizer::foldImmediate(
1355 MachineInstr *MI, MachineBasicBlock *MBB, SmallSet<unsigned, 4> &ImmDefRegs,
1356 DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001357 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1358 MachineOperand &MO = MI->getOperand(i);
1359 if (!MO.isReg() || MO.isDef())
1360 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001361 // Ignore dead implicit defs.
1362 if (MO.isImplicit() && MO.isDead())
1363 continue;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001364 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001365 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001366 continue;
1367 if (ImmDefRegs.count(Reg) == 0)
1368 continue;
1369 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
JF Bastien1ac69942015-12-03 23:43:56 +00001370 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001371 if (TII->FoldImmediate(*MI, *II->second, Reg, MRI)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001372 ++NumImmFold;
1373 return true;
1374 }
1375 }
1376 return false;
1377}
1378
Matt Arsenault10aa8072015-09-25 20:22:12 +00001379// FIXME: This is very simple and misses some cases which should be handled when
1380// motivating examples are found.
1381//
1382// The copy rewriting logic should look at uses as well as defs and be able to
1383// eliminate copies across blocks.
1384//
1385// Later copies that are subregister extracts will also not be eliminated since
1386// only the first copy is considered.
1387//
1388// e.g.
1389// %vreg1 = COPY %vreg0
1390// %vreg2 = COPY %vreg0:sub1
1391//
1392// Should replace %vreg2 uses with %vreg1:sub1
1393bool PeepholeOptimizer::foldRedundantCopy(
Sanjay Patelb120ae92015-12-29 19:34:53 +00001394 MachineInstr *MI, SmallSet<unsigned, 4> &CopySrcRegs,
JF Bastien1ac69942015-12-03 23:43:56 +00001395 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1396 assert(MI->isCopy() && "expected a COPY machine instruction");
Matt Arsenault10aa8072015-09-25 20:22:12 +00001397
1398 unsigned SrcReg = MI->getOperand(1).getReg();
1399 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1400 return false;
1401
1402 unsigned DstReg = MI->getOperand(0).getReg();
1403 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1404 return false;
1405
1406 if (CopySrcRegs.insert(SrcReg).second) {
1407 // First copy of this reg seen.
1408 CopyMIs.insert(std::make_pair(SrcReg, MI));
1409 return false;
1410 }
1411
1412 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1413
1414 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1415 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1416
1417 // Can't replace different subregister extracts.
1418 if (SrcSubReg != PrevSrcSubReg)
1419 return false;
1420
1421 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1422
1423 // Only replace if the copy register class is the same.
1424 //
1425 // TODO: If we have multiple copies to different register classes, we may want
1426 // to track multiple copies of the same source register.
1427 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1428 return false;
1429
1430 MRI->replaceRegWith(DstReg, PrevDstReg);
1431
1432 // Lifetime of the previous copy has been extended.
1433 MRI->clearKillFlags(PrevDstReg);
1434 return true;
1435}
1436
JF Bastien1ac69942015-12-03 23:43:56 +00001437bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1438 return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1439 !MRI->isAllocatable(Reg);
1440}
1441
1442bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1443 MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1444 assert(MI->isCopy() && "expected a COPY machine instruction");
1445
1446 if (DisableNAPhysCopyOpt)
1447 return false;
1448
1449 unsigned DstReg = MI->getOperand(0).getReg();
1450 unsigned SrcReg = MI->getOperand(1).getReg();
1451 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1452 // %vreg = COPY %PHYSREG
1453 // Avoid using a datastructure which can track multiple live non-allocatable
1454 // phys->virt copies since LLVM doesn't seem to do this.
1455 NAPhysToVirtMIs.insert({SrcReg, MI});
1456 return false;
1457 }
1458
1459 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1460 return false;
1461
1462 // %PHYSREG = COPY %vreg
1463 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1464 if (PrevCopy == NAPhysToVirtMIs.end()) {
1465 // We can't remove the copy: there was an intervening clobber of the
1466 // non-allocatable physical register after the copy to virtual.
1467 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI
1468 << '\n');
1469 return false;
1470 }
1471
1472 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1473 if (PrevDstReg == SrcReg) {
1474 // Remove the virt->phys copy: we saw the virtual register definition, and
1475 // the non-allocatable physical register's state hasn't changed since then.
1476 DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n');
1477 ++NumNAPhysCopies;
1478 return true;
1479 }
1480
1481 // Potential missed optimization opportunity: we saw a different virtual
1482 // register get a copy of the non-allocatable physical register, and we only
1483 // track one such copy. Avoid getting confused by this new non-allocatable
1484 // physical register definition, and remove it from the tracked copies.
1485 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n');
1486 NAPhysToVirtMIs.erase(PrevCopy);
1487 return false;
1488}
1489
Eric Christopher2181fb22014-10-15 21:06:25 +00001490bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001491 if (skipFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001492 return false;
1493
Craig Topper588ceec2012-12-17 03:56:00 +00001494 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001495 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001496
Evan Cheng2ce016c2010-11-15 21:20:45 +00001497 if (DisablePeephole)
1498 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001499
Eric Christopher2181fb22014-10-15 21:06:25 +00001500 TII = MF.getSubtarget().getInstrInfo();
1501 TRI = MF.getSubtarget().getRegisterInfo();
1502 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001503 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001504
1505 bool Changed = false;
1506
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001507 for (MachineBasicBlock &MBB : MF) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001508 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001509
1510 // During this forward scan, at some point it needs to answer the question
1511 // "given a pointer to an MI in the current BB, is it located before or
1512 // after the current instruction".
1513 // To perform this, the following set keeps track of the MIs already seen
1514 // during the scan, if a MI is not in the set, it is assumed to be located
1515 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001516 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001517 SmallSet<unsigned, 4> ImmDefRegs;
1518 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1519 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001520
JF Bastien1ac69942015-12-03 23:43:56 +00001521 // Track when a non-allocatable physical register is copied to a virtual
1522 // register so that useless moves can be removed.
1523 //
1524 // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG`
1525 // without any intervening re-definition of %PHYSREG.
1526 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1527
Matt Arsenault10aa8072015-09-25 20:22:12 +00001528 // Set of virtual registers that are copied from.
1529 SmallSet<unsigned, 4> CopySrcRegs;
1530 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1531
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001532 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1533 MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001534 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001535 // We may be erasing MI below, increment MII now.
1536 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001537 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001538
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001539 // Skip debug values. They should not affect this peephole optimization.
1540 if (MI->isDebugValue())
1541 continue;
1542
JF Bastien1ac69942015-12-03 23:43:56 +00001543 if (MI->isPosition() || MI->isPHI())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001544 continue;
1545
JF Bastien1ac69942015-12-03 23:43:56 +00001546 if (!MI->isCopy()) {
1547 for (const auto &Op : MI->operands()) {
1548 // Visit all operands: definitions can be implicit or explicit.
1549 if (Op.isReg()) {
1550 unsigned Reg = Op.getReg();
1551 if (Op.isDef() && isNAPhysCopy(Reg)) {
1552 const auto &Def = NAPhysToVirtMIs.find(Reg);
1553 if (Def != NAPhysToVirtMIs.end()) {
1554 // A new definition of the non-allocatable physical register
1555 // invalidates previous copies.
1556 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1557 << '\n');
1558 NAPhysToVirtMIs.erase(Def);
1559 }
1560 }
1561 } else if (Op.isRegMask()) {
1562 const uint32_t *RegMask = Op.getRegMask();
1563 for (auto &RegMI : NAPhysToVirtMIs) {
1564 unsigned Def = RegMI.first;
1565 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1566 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1567 << '\n');
1568 NAPhysToVirtMIs.erase(Def);
1569 }
1570 }
1571 }
1572 }
1573 }
1574
1575 if (MI->isImplicitDef() || MI->isKill())
1576 continue;
1577
1578 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1579 // Blow away all non-allocatable physical registers knowledge since we
1580 // don't know what's correct anymore.
1581 //
1582 // FIXME: handle explicit asm clobbers.
1583 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI
1584 << '\n');
1585 NAPhysToVirtMIs.clear();
JF Bastien1ac69942015-12-03 23:43:56 +00001586 }
1587
Quentin Colombet03e43f82014-08-20 17:41:48 +00001588 if ((isUncoalescableCopy(*MI) &&
1589 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001590 (MI->isCompare() && optimizeCmpInstr(MI, &MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001591 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001592 // MI is deleted.
1593 LocalMIs.erase(MI);
1594 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001595 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001596 }
1597
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001598 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1599 Changed = true;
1600 continue;
1601 }
1602
Quentin Colombet03e43f82014-08-20 17:41:48 +00001603 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1604 // MI is just rewritten.
1605 Changed = true;
1606 continue;
1607 }
1608
JF Bastien1ac69942015-12-03 23:43:56 +00001609 if (MI->isCopy() &&
1610 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1611 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
Matt Arsenault10aa8072015-09-25 20:22:12 +00001612 LocalMIs.erase(MI);
1613 MI->eraseFromParent();
1614 Changed = true;
1615 continue;
1616 }
1617
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001618 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001619 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001620 } else {
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001621 Changed |= optimizeExtInstr(MI, &MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001622 // optimizeExtInstr might have created new instructions after MI
1623 // and before the already incremented MII. Adjust MII so that the
1624 // next iteration sees the new instructions.
1625 MII = MI;
1626 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001627 if (SeenMoveImm)
Sanjay Patelfaeee6f2015-12-29 18:30:09 +00001628 Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001629 }
Evan Cheng98196b42011-02-15 05:00:24 +00001630
Manman Ren5759d012012-08-02 00:56:42 +00001631 // Check whether MI is a load candidate for folding into a later
1632 // instruction. If MI is not a candidate, check whether we can fold an
1633 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001634 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1635 !FoldAsLoadDefCandidates.empty()) {
Philip Reames1f1bbac2016-12-13 01:38:41 +00001636
1637 // We visit each operand even after successfully folding a previous
1638 // one. This allows us to fold multiple loads into a single
1639 // instruction. We do assume that optimizeLoadInstr doesn't insert
1640 // foldable uses earlier in the argument list. Since we don't restart
1641 // iteration, we'd miss such cases.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001642 const MCInstrDesc &MIDesc = MI->getDesc();
Philip Reames1f1bbac2016-12-13 01:38:41 +00001643 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
Lang Hames5dc14bd2014-04-02 22:59:58 +00001644 ++i) {
1645 const MachineOperand &MOp = MI->getOperand(i);
1646 if (!MOp.isReg())
1647 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001648 unsigned FoldAsLoadDefReg = MOp.getReg();
1649 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1650 // We need to fold load after optimizeCmpInstr, since
1651 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1652 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1653 // we need it for markUsesInDebugValueAsUndef().
1654 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001655 MachineInstr *DefMI = nullptr;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001656 if (MachineInstr *FoldMI =
1657 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001658 // Update LocalMIs since we replaced MI with FoldMI and deleted
1659 // DefMI.
1660 DEBUG(dbgs() << "Replacing: " << *MI);
1661 DEBUG(dbgs() << " With: " << *FoldMI);
1662 LocalMIs.erase(MI);
1663 LocalMIs.erase(DefMI);
1664 LocalMIs.insert(FoldMI);
1665 MI->eraseFromParent();
1666 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001667 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1668 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001669 ++NumLoadFold;
Philip Reames1f1bbac2016-12-13 01:38:41 +00001670
1671 // MI is replaced with FoldMI so we can continue trying to fold
Lang Hames5dc14bd2014-04-02 22:59:58 +00001672 Changed = true;
Philip Reames1f1bbac2016-12-13 01:38:41 +00001673 MI = FoldMI;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001674 }
1675 }
Manman Ren5759d012012-08-02 00:56:42 +00001676 }
1677 }
Philip Reames1f1bbac2016-12-13 01:38:41 +00001678
1679 // If we run into an instruction we can't fold across, discard
1680 // the load candidates. Note: We might be able to fold *into* this
1681 // instruction, so this needs to be after the folding logic.
1682 if (MI->isLoadFoldBarrier()) {
1683 DEBUG(dbgs() << "Encountered load fold barrier on " << *MI << "\n");
1684 FoldAsLoadDefCandidates.clear();
1685 }
1686
Bill Wendlingca678352010-08-09 23:59:04 +00001687 }
1688 }
1689
1690 return Changed;
1691}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001692
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001693ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001694 assert(Def->isCopy() && "Invalid definition");
1695 // Copy instruction are supposed to be: Def = Src.
1696 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001697 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001698
1699 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1700 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001701 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001702 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001703 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001704 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001705 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001706}
1707
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001708ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001709 assert(Def->isBitcast() && "Invalid definition");
1710
1711 // Bail if there are effects that a plain copy will not expose.
1712 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001713 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001714
1715 // Bitcasts with more than one def are not supported.
1716 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001717 return ValueTrackerResult();
Matthias Braunba7d95d2017-01-09 21:38:17 +00001718 const MachineOperand DefOp = Def->getOperand(DefIdx);
1719 if (DefOp.getSubReg() != DefSubReg)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001720 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001721 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001722 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001723
Quentin Colombet03e43f82014-08-20 17:41:48 +00001724 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001725 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1726 ++OpIdx) {
1727 const MachineOperand &MO = Def->getOperand(OpIdx);
1728 if (!MO.isReg() || !MO.getReg())
1729 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001730 // Ignore dead implicit defs.
1731 if (MO.isImplicit() && MO.isDead())
1732 continue;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001733 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1734 if (SrcIdx != EndOpIdx)
1735 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001736 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001737 SrcIdx = OpIdx;
1738 }
Matthias Braunba7d95d2017-01-09 21:38:17 +00001739
1740 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1741 // will break the assumed guarantees for the upper bits.
1742 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1743 if (UseMI.isSubregToReg())
1744 return ValueTrackerResult();
1745 }
1746
Quentin Colombet03e43f82014-08-20 17:41:48 +00001747 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001748 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001749}
1750
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001751ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001752 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1753 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001754
1755 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001756 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001757 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1758 // This should almost never happen as the SSA property is tracked at
1759 // the register level (as opposed to the subreg level).
1760 // I.e.,
1761 // Def.sub0 =
1762 // Def.sub1 =
1763 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1764 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001765 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001766 // Def.sub0 (i.e, not defining the other subregs) and we would
1767 // have this case.
1768 // If we can ascertain (or force) that this never happens, we could
1769 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001770 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001771
Quentin Colombet03e43f82014-08-20 17:41:48 +00001772 if (!TII)
1773 // We could handle the REG_SEQUENCE here, but we do not want to
1774 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001775 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001776
1777 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1778 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001779 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001780
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001781 // We are looking at:
1782 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1783 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001784 for (auto &RegSeqInput : RegSeqInputRegs) {
1785 if (RegSeqInput.SubIdx == DefSubReg) {
1786 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001787 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001788 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001789
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001790 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001791 }
1792 }
1793
1794 // If the subreg we are tracking is super-defined by another subreg,
1795 // we could follow this value. However, this would require to compose
1796 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001797 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001798}
1799
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001800ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001801 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1802 "Invalid definition");
1803
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001804 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001805 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001806 // Same remark as getNextSourceFromRegSequence.
1807 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001808 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001809
Quentin Colombet68962302014-08-21 00:19:16 +00001810 if (!TII)
1811 // We could handle the REG_SEQUENCE here, but we do not want to
1812 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001813 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001814
Quentin Colombet03e43f82014-08-20 17:41:48 +00001815 TargetInstrInfo::RegSubRegPair BaseReg;
1816 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001817 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001818 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001819
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001820 // We are looking at:
1821 // Def = INSERT_SUBREG v0, v1, sub1
1822 // There are two cases:
1823 // 1. DefSubReg == sub1, get v1.
1824 // 2. DefSubReg != sub1, the value may be available through v0.
1825
Quentin Colombet03e43f82014-08-20 17:41:48 +00001826 // #1 Check if the inserted register matches the required sub index.
1827 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001828 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001829 }
1830 // #2 Otherwise, if the sub register we are looking for is not partial
1831 // defined by the inserted element, we can look through the main
1832 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001833 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001834 // If the result register (Def) and the base register (v0) do not
1835 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00001836 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001837 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1838 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001839 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001840
Quentin Colombet03e43f82014-08-20 17:41:48 +00001841 // Get the TRI and check if the inserted sub-register overlaps with the
1842 // sub-register we are tracking.
1843 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001844 if (!TRI ||
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001845 !(TRI->getSubRegIndexLaneMask(DefSubReg) &
1846 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001847 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001848 // At this point, the value is available in v0 via the same subreg
1849 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001850 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001851}
1852
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001853ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001854 assert((Def->isExtractSubreg() ||
1855 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001856 // We are looking at:
1857 // Def = EXTRACT_SUBREG v0, sub0
1858
Matt Arsenault30991562015-09-09 00:38:33 +00001859 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001860 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1861 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001862 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001863
Quentin Colombet67639df2014-08-20 23:13:02 +00001864 if (!TII)
1865 // We could handle the EXTRACT_SUBREG here, but we do not want to
1866 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001867 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001868
Quentin Colombet03e43f82014-08-20 17:41:48 +00001869 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001870 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001871 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001872
Matt Arsenault30991562015-09-09 00:38:33 +00001873 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001874 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001875 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001876 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001877 // Otherwise, the value is available in the v0.sub0.
Sanjay Patelb120ae92015-12-29 19:34:53 +00001878 return ValueTrackerResult(ExtractSubregInputReg.Reg,
1879 ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001880}
1881
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001882ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001883 assert(Def->isSubregToReg() && "Invalid definition");
1884 // We are looking at:
1885 // Def = SUBREG_TO_REG Imm, v0, sub0
1886
Matt Arsenault30991562015-09-09 00:38:33 +00001887 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001888 // If DefSubReg != sub0, we would have to check that all the bits
1889 // we track are included in sub0 and if yes, we would have to
1890 // determine the right subreg in v0.
1891 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001892 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00001893 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001894 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1895 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001896 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001897
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001898 return ValueTrackerResult(Def->getOperand(2).getReg(),
1899 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001900}
1901
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001902/// \brief Explore each PHI incoming operand and return its sources
1903ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1904 assert(Def->isPHI() && "Invalid definition");
1905 ValueTrackerResult Res;
1906
Matt Arsenault30991562015-09-09 00:38:33 +00001907 // If we look for a different subreg, bail as we do not support composing
1908 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001909 if (Def->getOperand(0).getSubReg() != DefSubReg)
1910 return ValueTrackerResult();
1911
1912 // Return all register sources for PHI instructions.
1913 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1914 auto &MO = Def->getOperand(i);
1915 assert(MO.isReg() && "Invalid PHI instruction");
1916 Res.addSource(MO.getReg(), MO.getSubReg());
1917 }
1918
1919 return Res;
1920}
1921
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001922ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001923 assert(Def && "This method needs a valid definition");
1924
Eric Liue617ade2016-07-04 12:10:08 +00001925 assert(((Def->getOperand(DefIdx).isDef() &&
1926 (DefIdx < Def->getDesc().getNumDefs() ||
1927 Def->getDesc().isVariadic())) ||
1928 Def->getOperand(DefIdx).isImplicit()) &&
1929 "Invalid DefIdx");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001930 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001931 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001932 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001933 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001934 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00001935 // Bail if we did not ask for the advanced tracking.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001936 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001937 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001938 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001939 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001940 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001941 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001942 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001943 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001944 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001945 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001946 if (Def->isPHI())
1947 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001948 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001949}
1950
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001951ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001952 // If we reach a point where we cannot move up in the use-def chain,
1953 // there is nothing we can get.
1954 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001955 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001956
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001957 ValueTrackerResult Res = getNextSourceImpl();
1958 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001959 // Update definition, definition index, and subregister for the
1960 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001961 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001962 bool OneRegSrc = Res.getNumSources() == 1;
1963 if (OneRegSrc)
1964 Reg = Res.getSrcReg(0);
1965 // Update the result before moving up in the use-def chain
1966 // with the instruction containing the last found sources.
1967 Res.setInst(Def);
1968
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001969 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001970 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001971 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001972 Def = MRI.getVRegDef(Reg);
1973 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001974 DefSubReg = Res.getSrcSubReg(0);
1975 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001976 }
1977 }
1978 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001979 // for the next iteration. Make sure any new call to getNextSource bails out
1980 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001981 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001982 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001983}