blob: ebe05e3f27316bc15fd6a69ea3befc87fbd22117 [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
46// if it loads to virtual registers and the virtual register defined has
47// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Bill Wendlingca678352010-08-09 23:59:04 +000069#include "llvm/CodeGen/Passes.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000070#include "llvm/ADT/DenseMap.h"
Bill Wendlingca678352010-08-09 23:59:04 +000071#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng7f8ab6e2010-11-17 20:13:28 +000072#include "llvm/ADT/SmallSet.h"
Bill Wendlingca678352010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/CodeGen/MachineDominators.h"
75#include "llvm/CodeGen/MachineInstrBuilder.h"
76#include "llvm/CodeGen/MachineRegisterInfo.h"
77#include "llvm/Support/CommandLine.h"
Craig Topper588ceec2012-12-17 03:56:00 +000078#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000079#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000080#include "llvm/Target/TargetInstrInfo.h"
81#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000082#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet03e43f82014-08-20 17:41:48 +000083#include <utility>
Bill Wendlingca678352010-08-09 23:59:04 +000084using namespace llvm;
85
Chandler Carruth1b9dde02014-04-22 02:02:50 +000086#define DEBUG_TYPE "peephole-opt"
87
Bill Wendlingca678352010-08-09 23:59:04 +000088// Optimize Extensions
89static cl::opt<bool>
90Aggressive("aggressive-ext-opt", cl::Hidden,
91 cl::desc("Aggressive extension optimization"));
92
Bill Wendlingc6627ee2010-11-01 20:41:43 +000093static cl::opt<bool>
94DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
95 cl::desc("Disable the peephole optimizer"));
96
Quentin Colombet1111e6f2014-07-01 14:33:36 +000097static cl::opt<bool>
Quentin Colombet6674b092014-08-21 22:23:52 +000098DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
Quentin Colombet1111e6f2014-07-01 14:33:36 +000099 cl::desc("Disable advanced copy optimization"));
100
Bill Wendling66284312010-08-27 20:39:09 +0000101STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000102STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000103STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000104STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000105STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000106STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
107STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000108
109namespace {
110 class PeepholeOptimizer : public MachineFunctionPass {
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);
Mehdi Amini22e59742015-01-13 07:07:13 +0000137 bool optimizeSelect(MachineInstr *MI,
138 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000139 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000140 bool optimizeCopyOrBitcast(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000141 bool optimizeCoalescableCopy(MachineInstr *MI);
142 bool optimizeUncoalescableCopy(MachineInstr *MI,
143 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000144 bool findNextSource(unsigned &Reg, unsigned &SubReg);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000145 bool isMoveImmediate(MachineInstr *MI,
146 SmallSet<unsigned, 4> &ImmDefRegs,
147 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000148 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000149 SmallSet<unsigned, 4> &ImmDefRegs,
150 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Lang Hames5dc14bd2014-04-02 22:59:58 +0000151 bool isLoadFoldable(MachineInstr *MI,
152 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000153
154 /// \brief Check whether \p MI is understood by the register coalescer
155 /// but may require some rewriting.
156 bool isCoalescableCopy(const MachineInstr &MI) {
157 // SubregToRegs are not interesting, because they are already register
158 // coalescer friendly.
159 return MI.isCopy() || (!DisableAdvCopyOpt &&
160 (MI.isRegSequence() || MI.isInsertSubreg() ||
161 MI.isExtractSubreg()));
162 }
163
164 /// \brief Check whether \p MI is a copy like instruction that is
165 /// not recognized by the register coalescer.
166 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000167 return MI.isBitcast() ||
168 (!DisableAdvCopyOpt &&
169 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
170 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000171 }
Bill Wendlingca678352010-08-09 23:59:04 +0000172 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000173
174 /// \brief Helper class to track the possible sources of a value defined by
175 /// a (chain of) copy related instructions.
176 /// Given a definition (instruction and definition index), this class
177 /// follows the use-def chain to find successive suitable sources.
178 /// The given source can be used to rewrite the definition into
179 /// def = COPY src.
180 ///
181 /// For instance, let us consider the following snippet:
182 /// v0 =
183 /// v2 = INSERT_SUBREG v1, v0, sub0
184 /// def = COPY v2.sub0
185 ///
186 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
187 /// suitable sources:
188 /// v2.sub0 and v0.
189 /// Then, def can be rewritten into def = COPY v0.
190 class ValueTracker {
191 private:
192 /// The current point into the use-def chain.
193 const MachineInstr *Def;
194 /// The index of the definition in Def.
195 unsigned DefIdx;
196 /// The sub register index of the definition.
197 unsigned DefSubReg;
198 /// The register where the value can be found.
199 unsigned Reg;
200 /// Specifiy whether or not the value tracking looks through
201 /// complex instructions. When this is false, the value tracker
202 /// bails on everything that is not a copy or a bitcast.
203 ///
204 /// Note: This could have been implemented as a specialized version of
205 /// the ValueTracker class but that would have complicated the code of
206 /// the users of this class.
207 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000208 /// MachineRegisterInfo used to perform tracking.
209 const MachineRegisterInfo &MRI;
210 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000211 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000212 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000213
214 /// \brief Dispatcher to the right underlying implementation of
215 /// getNextSource.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000216 bool getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000217 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000218 bool getNextSourceFromCopy(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000219 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000220 bool getNextSourceFromBitcast(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000221 /// \brief Specialized version of getNextSource for RegSequence
222 /// instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000223 bool getNextSourceFromRegSequence(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000224 /// \brief Specialized version of getNextSource for InsertSubreg
225 /// instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000226 bool getNextSourceFromInsertSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000227 /// \brief Specialized version of getNextSource for ExtractSubreg
228 /// instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000229 bool getNextSourceFromExtractSubreg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000230 /// \brief Specialized version of getNextSource for SubregToReg
231 /// instructions.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000232 bool getNextSourceFromSubregToReg(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000233
234 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000235 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000236 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000237 /// track. It does not need to match the sub register index used in the
238 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000239 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
240 /// through complex instructions. By default (false), it handles only copy
241 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000242 /// If \p Reg is a physical register, a value tracker constructed with
243 /// this constructor will not find any alternative source.
244 /// Indeed, when \p Reg is a physical register that constructor does not
245 /// know which definition of \p Reg it should track.
246 /// Use the next constructor to track a physical register.
247 ValueTracker(unsigned Reg, unsigned DefSubReg,
248 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000249 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000250 const TargetInstrInfo *TII = nullptr)
251 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
252 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
253 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
254 Def = MRI.getVRegDef(Reg);
255 DefIdx = MRI.def_begin(Reg).getOperandNo();
256 }
257 }
258
259 /// \brief Create a ValueTracker instance for the value defined by
260 /// the pair \p MI, \p DefIdx.
261 /// Unlike the other constructor, the value tracker produced by this one
262 /// may be able to find a new source when the definition is a physical
263 /// register.
264 /// This could be useful to rewrite target specific instructions into
265 /// generic copy instructions.
266 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
267 const MachineRegisterInfo &MRI,
268 bool UseAdvancedTracking = false,
269 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000270 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000271 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
272 assert(DefIdx < Def->getDesc().getNumDefs() &&
273 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000274 Reg = Def->getOperand(DefIdx).getReg();
275 }
276
277 /// \brief Following the use-def chain, get the next available source
278 /// for the tracked value.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000279 /// When the returned value is not nullptr, \p SrcReg gives the register
280 /// that contain the tracked value.
281 /// \note The sub register index returned in \p SrcSubReg must be used
282 /// on \p SrcReg to access the actual value.
283 /// \return Unless the returned value is nullptr (i.e., no source found),
284 /// \p SrcReg gives the register of the next source used in the returned
285 /// instruction and \p SrcSubReg the sub-register index to be used on that
286 /// source to get the tracked value. When nullptr is returned, no
287 /// alternative source has been found.
288 const MachineInstr *getNextSource(unsigned &SrcReg, unsigned &SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000289
290 /// \brief Get the last register where the initial value can be found.
291 /// Initially this is the register of the definition.
292 /// Then, after each successful call to getNextSource, this is the
293 /// register of the last source.
294 unsigned getReg() const { return Reg; }
295 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000296}
Bill Wendlingca678352010-08-09 23:59:04 +0000297
298char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000299char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000300INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
301 "Peephole Optimizations", false, false)
302INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
303INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000304 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000305
Jim Grosbachedcb8682012-05-01 23:21:41 +0000306/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000307/// a single register and writes a single register and it does not modify the
308/// source, and if the source value is preserved as a sub-register of the
309/// result, then replace all reachable uses of the source with the subreg of the
310/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000311///
Bill Wendlingca678352010-08-09 23:59:04 +0000312/// Do not generate an EXTRACT that is used only in a debug use, as this changes
313/// the code. Since this code does not currently share EXTRACTs, just ignore all
314/// debug uses.
315bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000316optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000317 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000318 unsigned SrcReg, DstReg, SubIdx;
319 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
320 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000321
Bill Wendlingca678352010-08-09 23:59:04 +0000322 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
323 TargetRegisterInfo::isPhysicalRegister(SrcReg))
324 return false;
325
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000326 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000327 // No other uses.
328 return false;
329
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000330 // Ensure DstReg can get a register class that actually supports
331 // sub-registers. Don't change the class until we commit.
332 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000333 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000334 if (!DstRC)
335 return false;
336
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000337 // The ext instr may be operating on a sub-register of SrcReg as well.
338 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
339 // register.
340 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
341 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000342 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000343 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000344
Bill Wendlingca678352010-08-09 23:59:04 +0000345 // The source has other uses. See if we can replace the other uses with use of
346 // the result of the extension.
347 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000348 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
349 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000350
351 // Uses that are in the same BB of uses of the result of the instruction.
352 SmallVector<MachineOperand*, 8> Uses;
353
354 // Uses that the result of the instruction can reach.
355 SmallVector<MachineOperand*, 8> ExtendedUses;
356
357 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000358 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000359 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000360 if (UseMI == MI)
361 continue;
362
363 if (UseMI->isPHI()) {
364 ExtendLife = false;
365 continue;
366 }
367
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000368 // Only accept uses of SrcReg:SubIdx.
369 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
370 continue;
371
Bill Wendlingca678352010-08-09 23:59:04 +0000372 // It's an error to translate this:
373 //
374 // %reg1025 = <sext> %reg1024
375 // ...
376 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
377 //
378 // into this:
379 //
380 // %reg1025 = <sext> %reg1024
381 // ...
382 // %reg1027 = COPY %reg1025:4
383 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
384 //
385 // The problem here is that SUBREG_TO_REG is there to assert that an
386 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
387 // the COPY here, it will give us the value after the <sext>, not the
388 // original value of %reg1024 before <sext>.
389 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
390 continue;
391
392 MachineBasicBlock *UseMBB = UseMI->getParent();
393 if (UseMBB == MBB) {
394 // Local uses that come after the extension.
395 if (!LocalMIs.count(UseMI))
396 Uses.push_back(&UseMO);
397 } else if (ReachedBBs.count(UseMBB)) {
398 // Non-local uses where the result of the extension is used. Always
399 // replace these unless it's a PHI.
400 Uses.push_back(&UseMO);
401 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
402 // We may want to extend the live range of the extension result in order
403 // to replace these uses.
404 ExtendedUses.push_back(&UseMO);
405 } else {
406 // Both will be live out of the def MBB anyway. Don't extend live range of
407 // the extension result.
408 ExtendLife = false;
409 break;
410 }
411 }
412
413 if (ExtendLife && !ExtendedUses.empty())
414 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000415 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000416
417 // Now replace all uses.
418 bool Changed = false;
419 if (!Uses.empty()) {
420 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
421
422 // Look for PHI uses of the extended result, we don't want to extend the
423 // liveness of a PHI input. It breaks all kinds of assumptions down
424 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000425 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
426 if (UI.isPHI())
427 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000428
429 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
430 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
431 MachineOperand *UseMO = Uses[i];
432 MachineInstr *UseMI = UseMO->getParent();
433 MachineBasicBlock *UseMBB = UseMI->getParent();
434 if (PHIBBs.count(UseMBB))
435 continue;
436
Lang Hamesd5862ce2012-02-25 02:01:00 +0000437 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000438 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000439 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000440 MRI->constrainRegClass(DstReg, DstRC);
441 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000442
Bill Wendlingca678352010-08-09 23:59:04 +0000443 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000444 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
445 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000446 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000447 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
448 if (UseSrcSubIdx) {
449 Copy->getOperand(0).setSubReg(SubIdx);
450 Copy->getOperand(0).setIsUndef();
451 }
Bill Wendlingca678352010-08-09 23:59:04 +0000452 UseMO->setReg(NewVR);
453 ++NumReuse;
454 Changed = true;
455 }
456 }
457
458 return Changed;
459}
460
Jim Grosbachedcb8682012-05-01 23:21:41 +0000461/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000462/// instruction it's comparing against all ready sets (or could be modified to
463/// set) the same flag as the compare, then we can remove the comparison and use
464/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000465bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000466 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000467 // If this instruction is a comparison against zero and isn't comparing a
468 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000469 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000470 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000471 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
472 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
473 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000474 return false;
475
Bill Wendling27dddd12010-09-11 00:13:50 +0000476 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000477 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000478 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000479 return true;
480 }
481
482 return false;
483}
484
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000485/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000486bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
487 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000488 unsigned TrueOp = 0;
489 unsigned FalseOp = 0;
490 bool Optimizable = false;
491 SmallVector<MachineOperand, 4> Cond;
492 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
493 return false;
494 if (!Optimizable)
495 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000496 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000497 return false;
498 MI->eraseFromParent();
499 ++NumSelects;
500 return true;
501}
502
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000503/// \brief Check if a simpler conditional branch can be
504// generated
505bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
506 return TII->optimizeCondBranch(MI);
507}
508
Quentin Colombetcf71c632013-09-13 18:26:31 +0000509/// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
510/// share the same register file.
511static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
512 const TargetRegisterClass *DefRC,
513 unsigned DefSubReg,
514 const TargetRegisterClass *SrcRC,
515 unsigned SrcSubReg) {
516 // Same register class.
517 if (DefRC == SrcRC)
518 return true;
519
520 // Both operands are sub registers. Check if they share a register class.
521 unsigned SrcIdx, DefIdx;
522 if (SrcSubReg && DefSubReg)
523 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
Craig Topperc0196b12014-04-14 00:51:57 +0000524 SrcIdx, DefIdx) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000525 // At most one of the register is a sub register, make it Src to avoid
526 // duplicating the test.
527 if (!SrcSubReg) {
528 std::swap(DefSubReg, SrcSubReg);
529 std::swap(DefRC, SrcRC);
530 }
531
532 // One of the register is a sub register, check if we can get a superclass.
533 if (SrcSubReg)
Craig Topperc0196b12014-04-14 00:51:57 +0000534 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000535 // Plain copy.
Craig Topperc0196b12014-04-14 00:51:57 +0000536 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000537}
538
Quentin Colombet03e43f82014-08-20 17:41:48 +0000539/// \brief Try to find the next source that share the same register file
540/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000541/// When true is returned, \p Reg and \p SubReg are updated with the
542/// register number and sub-register index of the new source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000543/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000544bool PeepholeOptimizer::findNextSource(unsigned &Reg, unsigned &SubReg) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000545 // Do not try to find a new source for a physical register.
546 // So far we do not have any motivating example for doing that.
547 // Thus, instead of maintaining untested code, we will revisit that if
548 // that changes at some point.
549 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000550 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000551
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000552 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
553 unsigned DefSubReg = SubReg;
554
555 unsigned Src;
556 unsigned SrcSubReg;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000557 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000558
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000559 // Follow the chain of copies until we reach the top of the use-def chain
560 // or find a more suitable source.
561 ValueTracker ValTracker(Reg, DefSubReg, *MRI, !DisableAdvCopyOpt, TII);
562 do {
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000563 unsigned CopySrcReg, CopySrcSubReg;
564 if (!ValTracker.getNextSource(CopySrcReg, CopySrcSubReg))
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000565 break;
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000566 Src = CopySrcReg;
567 SrcSubReg = CopySrcSubReg;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000568
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000569 // Do not extend the live-ranges of physical registers as they add
570 // constraints to the register allocator.
571 // Moreover, if we want to extend the live-range of a physical register,
572 // unlike SSA virtual register, we will have to check that they are not
573 // redefine before the related use.
574 if (TargetRegisterInfo::isPhysicalRegister(Src))
575 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000576
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000577 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000578
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000579 // If this source does not incur a cross register bank copy, use it.
580 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, DefSubReg, SrcRC,
581 SrcSubReg);
582 } while (!ShouldRewrite);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000583
584 // If we did not find a more suitable source, there is nothing to optimize.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000585 if (!ShouldRewrite || Src == Reg)
Quentin Colombetcf71c632013-09-13 18:26:31 +0000586 return false;
587
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000588 Reg = Src;
589 SubReg = SrcSubReg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000590 return true;
591}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000592
Quentin Colombet03e43f82014-08-20 17:41:48 +0000593namespace {
594/// \brief Helper class to rewrite the arguments of a copy-like instruction.
595class CopyRewriter {
596protected:
597 /// The copy-like instruction.
598 MachineInstr &CopyLike;
599 /// The index of the source being rewritten.
600 unsigned CurrentSrcIdx;
601
602public:
603 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
604
605 virtual ~CopyRewriter() {}
606
607 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
608 /// the related value that it affects (TrackReg, TrackSubReg).
609 /// A source is considered rewritable if its register class and the
610 /// register class of the related TrackReg may not be register
611 /// coalescer friendly. In other words, given a copy-like instruction
612 /// not all the arguments may be returned at rewritable source, since
613 /// some arguments are none to be register coalescer friendly.
614 ///
615 /// Each call of this method moves the current source to the next
616 /// rewritable source.
617 /// For instance, let CopyLike be the instruction to rewrite.
618 /// CopyLike has one definition and one source:
619 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
620 ///
621 /// The first call will give the first rewritable source, i.e.,
622 /// the only source this instruction has:
623 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
624 /// This source defines the whole definition, i.e.,
625 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
626 ///
627 /// The second and subsequent calls will return false, has there is only one
628 /// rewritable source.
629 ///
630 /// \return True if a rewritable source has been found, false otherwise.
631 /// The output arguments are valid if and only if true is returned.
632 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
633 unsigned &TrackReg,
634 unsigned &TrackSubReg) {
635 // If CurrentSrcIdx == 1, this means this function has already been
636 // called once. CopyLike has one defintiion and one argument, thus,
637 // there is nothing else to rewrite.
638 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
639 return false;
640 // This is the first call to getNextRewritableSource.
641 // Move the CurrentSrcIdx to remember that we made that call.
642 CurrentSrcIdx = 1;
643 // The rewritable source is the argument.
644 const MachineOperand &MOSrc = CopyLike.getOperand(1);
645 SrcReg = MOSrc.getReg();
646 SrcSubReg = MOSrc.getSubReg();
647 // What we track are the alternative sources of the definition.
648 const MachineOperand &MODef = CopyLike.getOperand(0);
649 TrackReg = MODef.getReg();
650 TrackSubReg = MODef.getSubReg();
651 return true;
652 }
653
654 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
655 /// if possible.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000656 /// \return True if the rewritting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000657 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
658 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
659 return false;
660 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
661 MOSrc.setReg(NewReg);
662 MOSrc.setSubReg(NewSubReg);
663 return true;
664 }
665};
666
667/// \brief Specialized rewriter for INSERT_SUBREG instruction.
668class InsertSubregRewriter : public CopyRewriter {
669public:
670 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
671 assert(MI.isInsertSubreg() && "Invalid instruction");
672 }
673
674 /// \brief See CopyRewriter::getNextRewritableSource.
675 /// Here CopyLike has the following form:
676 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
677 /// Src1 has the same register class has dst, hence, there is
678 /// nothing to rewrite.
679 /// Src2.src2SubIdx, may not be register coalescer friendly.
680 /// Therefore, the first call to this method returns:
681 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
682 /// (TrackReg, TrackSubReg) = (dst, subIdx).
683 ///
684 /// Subsequence calls will return false.
685 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
686 unsigned &TrackReg,
687 unsigned &TrackSubReg) override {
688 // If we already get the only source we can rewrite, return false.
689 if (CurrentSrcIdx == 2)
690 return false;
691 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
692 CurrentSrcIdx = 2;
693 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
694 SrcReg = MOInsertedReg.getReg();
695 SrcSubReg = MOInsertedReg.getSubReg();
696 const MachineOperand &MODef = CopyLike.getOperand(0);
697
698 // We want to track something that is compatible with the
699 // partial definition.
700 TrackReg = MODef.getReg();
701 if (MODef.getSubReg())
702 // Bails if we have to compose sub-register indices.
703 return false;
704 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
705 return true;
706 }
707 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
708 if (CurrentSrcIdx != 2)
709 return false;
710 // We are rewriting the inserted reg.
711 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
712 MO.setReg(NewReg);
713 MO.setSubReg(NewSubReg);
714 return true;
715 }
716};
717
718/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
719class ExtractSubregRewriter : public CopyRewriter {
720 const TargetInstrInfo &TII;
721
722public:
723 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
724 : CopyRewriter(MI), TII(TII) {
725 assert(MI.isExtractSubreg() && "Invalid instruction");
726 }
727
728 /// \brief See CopyRewriter::getNextRewritableSource.
729 /// Here CopyLike has the following form:
730 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
731 /// There is only one rewritable source: Src.subIdx,
732 /// which defines dst.dstSubIdx.
733 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
734 unsigned &TrackReg,
735 unsigned &TrackSubReg) override {
736 // If we already get the only source we can rewrite, return false.
737 if (CurrentSrcIdx == 1)
738 return false;
739 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
740 CurrentSrcIdx = 1;
741 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
742 SrcReg = MOExtractedReg.getReg();
743 // If we have to compose sub-register indices, bails out.
744 if (MOExtractedReg.getSubReg())
745 return false;
746
747 SrcSubReg = CopyLike.getOperand(2).getImm();
748
749 // We want to track something that is compatible with the definition.
750 const MachineOperand &MODef = CopyLike.getOperand(0);
751 TrackReg = MODef.getReg();
752 TrackSubReg = MODef.getSubReg();
753 return true;
754 }
755
756 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
757 // The only source we can rewrite is the input register.
758 if (CurrentSrcIdx != 1)
759 return false;
760
761 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
762
763 // If we find a source that does not require to extract something,
764 // rewrite the operation with a copy.
765 if (!NewSubReg) {
766 // Move the current index to an invalid position.
767 // We do not want another call to this method to be able
768 // to do any change.
769 CurrentSrcIdx = -1;
770 // Rewrite the operation as a COPY.
771 // Get rid of the sub-register index.
772 CopyLike.RemoveOperand(2);
773 // Morph the operation into a COPY.
774 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
775 return true;
776 }
777 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
778 return true;
779 }
780};
781
782/// \brief Specialized rewriter for REG_SEQUENCE instruction.
783class RegSequenceRewriter : public CopyRewriter {
784public:
785 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
786 assert(MI.isRegSequence() && "Invalid instruction");
787 }
788
789 /// \brief See CopyRewriter::getNextRewritableSource.
790 /// Here CopyLike has the following form:
791 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
792 /// Each call will return a different source, walking all the available
793 /// source.
794 ///
795 /// The first call returns:
796 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
797 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
798 ///
799 /// The second call returns:
800 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
801 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
802 ///
803 /// And so on, until all the sources have been traversed, then
804 /// it returns false.
805 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
806 unsigned &TrackReg,
807 unsigned &TrackSubReg) override {
808 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
809
810 // If this is the first call, move to the first argument.
811 if (CurrentSrcIdx == 0) {
812 CurrentSrcIdx = 1;
813 } else {
814 // Otherwise, move to the next argument and check that it is valid.
815 CurrentSrcIdx += 2;
816 if (CurrentSrcIdx >= CopyLike.getNumOperands())
817 return false;
818 }
819 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
820 SrcReg = MOInsertedReg.getReg();
821 // If we have to compose sub-register indices, bails out.
822 if ((SrcSubReg = MOInsertedReg.getSubReg()))
823 return false;
824
825 // We want to track something that is compatible with the related
826 // partial definition.
827 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
828
829 const MachineOperand &MODef = CopyLike.getOperand(0);
830 TrackReg = MODef.getReg();
831 // If we have to compose sub-registers, bails.
832 return MODef.getSubReg() == 0;
833 }
834
835 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
836 // We cannot rewrite out of bound operands.
837 // Moreover, rewritable sources are at odd positions.
838 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
839 return false;
840
841 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
842 MO.setReg(NewReg);
843 MO.setSubReg(NewSubReg);
844 return true;
845 }
846};
847} // End namespace.
848
849/// \brief Get the appropriated CopyRewriter for \p MI.
850/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
851/// if no rewriter works for \p MI.
852static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000853 const TargetInstrInfo &TII) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000854 switch (MI.getOpcode()) {
855 default:
856 return nullptr;
857 case TargetOpcode::COPY:
858 return new CopyRewriter(MI);
859 case TargetOpcode::INSERT_SUBREG:
860 return new InsertSubregRewriter(MI);
861 case TargetOpcode::EXTRACT_SUBREG:
862 return new ExtractSubregRewriter(MI, TII);
863 case TargetOpcode::REG_SEQUENCE:
864 return new RegSequenceRewriter(MI);
865 }
866 llvm_unreachable(nullptr);
867}
868
869/// \brief Optimize generic copy instructions to avoid cross
870/// register bank copy. The optimization looks through a chain of
871/// copies and tries to find a source that has a compatible register
872/// class.
873/// Two register classes are considered to be compatible if they share
874/// the same register bank.
875/// New copies issued by this optimization are register allocator
876/// friendly. This optimization does not remove any copy as it may
877/// overconstraint the register allocator, but replaces some operands
878/// when possible.
879/// \pre isCoalescableCopy(*MI) is true.
880/// \return True, when \p MI has been rewritten. False otherwise.
881bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
882 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
883 assert(MI->getDesc().getNumDefs() == 1 &&
884 "Coalescer can understand multiple defs?!");
885 const MachineOperand &MODef = MI->getOperand(0);
886 // Do not rewrite physical definitions.
887 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
888 return false;
889
890 bool Changed = false;
891 // Get the right rewriter for the current copy.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000892 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000893 // If none exists, bails out.
894 if (!CpyRewriter)
895 return false;
896 // Rewrite each rewritable source.
897 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
898 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
899 TrackSubReg)) {
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000900 unsigned NewSrc = TrackReg;
901 unsigned NewSubReg = TrackSubReg;
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000902 // Try to find a more suitable source.
903 // If we failed to do so, or get the actual source,
904 // move to the next source.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000905 if (!findNextSource(NewSrc, NewSubReg) || SrcReg == NewSrc)
Quentin Colombet03e43f82014-08-20 17:41:48 +0000906 continue;
907 // Rewrite source.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000908 if (CpyRewriter->RewriteCurrentSource(NewSrc, NewSubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +0000909 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000910 MRI->clearKillFlags(NewSrc);
Quentin Colombet6b363372014-08-21 21:34:06 +0000911 Changed = true;
912 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000913 }
914 // TODO: We could have a clean-up method to tidy the instruction.
915 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
916 // => v0 = COPY v1
917 // Currently we haven't seen motivating example for that and we
918 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +0000919 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000920 return Changed;
921}
922
923/// \brief Optimize copy-like instructions to create
924/// register coalescer friendly instruction.
925/// The optimization tries to kill-off the \p MI by looking
926/// through a chain of copies to find a source that has a compatible
927/// register class.
928/// If such a source is found, it replace \p MI by a generic COPY
929/// operation.
930/// \pre isUncoalescableCopy(*MI) is true.
931/// \return True, when \p MI has been optimized. In that case, \p MI has
932/// been removed from its parent.
933/// All COPY instructions created, are inserted in \p LocalMIs.
934bool PeepholeOptimizer::optimizeUncoalescableCopy(
935 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
936 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
937
938 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000939 SmallVector<
940 std::pair<TargetInstrInfo::RegSubRegPair, TargetInstrInfo::RegSubRegPair>,
941 4> RewritePairs;
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000942 for (const MachineOperand &MODef : MI->defs()) {
943 if (MODef.isDead())
944 // We can ignore those.
945 continue;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000946
947 // If a physical register is here, this is probably for a good reason.
948 // Do not rewrite that.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000949 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
Quentin Colombet03e43f82014-08-20 17:41:48 +0000950 return false;
951
952 // If we do not know how to rewrite this definition, there is no point
953 // in trying to kill this instruction.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000954 TargetInstrInfo::RegSubRegPair Def(MODef.getReg(), MODef.getSubReg());
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000955 TargetInstrInfo::RegSubRegPair Src = Def;
956 if (!findNextSource(Src.Reg, Src.SubReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +0000957 return false;
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000958 RewritePairs.push_back(std::make_pair(Def, Src));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000959 }
960 // The change is possible for all defs, do it.
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000961 for (const auto &PairDefSrc : RewritePairs) {
962 const auto &Def = PairDefSrc.first;
963 const auto &Src = PairDefSrc.second;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000964 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000965 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
966 "We do not rewrite physical registers");
967 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
968 unsigned NewVR = MRI->createVirtualRegister(DefRC);
969 MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
970 TII->get(TargetOpcode::COPY),
971 NewVR).addReg(Src.Reg, 0, Src.SubReg);
972 NewCopy->getOperand(0).setSubReg(Def.SubReg);
973 if (Def.SubReg)
974 NewCopy->getOperand(0).setIsUndef();
Bruno Cardoso Lopesbd68a092015-07-15 15:35:09 +0000975 LocalMIs.insert(NewCopy);
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +0000976 MRI->replaceRegWith(Def.Reg, NewVR);
977 MRI->clearKillFlags(NewVR);
978 // We extended the lifetime of Src.
979 // Clear the kill flags to account for that.
980 MRI->clearKillFlags(Src.Reg);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000981 }
982 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +0000983 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +0000984 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000985 return true;
986}
987
Manman Ren5759d012012-08-02 00:56:42 +0000988/// isLoadFoldable - Check whether MI is a candidate for folding into a later
989/// instruction. We only fold loads to virtual registers and the virtual
990/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +0000991bool PeepholeOptimizer::isLoadFoldable(
992 MachineInstr *MI,
993 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +0000994 if (!MI->canFoldAsLoad() || !MI->mayLoad())
995 return false;
996 const MCInstrDesc &MCID = MI->getDesc();
997 if (MCID.getNumDefs() != 1)
998 return false;
999
1000 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001001 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001002 // loads. It should be checked when processing uses of the load, since
1003 // uses can be removed during peephole.
1004 if (!MI->getOperand(0).getSubReg() &&
1005 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001006 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001007 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001008 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001009 }
1010 return false;
1011}
1012
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001013bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1014 SmallSet<unsigned, 4> &ImmDefRegs,
1015 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001016 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001017 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001018 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001019 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001020 return false;
1021 unsigned Reg = MI->getOperand(0).getReg();
1022 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1023 ImmDefMIs.insert(std::make_pair(Reg, MI));
1024 ImmDefRegs.insert(Reg);
1025 return true;
1026 }
Andrew Trick9e761992012-02-08 21:22:43 +00001027
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001028 return false;
1029}
1030
Jim Grosbachedcb8682012-05-01 23:21:41 +00001031/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001032/// immediate instructions, i.e. a trivial constant folding optimization, if
1033/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001034bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001035 SmallSet<unsigned, 4> &ImmDefRegs,
1036 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1037 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1038 MachineOperand &MO = MI->getOperand(i);
1039 if (!MO.isReg() || MO.isDef())
1040 continue;
1041 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001042 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001043 continue;
1044 if (ImmDefRegs.count(Reg) == 0)
1045 continue;
1046 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1047 assert(II != ImmDefMIs.end());
1048 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1049 ++NumImmFold;
1050 return true;
1051 }
1052 }
1053 return false;
1054}
1055
Eric Christopher2181fb22014-10-15 21:06:25 +00001056bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1057 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001058 return false;
1059
Craig Topper588ceec2012-12-17 03:56:00 +00001060 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001061 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001062
Evan Cheng2ce016c2010-11-15 21:20:45 +00001063 if (DisablePeephole)
1064 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001065
Eric Christopher2181fb22014-10-15 21:06:25 +00001066 TII = MF.getSubtarget().getInstrInfo();
1067 TRI = MF.getSubtarget().getRegisterInfo();
1068 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001069 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001070
1071 bool Changed = false;
1072
Eric Christopher2181fb22014-10-15 21:06:25 +00001073 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001074 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001075
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001076 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001077
1078 // During this forward scan, at some point it needs to answer the question
1079 // "given a pointer to an MI in the current BB, is it located before or
1080 // after the current instruction".
1081 // To perform this, the following set keeps track of the MIs already seen
1082 // during the scan, if a MI is not in the set, it is assumed to be located
1083 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001084 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001085 SmallSet<unsigned, 4> ImmDefRegs;
1086 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1087 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001088
1089 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001090 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001091 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001092 // We may be erasing MI below, increment MII now.
1093 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001094 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001095
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001096 // Skip debug values. They should not affect this peephole optimization.
1097 if (MI->isDebugValue())
1098 continue;
1099
Manman Ren5759d012012-08-02 00:56:42 +00001100 // If there exists an instruction which belongs to the following
Lang Hames5dc14bd2014-04-02 22:59:58 +00001101 // categories, we will discard the load candidates.
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001102 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001103 MI->isKill() || MI->isInlineAsm() ||
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001104 MI->hasUnmodeledSideEffects()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001105 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001106 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001107 }
Manman Ren5759d012012-08-02 00:56:42 +00001108 if (MI->mayStore() || MI->isCall())
Lang Hames5dc14bd2014-04-02 22:59:58 +00001109 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001110
Quentin Colombet03e43f82014-08-20 17:41:48 +00001111 if ((isUncoalescableCopy(*MI) &&
1112 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001113 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001114 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001115 // MI is deleted.
1116 LocalMIs.erase(MI);
1117 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001118 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001119 }
1120
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001121 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1122 Changed = true;
1123 continue;
1124 }
1125
Quentin Colombet03e43f82014-08-20 17:41:48 +00001126 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1127 // MI is just rewritten.
1128 Changed = true;
1129 continue;
1130 }
1131
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001132 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001133 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001134 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001135 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001136 // optimizeExtInstr might have created new instructions after MI
1137 // and before the already incremented MII. Adjust MII so that the
1138 // next iteration sees the new instructions.
1139 MII = MI;
1140 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001141 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001142 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001143 }
Evan Cheng98196b42011-02-15 05:00:24 +00001144
Manman Ren5759d012012-08-02 00:56:42 +00001145 // Check whether MI is a load candidate for folding into a later
1146 // instruction. If MI is not a candidate, check whether we can fold an
1147 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001148 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1149 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001150 const MCInstrDesc &MIDesc = MI->getDesc();
1151 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1152 ++i) {
1153 const MachineOperand &MOp = MI->getOperand(i);
1154 if (!MOp.isReg())
1155 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001156 unsigned FoldAsLoadDefReg = MOp.getReg();
1157 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1158 // We need to fold load after optimizeCmpInstr, since
1159 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1160 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1161 // we need it for markUsesInDebugValueAsUndef().
1162 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001163 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001164 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1165 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001166 DefMI);
1167 if (FoldMI) {
1168 // Update LocalMIs since we replaced MI with FoldMI and deleted
1169 // DefMI.
1170 DEBUG(dbgs() << "Replacing: " << *MI);
1171 DEBUG(dbgs() << " With: " << *FoldMI);
1172 LocalMIs.erase(MI);
1173 LocalMIs.erase(DefMI);
1174 LocalMIs.insert(FoldMI);
1175 MI->eraseFromParent();
1176 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001177 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1178 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001179 ++NumLoadFold;
1180 // MI is replaced with FoldMI.
1181 Changed = true;
1182 break;
1183 }
1184 }
Manman Ren5759d012012-08-02 00:56:42 +00001185 }
1186 }
Bill Wendlingca678352010-08-09 23:59:04 +00001187 }
1188 }
1189
1190 return Changed;
1191}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001192
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001193bool ValueTracker::getNextSourceFromCopy(unsigned &SrcReg,
1194 unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001195 assert(Def->isCopy() && "Invalid definition");
1196 // Copy instruction are supposed to be: Def = Src.
1197 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001198 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001199
1200 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1201 // If we look for a different subreg, it means we want a subreg of src.
1202 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001203 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001204 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001205 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001206 SrcReg = Src.getReg();
1207 SrcSubReg = Src.getSubReg();
1208 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001209}
1210
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001211bool ValueTracker::getNextSourceFromBitcast(unsigned &SrcReg,
1212 unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001213 assert(Def->isBitcast() && "Invalid definition");
1214
1215 // Bail if there are effects that a plain copy will not expose.
1216 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001217 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001218
1219 // Bitcasts with more than one def are not supported.
1220 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001221 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001222 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1223 // If we look for a different subreg, it means we want a subreg of the src.
1224 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001225 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001226
Quentin Colombet03e43f82014-08-20 17:41:48 +00001227 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001228 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1229 ++OpIdx) {
1230 const MachineOperand &MO = Def->getOperand(OpIdx);
1231 if (!MO.isReg() || !MO.getReg())
1232 continue;
1233 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1234 if (SrcIdx != EndOpIdx)
1235 // Multiple sources?
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001236 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001237 SrcIdx = OpIdx;
1238 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001239 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001240 SrcReg = Src.getReg();
1241 SrcSubReg = Src.getSubReg();
1242 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001243}
1244
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001245bool ValueTracker::getNextSourceFromRegSequence(unsigned &SrcReg,
1246 unsigned &SrcSubReg) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001247 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1248 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001249
1250 if (Def->getOperand(DefIdx).getSubReg())
1251 // If we are composing subreg, bails out.
1252 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1253 // This should almost never happen as the SSA property is tracked at
1254 // the register level (as opposed to the subreg level).
1255 // I.e.,
1256 // Def.sub0 =
1257 // Def.sub1 =
1258 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1259 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001260 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001261 // Def.sub0 (i.e, not defining the other subregs) and we would
1262 // have this case.
1263 // If we can ascertain (or force) that this never happens, we could
1264 // turn that into an assertion.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001265 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001266
Quentin Colombet03e43f82014-08-20 17:41:48 +00001267 if (!TII)
1268 // We could handle the REG_SEQUENCE here, but we do not want to
1269 // duplicate the code from the generic TII.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001270 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001271
1272 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1273 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001274 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001275
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001276 // We are looking at:
1277 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1278 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001279 for (auto &RegSeqInput : RegSeqInputRegs) {
1280 if (RegSeqInput.SubIdx == DefSubReg) {
1281 if (RegSeqInput.SubReg)
1282 // Bails if we have to compose sub registers.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001283 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001284
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001285 SrcReg = RegSeqInput.Reg;
1286 SrcSubReg = RegSeqInput.SubReg;
1287 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001288 }
1289 }
1290
1291 // If the subreg we are tracking is super-defined by another subreg,
1292 // we could follow this value. However, this would require to compose
1293 // the subreg and we do not do that for now.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001294 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001295}
1296
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001297bool ValueTracker::getNextSourceFromInsertSubreg(unsigned &SrcReg,
1298 unsigned &SrcSubReg) {
Quentin Colombet68962302014-08-21 00:19:16 +00001299 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1300 "Invalid definition");
1301
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001302 if (Def->getOperand(DefIdx).getSubReg())
1303 // If we are composing subreg, bails out.
1304 // Same remark as getNextSourceFromRegSequence.
1305 // I.e., this may be turned into an assert.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001306 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001307
Quentin Colombet68962302014-08-21 00:19:16 +00001308 if (!TII)
1309 // We could handle the REG_SEQUENCE here, but we do not want to
1310 // duplicate the code from the generic TII.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001311 return false;
Quentin Colombet68962302014-08-21 00:19:16 +00001312
Quentin Colombet03e43f82014-08-20 17:41:48 +00001313 TargetInstrInfo::RegSubRegPair BaseReg;
1314 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001315 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001316 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001317
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001318 // We are looking at:
1319 // Def = INSERT_SUBREG v0, v1, sub1
1320 // There are two cases:
1321 // 1. DefSubReg == sub1, get v1.
1322 // 2. DefSubReg != sub1, the value may be available through v0.
1323
Quentin Colombet03e43f82014-08-20 17:41:48 +00001324 // #1 Check if the inserted register matches the required sub index.
1325 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001326 SrcReg = InsertedReg.Reg;
1327 SrcSubReg = InsertedReg.SubReg;
1328 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001329 }
1330 // #2 Otherwise, if the sub register we are looking for is not partial
1331 // defined by the inserted element, we can look through the main
1332 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001333 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001334 // If the result register (Def) and the base register (v0) do not
1335 // have the same register class or if we have to compose
1336 // subregisters, bails out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001337 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1338 BaseReg.SubReg)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001339 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001340
Quentin Colombet03e43f82014-08-20 17:41:48 +00001341 // Get the TRI and check if the inserted sub-register overlaps with the
1342 // sub-register we are tracking.
1343 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001344 if (!TRI ||
1345 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001346 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001347 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001348 // At this point, the value is available in v0 via the same subreg
1349 // we used for Def.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001350 SrcReg = BaseReg.Reg;
1351 SrcSubReg = DefSubReg;
1352 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001353}
1354
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001355bool ValueTracker::getNextSourceFromExtractSubreg(unsigned &SrcReg,
1356 unsigned &SrcSubReg) {
Quentin Colombet67639df2014-08-20 23:13:02 +00001357 assert((Def->isExtractSubreg() ||
1358 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001359 // We are looking at:
1360 // Def = EXTRACT_SUBREG v0, sub0
1361
1362 // Bails if we have to compose sub registers.
1363 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1364 if (DefSubReg)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001365 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001366
Quentin Colombet67639df2014-08-20 23:13:02 +00001367 if (!TII)
1368 // We could handle the EXTRACT_SUBREG here, but we do not want to
1369 // duplicate the code from the generic TII.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001370 return false;
Quentin Colombet67639df2014-08-20 23:13:02 +00001371
Quentin Colombet03e43f82014-08-20 17:41:48 +00001372 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001373 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001374 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001375
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001376 // Bails if we have to compose sub registers.
1377 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001378 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001379 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001380 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001381 SrcReg = ExtractSubregInputReg.Reg;
1382 SrcSubReg = ExtractSubregInputReg.SubIdx;
1383 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001384}
1385
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001386bool ValueTracker::getNextSourceFromSubregToReg(unsigned &SrcReg,
1387 unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001388 assert(Def->isSubregToReg() && "Invalid definition");
1389 // We are looking at:
1390 // Def = SUBREG_TO_REG Imm, v0, sub0
1391
1392 // Bails if we have to compose sub registers.
1393 // If DefSubReg != sub0, we would have to check that all the bits
1394 // we track are included in sub0 and if yes, we would have to
1395 // determine the right subreg in v0.
1396 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001397 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001398 // Bails if we have to compose sub registers.
1399 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1400 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001401 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001402
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001403 SrcReg = Def->getOperand(2).getReg();
1404 SrcSubReg = Def->getOperand(3).getImm();
1405 return true;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001406}
1407
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001408bool ValueTracker::getNextSourceImpl(unsigned &SrcReg, unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001409 assert(Def && "This method needs a valid definition");
1410
1411 assert(
1412 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1413 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1414 if (Def->isCopy())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001415 return getNextSourceFromCopy(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001416 if (Def->isBitcast())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001417 return getNextSourceFromBitcast(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001418 // All the remaining cases involve "complex" instructions.
1419 // Bails if we did not ask for the advanced tracking.
1420 if (!UseAdvancedTracking)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001421 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001422 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001423 return getNextSourceFromRegSequence(SrcReg, SrcSubReg);
Quentin Colombet68962302014-08-21 00:19:16 +00001424 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001425 return getNextSourceFromInsertSubreg(SrcReg, SrcSubReg);
Quentin Colombet67639df2014-08-20 23:13:02 +00001426 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001427 return getNextSourceFromExtractSubreg(SrcReg, SrcSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001428 if (Def->isSubregToReg())
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001429 return getNextSourceFromSubregToReg(SrcReg, SrcSubReg);
1430 return false;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001431}
1432
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001433const MachineInstr *ValueTracker::getNextSource(unsigned &SrcReg,
1434 unsigned &SrcSubReg) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001435 // If we reach a point where we cannot move up in the use-def chain,
1436 // there is nothing we can get.
1437 if (!Def)
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001438 return nullptr;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001439
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001440 const MachineInstr *PrevDef = nullptr;
1441 // Try to find the next source.
1442 if (getNextSourceImpl(SrcReg, SrcSubReg)) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001443 // Update definition, definition index, and subregister for the
1444 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001445 // Update the current register.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001446 Reg = SrcReg;
1447 // Update the return value before moving up in the use-def chain.
1448 PrevDef = Def;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001449 // If we can still move up in the use-def chain, move to the next
1450 // defintion.
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001451 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001452 Def = MRI.getVRegDef(Reg);
1453 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001454 DefSubReg = SrcSubReg;
1455 return PrevDef;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001456 }
1457 }
1458 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001459 // for the next iteration.
1460 // Make sure any new call to getNextSource bails out early by cutting the
1461 // use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001462 Def = nullptr;
Bruno Cardoso Lopes9b396932015-07-15 18:10:46 +00001463 return PrevDef;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001464}