blob: 6bc7e37e3d879a3752a0638bc9ece62ad8f402ac [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//
Evan Chengd158fba2011-03-15 05:13:13 +000043// - Optimize Bitcast pairs:
44//
45// v1 = bitcast v0
46// v2 = bitcast v1
47// = v2
48// =>
49// v1 = bitcast v0
50// = v0
Andrew Trick1df91b02012-02-08 21:22:43 +000051//
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000052//===----------------------------------------------------------------------===//
53
54#define DEBUG_TYPE "peephole-opt"
55#include "llvm/CodeGen/Passes.h"
56#include "llvm/CodeGen/MachineDominators.h"
57#include "llvm/CodeGen/MachineInstrBuilder.h"
58#include "llvm/CodeGen/MachineRegisterInfo.h"
59#include "llvm/Target/TargetInstrInfo.h"
60#include "llvm/Target/TargetRegisterInfo.h"
61#include "llvm/Support/CommandLine.h"
Evan Chengc4af4632010-11-17 20:13:28 +000062#include "llvm/ADT/DenseMap.h"
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000063#include "llvm/ADT/SmallPtrSet.h"
Evan Chengc4af4632010-11-17 20:13:28 +000064#include "llvm/ADT/SmallSet.h"
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000065#include "llvm/ADT/Statistic.h"
66using namespace llvm;
67
68// Optimize Extensions
69static cl::opt<bool>
70Aggressive("aggressive-ext-opt", cl::Hidden,
71 cl::desc("Aggressive extension optimization"));
72
Bill Wendling40a5eb12010-11-01 20:41:43 +000073static cl::opt<bool>
74DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
75 cl::desc("Disable the peephole optimizer"));
76
Bill Wendling69c5eb52010-08-27 20:39:09 +000077STATISTIC(NumReuse, "Number of extension results reused");
Evan Chengd158fba2011-03-15 05:13:13 +000078STATISTIC(NumBitcasts, "Number of bitcasts eliminated");
79STATISTIC(NumCmps, "Number of compares eliminated");
Lang Hames3b26eb62012-02-25 00:46:38 +000080STATISTIC(NumImmFold, "Number of move immediate folded");
Manman Rend7d003c2012-08-02 00:56:42 +000081STATISTIC(NumLoadFold, "Number of loads folded");
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000082
83namespace {
84 class PeepholeOptimizer : public MachineFunctionPass {
85 const TargetMachine *TM;
86 const TargetInstrInfo *TII;
87 MachineRegisterInfo *MRI;
88 MachineDominatorTree *DT; // Machine dominator tree
89
90 public:
91 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000092 PeepholeOptimizer() : MachineFunctionPass(ID) {
93 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
94 }
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000095
96 virtual bool runOnMachineFunction(MachineFunction &MF);
97
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.setPreservesCFG();
100 MachineFunctionPass::getAnalysisUsage(AU);
101 if (Aggressive) {
102 AU.addRequired<MachineDominatorTree>();
103 AU.addPreserved<MachineDominatorTree>();
104 }
105 }
106
107 private:
Jim Grosbach39cc5132012-05-01 23:21:41 +0000108 bool optimizeBitcastInstr(MachineInstr *MI, MachineBasicBlock *MBB);
109 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
110 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000111 SmallPtrSet<MachineInstr*, 8> &LocalMIs);
Evan Chengc4af4632010-11-17 20:13:28 +0000112 bool isMoveImmediate(MachineInstr *MI,
113 SmallSet<unsigned, 4> &ImmDefRegs,
114 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Jim Grosbach39cc5132012-05-01 23:21:41 +0000115 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Chengc4af4632010-11-17 20:13:28 +0000116 SmallSet<unsigned, 4> &ImmDefRegs,
117 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
Manman Rend7d003c2012-08-02 00:56:42 +0000118 bool isLoadFoldable(MachineInstr *MI, unsigned &FoldAsLoadDefReg);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000119 };
120}
121
122char PeepholeOptimizer::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000123char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000124INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
125 "Peephole Optimizations", false, false)
126INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
127INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersonce665bd2010-10-07 22:25:06 +0000128 "Peephole Optimizations", false, false)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000129
Jim Grosbach39cc5132012-05-01 23:21:41 +0000130/// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000131/// a single register and writes a single register and it does not modify the
132/// source, and if the source value is preserved as a sub-register of the
133/// result, then replace all reachable uses of the source with the subreg of the
134/// result.
Andrew Trick1df91b02012-02-08 21:22:43 +0000135///
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000136/// Do not generate an EXTRACT that is used only in a debug use, as this changes
137/// the code. Since this code does not currently share EXTRACTs, just ignore all
138/// debug uses.
139bool PeepholeOptimizer::
Jim Grosbach39cc5132012-05-01 23:21:41 +0000140optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000141 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000142 unsigned SrcReg, DstReg, SubIdx;
143 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
144 return false;
Andrew Trick1df91b02012-02-08 21:22:43 +0000145
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000146 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
147 TargetRegisterInfo::isPhysicalRegister(SrcReg))
148 return false;
149
Jakob Stoklund Olesend8d02792012-06-19 21:10:18 +0000150 if (MRI->hasOneNonDBGUse(SrcReg))
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000151 // No other uses.
152 return false;
153
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000154 // Ensure DstReg can get a register class that actually supports
155 // sub-registers. Don't change the class until we commit.
156 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
157 DstRC = TM->getRegisterInfo()->getSubClassWithSubReg(DstRC, SubIdx);
158 if (!DstRC)
159 return false;
160
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000161 // The ext instr may be operating on a sub-register of SrcReg as well.
162 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
163 // register.
164 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
165 // SrcReg:SubIdx should be replaced.
166 bool UseSrcSubIdx = TM->getRegisterInfo()->
167 getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != 0;
168
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000169 // The source has other uses. See if we can replace the other uses with use of
170 // the result of the extension.
171 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
Jakob Stoklund Olesend8d02792012-06-19 21:10:18 +0000172 for (MachineRegisterInfo::use_nodbg_iterator
173 UI = MRI->use_nodbg_begin(DstReg), UE = MRI->use_nodbg_end();
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000174 UI != UE; ++UI)
175 ReachedBBs.insert(UI->getParent());
176
177 // Uses that are in the same BB of uses of the result of the instruction.
178 SmallVector<MachineOperand*, 8> Uses;
179
180 // Uses that the result of the instruction can reach.
181 SmallVector<MachineOperand*, 8> ExtendedUses;
182
183 bool ExtendLife = true;
Jakob Stoklund Olesend8d02792012-06-19 21:10:18 +0000184 for (MachineRegisterInfo::use_nodbg_iterator
185 UI = MRI->use_nodbg_begin(SrcReg), UE = MRI->use_nodbg_end();
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000186 UI != UE; ++UI) {
187 MachineOperand &UseMO = UI.getOperand();
188 MachineInstr *UseMI = &*UI;
189 if (UseMI == MI)
190 continue;
191
192 if (UseMI->isPHI()) {
193 ExtendLife = false;
194 continue;
195 }
196
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000197 // Only accept uses of SrcReg:SubIdx.
198 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
199 continue;
200
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000201 // It's an error to translate this:
202 //
203 // %reg1025 = <sext> %reg1024
204 // ...
205 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
206 //
207 // into this:
208 //
209 // %reg1025 = <sext> %reg1024
210 // ...
211 // %reg1027 = COPY %reg1025:4
212 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
213 //
214 // The problem here is that SUBREG_TO_REG is there to assert that an
215 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
216 // the COPY here, it will give us the value after the <sext>, not the
217 // original value of %reg1024 before <sext>.
218 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
219 continue;
220
221 MachineBasicBlock *UseMBB = UseMI->getParent();
222 if (UseMBB == MBB) {
223 // Local uses that come after the extension.
224 if (!LocalMIs.count(UseMI))
225 Uses.push_back(&UseMO);
226 } else if (ReachedBBs.count(UseMBB)) {
227 // Non-local uses where the result of the extension is used. Always
228 // replace these unless it's a PHI.
229 Uses.push_back(&UseMO);
230 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
231 // We may want to extend the live range of the extension result in order
232 // to replace these uses.
233 ExtendedUses.push_back(&UseMO);
234 } else {
235 // Both will be live out of the def MBB anyway. Don't extend live range of
236 // the extension result.
237 ExtendLife = false;
238 break;
239 }
240 }
241
242 if (ExtendLife && !ExtendedUses.empty())
243 // Extend the liveness of the extension result.
244 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
245 std::back_inserter(Uses));
246
247 // Now replace all uses.
248 bool Changed = false;
249 if (!Uses.empty()) {
250 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
251
252 // Look for PHI uses of the extended result, we don't want to extend the
253 // liveness of a PHI input. It breaks all kinds of assumptions down
254 // stream. A PHI use is expected to be the kill of its source values.
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000255 for (MachineRegisterInfo::use_nodbg_iterator
Jakob Stoklund Olesend8d02792012-06-19 21:10:18 +0000256 UI = MRI->use_nodbg_begin(DstReg), UE = MRI->use_nodbg_end();
257 UI != UE; ++UI)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000258 if (UI->isPHI())
259 PHIBBs.insert(UI->getParent());
260
261 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
262 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
263 MachineOperand *UseMO = Uses[i];
264 MachineInstr *UseMI = UseMO->getParent();
265 MachineBasicBlock *UseMBB = UseMI->getParent();
266 if (PHIBBs.count(UseMBB))
267 continue;
268
Lang Hamesc69cbd02012-02-25 02:01:00 +0000269 // About to add uses of DstReg, clear DstReg's kill flags.
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000270 if (!Changed) {
Lang Hamesc69cbd02012-02-25 02:01:00 +0000271 MRI->clearKillFlags(DstReg);
Jakob Stoklund Olesen418a3632012-05-20 18:42:55 +0000272 MRI->constrainRegClass(DstReg, DstRC);
273 }
Lang Hamesc69cbd02012-02-25 02:01:00 +0000274
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000275 unsigned NewVR = MRI->createVirtualRegister(RC);
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000276 MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
277 TII->get(TargetOpcode::COPY), NewVR)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000278 .addReg(DstReg, 0, SubIdx);
Jakob Stoklund Olesen71642882012-06-19 21:14:34 +0000279 // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
280 if (UseSrcSubIdx) {
281 Copy->getOperand(0).setSubReg(SubIdx);
282 Copy->getOperand(0).setIsUndef();
283 }
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000284 UseMO->setReg(NewVR);
285 ++NumReuse;
286 Changed = true;
287 }
288 }
289
290 return Changed;
291}
292
Jim Grosbach39cc5132012-05-01 23:21:41 +0000293/// optimizeBitcastInstr - If the instruction is a bitcast instruction A that
Evan Chengd158fba2011-03-15 05:13:13 +0000294/// cannot be optimized away during isel (e.g. ARM::VMOVSR, which bitcast
295/// a value cross register classes), and the source is defined by another
296/// bitcast instruction B. And if the register class of source of B matches
297/// the register class of instruction A, then it is legal to replace all uses
298/// of the def of A with source of B. e.g.
299/// %vreg0<def> = VMOVSR %vreg1
300/// %vreg3<def> = VMOVRS %vreg0
301/// Replace all uses of vreg3 with vreg1.
302
Jim Grosbach39cc5132012-05-01 23:21:41 +0000303bool PeepholeOptimizer::optimizeBitcastInstr(MachineInstr *MI,
Evan Chengd158fba2011-03-15 05:13:13 +0000304 MachineBasicBlock *MBB) {
305 unsigned NumDefs = MI->getDesc().getNumDefs();
306 unsigned NumSrcs = MI->getDesc().getNumOperands() - NumDefs;
307 if (NumDefs != 1)
308 return false;
309
310 unsigned Def = 0;
311 unsigned Src = 0;
312 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
313 const MachineOperand &MO = MI->getOperand(i);
314 if (!MO.isReg())
315 continue;
316 unsigned Reg = MO.getReg();
317 if (!Reg)
318 continue;
319 if (MO.isDef())
320 Def = Reg;
321 else if (Src)
322 // Multiple sources?
323 return false;
324 else
325 Src = Reg;
326 }
327
328 assert(Def && Src && "Malformed bitcast instruction!");
329
330 MachineInstr *DefMI = MRI->getVRegDef(Src);
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000331 if (!DefMI || !DefMI->isBitcast())
Evan Chengd158fba2011-03-15 05:13:13 +0000332 return false;
333
Evan Chengd158fba2011-03-15 05:13:13 +0000334 unsigned SrcSrc = 0;
335 NumDefs = DefMI->getDesc().getNumDefs();
336 NumSrcs = DefMI->getDesc().getNumOperands() - NumDefs;
337 if (NumDefs != 1)
338 return false;
339 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
340 const MachineOperand &MO = DefMI->getOperand(i);
341 if (!MO.isReg() || MO.isDef())
342 continue;
343 unsigned Reg = MO.getReg();
344 if (!Reg)
345 continue;
Duncan Sands7becbc42011-07-26 15:05:06 +0000346 if (!MO.isDef()) {
347 if (SrcSrc)
348 // Multiple sources?
349 return false;
350 else
351 SrcSrc = Reg;
352 }
Evan Chengd158fba2011-03-15 05:13:13 +0000353 }
354
355 if (MRI->getRegClass(SrcSrc) != MRI->getRegClass(Def))
356 return false;
357
358 MRI->replaceRegWith(Def, SrcSrc);
359 MRI->clearKillFlags(SrcSrc);
360 MI->eraseFromParent();
361 ++NumBitcasts;
362 return true;
363}
364
Jim Grosbach39cc5132012-05-01 23:21:41 +0000365/// optimizeCmpInstr - If the instruction is a compare and the previous
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000366/// instruction it's comparing against all ready sets (or could be modified to
367/// set) the same flag as the compare, then we can remove the comparison and use
368/// the flag from the previous instruction.
Jim Grosbach39cc5132012-05-01 23:21:41 +0000369bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
Evan Chengd158fba2011-03-15 05:13:13 +0000370 MachineBasicBlock *MBB) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000371 // If this instruction is a comparison against zero and isn't comparing a
372 // physical register, we can try to optimize it.
Manman Rende7266c2012-06-29 21:33:59 +0000373 unsigned SrcReg, SrcReg2;
Gabor Greif04ac81d2010-09-21 12:01:15 +0000374 int CmpMask, CmpValue;
Manman Rende7266c2012-06-29 21:33:59 +0000375 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
376 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
377 (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000378 return false;
379
Bill Wendlinga6556862010-09-11 00:13:50 +0000380 // Attempt to optimize the comparison instruction.
Manman Rende7266c2012-06-29 21:33:59 +0000381 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
Evan Chengd158fba2011-03-15 05:13:13 +0000382 ++NumCmps;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000383 return true;
384 }
385
386 return false;
387}
388
Manman Rend7d003c2012-08-02 00:56:42 +0000389/// isLoadFoldable - Check whether MI is a candidate for folding into a later
390/// instruction. We only fold loads to virtual registers and the virtual
391/// register defined has a single use.
392bool PeepholeOptimizer::isLoadFoldable(MachineInstr *MI,
393 unsigned &FoldAsLoadDefReg) {
Manman Ren127eea82012-08-02 19:37:32 +0000394 if (!MI->canFoldAsLoad() || !MI->mayLoad())
395 return false;
396 const MCInstrDesc &MCID = MI->getDesc();
397 if (MCID.getNumDefs() != 1)
398 return false;
399
400 unsigned Reg = MI->getOperand(0).getReg();
401 // To reduce compilation time, we check MRI->hasOneUse when inserting
402 // loads. It should be checked when processing uses of the load, since
403 // uses can be removed during peephole.
404 if (!MI->getOperand(0).getSubReg() &&
405 TargetRegisterInfo::isVirtualRegister(Reg) &&
406 MRI->hasOneUse(Reg)) {
407 FoldAsLoadDefReg = Reg;
408 return true;
Manman Rend7d003c2012-08-02 00:56:42 +0000409 }
410 return false;
411}
412
Evan Chengc4af4632010-11-17 20:13:28 +0000413bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
414 SmallSet<unsigned, 4> &ImmDefRegs,
415 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
Evan Chenge837dea2011-06-28 19:10:37 +0000416 const MCInstrDesc &MCID = MI->getDesc();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000417 if (!MI->isMoveImmediate())
Evan Chengc4af4632010-11-17 20:13:28 +0000418 return false;
Evan Chenge837dea2011-06-28 19:10:37 +0000419 if (MCID.getNumDefs() != 1)
Evan Chengc4af4632010-11-17 20:13:28 +0000420 return false;
421 unsigned Reg = MI->getOperand(0).getReg();
422 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
423 ImmDefMIs.insert(std::make_pair(Reg, MI));
424 ImmDefRegs.insert(Reg);
425 return true;
426 }
Andrew Trick1df91b02012-02-08 21:22:43 +0000427
Evan Chengc4af4632010-11-17 20:13:28 +0000428 return false;
429}
430
Jim Grosbach39cc5132012-05-01 23:21:41 +0000431/// foldImmediate - Try folding register operands that are defined by move
Evan Chengc4af4632010-11-17 20:13:28 +0000432/// immediate instructions, i.e. a trivial constant folding optimization, if
433/// and only if the def and use are in the same BB.
Jim Grosbach39cc5132012-05-01 23:21:41 +0000434bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
Evan Chengc4af4632010-11-17 20:13:28 +0000435 SmallSet<unsigned, 4> &ImmDefRegs,
436 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
437 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
438 MachineOperand &MO = MI->getOperand(i);
439 if (!MO.isReg() || MO.isDef())
440 continue;
441 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000442 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengc4af4632010-11-17 20:13:28 +0000443 continue;
444 if (ImmDefRegs.count(Reg) == 0)
445 continue;
446 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
447 assert(II != ImmDefMIs.end());
448 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
449 ++NumImmFold;
450 return true;
451 }
452 }
453 return false;
454}
455
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000456bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
Evan Chengeb96a2f2010-11-15 21:20:45 +0000457 if (DisablePeephole)
458 return false;
Andrew Trick1df91b02012-02-08 21:22:43 +0000459
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000460 TM = &MF.getTarget();
461 TII = TM->getInstrInfo();
462 MRI = &MF.getRegInfo();
463 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
464
465 bool Changed = false;
466
467 SmallPtrSet<MachineInstr*, 8> LocalMIs;
Evan Chengc4af4632010-11-17 20:13:28 +0000468 SmallSet<unsigned, 4> ImmDefRegs;
469 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
Manman Rend7d003c2012-08-02 00:56:42 +0000470 unsigned FoldAsLoadDefReg;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000471 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
472 MachineBasicBlock *MBB = &*I;
Andrew Trick1df91b02012-02-08 21:22:43 +0000473
Evan Chengc4af4632010-11-17 20:13:28 +0000474 bool SeenMoveImm = false;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000475 LocalMIs.clear();
Evan Chengc4af4632010-11-17 20:13:28 +0000476 ImmDefRegs.clear();
477 ImmDefMIs.clear();
Manman Rend7d003c2012-08-02 00:56:42 +0000478 FoldAsLoadDefReg = 0;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000479
Evan Cheng326d9762011-02-15 05:00:24 +0000480 bool First = true;
481 MachineBasicBlock::iterator PMII;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000482 for (MachineBasicBlock::iterator
Bill Wendling220e2402010-09-10 21:55:43 +0000483 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Evan Chengcf75ab52011-02-14 21:50:37 +0000484 MachineInstr *MI = &*MII;
Evan Chengeb96a2f2010-11-15 21:20:45 +0000485 LocalMIs.insert(MI);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000486
Manman Rend7d003c2012-08-02 00:56:42 +0000487 // If there exists an instruction which belongs to the following
488 // categories, we will discard the load candidate.
Evan Cheng30a343a2011-01-07 21:08:26 +0000489 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
490 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue() ||
Evan Chengcf75ab52011-02-14 21:50:37 +0000491 MI->hasUnmodeledSideEffects()) {
Manman Rend7d003c2012-08-02 00:56:42 +0000492 FoldAsLoadDefReg = 0;
Evan Chengcf75ab52011-02-14 21:50:37 +0000493 ++MII;
Evan Chengeb96a2f2010-11-15 21:20:45 +0000494 continue;
Evan Chengcf75ab52011-02-14 21:50:37 +0000495 }
Manman Rend7d003c2012-08-02 00:56:42 +0000496 if (MI->mayStore() || MI->isCall())
497 FoldAsLoadDefReg = 0;
Evan Chengeb96a2f2010-11-15 21:20:45 +0000498
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000499 if (MI->isBitcast()) {
Jim Grosbach39cc5132012-05-01 23:21:41 +0000500 if (optimizeBitcastInstr(MI, MBB)) {
Evan Chengd158fba2011-03-15 05:13:13 +0000501 // MI is deleted.
Nick Lewyckydec1b102011-10-13 02:16:18 +0000502 LocalMIs.erase(MI);
Evan Chengd158fba2011-03-15 05:13:13 +0000503 Changed = true;
504 MII = First ? I->begin() : llvm::next(PMII);
505 continue;
Andrew Trick1df91b02012-02-08 21:22:43 +0000506 }
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000507 } else if (MI->isCompare()) {
Jim Grosbach39cc5132012-05-01 23:21:41 +0000508 if (optimizeCmpInstr(MI, MBB)) {
Evan Chengcf75ab52011-02-14 21:50:37 +0000509 // MI is deleted.
Nick Lewyckydec1b102011-10-13 02:16:18 +0000510 LocalMIs.erase(MI);
Evan Chengcf75ab52011-02-14 21:50:37 +0000511 Changed = true;
Evan Cheng326d9762011-02-15 05:00:24 +0000512 MII = First ? I->begin() : llvm::next(PMII);
Evan Chengcf75ab52011-02-14 21:50:37 +0000513 continue;
514 }
515 }
516
517 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
Evan Chengc4af4632010-11-17 20:13:28 +0000518 SeenMoveImm = true;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000519 } else {
Jim Grosbach39cc5132012-05-01 23:21:41 +0000520 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
Evan Chengc4af4632010-11-17 20:13:28 +0000521 if (SeenMoveImm)
Jim Grosbach39cc5132012-05-01 23:21:41 +0000522 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000523 }
Evan Cheng326d9762011-02-15 05:00:24 +0000524
Manman Rend7d003c2012-08-02 00:56:42 +0000525 // Check whether MI is a load candidate for folding into a later
526 // instruction. If MI is not a candidate, check whether we can fold an
527 // earlier load into MI.
528 if (!isLoadFoldable(MI, FoldAsLoadDefReg) && FoldAsLoadDefReg) {
529 // We need to fold load after optimizeCmpInstr, since optimizeCmpInstr
530 // can enable folding by converting SUB to CMP.
531 MachineInstr *DefMI = 0;
532 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
533 FoldAsLoadDefReg, DefMI);
534 if (FoldMI) {
535 // Update LocalMIs since we replaced MI with FoldMI and deleted DefMI.
536 LocalMIs.erase(MI);
537 LocalMIs.erase(DefMI);
538 LocalMIs.insert(FoldMI);
539 MI->eraseFromParent();
540 DefMI->eraseFromParent();
541 ++NumLoadFold;
542
543 // MI is replaced with FoldMI.
544 Changed = true;
545 PMII = FoldMI;
546 MII = llvm::next(PMII);
547 continue;
548 }
549 }
Evan Cheng326d9762011-02-15 05:00:24 +0000550 First = false;
Evan Chengcf75ab52011-02-14 21:50:37 +0000551 PMII = MII;
552 ++MII;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000553 }
554 }
555
556 return Changed;
557}