blob: f861edf7da258db8d67613b36627de5b12478874 [file] [log] [blame]
Bill Wendlingca678352010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
Evan Chenge4b8ac92011-03-15 05:13:13 +000033//
Manman Rendc8ad002012-05-11 01:30:47 +000034// Another instance, in this code:
35//
36// sub r1, r3 | sub r1, imm
37// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38// bge L1
39//
40// If the branch instruction can use flag from "sub", then we can replace
41// "sub" with "subs" and eliminate the "cmp" instruction.
42//
Joel Jones24e440d2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
Matt Arsenault30991562015-09-09 00:38:33 +000046// if it loads to virtual registers and the virtual register defined has
Joel Jones24e440d2012-12-11 16:10:25 +000047// a single use.
Quentin Colombetcf71c632013-09-13 18:26:31 +000048//
Quentin Colombet03e43f82014-08-20 17:41:48 +000049// - Optimize Copies and Bitcast (more generally, target specific copies):
Quentin Colombetcf71c632013-09-13 18:26:31 +000050//
51// Rewrite copies and bitcasts to avoid cross register bank copies
52// when possible.
53// E.g., Consider the following example, where capital and lower
54// letters denote different register file:
55// b = copy A <-- cross-bank copy
56// C = copy b <-- cross-bank copy
57// =>
58// b = copy A <-- cross-bank copy
59// C = copy A <-- same-bank copy
60//
61// E.g., for bitcast:
62// b = bitcast A <-- cross-bank copy
63// C = bitcast b <-- cross-bank copy
64// =>
65// b = bitcast A <-- cross-bank copy
66// C = copy A <-- same-bank copy
Bill Wendlingca678352010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
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
JF Bastien1ac69942015-12-03 23:43:56 +0000101static cl::opt<bool> DisableNAPhysCopyOpt(
102 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
103 cl::desc("Disable non-allocatable physical register copy optimization"));
104
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000105// Limit the number of PHI instructions to process
106// in PeepholeOptimizer::getNextSource.
107static cl::opt<unsigned> RewritePHILimit(
108 "rewrite-phi-limit", cl::Hidden, cl::init(10),
109 cl::desc("Limit the length of PHI chains to lookup"));
110
Bill Wendling66284312010-08-27 20:39:09 +0000111STATISTIC(NumReuse, "Number of extension results reused");
Evan Chenge4b8ac92011-03-15 05:13:13 +0000112STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames31bb57b2012-02-25 00:46:38 +0000113STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Ren5759d012012-08-02 00:56:42 +0000114STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000115STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet03e43f82014-08-20 17:41:48 +0000116STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
117STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
JF Bastien1ac69942015-12-03 23:43:56 +0000118STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
Bill Wendlingca678352010-08-09 23:59:04 +0000119
120namespace {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000121 class ValueTrackerResult;
122
Bill Wendlingca678352010-08-09 23:59:04 +0000123 class PeepholeOptimizer : public MachineFunctionPass {
Bill Wendlingca678352010-08-09 23:59:04 +0000124 const TargetInstrInfo *TII;
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000125 const TargetRegisterInfo *TRI;
Bill Wendlingca678352010-08-09 23:59:04 +0000126 MachineRegisterInfo *MRI;
127 MachineDominatorTree *DT; // Machine dominator tree
128
129 public:
130 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000131 PeepholeOptimizer() : MachineFunctionPass(ID) {
132 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
133 }
Bill Wendlingca678352010-08-09 23:59:04 +0000134
Craig Topper4584cd52014-03-07 09:26:03 +0000135 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingca678352010-08-09 23:59:04 +0000136
Craig Topper4584cd52014-03-07 09:26:03 +0000137 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingca678352010-08-09 23:59:04 +0000138 AU.setPreservesCFG();
139 MachineFunctionPass::getAnalysisUsage(AU);
140 if (Aggressive) {
141 AU.addRequired<MachineDominatorTree>();
142 AU.addPreserved<MachineDominatorTree>();
143 }
144 }
145
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000146 /// \brief Track Def -> Use info used for rewriting copies.
147 typedef SmallDenseMap<TargetInstrInfo::RegSubRegPair, ValueTrackerResult>
148 RewriteMapTy;
149
Bill Wendlingca678352010-08-09 23:59:04 +0000150 private:
Jim Grosbachedcb8682012-05-01 23:21:41 +0000151 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
152 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000153 SmallPtrSetImpl<MachineInstr*> &LocalMIs);
Mehdi Amini22e59742015-01-13 07:07:13 +0000154 bool optimizeSelect(MachineInstr *MI,
155 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000156 bool optimizeCondBranch(MachineInstr *MI);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000157 bool optimizeCoalescableCopy(MachineInstr *MI);
158 bool optimizeUncoalescableCopy(MachineInstr *MI,
159 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000160 bool findNextSource(unsigned Reg, unsigned SubReg,
161 RewriteMapTy &RewriteMap);
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000162 bool isMoveImmediate(MachineInstr *MI,
163 SmallSet<unsigned, 4> &ImmDefRegs,
164 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbachedcb8682012-05-01 23:21:41 +0000165 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +0000166 SmallSet<unsigned, 4> &ImmDefRegs,
167 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000168
169 /// \brief If copy instruction \p MI is a virtual register copy, track it in
JF Bastien1ac69942015-12-03 23:43:56 +0000170 /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
Matt Arsenault10aa8072015-09-25 20:22:12 +0000171 /// previously seen as a copy, replace the uses of this copy with the
172 /// previously seen copy's destination register.
173 bool foldRedundantCopy(MachineInstr *MI,
JF Bastien1ac69942015-12-03 23:43:56 +0000174 SmallSet<unsigned, 4> &CopySrcRegs,
175 DenseMap<unsigned, MachineInstr *> &CopyMIs);
176
177 /// \brief Is the register \p Reg a non-allocatable physical register?
178 bool isNAPhysCopy(unsigned Reg);
179
180 /// \brief If copy instruction \p MI is a non-allocatable virtual<->physical
181 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
182 /// non-allocatable physical register was previously copied to a virtual
183 /// registered and hasn't been clobbered, the virt->phys copy can be
184 /// deleted.
185 bool foldRedundantNAPhysCopy(
186 MachineInstr *MI,
187 DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
Matt Arsenault10aa8072015-09-25 20:22:12 +0000188
Lang Hames5dc14bd2014-04-02 22:59:58 +0000189 bool isLoadFoldable(MachineInstr *MI,
190 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Quentin Colombet03e43f82014-08-20 17:41:48 +0000191
192 /// \brief Check whether \p MI is understood by the register coalescer
193 /// but may require some rewriting.
194 bool isCoalescableCopy(const MachineInstr &MI) {
195 // SubregToRegs are not interesting, because they are already register
196 // coalescer friendly.
197 return MI.isCopy() || (!DisableAdvCopyOpt &&
198 (MI.isRegSequence() || MI.isInsertSubreg() ||
199 MI.isExtractSubreg()));
200 }
201
202 /// \brief Check whether \p MI is a copy like instruction that is
203 /// not recognized by the register coalescer.
204 bool isUncoalescableCopy(const MachineInstr &MI) {
Quentin Colombet68962302014-08-21 00:19:16 +0000205 return MI.isBitcast() ||
206 (!DisableAdvCopyOpt &&
207 (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
208 MI.isExtractSubregLike()));
Quentin Colombet03e43f82014-08-20 17:41:48 +0000209 }
Bill Wendlingca678352010-08-09 23:59:04 +0000210 };
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000211
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000212 /// \brief Helper class to hold a reply for ValueTracker queries. Contains the
213 /// returned sources for a given search and the instructions where the sources
214 /// were tracked from.
215 class ValueTrackerResult {
216 private:
217 /// Track all sources found by one ValueTracker query.
218 SmallVector<TargetInstrInfo::RegSubRegPair, 2> RegSrcs;
219
220 /// Instruction using the sources in 'RegSrcs'.
221 const MachineInstr *Inst;
222
223 public:
224 ValueTrackerResult() : Inst(nullptr) {}
225 ValueTrackerResult(unsigned Reg, unsigned SubReg) : Inst(nullptr) {
226 addSource(Reg, SubReg);
227 }
228
229 bool isValid() const { return getNumSources() > 0; }
230
231 void setInst(const MachineInstr *I) { Inst = I; }
232 const MachineInstr *getInst() const { return Inst; }
233
234 void clear() {
235 RegSrcs.clear();
236 Inst = nullptr;
237 }
238
239 void addSource(unsigned SrcReg, unsigned SrcSubReg) {
240 RegSrcs.push_back(TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg));
241 }
242
243 void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
244 assert(Idx < getNumSources() && "Reg pair source out of index");
245 RegSrcs[Idx] = TargetInstrInfo::RegSubRegPair(SrcReg, SrcSubReg);
246 }
247
248 int getNumSources() const { return RegSrcs.size(); }
249
250 unsigned getSrcReg(int Idx) const {
251 assert(Idx < getNumSources() && "Reg source out of index");
252 return RegSrcs[Idx].Reg;
253 }
254
255 unsigned getSrcSubReg(int Idx) const {
256 assert(Idx < getNumSources() && "SubReg source out of index");
257 return RegSrcs[Idx].SubReg;
258 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000259
260 bool operator==(const ValueTrackerResult &Other) {
261 if (Other.getInst() != getInst())
262 return false;
263
264 if (Other.getNumSources() != getNumSources())
265 return false;
266
267 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
268 if (Other.getSrcReg(i) != getSrcReg(i) ||
269 Other.getSrcSubReg(i) != getSrcSubReg(i))
270 return false;
271 return true;
272 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000273 };
274
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000275 /// \brief Helper class to track the possible sources of a value defined by
276 /// a (chain of) copy related instructions.
277 /// Given a definition (instruction and definition index), this class
278 /// follows the use-def chain to find successive suitable sources.
279 /// The given source can be used to rewrite the definition into
280 /// def = COPY src.
281 ///
282 /// For instance, let us consider the following snippet:
283 /// v0 =
284 /// v2 = INSERT_SUBREG v1, v0, sub0
285 /// def = COPY v2.sub0
286 ///
287 /// Using a ValueTracker for def = COPY v2.sub0 will give the following
288 /// suitable sources:
289 /// v2.sub0 and v0.
290 /// Then, def can be rewritten into def = COPY v0.
291 class ValueTracker {
292 private:
293 /// The current point into the use-def chain.
294 const MachineInstr *Def;
295 /// The index of the definition in Def.
296 unsigned DefIdx;
297 /// The sub register index of the definition.
298 unsigned DefSubReg;
299 /// The register where the value can be found.
300 unsigned Reg;
301 /// Specifiy whether or not the value tracking looks through
302 /// complex instructions. When this is false, the value tracker
303 /// bails on everything that is not a copy or a bitcast.
304 ///
305 /// Note: This could have been implemented as a specialized version of
306 /// the ValueTracker class but that would have complicated the code of
307 /// the users of this class.
308 bool UseAdvancedTracking;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000309 /// MachineRegisterInfo used to perform tracking.
310 const MachineRegisterInfo &MRI;
311 /// Optional TargetInstrInfo used to perform some complex
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000312 /// tracking.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000313 const TargetInstrInfo *TII;
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000314
315 /// \brief Dispatcher to the right underlying implementation of
316 /// getNextSource.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000317 ValueTrackerResult getNextSourceImpl();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000318 /// \brief Specialized version of getNextSource for Copy instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000319 ValueTrackerResult getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000320 /// \brief Specialized version of getNextSource for Bitcast instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000321 ValueTrackerResult getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000322 /// \brief Specialized version of getNextSource for RegSequence
323 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000324 ValueTrackerResult getNextSourceFromRegSequence();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000325 /// \brief Specialized version of getNextSource for InsertSubreg
326 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000327 ValueTrackerResult getNextSourceFromInsertSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000328 /// \brief Specialized version of getNextSource for ExtractSubreg
329 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000330 ValueTrackerResult getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000331 /// \brief Specialized version of getNextSource for SubregToReg
332 /// instructions.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000333 ValueTrackerResult getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000334 /// \brief Specialized version of getNextSource for PHI instructions.
335 ValueTrackerResult getNextSourceFromPHI();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000336
337 public:
Quentin Colombet03e43f82014-08-20 17:41:48 +0000338 /// \brief Create a ValueTracker instance for the value defined by \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000339 /// \p DefSubReg represents the sub register index the value tracker will
Quentin Colombet03e43f82014-08-20 17:41:48 +0000340 /// track. It does not need to match the sub register index used in the
341 /// definition of \p Reg.
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000342 /// \p UseAdvancedTracking specifies whether or not the value tracker looks
343 /// through complex instructions. By default (false), it handles only copy
344 /// and bitcast instructions.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000345 /// If \p Reg is a physical register, a value tracker constructed with
346 /// this constructor will not find any alternative source.
347 /// Indeed, when \p Reg is a physical register that constructor does not
348 /// know which definition of \p Reg it should track.
349 /// Use the next constructor to track a physical register.
350 ValueTracker(unsigned Reg, unsigned DefSubReg,
351 const MachineRegisterInfo &MRI,
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000352 bool UseAdvancedTracking = false,
Quentin Colombet03e43f82014-08-20 17:41:48 +0000353 const TargetInstrInfo *TII = nullptr)
354 : Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
355 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
356 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) {
357 Def = MRI.getVRegDef(Reg);
358 DefIdx = MRI.def_begin(Reg).getOperandNo();
359 }
360 }
361
362 /// \brief Create a ValueTracker instance for the value defined by
363 /// the pair \p MI, \p DefIdx.
364 /// Unlike the other constructor, the value tracker produced by this one
365 /// may be able to find a new source when the definition is a physical
366 /// register.
367 /// This could be useful to rewrite target specific instructions into
368 /// generic copy instructions.
369 ValueTracker(const MachineInstr &MI, unsigned DefIdx, unsigned DefSubReg,
370 const MachineRegisterInfo &MRI,
371 bool UseAdvancedTracking = false,
372 const TargetInstrInfo *TII = nullptr)
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000373 : Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
Quentin Colombet03e43f82014-08-20 17:41:48 +0000374 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI), TII(TII) {
375 assert(DefIdx < Def->getDesc().getNumDefs() &&
376 Def->getOperand(DefIdx).isReg() && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000377 Reg = Def->getOperand(DefIdx).getReg();
378 }
379
380 /// \brief Following the use-def chain, get the next available source
381 /// for the tracked value.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000382 /// \return A ValueTrackerResult containing a set of registers
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000383 /// and sub registers with tracked values. A ValueTrackerResult with
384 /// an empty set of registers means no source was found.
385 ValueTrackerResult getNextSource();
Quentin Colombet1111e6f2014-07-01 14:33:36 +0000386
387 /// \brief Get the last register where the initial value can be found.
388 /// Initially this is the register of the definition.
389 /// Then, after each successful call to getNextSource, this is the
390 /// register of the last source.
391 unsigned getReg() const { return Reg; }
392 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000393}
Bill Wendlingca678352010-08-09 23:59:04 +0000394
395char PeepholeOptimizer::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000396char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000397INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
398 "Peephole Optimizations", false, false)
399INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
400INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000401 "Peephole Optimizations", false, false)
Bill Wendlingca678352010-08-09 23:59:04 +0000402
Jim Grosbachedcb8682012-05-01 23:21:41 +0000403/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendlingca678352010-08-09 23:59:04 +0000404/// a single register and writes a single register and it does not modify the
405/// source, and if the source value is preserved as a sub-register of the
406/// result, then replace all reachable uses of the source with the subreg of the
407/// result.
Andrew Trick9e761992012-02-08 21:22:43 +0000408///
Bill Wendlingca678352010-08-09 23:59:04 +0000409/// Do not generate an EXTRACT that is used only in a debug use, as this changes
410/// the code. Since this code does not currently share EXTRACTs, just ignore all
411/// debug uses.
412bool PeepholeOptimizer::
Jim Grosbachedcb8682012-05-01 23:21:41 +0000413optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Hans Wennborg97a59ae2014-08-11 13:52:46 +0000414 SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
Bill Wendlingca678352010-08-09 23:59:04 +0000415 unsigned SrcReg, DstReg, SubIdx;
416 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
417 return false;
Andrew Trick9e761992012-02-08 21:22:43 +0000418
Bill Wendlingca678352010-08-09 23:59:04 +0000419 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
420 TargetRegisterInfo::isPhysicalRegister(SrcReg))
421 return false;
422
Jakob Stoklund Olesen8eb99052012-06-19 21:10:18 +0000423 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendlingca678352010-08-09 23:59:04 +0000424 // No other uses.
425 return false;
426
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000427 // Ensure DstReg can get a register class that actually supports
428 // sub-registers. Don't change the class until we commit.
429 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000430 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000431 if (!DstRC)
432 return false;
433
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000434 // The ext instr may be operating on a sub-register of SrcReg as well.
435 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
436 // register.
437 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
438 // SrcReg:SubIdx should be replaced.
Eric Christopherd9134482014-08-04 21:25:23 +0000439 bool UseSrcSubIdx =
Eric Christopher92b4bcb2014-10-14 07:17:20 +0000440 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000441
Bill Wendlingca678352010-08-09 23:59:04 +0000442 // The source has other uses. See if we can replace the other uses with use of
443 // the result of the extension.
444 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Owen Andersonb36376e2014-03-17 19:36:09 +0000445 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
446 ReachedBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000447
448 // Uses that are in the same BB of uses of the result of the instruction.
449 SmallVector<MachineOperand*, 8> Uses;
450
451 // Uses that the result of the instruction can reach.
452 SmallVector<MachineOperand*, 8> ExtendedUses;
453
454 bool ExtendLife = true;
Owen Andersonb36376e2014-03-17 19:36:09 +0000455 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000456 MachineInstr *UseMI = UseMO.getParent();
Bill Wendlingca678352010-08-09 23:59:04 +0000457 if (UseMI == MI)
458 continue;
459
460 if (UseMI->isPHI()) {
461 ExtendLife = false;
462 continue;
463 }
464
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000465 // Only accept uses of SrcReg:SubIdx.
466 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
467 continue;
468
Bill Wendlingca678352010-08-09 23:59:04 +0000469 // It's an error to translate this:
470 //
471 // %reg1025 = <sext> %reg1024
472 // ...
473 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
474 //
475 // into this:
476 //
477 // %reg1025 = <sext> %reg1024
478 // ...
479 // %reg1027 = COPY %reg1025:4
480 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
481 //
482 // The problem here is that SUBREG_TO_REG is there to assert that an
483 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
484 // the COPY here, it will give us the value after the <sext>, not the
485 // original value of %reg1024 before <sext>.
486 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
487 continue;
488
489 MachineBasicBlock *UseMBB = UseMI->getParent();
490 if (UseMBB == MBB) {
491 // Local uses that come after the extension.
492 if (!LocalMIs.count(UseMI))
493 Uses.push_back(&UseMO);
494 } else if (ReachedBBs.count(UseMBB)) {
495 // Non-local uses where the result of the extension is used. Always
496 // replace these unless it's a PHI.
497 Uses.push_back(&UseMO);
498 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
499 // We may want to extend the live range of the extension result in order
500 // to replace these uses.
501 ExtendedUses.push_back(&UseMO);
502 } else {
503 // Both will be live out of the def MBB anyway. Don't extend live range of
504 // the extension result.
505 ExtendLife = false;
506 break;
507 }
508 }
509
510 if (ExtendLife && !ExtendedUses.empty())
511 // Extend the liveness of the extension result.
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000512 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
Bill Wendlingca678352010-08-09 23:59:04 +0000513
514 // Now replace all uses.
515 bool Changed = false;
516 if (!Uses.empty()) {
517 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
518
519 // Look for PHI uses of the extended result, we don't want to extend the
520 // liveness of a PHI input. It breaks all kinds of assumptions down
521 // stream. A PHI use is expected to be the kill of its source values.
Owen Andersonb36376e2014-03-17 19:36:09 +0000522 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
523 if (UI.isPHI())
524 PHIBBs.insert(UI.getParent());
Bill Wendlingca678352010-08-09 23:59:04 +0000525
526 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
527 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
528 MachineOperand *UseMO = Uses[i];
529 MachineInstr *UseMI = UseMO->getParent();
530 MachineBasicBlock *UseMBB = UseMI->getParent();
531 if (PHIBBs.count(UseMBB))
532 continue;
533
Lang Hamesd5862ce2012-02-25 02:01:00 +0000534 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000535 if (!Changed) {
Lang Hamesd5862ce2012-02-25 02:01:00 +0000536 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen2f06a652012-05-20 18:42:55 +0000537 MRI->constrainRegClass(DstReg, DstRC);
538 }
Lang Hamesd5862ce2012-02-25 02:01:00 +0000539
Bill Wendlingca678352010-08-09 23:59:04 +0000540 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000541 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
542 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendlingca678352010-08-09 23:59:04 +0000543 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen0f855e42012-06-19 21:14:34 +0000544 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
545 if (UseSrcSubIdx) {
546 Copy->getOperand(0).setSubReg(SubIdx);
547 Copy->getOperand(0).setIsUndef();
548 }
Bill Wendlingca678352010-08-09 23:59:04 +0000549 UseMO->setReg(NewVR);
550 ++NumReuse;
551 Changed = true;
552 }
553 }
554
555 return Changed;
556}
557
Jim Grosbachedcb8682012-05-01 23:21:41 +0000558/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendlingca678352010-08-09 23:59:04 +0000559/// instruction it's comparing against all ready sets (or could be modified to
560/// set) the same flag as the compare, then we can remove the comparison and use
561/// the flag from the previous instruction.
Jim Grosbachedcb8682012-05-01 23:21:41 +0000562bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chenge4b8ac92011-03-15 05:13:13 +0000563 MachineBasicBlock *MBB) {
Bill Wendlingca678352010-08-09 23:59:04 +0000564 // If this instruction is a comparison against zero and isn't comparing a
565 // physical register, we can try to optimize it.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000566 unsigned SrcReg, SrcReg2;
Gabor Greifadbbb932010-09-21 12:01:15 +0000567 int CmpMask, CmpValue;
Manman Ren6fa76dc2012-06-29 21:33:59 +0000568 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
569 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
570 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendlingca678352010-08-09 23:59:04 +0000571 return false;
572
Bill Wendling27dddd12010-09-11 00:13:50 +0000573 // Attempt to optimize the comparison instruction.
Manman Ren6fa76dc2012-06-29 21:33:59 +0000574 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chenge4b8ac92011-03-15 05:13:13 +0000575 ++NumCmps;
Bill Wendlingca678352010-08-09 23:59:04 +0000576 return true;
577 }
578
579 return false;
580}
581
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000582/// Optimize a select instruction.
Mehdi Amini22e59742015-01-13 07:07:13 +0000583bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI,
584 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000585 unsigned TrueOp = 0;
586 unsigned FalseOp = 0;
587 bool Optimizable = false;
588 SmallVector<MachineOperand, 4> Cond;
589 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
590 return false;
591 if (!Optimizable)
592 return false;
Mehdi Amini22e59742015-01-13 07:07:13 +0000593 if (!TII->optimizeSelect(MI, LocalMIs))
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +0000594 return false;
595 MI->eraseFromParent();
596 ++NumSelects;
597 return true;
598}
599
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +0000600/// \brief Check if a simpler conditional branch can be
601// generated
602bool PeepholeOptimizer::optimizeCondBranch(MachineInstr *MI) {
603 return TII->optimizeCondBranch(MI);
604}
605
Quentin Colombet03e43f82014-08-20 17:41:48 +0000606/// \brief Try to find the next source that share the same register file
607/// for the value defined by \p Reg and \p SubReg.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000608/// When true is returned, the \p RewriteMap can be used by the client to
609/// retrieve all Def -> Use along the way up to the next source. Any found
610/// Use that is not itself a key for another entry, is the next source to
611/// use. During the search for the next source, multiple sources can be found
612/// given multiple incoming sources of a PHI instruction. In this case, we
613/// look in each PHI source for the next source; all found next sources must
614/// share the same register file as \p Reg and \p SubReg. The client should
615/// then be capable to rewrite all intermediate PHIs to get the next source.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000616/// \return False if no alternative sources are available. True otherwise.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000617bool PeepholeOptimizer::findNextSource(unsigned Reg, unsigned SubReg,
618 RewriteMapTy &RewriteMap) {
Quentin Colombet03e43f82014-08-20 17:41:48 +0000619 // Do not try to find a new source for a physical register.
620 // So far we do not have any motivating example for doing that.
621 // Thus, instead of maintaining untested code, we will revisit that if
622 // that changes at some point.
623 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Quentin Colombetcf71c632013-09-13 18:26:31 +0000624 return false;
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000625 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
Bruno Cardoso Lopes38c02502015-07-29 17:46:47 +0000626
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000627 SmallVector<TargetInstrInfo::RegSubRegPair, 4> SrcToLook;
628 TargetInstrInfo::RegSubRegPair CurSrcPair(Reg, SubReg);
629 SrcToLook.push_back(CurSrcPair);
Quentin Colombetcf71c632013-09-13 18:26:31 +0000630
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000631 unsigned PHICount = 0;
632 while (!SrcToLook.empty() && PHICount < RewritePHILimit) {
633 TargetInstrInfo::RegSubRegPair Pair = SrcToLook.pop_back_val();
634 // As explained above, do not handle physical registers
635 if (TargetRegisterInfo::isPhysicalRegister(Pair.Reg))
636 return false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000637
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000638 CurSrcPair = Pair;
639 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
640 !DisableAdvCopyOpt, TII);
641 ValueTrackerResult Res;
642 bool ShouldRewrite = false;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000643
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000644 do {
645 // Follow the chain of copies until we reach the top of the use-def chain
646 // or find a more suitable source.
647 Res = ValTracker.getNextSource();
648 if (!Res.isValid())
649 break;
Quentin Colombetcf71c632013-09-13 18:26:31 +0000650
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000651 // Insert the Def -> Use entry for the recently found source.
652 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
653 if (CurSrcRes.isValid()) {
654 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
655 // An existent entry with multiple sources is a PHI cycle we must avoid.
656 // Otherwise it's an entry with a valid next source we already found.
657 if (CurSrcRes.getNumSources() > 1) {
658 DEBUG(dbgs() << "findNextSource: found PHI cycle, aborting...\n");
659 return false;
660 }
661 break;
662 }
663 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
664
665 // ValueTrackerResult usually have one source unless it's the result from
666 // a PHI instruction. Add the found PHI edges to be looked up further.
667 unsigned NumSrcs = Res.getNumSources();
668 if (NumSrcs > 1) {
669 PHICount++;
670 for (unsigned i = 0; i < NumSrcs; ++i)
671 SrcToLook.push_back(TargetInstrInfo::RegSubRegPair(
672 Res.getSrcReg(i), Res.getSrcSubReg(i)));
673 break;
674 }
675
676 CurSrcPair.Reg = Res.getSrcReg(0);
677 CurSrcPair.SubReg = Res.getSrcSubReg(0);
678 // Do not extend the live-ranges of physical registers as they add
679 // constraints to the register allocator. Moreover, if we want to extend
680 // the live-range of a physical register, unlike SSA virtual register,
681 // we will have to check that they aren't redefine before the related use.
682 if (TargetRegisterInfo::isPhysicalRegister(CurSrcPair.Reg))
683 return false;
684
685 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
Matt Arsenault68d93862015-09-24 08:36:14 +0000686 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
687 CurSrcPair.SubReg);
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000688 } while (!ShouldRewrite);
689
690 // Continue looking for new sources...
691 if (Res.isValid())
692 continue;
693
694 // Do not continue searching for a new source if the there's at least
695 // one use-def which cannot be rewritten.
696 if (!ShouldRewrite)
697 return false;
698 }
699
700 if (PHICount >= RewritePHILimit) {
701 DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
702 return false;
703 }
Quentin Colombetcf71c632013-09-13 18:26:31 +0000704
705 // If we did not find a more suitable source, there is nothing to optimize.
Rafael Espindola84921b92015-10-24 23:11:13 +0000706 return CurSrcPair.Reg != Reg;
Quentin Colombet03e43f82014-08-20 17:41:48 +0000707}
Quentin Colombetcf71c632013-09-13 18:26:31 +0000708
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000709/// \brief Insert a PHI instruction with incoming edges \p SrcRegs that are
710/// guaranteed to have the same register class. This is necessary whenever we
711/// successfully traverse a PHI instruction and find suitable sources coming
712/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
713/// suitable to be used in a new COPY instruction.
Benjamin Kramerfcdb1c12015-08-20 09:57:22 +0000714static MachineInstr *
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000715insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
716 const SmallVectorImpl<TargetInstrInfo::RegSubRegPair> &SrcRegs,
717 MachineInstr *OrigPHI) {
718 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
719
720 const TargetRegisterClass *NewRC = MRI->getRegClass(SrcRegs[0].Reg);
721 unsigned NewVR = MRI->createVirtualRegister(NewRC);
722 MachineBasicBlock *MBB = OrigPHI->getParent();
723 MachineInstrBuilder MIB = BuildMI(*MBB, OrigPHI, OrigPHI->getDebugLoc(),
724 TII->get(TargetOpcode::PHI), NewVR);
725
726 unsigned MBBOpIdx = 2;
727 for (auto RegPair : SrcRegs) {
728 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
729 MIB.addMBB(OrigPHI->getOperand(MBBOpIdx).getMBB());
730 // Since we're extended the lifetime of RegPair.Reg, clear the
731 // kill flags to account for that and make RegPair.Reg reaches
732 // the new PHI.
733 MRI->clearKillFlags(RegPair.Reg);
734 MBBOpIdx += 2;
735 }
736
737 return MIB;
738}
739
Quentin Colombet03e43f82014-08-20 17:41:48 +0000740namespace {
741/// \brief Helper class to rewrite the arguments of a copy-like instruction.
742class CopyRewriter {
743protected:
744 /// The copy-like instruction.
745 MachineInstr &CopyLike;
746 /// The index of the source being rewritten.
747 unsigned CurrentSrcIdx;
748
749public:
750 CopyRewriter(MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
751
752 virtual ~CopyRewriter() {}
753
754 /// \brief Get the next rewritable source (SrcReg, SrcSubReg) and
755 /// the related value that it affects (TrackReg, TrackSubReg).
756 /// A source is considered rewritable if its register class and the
757 /// register class of the related TrackReg may not be register
758 /// coalescer friendly. In other words, given a copy-like instruction
759 /// not all the arguments may be returned at rewritable source, since
760 /// some arguments are none to be register coalescer friendly.
761 ///
762 /// Each call of this method moves the current source to the next
763 /// rewritable source.
764 /// For instance, let CopyLike be the instruction to rewrite.
765 /// CopyLike has one definition and one source:
766 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
767 ///
768 /// The first call will give the first rewritable source, i.e.,
769 /// the only source this instruction has:
770 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
771 /// This source defines the whole definition, i.e.,
772 /// (TrackReg, TrackSubReg) = (dst, dstSubIdx).
773 ///
Matt Arsenault30991562015-09-09 00:38:33 +0000774 /// The second and subsequent calls will return false, as there is only one
Quentin Colombet03e43f82014-08-20 17:41:48 +0000775 /// rewritable source.
776 ///
777 /// \return True if a rewritable source has been found, false otherwise.
778 /// The output arguments are valid if and only if true is returned.
779 virtual bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
780 unsigned &TrackReg,
781 unsigned &TrackSubReg) {
Matt Arsenault30991562015-09-09 00:38:33 +0000782 // If CurrentSrcIdx == 1, this means this function has already been called
783 // once. CopyLike has one definition and one argument, thus, there is
784 // nothing else to rewrite.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000785 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
786 return false;
787 // This is the first call to getNextRewritableSource.
788 // Move the CurrentSrcIdx to remember that we made that call.
789 CurrentSrcIdx = 1;
790 // The rewritable source is the argument.
791 const MachineOperand &MOSrc = CopyLike.getOperand(1);
792 SrcReg = MOSrc.getReg();
793 SrcSubReg = MOSrc.getSubReg();
794 // What we track are the alternative sources of the definition.
795 const MachineOperand &MODef = CopyLike.getOperand(0);
796 TrackReg = MODef.getReg();
797 TrackSubReg = MODef.getSubReg();
798 return true;
799 }
800
801 /// \brief Rewrite the current source with \p NewReg and \p NewSubReg
802 /// if possible.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000803 /// \return True if the rewriting was possible, false otherwise.
Quentin Colombet03e43f82014-08-20 17:41:48 +0000804 virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) {
805 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
806 return false;
807 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
808 MOSrc.setReg(NewReg);
809 MOSrc.setSubReg(NewSubReg);
810 return true;
811 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000812
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000813 /// \brief Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
814 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
815 /// multiple sources for a given \p Def are found along the way, we found a
816 /// PHI instructions that needs to be rewritten.
817 /// TODO: HandleMultipleSources should be removed once we test PHI handling
818 /// with coalescable copies.
819 TargetInstrInfo::RegSubRegPair
820 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
821 TargetInstrInfo::RegSubRegPair Def,
822 PeepholeOptimizer::RewriteMapTy &RewriteMap,
823 bool HandleMultipleSources = true) {
824
825 TargetInstrInfo::RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
826 do {
827 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
828 // If there are no entries on the map, LookupSrc is the new source.
829 if (!Res.isValid())
830 return LookupSrc;
831
832 // There's only one source for this definition, keep searching...
833 unsigned NumSrcs = Res.getNumSources();
834 if (NumSrcs == 1) {
835 LookupSrc.Reg = Res.getSrcReg(0);
836 LookupSrc.SubReg = Res.getSrcSubReg(0);
837 continue;
838 }
839
Matt Arsenault30991562015-09-09 00:38:33 +0000840 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000841 if (!HandleMultipleSources)
842 break;
843
844 // Multiple sources, recurse into each source to find a new source
845 // for it. Then, rewrite the PHI accordingly to its new edges.
846 SmallVector<TargetInstrInfo::RegSubRegPair, 4> NewPHISrcs;
847 for (unsigned i = 0; i < NumSrcs; ++i) {
848 TargetInstrInfo::RegSubRegPair PHISrc(Res.getSrcReg(i),
849 Res.getSrcSubReg(i));
850 NewPHISrcs.push_back(
851 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
852 }
853
854 // Build the new PHI node and return its def register as the new source.
855 MachineInstr *OrigPHI = const_cast<MachineInstr *>(Res.getInst());
856 MachineInstr *NewPHI = insertPHI(MRI, TII, NewPHISrcs, OrigPHI);
857 DEBUG(dbgs() << "-- getNewSource\n");
858 DEBUG(dbgs() << " Replacing: " << *OrigPHI);
859 DEBUG(dbgs() << " With: " << *NewPHI);
860 const MachineOperand &MODef = NewPHI->getOperand(0);
861 return TargetInstrInfo::RegSubRegPair(MODef.getReg(), MODef.getSubReg());
862
863 } while (1);
864
865 return TargetInstrInfo::RegSubRegPair(0, 0);
866 }
867
868 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
869 /// and create a new COPY instruction. More info about RewriteMap in
870 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
871 /// Uncoalescable copies, since they are copy like instructions that aren't
872 /// recognized by the register allocator.
873 virtual MachineInstr *
874 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
875 PeepholeOptimizer::RewriteMapTy &RewriteMap) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000876 return nullptr;
877 }
878};
879
880/// \brief Helper class to rewrite uncoalescable copy like instructions
881/// into new COPY (coalescable friendly) instructions.
882class UncoalescableRewriter : public CopyRewriter {
883protected:
884 const TargetInstrInfo &TII;
885 MachineRegisterInfo &MRI;
886 /// The number of defs in the bitcast
887 unsigned NumDefs;
888
889public:
890 UncoalescableRewriter(MachineInstr &MI, const TargetInstrInfo &TII,
891 MachineRegisterInfo &MRI)
892 : CopyRewriter(MI), TII(TII), MRI(MRI) {
893 NumDefs = MI.getDesc().getNumDefs();
894 }
895
896 /// \brief Get the next rewritable def source (TrackReg, TrackSubReg)
897 /// All such sources need to be considered rewritable in order to
898 /// rewrite a uncoalescable copy-like instruction. This method return
899 /// each definition that must be checked if rewritable.
900 ///
901 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
902 unsigned &TrackReg,
903 unsigned &TrackSubReg) override {
904 // Find the next non-dead definition and continue from there.
905 if (CurrentSrcIdx == NumDefs)
906 return false;
907
908 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
909 ++CurrentSrcIdx;
910 if (CurrentSrcIdx == NumDefs)
911 return false;
912 }
913
914 // What we track are the alternative sources of the definition.
915 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
916 TrackReg = MODef.getReg();
917 TrackSubReg = MODef.getSubReg();
918
919 CurrentSrcIdx++;
920 return true;
921 }
922
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000923 /// \brief Rewrite the source found through \p Def, by using the \p RewriteMap
924 /// and create a new COPY instruction. More info about RewriteMap in
925 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
926 /// Uncoalescable copies, since they are copy like instructions that aren't
927 /// recognized by the register allocator.
928 MachineInstr *
929 RewriteSource(TargetInstrInfo::RegSubRegPair Def,
930 PeepholeOptimizer::RewriteMapTy &RewriteMap) override {
931 assert(!TargetRegisterInfo::isPhysicalRegister(Def.Reg) &&
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000932 "We do not rewrite physical registers");
933
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000934 // Find the new source to use in the COPY rewrite.
935 TargetInstrInfo::RegSubRegPair NewSrc =
936 getNewSource(&MRI, &TII, Def, RewriteMap);
937
938 // Insert the COPY.
939 const TargetRegisterClass *DefRC = MRI.getRegClass(Def.Reg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000940 unsigned NewVR = MRI.createVirtualRegister(DefRC);
941
942 MachineInstr *NewCopy =
943 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
944 TII.get(TargetOpcode::COPY), NewVR)
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000945 .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000946
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000947 NewCopy->getOperand(0).setSubReg(Def.SubReg);
948 if (Def.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000949 NewCopy->getOperand(0).setIsUndef();
950
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000951 DEBUG(dbgs() << "-- RewriteSource\n");
952 DEBUG(dbgs() << " Replacing: " << CopyLike);
953 DEBUG(dbgs() << " With: " << *NewCopy);
954 MRI.replaceRegWith(Def.Reg, NewVR);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000955 MRI.clearKillFlags(NewVR);
956
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +0000957 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
958 // account for that.
959 MRI.clearKillFlags(NewSrc.Reg);
960
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +0000961 return NewCopy;
962 }
Quentin Colombet03e43f82014-08-20 17:41:48 +0000963};
964
965/// \brief Specialized rewriter for INSERT_SUBREG instruction.
966class InsertSubregRewriter : public CopyRewriter {
967public:
968 InsertSubregRewriter(MachineInstr &MI) : CopyRewriter(MI) {
969 assert(MI.isInsertSubreg() && "Invalid instruction");
970 }
971
972 /// \brief See CopyRewriter::getNextRewritableSource.
973 /// Here CopyLike has the following form:
974 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
975 /// Src1 has the same register class has dst, hence, there is
976 /// nothing to rewrite.
977 /// Src2.src2SubIdx, may not be register coalescer friendly.
978 /// Therefore, the first call to this method returns:
979 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
980 /// (TrackReg, TrackSubReg) = (dst, subIdx).
981 ///
982 /// Subsequence calls will return false.
983 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
984 unsigned &TrackReg,
985 unsigned &TrackSubReg) override {
986 // If we already get the only source we can rewrite, return false.
987 if (CurrentSrcIdx == 2)
988 return false;
989 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
990 CurrentSrcIdx = 2;
991 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
992 SrcReg = MOInsertedReg.getReg();
993 SrcSubReg = MOInsertedReg.getSubReg();
994 const MachineOperand &MODef = CopyLike.getOperand(0);
995
996 // We want to track something that is compatible with the
997 // partial definition.
998 TrackReg = MODef.getReg();
999 if (MODef.getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001000 // Bail if we have to compose sub-register indices.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001001 return false;
1002 TrackSubReg = (unsigned)CopyLike.getOperand(3).getImm();
1003 return true;
1004 }
1005 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1006 if (CurrentSrcIdx != 2)
1007 return false;
1008 // We are rewriting the inserted reg.
1009 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1010 MO.setReg(NewReg);
1011 MO.setSubReg(NewSubReg);
1012 return true;
1013 }
1014};
1015
1016/// \brief Specialized rewriter for EXTRACT_SUBREG instruction.
1017class ExtractSubregRewriter : public CopyRewriter {
1018 const TargetInstrInfo &TII;
1019
1020public:
1021 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
1022 : CopyRewriter(MI), TII(TII) {
1023 assert(MI.isExtractSubreg() && "Invalid instruction");
1024 }
1025
1026 /// \brief See CopyRewriter::getNextRewritableSource.
1027 /// Here CopyLike has the following form:
1028 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
1029 /// There is only one rewritable source: Src.subIdx,
1030 /// which defines dst.dstSubIdx.
1031 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1032 unsigned &TrackReg,
1033 unsigned &TrackSubReg) override {
1034 // If we already get the only source we can rewrite, return false.
1035 if (CurrentSrcIdx == 1)
1036 return false;
1037 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
1038 CurrentSrcIdx = 1;
1039 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
1040 SrcReg = MOExtractedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001041 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001042 if (MOExtractedReg.getSubReg())
1043 return false;
1044
1045 SrcSubReg = CopyLike.getOperand(2).getImm();
1046
1047 // We want to track something that is compatible with the definition.
1048 const MachineOperand &MODef = CopyLike.getOperand(0);
1049 TrackReg = MODef.getReg();
1050 TrackSubReg = MODef.getSubReg();
1051 return true;
1052 }
1053
1054 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1055 // The only source we can rewrite is the input register.
1056 if (CurrentSrcIdx != 1)
1057 return false;
1058
1059 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1060
1061 // If we find a source that does not require to extract something,
1062 // rewrite the operation with a copy.
1063 if (!NewSubReg) {
1064 // Move the current index to an invalid position.
1065 // We do not want another call to this method to be able
1066 // to do any change.
1067 CurrentSrcIdx = -1;
1068 // Rewrite the operation as a COPY.
1069 // Get rid of the sub-register index.
1070 CopyLike.RemoveOperand(2);
1071 // Morph the operation into a COPY.
1072 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1073 return true;
1074 }
1075 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1076 return true;
1077 }
1078};
1079
1080/// \brief Specialized rewriter for REG_SEQUENCE instruction.
1081class RegSequenceRewriter : public CopyRewriter {
1082public:
1083 RegSequenceRewriter(MachineInstr &MI) : CopyRewriter(MI) {
1084 assert(MI.isRegSequence() && "Invalid instruction");
1085 }
1086
1087 /// \brief See CopyRewriter::getNextRewritableSource.
1088 /// Here CopyLike has the following form:
1089 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1090 /// Each call will return a different source, walking all the available
1091 /// source.
1092 ///
1093 /// The first call returns:
1094 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1095 /// (TrackReg, TrackSubReg) = (dst, subIdx1).
1096 ///
1097 /// The second call returns:
1098 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1099 /// (TrackReg, TrackSubReg) = (dst, subIdx2).
1100 ///
1101 /// And so on, until all the sources have been traversed, then
1102 /// it returns false.
1103 bool getNextRewritableSource(unsigned &SrcReg, unsigned &SrcSubReg,
1104 unsigned &TrackReg,
1105 unsigned &TrackSubReg) override {
1106 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1107
1108 // If this is the first call, move to the first argument.
1109 if (CurrentSrcIdx == 0) {
1110 CurrentSrcIdx = 1;
1111 } else {
1112 // Otherwise, move to the next argument and check that it is valid.
1113 CurrentSrcIdx += 2;
1114 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1115 return false;
1116 }
1117 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1118 SrcReg = MOInsertedReg.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001119 // If we have to compose sub-register indices, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001120 if ((SrcSubReg = MOInsertedReg.getSubReg()))
1121 return false;
1122
1123 // We want to track something that is compatible with the related
1124 // partial definition.
1125 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1126
1127 const MachineOperand &MODef = CopyLike.getOperand(0);
1128 TrackReg = MODef.getReg();
Matt Arsenault30991562015-09-09 00:38:33 +00001129 // If we have to compose sub-registers, bail.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001130 return MODef.getSubReg() == 0;
1131 }
1132
1133 bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1134 // We cannot rewrite out of bound operands.
1135 // Moreover, rewritable sources are at odd positions.
1136 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1137 return false;
1138
1139 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1140 MO.setReg(NewReg);
1141 MO.setSubReg(NewSubReg);
1142 return true;
1143 }
1144};
1145} // End namespace.
1146
1147/// \brief Get the appropriated CopyRewriter for \p MI.
1148/// \return A pointer to a dynamically allocated CopyRewriter or nullptr
1149/// if no rewriter works for \p MI.
1150static CopyRewriter *getCopyRewriter(MachineInstr &MI,
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001151 const TargetInstrInfo &TII,
1152 MachineRegisterInfo &MRI) {
1153 // Handle uncoalescable copy-like instructions.
1154 if (MI.isBitcast() || (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1155 MI.isExtractSubregLike()))
1156 return new UncoalescableRewriter(MI, TII, MRI);
1157
Quentin Colombet03e43f82014-08-20 17:41:48 +00001158 switch (MI.getOpcode()) {
1159 default:
1160 return nullptr;
1161 case TargetOpcode::COPY:
1162 return new CopyRewriter(MI);
1163 case TargetOpcode::INSERT_SUBREG:
1164 return new InsertSubregRewriter(MI);
1165 case TargetOpcode::EXTRACT_SUBREG:
1166 return new ExtractSubregRewriter(MI, TII);
1167 case TargetOpcode::REG_SEQUENCE:
1168 return new RegSequenceRewriter(MI);
1169 }
1170 llvm_unreachable(nullptr);
1171}
1172
1173/// \brief Optimize generic copy instructions to avoid cross
1174/// register bank copy. The optimization looks through a chain of
1175/// copies and tries to find a source that has a compatible register
1176/// class.
1177/// Two register classes are considered to be compatible if they share
1178/// the same register bank.
1179/// New copies issued by this optimization are register allocator
1180/// friendly. This optimization does not remove any copy as it may
Matt Arsenault30991562015-09-09 00:38:33 +00001181/// overconstrain the register allocator, but replaces some operands
Quentin Colombet03e43f82014-08-20 17:41:48 +00001182/// when possible.
1183/// \pre isCoalescableCopy(*MI) is true.
1184/// \return True, when \p MI has been rewritten. False otherwise.
1185bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr *MI) {
1186 assert(MI && isCoalescableCopy(*MI) && "Invalid argument");
1187 assert(MI->getDesc().getNumDefs() == 1 &&
1188 "Coalescer can understand multiple defs?!");
1189 const MachineOperand &MODef = MI->getOperand(0);
1190 // Do not rewrite physical definitions.
1191 if (TargetRegisterInfo::isPhysicalRegister(MODef.getReg()))
1192 return false;
1193
1194 bool Changed = false;
1195 // Get the right rewriter for the current copy.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001196 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001197 // If none exists, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001198 if (!CpyRewriter)
1199 return false;
1200 // Rewrite each rewritable source.
1201 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1202 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1203 TrackSubReg)) {
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001204 // Keep track of PHI nodes and its incoming edges when looking for sources.
1205 RewriteMapTy RewriteMap;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001206 // Try to find a more suitable source. If we failed to do so, or get the
1207 // actual source, move to the next source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001208 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001209 continue;
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001210
1211 // Get the new source to rewrite. TODO: Only enable handling of multiple
1212 // sources (PHIs) once we have a motivating example and testcases for it.
1213 TargetInstrInfo::RegSubRegPair TrackPair(TrackReg, TrackSubReg);
1214 TargetInstrInfo::RegSubRegPair NewSrc = CpyRewriter->getNewSource(
1215 MRI, TII, TrackPair, RewriteMap, false /* multiple sources */);
1216 if (SrcReg == NewSrc.Reg || NewSrc.Reg == 0)
1217 continue;
1218
Quentin Colombet03e43f82014-08-20 17:41:48 +00001219 // Rewrite source.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001220 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
Quentin Colombet6b363372014-08-21 21:34:06 +00001221 // We may have extended the live-range of NewSrc, account for that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001222 MRI->clearKillFlags(NewSrc.Reg);
Quentin Colombet6b363372014-08-21 21:34:06 +00001223 Changed = true;
1224 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001225 }
1226 // TODO: We could have a clean-up method to tidy the instruction.
1227 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1228 // => v0 = COPY v1
1229 // Currently we haven't seen motivating example for that and we
1230 // want to avoid untested code.
David Blaikiedc3f01e2015-03-09 01:57:13 +00001231 NumRewrittenCopies += Changed;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001232 return Changed;
1233}
1234
1235/// \brief Optimize copy-like instructions to create
1236/// register coalescer friendly instruction.
1237/// The optimization tries to kill-off the \p MI by looking
1238/// through a chain of copies to find a source that has a compatible
1239/// register class.
1240/// If such a source is found, it replace \p MI by a generic COPY
1241/// operation.
1242/// \pre isUncoalescableCopy(*MI) is true.
1243/// \return True, when \p MI has been optimized. In that case, \p MI has
1244/// been removed from its parent.
1245/// All COPY instructions created, are inserted in \p LocalMIs.
1246bool PeepholeOptimizer::optimizeUncoalescableCopy(
1247 MachineInstr *MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1248 assert(MI && isUncoalescableCopy(*MI) && "Invalid argument");
1249
1250 // Check if we can rewrite all the values defined by this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001251 SmallVector<TargetInstrInfo::RegSubRegPair, 4> RewritePairs;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001252 // Get the right rewriter for the current copy.
1253 std::unique_ptr<CopyRewriter> CpyRewriter(getCopyRewriter(*MI, *TII, *MRI));
Matt Arsenault30991562015-09-09 00:38:33 +00001254 // If none exists, bail out.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001255 if (!CpyRewriter)
1256 return false;
Quentin Colombet03e43f82014-08-20 17:41:48 +00001257
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001258 // Rewrite each rewritable source by generating new COPYs. This works
1259 // differently from optimizeCoalescableCopy since it first makes sure that all
1260 // definitions can be rewritten.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001261 RewriteMapTy RewriteMap;
1262 unsigned Reg, SubReg, CopyDefReg, CopyDefSubReg;
1263 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1264 CopyDefSubReg)) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001265 // If a physical register is here, this is probably for a good reason.
1266 // Do not rewrite that.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001267 if (TargetRegisterInfo::isPhysicalRegister(CopyDefReg))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001268 return false;
1269
1270 // If we do not know how to rewrite this definition, there is no point
1271 // in trying to kill this instruction.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001272 TargetInstrInfo::RegSubRegPair Def(CopyDefReg, CopyDefSubReg);
1273 if (!findNextSource(Def.Reg, Def.SubReg, RewriteMap))
Quentin Colombet03e43f82014-08-20 17:41:48 +00001274 return false;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001275
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001276 RewritePairs.push_back(Def);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001277 }
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001278
Quentin Colombet03e43f82014-08-20 17:41:48 +00001279 // The change is possible for all defs, do it.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001280 for (const auto &Def : RewritePairs) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001281 // Rewrite the "copy" in a way the register coalescer understands.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001282 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001283 assert(NewCopy && "Should be able to always generate a new copy");
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001284 LocalMIs.insert(NewCopy);
Quentin Colombet03e43f82014-08-20 17:41:48 +00001285 }
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001286
Quentin Colombet03e43f82014-08-20 17:41:48 +00001287 // MI is now dead.
Quentin Colombetcf71c632013-09-13 18:26:31 +00001288 MI->eraseFromParent();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001289 ++NumUncoalescableCopies;
Quentin Colombetcf71c632013-09-13 18:26:31 +00001290 return true;
1291}
1292
Manman Ren5759d012012-08-02 00:56:42 +00001293/// isLoadFoldable - Check whether MI is a candidate for folding into a later
1294/// instruction. We only fold loads to virtual registers and the virtual
1295/// register defined has a single use.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001296bool PeepholeOptimizer::isLoadFoldable(
1297 MachineInstr *MI,
1298 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Renba8122c2012-08-02 19:37:32 +00001299 if (!MI->canFoldAsLoad() || !MI->mayLoad())
1300 return false;
1301 const MCInstrDesc &MCID = MI->getDesc();
1302 if (MCID.getNumDefs() != 1)
1303 return false;
1304
1305 unsigned Reg = MI->getOperand(0).getReg();
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001306 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Renba8122c2012-08-02 19:37:32 +00001307 // loads. It should be checked when processing uses of the load, since
1308 // uses can be removed during peephole.
1309 if (!MI->getOperand(0).getSubReg() &&
1310 TargetRegisterInfo::isVirtualRegister(Reg) &&
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001311 MRI->hasOneNonDBGUse(Reg)) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001312 FoldAsLoadDefCandidates.insert(Reg);
Manman Renba8122c2012-08-02 19:37:32 +00001313 return true;
Manman Ren5759d012012-08-02 00:56:42 +00001314 }
1315 return false;
1316}
1317
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001318bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
1319 SmallSet<unsigned, 4> &ImmDefRegs,
1320 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001321 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng7f8e5632011-12-07 07:15:52 +00001322 if (!MI->isMoveImmediate())
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001323 return false;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001324 if (MCID.getNumDefs() != 1)
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001325 return false;
1326 unsigned Reg = MI->getOperand(0).getReg();
1327 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1328 ImmDefMIs.insert(std::make_pair(Reg, MI));
1329 ImmDefRegs.insert(Reg);
1330 return true;
1331 }
Andrew Trick9e761992012-02-08 21:22:43 +00001332
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001333 return false;
1334}
1335
Jim Grosbachedcb8682012-05-01 23:21:41 +00001336/// foldImmediate - Try folding register operands that are defined by move
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001337/// immediate instructions, i.e. a trivial constant folding optimization, if
1338/// and only if the def and use are in the same BB.
Jim Grosbachedcb8682012-05-01 23:21:41 +00001339bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001340 SmallSet<unsigned, 4> &ImmDefRegs,
1341 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
1342 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1343 MachineOperand &MO = MI->getOperand(i);
1344 if (!MO.isReg() || MO.isDef())
1345 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001346 // Ignore dead implicit defs.
1347 if (MO.isImplicit() && MO.isDead())
1348 continue;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001349 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);
JF Bastien1ac69942015-12-03 23:43:56 +00001355 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001356 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
1357 ++NumImmFold;
1358 return true;
1359 }
1360 }
1361 return false;
1362}
1363
Matt Arsenault10aa8072015-09-25 20:22:12 +00001364// FIXME: This is very simple and misses some cases which should be handled when
1365// motivating examples are found.
1366//
1367// The copy rewriting logic should look at uses as well as defs and be able to
1368// eliminate copies across blocks.
1369//
1370// Later copies that are subregister extracts will also not be eliminated since
1371// only the first copy is considered.
1372//
1373// e.g.
1374// %vreg1 = COPY %vreg0
1375// %vreg2 = COPY %vreg0:sub1
1376//
1377// Should replace %vreg2 uses with %vreg1:sub1
1378bool PeepholeOptimizer::foldRedundantCopy(
JF Bastien1ac69942015-12-03 23:43:56 +00001379 MachineInstr *MI,
1380 SmallSet<unsigned, 4> &CopySrcRegs,
1381 DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1382 assert(MI->isCopy() && "expected a COPY machine instruction");
Matt Arsenault10aa8072015-09-25 20:22:12 +00001383
1384 unsigned SrcReg = MI->getOperand(1).getReg();
1385 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1386 return false;
1387
1388 unsigned DstReg = MI->getOperand(0).getReg();
1389 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1390 return false;
1391
1392 if (CopySrcRegs.insert(SrcReg).second) {
1393 // First copy of this reg seen.
1394 CopyMIs.insert(std::make_pair(SrcReg, MI));
1395 return false;
1396 }
1397
1398 MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1399
1400 unsigned SrcSubReg = MI->getOperand(1).getSubReg();
1401 unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1402
1403 // Can't replace different subregister extracts.
1404 if (SrcSubReg != PrevSrcSubReg)
1405 return false;
1406
1407 unsigned PrevDstReg = PrevCopy->getOperand(0).getReg();
1408
1409 // Only replace if the copy register class is the same.
1410 //
1411 // TODO: If we have multiple copies to different register classes, we may want
1412 // to track multiple copies of the same source register.
1413 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1414 return false;
1415
1416 MRI->replaceRegWith(DstReg, PrevDstReg);
1417
1418 // Lifetime of the previous copy has been extended.
1419 MRI->clearKillFlags(PrevDstReg);
1420 return true;
1421}
1422
JF Bastien1ac69942015-12-03 23:43:56 +00001423bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1424 return TargetRegisterInfo::isPhysicalRegister(Reg) &&
1425 !MRI->isAllocatable(Reg);
1426}
1427
1428bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1429 MachineInstr *MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1430 assert(MI->isCopy() && "expected a COPY machine instruction");
1431
1432 if (DisableNAPhysCopyOpt)
1433 return false;
1434
1435 unsigned DstReg = MI->getOperand(0).getReg();
1436 unsigned SrcReg = MI->getOperand(1).getReg();
1437 if (isNAPhysCopy(SrcReg) && TargetRegisterInfo::isVirtualRegister(DstReg)) {
1438 // %vreg = COPY %PHYSREG
1439 // Avoid using a datastructure which can track multiple live non-allocatable
1440 // phys->virt copies since LLVM doesn't seem to do this.
1441 NAPhysToVirtMIs.insert({SrcReg, MI});
1442 return false;
1443 }
1444
1445 if (!(TargetRegisterInfo::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1446 return false;
1447
1448 // %PHYSREG = COPY %vreg
1449 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1450 if (PrevCopy == NAPhysToVirtMIs.end()) {
1451 // We can't remove the copy: there was an intervening clobber of the
1452 // non-allocatable physical register after the copy to virtual.
1453 DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " << *MI
1454 << '\n');
1455 return false;
1456 }
1457
1458 unsigned PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1459 if (PrevDstReg == SrcReg) {
1460 // Remove the virt->phys copy: we saw the virtual register definition, and
1461 // the non-allocatable physical register's state hasn't changed since then.
1462 DEBUG(dbgs() << "NAPhysCopy: erasing " << *MI << '\n');
1463 ++NumNAPhysCopies;
1464 return true;
1465 }
1466
1467 // Potential missed optimization opportunity: we saw a different virtual
1468 // register get a copy of the non-allocatable physical register, and we only
1469 // track one such copy. Avoid getting confused by this new non-allocatable
1470 // physical register definition, and remove it from the tracked copies.
1471 DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << *MI << '\n');
1472 NAPhysToVirtMIs.erase(PrevCopy);
1473 return false;
1474}
1475
Eric Christopher2181fb22014-10-15 21:06:25 +00001476bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1477 if (skipOptnoneFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +00001478 return false;
1479
Craig Topper588ceec2012-12-17 03:56:00 +00001480 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
Eric Christopher2181fb22014-10-15 21:06:25 +00001481 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
Craig Topper588ceec2012-12-17 03:56:00 +00001482
Evan Cheng2ce016c2010-11-15 21:20:45 +00001483 if (DisablePeephole)
1484 return false;
Andrew Trick9e761992012-02-08 21:22:43 +00001485
Eric Christopher2181fb22014-10-15 21:06:25 +00001486 TII = MF.getSubtarget().getInstrInfo();
1487 TRI = MF.getSubtarget().getRegisterInfo();
1488 MRI = &MF.getRegInfo();
Craig Topperc0196b12014-04-14 00:51:57 +00001489 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendlingca678352010-08-09 23:59:04 +00001490
1491 bool Changed = false;
1492
Eric Christopher2181fb22014-10-15 21:06:25 +00001493 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Bill Wendlingca678352010-08-09 23:59:04 +00001494 MachineBasicBlock *MBB = &*I;
Andrew Trick9e761992012-02-08 21:22:43 +00001495
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001496 bool SeenMoveImm = false;
Mehdi Amini22e59742015-01-13 07:07:13 +00001497
1498 // During this forward scan, at some point it needs to answer the question
1499 // "given a pointer to an MI in the current BB, is it located before or
1500 // after the current instruction".
1501 // To perform this, the following set keeps track of the MIs already seen
1502 // during the scan, if a MI is not in the set, it is assumed to be located
1503 // after. Newly created MIs have to be inserted in the set as well.
Hans Wennborg941a5702014-08-11 02:50:43 +00001504 SmallPtrSet<MachineInstr*, 16> LocalMIs;
Lang Hames5dc14bd2014-04-02 22:59:58 +00001505 SmallSet<unsigned, 4> ImmDefRegs;
1506 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1507 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendlingca678352010-08-09 23:59:04 +00001508
JF Bastien1ac69942015-12-03 23:43:56 +00001509 // Track when a non-allocatable physical register is copied to a virtual
1510 // register so that useless moves can be removed.
1511 //
1512 // %PHYSREG is the map index; MI is the last valid `%vreg = COPY %PHYSREG`
1513 // without any intervening re-definition of %PHYSREG.
1514 DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1515
Matt Arsenault10aa8072015-09-25 20:22:12 +00001516 // Set of virtual registers that are copied from.
1517 SmallSet<unsigned, 4> CopySrcRegs;
1518 DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1519
Bill Wendlingca678352010-08-09 23:59:04 +00001520 for (MachineBasicBlock::iterator
Bill Wendlingaee679b2010-09-10 21:55:43 +00001521 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001522 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen714f5952012-08-17 14:38:59 +00001523 // We may be erasing MI below, increment MII now.
1524 ++MII;
Evan Cheng2ce016c2010-11-15 21:20:45 +00001525 LocalMIs.insert(MI);
Bill Wendlingca678352010-08-09 23:59:04 +00001526
Ekaterina Romanova8d620082014-03-13 18:47:12 +00001527 // Skip debug values. They should not affect this peephole optimization.
1528 if (MI->isDebugValue())
1529 continue;
1530
Michael Kupersteinbc7f99a2015-08-12 10:14:58 +00001531 // If we run into an instruction we can't fold across, discard
1532 // the load candidates.
1533 if (MI->isLoadFoldBarrier())
Michael Kuperstein82814f62015-08-11 08:19:43 +00001534 FoldAsLoadDefCandidates.clear();
1535
JF Bastien1ac69942015-12-03 23:43:56 +00001536 if (MI->isPosition() || MI->isPHI())
Evan Cheng2ce016c2010-11-15 21:20:45 +00001537 continue;
1538
JF Bastien1ac69942015-12-03 23:43:56 +00001539 if (!MI->isCopy()) {
1540 for (const auto &Op : MI->operands()) {
1541 // Visit all operands: definitions can be implicit or explicit.
1542 if (Op.isReg()) {
1543 unsigned Reg = Op.getReg();
1544 if (Op.isDef() && isNAPhysCopy(Reg)) {
1545 const auto &Def = NAPhysToVirtMIs.find(Reg);
1546 if (Def != NAPhysToVirtMIs.end()) {
1547 // A new definition of the non-allocatable physical register
1548 // invalidates previous copies.
1549 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1550 << '\n');
1551 NAPhysToVirtMIs.erase(Def);
1552 }
1553 }
1554 } else if (Op.isRegMask()) {
1555 const uint32_t *RegMask = Op.getRegMask();
1556 for (auto &RegMI : NAPhysToVirtMIs) {
1557 unsigned Def = RegMI.first;
1558 if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1559 DEBUG(dbgs() << "NAPhysCopy: invalidating because of " << *MI
1560 << '\n');
1561 NAPhysToVirtMIs.erase(Def);
1562 }
1563 }
1564 }
1565 }
1566 }
1567
1568 if (MI->isImplicitDef() || MI->isKill())
1569 continue;
1570
1571 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1572 // Blow away all non-allocatable physical registers knowledge since we
1573 // don't know what's correct anymore.
1574 //
1575 // FIXME: handle explicit asm clobbers.
1576 DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " << *MI
1577 << '\n');
1578 NAPhysToVirtMIs.clear();
1579 continue;
1580 }
1581
Quentin Colombet03e43f82014-08-20 17:41:48 +00001582 if ((isUncoalescableCopy(*MI) &&
1583 optimizeUncoalescableCopy(MI, LocalMIs)) ||
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001584 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
Mehdi Amini22e59742015-01-13 07:07:13 +00001585 (MI->isSelect() && optimizeSelect(MI, LocalMIs))) {
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001586 // MI is deleted.
1587 LocalMIs.erase(MI);
1588 Changed = true;
Jakob Stoklund Olesen2382d322012-08-16 23:11:47 +00001589 continue;
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001590 }
1591
Gerolf Hoflehnera4c96d02014-10-14 23:07:53 +00001592 if (MI->isConditionalBranch() && optimizeCondBranch(MI)) {
1593 Changed = true;
1594 continue;
1595 }
1596
Quentin Colombet03e43f82014-08-20 17:41:48 +00001597 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1598 // MI is just rewritten.
1599 Changed = true;
1600 continue;
1601 }
1602
JF Bastien1ac69942015-12-03 23:43:56 +00001603 if (MI->isCopy() &&
1604 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1605 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
Matt Arsenault10aa8072015-09-25 20:22:12 +00001606 LocalMIs.erase(MI);
1607 MI->eraseFromParent();
1608 Changed = true;
1609 continue;
1610 }
1611
Evan Cheng9bf3f8e2011-02-14 21:50:37 +00001612 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001613 SeenMoveImm = true;
Bill Wendlingca678352010-08-09 23:59:04 +00001614 } else {
Jim Grosbachedcb8682012-05-01 23:21:41 +00001615 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola048405f2012-10-15 18:21:07 +00001616 // optimizeExtInstr might have created new instructions after MI
1617 // and before the already incremented MII. Adjust MII so that the
1618 // next iteration sees the new instructions.
1619 MII = MI;
1620 ++MII;
Evan Cheng7f8ab6e2010-11-17 20:13:28 +00001621 if (SeenMoveImm)
Jim Grosbachedcb8682012-05-01 23:21:41 +00001622 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendlingca678352010-08-09 23:59:04 +00001623 }
Evan Cheng98196b42011-02-15 05:00:24 +00001624
Manman Ren5759d012012-08-02 00:56:42 +00001625 // Check whether MI is a load candidate for folding into a later
1626 // instruction. If MI is not a candidate, check whether we can fold an
1627 // earlier load into MI.
Lang Hames5dc14bd2014-04-02 22:59:58 +00001628 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1629 !FoldAsLoadDefCandidates.empty()) {
Lang Hames5dc14bd2014-04-02 22:59:58 +00001630 const MCInstrDesc &MIDesc = MI->getDesc();
1631 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
1632 ++i) {
1633 const MachineOperand &MOp = MI->getOperand(i);
1634 if (!MOp.isReg())
1635 continue;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001636 unsigned FoldAsLoadDefReg = MOp.getReg();
1637 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1638 // We need to fold load after optimizeCmpInstr, since
1639 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1640 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1641 // we need it for markUsesInDebugValueAsUndef().
1642 unsigned FoldedReg = FoldAsLoadDefReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001643 MachineInstr *DefMI = nullptr;
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001644 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
1645 FoldAsLoadDefReg,
Lang Hames5dc14bd2014-04-02 22:59:58 +00001646 DefMI);
1647 if (FoldMI) {
1648 // Update LocalMIs since we replaced MI with FoldMI and deleted
1649 // DefMI.
1650 DEBUG(dbgs() << "Replacing: " << *MI);
1651 DEBUG(dbgs() << " With: " << *FoldMI);
1652 LocalMIs.erase(MI);
1653 LocalMIs.erase(DefMI);
1654 LocalMIs.insert(FoldMI);
1655 MI->eraseFromParent();
1656 DefMI->eraseFromParent();
Lang Hames3c0dc2a2014-04-03 05:03:20 +00001657 MRI->markUsesInDebugValueAsUndef(FoldedReg);
1658 FoldAsLoadDefCandidates.erase(FoldedReg);
Lang Hames5dc14bd2014-04-02 22:59:58 +00001659 ++NumLoadFold;
1660 // MI is replaced with FoldMI.
1661 Changed = true;
1662 break;
1663 }
1664 }
Manman Ren5759d012012-08-02 00:56:42 +00001665 }
1666 }
Bill Wendlingca678352010-08-09 23:59:04 +00001667 }
1668 }
1669
1670 return Changed;
1671}
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001672
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001673ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001674 assert(Def->isCopy() && "Invalid definition");
1675 // Copy instruction are supposed to be: Def = Src.
1676 // If someone breaks this assumption, bad things will happen everywhere.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001677 assert(Def->getNumOperands() == 2 && "Invalid number of operands");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001678
1679 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1680 // If we look for a different subreg, it means we want a subreg of src.
Matt Arsenault30991562015-09-09 00:38:33 +00001681 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001682 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001683 // Otherwise, we want the whole source.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001684 const MachineOperand &Src = Def->getOperand(1);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001685 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001686}
1687
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001688ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001689 assert(Def->isBitcast() && "Invalid definition");
1690
1691 // Bail if there are effects that a plain copy will not expose.
1692 if (Def->hasUnmodeledSideEffects())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001693 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001694
1695 // Bitcasts with more than one def are not supported.
1696 if (Def->getDesc().getNumDefs() != 1)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001697 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001698 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1699 // If we look for a different subreg, it means we want a subreg of the src.
Matt Arsenault30991562015-09-09 00:38:33 +00001700 // Bails as we do not support composing subregs yet.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001701 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001702
Quentin Colombet03e43f82014-08-20 17:41:48 +00001703 unsigned SrcIdx = Def->getNumOperands();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001704 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1705 ++OpIdx) {
1706 const MachineOperand &MO = Def->getOperand(OpIdx);
1707 if (!MO.isReg() || !MO.getReg())
1708 continue;
Dan Gohmandab313e2015-12-10 00:37:51 +00001709 // Ignore dead implicit defs.
1710 if (MO.isImplicit() && MO.isDead())
1711 continue;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001712 assert(!MO.isDef() && "We should have skipped all the definitions by now");
1713 if (SrcIdx != EndOpIdx)
1714 // Multiple sources?
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001715 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001716 SrcIdx = OpIdx;
1717 }
Quentin Colombet03e43f82014-08-20 17:41:48 +00001718 const MachineOperand &Src = Def->getOperand(SrcIdx);
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001719 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001720}
1721
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001722ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001723 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1724 "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001725
1726 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001727 // If we are composing subregs, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001728 // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1729 // This should almost never happen as the SSA property is tracked at
1730 // the register level (as opposed to the subreg level).
1731 // I.e.,
1732 // Def.sub0 =
1733 // Def.sub1 =
1734 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1735 // Def. Thus, it must not be generated.
Quentin Colombet6d590d52014-07-01 16:23:44 +00001736 // However, some code could theoretically generates a single
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001737 // Def.sub0 (i.e, not defining the other subregs) and we would
1738 // have this case.
1739 // If we can ascertain (or force) that this never happens, we could
1740 // turn that into an assertion.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001741 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001742
Quentin Colombet03e43f82014-08-20 17:41:48 +00001743 if (!TII)
1744 // We could handle the REG_SEQUENCE here, but we do not want to
1745 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001746 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001747
1748 SmallVector<TargetInstrInfo::RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1749 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001750 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001751
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001752 // We are looking at:
1753 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1754 // Check if one of the operand defines the subreg we are interested in.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001755 for (auto &RegSeqInput : RegSeqInputRegs) {
1756 if (RegSeqInput.SubIdx == DefSubReg) {
1757 if (RegSeqInput.SubReg)
Matt Arsenault30991562015-09-09 00:38:33 +00001758 // Bail if we have to compose sub registers.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001759 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001760
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001761 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001762 }
1763 }
1764
1765 // If the subreg we are tracking is super-defined by another subreg,
1766 // we could follow this value. However, this would require to compose
1767 // the subreg and we do not do that for now.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001768 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001769}
1770
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001771ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
Quentin Colombet68962302014-08-21 00:19:16 +00001772 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1773 "Invalid definition");
1774
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001775 if (Def->getOperand(DefIdx).getSubReg())
Matt Arsenault30991562015-09-09 00:38:33 +00001776 // If we are composing subreg, bail out.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001777 // Same remark as getNextSourceFromRegSequence.
1778 // I.e., this may be turned into an assert.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001779 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001780
Quentin Colombet68962302014-08-21 00:19:16 +00001781 if (!TII)
1782 // We could handle the REG_SEQUENCE here, but we do not want to
1783 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001784 return ValueTrackerResult();
Quentin Colombet68962302014-08-21 00:19:16 +00001785
Quentin Colombet03e43f82014-08-20 17:41:48 +00001786 TargetInstrInfo::RegSubRegPair BaseReg;
1787 TargetInstrInfo::RegSubRegPairAndIdx InsertedReg;
Quentin Colombet68962302014-08-21 00:19:16 +00001788 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001789 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001790
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001791 // We are looking at:
1792 // Def = INSERT_SUBREG v0, v1, sub1
1793 // There are two cases:
1794 // 1. DefSubReg == sub1, get v1.
1795 // 2. DefSubReg != sub1, the value may be available through v0.
1796
Quentin Colombet03e43f82014-08-20 17:41:48 +00001797 // #1 Check if the inserted register matches the required sub index.
1798 if (InsertedReg.SubIdx == DefSubReg) {
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001799 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001800 }
1801 // #2 Otherwise, if the sub register we are looking for is not partial
1802 // defined by the inserted element, we can look through the main
1803 // register (v0).
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001804 const MachineOperand &MODef = Def->getOperand(DefIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001805 // If the result register (Def) and the base register (v0) do not
1806 // have the same register class or if we have to compose
Matt Arsenault30991562015-09-09 00:38:33 +00001807 // subregisters, bail out.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001808 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1809 BaseReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001810 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001811
Quentin Colombet03e43f82014-08-20 17:41:48 +00001812 // Get the TRI and check if the inserted sub-register overlaps with the
1813 // sub-register we are tracking.
1814 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001815 if (!TRI ||
1816 (TRI->getSubRegIndexLaneMask(DefSubReg) &
Quentin Colombet03e43f82014-08-20 17:41:48 +00001817 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)) != 0)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001818 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001819 // At this point, the value is available in v0 via the same subreg
1820 // we used for Def.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001821 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001822}
1823
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001824ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
Quentin Colombet67639df2014-08-20 23:13:02 +00001825 assert((Def->isExtractSubreg() ||
1826 Def->isExtractSubregLike()) && "Invalid definition");
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001827 // We are looking at:
1828 // Def = EXTRACT_SUBREG v0, sub0
1829
Matt Arsenault30991562015-09-09 00:38:33 +00001830 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001831 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1832 if (DefSubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001833 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001834
Quentin Colombet67639df2014-08-20 23:13:02 +00001835 if (!TII)
1836 // We could handle the EXTRACT_SUBREG here, but we do not want to
1837 // duplicate the code from the generic TII.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001838 return ValueTrackerResult();
Quentin Colombet67639df2014-08-20 23:13:02 +00001839
Quentin Colombet03e43f82014-08-20 17:41:48 +00001840 TargetInstrInfo::RegSubRegPairAndIdx ExtractSubregInputReg;
Quentin Colombet67639df2014-08-20 23:13:02 +00001841 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001842 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001843
Matt Arsenault30991562015-09-09 00:38:33 +00001844 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001845 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
Quentin Colombet03e43f82014-08-20 17:41:48 +00001846 if (ExtractSubregInputReg.SubReg)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001847 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001848 // Otherwise, the value is available in the v0.sub0.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001849 return ValueTrackerResult(ExtractSubregInputReg.Reg, ExtractSubregInputReg.SubIdx);
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001850}
1851
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001852ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001853 assert(Def->isSubregToReg() && "Invalid definition");
1854 // We are looking at:
1855 // Def = SUBREG_TO_REG Imm, v0, sub0
1856
Matt Arsenault30991562015-09-09 00:38:33 +00001857 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001858 // If DefSubReg != sub0, we would have to check that all the bits
1859 // we track are included in sub0 and if yes, we would have to
1860 // determine the right subreg in v0.
1861 if (DefSubReg != Def->getOperand(3).getImm())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001862 return ValueTrackerResult();
Matt Arsenault30991562015-09-09 00:38:33 +00001863 // Bail if we have to compose sub registers.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001864 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
1865 if (Def->getOperand(2).getSubReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001866 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001867
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001868 return ValueTrackerResult(Def->getOperand(2).getReg(),
1869 Def->getOperand(3).getImm());
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001870}
1871
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001872/// \brief Explore each PHI incoming operand and return its sources
1873ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
1874 assert(Def->isPHI() && "Invalid definition");
1875 ValueTrackerResult Res;
1876
Matt Arsenault30991562015-09-09 00:38:33 +00001877 // If we look for a different subreg, bail as we do not support composing
1878 // subregs yet.
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001879 if (Def->getOperand(0).getSubReg() != DefSubReg)
1880 return ValueTrackerResult();
1881
1882 // Return all register sources for PHI instructions.
1883 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
1884 auto &MO = Def->getOperand(i);
1885 assert(MO.isReg() && "Invalid PHI instruction");
1886 Res.addSource(MO.getReg(), MO.getSubReg());
1887 }
1888
1889 return Res;
1890}
1891
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001892ValueTrackerResult ValueTracker::getNextSourceImpl() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001893 assert(Def && "This method needs a valid definition");
1894
1895 assert(
1896 (DefIdx < Def->getDesc().getNumDefs() || Def->getDesc().isVariadic()) &&
1897 Def->getOperand(DefIdx).isDef() && "Invalid DefIdx");
1898 if (Def->isCopy())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001899 return getNextSourceFromCopy();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001900 if (Def->isBitcast())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001901 return getNextSourceFromBitcast();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001902 // All the remaining cases involve "complex" instructions.
Matt Arsenault30991562015-09-09 00:38:33 +00001903 // Bail if we did not ask for the advanced tracking.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001904 if (!UseAdvancedTracking)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001905 return ValueTrackerResult();
Quentin Colombet03e43f82014-08-20 17:41:48 +00001906 if (Def->isRegSequence() || Def->isRegSequenceLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001907 return getNextSourceFromRegSequence();
Quentin Colombet68962302014-08-21 00:19:16 +00001908 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001909 return getNextSourceFromInsertSubreg();
Quentin Colombet67639df2014-08-20 23:13:02 +00001910 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001911 return getNextSourceFromExtractSubreg();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001912 if (Def->isSubregToReg())
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001913 return getNextSourceFromSubregToReg();
Bruno Cardoso Lopes27fd0692015-08-19 18:53:36 +00001914 if (Def->isPHI())
1915 return getNextSourceFromPHI();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001916 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001917}
1918
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001919ValueTrackerResult ValueTracker::getNextSource() {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001920 // If we reach a point where we cannot move up in the use-def chain,
1921 // there is nothing we can get.
1922 if (!Def)
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001923 return ValueTrackerResult();
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001924
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001925 ValueTrackerResult Res = getNextSourceImpl();
1926 if (Res.isValid()) {
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001927 // Update definition, definition index, and subregister for the
1928 // next call of getNextSource.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001929 // Update the current register.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001930 bool OneRegSrc = Res.getNumSources() == 1;
1931 if (OneRegSrc)
1932 Reg = Res.getSrcReg(0);
1933 // Update the result before moving up in the use-def chain
1934 // with the instruction containing the last found sources.
1935 Res.setInst(Def);
1936
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001937 // If we can still move up in the use-def chain, move to the next
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001938 // definition.
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001939 if (!TargetRegisterInfo::isPhysicalRegister(Reg) && OneRegSrc) {
Quentin Colombet03e43f82014-08-20 17:41:48 +00001940 Def = MRI.getVRegDef(Reg);
1941 DefIdx = MRI.def_begin(Reg).getOperandNo();
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001942 DefSubReg = Res.getSrcSubReg(0);
1943 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001944 }
1945 }
1946 // If we end up here, this means we will not be able to find another source
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001947 // for the next iteration. Make sure any new call to getNextSource bails out
1948 // early by cutting the use-def chain.
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001949 Def = nullptr;
Bruno Cardoso Lopesf16ec122015-07-22 21:30:16 +00001950 return Res;
Quentin Colombet1111e6f2014-07-01 14:33:36 +00001951}