blob: eeee93a8895ee52ccf04543287f08b1fe969f3ea [file] [log] [blame]
Bill Wendling6cdb1ab2010-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 Chengd158fba2011-03-15 05:13:13 +000033//
Manman Ren247c5ab2012-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 Jones8293b7b2012-12-11 16:10:25 +000043// - Optimize Loads:
44//
45// Loads that can be folded into a later instruction. A load is foldable
46// if it loads to virtual registers and the virtual register defined has
47// a single use.
Quentin Colombet0df68422013-09-13 18:26:31 +000048//
49// - Optimize Copies and Bitcast:
50//
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 Wendling6cdb1ab2010-08-09 23:59:04 +000067//===----------------------------------------------------------------------===//
68
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000069#include "llvm/CodeGen/Passes.h"
Evan Chengc4af4632010-11-17 20:13:28 +000070#include "llvm/ADT/DenseMap.h"
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000071#include "llvm/ADT/SmallPtrSet.h"
Evan Chengc4af4632010-11-17 20:13:28 +000072#include "llvm/ADT/SmallSet.h"
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000073#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-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 Toppera1032b72012-12-17 03:56:00 +000078#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000079#include "llvm/Target/TargetInstrInfo.h"
80#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000081using namespace llvm;
82
Stephen Hinesdce4a402014-05-29 02:49:00 -070083#define DEBUG_TYPE "peephole-opt"
84
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000085// Optimize Extensions
86static cl::opt<bool>
87Aggressive("aggressive-ext-opt", cl::Hidden,
88 cl::desc("Aggressive extension optimization"));
89
Bill Wendling40a5eb12010-11-01 20:41:43 +000090static cl::opt<bool>
91DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
92 cl::desc("Disable the peephole optimizer"));
93
Bill Wendling69c5eb52010-08-27 20:39:09 +000094STATISTIC(NumReuse, "Number of extension results reused");
Evan Chengd158fba2011-03-15 05:13:13 +000095STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames3b26eb62012-02-25 00:46:38 +000096STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Rend7d003c2012-08-02 00:56:42 +000097STATISTIC(NumLoadFold, "Number of loads folded");
Jakob Stoklund Olesenf2c64ef2012-08-16 23:11:47 +000098STATISTIC(NumSelects, "Number of selects optimized");
Quentin Colombet0df68422013-09-13 18:26:31 +000099STATISTIC(NumCopiesBitcasts, "Number of copies/bitcasts optimized");
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000100
101namespace {
102 class PeepholeOptimizer : public MachineFunctionPass {
103 const TargetMachine *TM;
104 const TargetInstrInfo *TII;
105 MachineRegisterInfo *MRI;
106 MachineDominatorTree *DT; // Machine dominator tree
107
108 public:
109 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +0000110 PeepholeOptimizer() : MachineFunctionPass(ID) {
111 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
112 }
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000113
Stephen Hines36b56882014-04-23 16:57:46 -0700114 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000115
Stephen Hines36b56882014-04-23 16:57:46 -0700116 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000117 AU.setPreservesCFG();
118 MachineFunctionPass::getAnalysisUsage(AU);
119 if (Aggressive) {
120 AU.addRequired<MachineDominatorTree>();
121 AU.addPreserved<MachineDominatorTree>();
122 }
123 }
124
125 private:
Jim Grosbach39cc5132012-05-01 23:21:41 +0000126 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
127 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000128 SmallPtrSet<MachineInstr*, 8> &LocalMIs);
Jakob Stoklund Olesenf2c64ef2012-08-16 23:11:47 +0000129 bool optimizeSelect(MachineInstr *MI);
Quentin Colombet0df68422013-09-13 18:26:31 +0000130 bool optimizeCopyOrBitcast(MachineInstr *MI);
Evan Chengc4af4632010-11-17 20:13:28 +0000131 bool isMoveImmediate(MachineInstr *MI,
132 SmallSet<unsigned, 4> &ImmDefRegs,
133 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbach39cc5132012-05-01 23:21:41 +0000134 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Chengc4af4632010-11-17 20:13:28 +0000135 SmallSet<unsigned, 4> &ImmDefRegs,
136 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Stephen Hines36b56882014-04-23 16:57:46 -0700137 bool isLoadFoldable(MachineInstr *MI,
138 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000139 };
140}
141
142char PeepholeOptimizer::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000143char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000144INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
145 "Peephole Optimizations", false, false)
146INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
147INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersonce665bd2010-10-07 22:25:06 +0000148 "Peephole Optimizations", false, false)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000149
Jim Grosbach39cc5132012-05-01 23:21:41 +0000150/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000151/// a single register and writes a single register and it does not modify the
152/// source, and if the source value is preserved as a sub-register of the
153/// result, then replace all reachable uses of the source with the subreg of the
154/// result.
Andrew Trick1df91b02012-02-08 21:22:43 +0000155///
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000156/// Do not generate an EXTRACT that is used only in a debug use, as this changes
157/// the code. Since this code does not currently share EXTRACTs, just ignore all
158/// debug uses.
159bool PeepholeOptimizer::
Jim Grosbach39cc5132012-05-01 23:21:41 +0000160optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000161 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000162 unsigned SrcReg, DstReg, SubIdx;
163 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
164 return false;
Andrew Trick1df91b02012-02-08 21:22:43 +0000165
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000166 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
167 TargetRegisterInfo::isPhysicalRegister(SrcReg))
168 return false;
169
Jakob Stoklund Olesend8d02792012-06-19 21:10:18 +0000170 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000171 // No other uses.
172 return false;
173
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000174 // Ensure DstReg can get a register class that actually supports
175 // sub-registers. Don't change the class until we commit.
176 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
177 DstRC = TM->getRegisterInfo()->getSubClassWithSubReg(DstRC, SubIdx);
178 if (!DstRC)
179 return false;
180
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000181 // The ext instr may be operating on a sub-register of SrcReg as well.
182 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
183 // register.
184 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
185 // SrcReg:SubIdx should be replaced.
186 bool UseSrcSubIdx = TM->getRegisterInfo()->
Stephen Hinesdce4a402014-05-29 02:49:00 -0700187 getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000188
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000189 // The source has other uses. See if we can replace the other uses with use of
190 // the result of the extension.
191 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Stephen Hines36b56882014-04-23 16:57:46 -0700192 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
193 ReachedBBs.insert(UI.getParent());
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000194
195 // Uses that are in the same BB of uses of the result of the instruction.
196 SmallVector<MachineOperand*, 8> Uses;
197
198 // Uses that the result of the instruction can reach.
199 SmallVector<MachineOperand*, 8> ExtendedUses;
200
201 bool ExtendLife = true;
Stephen Hines36b56882014-04-23 16:57:46 -0700202 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
203 MachineInstr *UseMI = UseMO.getParent();
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000204 if (UseMI == MI)
205 continue;
206
207 if (UseMI->isPHI()) {
208 ExtendLife = false;
209 continue;
210 }
211
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000212 // Only accept uses of SrcReg:SubIdx.
213 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
214 continue;
215
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000216 // It's an error to translate this:
217 //
218 // %reg1025 = <sext> %reg1024
219 // ...
220 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
221 //
222 // into this:
223 //
224 // %reg1025 = <sext> %reg1024
225 // ...
226 // %reg1027 = COPY %reg1025:4
227 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
228 //
229 // The problem here is that SUBREG_TO_REG is there to assert that an
230 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
231 // the COPY here, it will give us the value after the <sext>, not the
232 // original value of %reg1024 before <sext>.
233 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
234 continue;
235
236 MachineBasicBlock *UseMBB = UseMI->getParent();
237 if (UseMBB == MBB) {
238 // Local uses that come after the extension.
239 if (!LocalMIs.count(UseMI))
240 Uses.push_back(&UseMO);
241 } else if (ReachedBBs.count(UseMBB)) {
242 // Non-local uses where the result of the extension is used. Always
243 // replace these unless it's a PHI.
244 Uses.push_back(&UseMO);
245 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
246 // We may want to extend the live range of the extension result in order
247 // to replace these uses.
248 ExtendedUses.push_back(&UseMO);
249 } else {
250 // Both will be live out of the def MBB anyway. Don't extend live range of
251 // the extension result.
252 ExtendLife = false;
253 break;
254 }
255 }
256
257 if (ExtendLife && !ExtendedUses.empty())
258 // Extend the liveness of the extension result.
259 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
260 std::back_inserter(Uses));
261
262 // Now replace all uses.
263 bool Changed = false;
264 if (!Uses.empty()) {
265 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
266
267 // Look for PHI uses of the extended result, we don't want to extend the
268 // liveness of a PHI input. It breaks all kinds of assumptions down
269 // stream. A PHI use is expected to be the kill of its source values.
Stephen Hines36b56882014-04-23 16:57:46 -0700270 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
271 if (UI.isPHI())
272 PHIBBs.insert(UI.getParent());
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000273
274 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
275 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
276 MachineOperand *UseMO = Uses[i];
277 MachineInstr *UseMI = UseMO->getParent();
278 MachineBasicBlock *UseMBB = UseMI->getParent();
279 if (PHIBBs.count(UseMBB))
280 continue;
281
Lang Hamesc69cbd02012-02-25 02:01:00 +0000282 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000283 if (!Changed) {
Lang Hamesc69cbd02012-02-25 02:01:00 +0000284 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000285 MRI->constrainRegClass(DstReg, DstRC);
286 }
Lang Hamesc69cbd02012-02-25 02:01:00 +0000287
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000288 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000289 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
290 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000291 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000292 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
293 if (UseSrcSubIdx) {
294 Copy->getOperand(0).setSubReg(SubIdx);
295 Copy->getOperand(0).setIsUndef();
296 }
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000297 UseMO->setReg(NewVR);
298 ++NumReuse;
299 Changed = true;
300 }
301 }
302
303 return Changed;
304}
305
Jim Grosbach39cc5132012-05-01 23:21:41 +0000306/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000307/// instruction it's comparing against all ready sets (or could be modified to
308/// set) the same flag as the compare, then we can remove the comparison and use
309/// the flag from the previous instruction.
Jim Grosbach39cc5132012-05-01 23:21:41 +0000310bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chengd158fba2011-03-15 05:13:13 +0000311 MachineBasicBlock *MBB) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000312 // If this instruction is a comparison against zero and isn't comparing a
313 // physical register, we can try to optimize it.
Manman Rende7266c2012-06-29 21:33:59 +0000314 unsigned SrcReg, SrcReg2;
Gabor Greif04ac81d2010-09-21 12:01:15 +0000315 int CmpMask, CmpValue;
Manman Rende7266c2012-06-29 21:33:59 +0000316 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
317 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
318 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000319 return false;
320
Bill Wendlinga6556862010-09-11 00:13:50 +0000321 // Attempt to optimize the comparison instruction.
Manman Rende7266c2012-06-29 21:33:59 +0000322 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chengd158fba2011-03-15 05:13:13 +0000323 ++NumCmps;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000324 return true;
325 }
326
327 return false;
328}
329
Jakob Stoklund Olesenf2c64ef2012-08-16 23:11:47 +0000330/// Optimize a select instruction.
331bool PeepholeOptimizer::optimizeSelect(MachineInstr *MI) {
332 unsigned TrueOp = 0;
333 unsigned FalseOp = 0;
334 bool Optimizable = false;
335 SmallVector<MachineOperand, 4> Cond;
336 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
337 return false;
338 if (!Optimizable)
339 return false;
340 if (!TII->optimizeSelect(MI))
341 return false;
342 MI->eraseFromParent();
343 ++NumSelects;
344 return true;
345}
346
Quentin Colombet0df68422013-09-13 18:26:31 +0000347/// \brief Check if the registers defined by the pair (RegisterClass, SubReg)
348/// share the same register file.
349static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
350 const TargetRegisterClass *DefRC,
351 unsigned DefSubReg,
352 const TargetRegisterClass *SrcRC,
353 unsigned SrcSubReg) {
354 // Same register class.
355 if (DefRC == SrcRC)
356 return true;
357
358 // Both operands are sub registers. Check if they share a register class.
359 unsigned SrcIdx, DefIdx;
360 if (SrcSubReg && DefSubReg)
361 return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
Stephen Hinesdce4a402014-05-29 02:49:00 -0700362 SrcIdx, DefIdx) != nullptr;
Quentin Colombet0df68422013-09-13 18:26:31 +0000363 // At most one of the register is a sub register, make it Src to avoid
364 // duplicating the test.
365 if (!SrcSubReg) {
366 std::swap(DefSubReg, SrcSubReg);
367 std::swap(DefRC, SrcRC);
368 }
369
370 // One of the register is a sub register, check if we can get a superclass.
371 if (SrcSubReg)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700372 return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
Quentin Colombet0df68422013-09-13 18:26:31 +0000373 // Plain copy.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700374 return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
Quentin Colombet0df68422013-09-13 18:26:31 +0000375}
376
377/// \brief Get the index of the definition and source for \p Copy
378/// instruction.
379/// \pre Copy.isCopy() or Copy.isBitcast().
380/// \return True if the Copy instruction has only one register source
381/// and one register definition. Otherwise, \p DefIdx and \p SrcIdx
382/// are invalid.
383static bool getCopyOrBitcastDefUseIdx(const MachineInstr &Copy,
384 unsigned &DefIdx, unsigned &SrcIdx) {
385 assert((Copy.isCopy() || Copy.isBitcast()) && "Wrong operation type.");
386 if (Copy.isCopy()) {
387 // Copy instruction are supposed to be: Def = Src.
388 if (Copy.getDesc().getNumOperands() != 2)
389 return false;
390 DefIdx = 0;
391 SrcIdx = 1;
392 assert(Copy.getOperand(DefIdx).isDef() && "Use comes before def!");
393 return true;
394 }
395 // Bitcast case.
396 // Bitcasts with more than one def are not supported.
397 if (Copy.getDesc().getNumDefs() != 1)
398 return false;
399 // Initialize SrcIdx to an undefined operand.
400 SrcIdx = Copy.getDesc().getNumOperands();
401 for (unsigned OpIdx = 0, EndOpIdx = SrcIdx; OpIdx != EndOpIdx; ++OpIdx) {
402 const MachineOperand &MO = Copy.getOperand(OpIdx);
403 if (!MO.isReg() || !MO.getReg())
404 continue;
405 if (MO.isDef())
406 DefIdx = OpIdx;
407 else if (SrcIdx != EndOpIdx)
408 // Multiple sources?
409 return false;
410 SrcIdx = OpIdx;
411 }
412 return true;
413}
414
415/// \brief Optimize a copy or bitcast instruction to avoid cross
416/// register bank copy. The optimization looks through a chain of
417/// copies and try to find a source that has a compatible register
418/// class.
419/// Two register classes are considered to be compatible if they share
420/// the same register bank.
421/// New copies issued by this optimization are register allocator
422/// friendly. This optimization does not remove any copy as it may
423/// overconstraint the register allocator, but replaces some when
424/// possible.
425/// \pre \p MI is a Copy (MI->isCopy() is true)
426/// \return True, when \p MI has been optimized. In that case, \p MI has
427/// been removed from its parent.
428bool PeepholeOptimizer::optimizeCopyOrBitcast(MachineInstr *MI) {
429 unsigned DefIdx, SrcIdx;
430 if (!MI || !getCopyOrBitcastDefUseIdx(*MI, DefIdx, SrcIdx))
431 return false;
432
433 const MachineOperand &MODef = MI->getOperand(DefIdx);
434 assert(MODef.isReg() && "Copies must be between registers.");
435 unsigned Def = MODef.getReg();
436
437 if (TargetRegisterInfo::isPhysicalRegister(Def))
438 return false;
439
440 const TargetRegisterClass *DefRC = MRI->getRegClass(Def);
441 unsigned DefSubReg = MODef.getSubReg();
442
443 unsigned Src;
444 unsigned SrcSubReg;
445 bool ShouldRewrite = false;
446 MachineInstr *Copy = MI;
447 const TargetRegisterInfo &TRI = *TM->getRegisterInfo();
448
449 // Follow the chain of copies until we reach the top or find a
450 // more suitable source.
451 do {
452 unsigned CopyDefIdx, CopySrcIdx;
453 if (!getCopyOrBitcastDefUseIdx(*Copy, CopyDefIdx, CopySrcIdx))
454 break;
455 const MachineOperand &MO = Copy->getOperand(CopySrcIdx);
456 assert(MO.isReg() && "Copies must be between registers.");
457 Src = MO.getReg();
458
459 if (TargetRegisterInfo::isPhysicalRegister(Src))
460 break;
461
462 const TargetRegisterClass *SrcRC = MRI->getRegClass(Src);
463 SrcSubReg = MO.getSubReg();
464
465 // If this source does not incur a cross register bank copy, use it.
466 ShouldRewrite = shareSameRegisterFile(TRI, DefRC, DefSubReg, SrcRC,
467 SrcSubReg);
468 // Follow the chain of copies: get the definition of Src.
469 Copy = MRI->getVRegDef(Src);
470 } while (!ShouldRewrite && Copy && (Copy->isCopy() || Copy->isBitcast()));
471
472 // If we did not find a more suitable source, there is nothing to optimize.
473 if (!ShouldRewrite || Src == MI->getOperand(SrcIdx).getReg())
474 return false;
475
476 // Rewrite the copy to avoid a cross register bank penalty.
477 unsigned NewVR = TargetRegisterInfo::isPhysicalRegister(Def) ? Def :
478 MRI->createVirtualRegister(DefRC);
479 MachineInstr *NewCopy = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
480 TII->get(TargetOpcode::COPY), NewVR)
481 .addReg(Src, 0, SrcSubReg);
482 NewCopy->getOperand(0).setSubReg(DefSubReg);
483
484 MRI->replaceRegWith(Def, NewVR);
485 MRI->clearKillFlags(NewVR);
486 MI->eraseFromParent();
487 ++NumCopiesBitcasts;
488 return true;
489}
490
Manman Rend7d003c2012-08-02 00:56:42 +0000491/// isLoadFoldable - Check whether MI is a candidate for folding into a later
492/// instruction. We only fold loads to virtual registers and the virtual
493/// register defined has a single use.
Stephen Hines36b56882014-04-23 16:57:46 -0700494bool PeepholeOptimizer::isLoadFoldable(
495 MachineInstr *MI,
496 SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
Manman Ren127eea82012-08-02 19:37:32 +0000497 if (!MI->canFoldAsLoad() || !MI->mayLoad())
498 return false;
499 const MCInstrDesc &MCID = MI->getDesc();
500 if (MCID.getNumDefs() != 1)
501 return false;
502
503 unsigned Reg = MI->getOperand(0).getReg();
Stephen Hines36b56882014-04-23 16:57:46 -0700504 // To reduce compilation time, we check MRI->hasOneNonDBGUse when inserting
Manman Ren127eea82012-08-02 19:37:32 +0000505 // loads. It should be checked when processing uses of the load, since
506 // uses can be removed during peephole.
507 if (!MI->getOperand(0).getSubReg() &&
508 TargetRegisterInfo::isVirtualRegister(Reg) &&
Stephen Hines36b56882014-04-23 16:57:46 -0700509 MRI->hasOneNonDBGUse(Reg)) {
510 FoldAsLoadDefCandidates.insert(Reg);
Manman Ren127eea82012-08-02 19:37:32 +0000511 return true;
Manman Rend7d003c2012-08-02 00:56:42 +0000512 }
513 return false;
514}
515
Evan Chengc4af4632010-11-17 20:13:28 +0000516bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
517 SmallSet<unsigned, 4> &ImmDefRegs,
518 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Chenge837dea2011-06-28 19:10:37 +0000519 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000520 if (!MI->isMoveImmediate())
Evan Chengc4af4632010-11-17 20:13:28 +0000521 return false;
Evan Chenge837dea2011-06-28 19:10:37 +0000522 if (MCID.getNumDefs() != 1)
Evan Chengc4af4632010-11-17 20:13:28 +0000523 return false;
524 unsigned Reg = MI->getOperand(0).getReg();
525 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
526 ImmDefMIs.insert(std::make_pair(Reg, MI));
527 ImmDefRegs.insert(Reg);
528 return true;
529 }
Andrew Trick1df91b02012-02-08 21:22:43 +0000530
Evan Chengc4af4632010-11-17 20:13:28 +0000531 return false;
532}
533
Jim Grosbach39cc5132012-05-01 23:21:41 +0000534/// foldImmediate - Try folding register operands that are defined by move
Evan Chengc4af4632010-11-17 20:13:28 +0000535/// immediate instructions, i.e. a trivial constant folding optimization, if
536/// and only if the def and use are in the same BB.
Jim Grosbach39cc5132012-05-01 23:21:41 +0000537bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Chengc4af4632010-11-17 20:13:28 +0000538 SmallSet<unsigned, 4> &ImmDefRegs,
539 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
540 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
541 MachineOperand &MO = MI->getOperand(i);
542 if (!MO.isReg() || MO.isDef())
543 continue;
544 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000545 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengc4af4632010-11-17 20:13:28 +0000546 continue;
547 if (ImmDefRegs.count(Reg) == 0)
548 continue;
549 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
550 assert(II != ImmDefMIs.end());
551 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
552 ++NumImmFold;
553 return true;
554 }
555 }
556 return false;
557}
558
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000559bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
Stephen Hines36b56882014-04-23 16:57:46 -0700560 if (skipOptnoneFunction(*MF.getFunction()))
561 return false;
562
Craig Toppera1032b72012-12-17 03:56:00 +0000563 DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
564 DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
565
Evan Chengeb96a2f2010-11-15 21:20:45 +0000566 if (DisablePeephole)
567 return false;
Andrew Trick1df91b02012-02-08 21:22:43 +0000568
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000569 TM = &MF.getTarget();
570 TII = TM->getInstrInfo();
571 MRI = &MF.getRegInfo();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700572 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000573
574 bool Changed = false;
575
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000576 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
577 MachineBasicBlock *MBB = &*I;
Andrew Trick1df91b02012-02-08 21:22:43 +0000578
Evan Chengc4af4632010-11-17 20:13:28 +0000579 bool SeenMoveImm = false;
Stephen Hines36b56882014-04-23 16:57:46 -0700580 SmallPtrSet<MachineInstr*, 8> LocalMIs;
581 SmallSet<unsigned, 4> ImmDefRegs;
582 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
583 SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000584
585 for (MachineBasicBlock::iterator
Bill Wendling220e2402010-09-10 21:55:43 +0000586 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Chengcf75ab52011-02-14 21:50:37 +0000587 MachineInstr *MI = &*MII;
Jakob Stoklund Olesencabc0692012-08-17 14:38:59 +0000588 // We may be erasing MI below, increment MII now.
589 ++MII;
Evan Chengeb96a2f2010-11-15 21:20:45 +0000590 LocalMIs.insert(MI);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000591
Stephen Hines36b56882014-04-23 16:57:46 -0700592 // Skip debug values. They should not affect this peephole optimization.
593 if (MI->isDebugValue())
594 continue;
595
Manman Rend7d003c2012-08-02 00:56:42 +0000596 // If there exists an instruction which belongs to the following
Stephen Hines36b56882014-04-23 16:57:46 -0700597 // categories, we will discard the load candidates.
598 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() ||
599 MI->isKill() || MI->isInlineAsm() ||
Evan Chengcf75ab52011-02-14 21:50:37 +0000600 MI->hasUnmodeledSideEffects()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700601 FoldAsLoadDefCandidates.clear();
Evan Chengeb96a2f2010-11-15 21:20:45 +0000602 continue;
Evan Chengcf75ab52011-02-14 21:50:37 +0000603 }
Manman Rend7d003c2012-08-02 00:56:42 +0000604 if (MI->mayStore() || MI->isCall())
Stephen Hines36b56882014-04-23 16:57:46 -0700605 FoldAsLoadDefCandidates.clear();
Evan Chengeb96a2f2010-11-15 21:20:45 +0000606
Quentin Colombet0df68422013-09-13 18:26:31 +0000607 if (((MI->isBitcast() || MI->isCopy()) && optimizeCopyOrBitcast(MI)) ||
Jakob Stoklund Olesenf2c64ef2012-08-16 23:11:47 +0000608 (MI->isCompare() && optimizeCmpInstr(MI, MBB)) ||
609 (MI->isSelect() && optimizeSelect(MI))) {
610 // MI is deleted.
611 LocalMIs.erase(MI);
612 Changed = true;
Jakob Stoklund Olesenf2c64ef2012-08-16 23:11:47 +0000613 continue;
Evan Chengcf75ab52011-02-14 21:50:37 +0000614 }
615
616 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Chengc4af4632010-11-17 20:13:28 +0000617 SeenMoveImm = true;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000618 } else {
Jim Grosbach39cc5132012-05-01 23:21:41 +0000619 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Rafael Espindola10ad98b2012-10-15 18:21:07 +0000620 // optimizeExtInstr might have created new instructions after MI
621 // and before the already incremented MII. Adjust MII so that the
622 // next iteration sees the new instructions.
623 MII = MI;
624 ++MII;
Evan Chengc4af4632010-11-17 20:13:28 +0000625 if (SeenMoveImm)
Jim Grosbach39cc5132012-05-01 23:21:41 +0000626 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000627 }
Evan Cheng326d9762011-02-15 05:00:24 +0000628
Manman Rend7d003c2012-08-02 00:56:42 +0000629 // Check whether MI is a load candidate for folding into a later
630 // instruction. If MI is not a candidate, check whether we can fold an
631 // earlier load into MI.
Stephen Hines36b56882014-04-23 16:57:46 -0700632 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
633 !FoldAsLoadDefCandidates.empty()) {
634 const MCInstrDesc &MIDesc = MI->getDesc();
635 for (unsigned i = MIDesc.getNumDefs(); i != MIDesc.getNumOperands();
636 ++i) {
637 const MachineOperand &MOp = MI->getOperand(i);
638 if (!MOp.isReg())
639 continue;
640 unsigned FoldAsLoadDefReg = MOp.getReg();
641 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
642 // We need to fold load after optimizeCmpInstr, since
643 // optimizeCmpInstr can enable folding by converting SUB to CMP.
644 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
645 // we need it for markUsesInDebugValueAsUndef().
646 unsigned FoldedReg = FoldAsLoadDefReg;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700647 MachineInstr *DefMI = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700648 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
649 FoldAsLoadDefReg,
650 DefMI);
651 if (FoldMI) {
652 // Update LocalMIs since we replaced MI with FoldMI and deleted
653 // DefMI.
654 DEBUG(dbgs() << "Replacing: " << *MI);
655 DEBUG(dbgs() << " With: " << *FoldMI);
656 LocalMIs.erase(MI);
657 LocalMIs.erase(DefMI);
658 LocalMIs.insert(FoldMI);
659 MI->eraseFromParent();
660 DefMI->eraseFromParent();
661 MRI->markUsesInDebugValueAsUndef(FoldedReg);
662 FoldAsLoadDefCandidates.erase(FoldedReg);
663 ++NumLoadFold;
664 // MI is replaced with FoldMI.
665 Changed = true;
666 break;
667 }
668 }
Manman Rend7d003c2012-08-02 00:56:42 +0000669 }
670 }
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000671 }
672 }
673
674 return Changed;
675}