blob: 7c195a89bd762f02d607729582ae005a58713f1d [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
46// if it loads to virtual registers and the virtual register defined has
47// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Bill Wendlingca678352010-08-09 23:59:04 +000069#include "llvm/CodeGen/Passes.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000070#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000071#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000072#include "llvm/ADT/SmallSet.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/CodeGen/MachineDominators.h"
75#include "llvm/CodeGen/MachineInstrBuilder.h"
76#include "llvm/CodeGen/MachineRegisterInfo.h"
77#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000078#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000079#include "llvm/Target/TargetInstrInfo.h"
80#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000081#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet03e43f82014-08-20 17:41:48 +000082#include <utility>
Bill Wendlingca678352010-08-09 23:59:04 +000083using namespace llvm;
84
Chandler Carruth1b9dde02014-04-22 02:02:50 +000085#define DEBUG_TYPE "peephole-opt"
86
Bill Wendlingca678352010-08-09 23:59:04 +000087// Optimize Extensions
88static cl::opt<bool>
89Aggressive("aggressive-ext-opt", cl::Hidden,
90 cl::desc("Aggressive extension optimization"));
91
Bill Wendlingc6627ee2010-11-01 20:41:43 +000092static cl::opt<bool>
93DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
94 cl::desc("Disable the peephole optimizer"));
95
Quentin Colombet1111e6f2014-07-01 14:33:36 +000096static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +000097DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +000098 cl::desc("Disable advanced copy optimization"));
99
Bill Wendling66284312010-08-27 20:39:09 +0000100STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000101STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000102STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000103STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000104STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000105STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
106STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000107
108namespace {
109 class PeepholeOptimizer : public MachineFunctionPass {
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000110 MachineFunction *MF;
Bill Wendlingca678352010-08-09 23:59:04 +0000111 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000112 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000113 MachineRegisterInfo *MRI;
114 MachineDominatorTree *DT; // Machine dominator tree
115
116 public:
117 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000118 PeepholeOptimizer() : MachineFunctionPass(ID) {
119 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
120 }
Bill Wendlingca678352010-08-09 23:59:04 +0000121
Craig Topper4584cd52014-03-07 09:26:03 +0000122 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000123
Craig Topper4584cd52014-03-07 09:26:03 +0000124 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000125 AU.setPreservesCFG();
126 MachineFunctionPass::getAnalysisUsage(AU);
127 if (Aggressive) {
128 AU.addRequired<MachineDominatorTree>();
129 AU.addPreserved<MachineDominatorTree>();
130 }
131 }
132
133 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000134 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
135 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000136 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000137 bool optimizeSelect(MachineInstr *MI);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000138 bool optimizeCopyOrBitcast(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000139 bool optimizeCoalescableCopy(MachineInstr *MI);
140 bool optimizeUncoalescableCopy(MachineInstr *MI,
141 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
142 bool findNextSource(unsigned &Reg, unsigned &SubReg);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000143 bool isMoveImmediate(MachineInstr *MI,
144 SmallSet<unsigned, 4> &ImmDefRegs,
145 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000146 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000147 SmallSet<unsigned, 4> &ImmDefRegs,
148 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Lang Hames5dc14bd2014-04-02 22:59:58 +0000149 bool isLoadFoldable(MachineInstr *MI,
150 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000151
152 /// \brief Check whether \p MI is understood by the register coalescer
153 /// but may require some rewriting.
154 bool isCoalescableCopy(const MachineInstr &MI) {
155 // SubregToRegs are not interesting, because they are already register
156 // coalescer friendly.
157 return MI.isCopy() || (!DisableAdvCopyOpt &&
158 (MI.isRegSequence() || MI.isInsertSubreg() ||
159 MI.isExtractSubreg()));
160 }
161
162 /// \brief Check whether \p MI is a copy like instruction that is
163 /// not recognized by the register coalescer.
164 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000165 return MI.isBitcast() ||
166 (!DisableAdvCopyOpt &&
167 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
168 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000169 }
Bill Wendlingca678352010-08-09 23:59:04 +0000170 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000171
172 /// \brief Helper class to track the possible sources of a value defined by
173 /// a (chain of) copy related instructions.
174 /// Given a definition (instruction and definition index), this class
175 /// follows the use-def chain to find successive suitable sources.
176 /// The given source can be used to rewrite the definition into
177 /// def = COPY src.
178 ///
179 /// For instance, let us consider the following snippet:
180 /// v0 =
181 /// v2 = INSERT_SUBREG v1, v0, sub0
182 /// def = COPY v2.sub0
183 ///
184 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
185 /// suitable sources:
186 /// v2.sub0 and v0.
187 /// Then, def can be rewritten into def = COPY v0.
188 class ValueTracker {
189 private:
190 /// The current point into the use-def chain.
191 const MachineInstr *Def;
192 /// The index of the definition in Def.
193 unsigned DefIdx;
194 /// The sub register index of the definition.
195 unsigned DefSubReg;
196 /// The register where the value can be found.
197 unsigned Reg;
198 /// Specifiy whether or not the value tracking looks through
199 /// complex instructions. When this is false, the value tracker
200 /// bails on everything that is not a copy or a bitcast.
201 ///
202 /// Note: This could have been implemented as a specialized version of
203 /// the ValueTracker class but that would have complicated the code of
204 /// the users of this class.
205 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000206 /// MachineRegisterInfo used to perform tracking.
207 const MachineRegisterInfo &MRI;
208 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000209 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000210 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000211
212 /// \brief Dispatcher to the right underlying implementation of
213 /// getNextSource.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000214 bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000215 /// \brief Specialized version of getNextSource for Copy instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000216 bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000217 /// \brief Specialized version of getNextSource for Bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000218 bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000219 /// \brief Specialized version of getNextSource for RegSequence
220 /// instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000221 bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000222 /// \brief Specialized version of getNextSource for InsertSubreg
223 /// instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000224 bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000225 /// \brief Specialized version of getNextSource for ExtractSubreg
226 /// instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000227 bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000228 /// \brief Specialized version of getNextSource for SubregToReg
229 /// instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000230 bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000231
232 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000233 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000234 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000235 /// track. It does not need to match the sub register index used in the
236 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000237 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
238 /// through complex instructions. By default (false), it handles only copy
239 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000240 /// If \p Reg is a physical register, a value tracker constructed with
241 /// this constructor will not find any alternative source.
242 /// Indeed, when \p Reg is a physical register that constructor does not
243 /// know which definition of \p Reg it should track.
244 /// Use the next constructor to track a physical register.
245 ValueTracker(unsigned Reg, unsigned DefSubReg,
246 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000247 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000248 const TargetInstrInfo *TII = nullptr)
249 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
250 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
251 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
252 Def = MRI.getVRegDef(Reg);
253 DefIdx = MRI.def_begin(Reg).getOperandNo();
254 }
255 }
256
257 /// \brief Create a ValueTracker instance for the value defined by
258 /// the pair \p MI, \p DefIdx.
259 /// Unlike the other constructor, the value tracker produced by this one
260 /// may be able to find a new source when the definition is a physical
261 /// register.
262 /// This could be useful to rewrite target specific instructions into
263 /// generic copy instructions.
264 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
265 const MachineRegisterInfo &MRI,
266 bool UseAdvancedTracking = false,
267 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000268 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000269 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
270 assert(DefIdx < Def->getDesc().getNumDefs() &&
271 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000272 Reg = Def->getOperand(DefIdx).getReg();
273 }
274
275 /// \brief Following the use-def chain, get the next available source
276 /// for the tracked value.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000277 /// When the returned value is not nullptr, \p SrcReg gives the register
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000278 /// that contain the tracked value.
279 /// \note The sub register index returned in \p SrcSubReg must be used
Quentin Colombet03e43f82014-08-20 17:41:48 +0000280 /// on \p SrcReg to access the actual value.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000281 /// \return Unless the returned value is nullptr (i.e., no source found),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000282 /// \p SrcReg gives the register of the next source used in the returned
283 /// instruction and \p SrcSubReg the sub-register index to be used on that
284 /// source to get the tracked value. When nullptr is returned, no
285 /// alternative source has been found.
286 const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000287
288 /// \brief Get the last register where the initial value can be found.
289 /// Initially this is the register of the definition.
290 /// Then, after each successful call to getNextSource, this is the
291 /// register of the last source.
292 unsigned getReg() const { return Reg; }
293 };
Bill Wendlingca678352010-08-09 23:59:04 +0000294}
295
296char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000297char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000298INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
299 "Peephole Optimizations", false, false)
300INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
301INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000302 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000303
Jim Grosbachedcb8682012-05-01 23:21:41 +0000304/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000305/// a single register and writes a single register and it does not modify the
306/// source, and if the source value is preserved as a sub-register of the
307/// result, then replace all reachable uses of the source with the subreg of the
308/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000309///
Bill Wendlingca678352010-08-09 23:59:04 +0000310/// Do not generate an EXTRACT that is used only in a debug use, as this changes
311/// the code. Since this code does not currently share EXTRACTs, just ignore all
312/// debug uses.
313bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000314optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000315 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000316 unsigned SrcReg, DstReg, SubIdx;
317 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
318 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000319
Bill Wendlingca678352010-08-09 23:59:04 +0000320 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
321 TargetRegisterInfo::isPhysicalRegister(SrcReg))
322 return false;
323
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000324 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000325 // No other uses.
326 return false;
327
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000328 // Ensure DstReg can get a register class that actually supports
329 // sub-registers. Don't change the class until we commit.
330 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000331 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000332 if (!DstRC)
333 return false;
334
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000335 // The ext instr may be operating on a sub-register of SrcReg as well.
336 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
337 // register.
338 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
339 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000340 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000341 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000342
Bill Wendlingca678352010-08-09 23:59:04 +0000343 // The source has other uses. See if we can replace the other uses with use of
344 // the result of the extension.
345 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000346 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
347 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000348
349 // Uses that are in the same BB of uses of the result of the instruction.
350 SmallVector<MachineOperand*, 8> Uses;
351
352 // Uses that the result of the instruction can reach.
353 SmallVector<MachineOperand*, 8> ExtendedUses;
354
355 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000356 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000357 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000358 if (UseMI == MI)
359 continue;
360
361 if (UseMI->isPHI()) {
362 ExtendLife = false;
363 continue;
364 }
365
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000366 // Only accept uses of SrcReg:SubIdx.
367 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
368 continue;
369
Bill Wendlingca678352010-08-09 23:59:04 +0000370 // It's an error to translate this:
371 //
372 // %reg1025 = <sext> %reg1024
373 // ...
374 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
375 //
376 // into this:
377 //
378 // %reg1025 = <sext> %reg1024
379 // ...
380 // %reg1027 = COPY %reg1025:4
381 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
382 //
383 // The problem here is that SUBREG_TO_REG is there to assert that an
384 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
385 // the COPY here, it will give us the value after the <sext>, not the
386 // original value of %reg1024 before <sext>.
387 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
388 continue;
389
390 MachineBasicBlock *UseMBB = UseMI->getParent();
391 if (UseMBB == MBB) {
392 // Local uses that come after the extension.
393 if (!LocalMIs.count(UseMI))
394 Uses.push_back(&UseMO);
395 } else if (ReachedBBs.count(UseMBB)) {
396 // Non-local uses where the result of the extension is used. Always
397 // replace these unless it's a PHI.
398 Uses.push_back(&UseMO);
399 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
400 // We may want to extend the live range of the extension result in order
401 // to replace these uses.
402 ExtendedUses.push_back(&UseMO);
403 } else {
404 // Both will be live out of the def MBB anyway. Don't extend live range of
405 // the extension result.
406 ExtendLife = false;
407 break;
408 }
409 }
410
411 if (ExtendLife && !ExtendedUses.empty())
412 // Extend the liveness of the extension result.
413 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
414 std::back_inserter(Uses));
415
416 // Now replace all uses.
417 bool Changed = false;
418 if (!Uses.empty()) {
419 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
420
421 // Look for PHI uses of the extended result, we don't want to extend the
422 // liveness of a PHI input. It breaks all kinds of assumptions down
423 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000424 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
425 if (UI.isPHI())
426 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000427
428 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
429 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
430 MachineOperand *UseMO = Uses[i];
431 MachineInstr *UseMI = UseMO->getParent();
432 MachineBasicBlock *UseMBB = UseMI->getParent();
433 if (PHIBBs.count(UseMBB))
434 continue;
435
Lang Hamesd5862ce2012-02-25 02:01:00 +0000436 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000437 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000438 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000439 MRI->constrainRegClass(DstReg, DstRC);
440 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000441
Bill Wendlingca678352010-08-09 23:59:04 +0000442 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000443 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
444 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000445 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000446 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
447 if (UseSrcSubIdx) {
448 Copy->getOperand(0).setSubReg(SubIdx);
449 Copy->getOperand(0).setIsUndef();
450 }
Bill Wendlingca678352010-08-09 23:59:04 +0000451 UseMO->setReg(NewVR);
452 ++NumReuse;
453 Changed = true;
454 }
455 }
456
457 return Changed;
458}
459
Jim Grosbachedcb8682012-05-01 23:21:41 +0000460/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000461/// instruction it's comparing against all ready sets (or could be modified to
462/// set) the same flag as the compare, then we can remove the comparison and use
463/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000464bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000465 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000466 // If this instruction is a comparison against zero and isn't comparing a
467 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000468 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000469 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000470 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
471 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
472 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000473 return false;
474
Bill Wendling27dddd12010-09-11 00:13:50 +0000475 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000476 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000477 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000478 return true;
479 }
480
481 return false;
482}
483
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000484/// Optimize a select instruction.
485bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI) {
486 unsigned TrueOp = 0;
487 unsigned FalseOp = 0;
488 bool Optimizable = false;
489 SmallVector<MachineOperand, 4> Cond;
490 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
491 return false;
492 if (!Optimizable)
493 return false;
494 if (!TII->optimizeSelect(MI))
495 return false;
496 MI->eraseFromParent();
497 ++NumSelects;
498 return true;
499}
500
Quentin Colombetcf71c632013-09-13 18:26:31 +0000501/// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
502/// share the same register file.
503static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
504 const TargetRegisterClass *DefRC,
505 unsigned DefSubReg,
506 const TargetRegisterClass *SrcRC,
507 unsigned SrcSubReg) {
508 // Same register class.
509 if (DefRC == SrcRC)
510 return true;
511
512 // Both operands are sub registers. Check if they share a register class.
513 unsigned SrcIdx, DefIdx;
514 if (SrcSubReg && DefSubReg)
515 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
Craig Topperc0196b12014-04-14 00:51:57 +0000516 SrcIdx, DefIdx) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000517 // At most one of the register is a sub register, make it Src to avoid
518 // duplicating the test.
519 if (!SrcSubReg) {
520 std::swap(DefSubReg, SrcSubReg);
521 std::swap(DefRC, SrcRC);
522 }
523
524 // One of the register is a sub register, check if we can get a superclass.
525 if (SrcSubReg)
Craig Topperc0196b12014-04-14 00:51:57 +0000526 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000527 // Plain copy.
Craig Topperc0196b12014-04-14 00:51:57 +0000528 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000529}
530
Quentin Colombet03e43f82014-08-20 17:41:48 +0000531/// \brief Try to find the next source that share the same register file
532/// for the value defined by \p Reg and \p SubReg.
533/// When true is returned, \p Reg and \p SubReg are updated with the
534/// register number and sub-register index of the new source.
535/// \return False if no alternative sources are available. True otherwise.
536bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
537 // Do not try to find a new source for a physical register.
538 // So far we do not have any motivating example for doing that.
539 // Thus, instead of maintaining untested code, we will revisit that if
540 // that changes at some point.
541 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000542 return false;
543
Quentin Colombet03e43f82014-08-20 17:41:48 +0000544 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
545 unsigned DefSubReg = SubReg;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000546
547 unsigned Src;
548 unsigned SrcSubReg;
549 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000550
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000551 // Follow the chain of copies until we reach the top of the use-def chain
552 // or find a more suitable source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000553 ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000554 do {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000555 unsigned CopySrcReg, CopySrcSubReg;
556 if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000557 break;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000558 Src = CopySrcReg;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000559 SrcSubReg = CopySrcSubReg;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000560
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000561 // Do not extend the live-ranges of physical registers as they add
562 // constraints to the register allocator.
563 // Moreover, if we want to extend the live-range of a physical register,
564 // unlike SSA virtual register, we will have to check that they are not
565 // redefine before the related use.
Quentin Colombetcf71c632013-09-13 18:26:31 +0000566 if (TargetRegisterInfo::isPhysicalRegister(Src))
567 break;
568
569 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000570
571 // If this source does not incur a cross register bank copy, use it.
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000572 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, DefSubReg, SrcRC,
Quentin Colombetcf71c632013-09-13 18:26:31 +0000573 SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000574 } while (!ShouldRewrite);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000575
576 // If we did not find a more suitable source, there is nothing to optimize.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000577 if (!ShouldRewrite || Src == Reg)
Quentin Colombetcf71c632013-09-13 18:26:31 +0000578 return false;
579
Quentin Colombet03e43f82014-08-20 17:41:48 +0000580 Reg = Src;
581 SubReg = SrcSubReg;
582 return true;
583}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000584
Quentin Colombet03e43f82014-08-20 17:41:48 +0000585namespace {
586/// \brief Helper class to rewrite the arguments of a copy-like instruction.
587class CopyRewriter {
588protected:
589 /// The copy-like instruction.
590 MachineInstr &CopyLike;
591 /// The index of the source being rewritten.
592 unsigned CurrentSrcIdx;
593
594public:
595 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
596
597 virtual ~CopyRewriter() {}
598
599 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
600 /// the related value that it affects (TrackReg, TrackSubReg).
601 /// A source is considered rewritable if its register class and the
602 /// register class of the related TrackReg may not be register
603 /// coalescer friendly. In other words, given a copy-like instruction
604 /// not all the arguments may be returned at rewritable source, since
605 /// some arguments are none to be register coalescer friendly.
606 ///
607 /// Each call of this method moves the current source to the next
608 /// rewritable source.
609 /// For instance, let CopyLike be the instruction to rewrite.
610 /// CopyLike has one definition and one source:
611 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
612 ///
613 /// The first call will give the first rewritable source, i.e.,
614 /// the only source this instruction has:
615 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
616 /// This source defines the whole definition, i.e.,
617 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
618 ///
619 /// The second and subsequent calls will return false, has there is only one
620 /// rewritable source.
621 ///
622 /// \return True if a rewritable source has been found, false otherwise.
623 /// The output arguments are valid if and only if true is returned.
624 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
625 unsigned &TrackReg,
626 unsigned &TrackSubReg) {
627 // If CurrentSrcIdx == 1, this means this function has already been
628 // called once. CopyLike has one defintiion and one argument, thus,
629 // there is nothing else to rewrite.
630 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
631 return false;
632 // This is the first call to getNextRewritableSource.
633 // Move the CurrentSrcIdx to remember that we made that call.
634 CurrentSrcIdx = 1;
635 // The rewritable source is the argument.
636 const MachineOperand &MOSrc = CopyLike.getOperand(1);
637 SrcReg = MOSrc.getReg();
638 SrcSubReg = MOSrc.getSubReg();
639 // What we track are the alternative sources of the definition.
640 const MachineOperand &MODef = CopyLike.getOperand(0);
641 TrackReg = MODef.getReg();
642 TrackSubReg = MODef.getSubReg();
643 return true;
644 }
645
646 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
647 /// if possible.
648 /// \return True if the rewritting was possible, false otherwise.
649 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
650 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
651 return false;
652 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
653 MOSrc.setReg(NewReg);
654 MOSrc.setSubReg(NewSubReg);
655 return true;
656 }
657};
658
659/// \brief Specialized rewriter for INSERT_SUBREG instruction.
660class InsertSubregRewriter : public CopyRewriter {
661public:
662 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
663 assert(MI.isInsertSubreg() && "Invalid instruction");
664 }
665
666 /// \brief See CopyRewriter::getNextRewritableSource.
667 /// Here CopyLike has the following form:
668 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
669 /// Src1 has the same register class has dst, hence, there is
670 /// nothing to rewrite.
671 /// Src2.src2SubIdx, may not be register coalescer friendly.
672 /// Therefore, the first call to this method returns:
673 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
674 /// (TrackReg, TrackSubReg) = (dst, subIdx).
675 ///
676 /// Subsequence calls will return false.
677 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
678 unsigned &TrackReg,
679 unsigned &TrackSubReg) override {
680 // If we already get the only source we can rewrite, return false.
681 if (CurrentSrcIdx == 2)
682 return false;
683 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
684 CurrentSrcIdx = 2;
685 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
686 SrcReg = MOInsertedReg.getReg();
687 SrcSubReg = MOInsertedReg.getSubReg();
688 const MachineOperand &MODef = CopyLike.getOperand(0);
689
690 // We want to track something that is compatible with the
691 // partial definition.
692 TrackReg = MODef.getReg();
693 if (MODef.getSubReg())
694 // Bails if we have to compose sub-register indices.
695 return false;
696 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
697 return true;
698 }
699 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
700 if (CurrentSrcIdx != 2)
701 return false;
702 // We are rewriting the inserted reg.
703 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
704 MO.setReg(NewReg);
705 MO.setSubReg(NewSubReg);
706 return true;
707 }
708};
709
710/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
711class ExtractSubregRewriter : public CopyRewriter {
712 const TargetInstrInfo &TII;
713
714public:
715 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
716 : CopyRewriter(MI), TII(TII) {
717 assert(MI.isExtractSubreg() && "Invalid instruction");
718 }
719
720 /// \brief See CopyRewriter::getNextRewritableSource.
721 /// Here CopyLike has the following form:
722 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
723 /// There is only one rewritable source: Src.subIdx,
724 /// which defines dst.dstSubIdx.
725 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
726 unsigned &TrackReg,
727 unsigned &TrackSubReg) override {
728 // If we already get the only source we can rewrite, return false.
729 if (CurrentSrcIdx == 1)
730 return false;
731 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
732 CurrentSrcIdx = 1;
733 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
734 SrcReg = MOExtractedReg.getReg();
735 // If we have to compose sub-register indices, bails out.
736 if (MOExtractedReg.getSubReg())
737 return false;
738
739 SrcSubReg = CopyLike.getOperand(2).getImm();
740
741 // We want to track something that is compatible with the definition.
742 const MachineOperand &MODef = CopyLike.getOperand(0);
743 TrackReg = MODef.getReg();
744 TrackSubReg = MODef.getSubReg();
745 return true;
746 }
747
748 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
749 // The only source we can rewrite is the input register.
750 if (CurrentSrcIdx != 1)
751 return false;
752
753 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
754
755 // If we find a source that does not require to extract something,
756 // rewrite the operation with a copy.
757 if (!NewSubReg) {
758 // Move the current index to an invalid position.
759 // We do not want another call to this method to be able
760 // to do any change.
761 CurrentSrcIdx = -1;
762 // Rewrite the operation as a COPY.
763 // Get rid of the sub-register index.
764 CopyLike.RemoveOperand(2);
765 // Morph the operation into a COPY.
766 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
767 return true;
768 }
769 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
770 return true;
771 }
772};
773
774/// \brief Specialized rewriter for REG_SEQUENCE instruction.
775class RegSequenceRewriter : public CopyRewriter {
776public:
777 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
778 assert(MI.isRegSequence() && "Invalid instruction");
779 }
780
781 /// \brief See CopyRewriter::getNextRewritableSource.
782 /// Here CopyLike has the following form:
783 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
784 /// Each call will return a different source, walking all the available
785 /// source.
786 ///
787 /// The first call returns:
788 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
789 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
790 ///
791 /// The second call returns:
792 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
793 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
794 ///
795 /// And so on, until all the sources have been traversed, then
796 /// it returns false.
797 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
798 unsigned &TrackReg,
799 unsigned &TrackSubReg) override {
800 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
801
802 // If this is the first call, move to the first argument.
803 if (CurrentSrcIdx == 0) {
804 CurrentSrcIdx = 1;
805 } else {
806 // Otherwise, move to the next argument and check that it is valid.
807 CurrentSrcIdx += 2;
808 if (CurrentSrcIdx >= CopyLike.getNumOperands())
809 return false;
810 }
811 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
812 SrcReg = MOInsertedReg.getReg();
813 // If we have to compose sub-register indices, bails out.
814 if ((SrcSubReg = MOInsertedReg.getSubReg()))
815 return false;
816
817 // We want to track something that is compatible with the related
818 // partial definition.
819 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
820
821 const MachineOperand &MODef = CopyLike.getOperand(0);
822 TrackReg = MODef.getReg();
823 // If we have to compose sub-registers, bails.
824 return MODef.getSubReg() == 0;
825 }
826
827 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
828 // We cannot rewrite out of bound operands.
829 // Moreover, rewritable sources are at odd positions.
830 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
831 return false;
832
833 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
834 MO.setReg(NewReg);
835 MO.setSubReg(NewSubReg);
836 return true;
837 }
838};
839} // End namespace.
840
841/// \brief Get the appropriated CopyRewriter for \p MI.
842/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
843/// if no rewriter works for \p MI.
844static CopyRewriter *getCopyRewriter(MachineInstr &MI,
845 const TargetInstrInfo &TII) {
846 switch (MI.getOpcode()) {
847 default:
848 return nullptr;
849 case TargetOpcode::COPY:
850 return new CopyRewriter(MI);
851 case TargetOpcode::INSERT_SUBREG:
852 return new InsertSubregRewriter(MI);
853 case TargetOpcode::EXTRACT_SUBREG:
854 return new ExtractSubregRewriter(MI, TII);
855 case TargetOpcode::REG_SEQUENCE:
856 return new RegSequenceRewriter(MI);
857 }
858 llvm_unreachable(nullptr);
859}
860
861/// \brief Optimize generic copy instructions to avoid cross
862/// register bank copy. The optimization looks through a chain of
863/// copies and tries to find a source that has a compatible register
864/// class.
865/// Two register classes are considered to be compatible if they share
866/// the same register bank.
867/// New copies issued by this optimization are register allocator
868/// friendly. This optimization does not remove any copy as it may
869/// overconstraint the register allocator, but replaces some operands
870/// when possible.
871/// \pre isCoalescableCopy(*MI) is true.
872/// \return True, when \p MI has been rewritten. False otherwise.
873bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
874 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
875 assert(MI->getDesc().getNumDefs() == 1 &&
876 "Coalescer can understand multiple defs?!");
877 const MachineOperand &MODef = MI->getOperand(0);
878 // Do not rewrite physical definitions.
879 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
880 return false;
881
882 bool Changed = false;
883 // Get the right rewriter for the current copy.
884 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
885 // If none exists, bails out.
886 if (!CpyRewriter)
887 return false;
888 // Rewrite each rewritable source.
889 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
890 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
891 TrackSubReg)) {
892 unsigned NewSrc = TrackReg;
893 unsigned NewSubReg = TrackSubReg;
894 // Try to find a more suitable source.
895 // If we failed to do so, or get the actual source,
896 // move to the next source.
897 if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
898 continue;
899 // Rewrite source.
Quentin Colombet6b363372014-08-21 21:34:06 +0000900 if (CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg)) {
901 // We may have extended the live-range of NewSrc, account for that.
902 MRI->clearKillFlags(NewSrc);
903 Changed = true;
904 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000905 }
906 // TODO: We could have a clean-up method to tidy the instruction.
907 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
908 // => v0 = COPY v1
909 // Currently we haven't seen motivating example for that and we
910 // want to avoid untested code.
911 NumRewrittenCopies += Changed == true;
912 return Changed;
913}
914
915/// \brief Optimize copy-like instructions to create
916/// register coalescer friendly instruction.
917/// The optimization tries to kill-off the \p MI by looking
918/// through a chain of copies to find a source that has a compatible
919/// register class.
920/// If such a source is found, it replace \p MI by a generic COPY
921/// operation.
922/// \pre isUncoalescableCopy(*MI) is true.
923/// \return True, when \p MI has been optimized. In that case, \p MI has
924/// been removed from its parent.
925/// All COPY instructions created, are inserted in \p LocalMIs.
926bool PeepholeOptimizer::optimizeUncoalescableCopy(
927 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
928 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
929
930 // Check if we can rewrite all the values defined by this instruction.
931 SmallVector<
932 std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
933 4> RewritePairs;
934 for (const MachineOperand &MODef : MI->defs()) {
935 if (MODef.isDead())
936 // We can ignore those.
937 continue;
938
939 // If a physical register is here, this is probably for a good reason.
940 // Do not rewrite that.
941 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
942 return false;
943
944 // If we do not know how to rewrite this definition, there is no point
945 // in trying to kill this instruction.
946 TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
947 TargetInstrInfo::RegSubRegPair Src = Def;
948 if (!findNextSource(Src.Reg, Src.SubReg))
949 return false;
950 RewritePairs.push_back(std::make_pair(Def, Src));
951 }
952 // The change is possible for all defs, do it.
953 for (const auto &PairDefSrc : RewritePairs) {
954 const auto &Def = PairDefSrc.first;
955 const auto &Src = PairDefSrc.second;
956 // Rewrite the "copy" in a way the register coalescer understands.
957 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
958 "We do not rewrite physical registers");
959 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
960 unsigned NewVR = MRI->createVirtualRegister(DefRC);
961 MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
962 TII->get(TargetOpcode::COPY),
963 NewVR).addReg(Src.Reg, 0, Src.SubReg);
964 NewCopy->getOperand(0).setSubReg(Def.SubReg);
965 if (Def.SubReg)
966 NewCopy->getOperand(0).setIsUndef();
967 LocalMIs.insert(NewCopy);
968 MRI->replaceRegWith(Def.Reg, NewVR);
969 MRI->clearKillFlags(NewVR);
970 // We extended the lifetime of Src.
971 // Clear the kill flags to account for that.
972 MRI->clearKillFlags(Src.Reg);
973 }
974 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +0000975 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +0000976 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000977 return true;
978}
979
Manman Ren5759d012012-08-02 00:56:42 +0000980/// isLoadFoldable - Check whether MI is a candidate for folding into a later
981/// instruction. We only fold loads to virtual registers and the virtual
982/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +0000983bool PeepholeOptimizer::isLoadFoldable(
984 MachineInstr *MI,
985 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +0000986 if (!MI->canFoldAsLoad() || !MI->mayLoad())
987 return false;
988 const MCInstrDesc &MCID = MI->getDesc();
989 if (MCID.getNumDefs() != 1)
990 return false;
991
992 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +0000993 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +0000994 // loads. It should be checked when processing uses of the load, since
995 // uses can be removed during peephole.
996 if (!MI->getOperand(0).getSubReg() &&
997 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +0000998 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +0000999 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001000 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001001 }
1002 return false;
1003}
1004
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001005bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1006 SmallSet<unsigned, 4> &ImmDefRegs,
1007 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001008 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001009 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001010 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001011 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001012 return false;
1013 unsigned Reg = MI->getOperand(0).getReg();
1014 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1015 ImmDefMIs.insert(std::make_pair(Reg, MI));
1016 ImmDefRegs.insert(Reg);
1017 return true;
1018 }
Andrew Trick9e761992012-02-08 21:22:43 +00001019
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001020 return false;
1021}
1022
Jim Grosbachedcb8682012-05-01 23:21:41 +00001023/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001024/// immediate instructions, i.e. a trivial constant folding optimization, if
1025/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001026bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001027 SmallSet<unsigned, 4> &ImmDefRegs,
1028 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1029 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1030 MachineOperand &MO = MI->getOperand(i);
1031 if (!MO.isReg() || MO.isDef())
1032 continue;
1033 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001034 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001035 continue;
1036 if (ImmDefRegs.count(Reg) == 0)
1037 continue;
1038 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1039 assert(II != ImmDefMIs.end());
1040 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1041 ++NumImmFold;
1042 return true;
1043 }
1044 }
1045 return false;
1046}
1047
Eric Christopher92b4bcb2014-10-14 07:17:20 +00001048bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &mf) {
1049 if (skipOptnoneFunction(*mf.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001050 return false;
1051
Craig Topper588ceec2012-12-17 03:56:00 +00001052 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher92b4bcb2014-10-14 07:17:20 +00001053 DEBUG(dbgs() << "********** Function: " << mf.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001054
Evan Cheng2ce016c2010-11-15 21:20:45 +00001055 if (DisablePeephole)
1056 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001057
Eric Christopher92b4bcb2014-10-14 07:17:20 +00001058 MF = &mf;
1059 TII = MF->getSubtarget().getInstrInfo();
1060 TRI = MF->getSubtarget().getRegisterInfo();
1061 MRI = &MF->getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001062 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001063
1064 bool Changed = false;
1065
Eric Christopher92b4bcb2014-10-14 07:17:20 +00001066 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001067 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001068
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001069 bool SeenMoveImm = false;
Hans Wennborg941a5702014-08-11 02:50:43 +00001070 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001071 SmallSet<unsigned, 4> ImmDefRegs;
1072 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1073 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001074
1075 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001076 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001077 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001078 // We may be erasing MI below, increment MII now.
1079 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001080 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001081
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001082 // Skip debug values. They should not affect this peephole optimization.
1083 if (MI->isDebugValue())
1084 continue;
1085
Manman Ren5759d012012-08-02 00:56:42 +00001086 // If there exists an instruction which belongs to the following
Lang Hames5dc14bd2014-04-02 22:59:58 +00001087 // categories, we will discard the load candidates.
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001088 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001089 MI->isKill() || MI->isInlineAsm() ||
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001090 MI->hasUnmodeledSideEffects()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001091 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001092 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001093 }
Manman Ren5759d012012-08-02 00:56:42 +00001094 if (MI->mayStore() || MI->isCall())
Lang Hames5dc14bd2014-04-02 22:59:58 +00001095 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001096
Quentin Colombet03e43f82014-08-20 17:41:48 +00001097 if ((isUncoalescableCopy(*MI) &&
1098 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001099 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
1100 (MI->isSelect() && optimizeSelect(MI))) {
1101 // MI is deleted.
1102 LocalMIs.erase(MI);
1103 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001104 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001105 }
1106
Quentin Colombet03e43f82014-08-20 17:41:48 +00001107 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1108 // MI is just rewritten.
1109 Changed = true;
1110 continue;
1111 }
1112
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001113 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001114 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001115 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001116 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001117 // optimizeExtInstr might have created new instructions after MI
1118 // and before the already incremented MII. Adjust MII so that the
1119 // next iteration sees the new instructions.
1120 MII = MI;
1121 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001122 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001123 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001124 }
Evan Cheng98196b42011-02-15 05:00:24 +00001125
Manman Ren5759d012012-08-02 00:56:42 +00001126 // Check whether MI is a load candidate for folding into a later
1127 // instruction. If MI is not a candidate, check whether we can fold an
1128 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001129 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1130 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001131 const MCInstrDesc &MIDesc = MI->getDesc();
1132 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1133 ++i) {
1134 const MachineOperand &MOp = MI->getOperand(i);
1135 if (!MOp.isReg())
1136 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001137 unsigned FoldAsLoadDefReg = MOp.getReg();
1138 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1139 // We need to fold load after optimizeCmpInstr, since
1140 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1141 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1142 // we need it for markUsesInDebugValueAsUndef().
1143 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001144 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001145 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1146 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001147 DefMI);
1148 if (FoldMI) {
1149 // Update LocalMIs since we replaced MI with FoldMI and deleted
1150 // DefMI.
1151 DEBUG(dbgs() << "Replacing: " << *MI);
1152 DEBUG(dbgs() << " With: " << *FoldMI);
1153 LocalMIs.erase(MI);
1154 LocalMIs.erase(DefMI);
1155 LocalMIs.insert(FoldMI);
1156 MI->eraseFromParent();
1157 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001158 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1159 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001160 ++NumLoadFold;
1161 // MI is replaced with FoldMI.
1162 Changed = true;
1163 break;
1164 }
1165 }
Manman Ren5759d012012-08-02 00:56:42 +00001166 }
1167 }
Bill Wendlingca678352010-08-09 23:59:04 +00001168 }
1169 }
1170
1171 return Changed;
1172}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001173
Quentin Colombet03e43f82014-08-20 17:41:48 +00001174bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001175 unsigned &SrcSubReg) {
1176 assert(Def->isCopy() && "Invalid definition");
1177 // Copy instruction are supposed to be: Def = Src.
1178 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001179 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001180
1181 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1182 // If we look for a different subreg, it means we want a subreg of src.
1183 // Bails as we do not support composing subreg yet.
1184 return false;
1185 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001186 const MachineOperand &Src = Def->getOperand(1);
1187 SrcReg = Src.getReg();
1188 SrcSubReg = Src.getSubReg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001189 return true;
1190}
1191
Quentin Colombet03e43f82014-08-20 17:41:48 +00001192bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001193 unsigned &SrcSubReg) {
1194 assert(Def->isBitcast() && "Invalid definition");
1195
1196 // Bail if there are effects that a plain copy will not expose.
1197 if (Def->hasUnmodeledSideEffects())
1198 return false;
1199
1200 // Bitcasts with more than one def are not supported.
1201 if (Def->getDesc().getNumDefs() != 1)
1202 return false;
1203 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1204 // If we look for a different subreg, it means we want a subreg of the src.
1205 // Bails as we do not support composing subreg yet.
1206 return false;
1207
Quentin Colombet03e43f82014-08-20 17:41:48 +00001208 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001209 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1210 ++OpIdx) {
1211 const MachineOperand &MO = Def->getOperand(OpIdx);
1212 if (!MO.isReg() || !MO.getReg())
1213 continue;
1214 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1215 if (SrcIdx != EndOpIdx)
1216 // Multiple sources?
1217 return false;
1218 SrcIdx = OpIdx;
1219 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001220 const MachineOperand &Src = Def->getOperand(SrcIdx);
1221 SrcReg = Src.getReg();
1222 SrcSubReg = Src.getSubReg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001223 return true;
1224}
1225
Quentin Colombet03e43f82014-08-20 17:41:48 +00001226bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001227 unsigned &SrcSubReg) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001228 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1229 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001230
1231 if (Def->getOperand(DefIdx).getSubReg())
1232 // If we are composing subreg, bails out.
1233 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1234 // This should almost never happen as the SSA property is tracked at
1235 // the register level (as opposed to the subreg level).
1236 // I.e.,
1237 // Def.sub0 =
1238 // Def.sub1 =
1239 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1240 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001241 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001242 // Def.sub0 (i.e, not defining the other subregs) and we would
1243 // have this case.
1244 // If we can ascertain (or force) that this never happens, we could
1245 // turn that into an assertion.
1246 return false;
1247
Quentin Colombet03e43f82014-08-20 17:41:48 +00001248 if (!TII)
1249 // We could handle the REG_SEQUENCE here, but we do not want to
1250 // duplicate the code from the generic TII.
1251 return false;
1252
1253 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1254 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1255 return false;
1256
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001257 // We are looking at:
1258 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1259 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001260 for (auto &RegSeqInput : RegSeqInputRegs) {
1261 if (RegSeqInput.SubIdx == DefSubReg) {
1262 if (RegSeqInput.SubReg)
1263 // Bails if we have to compose sub registers.
1264 return false;
1265
1266 SrcReg = RegSeqInput.Reg;
1267 SrcSubReg = RegSeqInput.SubReg;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001268 return true;
1269 }
1270 }
1271
1272 // If the subreg we are tracking is super-defined by another subreg,
1273 // we could follow this value. However, this would require to compose
1274 // the subreg and we do not do that for now.
1275 return false;
1276}
1277
Quentin Colombet03e43f82014-08-20 17:41:48 +00001278bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001279 unsigned &SrcSubReg) {
Quentin Colombet68962302014-08-21 00:19:16 +00001280 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1281 "Invalid definition");
1282
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001283 if (Def->getOperand(DefIdx).getSubReg())
1284 // If we are composing subreg, bails out.
1285 // Same remark as getNextSourceFromRegSequence.
1286 // I.e., this may be turned into an assert.
1287 return false;
1288
Quentin Colombet68962302014-08-21 00:19:16 +00001289 if (!TII)
1290 // We could handle the REG_SEQUENCE here, but we do not want to
1291 // duplicate the code from the generic TII.
1292 return false;
1293
Quentin Colombet03e43f82014-08-20 17:41:48 +00001294 TargetInstrInfo::RegSubRegPair BaseReg;
1295 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001296 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1297 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001298
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001299 // We are looking at:
1300 // Def = INSERT_SUBREG v0, v1, sub1
1301 // There are two cases:
1302 // 1. DefSubReg == sub1, get v1.
1303 // 2. DefSubReg != sub1, the value may be available through v0.
1304
Quentin Colombet03e43f82014-08-20 17:41:48 +00001305 // #1 Check if the inserted register matches the required sub index.
1306 if (InsertedReg.SubIdx == DefSubReg) {
1307 SrcReg = InsertedReg.Reg;
1308 SrcSubReg = InsertedReg.SubReg;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001309 return true;
1310 }
1311 // #2 Otherwise, if the sub register we are looking for is not partial
1312 // defined by the inserted element, we can look through the main
1313 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001314 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001315 // If the result register (Def) and the base register (v0) do not
1316 // have the same register class or if we have to compose
1317 // subregisters, bails out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001318 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1319 BaseReg.SubReg)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001320 return false;
1321
Quentin Colombet03e43f82014-08-20 17:41:48 +00001322 // Get the TRI and check if the inserted sub-register overlaps with the
1323 // sub-register we are tracking.
1324 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001325 if (!TRI ||
1326 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001327 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001328 return false;
1329 // At this point, the value is available in v0 via the same subreg
1330 // we used for Def.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001331 SrcReg = BaseReg.Reg;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001332 SrcSubReg = DefSubReg;
1333 return true;
1334}
1335
Quentin Colombet03e43f82014-08-20 17:41:48 +00001336bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001337 unsigned &SrcSubReg) {
Quentin Colombet67639df2014-08-20 23:13:02 +00001338 assert((Def->isExtractSubreg() ||
1339 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001340 // We are looking at:
1341 // Def = EXTRACT_SUBREG v0, sub0
1342
1343 // Bails if we have to compose sub registers.
1344 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1345 if (DefSubReg)
1346 return false;
1347
Quentin Colombet67639df2014-08-20 23:13:02 +00001348 if (!TII)
1349 // We could handle the EXTRACT_SUBREG here, but we do not want to
1350 // duplicate the code from the generic TII.
1351 return false;
1352
Quentin Colombet03e43f82014-08-20 17:41:48 +00001353 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001354 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1355 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001356
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001357 // Bails if we have to compose sub registers.
1358 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001359 if (ExtractSubregInputReg.SubReg)
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001360 return false;
1361 // Otherwise, the value is available in the v0.sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001362 SrcReg = ExtractSubregInputReg.Reg;
1363 SrcSubReg = ExtractSubregInputReg.SubIdx;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001364 return true;
1365}
1366
Quentin Colombet03e43f82014-08-20 17:41:48 +00001367bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001368 unsigned &SrcSubReg) {
1369 assert(Def->isSubregToReg() && "Invalid definition");
1370 // We are looking at:
1371 // Def = SUBREG_TO_REG Imm, v0, sub0
1372
1373 // Bails if we have to compose sub registers.
1374 // If DefSubReg != sub0, we would have to check that all the bits
1375 // we track are included in sub0 and if yes, we would have to
1376 // determine the right subreg in v0.
1377 if (DefSubReg != Def->getOperand(3).getImm())
1378 return false;
1379 // Bails if we have to compose sub registers.
1380 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1381 if (Def->getOperand(2).getSubReg())
1382 return false;
1383
Quentin Colombet03e43f82014-08-20 17:41:48 +00001384 SrcReg = Def->getOperand(2).getReg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001385 SrcSubReg = Def->getOperand(3).getImm();
1386 return true;
1387}
1388
Quentin Colombet03e43f82014-08-20 17:41:48 +00001389bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001390 assert(Def && "This method needs a valid definition");
1391
1392 assert(
1393 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1394 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1395 if (Def->isCopy())
Quentin Colombet03e43f82014-08-20 17:41:48 +00001396 return getNextSourceFromCopy(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001397 if (Def->isBitcast())
Quentin Colombet03e43f82014-08-20 17:41:48 +00001398 return getNextSourceFromBitcast(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001399 // All the remaining cases involve "complex" instructions.
1400 // Bails if we did not ask for the advanced tracking.
1401 if (!UseAdvancedTracking)
1402 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001403 if (Def->isRegSequence() || Def->isRegSequenceLike())
1404 return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
Quentin Colombet68962302014-08-21 00:19:16 +00001405 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Quentin Colombet03e43f82014-08-20 17:41:48 +00001406 return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
Quentin Colombet67639df2014-08-20 23:13:02 +00001407 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Quentin Colombet03e43f82014-08-20 17:41:48 +00001408 return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001409 if (Def->isSubregToReg())
Quentin Colombet03e43f82014-08-20 17:41:48 +00001410 return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001411 return false;
1412}
1413
Quentin Colombet03e43f82014-08-20 17:41:48 +00001414const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001415 unsigned &SrcSubReg) {
1416 // If we reach a point where we cannot move up in the use-def chain,
1417 // there is nothing we can get.
1418 if (!Def)
1419 return nullptr;
1420
1421 const MachineInstr *PrevDef = nullptr;
1422 // Try to find the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001423 if (getNextSourceImpl(SrcReg, SrcSubReg)) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001424 // Update definition, definition index, and subregister for the
1425 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001426 // Update the current register.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001427 Reg = SrcReg;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001428 // Update the return value before moving up in the use-def chain.
1429 PrevDef = Def;
1430 // If we can still move up in the use-def chain, move to the next
1431 // defintion.
1432 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001433 Def = MRI.getVRegDef(Reg);
1434 DefIdx = MRI.def_begin(Reg).getOperandNo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001435 DefSubReg = SrcSubReg;
1436 return PrevDef;
1437 }
1438 }
1439 // If we end up here, this means we will not be able to find another source
1440 // for the next iteration.
1441 // Make sure any new call to getNextSource bails out early by cutting the
1442 // use-def chain.
1443 Def = nullptr;
1444 return PrevDef;
1445}