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 bool isProfitableToConv3Addr(unsigned RegA);
101 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
102 MachineBasicBlock::iterator &nmi,
103 MachineFunction::iterator &mbbi,
104 unsigned RegB, unsigned Dist);
106 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
107 SmallPtrSet<MachineInstr*, 8> &Processed);
109 static char ID; // Pass identification, replacement for typeid
110 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.addPreserved<LiveVariables>();
114 AU.addPreservedID(MachineLoopInfoID);
115 AU.addPreservedID(MachineDominatorsID);
117 AU.addPreservedID(StrongPHIEliminationID);
119 AU.addPreservedID(PHIEliminationID);
120 MachineFunctionPass::getAnalysisUsage(AU);
123 /// runOnMachineFunction - Pass entry point.
124 bool runOnMachineFunction(MachineFunction&);
128 char TwoAddressInstructionPass::ID = 0;
129 static RegisterPass<TwoAddressInstructionPass>
130 X("twoaddressinstruction", "Two-Address instruction pass");
132 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
134 /// Sink3AddrInstruction - A two-address instruction has been converted to a
135 /// three-address instruction to avoid clobbering a register. Try to sink it
136 /// past the instruction that would kill the above mentioned register to reduce
137 /// register pressure.
138 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
139 MachineInstr *MI, unsigned SavedReg,
140 MachineBasicBlock::iterator OldPos) {
141 // Check if it's safe to move this instruction.
142 bool SeenStore = true; // Be conservative.
143 if (!MI->isSafeToMove(TII, SeenStore))
147 SmallSet<unsigned, 4> UseRegs;
149 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
150 const MachineOperand &MO = MI->getOperand(i);
153 unsigned MOReg = MO.getReg();
156 if (MO.isUse() && MOReg != SavedReg)
157 UseRegs.insert(MO.getReg());
161 // Don't try to move it if it implicitly defines a register.
164 // For now, don't move any instructions that define multiple registers.
166 DefReg = MO.getReg();
169 // Find the instruction that kills SavedReg.
170 MachineInstr *KillMI = NULL;
171 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
172 UE = MRI->use_end(); UI != UE; ++UI) {
173 MachineOperand &UseMO = UI.getOperand();
176 KillMI = UseMO.getParent();
180 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
183 // If any of the definitions are used by another instruction between the
184 // position and the kill use, then it's not safe to sink it.
186 // FIXME: This can be sped up if there is an easy way to query whether an
187 // instruction is before or after another instruction. Then we can use
188 // MachineRegisterInfo def / use instead.
189 MachineOperand *KillMO = NULL;
190 MachineBasicBlock::iterator KillPos = KillMI;
193 unsigned NumVisited = 0;
194 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
195 MachineInstr *OtherMI = I;
196 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
199 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
200 MachineOperand &MO = OtherMI->getOperand(i);
203 unsigned MOReg = MO.getReg();
210 if (OtherMI == KillMI && MOReg == SavedReg)
211 // Save the operand that kills the register. We want to unset the kill
212 // marker if we can sink MI past it.
214 else if (UseRegs.count(MOReg))
215 // One of the uses is killed before the destination.
221 // Update kill and LV information.
222 KillMO->setIsKill(false);
223 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
224 KillMO->setIsKill(true);
227 LV->replaceKillInstruction(SavedReg, KillMI, MI);
229 // Move instruction to its destination.
231 MBB->insert(KillPos, MI);
237 /// isTwoAddrUse - Return true if the specified MI is using the specified
238 /// register as a two-address operand.
239 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
240 const TargetInstrDesc &TID = UseMI->getDesc();
241 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
242 MachineOperand &MO = UseMI->getOperand(i);
243 if (MO.isReg() && MO.getReg() == Reg &&
244 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
245 // Earlier use is a two-address one.
251 /// isProfitableToReMat - Return true if the heuristics determines it is likely
252 /// to be profitable to re-materialize the definition of Reg rather than copy
255 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
256 const TargetRegisterClass *RC,
257 MachineInstr *MI, MachineInstr *DefMI,
258 MachineBasicBlock *MBB, unsigned Loc) {
259 bool OtherUse = false;
260 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
261 UE = MRI->use_end(); UI != UE; ++UI) {
262 MachineOperand &UseMO = UI.getOperand();
263 MachineInstr *UseMI = UseMO.getParent();
264 MachineBasicBlock *UseMBB = UseMI->getParent();
266 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
267 if (DI != DistanceMap.end() && DI->second == Loc)
268 continue; // Current use.
270 // There is at least one other use in the MBB that will clobber the
272 if (isTwoAddrUse(UseMI, Reg))
277 // If other uses in MBB are not two-address uses, then don't remat.
281 // No other uses in the same block, remat if it's defined in the same
282 // block so it does not unnecessarily extend the live range.
283 return MBB == DefMI->getParent();
286 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
287 /// last instruction in the MBB that defines the specified register and the
288 /// two-address instruction which is being processed. It also returns the last
289 /// def location by reference
290 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
291 MachineBasicBlock *MBB, unsigned Dist,
294 unsigned LastUse = Dist;
295 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
296 E = MRI->reg_end(); I != E; ++I) {
297 MachineOperand &MO = I.getOperand();
298 MachineInstr *MI = MO.getParent();
299 if (MI->getParent() != MBB)
301 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
302 if (DI == DistanceMap.end())
304 if (MO.isUse() && DI->second < LastUse)
305 LastUse = DI->second;
306 if (MO.isDef() && DI->second > LastDef)
307 LastDef = DI->second;
310 return !(LastUse > LastDef && LastUse < Dist);
313 /// isCopyToReg - Return true if the specified MI is a copy instruction or
314 /// a extract_subreg instruction. It also returns the source and destination
315 /// registers and whether they are physical registers by reference.
316 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
317 unsigned &SrcReg, unsigned &DstReg,
318 bool &IsSrcPhys, bool &IsDstPhys) {
321 unsigned SrcSubIdx, DstSubIdx;
322 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
323 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
324 DstReg = MI.getOperand(0).getReg();
325 SrcReg = MI.getOperand(1).getReg();
326 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
327 DstReg = MI.getOperand(0).getReg();
328 SrcReg = MI.getOperand(2).getReg();
329 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
330 DstReg = MI.getOperand(0).getReg();
331 SrcReg = MI.getOperand(2).getReg();
336 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
337 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
343 /// isKilled - Test if the given register value, which is used by the given
344 /// instruction, is killed by the given instruction. This looks through
345 /// coalescable copies to see if the original value is potentially not killed.
347 /// For example, in this code:
349 /// %reg1034 = copy %reg1024
350 /// %reg1035 = copy %reg1025<kill>
351 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
353 /// %reg1034 is not considered to be killed, since it is copied from a
354 /// register which is not killed. Treating it as not killed lets the
355 /// normal heuristics commute the (two-address) add, which lets
356 /// coalescing eliminate the extra copy.
358 static bool isKilled(MachineInstr &MI, unsigned Reg,
359 const MachineRegisterInfo *MRI,
360 const TargetInstrInfo *TII) {
361 MachineInstr *DefMI = &MI;
363 if (!DefMI->killsRegister(Reg))
365 if (TargetRegisterInfo::isPhysicalRegister(Reg))
367 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
368 // If there are multiple defs, we can't do a simple analysis, so just
369 // go with what the kill flag says.
370 if (next(Begin) != MRI->def_end())
373 bool IsSrcPhys, IsDstPhys;
374 unsigned SrcReg, DstReg;
375 // If the def is something other than a copy, then it isn't going to
376 // be coalesced, so follow the kill flag.
377 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
383 /// isTwoAddrUse - Return true if the specified MI uses the specified register
384 /// as a two-address use. If so, return the destination register by reference.
385 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
386 const TargetInstrDesc &TID = MI.getDesc();
387 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
388 ? MI.getNumOperands() : TID.getNumOperands();
389 for (unsigned i = 0; i != NumOps; ++i) {
390 const MachineOperand &MO = MI.getOperand(i);
391 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
394 if (MI.isRegTiedToDefOperand(i, &ti)) {
395 DstReg = MI.getOperand(ti).getReg();
402 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
403 /// use, return the use instruction if it's a copy or a two-address use.
405 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
406 MachineRegisterInfo *MRI,
407 const TargetInstrInfo *TII,
409 unsigned &DstReg, bool &IsDstPhys) {
410 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
411 if (UI == MRI->use_end())
413 MachineInstr &UseMI = *UI;
414 if (++UI != MRI->use_end())
415 // More than one use.
417 if (UseMI.getParent() != MBB)
421 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
426 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
427 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
433 /// getMappedReg - Return the physical register the specified virtual register
434 /// might be mapped to.
436 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
437 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
438 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
439 if (SI == RegMap.end())
443 if (TargetRegisterInfo::isPhysicalRegister(Reg))
448 /// regsAreCompatible - Return true if the two registers are equal or aliased.
451 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
456 return TRI->regsOverlap(RegA, RegB);
460 /// isProfitableToReMat - Return true if it's potentially profitable to commute
461 /// the two-address instruction that's being processed.
463 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
464 MachineInstr *MI, MachineBasicBlock *MBB,
466 // Determine if it's profitable to commute this two address instruction. In
467 // general, we want no uses between this instruction and the definition of
468 // the two-address register.
470 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
471 // %reg1029<def> = MOV8rr %reg1028
472 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
473 // insert => %reg1030<def> = MOV8rr %reg1028
474 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
475 // In this case, it might not be possible to coalesce the second MOV8rr
476 // instruction if the first one is coalesced. So it would be profitable to
478 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
479 // %reg1029<def> = MOV8rr %reg1028
480 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
481 // insert => %reg1030<def> = MOV8rr %reg1029
482 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
484 if (!MI->killsRegister(regC))
487 // Ok, we have something like:
488 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
489 // let's see if it's worth commuting it.
491 // Look for situations like this:
492 // %reg1024<def> = MOV r1
493 // %reg1025<def> = MOV r0
494 // %reg1026<def> = ADD %reg1024, %reg1025
496 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
497 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
498 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
499 unsigned ToRegB = getMappedReg(regB, DstRegMap);
500 unsigned ToRegC = getMappedReg(regC, DstRegMap);
501 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
502 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
503 regsAreCompatible(FromRegC, ToRegB, TRI)))
506 // If there is a use of regC between its last def (could be livein) and this
507 // instruction, then bail.
508 unsigned LastDefC = 0;
509 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
512 // If there is a use of regB between its last def (could be livein) and this
513 // instruction, then go ahead and make this transformation.
514 unsigned LastDefB = 0;
515 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
518 // Since there are no intervening uses for both registers, then commute
519 // if the def of regC is closer. Its live interval is shorter.
520 return LastDefB && LastDefC && LastDefC > LastDefB;
523 /// CommuteInstruction - Commute a two-address instruction and update the basic
524 /// block, distance map, and live variables if needed. Return true if it is
527 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
528 MachineFunction::iterator &mbbi,
529 unsigned RegB, unsigned RegC, unsigned Dist) {
530 MachineInstr *MI = mi;
531 DOUT << "2addr: COMMUTING : " << *MI;
532 MachineInstr *NewMI = TII->commuteInstruction(MI);
535 DOUT << "2addr: COMMUTING FAILED!\n";
539 DOUT << "2addr: COMMUTED TO: " << *NewMI;
540 // If the instruction changed to commute it, update livevar.
543 // Update live variables
544 LV->replaceKillInstruction(RegC, MI, NewMI);
546 mbbi->insert(mi, NewMI); // Insert the new inst
547 mbbi->erase(mi); // Nuke the old inst.
549 DistanceMap.insert(std::make_pair(NewMI, Dist));
552 // Update source register map.
553 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
555 unsigned RegA = MI->getOperand(0).getReg();
556 SrcRegMap[RegA] = FromRegC;
562 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
563 /// given 2-address instruction to a 3-address one.
565 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
566 // Look for situations like this:
567 // %reg1024<def> = MOV r1
568 // %reg1025<def> = MOV r0
569 // %reg1026<def> = ADD %reg1024, %reg1025
571 // Turn ADD into a 3-address instruction to avoid a copy.
572 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
573 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
574 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
577 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
578 /// three address one. Return true if this transformation was successful.
580 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
581 MachineBasicBlock::iterator &nmi,
582 MachineFunction::iterator &mbbi,
583 unsigned RegB, unsigned Dist) {
584 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
586 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
587 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
590 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
591 // FIXME: Temporary workaround. If the new instruction doesn't
592 // uses RegB, convertToThreeAddress must have created more
593 // then one instruction.
594 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
596 mbbi->erase(mi); // Nuke the old inst.
599 DistanceMap.insert(std::make_pair(NewMI, Dist));
609 /// ProcessCopy - If the specified instruction is not yet processed, process it
610 /// if it's a copy. For a copy instruction, we find the physical registers the
611 /// source and destination registers might be mapped to. These are kept in
612 /// point-to maps used to determine future optimizations. e.g.
615 /// v1026 = add v1024, v1025
617 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
618 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
619 /// potentially joined with r1 on the output side. It's worthwhile to commute
620 /// 'add' to eliminate a copy.
621 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
622 MachineBasicBlock *MBB,
623 SmallPtrSet<MachineInstr*, 8> &Processed) {
624 if (Processed.count(MI))
627 bool IsSrcPhys, IsDstPhys;
628 unsigned SrcReg, DstReg;
629 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
632 if (IsDstPhys && !IsSrcPhys)
633 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
634 else if (!IsDstPhys && IsSrcPhys) {
635 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
637 assert(SrcRegMap[DstReg] == SrcReg &&
638 "Can't map to two src physical registers!");
640 SmallVector<unsigned, 4> VirtRegPairs;
643 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
644 IsCopy, NewReg, IsDstPhys)) {
646 if (!Processed.insert(UseMI))
650 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
651 if (DI != DistanceMap.end())
652 // Earlier in the same MBB.Reached via a back edge.
656 VirtRegPairs.push_back(NewReg);
659 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
661 assert(SrcRegMap[NewReg] == DstReg &&
662 "Can't map to two src physical registers!");
663 VirtRegPairs.push_back(NewReg);
667 if (!VirtRegPairs.empty()) {
668 unsigned ToReg = VirtRegPairs.back();
669 VirtRegPairs.pop_back();
670 while (!VirtRegPairs.empty()) {
671 unsigned FromReg = VirtRegPairs.back();
672 VirtRegPairs.pop_back();
673 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
675 assert(DstRegMap[FromReg] == ToReg &&
676 "Can't map to two dst physical registers!");
682 Processed.insert(MI);
685 /// isSafeToDelete - If the specified instruction does not produce any side
686 /// effects and all of its defs are dead, then it's safe to delete.
687 static bool isSafeToDelete(MachineInstr *MI, const TargetInstrInfo *TII) {
688 const TargetInstrDesc &TID = MI->getDesc();
689 if (TID.mayStore() || TID.isCall())
691 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
694 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
695 MachineOperand &MO = MI->getOperand(i);
696 if (!MO.isReg() || !MO.isDef())
705 /// runOnMachineFunction - Reduce two-address instructions to two operands.
707 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
708 DOUT << "Machine Function\n";
709 const TargetMachine &TM = MF.getTarget();
710 MRI = &MF.getRegInfo();
711 TII = TM.getInstrInfo();
712 TRI = TM.getRegisterInfo();
713 LV = getAnalysisIfAvailable<LiveVariables>();
715 bool MadeChange = false;
717 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
718 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
720 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
722 ReMatRegs.resize(MRI->getLastVirtReg()+1);
724 SmallPtrSet<MachineInstr*, 8> Processed;
725 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
726 mbbi != mbbe; ++mbbi) {
732 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
734 MachineBasicBlock::iterator nmi = next(mi);
735 const TargetInstrDesc &TID = mi->getDesc();
736 bool FirstTied = true;
738 DistanceMap.insert(std::make_pair(mi, ++Dist));
740 ProcessCopy(&*mi, &*mbbi, Processed);
742 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
743 ? mi->getNumOperands() : TID.getNumOperands();
744 for (unsigned si = 0; si < NumOps; ++si) {
746 if (!mi->isRegTiedToDefOperand(si, &ti))
750 ++NumTwoAddressInstrs;
751 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
756 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
757 mi->getOperand(si).isUse() && "two address instruction invalid");
759 // If the two operands are the same we just remove the use
760 // and mark the def as def&use, otherwise we have to insert a copy.
761 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
767 unsigned regA = mi->getOperand(ti).getReg();
768 unsigned regB = mi->getOperand(si).getReg();
770 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
771 "cannot update physical register live information");
774 // First, verify that we don't have a use of a in the instruction (a =
775 // b + a for example) because our transformation will not work. This
776 // should never occur because we are in SSA form.
777 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
779 !mi->getOperand(i).isReg() ||
780 mi->getOperand(i).getReg() != regA);
783 // If this instruction is not the killing user of B, see if we can
784 // rearrange the code to make it so. Making it the killing user will
785 // allow us to coalesce A and B together, eliminating the copy we are
787 if (!isKilled(*mi, regB, MRI, TII)) {
788 // If regA is dead and the instruction can be deleted, just delete
789 // it so it doesn't clobber regB.
790 if (mi->getOperand(ti).isDead() && isSafeToDelete(mi, TII)) {
791 mbbi->erase(mi); // Nuke the old inst.
794 break; // Done with this instruction.
797 // If this instruction is commutative, check to see if C dies. If
798 // so, swap the B and C operands. This makes the live ranges of A
800 // FIXME: This code also works for A := B op C instructions.
801 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
802 assert(mi->getOperand(3-si).isReg() &&
803 "Not a proper commutative instruction!");
804 unsigned regC = mi->getOperand(3-si).getReg();
805 if (isKilled(*mi, regC, MRI, TII)) {
806 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
809 goto InstructionRearranged;
814 // If this instruction is potentially convertible to a true
815 // three-address instruction,
816 if (TID.isConvertibleTo3Addr()) {
817 // FIXME: This assumes there are no more operands which are tied
818 // to another register.
820 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
821 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
824 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
825 ++NumConvertedTo3Addr;
826 break; // Done with this instruction.
831 // If it's profitable to commute the instruction, do so.
832 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
833 unsigned regC = mi->getOperand(3-si).getReg();
834 if (isProfitableToCommute(regB, regC, mi, mbbi, Dist))
835 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
839 goto InstructionRearranged;
843 // If it's profitable to convert the 2-address instruction to a
844 // 3-address one, do so.
845 if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
846 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
847 ++NumConvertedTo3Addr;
848 break; // Done with this instruction.
852 InstructionRearranged:
853 const TargetRegisterClass* rc = MRI->getRegClass(regB);
854 MachineInstr *DefMI = MRI->getVRegDef(regB);
855 // If it's safe and profitable, remat the definition instead of
858 DefMI->getDesc().isAsCheapAsAMove() &&
859 DefMI->isSafeToReMat(TII, regB) &&
860 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
861 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
862 TII->reMaterialize(*mbbi, mi, regA, DefMI);
866 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
867 assert(Emitted && "Unable to issue a copy instruction!\n");
870 MachineBasicBlock::iterator prevMI = prior(mi);
871 // Update DistanceMap.
872 DistanceMap.insert(std::make_pair(prevMI, Dist));
873 DistanceMap[mi] = ++Dist;
875 // Update live variables for regB.
877 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
879 // regB is used in this BB.
880 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
882 if (LV->removeVirtualRegisterKilled(regB, mi))
883 LV->addVirtualRegisterKilled(regB, prevMI);
885 if (LV->removeVirtualRegisterDead(regB, mi))
886 LV->addVirtualRegisterDead(regB, prevMI);
889 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
891 // Replace all occurences of regB with regA.
892 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
893 if (mi->getOperand(i).isReg() &&
894 mi->getOperand(i).getReg() == regB)
895 mi->getOperand(i).setReg(regA);
899 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
900 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
903 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
910 // Some remat'ed instructions are dead.
911 int VReg = ReMatRegs.find_first();
913 if (MRI->use_empty(VReg)) {
914 MachineInstr *DefMI = MRI->getVRegDef(VReg);
915 DefMI->eraseFromParent();
917 VReg = ReMatRegs.find_next(VReg);