blob: 92daaf7a9b0d750002ebd5d6019e0fc78d47ebec [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
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000101// Limit the number of PHI instructions to process
102// in PeepholeOptimizer::getNextSource.
103static cl::opt<unsigned> RewritePHILimit(
104 "rewrite-phi-limit", cl::Hidden, cl::init(10),
105 cl::desc("Limit the length of PHI chains to lookup"));
106
Bill Wendling66284312010-08-27 20:39:09 +0000107STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000108STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000109STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000110STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000111STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000112STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
113STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
Bill Wendlingca678352010-08-09 23:59:04 +0000114
115namespace {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000116 class ValueTrackerResult;
117
Bill Wendlingca678352010-08-09 23:59:04 +0000118 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000119 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000120 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000121 MachineRegisterInfo *MRI;
122 MachineDominatorTree *DT; // Machine dominator tree
123
124 public:
125 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000126 PeepholeOptimizer() : MachineFunctionPass(ID) {
127 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
128 }
Bill Wendlingca678352010-08-09 23:59:04 +0000129
Craig Topper4584cd52014-03-07 09:26:03 +0000130 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000131
Craig Topper4584cd52014-03-07 09:26:03 +0000132 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000133 AU.setPreservesCFG();
134 MachineFunctionPass::getAnalysisUsage(AU);
135 if (Aggressive) {
136 AU.addRequired<MachineDominatorTree>();
137 AU.addPreserved<MachineDominatorTree>();
138 }
139 }
140
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000141 /// \brief Track Def -> Use info used for rewriting copies.
142 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
143 RewriteMapTy;
144
Bill Wendlingca678352010-08-09 23:59:04 +0000145 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000146 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
147 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000148 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000149 bool optimizeSelect(MachineInstr *MI,
150 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000151 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000152 bool optimizeCopyOrBitcast(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000153 bool optimizeCoalescableCopy(MachineInstr *MI);
154 bool optimizeUncoalescableCopy(MachineInstr *MI,
155 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000156 bool findNextSource(unsigned Reg, unsigned SubReg,
157 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000158 bool isMoveImmediate(MachineInstr *MI,
159 SmallSet<unsigned, 4> &ImmDefRegs,
160 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000161 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000162 SmallSet<unsigned, 4> &ImmDefRegs,
163 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Lang Hames5dc14bd2014-04-02 22:59:58 +0000164 bool isLoadFoldable(MachineInstr *MI,
165 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000166
167 /// \brief Check whether \p MI is understood by the register coalescer
168 /// but may require some rewriting.
169 bool isCoalescableCopy(const MachineInstr &MI) {
170 // SubregToRegs are not interesting, because they are already register
171 // coalescer friendly.
172 return MI.isCopy() || (!DisableAdvCopyOpt &&
173 (MI.isRegSequence() || MI.isInsertSubreg() ||
174 MI.isExtractSubreg()));
175 }
176
177 /// \brief Check whether \p MI is a copy like instruction that is
178 /// not recognized by the register coalescer.
179 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000180 return MI.isBitcast() ||
181 (!DisableAdvCopyOpt &&
182 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
183 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000184 }
Bill Wendlingca678352010-08-09 23:59:04 +0000185 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000186
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000187 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
188 /// returned sources for a given search and the instructions where the sources
189 /// were tracked from.
190 class ValueTrackerResult {
191 private:
192 /// Track all sources found by one ValueTracker query.
193 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
194
195 /// Instruction using the sources in 'RegSrcs'.
196 const MachineInstr *Inst;
197
198 public:
199 ValueTrackerResult() : Inst(nullptr) {}
200 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
201 addSource(Reg, SubReg);
202 }
203
204 bool isValid() const { return getNumSources() > 0; }
205
206 void setInst(const MachineInstr *I) { Inst = I; }
207 const MachineInstr *getInst() const { return Inst; }
208
209 void clear() {
210 RegSrcs.clear();
211 Inst = nullptr;
212 }
213
214 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
215 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
216 }
217
218 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
219 assert(Idx < getNumSources() && "Reg pair source out of index");
220 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
221 }
222
223 int getNumSources() const { return RegSrcs.size(); }
224
225 unsigned getSrcReg(int Idx) const {
226 assert(Idx < getNumSources() && "Reg source out of index");
227 return RegSrcs[Idx].Reg;
228 }
229
230 unsigned getSrcSubReg(int Idx) const {
231 assert(Idx < getNumSources() && "SubReg source out of index");
232 return RegSrcs[Idx].SubReg;
233 }
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000234
235 bool operator==(const ValueTrackerResult &Other) {
236 if (Other.getInst() != getInst())
237 return false;
238
239 if (Other.getNumSources() != getNumSources())
240 return false;
241
242 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
243 if (Other.getSrcReg(i) != getSrcReg(i) ||
244 Other.getSrcSubReg(i) != getSrcSubReg(i))
245 return false;
246 return true;
247 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000248 };
249
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000250 /// \brief Helper class to track the possible sources of a value defined by
251 /// a (chain of) copy related instructions.
252 /// Given a definition (instruction and definition index), this class
253 /// follows the use-def chain to find successive suitable sources.
254 /// The given source can be used to rewrite the definition into
255 /// def = COPY src.
256 ///
257 /// For instance, let us consider the following snippet:
258 /// v0 =
259 /// v2 = INSERT_SUBREG v1, v0, sub0
260 /// def = COPY v2.sub0
261 ///
262 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
263 /// suitable sources:
264 /// v2.sub0 and v0.
265 /// Then, def can be rewritten into def = COPY v0.
266 class ValueTracker {
267 private:
268 /// The current point into the use-def chain.
269 const MachineInstr *Def;
270 /// The index of the definition in Def.
271 unsigned DefIdx;
272 /// The sub register index of the definition.
273 unsigned DefSubReg;
274 /// The register where the value can be found.
275 unsigned Reg;
276 /// Specifiy whether or not the value tracking looks through
277 /// complex instructions. When this is false, the value tracker
278 /// bails on everything that is not a copy or a bitcast.
279 ///
280 /// Note: This could have been implemented as a specialized version of
281 /// the ValueTracker class but that would have complicated the code of
282 /// the users of this class.
283 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000284 /// MachineRegisterInfo used to perform tracking.
285 const MachineRegisterInfo &MRI;
286 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000287 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000288 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000289
290 /// \brief Dispatcher to the right underlying implementation of
291 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000292 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000293 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000294 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000295 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000296 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000297 /// \brief Specialized version of getNextSource for RegSequence
298 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000299 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000300 /// \brief Specialized version of getNextSource for InsertSubreg
301 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000302 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000303 /// \brief Specialized version of getNextSource for ExtractSubreg
304 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000305 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000306 /// \brief Specialized version of getNextSource for SubregToReg
307 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000308 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000309 /// \brief Specialized version of getNextSource for PHI instructions.
310 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000311
312 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000313 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000314 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000315 /// track. It does not need to match the sub register index used in the
316 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000317 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
318 /// through complex instructions. By default (false), it handles only copy
319 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000320 /// If \p Reg is a physical register, a value tracker constructed with
321 /// this constructor will not find any alternative source.
322 /// Indeed, when \p Reg is a physical register that constructor does not
323 /// know which definition of \p Reg it should track.
324 /// Use the next constructor to track a physical register.
325 ValueTracker(unsigned Reg, unsigned DefSubReg,
326 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000327 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000328 const TargetInstrInfo *TII = nullptr)
329 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
330 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
331 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
332 Def = MRI.getVRegDef(Reg);
333 DefIdx = MRI.def_begin(Reg).getOperandNo();
334 }
335 }
336
337 /// \brief Create a ValueTracker instance for the value defined by
338 /// the pair \p MI, \p DefIdx.
339 /// Unlike the other constructor, the value tracker produced by this one
340 /// may be able to find a new source when the definition is a physical
341 /// register.
342 /// This could be useful to rewrite target specific instructions into
343 /// generic copy instructions.
344 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
345 const MachineRegisterInfo &MRI,
346 bool UseAdvancedTracking = false,
347 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000348 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000349 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
350 assert(DefIdx < Def->getDesc().getNumDefs() &&
351 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000352 Reg = Def->getOperand(DefIdx).getReg();
353 }
354
355 /// \brief Following the use-def chain, get the next available source
356 /// for the tracked value.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000357 /// \return A ValueTrackerResult containing the a set of registers
358 /// and sub registers with tracked values. A ValueTrackerResult with
359 /// an empty set of registers means no source was found.
360 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000361
362 /// \brief Get the last register where the initial value can be found.
363 /// Initially this is the register of the definition.
364 /// Then, after each successful call to getNextSource, this is the
365 /// register of the last source.
366 unsigned getReg() const { return Reg; }
367 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000368}
Bill Wendlingca678352010-08-09 23:59:04 +0000369
370char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000371char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000372INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
373 "Peephole Optimizations", false, false)
374INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
375INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000376 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000377
Jim Grosbachedcb8682012-05-01 23:21:41 +0000378/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000379/// a single register and writes a single register and it does not modify the
380/// source, and if the source value is preserved as a sub-register of the
381/// result, then replace all reachable uses of the source with the subreg of the
382/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000383///
Bill Wendlingca678352010-08-09 23:59:04 +0000384/// Do not generate an EXTRACT that is used only in a debug use, as this changes
385/// the code. Since this code does not currently share EXTRACTs, just ignore all
386/// debug uses.
387bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000388optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000389 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000390 unsigned SrcReg, DstReg, SubIdx;
391 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
392 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000393
Bill Wendlingca678352010-08-09 23:59:04 +0000394 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
395 TargetRegisterInfo::isPhysicalRegister(SrcReg))
396 return false;
397
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000398 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000399 // No other uses.
400 return false;
401
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000402 // Ensure DstReg can get a register class that actually supports
403 // sub-registers. Don't change the class until we commit.
404 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000405 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000406 if (!DstRC)
407 return false;
408
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000409 // The ext instr may be operating on a sub-register of SrcReg as well.
410 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
411 // register.
412 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
413 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000414 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000415 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000416
Bill Wendlingca678352010-08-09 23:59:04 +0000417 // The source has other uses. See if we can replace the other uses with use of
418 // the result of the extension.
419 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000420 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
421 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000422
423 // Uses that are in the same BB of uses of the result of the instruction.
424 SmallVector<MachineOperand*, 8> Uses;
425
426 // Uses that the result of the instruction can reach.
427 SmallVector<MachineOperand*, 8> ExtendedUses;
428
429 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000430 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000431 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000432 if (UseMI == MI)
433 continue;
434
435 if (UseMI->isPHI()) {
436 ExtendLife = false;
437 continue;
438 }
439
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000440 // Only accept uses of SrcReg:SubIdx.
441 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
442 continue;
443
Bill Wendlingca678352010-08-09 23:59:04 +0000444 // It's an error to translate this:
445 //
446 // %reg1025 = <sext> %reg1024
447 // ...
448 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
449 //
450 // into this:
451 //
452 // %reg1025 = <sext> %reg1024
453 // ...
454 // %reg1027 = COPY %reg1025:4
455 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
456 //
457 // The problem here is that SUBREG_TO_REG is there to assert that an
458 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
459 // the COPY here, it will give us the value after the <sext>, not the
460 // original value of %reg1024 before <sext>.
461 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
462 continue;
463
464 MachineBasicBlock *UseMBB = UseMI->getParent();
465 if (UseMBB == MBB) {
466 // Local uses that come after the extension.
467 if (!LocalMIs.count(UseMI))
468 Uses.push_back(&UseMO);
469 } else if (ReachedBBs.count(UseMBB)) {
470 // Non-local uses where the result of the extension is used. Always
471 // replace these unless it's a PHI.
472 Uses.push_back(&UseMO);
473 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
474 // We may want to extend the live range of the extension result in order
475 // to replace these uses.
476 ExtendedUses.push_back(&UseMO);
477 } else {
478 // Both will be live out of the def MBB anyway. Don't extend live range of
479 // the extension result.
480 ExtendLife = false;
481 break;
482 }
483 }
484
485 if (ExtendLife && !ExtendedUses.empty())
486 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000487 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000488
489 // Now replace all uses.
490 bool Changed = false;
491 if (!Uses.empty()) {
492 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
493
494 // Look for PHI uses of the extended result, we don't want to extend the
495 // liveness of a PHI input. It breaks all kinds of assumptions down
496 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000497 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
498 if (UI.isPHI())
499 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000500
501 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
502 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
503 MachineOperand *UseMO = Uses[i];
504 MachineInstr *UseMI = UseMO->getParent();
505 MachineBasicBlock *UseMBB = UseMI->getParent();
506 if (PHIBBs.count(UseMBB))
507 continue;
508
Lang Hamesd5862ce2012-02-25 02:01:00 +0000509 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000510 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000511 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000512 MRI->constrainRegClass(DstReg, DstRC);
513 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000514
Bill Wendlingca678352010-08-09 23:59:04 +0000515 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000516 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
517 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000518 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000519 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
520 if (UseSrcSubIdx) {
521 Copy->getOperand(0).setSubReg(SubIdx);
522 Copy->getOperand(0).setIsUndef();
523 }
Bill Wendlingca678352010-08-09 23:59:04 +0000524 UseMO->setReg(NewVR);
525 ++NumReuse;
526 Changed = true;
527 }
528 }
529
530 return Changed;
531}
532
Jim Grosbachedcb8682012-05-01 23:21:41 +0000533/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000534/// instruction it's comparing against all ready sets (or could be modified to
535/// set) the same flag as the compare, then we can remove the comparison and use
536/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000537bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000538 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000539 // If this instruction is a comparison against zero and isn't comparing a
540 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000541 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000542 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000543 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
544 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
545 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000546 return false;
547
Bill Wendling27dddd12010-09-11 00:13:50 +0000548 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000549 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000550 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000551 return true;
552 }
553
554 return false;
555}
556
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000557/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000558bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
559 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000560 unsigned TrueOp = 0;
561 unsigned FalseOp = 0;
562 bool Optimizable = false;
563 SmallVector<MachineOperand, 4> Cond;
564 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
565 return false;
566 if (!Optimizable)
567 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000568 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000569 return false;
570 MI->eraseFromParent();
571 ++NumSelects;
572 return true;
573}
574
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000575/// \brief Check if a simpler conditional branch can be
576// generated
577bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
578 return TII->optimizeCondBranch(MI);
579}
580
Quentin Colombetcf71c632013-09-13 18:26:31 +0000581/// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
582/// share the same register file.
583static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
584 const TargetRegisterClass *DefRC,
585 unsigned DefSubReg,
586 const TargetRegisterClass *SrcRC,
587 unsigned SrcSubReg) {
588 // Same register class.
589 if (DefRC == SrcRC)
590 return true;
591
592 // Both operands are sub registers. Check if they share a register class.
593 unsigned SrcIdx, DefIdx;
594 if (SrcSubReg && DefSubReg)
595 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
Craig Topperc0196b12014-04-14 00:51:57 +0000596 SrcIdx, DefIdx) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000597 // At most one of the register is a sub register, make it Src to avoid
598 // duplicating the test.
599 if (!SrcSubReg) {
600 std::swap(DefSubReg, SrcSubReg);
601 std::swap(DefRC, SrcRC);
602 }
603
604 // One of the register is a sub register, check if we can get a superclass.
605 if (SrcSubReg)
Craig Topperc0196b12014-04-14 00:51:57 +0000606 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000607 // Plain copy.
Craig Topperc0196b12014-04-14 00:51:57 +0000608 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000609}
610
Quentin Colombet03e43f82014-08-20 17:41:48 +0000611/// \brief Try to find the next source that share the same register file
612/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000613/// When true is returned, the \p RewriteMap can be used by the client to
614/// retrieve all Def -> Use along the way up to the next source. Any found
615/// Use that is not itself a key for another entry, is the next source to
616/// use. During the search for the next source, multiple sources can be found
617/// given multiple incoming sources of a PHI instruction. In this case, we
618/// look in each PHI source for the next source; all found next sources must
619/// share the same register file as \p Reg and \p SubReg. The client should
620/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000621/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000622bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
623 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000624 // Do not try to find a new source for a physical register.
625 // So far we do not have any motivating example for doing that.
626 // Thus, instead of maintaining untested code, we will revisit that if
627 // that changes at some point.
628 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000629 return false;
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000630 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopesad61f342015-07-15 18:10:35 +0000631
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000632 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
633 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
634 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000635 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000636
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000637 unsigned PHILimit = RewritePHILimit;
638 while (!SrcToLook.empty() && PHILimit) {
639 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
640 // As explained above, do not handle physical registers
641 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
642 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000643
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000644 CurSrcPair = Pair;
645 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
646 !DisableAdvCopyOpt, TII);
647 ValueTrackerResult Res;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000648
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000649 do {
650 // Follow the chain of copies until we reach the top of the use-def chain
651 // or find a more suitable source.
652 Res = ValTracker.getNextSource();
653 if (!Res.isValid())
654 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000655
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000656 // Insert the Def -> Use entry for the recently found source.
657 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
658 if (CurSrcRes.isValid()) {
659 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
660 // An existent entry with multiple sources is a PHI cycle we must avoid.
661 // Otherwise it's an entry with a valid next source we already found.
662 if (CurSrcRes.getNumSources() > 1) {
663 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
664 return false;
665 }
666 break;
667 }
668 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
669
670 // ValueTrackerResult usually have one source unless it's the result from
671 // a PHI instruction. Add the found PHI edges to be looked up further.
672 unsigned NumSrcs = Res.getNumSources();
673 if (NumSrcs > 1) {
674 PHILimit--;
675 for (unsigned i = 0; i < NumSrcs; ++i)
676 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
677 Res.getSrcReg(i), Res.getSrcSubReg(i)));
678 break;
679 }
680
681 CurSrcPair.Reg = Res.getSrcReg(0);
682 CurSrcPair.SubReg = Res.getSrcSubReg(0);
683 // Do not extend the live-ranges of physical registers as they add
684 // constraints to the register allocator. Moreover, if we want to extend
685 // the live-range of a physical register, unlike SSA virtual register,
686 // we will have to check that they aren't redefine before the related use.
687 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
688 return false;
689
690 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
691
692 // If this source does not incur a cross register bank copy, use it.
693 ShouldRewrite = shareSameRegisterFile(*TRI, DefRC, SubReg, SrcRC,
694 CurSrcPair.SubReg);
695 } while (!ShouldRewrite);
696
697 // Continue looking for new sources...
698 if (Res.isValid())
699 continue;
700
701 if (!PHILimit) {
702 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
703 return false;
704 }
705
706 // Do not continue searching for a new source if the there's at least
707 // one use-def which cannot be rewritten.
708 if (!ShouldRewrite)
709 return false;
710 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000711
712 // If we did not find a more suitable source, there is nothing to optimize.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000713 if (CurSrcPair.Reg == Reg)
Quentin Colombetcf71c632013-09-13 18:26:31 +0000714 return false;
715
Quentin Colombet03e43f82014-08-20 17:41:48 +0000716 return true;
717}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000718
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000719/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
720/// guaranteed to have the same register class. This is necessary whenever we
721/// successfully traverse a PHI instruction and find suitable sources coming
722/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
723/// suitable to be used in a new COPY instruction.
724MachineInstr *
725insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
726 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
727 MachineInstr *OrigPHI) {
728 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
729
730 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
731 unsigned NewVR = MRI->createVirtualRegister(NewRC);
732 MachineBasicBlock *MBB = OrigPHI->getParent();
733 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
734 TII->get(TargetOpcode::PHI), NewVR);
735
736 unsigned MBBOpIdx = 2;
737 for (auto RegPair : SrcRegs) {
738 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
739 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
740 // Since we're extended the lifetime of RegPair.Reg, clear the
741 // kill flags to account for that and make RegPair.Reg reaches
742 // the new PHI.
743 MRI->clearKillFlags(RegPair.Reg);
744 MBBOpIdx += 2;
745 }
746
747 return MIB;
748}
749
Quentin Colombet03e43f82014-08-20 17:41:48 +0000750namespace {
751/// \brief Helper class to rewrite the arguments of a copy-like instruction.
752class CopyRewriter {
753protected:
754 /// The copy-like instruction.
755 MachineInstr &CopyLike;
756 /// The index of the source being rewritten.
757 unsigned CurrentSrcIdx;
758
759public:
760 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
761
762 virtual ~CopyRewriter() {}
763
764 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
765 /// the related value that it affects (TrackReg, TrackSubReg).
766 /// A source is considered rewritable if its register class and the
767 /// register class of the related TrackReg may not be register
768 /// coalescer friendly. In other words, given a copy-like instruction
769 /// not all the arguments may be returned at rewritable source, since
770 /// some arguments are none to be register coalescer friendly.
771 ///
772 /// Each call of this method moves the current source to the next
773 /// rewritable source.
774 /// For instance, let CopyLike be the instruction to rewrite.
775 /// CopyLike has one definition and one source:
776 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
777 ///
778 /// The first call will give the first rewritable source, i.e.,
779 /// the only source this instruction has:
780 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
781 /// This source defines the whole definition, i.e.,
782 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
783 ///
784 /// The second and subsequent calls will return false, has there is only one
785 /// rewritable source.
786 ///
787 /// \return True if a rewritable source has been found, false otherwise.
788 /// The output arguments are valid if and only if true is returned.
789 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
790 unsigned &TrackReg,
791 unsigned &TrackSubReg) {
792 // If CurrentSrcIdx == 1, this means this function has already been
793 // called once. CopyLike has one defintiion and one argument, thus,
794 // there is nothing else to rewrite.
795 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
796 return false;
797 // This is the first call to getNextRewritableSource.
798 // Move the CurrentSrcIdx to remember that we made that call.
799 CurrentSrcIdx = 1;
800 // The rewritable source is the argument.
801 const MachineOperand &MOSrc = CopyLike.getOperand(1);
802 SrcReg = MOSrc.getReg();
803 SrcSubReg = MOSrc.getSubReg();
804 // What we track are the alternative sources of the definition.
805 const MachineOperand &MODef = CopyLike.getOperand(0);
806 TrackReg = MODef.getReg();
807 TrackSubReg = MODef.getSubReg();
808 return true;
809 }
810
811 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
812 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000813 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000814 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
815 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
816 return false;
817 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
818 MOSrc.setReg(NewReg);
819 MOSrc.setSubReg(NewSubReg);
820 return true;
821 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000822
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000823 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
824 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
825 /// multiple sources for a given \p Def are found along the way, we found a
826 /// PHI instructions that needs to be rewritten.
827 /// TODO: HandleMultipleSources should be removed once we test PHI handling
828 /// with coalescable copies.
829 TargetInstrInfo::RegSubRegPair
830 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
831 TargetInstrInfo::RegSubRegPair Def,
832 PeepholeOptimizer::RewriteMapTy &RewriteMap,
833 bool HandleMultipleSources = true) {
834
835 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
836 do {
837 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
838 // If there are no entries on the map, LookupSrc is the new source.
839 if (!Res.isValid())
840 return LookupSrc;
841
842 // There's only one source for this definition, keep searching...
843 unsigned NumSrcs = Res.getNumSources();
844 if (NumSrcs == 1) {
845 LookupSrc.Reg = Res.getSrcReg(0);
846 LookupSrc.SubReg = Res.getSrcSubReg(0);
847 continue;
848 }
849
850 if (!HandleMultipleSources)
851 break;
852
853 // Multiple sources, recurse into each source to find a new source
854 // for it. Then, rewrite the PHI accordingly to its new edges.
855 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
856 for (unsigned i = 0; i < NumSrcs; ++i) {
857 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
858 Res.getSrcSubReg(i));
859 NewPHISrcs.push_back(
860 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
861 }
862
863 // Build the new PHI node and return its def register as the new source.
864 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
865 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
866 const MachineOperand &MODef = NewPHI->getOperand(0);
867 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
868
869 } while (1);
870
871 return TargetInstrInfo::RegSubRegPair(0, 0);
872 }
873
874 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
875 /// and create a new COPY instruction. More info about RewriteMap in
876 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
877 /// Uncoalescable copies, since they are copy like instructions that aren't
878 /// recognized by the register allocator.
879 virtual MachineInstr *
880 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
881 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000882 return nullptr;
883 }
884};
885
886/// \brief Helper class to rewrite uncoalescable copy like instructions
887/// into new COPY (coalescable friendly) instructions.
888class UncoalescableRewriter : public CopyRewriter {
889protected:
890 const TargetInstrInfo &TII;
891 MachineRegisterInfo &MRI;
892 /// The number of defs in the bitcast
893 unsigned NumDefs;
894
895public:
896 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
897 MachineRegisterInfo &MRI)
898 : CopyRewriter(MI), TII(TII), MRI(MRI) {
899 NumDefs = MI.getDesc().getNumDefs();
900 }
901
902 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
903 /// All such sources need to be considered rewritable in order to
904 /// rewrite a uncoalescable copy-like instruction. This method return
905 /// each definition that must be checked if rewritable.
906 ///
907 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
908 unsigned &TrackReg,
909 unsigned &TrackSubReg) override {
910 // Find the next non-dead definition and continue from there.
911 if (CurrentSrcIdx == NumDefs)
912 return false;
913
914 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
915 ++CurrentSrcIdx;
916 if (CurrentSrcIdx == NumDefs)
917 return false;
918 }
919
920 // What we track are the alternative sources of the definition.
921 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
922 TrackReg = MODef.getReg();
923 TrackSubReg = MODef.getSubReg();
924
925 CurrentSrcIdx++;
926 return true;
927 }
928
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000929 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
930 /// and create a new COPY instruction. More info about RewriteMap in
931 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
932 /// Uncoalescable copies, since they are copy like instructions that aren't
933 /// recognized by the register allocator.
934 MachineInstr *
935 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
936 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
937 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000938 "We do not rewrite physical registers");
939
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000940 // Find the new source to use in the COPY rewrite.
941 TargetInstrInfo::RegSubRegPair NewSrc =
942 getNewSource(&MRI, &TII, Def, RewriteMap);
943
944 // Insert the COPY.
945 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000946 unsigned NewVR = MRI.createVirtualRegister(DefRC);
947
948 MachineInstr *NewCopy =
949 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
950 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000951 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000952
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000953 NewCopy->getOperand(0).setSubReg(Def.SubReg);
954 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000955 NewCopy->getOperand(0).setIsUndef();
956
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000957 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000958 MRI.clearKillFlags(NewVR);
959
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +0000960 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
961 // account for that.
962 MRI.clearKillFlags(NewSrc.Reg);
963
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000964 return NewCopy;
965 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000966};
967
968/// \brief Specialized rewriter for INSERT_SUBREG instruction.
969class InsertSubregRewriter : public CopyRewriter {
970public:
971 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
972 assert(MI.isInsertSubreg() && "Invalid instruction");
973 }
974
975 /// \brief See CopyRewriter::getNextRewritableSource.
976 /// Here CopyLike has the following form:
977 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
978 /// Src1 has the same register class has dst, hence, there is
979 /// nothing to rewrite.
980 /// Src2.src2SubIdx, may not be register coalescer friendly.
981 /// Therefore, the first call to this method returns:
982 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
983 /// (TrackReg, TrackSubReg) = (dst, subIdx).
984 ///
985 /// Subsequence calls will return false.
986 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
987 unsigned &TrackReg,
988 unsigned &TrackSubReg) override {
989 // If we already get the only source we can rewrite, return false.
990 if (CurrentSrcIdx == 2)
991 return false;
992 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
993 CurrentSrcIdx = 2;
994 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
995 SrcReg = MOInsertedReg.getReg();
996 SrcSubReg = MOInsertedReg.getSubReg();
997 const MachineOperand &MODef = CopyLike.getOperand(0);
998
999 // We want to track something that is compatible with the
1000 // partial definition.
1001 TrackReg = MODef.getReg();
1002 if (MODef.getSubReg())
1003 // Bails if we have to compose sub-register indices.
1004 return false;
1005 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1006 return true;
1007 }
1008 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1009 if (CurrentSrcIdx != 2)
1010 return false;
1011 // We are rewriting the inserted reg.
1012 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1013 MO.setReg(NewReg);
1014 MO.setSubReg(NewSubReg);
1015 return true;
1016 }
1017};
1018
1019/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1020class ExtractSubregRewriter : public CopyRewriter {
1021 const TargetInstrInfo &TII;
1022
1023public:
1024 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1025 : CopyRewriter(MI), TII(TII) {
1026 assert(MI.isExtractSubreg() && "Invalid instruction");
1027 }
1028
1029 /// \brief See CopyRewriter::getNextRewritableSource.
1030 /// Here CopyLike has the following form:
1031 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1032 /// There is only one rewritable source: Src.subIdx,
1033 /// which defines dst.dstSubIdx.
1034 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1035 unsigned &TrackReg,
1036 unsigned &TrackSubReg) override {
1037 // If we already get the only source we can rewrite, return false.
1038 if (CurrentSrcIdx == 1)
1039 return false;
1040 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1041 CurrentSrcIdx = 1;
1042 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1043 SrcReg = MOExtractedReg.getReg();
1044 // If we have to compose sub-register indices, bails out.
1045 if (MOExtractedReg.getSubReg())
1046 return false;
1047
1048 SrcSubReg = CopyLike.getOperand(2).getImm();
1049
1050 // We want to track something that is compatible with the definition.
1051 const MachineOperand &MODef = CopyLike.getOperand(0);
1052 TrackReg = MODef.getReg();
1053 TrackSubReg = MODef.getSubReg();
1054 return true;
1055 }
1056
1057 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1058 // The only source we can rewrite is the input register.
1059 if (CurrentSrcIdx != 1)
1060 return false;
1061
1062 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1063
1064 // If we find a source that does not require to extract something,
1065 // rewrite the operation with a copy.
1066 if (!NewSubReg) {
1067 // Move the current index to an invalid position.
1068 // We do not want another call to this method to be able
1069 // to do any change.
1070 CurrentSrcIdx = -1;
1071 // Rewrite the operation as a COPY.
1072 // Get rid of the sub-register index.
1073 CopyLike.RemoveOperand(2);
1074 // Morph the operation into a COPY.
1075 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1076 return true;
1077 }
1078 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1079 return true;
1080 }
1081};
1082
1083/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1084class RegSequenceRewriter : public CopyRewriter {
1085public:
1086 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1087 assert(MI.isRegSequence() && "Invalid instruction");
1088 }
1089
1090 /// \brief See CopyRewriter::getNextRewritableSource.
1091 /// Here CopyLike has the following form:
1092 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1093 /// Each call will return a different source, walking all the available
1094 /// source.
1095 ///
1096 /// The first call returns:
1097 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1098 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1099 ///
1100 /// The second call returns:
1101 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1102 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1103 ///
1104 /// And so on, until all the sources have been traversed, then
1105 /// it returns false.
1106 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1107 unsigned &TrackReg,
1108 unsigned &TrackSubReg) override {
1109 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1110
1111 // If this is the first call, move to the first argument.
1112 if (CurrentSrcIdx == 0) {
1113 CurrentSrcIdx = 1;
1114 } else {
1115 // Otherwise, move to the next argument and check that it is valid.
1116 CurrentSrcIdx += 2;
1117 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1118 return false;
1119 }
1120 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1121 SrcReg = MOInsertedReg.getReg();
1122 // If we have to compose sub-register indices, bails out.
1123 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1124 return false;
1125
1126 // We want to track something that is compatible with the related
1127 // partial definition.
1128 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1129
1130 const MachineOperand &MODef = CopyLike.getOperand(0);
1131 TrackReg = MODef.getReg();
1132 // If we have to compose sub-registers, bails.
1133 return MODef.getSubReg() == 0;
1134 }
1135
1136 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1137 // We cannot rewrite out of bound operands.
1138 // Moreover, rewritable sources are at odd positions.
1139 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1140 return false;
1141
1142 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1143 MO.setReg(NewReg);
1144 MO.setSubReg(NewSubReg);
1145 return true;
1146 }
1147};
1148} // End namespace.
1149
1150/// \brief Get the appropriated CopyRewriter for \p MI.
1151/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1152/// if no rewriter works for \p MI.
1153static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001154 const TargetInstrInfo &TII,
1155 MachineRegisterInfo &MRI) {
1156 // Handle uncoalescable copy-like instructions.
1157 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1158 MI.isExtractSubregLike()))
1159 return new UncoalescableRewriter(MI, TII, MRI);
1160
Quentin Colombet03e43f82014-08-20 17:41:48 +00001161 switch (MI.getOpcode()) {
1162 default:
1163 return nullptr;
1164 case TargetOpcode::COPY:
1165 return new CopyRewriter(MI);
1166 case TargetOpcode::INSERT_SUBREG:
1167 return new InsertSubregRewriter(MI);
1168 case TargetOpcode::EXTRACT_SUBREG:
1169 return new ExtractSubregRewriter(MI, TII);
1170 case TargetOpcode::REG_SEQUENCE:
1171 return new RegSequenceRewriter(MI);
1172 }
1173 llvm_unreachable(nullptr);
1174}
1175
1176/// \brief Optimize generic copy instructions to avoid cross
1177/// register bank copy. The optimization looks through a chain of
1178/// copies and tries to find a source that has a compatible register
1179/// class.
1180/// Two register classes are considered to be compatible if they share
1181/// the same register bank.
1182/// New copies issued by this optimization are register allocator
1183/// friendly. This optimization does not remove any copy as it may
1184/// overconstraint the register allocator, but replaces some operands
1185/// when possible.
1186/// \pre isCoalescableCopy(*MI) is true.
1187/// \return True, when \p MI has been rewritten. False otherwise.
1188bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1189 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1190 assert(MI->getDesc().getNumDefs() == 1 &&
1191 "Coalescer can understand multiple defs?!");
1192 const MachineOperand &MODef = MI->getOperand(0);
1193 // Do not rewrite physical definitions.
1194 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1195 return false;
1196
1197 bool Changed = false;
1198 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001199 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Quentin Colombet03e43f82014-08-20 17:41:48 +00001200 // If none exists, bails out.
1201 if (!CpyRewriter)
1202 return false;
1203 // Rewrite each rewritable source.
1204 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1205 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1206 TrackSubReg)) {
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001207 // Keep track of PHI nodes and its incoming edges when looking for sources.
1208 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001209 // Try to find a more suitable source. If we failed to do so, or get the
1210 // actual source, move to the next source.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001211 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001212 continue;
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001213
1214 // Get the new source to rewrite. TODO: Only enable handling of multiple
1215 // sources (PHIs) once we have a motivating example and testcases for it.
1216 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1217 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1218 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1219 if (SrcReg == NewSrc.Reg)
1220 continue;
1221
Quentin Colombet03e43f82014-08-20 17:41:48 +00001222 // Rewrite source.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001223 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001224 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001225 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001226 Changed = true;
1227 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001228 }
1229 // TODO: We could have a clean-up method to tidy the instruction.
1230 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1231 // => v0 = COPY v1
1232 // Currently we haven't seen motivating example for that and we
1233 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001234 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001235 return Changed;
1236}
1237
1238/// \brief Optimize copy-like instructions to create
1239/// register coalescer friendly instruction.
1240/// The optimization tries to kill-off the \p MI by looking
1241/// through a chain of copies to find a source that has a compatible
1242/// register class.
1243/// If such a source is found, it replace \p MI by a generic COPY
1244/// operation.
1245/// \pre isUncoalescableCopy(*MI) is true.
1246/// \return True, when \p MI has been optimized. In that case, \p MI has
1247/// been removed from its parent.
1248/// All COPY instructions created, are inserted in \p LocalMIs.
1249bool PeepholeOptimizer::optimizeUncoalescableCopy(
1250 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1251 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1252
1253 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001254 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001255 // Get the right rewriter for the current copy.
1256 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
1257 // If none exists, bails out.
1258 if (!CpyRewriter)
1259 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001260
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001261 // Rewrite each rewritable source by generating new COPYs. This works
1262 // differently from optimizeCoalescableCopy since it first makes sure that all
1263 // definitions can be rewritten.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001264 RewriteMapTy RewriteMap;
1265 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1266 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1267 CopyDefSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001268 // If a physical register is here, this is probably for a good reason.
1269 // Do not rewrite that.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001270 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001271 return false;
1272
1273 // If we do not know how to rewrite this definition, there is no point
1274 // in trying to kill this instruction.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001275 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1276 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001277 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001278
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001279 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001280 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001281
Quentin Colombet03e43f82014-08-20 17:41:48 +00001282 // The change is possible for all defs, do it.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001283 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001284 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001285 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001286 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001287 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001288 }
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001289
Quentin Colombet03e43f82014-08-20 17:41:48 +00001290 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001291 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001292 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001293 return true;
1294}
1295
Manman Ren5759d012012-08-02 00:56:42 +00001296/// isLoadFoldable - Check whether MI is a candidate for folding into a later
1297/// instruction. We only fold loads to virtual registers and the virtual
1298/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001299bool PeepholeOptimizer::isLoadFoldable(
1300 MachineInstr *MI,
1301 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001302 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1303 return false;
1304 const MCInstrDesc &MCID = MI->getDesc();
1305 if (MCID.getNumDefs() != 1)
1306 return false;
1307
1308 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001309 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001310 // loads. It should be checked when processing uses of the load, since
1311 // uses can be removed during peephole.
1312 if (!MI->getOperand(0).getSubReg() &&
1313 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001314 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001315 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001316 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001317 }
1318 return false;
1319}
1320
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001321bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1322 SmallSet<unsigned, 4> &ImmDefRegs,
1323 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001324 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001325 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001326 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001327 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001328 return false;
1329 unsigned Reg = MI->getOperand(0).getReg();
1330 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1331 ImmDefMIs.insert(std::make_pair(Reg, MI));
1332 ImmDefRegs.insert(Reg);
1333 return true;
1334 }
Andrew Trick9e761992012-02-08 21:22:43 +00001335
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001336 return false;
1337}
1338
Jim Grosbachedcb8682012-05-01 23:21:41 +00001339/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001340/// immediate instructions, i.e. a trivial constant folding optimization, if
1341/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001342bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001343 SmallSet<unsigned, 4> &ImmDefRegs,
1344 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1345 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1346 MachineOperand &MO = MI->getOperand(i);
1347 if (!MO.isReg() || MO.isDef())
1348 continue;
1349 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001350 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001351 continue;
1352 if (ImmDefRegs.count(Reg) == 0)
1353 continue;
1354 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1355 assert(II != ImmDefMIs.end());
1356 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1357 ++NumImmFold;
1358 return true;
1359 }
1360 }
1361 return false;
1362}
1363
Eric Christopher2181fb22014-10-15 21:06:25 +00001364bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1365 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001366 return false;
1367
Craig Topper588ceec2012-12-17 03:56:00 +00001368 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001369 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001370
Evan Cheng2ce016c2010-11-15 21:20:45 +00001371 if (DisablePeephole)
1372 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001373
Eric Christopher2181fb22014-10-15 21:06:25 +00001374 TII = MF.getSubtarget().getInstrInfo();
1375 TRI = MF.getSubtarget().getRegisterInfo();
1376 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001377 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001378
1379 bool Changed = false;
1380
Eric Christopher2181fb22014-10-15 21:06:25 +00001381 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001382 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001383
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001384 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001385
1386 // During this forward scan, at some point it needs to answer the question
1387 // "given a pointer to an MI in the current BB, is it located before or
1388 // after the current instruction".
1389 // To perform this, the following set keeps track of the MIs already seen
1390 // during the scan, if a MI is not in the set, it is assumed to be located
1391 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001392 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001393 SmallSet<unsigned, 4> ImmDefRegs;
1394 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1395 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001396
1397 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001398 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001399 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001400 // We may be erasing MI below, increment MII now.
1401 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001402 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001403
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001404 // Skip debug values. They should not affect this peephole optimization.
1405 if (MI->isDebugValue())
1406 continue;
1407
Manman Ren5759d012012-08-02 00:56:42 +00001408 // If there exists an instruction which belongs to the following
Lang Hames5dc14bd2014-04-02 22:59:58 +00001409 // categories, we will discard the load candidates.
Rafael Espindolab1f25f12014-03-07 06:08:31 +00001410 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001411 MI->isKill() || MI->isInlineAsm() ||
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001412 MI->hasUnmodeledSideEffects()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001413 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001414 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001415 }
Manman Ren5759d012012-08-02 00:56:42 +00001416 if (MI->mayStore() || MI->isCall())
Lang Hames5dc14bd2014-04-02 22:59:58 +00001417 FoldAsLoadDefCandidates.clear();
Evan Cheng2ce016c2010-11-15 21:20:45 +00001418
Quentin Colombet03e43f82014-08-20 17:41:48 +00001419 if ((isUncoalescableCopy(*MI) &&
1420 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001421 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001422 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001423 // MI is deleted.
1424 LocalMIs.erase(MI);
1425 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001426 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001427 }
1428
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001429 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1430 Changed = true;
1431 continue;
1432 }
1433
Quentin Colombet03e43f82014-08-20 17:41:48 +00001434 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1435 // MI is just rewritten.
1436 Changed = true;
1437 continue;
1438 }
1439
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001440 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001441 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001442 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001443 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001444 // optimizeExtInstr might have created new instructions after MI
1445 // and before the already incremented MII. Adjust MII so that the
1446 // next iteration sees the new instructions.
1447 MII = MI;
1448 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001449 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001450 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001451 }
Evan Cheng98196b42011-02-15 05:00:24 +00001452
Manman Ren5759d012012-08-02 00:56:42 +00001453 // Check whether MI is a load candidate for folding into a later
1454 // instruction. If MI is not a candidate, check whether we can fold an
1455 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001456 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1457 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001458 const MCInstrDesc &MIDesc = MI->getDesc();
1459 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1460 ++i) {
1461 const MachineOperand &MOp = MI->getOperand(i);
1462 if (!MOp.isReg())
1463 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001464 unsigned FoldAsLoadDefReg = MOp.getReg();
1465 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1466 // We need to fold load after optimizeCmpInstr, since
1467 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1468 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1469 // we need it for markUsesInDebugValueAsUndef().
1470 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001471 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001472 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1473 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001474 DefMI);
1475 if (FoldMI) {
1476 // Update LocalMIs since we replaced MI with FoldMI and deleted
1477 // DefMI.
1478 DEBUG(dbgs() << "Replacing: " << *MI);
1479 DEBUG(dbgs() << " With: " << *FoldMI);
1480 LocalMIs.erase(MI);
1481 LocalMIs.erase(DefMI);
1482 LocalMIs.insert(FoldMI);
1483 MI->eraseFromParent();
1484 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001485 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1486 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001487 ++NumLoadFold;
1488 // MI is replaced with FoldMI.
1489 Changed = true;
1490 break;
1491 }
1492 }
Manman Ren5759d012012-08-02 00:56:42 +00001493 }
1494 }
Bill Wendlingca678352010-08-09 23:59:04 +00001495 }
1496 }
1497
1498 return Changed;
1499}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001500
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001501ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001502 assert(Def->isCopy() && "Invalid definition");
1503 // Copy instruction are supposed to be: Def = Src.
1504 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001505 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001506
1507 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1508 // If we look for a different subreg, it means we want a subreg of src.
1509 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001510 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001511 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001512 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001513 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001514}
1515
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001516ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001517 assert(Def->isBitcast() && "Invalid definition");
1518
1519 // Bail if there are effects that a plain copy will not expose.
1520 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001521 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001522
1523 // Bitcasts with more than one def are not supported.
1524 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001525 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001526 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1527 // If we look for a different subreg, it means we want a subreg of the src.
1528 // Bails as we do not support composing subreg yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001529 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001530
Quentin Colombet03e43f82014-08-20 17:41:48 +00001531 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001532 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1533 ++OpIdx) {
1534 const MachineOperand &MO = Def->getOperand(OpIdx);
1535 if (!MO.isReg() || !MO.getReg())
1536 continue;
1537 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1538 if (SrcIdx != EndOpIdx)
1539 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001540 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001541 SrcIdx = OpIdx;
1542 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001543 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001544 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001545}
1546
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001547ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001548 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1549 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001550
1551 if (Def->getOperand(DefIdx).getSubReg())
1552 // If we are composing subreg, bails out.
1553 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1554 // This should almost never happen as the SSA property is tracked at
1555 // the register level (as opposed to the subreg level).
1556 // I.e.,
1557 // Def.sub0 =
1558 // Def.sub1 =
1559 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1560 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001561 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001562 // Def.sub0 (i.e, not defining the other subregs) and we would
1563 // have this case.
1564 // If we can ascertain (or force) that this never happens, we could
1565 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001566 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001567
Quentin Colombet03e43f82014-08-20 17:41:48 +00001568 if (!TII)
1569 // We could handle the REG_SEQUENCE here, but we do not want to
1570 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001571 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001572
1573 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1574 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001575 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001576
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001577 // We are looking at:
1578 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1579 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001580 for (auto &RegSeqInput : RegSeqInputRegs) {
1581 if (RegSeqInput.SubIdx == DefSubReg) {
1582 if (RegSeqInput.SubReg)
1583 // Bails if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001584 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001585
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001586 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001587 }
1588 }
1589
1590 // If the subreg we are tracking is super-defined by another subreg,
1591 // we could follow this value. However, this would require to compose
1592 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001593 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001594}
1595
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001596ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001597 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1598 "Invalid definition");
1599
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001600 if (Def->getOperand(DefIdx).getSubReg())
1601 // If we are composing subreg, bails out.
1602 // Same remark as getNextSourceFromRegSequence.
1603 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001604 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001605
Quentin Colombet68962302014-08-21 00:19:16 +00001606 if (!TII)
1607 // We could handle the REG_SEQUENCE here, but we do not want to
1608 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001609 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001610
Quentin Colombet03e43f82014-08-20 17:41:48 +00001611 TargetInstrInfo::RegSubRegPair BaseReg;
1612 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001613 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001614 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001615
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001616 // We are looking at:
1617 // Def = INSERT_SUBREG v0, v1, sub1
1618 // There are two cases:
1619 // 1. DefSubReg == sub1, get v1.
1620 // 2. DefSubReg != sub1, the value may be available through v0.
1621
Quentin Colombet03e43f82014-08-20 17:41:48 +00001622 // #1 Check if the inserted register matches the required sub index.
1623 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001624 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001625 }
1626 // #2 Otherwise, if the sub register we are looking for is not partial
1627 // defined by the inserted element, we can look through the main
1628 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001629 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001630 // If the result register (Def) and the base register (v0) do not
1631 // have the same register class or if we have to compose
1632 // subregisters, bails out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001633 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1634 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001635 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001636
Quentin Colombet03e43f82014-08-20 17:41:48 +00001637 // Get the TRI and check if the inserted sub-register overlaps with the
1638 // sub-register we are tracking.
1639 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001640 if (!TRI ||
1641 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001642 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001643 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001644 // At this point, the value is available in v0 via the same subreg
1645 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001646 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001647}
1648
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001649ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001650 assert((Def->isExtractSubreg() ||
1651 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001652 // We are looking at:
1653 // Def = EXTRACT_SUBREG v0, sub0
1654
1655 // Bails if we have to compose sub registers.
1656 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1657 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001658 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001659
Quentin Colombet67639df2014-08-20 23:13:02 +00001660 if (!TII)
1661 // We could handle the EXTRACT_SUBREG here, but we do not want to
1662 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001663 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001664
Quentin Colombet03e43f82014-08-20 17:41:48 +00001665 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001666 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001667 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001668
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001669 // Bails if we have to compose sub registers.
1670 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001671 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001672 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001673 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001674 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001675}
1676
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001677ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001678 assert(Def->isSubregToReg() && "Invalid definition");
1679 // We are looking at:
1680 // Def = SUBREG_TO_REG Imm, v0, sub0
1681
1682 // Bails if we have to compose sub registers.
1683 // If DefSubReg != sub0, we would have to check that all the bits
1684 // we track are included in sub0 and if yes, we would have to
1685 // determine the right subreg in v0.
1686 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001687 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001688 // Bails if we have to compose sub registers.
1689 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1690 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001691 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001692
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001693 return ValueTrackerResult(Def->getOperand(2).getReg(),
1694 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001695}
1696
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001697/// \brief Explore each PHI incoming operand and return its sources
1698ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1699 assert(Def->isPHI() && "Invalid definition");
1700 ValueTrackerResult Res;
1701
1702 // If we look for a different subreg, bails as we do not
1703 // support composing subreg yet.
1704 if (Def->getOperand(0).getSubReg() != DefSubReg)
1705 return ValueTrackerResult();
1706
1707 // Return all register sources for PHI instructions.
1708 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1709 auto &MO = Def->getOperand(i);
1710 assert(MO.isReg() && "Invalid PHI instruction");
1711 Res.addSource(MO.getReg(), MO.getSubReg());
1712 }
1713
1714 return Res;
1715}
1716
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001717ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001718 assert(Def && "This method needs a valid definition");
1719
1720 assert(
1721 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1722 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1723 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001724 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001725 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001726 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001727 // All the remaining cases involve "complex" instructions.
1728 // Bails if we did not ask for the advanced tracking.
1729 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001730 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001731 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001732 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001733 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001734 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001735 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001736 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001737 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001738 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes669c9212015-07-27 14:39:46 +00001739 if (Def->isPHI())
1740 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001741 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001742}
1743
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001744ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001745 // If we reach a point where we cannot move up in the use-def chain,
1746 // there is nothing we can get.
1747 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001748 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001749
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001750 ValueTrackerResult Res = getNextSourceImpl();
1751 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001752 // Update definition, definition index, and subregister for the
1753 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001754 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001755 bool OneRegSrc = Res.getNumSources() == 1;
1756 if (OneRegSrc)
1757 Reg = Res.getSrcReg(0);
1758 // Update the result before moving up in the use-def chain
1759 // with the instruction containing the last found sources.
1760 Res.setInst(Def);
1761
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001762 // If we can still move up in the use-def chain, move to the next
1763 // defintion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001764 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001765 Def = MRI.getVRegDef(Reg);
1766 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001767 DefSubReg = Res.getSrcSubReg(0);
1768 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001769 }
1770 }
1771 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001772 // for the next iteration. Make sure any new call to getNextSource bails out
1773 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001774 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001775 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001776}