1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
21 // Note that if a register allocator chooses to use this pass, that it
22 // has to be capable of handling the non-SSA nature of these rewritten
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallSet.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/STLExtras.h"
50 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
52 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
53 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
54 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
55 STATISTIC(NumReMats, "Number of instructions re-materialized");
56 STATISTIC(NumDeletes, "Number of dead instructions deleted");
59 class VISIBILITY_HIDDEN TwoAddressInstructionPass
60 : public MachineFunctionPass {
61 const TargetInstrInfo *TII;
62 const TargetRegisterInfo *TRI;
63 MachineRegisterInfo *MRI;
66 // DistanceMap - Keep track the distance of a MI from the start of the
67 // current basic block.
68 DenseMap<MachineInstr*, unsigned> DistanceMap;
70 // SrcRegMap - A map from virtual registers to physical registers which
71 // are likely targets to be coalesced to due to copies from physical
72 // registers to virtual registers. e.g. v1024 = move r0.
73 DenseMap<unsigned, unsigned> SrcRegMap;
75 // DstRegMap - A map from virtual registers to physical registers which
76 // are likely targets to be coalesced to due to copies to physical
77 // registers from virtual registers. e.g. r1 = move v1024.
78 DenseMap<unsigned, unsigned> DstRegMap;
80 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
82 MachineBasicBlock::iterator OldPos);
84 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
85 MachineInstr *MI, MachineInstr *DefMI,
86 MachineBasicBlock *MBB, unsigned Loc);
88 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
91 bool isProfitableToCommute(unsigned regB, unsigned regC,
92 MachineInstr *MI, MachineBasicBlock *MBB,
95 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
96 MachineFunction::iterator &mbbi,
97 unsigned RegB, unsigned RegC, unsigned Dist);
99 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
100 SmallPtrSet<MachineInstr*, 8> &Processed);
102 static char ID; // Pass identification, replacement for typeid
103 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addPreserved<LiveVariables>();
107 AU.addPreservedID(MachineLoopInfoID);
108 AU.addPreservedID(MachineDominatorsID);
110 AU.addPreservedID(StrongPHIEliminationID);
112 AU.addPreservedID(PHIEliminationID);
113 MachineFunctionPass::getAnalysisUsage(AU);
116 /// runOnMachineFunction - Pass entry point.
117 bool runOnMachineFunction(MachineFunction&);
121 char TwoAddressInstructionPass::ID = 0;
122 static RegisterPass<TwoAddressInstructionPass>
123 X("twoaddressinstruction", "Two-Address instruction pass");
125 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
127 /// Sink3AddrInstruction - A two-address instruction has been converted to a
128 /// three-address instruction to avoid clobbering a register. Try to sink it
129 /// past the instruction that would kill the above mentioned register to reduce
130 /// register pressure.
131 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
132 MachineInstr *MI, unsigned SavedReg,
133 MachineBasicBlock::iterator OldPos) {
134 // Check if it's safe to move this instruction.
135 bool SeenStore = true; // Be conservative.
136 if (!MI->isSafeToMove(TII, SeenStore))
140 SmallSet<unsigned, 4> UseRegs;
142 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
143 const MachineOperand &MO = MI->getOperand(i);
146 unsigned MOReg = MO.getReg();
149 if (MO.isUse() && MOReg != SavedReg)
150 UseRegs.insert(MO.getReg());
154 // Don't try to move it if it implicitly defines a register.
157 // For now, don't move any instructions that define multiple registers.
159 DefReg = MO.getReg();
162 // Find the instruction that kills SavedReg.
163 MachineInstr *KillMI = NULL;
164 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
165 UE = MRI->use_end(); UI != UE; ++UI) {
166 MachineOperand &UseMO = UI.getOperand();
169 KillMI = UseMO.getParent();
173 if (!KillMI || KillMI->getParent() != MBB)
176 // If any of the definitions are used by another instruction between the
177 // position and the kill use, then it's not safe to sink it.
179 // FIXME: This can be sped up if there is an easy way to query whether an
180 // instruction is before or after another instruction. Then we can use
181 // MachineRegisterInfo def / use instead.
182 MachineOperand *KillMO = NULL;
183 MachineBasicBlock::iterator KillPos = KillMI;
186 unsigned NumVisited = 0;
187 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
188 MachineInstr *OtherMI = I;
189 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
192 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
193 MachineOperand &MO = OtherMI->getOperand(i);
196 unsigned MOReg = MO.getReg();
203 if (OtherMI == KillMI && MOReg == SavedReg)
204 // Save the operand that kills the register. We want to unset the kill
205 // marker if we can sink MI past it.
207 else if (UseRegs.count(MOReg))
208 // One of the uses is killed before the destination.
214 // Update kill and LV information.
215 KillMO->setIsKill(false);
216 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
217 KillMO->setIsKill(true);
220 LV->replaceKillInstruction(SavedReg, KillMI, MI);
222 // Move instruction to its destination.
224 MBB->insert(KillPos, MI);
230 /// isTwoAddrUse - Return true if the specified MI is using the specified
231 /// register as a two-address operand.
232 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
233 const TargetInstrDesc &TID = UseMI->getDesc();
234 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
235 MachineOperand &MO = UseMI->getOperand(i);
236 if (MO.isReg() && MO.getReg() == Reg &&
237 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
238 // Earlier use is a two-address one.
244 /// isProfitableToReMat - Return true if the heuristics determines it is likely
245 /// to be profitable to re-materialize the definition of Reg rather than copy
248 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
249 const TargetRegisterClass *RC,
250 MachineInstr *MI, MachineInstr *DefMI,
251 MachineBasicBlock *MBB, unsigned Loc) {
252 bool OtherUse = false;
253 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
254 UE = MRI->use_end(); UI != UE; ++UI) {
255 MachineOperand &UseMO = UI.getOperand();
256 MachineInstr *UseMI = UseMO.getParent();
257 MachineBasicBlock *UseMBB = UseMI->getParent();
259 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
260 if (DI != DistanceMap.end() && DI->second == Loc)
261 continue; // Current use.
263 // There is at least one other use in the MBB that will clobber the
265 if (isTwoAddrUse(UseMI, Reg))
270 // If other uses in MBB are not two-address uses, then don't remat.
274 // No other uses in the same block, remat if it's defined in the same
275 // block so it does not unnecessarily extend the live range.
276 return MBB == DefMI->getParent();
279 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
280 /// last instruction in the MBB that defines the specified register and the
281 /// two-address instruction which is being processed. It also returns the last
282 /// def location by reference
283 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
284 MachineBasicBlock *MBB, unsigned Dist,
287 unsigned LastUse = Dist;
288 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
289 E = MRI->reg_end(); I != E; ++I) {
290 MachineOperand &MO = I.getOperand();
291 MachineInstr *MI = MO.getParent();
292 if (MI->getParent() != MBB)
294 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
295 if (DI == DistanceMap.end())
297 if (MO.isUse() && DI->second < LastUse)
298 LastUse = DI->second;
299 if (MO.isDef() && DI->second > LastDef)
300 LastDef = DI->second;
303 return !(LastUse > LastDef && LastUse < Dist);
306 /// isCopyToReg - Return true if the specified MI is a copy instruction or
307 /// a extract_subreg instruction. It also returns the source and destination
308 /// registers and whether they are physical registers by reference.
309 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
310 unsigned &SrcReg, unsigned &DstReg,
311 bool &IsSrcPhys, bool &IsDstPhys) {
314 unsigned SrcSubIdx, DstSubIdx;
315 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
316 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
317 DstReg = MI.getOperand(0).getReg();
318 SrcReg = MI.getOperand(1).getReg();
319 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
320 DstReg = MI.getOperand(0).getReg();
321 SrcReg = MI.getOperand(2).getReg();
326 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
327 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
333 /// isTwoAddrUse - Return true if the specified MI uses the specified register
334 /// as a two-address use. If so, return the destination register by reference.
335 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
336 const TargetInstrDesc &TID = MI.getDesc();
337 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
338 const MachineOperand &MO = MI.getOperand(i);
339 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
342 if (MI.isRegTiedToDefOperand(i, &ti)) {
343 DstReg = MI.getOperand(ti).getReg();
350 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
351 /// use, return the use instruction if it's a copy or a two-address use.
353 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
354 MachineRegisterInfo *MRI,
355 const TargetInstrInfo *TII,
357 unsigned &DstReg, bool &IsDstPhys) {
358 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
359 if (UI == MRI->use_end())
361 MachineInstr &UseMI = *UI;
362 if (++UI != MRI->use_end())
363 // More than one use.
365 if (UseMI.getParent() != MBB)
369 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
372 if (isTwoAddrUse(UseMI, Reg, DstReg))
377 /// getMappedReg - Return the physical register the specified virtual register
378 /// might be mapped to.
380 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
381 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
382 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
383 if (SI == RegMap.end())
387 if (TargetRegisterInfo::isPhysicalRegister(Reg))
392 /// regsAreCompatible - Return true if the two registers are equal or aliased.
395 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
400 return TRI->regsOverlap(RegA, RegB);
404 /// isProfitableToReMat - Return true if it's potentially profitable to commute
405 /// the two-address instruction that's being processed.
407 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
408 MachineInstr *MI, MachineBasicBlock *MBB,
410 // Determine if it's profitable to commute this two address instruction. In
411 // general, we want no uses between this instruction and the definition of
412 // the two-address register.
414 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
415 // %reg1029<def> = MOV8rr %reg1028
416 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
417 // insert => %reg1030<def> = MOV8rr %reg1028
418 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
419 // In this case, it might not be possible to coalesce the second MOV8rr
420 // instruction if the first one is coalesced. So it would be profitable to
422 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
423 // %reg1029<def> = MOV8rr %reg1028
424 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
425 // insert => %reg1030<def> = MOV8rr %reg1029
426 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
428 if (!MI->killsRegister(regC))
431 // Ok, we have something like:
432 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
433 // let's see if it's worth commuting it.
435 // Look for situations like this:
436 // %reg1024<def> = MOV r1
437 // %reg1025<def> = MOV r0
438 // %reg1026<def> = ADD %reg1024, %reg1025
440 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
441 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
442 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
443 unsigned ToRegB = getMappedReg(regB, DstRegMap);
444 unsigned ToRegC = getMappedReg(regC, DstRegMap);
445 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
446 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
447 regsAreCompatible(FromRegC, ToRegB, TRI)))
450 // If there is a use of regC between its last def (could be livein) and this
451 // instruction, then bail.
452 unsigned LastDefC = 0;
453 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
456 // If there is a use of regB between its last def (could be livein) and this
457 // instruction, then go ahead and make this transformation.
458 unsigned LastDefB = 0;
459 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
462 // Since there are no intervening uses for both registers, then commute
463 // if the def of regC is closer. Its live interval is shorter.
464 return LastDefB && LastDefC && LastDefC > LastDefB;
467 /// CommuteInstruction - Commute a two-address instruction and update the basic
468 /// block, distance map, and live variables if needed. Return true if it is
471 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
472 MachineFunction::iterator &mbbi,
473 unsigned RegB, unsigned RegC, unsigned Dist) {
474 MachineInstr *MI = mi;
475 DOUT << "2addr: COMMUTING : " << *MI;
476 MachineInstr *NewMI = TII->commuteInstruction(MI);
479 DOUT << "2addr: COMMUTING FAILED!\n";
483 DOUT << "2addr: COMMUTED TO: " << *NewMI;
484 // If the instruction changed to commute it, update livevar.
487 // Update live variables
488 LV->replaceKillInstruction(RegC, MI, NewMI);
490 mbbi->insert(mi, NewMI); // Insert the new inst
491 mbbi->erase(mi); // Nuke the old inst.
493 DistanceMap.insert(std::make_pair(NewMI, Dist));
496 // Update source register map.
497 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
499 unsigned RegA = MI->getOperand(0).getReg();
500 SrcRegMap[RegA] = FromRegC;
506 /// ProcessCopy - If the specified instruction is not yet processed, process it
507 /// if it's a copy. For a copy instruction, we find the physical registers the
508 /// source and destination registers might be mapped to. These are kept in
509 /// point-to maps used to determine future optimizations. e.g.
512 /// v1026 = add v1024, v1025
514 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
515 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
516 /// potentially joined with r1 on the output side. It's worthwhile to commute
517 /// 'add' to eliminate a copy.
518 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
519 MachineBasicBlock *MBB,
520 SmallPtrSet<MachineInstr*, 8> &Processed) {
521 if (Processed.count(MI))
524 bool IsSrcPhys, IsDstPhys;
525 unsigned SrcReg, DstReg;
526 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
529 if (IsDstPhys && !IsSrcPhys)
530 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
531 else if (!IsDstPhys && IsSrcPhys) {
533 SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
534 isNew = isNew; // Silence compiler warning.
535 assert(isNew && "Can't map to two src physical registers!");
537 SmallVector<unsigned, 4> VirtRegPairs;
540 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
541 isCopy, NewReg, IsDstPhys)) {
543 if (Processed.insert(UseMI))
547 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
548 if (DI != DistanceMap.end())
549 // Earlier in the same MBB.Reached via a back edge.
553 VirtRegPairs.push_back(NewReg);
556 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
557 isNew = isNew; // Silence compiler warning.
558 assert(isNew && "Can't map to two src physical registers!");
559 VirtRegPairs.push_back(NewReg);
563 if (!VirtRegPairs.empty()) {
564 unsigned ToReg = VirtRegPairs.back();
565 VirtRegPairs.pop_back();
566 while (!VirtRegPairs.empty()) {
567 unsigned FromReg = VirtRegPairs.back();
568 VirtRegPairs.pop_back();
569 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
570 isNew = isNew; // Silence compiler warning.
571 assert(isNew && "Can't map to two dst physical registers!");
577 Processed.insert(MI);
580 /// isSafeToDelete - If the specified instruction does not produce any side
581 /// effects and all of its defs are dead, then it's safe to delete.
582 static bool isSafeToDelete(MachineInstr *MI, const TargetInstrInfo *TII) {
583 const TargetInstrDesc &TID = MI->getDesc();
584 if (TID.mayStore() || TID.isCall())
586 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
589 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
590 MachineOperand &MO = MI->getOperand(i);
591 if (!MO.isReg() || !MO.isDef())
600 /// runOnMachineFunction - Reduce two-address instructions to two operands.
602 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
603 DOUT << "Machine Function\n";
604 const TargetMachine &TM = MF.getTarget();
605 MRI = &MF.getRegInfo();
606 TII = TM.getInstrInfo();
607 TRI = TM.getRegisterInfo();
608 LV = getAnalysisIfAvailable<LiveVariables>();
610 bool MadeChange = false;
612 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
613 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
615 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
617 ReMatRegs.resize(MRI->getLastVirtReg()+1);
619 SmallPtrSet<MachineInstr*, 8> Processed;
620 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
621 mbbi != mbbe; ++mbbi) {
627 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
629 MachineBasicBlock::iterator nmi = next(mi);
630 const TargetInstrDesc &TID = mi->getDesc();
631 bool FirstTied = true;
633 DistanceMap.insert(std::make_pair(mi, ++Dist));
635 ProcessCopy(&*mi, &*mbbi, Processed);
637 for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
639 if (!mi->isRegTiedToDefOperand(si, &ti))
643 ++NumTwoAddressInstrs;
644 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
649 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
650 mi->getOperand(si).isUse() && "two address instruction invalid");
652 // If the two operands are the same we just remove the use
653 // and mark the def as def&use, otherwise we have to insert a copy.
654 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
660 unsigned regA = mi->getOperand(ti).getReg();
661 unsigned regB = mi->getOperand(si).getReg();
663 assert(TargetRegisterInfo::isVirtualRegister(regA) &&
664 TargetRegisterInfo::isVirtualRegister(regB) &&
665 "cannot update physical register live information");
668 // First, verify that we don't have a use of a in the instruction (a =
669 // b + a for example) because our transformation will not work. This
670 // should never occur because we are in SSA form.
671 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
673 !mi->getOperand(i).isReg() ||
674 mi->getOperand(i).getReg() != regA);
677 // If this instruction is not the killing user of B, see if we can
678 // rearrange the code to make it so. Making it the killing user will
679 // allow us to coalesce A and B together, eliminating the copy we are
681 if (!mi->killsRegister(regB)) {
682 // If regA is dead and the instruction can be deleted, just delete
683 // it so it doesn't clobber regB.
684 if (mi->getOperand(ti).isDead() && isSafeToDelete(mi, TII)) {
685 mbbi->erase(mi); // Nuke the old inst.
688 break; // Done with this instruction.
691 // If this instruction is commutative, check to see if C dies. If
692 // so, swap the B and C operands. This makes the live ranges of A
694 // FIXME: This code also works for A := B op C instructions.
695 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
696 assert(mi->getOperand(3-si).isReg() &&
697 "Not a proper commutative instruction!");
698 unsigned regC = mi->getOperand(3-si).getReg();
699 if (mi->killsRegister(regC)) {
700 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
703 goto InstructionRearranged;
708 // If this instruction is potentially convertible to a true
709 // three-address instruction,
710 if (TID.isConvertibleTo3Addr()) {
711 // FIXME: This assumes there are no more operands which are tied
712 // to another register.
714 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
715 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
718 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
720 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
721 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
724 if (NewMI->findRegisterUseOperand(regB, false, TRI))
725 // FIXME: Temporary workaround. If the new instruction doesn't
726 // uses regB, convertToThreeAddress must have created more
727 // then one instruction.
728 Sunk = Sink3AddrInstruction(mbbi, NewMI, regB, mi);
730 mbbi->erase(mi); // Nuke the old inst.
733 DistanceMap.insert(std::make_pair(NewMI, Dist));
738 ++NumConvertedTo3Addr;
739 break; // Done with this instruction.
744 // If it's profitable to commute the instruction, do so.
745 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
746 unsigned regC = mi->getOperand(3-si).getReg();
747 if (isProfitableToCommute(regB, regC, mi, mbbi, Dist))
748 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
755 InstructionRearranged:
756 const TargetRegisterClass* rc = MRI->getRegClass(regA);
757 MachineInstr *DefMI = MRI->getVRegDef(regB);
758 // If it's safe and profitable, remat the definition instead of
761 DefMI->getDesc().isAsCheapAsAMove() &&
762 DefMI->isSafeToReMat(TII, regB) &&
763 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
764 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
765 TII->reMaterialize(*mbbi, mi, regA, DefMI);
769 TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
772 MachineBasicBlock::iterator prevMI = prior(mi);
773 // Update DistanceMap.
774 DistanceMap.insert(std::make_pair(prevMI, Dist));
775 DistanceMap[mi] = ++Dist;
777 // Update live variables for regB.
779 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
781 // regB is used in this BB.
782 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
784 if (LV->removeVirtualRegisterKilled(regB, mi))
785 LV->addVirtualRegisterKilled(regB, prevMI);
787 if (LV->removeVirtualRegisterDead(regB, mi))
788 LV->addVirtualRegisterDead(regB, prevMI);
791 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
793 // Replace all occurences of regB with regA.
794 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
795 if (mi->getOperand(i).isReg() &&
796 mi->getOperand(i).getReg() == regB)
797 mi->getOperand(i).setReg(regA);
801 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
802 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
805 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
812 // Some remat'ed instructions are dead.
813 int VReg = ReMatRegs.find_first();
815 if (MRI->use_empty(VReg)) {
816 MachineInstr *DefMI = MRI->getVRegDef(VReg);
817 DefMI->eraseFromParent();
819 VReg = ReMatRegs.find_next(VReg);