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/Analysis/AliasAnalysis.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.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 TwoAddressInstructionPass : public MachineFunctionPass {
60 const TargetInstrInfo *TII;
61 const TargetRegisterInfo *TRI;
62 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 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
94 bool isProfitableToCommute(unsigned regB, unsigned regC,
95 MachineInstr *MI, MachineBasicBlock *MBB,
98 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99 MachineFunction::iterator &mbbi,
100 unsigned RegB, unsigned RegC, unsigned Dist);
102 bool isProfitableToConv3Addr(unsigned RegA);
104 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
105 MachineBasicBlock::iterator &nmi,
106 MachineFunction::iterator &mbbi,
107 unsigned RegB, unsigned Dist);
109 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
110 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
111 SmallVector<NewKill, 4> &NewKills,
112 MachineBasicBlock *MBB, unsigned Dist);
113 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
114 MachineBasicBlock::iterator &nmi,
115 MachineFunction::iterator &mbbi, unsigned Dist);
117 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
119 MachineFunction::iterator &mbbi,
120 unsigned SrcIdx, unsigned DstIdx,
123 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
124 SmallPtrSet<MachineInstr*, 8> &Processed);
127 static char ID; // Pass identification, replacement for typeid
128 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
131 AU.setPreservesCFG();
132 AU.addRequired<AliasAnalysis>();
133 AU.addPreserved<LiveVariables>();
134 AU.addPreservedID(MachineLoopInfoID);
135 AU.addPreservedID(MachineDominatorsID);
137 AU.addPreservedID(StrongPHIEliminationID);
139 AU.addPreservedID(PHIEliminationID);
140 MachineFunctionPass::getAnalysisUsage(AU);
143 /// runOnMachineFunction - Pass entry point.
144 bool runOnMachineFunction(MachineFunction&);
148 char TwoAddressInstructionPass::ID = 0;
149 static RegisterPass<TwoAddressInstructionPass>
150 X("twoaddressinstruction", "Two-Address instruction pass");
152 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
154 /// Sink3AddrInstruction - A two-address instruction has been converted to a
155 /// three-address instruction to avoid clobbering a register. Try to sink it
156 /// past the instruction that would kill the above mentioned register to reduce
157 /// register pressure.
158 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
159 MachineInstr *MI, unsigned SavedReg,
160 MachineBasicBlock::iterator OldPos) {
161 // Check if it's safe to move this instruction.
162 bool SeenStore = true; // Be conservative.
163 if (!MI->isSafeToMove(TII, AA, SeenStore))
167 SmallSet<unsigned, 4> UseRegs;
169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 const MachineOperand &MO = MI->getOperand(i);
173 unsigned MOReg = MO.getReg();
176 if (MO.isUse() && MOReg != SavedReg)
177 UseRegs.insert(MO.getReg());
181 // Don't try to move it if it implicitly defines a register.
184 // For now, don't move any instructions that define multiple registers.
186 DefReg = MO.getReg();
189 // Find the instruction that kills SavedReg.
190 MachineInstr *KillMI = NULL;
191 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
192 UE = MRI->use_end(); UI != UE; ++UI) {
193 MachineOperand &UseMO = UI.getOperand();
196 KillMI = UseMO.getParent();
200 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
203 // If any of the definitions are used by another instruction between the
204 // position and the kill use, then it's not safe to sink it.
206 // FIXME: This can be sped up if there is an easy way to query whether an
207 // instruction is before or after another instruction. Then we can use
208 // MachineRegisterInfo def / use instead.
209 MachineOperand *KillMO = NULL;
210 MachineBasicBlock::iterator KillPos = KillMI;
213 unsigned NumVisited = 0;
214 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
215 MachineInstr *OtherMI = I;
216 // DBG_VALUE cannot be counted against the limit.
217 if (OtherMI->isDebugValue())
219 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
222 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
223 MachineOperand &MO = OtherMI->getOperand(i);
226 unsigned MOReg = MO.getReg();
233 if (OtherMI == KillMI && MOReg == SavedReg)
234 // Save the operand that kills the register. We want to unset the kill
235 // marker if we can sink MI past it.
237 else if (UseRegs.count(MOReg))
238 // One of the uses is killed before the destination.
244 // Update kill and LV information.
245 KillMO->setIsKill(false);
246 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
247 KillMO->setIsKill(true);
250 LV->replaceKillInstruction(SavedReg, KillMI, MI);
252 // Move instruction to its destination.
254 MBB->insert(KillPos, MI);
260 /// isTwoAddrUse - Return true if the specified MI is using the specified
261 /// register as a two-address operand.
262 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
263 const TargetInstrDesc &TID = UseMI->getDesc();
264 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
265 MachineOperand &MO = UseMI->getOperand(i);
266 if (MO.isReg() && MO.getReg() == Reg &&
267 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
268 // Earlier use is a two-address one.
274 /// isProfitableToReMat - Return true if the heuristics determines it is likely
275 /// to be profitable to re-materialize the definition of Reg rather than copy
278 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
279 const TargetRegisterClass *RC,
280 MachineInstr *MI, MachineInstr *DefMI,
281 MachineBasicBlock *MBB, unsigned Loc) {
282 bool OtherUse = false;
283 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
284 UE = MRI->use_end(); UI != UE; ++UI) {
285 MachineOperand &UseMO = UI.getOperand();
286 MachineInstr *UseMI = UseMO.getParent();
287 MachineBasicBlock *UseMBB = UseMI->getParent();
289 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
290 if (DI != DistanceMap.end() && DI->second == Loc)
291 continue; // Current use.
293 // There is at least one other use in the MBB that will clobber the
295 if (isTwoAddrUse(UseMI, Reg))
300 // If other uses in MBB are not two-address uses, then don't remat.
304 // No other uses in the same block, remat if it's defined in the same
305 // block so it does not unnecessarily extend the live range.
306 return MBB == DefMI->getParent();
309 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
310 /// last instruction in the MBB that defines the specified register and the
311 /// two-address instruction which is being processed. It also returns the last
312 /// def location by reference
313 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
314 MachineBasicBlock *MBB, unsigned Dist,
317 unsigned LastUse = Dist;
318 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
319 E = MRI->reg_end(); I != E; ++I) {
320 MachineOperand &MO = I.getOperand();
321 MachineInstr *MI = MO.getParent();
322 if (MI->getParent() != MBB || MI->isDebugValue())
324 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
325 if (DI == DistanceMap.end())
327 if (MO.isUse() && DI->second < LastUse)
328 LastUse = DI->second;
329 if (MO.isDef() && DI->second > LastDef)
330 LastDef = DI->second;
333 return !(LastUse > LastDef && LastUse < Dist);
336 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
337 MachineBasicBlock *MBB,
339 unsigned LastUseDist = 0;
340 MachineInstr *LastUse = 0;
341 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
342 E = MRI->reg_end(); I != E; ++I) {
343 MachineOperand &MO = I.getOperand();
344 MachineInstr *MI = MO.getParent();
345 if (MI->getParent() != MBB || MI->isDebugValue())
347 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
348 if (DI == DistanceMap.end())
350 if (DI->second >= Dist)
353 if (MO.isUse() && DI->second > LastUseDist) {
355 LastUseDist = DI->second;
361 /// isCopyToReg - Return true if the specified MI is a copy instruction or
362 /// a extract_subreg instruction. It also returns the source and destination
363 /// registers and whether they are physical registers by reference.
364 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
365 unsigned &SrcReg, unsigned &DstReg,
366 bool &IsSrcPhys, bool &IsDstPhys) {
369 unsigned SrcSubIdx, DstSubIdx;
370 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
371 if (MI.isExtractSubreg()) {
372 DstReg = MI.getOperand(0).getReg();
373 SrcReg = MI.getOperand(1).getReg();
374 } else if (MI.isInsertSubreg()) {
375 DstReg = MI.getOperand(0).getReg();
376 SrcReg = MI.getOperand(2).getReg();
377 } else if (MI.isSubregToReg()) {
378 DstReg = MI.getOperand(0).getReg();
379 SrcReg = MI.getOperand(2).getReg();
384 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
385 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
391 /// isKilled - Test if the given register value, which is used by the given
392 /// instruction, is killed by the given instruction. This looks through
393 /// coalescable copies to see if the original value is potentially not killed.
395 /// For example, in this code:
397 /// %reg1034 = copy %reg1024
398 /// %reg1035 = copy %reg1025<kill>
399 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
401 /// %reg1034 is not considered to be killed, since it is copied from a
402 /// register which is not killed. Treating it as not killed lets the
403 /// normal heuristics commute the (two-address) add, which lets
404 /// coalescing eliminate the extra copy.
406 static bool isKilled(MachineInstr &MI, unsigned Reg,
407 const MachineRegisterInfo *MRI,
408 const TargetInstrInfo *TII) {
409 MachineInstr *DefMI = &MI;
411 if (!DefMI->killsRegister(Reg))
413 if (TargetRegisterInfo::isPhysicalRegister(Reg))
415 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
416 // If there are multiple defs, we can't do a simple analysis, so just
417 // go with what the kill flag says.
418 if (llvm::next(Begin) != MRI->def_end())
421 bool IsSrcPhys, IsDstPhys;
422 unsigned SrcReg, DstReg;
423 // If the def is something other than a copy, then it isn't going to
424 // be coalesced, so follow the kill flag.
425 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
431 /// isTwoAddrUse - Return true if the specified MI uses the specified register
432 /// as a two-address use. If so, return the destination register by reference.
433 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
434 const TargetInstrDesc &TID = MI.getDesc();
435 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
436 for (unsigned i = 0; i != NumOps; ++i) {
437 const MachineOperand &MO = MI.getOperand(i);
438 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
441 if (MI.isRegTiedToDefOperand(i, &ti)) {
442 DstReg = MI.getOperand(ti).getReg();
449 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
450 /// use, return the use instruction if it's a copy or a two-address use.
452 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
453 MachineRegisterInfo *MRI,
454 const TargetInstrInfo *TII,
456 unsigned &DstReg, bool &IsDstPhys) {
457 if (!MRI->hasOneNonDBGUse(Reg))
458 // None or more than one use.
460 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
461 if (UseMI.getParent() != MBB)
465 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
470 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
471 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
477 /// getMappedReg - Return the physical register the specified virtual register
478 /// might be mapped to.
480 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
481 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
482 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
483 if (SI == RegMap.end())
487 if (TargetRegisterInfo::isPhysicalRegister(Reg))
492 /// regsAreCompatible - Return true if the two registers are equal or aliased.
495 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
500 return TRI->regsOverlap(RegA, RegB);
504 /// isProfitableToReMat - Return true if it's potentially profitable to commute
505 /// the two-address instruction that's being processed.
507 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
508 MachineInstr *MI, MachineBasicBlock *MBB,
510 // Determine if it's profitable to commute this two address instruction. In
511 // general, we want no uses between this instruction and the definition of
512 // the two-address register.
514 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
515 // %reg1029<def> = MOV8rr %reg1028
516 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
517 // insert => %reg1030<def> = MOV8rr %reg1028
518 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
519 // In this case, it might not be possible to coalesce the second MOV8rr
520 // instruction if the first one is coalesced. So it would be profitable to
522 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
523 // %reg1029<def> = MOV8rr %reg1028
524 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
525 // insert => %reg1030<def> = MOV8rr %reg1029
526 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
528 if (!MI->killsRegister(regC))
531 // Ok, we have something like:
532 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
533 // let's see if it's worth commuting it.
535 // Look for situations like this:
536 // %reg1024<def> = MOV r1
537 // %reg1025<def> = MOV r0
538 // %reg1026<def> = ADD %reg1024, %reg1025
540 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
541 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
542 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
543 unsigned ToRegB = getMappedReg(regB, DstRegMap);
544 unsigned ToRegC = getMappedReg(regC, DstRegMap);
545 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
546 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
547 regsAreCompatible(FromRegC, ToRegB, TRI)))
550 // If there is a use of regC between its last def (could be livein) and this
551 // instruction, then bail.
552 unsigned LastDefC = 0;
553 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
556 // If there is a use of regB between its last def (could be livein) and this
557 // instruction, then go ahead and make this transformation.
558 unsigned LastDefB = 0;
559 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
562 // Since there are no intervening uses for both registers, then commute
563 // if the def of regC is closer. Its live interval is shorter.
564 return LastDefB && LastDefC && LastDefC > LastDefB;
567 /// CommuteInstruction - Commute a two-address instruction and update the basic
568 /// block, distance map, and live variables if needed. Return true if it is
571 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
572 MachineFunction::iterator &mbbi,
573 unsigned RegB, unsigned RegC, unsigned Dist) {
574 MachineInstr *MI = mi;
575 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
576 MachineInstr *NewMI = TII->commuteInstruction(MI);
579 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
583 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
584 // If the instruction changed to commute it, update livevar.
587 // Update live variables
588 LV->replaceKillInstruction(RegC, MI, NewMI);
590 mbbi->insert(mi, NewMI); // Insert the new inst
591 mbbi->erase(mi); // Nuke the old inst.
593 DistanceMap.insert(std::make_pair(NewMI, Dist));
596 // Update source register map.
597 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
599 unsigned RegA = MI->getOperand(0).getReg();
600 SrcRegMap[RegA] = FromRegC;
606 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
607 /// given 2-address instruction to a 3-address one.
609 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
610 // Look for situations like this:
611 // %reg1024<def> = MOV r1
612 // %reg1025<def> = MOV r0
613 // %reg1026<def> = ADD %reg1024, %reg1025
615 // Turn ADD into a 3-address instruction to avoid a copy.
616 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
617 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
618 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
621 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
622 /// three address one. Return true if this transformation was successful.
624 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
625 MachineBasicBlock::iterator &nmi,
626 MachineFunction::iterator &mbbi,
627 unsigned RegB, unsigned Dist) {
628 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
630 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
631 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
634 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
635 // FIXME: Temporary workaround. If the new instruction doesn't
636 // uses RegB, convertToThreeAddress must have created more
637 // then one instruction.
638 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
640 mbbi->erase(mi); // Nuke the old inst.
643 DistanceMap.insert(std::make_pair(NewMI, Dist));
645 nmi = llvm::next(mi);
653 /// ProcessCopy - If the specified instruction is not yet processed, process it
654 /// if it's a copy. For a copy instruction, we find the physical registers the
655 /// source and destination registers might be mapped to. These are kept in
656 /// point-to maps used to determine future optimizations. e.g.
659 /// v1026 = add v1024, v1025
661 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
662 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
663 /// potentially joined with r1 on the output side. It's worthwhile to commute
664 /// 'add' to eliminate a copy.
665 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
666 MachineBasicBlock *MBB,
667 SmallPtrSet<MachineInstr*, 8> &Processed) {
668 if (Processed.count(MI))
671 bool IsSrcPhys, IsDstPhys;
672 unsigned SrcReg, DstReg;
673 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
676 if (IsDstPhys && !IsSrcPhys)
677 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
678 else if (!IsDstPhys && IsSrcPhys) {
679 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
681 assert(SrcRegMap[DstReg] == SrcReg &&
682 "Can't map to two src physical registers!");
684 SmallVector<unsigned, 4> VirtRegPairs;
687 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
688 IsCopy, NewReg, IsDstPhys)) {
690 if (!Processed.insert(UseMI))
694 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
695 if (DI != DistanceMap.end())
696 // Earlier in the same MBB.Reached via a back edge.
700 VirtRegPairs.push_back(NewReg);
703 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
705 assert(SrcRegMap[NewReg] == DstReg &&
706 "Can't map to two src physical registers!");
707 VirtRegPairs.push_back(NewReg);
711 if (!VirtRegPairs.empty()) {
712 unsigned ToReg = VirtRegPairs.back();
713 VirtRegPairs.pop_back();
714 while (!VirtRegPairs.empty()) {
715 unsigned FromReg = VirtRegPairs.back();
716 VirtRegPairs.pop_back();
717 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
719 assert(DstRegMap[FromReg] == ToReg &&
720 "Can't map to two dst physical registers!");
726 Processed.insert(MI);
729 /// isSafeToDelete - If the specified instruction does not produce any side
730 /// effects and all of its defs are dead, then it's safe to delete.
731 static bool isSafeToDelete(MachineInstr *MI,
732 const TargetInstrInfo *TII,
733 SmallVector<unsigned, 4> &Kills) {
734 const TargetInstrDesc &TID = MI->getDesc();
735 if (TID.mayStore() || TID.isCall())
737 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
740 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
741 MachineOperand &MO = MI->getOperand(i);
744 if (MO.isDef() && !MO.isDead())
746 if (MO.isUse() && MO.isKill())
747 Kills.push_back(MO.getReg());
752 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
753 /// killed by instructions in MBB preceding the current instruction at
754 /// position Dist. If so, return true and record information about the
755 /// preceding kills in NewKills.
756 bool TwoAddressInstructionPass::
757 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
758 SmallVector<NewKill, 4> &NewKills,
759 MachineBasicBlock *MBB, unsigned Dist) {
760 while (!Kills.empty()) {
761 unsigned Kill = Kills.back();
763 if (TargetRegisterInfo::isPhysicalRegister(Kill))
766 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
770 bool isModRef = LastKill->modifiesRegister(Kill);
771 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
777 /// DeleteUnusedInstr - If an instruction with a tied register operand can
778 /// be safely deleted, just delete it.
780 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
781 MachineBasicBlock::iterator &nmi,
782 MachineFunction::iterator &mbbi,
784 // Check if the instruction has no side effects and if all its defs are dead.
785 SmallVector<unsigned, 4> Kills;
786 if (!isSafeToDelete(mi, TII, Kills))
789 // If this instruction kills some virtual registers, we need to
790 // update the kill information. If it's not possible to do so,
792 SmallVector<NewKill, 4> NewKills;
793 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
797 while (!NewKills.empty()) {
798 MachineInstr *NewKill = NewKills.back().second;
799 unsigned Kill = NewKills.back().first.first;
800 bool isDead = NewKills.back().first.second;
802 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
804 LV->addVirtualRegisterDead(Kill, NewKill);
806 LV->addVirtualRegisterKilled(Kill, NewKill);
811 mbbi->erase(mi); // Nuke the old inst.
816 /// TryInstructionTransform - For the case where an instruction has a single
817 /// pair of tied register operands, attempt some transformations that may
818 /// either eliminate the tied operands or improve the opportunities for
819 /// coalescing away the register copy. Returns true if the tied operands
820 /// are eliminated altogether.
821 bool TwoAddressInstructionPass::
822 TryInstructionTransform(MachineBasicBlock::iterator &mi,
823 MachineBasicBlock::iterator &nmi,
824 MachineFunction::iterator &mbbi,
825 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
826 const TargetInstrDesc &TID = mi->getDesc();
827 unsigned regA = mi->getOperand(DstIdx).getReg();
828 unsigned regB = mi->getOperand(SrcIdx).getReg();
830 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
831 "cannot make instruction into two-address form");
833 // If regA is dead and the instruction can be deleted, just delete
834 // it so it doesn't clobber regB.
835 bool regBKilled = isKilled(*mi, regB, MRI, TII);
836 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
837 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
839 return true; // Done with this instruction.
842 // Check if it is profitable to commute the operands.
843 unsigned SrcOp1, SrcOp2;
845 unsigned regCIdx = ~0U;
846 bool TryCommute = false;
847 bool AggressiveCommute = false;
848 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
849 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
850 if (SrcIdx == SrcOp1)
852 else if (SrcIdx == SrcOp2)
855 if (regCIdx != ~0U) {
856 regC = mi->getOperand(regCIdx).getReg();
857 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
858 // If C dies but B does not, swap the B and C operands.
859 // This makes the live ranges of A and C joinable.
861 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
863 AggressiveCommute = true;
868 // If it's profitable to commute, try to do so.
869 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
871 if (AggressiveCommute)
876 if (TID.isConvertibleTo3Addr()) {
877 // This instruction is potentially convertible to a true
878 // three-address instruction. Check if it is profitable.
879 if (!regBKilled || isProfitableToConv3Addr(regA)) {
880 // Try to convert it.
881 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
882 ++NumConvertedTo3Addr;
883 return true; // Done with this instruction.
890 /// runOnMachineFunction - Reduce two-address instructions to two operands.
892 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
893 DEBUG(dbgs() << "Machine Function\n");
894 const TargetMachine &TM = MF.getTarget();
895 MRI = &MF.getRegInfo();
896 TII = TM.getInstrInfo();
897 TRI = TM.getRegisterInfo();
898 LV = getAnalysisIfAvailable<LiveVariables>();
899 AA = &getAnalysis<AliasAnalysis>();
901 bool MadeChange = false;
903 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
904 DEBUG(dbgs() << "********** Function: "
905 << MF.getFunction()->getName() << '\n');
907 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
909 ReMatRegs.resize(MRI->getLastVirtReg()+1);
911 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
913 TiedOperandMap TiedOperands(4);
915 SmallPtrSet<MachineInstr*, 8> Processed;
916 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
917 mbbi != mbbe; ++mbbi) {
923 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
925 MachineBasicBlock::iterator nmi = llvm::next(mi);
926 if (mi->isDebugValue()) {
930 const TargetInstrDesc &TID = mi->getDesc();
931 bool FirstTied = true;
933 DistanceMap.insert(std::make_pair(mi, ++Dist));
935 ProcessCopy(&*mi, &*mbbi, Processed);
937 // First scan through all the tied register uses in this instruction
938 // and record a list of pairs of tied operands for each register.
939 unsigned NumOps = mi->isInlineAsm()
940 ? mi->getNumOperands() : TID.getNumOperands();
941 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
943 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
948 ++NumTwoAddressInstrs;
949 DEBUG(dbgs() << '\t' << *mi);
952 assert(mi->getOperand(SrcIdx).isReg() &&
953 mi->getOperand(SrcIdx).getReg() &&
954 mi->getOperand(SrcIdx).isUse() &&
955 "two address instruction invalid");
957 unsigned regB = mi->getOperand(SrcIdx).getReg();
958 TiedOperandMap::iterator OI = TiedOperands.find(regB);
959 if (OI == TiedOperands.end()) {
960 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
961 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
963 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
966 // Now iterate over the information collected above.
967 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
968 OE = TiedOperands.end(); OI != OE; ++OI) {
969 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
971 // If the instruction has a single pair of tied operands, try some
972 // transformations that may either eliminate the tied operands or
973 // improve the opportunities for coalescing away the register copy.
974 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
975 unsigned SrcIdx = TiedPairs[0].first;
976 unsigned DstIdx = TiedPairs[0].second;
978 // If the registers are already equal, nothing needs to be done.
979 if (mi->getOperand(SrcIdx).getReg() ==
980 mi->getOperand(DstIdx).getReg())
981 break; // Done with this instruction.
983 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
984 break; // The tied operands have been eliminated.
987 bool RemovedKillFlag = false;
988 bool AllUsesCopied = true;
989 unsigned LastCopiedReg = 0;
990 unsigned regB = OI->first;
991 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
992 unsigned SrcIdx = TiedPairs[tpi].first;
993 unsigned DstIdx = TiedPairs[tpi].second;
994 unsigned regA = mi->getOperand(DstIdx).getReg();
995 // Grab regB from the instruction because it may have changed if the
996 // instruction was commuted.
997 regB = mi->getOperand(SrcIdx).getReg();
1000 // The register is tied to multiple destinations (or else we would
1001 // not have continued this far), but this use of the register
1002 // already matches the tied destination. Leave it.
1003 AllUsesCopied = false;
1006 LastCopiedReg = regA;
1008 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1009 "cannot make instruction into two-address form");
1012 // First, verify that we don't have a use of "a" in the instruction
1013 // (a = b + a for example) because our transformation will not
1014 // work. This should never occur because we are in SSA form.
1015 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1016 assert(i == DstIdx ||
1017 !mi->getOperand(i).isReg() ||
1018 mi->getOperand(i).getReg() != regA);
1021 // Emit a copy or rematerialize the definition.
1022 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1023 MachineInstr *DefMI = MRI->getVRegDef(regB);
1024 // If it's safe and profitable, remat the definition instead of
1027 DefMI->getDesc().isAsCheapAsAMove() &&
1028 DefMI->isSafeToReMat(TII, AA, regB) &&
1029 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1030 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1031 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1032 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, TRI);
1033 ReMatRegs.set(regB);
1036 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1038 assert(Emitted && "Unable to issue a copy instruction!\n");
1041 MachineBasicBlock::iterator prevMI = prior(mi);
1042 // Update DistanceMap.
1043 DistanceMap.insert(std::make_pair(prevMI, Dist));
1044 DistanceMap[mi] = ++Dist;
1046 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1048 MachineOperand &MO = mi->getOperand(SrcIdx);
1049 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1050 "inconsistent operand info for 2-reg pass");
1052 MO.setIsKill(false);
1053 RemovedKillFlag = true;
1058 if (AllUsesCopied) {
1059 // Replace other (un-tied) uses of regB with LastCopiedReg.
1060 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1061 MachineOperand &MO = mi->getOperand(i);
1062 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1064 MO.setIsKill(false);
1065 RemovedKillFlag = true;
1067 MO.setReg(LastCopiedReg);
1071 // Update live variables for regB.
1072 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1073 LV->addVirtualRegisterKilled(regB, prior(mi));
1075 } else if (RemovedKillFlag) {
1076 // Some tied uses of regB matched their destination registers, so
1077 // regB is still used in this instruction, but a kill flag was
1078 // removed from a different tied use of regB, so now we need to add
1079 // a kill flag to one of the remaining uses of regB.
1080 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1081 MachineOperand &MO = mi->getOperand(i);
1082 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1091 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1094 // Clear TiedOperands here instead of at the top of the loop
1095 // since most instructions do not have tied operands.
1096 TiedOperands.clear();
1101 // Some remat'ed instructions are dead.
1102 int VReg = ReMatRegs.find_first();
1103 while (VReg != -1) {
1104 if (MRI->use_empty(VReg)) {
1105 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1106 DefMI->eraseFromParent();
1108 VReg = ReMatRegs.find_next(VReg);