1 //===-- PeepholeOptimizer.cpp - X86 Peephole Optimizer --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a peephole optimizer for the X86.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/Target/MRegisterInfo.h"
18 #include "Support/Statistic.h"
19 #include "Support/STLExtras.h"
24 Statistic<> NumPHOpts("x86-peephole",
25 "Number of peephole optimization performed");
26 struct PH : public MachineFunctionPass {
27 virtual bool runOnMachineFunction(MachineFunction &MF);
29 bool PeepholeOptimize(MachineBasicBlock &MBB,
30 MachineBasicBlock::iterator &I);
32 virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
36 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
38 bool PH::runOnMachineFunction(MachineFunction &MF) {
41 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
42 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
43 if (PeepholeOptimize(*BI, I)) {
53 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
54 MachineBasicBlock::iterator &I) {
55 assert(I != MBB.end());
56 MachineBasicBlock::iterator NextI = next(I);
59 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
61 switch (MI->getOpcode()) {
64 case X86::MOVrr32: // Destroy X = X copies...
65 if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
71 // A large number of X86 instructions have forms which take an 8-bit
72 // immediate despite the fact that the operands are 16 or 32 bits. Because
73 // this can save three bytes of code size (and icache space), we want to
74 // shrink them if possible.
75 case X86::IMULrri16: case X86::IMULrri32:
76 assert(MI->getNumOperands() == 3 && "These should all have 3 operands!");
77 if (MI->getOperand(2).isImmediate()) {
78 int Val = MI->getOperand(2).getImmedValue();
79 // If the value is the same when signed extended from 8 bits...
80 if (Val == (signed int)(signed char)Val) {
82 switch (MI->getOpcode()) {
83 default: assert(0 && "Unknown opcode value!");
84 case X86::IMULrri16: Opcode = X86::IMULrri16b; break;
85 case X86::IMULrri32: Opcode = X86::IMULrri32b; break;
87 unsigned R0 = MI->getOperand(0).getReg();
88 unsigned R1 = MI->getOperand(1).getReg();
89 I = MBB.insert(MBB.erase(I),
90 BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
97 case X86::IMULrmi16: case X86::IMULrmi32:
98 assert(MI->getNumOperands() == 6 && "These should all have 6 operands!");
99 if (MI->getOperand(5).isImmediate()) {
100 int Val = MI->getOperand(5).getImmedValue();
101 // If the value is the same when signed extended from 8 bits...
102 if (Val == (signed int)(signed char)Val) {
104 switch (MI->getOpcode()) {
105 default: assert(0 && "Unknown opcode value!");
106 case X86::IMULrmi16: Opcode = X86::IMULrmi16b; break;
107 case X86::IMULrmi32: Opcode = X86::IMULrmi32b; break;
109 unsigned R0 = MI->getOperand(0).getReg();
110 unsigned R1 = MI->getOperand(1).getReg();
111 unsigned Scale = MI->getOperand(2).getImmedValue();
112 unsigned R2 = MI->getOperand(3).getReg();
113 unsigned Offset = MI->getOperand(4).getImmedValue();
114 I = MBB.insert(MBB.erase(I),
115 BuildMI(Opcode, 5, R0).addReg(R1).addZImm(Scale).
116 addReg(R2).addSImm(Offset).addZImm((char)Val));
123 case X86::ADDri16: case X86::ADDri32:
124 case X86::SUBri16: case X86::SUBri32:
125 case X86::ANDri16: case X86::ANDri32:
126 case X86::ORri16: case X86::ORri32:
127 case X86::XORri16: case X86::XORri32:
128 assert(MI->getNumOperands() == 2 && "These should all have 2 operands!");
129 if (MI->getOperand(1).isImmediate()) {
130 int Val = MI->getOperand(1).getImmedValue();
131 // If the value is the same when signed extended from 8 bits...
132 if (Val == (signed int)(signed char)Val) {
134 switch (MI->getOpcode()) {
135 default: assert(0 && "Unknown opcode value!");
136 case X86::ADDri16: Opcode = X86::ADDri16b; break;
137 case X86::ADDri32: Opcode = X86::ADDri32b; break;
138 case X86::SUBri16: Opcode = X86::SUBri16b; break;
139 case X86::SUBri32: Opcode = X86::SUBri32b; break;
140 case X86::ANDri16: Opcode = X86::ANDri16b; break;
141 case X86::ANDri32: Opcode = X86::ANDri32b; break;
142 case X86::ORri16: Opcode = X86::ORri16b; break;
143 case X86::ORri32: Opcode = X86::ORri32b; break;
144 case X86::XORri16: Opcode = X86::XORri16b; break;
145 case X86::XORri32: Opcode = X86::XORri32b; break;
147 unsigned R0 = MI->getOperand(0).getReg();
148 I = MBB.insert(MBB.erase(I),
149 BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
156 case X86::ADDmi16: case X86::ADDmi32:
157 case X86::SUBmi16: case X86::SUBmi32:
158 case X86::ANDmi16: case X86::ANDmi32:
159 case X86::ORmi16: case X86::ORmi32:
160 case X86::XORmi16: case X86::XORmi32:
161 assert(MI->getNumOperands() == 5 && "These should all have 5 operands!");
162 if (MI->getOperand(4).isImmediate()) {
163 int Val = MI->getOperand(4).getImmedValue();
164 // If the value is the same when signed extended from 8 bits...
165 if (Val == (signed int)(signed char)Val) {
167 switch (MI->getOpcode()) {
168 default: assert(0 && "Unknown opcode value!");
169 case X86::ADDmi16: Opcode = X86::ADDmi16b; break;
170 case X86::ADDmi32: Opcode = X86::ADDmi32b; break;
171 case X86::SUBmi16: Opcode = X86::SUBmi16b; break;
172 case X86::SUBmi32: Opcode = X86::SUBmi32b; break;
173 case X86::ANDmi16: Opcode = X86::ANDmi16b; break;
174 case X86::ANDmi32: Opcode = X86::ANDmi32b; break;
175 case X86::ORmi16: Opcode = X86::ORmi16b; break;
176 case X86::ORmi32: Opcode = X86::ORmi32b; break;
177 case X86::XORmi16: Opcode = X86::XORmi16b; break;
178 case X86::XORmi32: Opcode = X86::XORmi32b; break;
180 unsigned R0 = MI->getOperand(0).getReg();
181 unsigned Scale = MI->getOperand(1).getImmedValue();
182 unsigned R1 = MI->getOperand(2).getReg();
183 unsigned Offset = MI->getOperand(3).getImmedValue();
184 I = MBB.insert(MBB.erase(I),
185 BuildMI(Opcode, 5).addReg(R0).addZImm(Scale).
186 addReg(R1).addSImm(Offset).addZImm((char)Val));
193 case X86::MOVri32: Size++;
194 case X86::MOVri16: Size++;
196 // FIXME: We can only do this transformation if we know that flags are not
197 // used here, because XOR clobbers the flags!
198 if (MI->getOperand(1).isImmediate()) { // avoid mov EAX, <value>
199 int Val = MI->getOperand(1).getImmedValue();
200 if (Val == 0) { // mov EAX, 0 -> xor EAX, EAX
201 static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
202 unsigned Reg = MI->getOperand(0).getReg();
203 I = MBB.insert(MBB.erase(I),
204 BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
206 } else if (Val == -1) { // mov EAX, -1 -> or EAX, -1
207 // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
212 case X86::BSWAPr32: // Change bswap EAX, bswap EAX into nothing
213 if (Next->getOpcode() == X86::BSWAPr32 &&
214 MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
215 I = MBB.erase(MBB.erase(I));
225 class UseDefChains : public MachineFunctionPass {
226 std::vector<MachineInstr*> DefiningInst;
228 // getDefinition - Return the machine instruction that defines the specified
229 // SSA virtual register.
230 MachineInstr *getDefinition(unsigned Reg) {
231 assert(MRegisterInfo::isVirtualRegister(Reg) &&
232 "use-def chains only exist for SSA registers!");
233 assert(Reg - MRegisterInfo::FirstVirtualRegister < DefiningInst.size() &&
234 "Unknown register number!");
235 assert(DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] &&
236 "Unknown register number!");
237 return DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister];
240 // setDefinition - Update the use-def chains to indicate that MI defines
242 void setDefinition(unsigned Reg, MachineInstr *MI) {
243 if (Reg-MRegisterInfo::FirstVirtualRegister >= DefiningInst.size())
244 DefiningInst.resize(Reg-MRegisterInfo::FirstVirtualRegister+1);
245 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = MI;
248 // removeDefinition - Update the use-def chains to forget about Reg
250 void removeDefinition(unsigned Reg) {
251 assert(getDefinition(Reg)); // Check validity
252 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
255 virtual bool runOnMachineFunction(MachineFunction &MF) {
256 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
257 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
258 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
259 MachineOperand &MO = I->getOperand(i);
260 if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
261 MRegisterInfo::isVirtualRegister(MO.getReg()))
262 setDefinition(MO.getReg(), I);
268 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
269 AU.setPreservesAll();
270 MachineFunctionPass::getAnalysisUsage(AU);
273 virtual void releaseMemory() {
274 std::vector<MachineInstr*>().swap(DefiningInst);
278 RegisterAnalysis<UseDefChains> X("use-def-chains",
279 "use-def chain construction for machine code");
284 Statistic<> NumSSAPHOpts("x86-ssa-peephole",
285 "Number of SSA peephole optimization performed");
287 /// SSAPH - This pass is an X86-specific, SSA-based, peephole optimizer. This
288 /// pass is really a bad idea: a better instruction selector should completely
289 /// supersume it. However, that will take some time to develop, and the
290 /// simple things this can do are important now.
291 class SSAPH : public MachineFunctionPass {
294 virtual bool runOnMachineFunction(MachineFunction &MF);
296 bool PeepholeOptimize(MachineBasicBlock &MBB,
297 MachineBasicBlock::iterator &I);
299 virtual const char *getPassName() const {
300 return "X86 SSA-based Peephole Optimizer";
303 /// Propagate - Set MI[DestOpNo] = Src[SrcOpNo], optionally change the
304 /// opcode of the instruction, then return true.
305 bool Propagate(MachineInstr *MI, unsigned DestOpNo,
306 MachineInstr *Src, unsigned SrcOpNo, unsigned NewOpcode = 0){
307 MI->getOperand(DestOpNo) = Src->getOperand(SrcOpNo);
308 if (NewOpcode) MI->setOpcode(NewOpcode);
312 /// OptimizeAddress - If we can fold the addressing arithmetic for this
313 /// memory instruction into the instruction itself, do so and return true.
314 bool OptimizeAddress(MachineInstr *MI, unsigned OpNo);
316 /// getDefininingInst - If the specified operand is a read of an SSA
317 /// register, return the machine instruction defining it, otherwise, return
319 MachineInstr *getDefiningInst(MachineOperand &MO) {
320 if (MO.isDef() || !MO.isRegister() ||
321 !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
322 return UDC->getDefinition(MO.getReg());
325 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
326 AU.addRequired<UseDefChains>();
327 AU.addPreserved<UseDefChains>();
328 MachineFunctionPass::getAnalysisUsage(AU);
333 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
335 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
336 bool Changed = false;
339 UDC = &getAnalysis<UseDefChains>();
342 LocalChanged = false;
344 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
345 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
346 if (PeepholeOptimize(*BI, I)) {
351 Changed |= LocalChanged;
352 } while (LocalChanged);
357 static bool isValidScaleAmount(unsigned Scale) {
358 return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
361 /// OptimizeAddress - If we can fold the addressing arithmetic for this
362 /// memory instruction into the instruction itself, do so and return true.
363 bool SSAPH::OptimizeAddress(MachineInstr *MI, unsigned OpNo) {
364 MachineOperand &BaseRegOp = MI->getOperand(OpNo+0);
365 MachineOperand &ScaleOp = MI->getOperand(OpNo+1);
366 MachineOperand &IndexRegOp = MI->getOperand(OpNo+2);
367 MachineOperand &DisplacementOp = MI->getOperand(OpNo+3);
369 unsigned BaseReg = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
370 unsigned Scale = ScaleOp.getImmedValue();
371 unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
373 bool Changed = false;
375 // If the base register is unset, and the index register is set with a scale
376 // of 1, move it to be the base register.
377 if (BaseRegOp.hasAllocatedReg() && BaseReg == 0 &&
378 Scale == 1 && IndexReg != 0) {
379 BaseRegOp.setReg(IndexReg);
380 IndexRegOp.setReg(0);
384 // Attempt to fold instructions used by the base register into the instruction
385 if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
386 switch (DefInst->getOpcode()) {
388 // If there is no displacement set for this instruction set one now.
389 // FIXME: If we can fold two immediates together, we should do so!
390 if (DisplacementOp.isImmediate() && !DisplacementOp.getImmedValue()) {
391 if (DefInst->getOperand(1).isImmediate()) {
393 return Propagate(MI, OpNo+3, DefInst, 1);
399 // If the source is a register-register add, and we do not yet have an
400 // index register, fold the add into the memory address.
402 BaseRegOp = DefInst->getOperand(1);
403 IndexRegOp = DefInst->getOperand(2);
404 ScaleOp.setImmedValue(1);
410 // If this shift could be folded into the index portion of the address if
411 // it were the index register, move it to the index register operand now,
412 // so it will be folded in below.
413 if ((Scale == 1 || (IndexReg == 0 && IndexRegOp.hasAllocatedReg())) &&
414 DefInst->getOperand(2).getImmedValue() < 4) {
415 std::swap(BaseRegOp, IndexRegOp);
416 ScaleOp.setImmedValue(1); Scale = 1;
417 std::swap(IndexReg, BaseReg);
424 // Attempt to fold instructions used by the index into the instruction
425 if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
426 switch (DefInst->getOpcode()) {
428 // Figure out what the resulting scale would be if we folded this shift.
429 unsigned ResScale = Scale * (1 << DefInst->getOperand(2).getImmedValue());
430 if (isValidScaleAmount(ResScale)) {
431 IndexRegOp = DefInst->getOperand(1);
432 ScaleOp.setImmedValue(ResScale);
443 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
444 MachineBasicBlock::iterator &I) {
445 MachineBasicBlock::iterator NextI = next(I);
447 MachineInstr *MI = I;
448 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
450 bool Changed = false;
452 // Scan the operands of this instruction. If any operands are
453 // register-register copies, replace the operand with the source.
454 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
455 // Is this an SSA register use?
456 if (MachineInstr *DefInst = getDefiningInst(MI->getOperand(i)))
457 // If the operand is a vreg-vreg copy, it is always safe to replace the
458 // source value with the input operand.
459 if (DefInst->getOpcode() == X86::MOVrr8 ||
460 DefInst->getOpcode() == X86::MOVrr16 ||
461 DefInst->getOpcode() == X86::MOVrr32) {
462 // Don't propagate physical registers into PHI nodes...
463 if (MI->getOpcode() != X86::PHI ||
464 (DefInst->getOperand(1).isRegister() &&
465 MRegisterInfo::isVirtualRegister(DefInst->getOperand(1).getReg())))
466 Changed = Propagate(MI, i, DefInst, 1);
470 // Perform instruction specific optimizations.
471 switch (MI->getOpcode()) {
473 // Register to memory stores. Format: <base,scale,indexreg,immdisp>, srcreg
474 case X86::MOVmr32: case X86::MOVmr16: case X86::MOVmr8:
475 case X86::MOVmi32: case X86::MOVmi16: case X86::MOVmi8:
476 // Check to see if we can fold the source instruction into this one...
477 if (MachineInstr *SrcInst = getDefiningInst(MI->getOperand(4))) {
478 switch (SrcInst->getOpcode()) {
479 // Fold the immediate value into the store, if possible.
480 case X86::MOVri8: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi8);
481 case X86::MOVri16: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi16);
482 case X86::MOVri32: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi32);
487 // If we can optimize the addressing expression, do so now.
488 if (OptimizeAddress(MI, 0))
495 // If we can optimize the addressing expression, do so now.
496 if (OptimizeAddress(MI, 1))