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 "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "Support/Statistic.h"
21 #include "Support/STLExtras.h"
26 Statistic<> NumPHOpts("x86-peephole",
27 "Number of peephole optimization performed");
28 Statistic<> NumPHMoves("x86-peephole", "Number of peephole moves folded");
29 struct PH : public MachineFunctionPass {
30 virtual bool runOnMachineFunction(MachineFunction &MF);
32 bool PeepholeOptimize(MachineBasicBlock &MBB,
33 MachineBasicBlock::iterator &I);
35 virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
39 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
41 bool PH::runOnMachineFunction(MachineFunction &MF) {
44 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
45 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
46 if (PeepholeOptimize(*BI, I)) {
56 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
57 MachineBasicBlock::iterator &I) {
58 assert(I != MBB.end());
59 MachineBasicBlock::iterator NextI = next(I);
62 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
64 switch (MI->getOpcode()) {
67 case X86::MOVrr32: // Destroy X = X copies...
68 if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
74 // A large number of X86 instructions have forms which take an 8-bit
75 // immediate despite the fact that the operands are 16 or 32 bits. Because
76 // this can save three bytes of code size (and icache space), we want to
77 // shrink them if possible.
78 case X86::IMULrri16: case X86::IMULrri32:
79 assert(MI->getNumOperands() == 3 && "These should all have 3 operands!");
80 if (MI->getOperand(2).isImmediate()) {
81 int Val = MI->getOperand(2).getImmedValue();
82 // If the value is the same when signed extended from 8 bits...
83 if (Val == (signed int)(signed char)Val) {
85 switch (MI->getOpcode()) {
86 default: assert(0 && "Unknown opcode value!");
87 case X86::IMULrri16: Opcode = X86::IMULrri16b; break;
88 case X86::IMULrri32: Opcode = X86::IMULrri32b; break;
90 unsigned R0 = MI->getOperand(0).getReg();
91 unsigned R1 = MI->getOperand(1).getReg();
92 I = MBB.insert(MBB.erase(I),
93 BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
100 case X86::IMULrmi16: case X86::IMULrmi32:
101 assert(MI->getNumOperands() == 6 && "These should all have 6 operands!");
102 if (MI->getOperand(5).isImmediate()) {
103 int Val = MI->getOperand(5).getImmedValue();
104 // If the value is the same when signed extended from 8 bits...
105 if (Val == (signed int)(signed char)Val) {
107 switch (MI->getOpcode()) {
108 default: assert(0 && "Unknown opcode value!");
109 case X86::IMULrmi16: Opcode = X86::IMULrmi16b; break;
110 case X86::IMULrmi32: Opcode = X86::IMULrmi32b; break;
112 unsigned R0 = MI->getOperand(0).getReg();
113 unsigned R1 = MI->getOperand(1).getReg();
114 unsigned Scale = MI->getOperand(2).getImmedValue();
115 unsigned R2 = MI->getOperand(3).getReg();
116 unsigned Offset = MI->getOperand(4).getImmedValue();
117 I = MBB.insert(MBB.erase(I),
118 BuildMI(Opcode, 5, R0).addReg(R1).addZImm(Scale).
119 addReg(R2).addSImm(Offset).addZImm((char)Val));
126 case X86::ADDri16: case X86::ADDri32:
127 case X86::SUBri16: case X86::SUBri32:
128 case X86::ANDri16: case X86::ANDri32:
129 case X86::ORri16: case X86::ORri32:
130 case X86::XORri16: case X86::XORri32:
131 assert(MI->getNumOperands() == 2 && "These should all have 2 operands!");
132 if (MI->getOperand(1).isImmediate()) {
133 int Val = MI->getOperand(1).getImmedValue();
134 // If the value is the same when signed extended from 8 bits...
135 if (Val == (signed int)(signed char)Val) {
137 switch (MI->getOpcode()) {
138 default: assert(0 && "Unknown opcode value!");
139 case X86::ADDri16: Opcode = X86::ADDri16b; break;
140 case X86::ADDri32: Opcode = X86::ADDri32b; break;
141 case X86::SUBri16: Opcode = X86::SUBri16b; break;
142 case X86::SUBri32: Opcode = X86::SUBri32b; break;
143 case X86::ANDri16: Opcode = X86::ANDri16b; break;
144 case X86::ANDri32: Opcode = X86::ANDri32b; break;
145 case X86::ORri16: Opcode = X86::ORri16b; break;
146 case X86::ORri32: Opcode = X86::ORri32b; break;
147 case X86::XORri16: Opcode = X86::XORri16b; break;
148 case X86::XORri32: Opcode = X86::XORri32b; break;
150 unsigned R0 = MI->getOperand(0).getReg();
151 I = MBB.insert(MBB.erase(I),
152 BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
159 case X86::ADDmi16: case X86::ADDmi32:
160 case X86::SUBmi16: case X86::SUBmi32:
161 case X86::ANDmi16: case X86::ANDmi32:
162 case X86::ORmi16: case X86::ORmi32:
163 case X86::XORmi16: case X86::XORmi32:
164 assert(MI->getNumOperands() == 5 && "These should all have 5 operands!");
165 if (MI->getOperand(4).isImmediate()) {
166 int Val = MI->getOperand(4).getImmedValue();
167 // If the value is the same when signed extended from 8 bits...
168 if (Val == (signed int)(signed char)Val) {
170 switch (MI->getOpcode()) {
171 default: assert(0 && "Unknown opcode value!");
172 case X86::ADDmi16: Opcode = X86::ADDmi16b; break;
173 case X86::ADDmi32: Opcode = X86::ADDmi32b; break;
174 case X86::SUBmi16: Opcode = X86::SUBmi16b; break;
175 case X86::SUBmi32: Opcode = X86::SUBmi32b; break;
176 case X86::ANDmi16: Opcode = X86::ANDmi16b; break;
177 case X86::ANDmi32: Opcode = X86::ANDmi32b; break;
178 case X86::ORmi16: Opcode = X86::ORmi16b; break;
179 case X86::ORmi32: Opcode = X86::ORmi32b; break;
180 case X86::XORmi16: Opcode = X86::XORmi16b; break;
181 case X86::XORmi32: Opcode = X86::XORmi32b; break;
183 unsigned R0 = MI->getOperand(0).getReg();
184 unsigned Scale = MI->getOperand(1).getImmedValue();
185 unsigned R1 = MI->getOperand(2).getReg();
186 unsigned Offset = MI->getOperand(3).getImmedValue();
187 I = MBB.insert(MBB.erase(I),
188 BuildMI(Opcode, 5).addReg(R0).addZImm(Scale).
189 addReg(R1).addSImm(Offset).addZImm((char)Val));
196 case X86::MOVri32: Size++;
197 case X86::MOVri16: Size++;
199 // FIXME: We can only do this transformation if we know that flags are not
200 // used here, because XOR clobbers the flags!
201 if (MI->getOperand(1).isImmediate()) { // avoid mov EAX, <value>
202 int Val = MI->getOperand(1).getImmedValue();
203 if (Val == 0) { // mov EAX, 0 -> xor EAX, EAX
204 static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
205 unsigned Reg = MI->getOperand(0).getReg();
206 I = MBB.insert(MBB.erase(I),
207 BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
209 } else if (Val == -1) { // mov EAX, -1 -> or EAX, -1
210 // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
215 case X86::BSWAPr32: // Change bswap EAX, bswap EAX into nothing
216 if (Next->getOpcode() == X86::BSWAPr32 &&
217 MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
218 I = MBB.erase(MBB.erase(I));
228 class UseDefChains : public MachineFunctionPass {
229 std::vector<MachineInstr*> DefiningInst;
231 // getDefinition - Return the machine instruction that defines the specified
232 // SSA virtual register.
233 MachineInstr *getDefinition(unsigned Reg) {
234 assert(MRegisterInfo::isVirtualRegister(Reg) &&
235 "use-def chains only exist for SSA registers!");
236 assert(Reg - MRegisterInfo::FirstVirtualRegister < DefiningInst.size() &&
237 "Unknown register number!");
238 assert(DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] &&
239 "Unknown register number!");
240 return DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister];
243 // setDefinition - Update the use-def chains to indicate that MI defines
245 void setDefinition(unsigned Reg, MachineInstr *MI) {
246 if (Reg-MRegisterInfo::FirstVirtualRegister >= DefiningInst.size())
247 DefiningInst.resize(Reg-MRegisterInfo::FirstVirtualRegister+1);
248 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = MI;
251 // removeDefinition - Update the use-def chains to forget about Reg
253 void removeDefinition(unsigned Reg) {
254 assert(getDefinition(Reg)); // Check validity
255 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
258 virtual bool runOnMachineFunction(MachineFunction &MF) {
259 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
260 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
261 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
262 MachineOperand &MO = I->getOperand(i);
263 if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
264 MRegisterInfo::isVirtualRegister(MO.getReg()))
265 setDefinition(MO.getReg(), I);
271 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
272 AU.setPreservesAll();
273 MachineFunctionPass::getAnalysisUsage(AU);
276 virtual void releaseMemory() {
277 std::vector<MachineInstr*>().swap(DefiningInst);
281 RegisterAnalysis<UseDefChains> X("use-def-chains",
282 "use-def chain construction for machine code");
287 Statistic<> NumSSAPHOpts("x86-ssa-peephole",
288 "Number of SSA peephole optimization performed");
290 /// SSAPH - This pass is an X86-specific, SSA-based, peephole optimizer. This
291 /// pass is really a bad idea: a better instruction selector should completely
292 /// supersume it. However, that will take some time to develop, and the
293 /// simple things this can do are important now.
294 class SSAPH : public MachineFunctionPass {
297 virtual bool runOnMachineFunction(MachineFunction &MF);
299 bool PeepholeOptimize(MachineBasicBlock &MBB,
300 MachineBasicBlock::iterator &I);
302 virtual const char *getPassName() const {
303 return "X86 SSA-based Peephole Optimizer";
306 /// Propagate - Set MI[DestOpNo] = Src[SrcOpNo], optionally change the
307 /// opcode of the instruction, then return true.
308 bool Propagate(MachineInstr *MI, unsigned DestOpNo,
309 MachineInstr *Src, unsigned SrcOpNo, unsigned NewOpcode = 0){
310 MI->getOperand(DestOpNo) = Src->getOperand(SrcOpNo);
311 if (NewOpcode) MI->setOpcode(NewOpcode);
315 /// OptimizeAddress - If we can fold the addressing arithmetic for this
316 /// memory instruction into the instruction itself, do so and return true.
317 bool OptimizeAddress(MachineInstr *MI, unsigned OpNo);
319 /// getDefininingInst - If the specified operand is a read of an SSA
320 /// register, return the machine instruction defining it, otherwise, return
322 MachineInstr *getDefiningInst(MachineOperand &MO) {
323 if (MO.isDef() || !MO.isRegister() ||
324 !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
325 return UDC->getDefinition(MO.getReg());
328 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
329 AU.addRequired<UseDefChains>();
330 AU.addPreserved<UseDefChains>();
331 MachineFunctionPass::getAnalysisUsage(AU);
336 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
338 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
339 bool Changed = false;
342 UDC = &getAnalysis<UseDefChains>();
345 LocalChanged = false;
347 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
348 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
349 if (PeepholeOptimize(*BI, I)) {
354 Changed |= LocalChanged;
355 } while (LocalChanged);
360 static bool isValidScaleAmount(unsigned Scale) {
361 return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
364 /// OptimizeAddress - If we can fold the addressing arithmetic for this
365 /// memory instruction into the instruction itself, do so and return true.
366 bool SSAPH::OptimizeAddress(MachineInstr *MI, unsigned OpNo) {
367 MachineOperand &BaseRegOp = MI->getOperand(OpNo+0);
368 MachineOperand &ScaleOp = MI->getOperand(OpNo+1);
369 MachineOperand &IndexRegOp = MI->getOperand(OpNo+2);
370 MachineOperand &DisplacementOp = MI->getOperand(OpNo+3);
372 unsigned BaseReg = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
373 unsigned Scale = ScaleOp.getImmedValue();
374 unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
376 bool Changed = false;
378 // If the base register is unset, and the index register is set with a scale
379 // of 1, move it to be the base register.
380 if (BaseRegOp.hasAllocatedReg() && BaseReg == 0 &&
381 Scale == 1 && IndexReg != 0) {
382 BaseRegOp.setReg(IndexReg);
383 IndexRegOp.setReg(0);
387 // Attempt to fold instructions used by the base register into the instruction
388 if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
389 switch (DefInst->getOpcode()) {
391 // If there is no displacement set for this instruction set one now.
392 // FIXME: If we can fold two immediates together, we should do so!
393 if (DisplacementOp.isImmediate() && !DisplacementOp.getImmedValue()) {
394 if (DefInst->getOperand(1).isImmediate()) {
396 return Propagate(MI, OpNo+3, DefInst, 1);
402 // If the source is a register-register add, and we do not yet have an
403 // index register, fold the add into the memory address.
405 BaseRegOp = DefInst->getOperand(1);
406 IndexRegOp = DefInst->getOperand(2);
407 ScaleOp.setImmedValue(1);
413 // If this shift could be folded into the index portion of the address if
414 // it were the index register, move it to the index register operand now,
415 // so it will be folded in below.
416 if ((Scale == 1 || (IndexReg == 0 && IndexRegOp.hasAllocatedReg())) &&
417 DefInst->getOperand(2).getImmedValue() < 4) {
418 std::swap(BaseRegOp, IndexRegOp);
419 ScaleOp.setImmedValue(1); Scale = 1;
420 std::swap(IndexReg, BaseReg);
427 // Attempt to fold instructions used by the index into the instruction
428 if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
429 switch (DefInst->getOpcode()) {
431 // Figure out what the resulting scale would be if we folded this shift.
432 unsigned ResScale = Scale * (1 << DefInst->getOperand(2).getImmedValue());
433 if (isValidScaleAmount(ResScale)) {
434 IndexRegOp = DefInst->getOperand(1);
435 ScaleOp.setImmedValue(ResScale);
446 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
447 MachineBasicBlock::iterator &I) {
448 MachineBasicBlock::iterator NextI = next(I);
450 MachineInstr *MI = I;
451 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
453 bool Changed = false;
455 const TargetInstrInfo &TII = MBB.getParent()->getTarget().getInstrInfo();
457 // Scan the operands of this instruction. If any operands are
458 // register-register copies, replace the operand with the source.
459 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
460 // Is this an SSA register use?
461 if (MachineInstr *DefInst = getDefiningInst(MI->getOperand(i))) {
462 // If the operand is a vreg-vreg copy, it is always safe to replace the
463 // source value with the input operand.
464 unsigned Source, Dest;
465 if (TII.isMoveInstr(*DefInst, Source, Dest)) {
466 // Don't propagate physical registers into any instructions.
467 if (DefInst->getOperand(1).isRegister() &&
468 MRegisterInfo::isVirtualRegister(Source)) {
469 MI->getOperand(i).setReg(Source);
477 // Perform instruction specific optimizations.
478 switch (MI->getOpcode()) {
480 // Register to memory stores. Format: <base,scale,indexreg,immdisp>, srcreg
481 case X86::MOVmr32: case X86::MOVmr16: case X86::MOVmr8:
482 case X86::MOVmi32: case X86::MOVmi16: case X86::MOVmi8:
483 // Check to see if we can fold the source instruction into this one...
484 if (MachineInstr *SrcInst = getDefiningInst(MI->getOperand(4))) {
485 switch (SrcInst->getOpcode()) {
486 // Fold the immediate value into the store, if possible.
487 case X86::MOVri8: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi8);
488 case X86::MOVri16: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi16);
489 case X86::MOVri32: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi32);
494 // If we can optimize the addressing expression, do so now.
495 if (OptimizeAddress(MI, 0))
502 // If we can optimize the addressing expression, do so now.
503 if (OptimizeAddress(MI, 1))