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/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/ADT/BitVector.h"
46 #include "llvm/ADT/DenseMap.h"
47 #include "llvm/ADT/SmallSet.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/STLExtras.h"
52 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
53 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
54 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
55 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
56 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
57 STATISTIC(NumReMats, "Number of instructions re-materialized");
58 STATISTIC(NumDeletes, "Number of dead instructions deleted");
61 class TwoAddressInstructionPass : public MachineFunctionPass {
62 const TargetInstrInfo *TII;
63 const TargetRegisterInfo *TRI;
64 MachineRegisterInfo *MRI;
68 // DistanceMap - Keep track the distance of a MI from the start of the
69 // current basic block.
70 DenseMap<MachineInstr*, unsigned> DistanceMap;
72 // SrcRegMap - A map from virtual registers to physical registers which
73 // are likely targets to be coalesced to due to copies from physical
74 // registers to virtual registers. e.g. v1024 = move r0.
75 DenseMap<unsigned, unsigned> SrcRegMap;
77 // DstRegMap - A map from virtual registers to physical registers which
78 // are likely targets to be coalesced to due to copies to physical
79 // registers from virtual registers. e.g. r1 = move v1024.
80 DenseMap<unsigned, unsigned> DstRegMap;
82 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
83 /// during the initial walk of the machine function.
84 SmallVector<MachineInstr*, 16> RegSequences;
86 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
88 MachineBasicBlock::iterator OldPos);
90 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
91 MachineInstr *MI, MachineInstr *DefMI,
92 MachineBasicBlock *MBB, unsigned Loc);
94 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
97 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
100 bool isProfitableToCommute(unsigned regB, unsigned regC,
101 MachineInstr *MI, MachineBasicBlock *MBB,
104 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
106 unsigned RegB, unsigned RegC, unsigned Dist);
108 bool isProfitableToConv3Addr(unsigned RegA);
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
113 unsigned RegB, unsigned Dist);
115 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
116 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
117 SmallVector<NewKill, 4> &NewKills,
118 MachineBasicBlock *MBB, unsigned Dist);
119 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
121 MachineFunction::iterator &mbbi, unsigned Dist);
123 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
125 MachineFunction::iterator &mbbi,
126 unsigned SrcIdx, unsigned DstIdx,
129 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
130 SmallPtrSet<MachineInstr*, 8> &Processed);
132 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
134 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
135 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
136 /// sub-register references of the register defined by REG_SEQUENCE.
137 bool EliminateRegSequences();
140 static char ID; // Pass identification, replacement for typeid
141 TwoAddressInstructionPass() : MachineFunctionPass(ID) {}
143 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
144 AU.setPreservesCFG();
145 AU.addRequired<AliasAnalysis>();
146 AU.addPreserved<LiveVariables>();
147 AU.addPreservedID(MachineLoopInfoID);
148 AU.addPreservedID(MachineDominatorsID);
150 AU.addPreservedID(StrongPHIEliminationID);
152 AU.addPreservedID(PHIEliminationID);
153 MachineFunctionPass::getAnalysisUsage(AU);
156 /// runOnMachineFunction - Pass entry point.
157 bool runOnMachineFunction(MachineFunction&);
161 char TwoAddressInstructionPass::ID = 0;
162 INITIALIZE_PASS(TwoAddressInstructionPass, "twoaddressinstruction",
163 "Two-Address instruction pass", false, false);
165 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
167 /// Sink3AddrInstruction - A two-address instruction has been converted to a
168 /// three-address instruction to avoid clobbering a register. Try to sink it
169 /// past the instruction that would kill the above mentioned register to reduce
170 /// register pressure.
171 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
172 MachineInstr *MI, unsigned SavedReg,
173 MachineBasicBlock::iterator OldPos) {
174 // Check if it's safe to move this instruction.
175 bool SeenStore = true; // Be conservative.
176 if (!MI->isSafeToMove(TII, AA, SeenStore))
180 SmallSet<unsigned, 4> UseRegs;
182 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
183 const MachineOperand &MO = MI->getOperand(i);
186 unsigned MOReg = MO.getReg();
189 if (MO.isUse() && MOReg != SavedReg)
190 UseRegs.insert(MO.getReg());
194 // Don't try to move it if it implicitly defines a register.
197 // For now, don't move any instructions that define multiple registers.
199 DefReg = MO.getReg();
202 // Find the instruction that kills SavedReg.
203 MachineInstr *KillMI = NULL;
204 for (MachineRegisterInfo::use_nodbg_iterator
205 UI = MRI->use_nodbg_begin(SavedReg),
206 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
207 MachineOperand &UseMO = UI.getOperand();
210 KillMI = UseMO.getParent();
214 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
217 // If any of the definitions are used by another instruction between the
218 // position and the kill use, then it's not safe to sink it.
220 // FIXME: This can be sped up if there is an easy way to query whether an
221 // instruction is before or after another instruction. Then we can use
222 // MachineRegisterInfo def / use instead.
223 MachineOperand *KillMO = NULL;
224 MachineBasicBlock::iterator KillPos = KillMI;
227 unsigned NumVisited = 0;
228 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
229 MachineInstr *OtherMI = I;
230 // DBG_VALUE cannot be counted against the limit.
231 if (OtherMI->isDebugValue())
233 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
236 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
237 MachineOperand &MO = OtherMI->getOperand(i);
240 unsigned MOReg = MO.getReg();
247 if (OtherMI == KillMI && MOReg == SavedReg)
248 // Save the operand that kills the register. We want to unset the kill
249 // marker if we can sink MI past it.
251 else if (UseRegs.count(MOReg))
252 // One of the uses is killed before the destination.
258 // Update kill and LV information.
259 KillMO->setIsKill(false);
260 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
261 KillMO->setIsKill(true);
264 LV->replaceKillInstruction(SavedReg, KillMI, MI);
266 // Move instruction to its destination.
268 MBB->insert(KillPos, MI);
274 /// isTwoAddrUse - Return true if the specified MI is using the specified
275 /// register as a two-address operand.
276 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
277 const TargetInstrDesc &TID = UseMI->getDesc();
278 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
279 MachineOperand &MO = UseMI->getOperand(i);
280 if (MO.isReg() && MO.getReg() == Reg &&
281 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
282 // Earlier use is a two-address one.
288 /// isProfitableToReMat - Return true if the heuristics determines it is likely
289 /// to be profitable to re-materialize the definition of Reg rather than copy
292 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
293 const TargetRegisterClass *RC,
294 MachineInstr *MI, MachineInstr *DefMI,
295 MachineBasicBlock *MBB, unsigned Loc) {
296 bool OtherUse = false;
297 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
298 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
299 MachineOperand &UseMO = UI.getOperand();
300 MachineInstr *UseMI = UseMO.getParent();
301 MachineBasicBlock *UseMBB = UseMI->getParent();
303 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
304 if (DI != DistanceMap.end() && DI->second == Loc)
305 continue; // Current use.
307 // There is at least one other use in the MBB that will clobber the
309 if (isTwoAddrUse(UseMI, Reg))
314 // If other uses in MBB are not two-address uses, then don't remat.
318 // No other uses in the same block, remat if it's defined in the same
319 // block so it does not unnecessarily extend the live range.
320 return MBB == DefMI->getParent();
323 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
324 /// last instruction in the MBB that defines the specified register and the
325 /// two-address instruction which is being processed. It also returns the last
326 /// def location by reference
327 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
328 MachineBasicBlock *MBB, unsigned Dist,
331 unsigned LastUse = Dist;
332 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
333 E = MRI->reg_end(); I != E; ++I) {
334 MachineOperand &MO = I.getOperand();
335 MachineInstr *MI = MO.getParent();
336 if (MI->getParent() != MBB || MI->isDebugValue())
338 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
339 if (DI == DistanceMap.end())
341 if (MO.isUse() && DI->second < LastUse)
342 LastUse = DI->second;
343 if (MO.isDef() && DI->second > LastDef)
344 LastDef = DI->second;
347 return !(LastUse > LastDef && LastUse < Dist);
350 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
351 MachineBasicBlock *MBB,
353 unsigned LastUseDist = 0;
354 MachineInstr *LastUse = 0;
355 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
356 E = MRI->reg_end(); I != E; ++I) {
357 MachineOperand &MO = I.getOperand();
358 MachineInstr *MI = MO.getParent();
359 if (MI->getParent() != MBB || MI->isDebugValue())
361 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
362 if (DI == DistanceMap.end())
364 if (DI->second >= Dist)
367 if (MO.isUse() && DI->second > LastUseDist) {
369 LastUseDist = DI->second;
375 /// isCopyToReg - Return true if the specified MI is a copy instruction or
376 /// a extract_subreg instruction. It also returns the source and destination
377 /// registers and whether they are physical registers by reference.
378 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
379 unsigned &SrcReg, unsigned &DstReg,
380 bool &IsSrcPhys, bool &IsDstPhys) {
384 DstReg = MI.getOperand(0).getReg();
385 SrcReg = MI.getOperand(1).getReg();
386 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
387 DstReg = MI.getOperand(0).getReg();
388 SrcReg = MI.getOperand(2).getReg();
392 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
393 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
397 /// isKilled - Test if the given register value, which is used by the given
398 /// instruction, is killed by the given instruction. This looks through
399 /// coalescable copies to see if the original value is potentially not killed.
401 /// For example, in this code:
403 /// %reg1034 = copy %reg1024
404 /// %reg1035 = copy %reg1025<kill>
405 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
407 /// %reg1034 is not considered to be killed, since it is copied from a
408 /// register which is not killed. Treating it as not killed lets the
409 /// normal heuristics commute the (two-address) add, which lets
410 /// coalescing eliminate the extra copy.
412 static bool isKilled(MachineInstr &MI, unsigned Reg,
413 const MachineRegisterInfo *MRI,
414 const TargetInstrInfo *TII) {
415 MachineInstr *DefMI = &MI;
417 if (!DefMI->killsRegister(Reg))
419 if (TargetRegisterInfo::isPhysicalRegister(Reg))
421 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
422 // If there are multiple defs, we can't do a simple analysis, so just
423 // go with what the kill flag says.
424 if (llvm::next(Begin) != MRI->def_end())
427 bool IsSrcPhys, IsDstPhys;
428 unsigned SrcReg, DstReg;
429 // If the def is something other than a copy, then it isn't going to
430 // be coalesced, so follow the kill flag.
431 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
437 /// isTwoAddrUse - Return true if the specified MI uses the specified register
438 /// as a two-address use. If so, return the destination register by reference.
439 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
440 const TargetInstrDesc &TID = MI.getDesc();
441 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
442 for (unsigned i = 0; i != NumOps; ++i) {
443 const MachineOperand &MO = MI.getOperand(i);
444 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
447 if (MI.isRegTiedToDefOperand(i, &ti)) {
448 DstReg = MI.getOperand(ti).getReg();
455 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
456 /// use, return the use instruction if it's a copy or a two-address use.
458 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
459 MachineRegisterInfo *MRI,
460 const TargetInstrInfo *TII,
462 unsigned &DstReg, bool &IsDstPhys) {
463 if (!MRI->hasOneNonDBGUse(Reg))
464 // None or more than one use.
466 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
467 if (UseMI.getParent() != MBB)
471 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
476 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
477 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
483 /// getMappedReg - Return the physical register the specified virtual register
484 /// might be mapped to.
486 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
487 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
488 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
489 if (SI == RegMap.end())
493 if (TargetRegisterInfo::isPhysicalRegister(Reg))
498 /// regsAreCompatible - Return true if the two registers are equal or aliased.
501 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
506 return TRI->regsOverlap(RegA, RegB);
510 /// isProfitableToReMat - Return true if it's potentially profitable to commute
511 /// the two-address instruction that's being processed.
513 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
514 MachineInstr *MI, MachineBasicBlock *MBB,
516 // Determine if it's profitable to commute this two address instruction. In
517 // general, we want no uses between this instruction and the definition of
518 // the two-address register.
520 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
521 // %reg1029<def> = MOV8rr %reg1028
522 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
523 // insert => %reg1030<def> = MOV8rr %reg1028
524 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
525 // In this case, it might not be possible to coalesce the second MOV8rr
526 // instruction if the first one is coalesced. So it would be profitable to
528 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
529 // %reg1029<def> = MOV8rr %reg1028
530 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
531 // insert => %reg1030<def> = MOV8rr %reg1029
532 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
534 if (!MI->killsRegister(regC))
537 // Ok, we have something like:
538 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
539 // let's see if it's worth commuting it.
541 // Look for situations like this:
542 // %reg1024<def> = MOV r1
543 // %reg1025<def> = MOV r0
544 // %reg1026<def> = ADD %reg1024, %reg1025
546 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
547 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
548 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
549 unsigned ToRegB = getMappedReg(regB, DstRegMap);
550 unsigned ToRegC = getMappedReg(regC, DstRegMap);
551 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
552 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
553 regsAreCompatible(FromRegC, ToRegB, TRI)))
556 // If there is a use of regC between its last def (could be livein) and this
557 // instruction, then bail.
558 unsigned LastDefC = 0;
559 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
562 // If there is a use of regB between its last def (could be livein) and this
563 // instruction, then go ahead and make this transformation.
564 unsigned LastDefB = 0;
565 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
568 // Since there are no intervening uses for both registers, then commute
569 // if the def of regC is closer. Its live interval is shorter.
570 return LastDefB && LastDefC && LastDefC > LastDefB;
573 /// CommuteInstruction - Commute a two-address instruction and update the basic
574 /// block, distance map, and live variables if needed. Return true if it is
577 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
578 MachineFunction::iterator &mbbi,
579 unsigned RegB, unsigned RegC, unsigned Dist) {
580 MachineInstr *MI = mi;
581 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
582 MachineInstr *NewMI = TII->commuteInstruction(MI);
585 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
589 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
590 // If the instruction changed to commute it, update livevar.
593 // Update live variables
594 LV->replaceKillInstruction(RegC, MI, NewMI);
596 mbbi->insert(mi, NewMI); // Insert the new inst
597 mbbi->erase(mi); // Nuke the old inst.
599 DistanceMap.insert(std::make_pair(NewMI, Dist));
602 // Update source register map.
603 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
605 unsigned RegA = MI->getOperand(0).getReg();
606 SrcRegMap[RegA] = FromRegC;
612 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
613 /// given 2-address instruction to a 3-address one.
615 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
616 // Look for situations like this:
617 // %reg1024<def> = MOV r1
618 // %reg1025<def> = MOV r0
619 // %reg1026<def> = ADD %reg1024, %reg1025
621 // Turn ADD into a 3-address instruction to avoid a copy.
622 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
623 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
624 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
627 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
628 /// three address one. Return true if this transformation was successful.
630 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
631 MachineBasicBlock::iterator &nmi,
632 MachineFunction::iterator &mbbi,
633 unsigned RegB, unsigned Dist) {
634 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
636 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
637 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
640 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
641 // FIXME: Temporary workaround. If the new instruction doesn't
642 // uses RegB, convertToThreeAddress must have created more
643 // then one instruction.
644 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
646 mbbi->erase(mi); // Nuke the old inst.
649 DistanceMap.insert(std::make_pair(NewMI, Dist));
651 nmi = llvm::next(mi);
659 /// ProcessCopy - If the specified instruction is not yet processed, process it
660 /// if it's a copy. For a copy instruction, we find the physical registers the
661 /// source and destination registers might be mapped to. These are kept in
662 /// point-to maps used to determine future optimizations. e.g.
665 /// v1026 = add v1024, v1025
667 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
668 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
669 /// potentially joined with r1 on the output side. It's worthwhile to commute
670 /// 'add' to eliminate a copy.
671 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
672 MachineBasicBlock *MBB,
673 SmallPtrSet<MachineInstr*, 8> &Processed) {
674 if (Processed.count(MI))
677 bool IsSrcPhys, IsDstPhys;
678 unsigned SrcReg, DstReg;
679 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
682 if (IsDstPhys && !IsSrcPhys)
683 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
684 else if (!IsDstPhys && IsSrcPhys) {
685 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
687 assert(SrcRegMap[DstReg] == SrcReg &&
688 "Can't map to two src physical registers!");
690 SmallVector<unsigned, 4> VirtRegPairs;
693 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
694 IsCopy, NewReg, IsDstPhys)) {
696 if (!Processed.insert(UseMI))
700 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
701 if (DI != DistanceMap.end())
702 // Earlier in the same MBB.Reached via a back edge.
706 VirtRegPairs.push_back(NewReg);
709 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
711 assert(SrcRegMap[NewReg] == DstReg &&
712 "Can't map to two src physical registers!");
713 VirtRegPairs.push_back(NewReg);
717 if (!VirtRegPairs.empty()) {
718 unsigned ToReg = VirtRegPairs.back();
719 VirtRegPairs.pop_back();
720 while (!VirtRegPairs.empty()) {
721 unsigned FromReg = VirtRegPairs.back();
722 VirtRegPairs.pop_back();
723 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
725 assert(DstRegMap[FromReg] == ToReg &&
726 "Can't map to two dst physical registers!");
732 Processed.insert(MI);
735 /// isSafeToDelete - If the specified instruction does not produce any side
736 /// effects and all of its defs are dead, then it's safe to delete.
737 static bool isSafeToDelete(MachineInstr *MI,
738 const TargetInstrInfo *TII,
739 SmallVector<unsigned, 4> &Kills) {
740 const TargetInstrDesc &TID = MI->getDesc();
741 if (TID.mayStore() || TID.isCall())
743 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
746 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
747 MachineOperand &MO = MI->getOperand(i);
750 if (MO.isDef() && !MO.isDead())
752 if (MO.isUse() && MO.isKill())
753 Kills.push_back(MO.getReg());
758 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
759 /// killed by instructions in MBB preceding the current instruction at
760 /// position Dist. If so, return true and record information about the
761 /// preceding kills in NewKills.
762 bool TwoAddressInstructionPass::
763 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
764 SmallVector<NewKill, 4> &NewKills,
765 MachineBasicBlock *MBB, unsigned Dist) {
766 while (!Kills.empty()) {
767 unsigned Kill = Kills.back();
769 if (TargetRegisterInfo::isPhysicalRegister(Kill))
772 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
776 bool isModRef = LastKill->definesRegister(Kill);
777 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
783 /// DeleteUnusedInstr - If an instruction with a tied register operand can
784 /// be safely deleted, just delete it.
786 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
787 MachineBasicBlock::iterator &nmi,
788 MachineFunction::iterator &mbbi,
790 // Check if the instruction has no side effects and if all its defs are dead.
791 SmallVector<unsigned, 4> Kills;
792 if (!isSafeToDelete(mi, TII, Kills))
795 // If this instruction kills some virtual registers, we need to
796 // update the kill information. If it's not possible to do so,
798 SmallVector<NewKill, 4> NewKills;
799 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
803 while (!NewKills.empty()) {
804 MachineInstr *NewKill = NewKills.back().second;
805 unsigned Kill = NewKills.back().first.first;
806 bool isDead = NewKills.back().first.second;
808 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
810 LV->addVirtualRegisterDead(Kill, NewKill);
812 LV->addVirtualRegisterKilled(Kill, NewKill);
817 mbbi->erase(mi); // Nuke the old inst.
822 /// TryInstructionTransform - For the case where an instruction has a single
823 /// pair of tied register operands, attempt some transformations that may
824 /// either eliminate the tied operands or improve the opportunities for
825 /// coalescing away the register copy. Returns true if the tied operands
826 /// are eliminated altogether.
827 bool TwoAddressInstructionPass::
828 TryInstructionTransform(MachineBasicBlock::iterator &mi,
829 MachineBasicBlock::iterator &nmi,
830 MachineFunction::iterator &mbbi,
831 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
832 const TargetInstrDesc &TID = mi->getDesc();
833 unsigned regA = mi->getOperand(DstIdx).getReg();
834 unsigned regB = mi->getOperand(SrcIdx).getReg();
836 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
837 "cannot make instruction into two-address form");
839 // If regA is dead and the instruction can be deleted, just delete
840 // it so it doesn't clobber regB.
841 bool regBKilled = isKilled(*mi, regB, MRI, TII);
842 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
843 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
845 return true; // Done with this instruction.
848 // Check if it is profitable to commute the operands.
849 unsigned SrcOp1, SrcOp2;
851 unsigned regCIdx = ~0U;
852 bool TryCommute = false;
853 bool AggressiveCommute = false;
854 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
855 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
856 if (SrcIdx == SrcOp1)
858 else if (SrcIdx == SrcOp2)
861 if (regCIdx != ~0U) {
862 regC = mi->getOperand(regCIdx).getReg();
863 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
864 // If C dies but B does not, swap the B and C operands.
865 // This makes the live ranges of A and C joinable.
867 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
869 AggressiveCommute = true;
874 // If it's profitable to commute, try to do so.
875 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
877 if (AggressiveCommute)
882 if (TID.isConvertibleTo3Addr()) {
883 // This instruction is potentially convertible to a true
884 // three-address instruction. Check if it is profitable.
885 if (!regBKilled || isProfitableToConv3Addr(regA)) {
886 // Try to convert it.
887 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
888 ++NumConvertedTo3Addr;
889 return true; // Done with this instruction.
894 // If this is an instruction with a load folded into it, try unfolding
895 // the load, e.g. avoid this:
901 // because it's preferable to schedule a load than a register copy.
902 if (TID.mayLoad() && !regBKilled) {
903 // Determine if a load can be unfolded.
904 unsigned LoadRegIndex;
906 TII->getOpcodeAfterMemoryUnfold(mi->getOpcode(),
908 /*UnfoldStore=*/false,
911 const TargetInstrDesc &UnfoldTID = TII->get(NewOpc);
912 if (UnfoldTID.getNumDefs() == 1) {
913 MachineFunction &MF = *mbbi->getParent();
916 DEBUG(dbgs() << "2addr: UNFOLDING: " << *mi);
917 const TargetRegisterClass *RC =
918 UnfoldTID.OpInfo[LoadRegIndex].getRegClass(TRI);
919 unsigned Reg = MRI->createVirtualRegister(RC);
920 SmallVector<MachineInstr *, 2> NewMIs;
921 if (!TII->unfoldMemoryOperand(MF, mi, Reg,
922 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
924 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
927 assert(NewMIs.size() == 2 &&
928 "Unfolded a load into multiple instructions!");
929 // The load was previously folded, so this is the only use.
930 NewMIs[1]->addRegisterKilled(Reg, TRI);
932 // Tentatively insert the instructions into the block so that they
933 // look "normal" to the transformation logic.
934 mbbi->insert(mi, NewMIs[0]);
935 mbbi->insert(mi, NewMIs[1]);
937 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
938 << "2addr: NEW INST: " << *NewMIs[1]);
940 // Transform the instruction, now that it no longer has a load.
941 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
942 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
943 MachineBasicBlock::iterator NewMI = NewMIs[1];
944 bool TransformSuccess =
945 TryInstructionTransform(NewMI, mi, mbbi,
946 NewSrcIdx, NewDstIdx, Dist);
947 if (TransformSuccess ||
948 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
949 // Success, or at least we made an improvement. Keep the unfolded
950 // instructions and discard the original.
952 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
953 MachineOperand &MO = mi->getOperand(i);
954 if (MO.isReg() && MO.getReg() != 0 &&
955 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
958 if (NewMIs[0]->killsRegister(MO.getReg()))
959 LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[0]);
961 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
962 "Kill missing after load unfold!");
963 LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[1]);
966 } else if (LV->removeVirtualRegisterDead(MO.getReg(), mi)) {
967 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
968 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
970 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
971 "Dead flag missing after load unfold!");
972 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
977 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
979 mi->eraseFromParent();
981 if (TransformSuccess)
984 // Transforming didn't eliminate the tie and didn't lead to an
985 // improvement. Clean up the unfolded instructions and keep the
987 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
988 NewMIs[0]->eraseFromParent();
989 NewMIs[1]->eraseFromParent();
998 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1000 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1001 DEBUG(dbgs() << "Machine Function\n");
1002 const TargetMachine &TM = MF.getTarget();
1003 MRI = &MF.getRegInfo();
1004 TII = TM.getInstrInfo();
1005 TRI = TM.getRegisterInfo();
1006 LV = getAnalysisIfAvailable<LiveVariables>();
1007 AA = &getAnalysis<AliasAnalysis>();
1009 bool MadeChange = false;
1011 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1012 DEBUG(dbgs() << "********** Function: "
1013 << MF.getFunction()->getName() << '\n');
1015 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1016 BitVector ReMatRegs;
1017 ReMatRegs.resize(MRI->getLastVirtReg()+1);
1019 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1021 TiedOperandMap TiedOperands(4);
1023 SmallPtrSet<MachineInstr*, 8> Processed;
1024 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1025 mbbi != mbbe; ++mbbi) {
1027 DistanceMap.clear();
1031 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1033 MachineBasicBlock::iterator nmi = llvm::next(mi);
1034 if (mi->isDebugValue()) {
1039 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1040 if (mi->isRegSequence())
1041 RegSequences.push_back(&*mi);
1043 const TargetInstrDesc &TID = mi->getDesc();
1044 bool FirstTied = true;
1046 DistanceMap.insert(std::make_pair(mi, ++Dist));
1048 ProcessCopy(&*mi, &*mbbi, Processed);
1050 // First scan through all the tied register uses in this instruction
1051 // and record a list of pairs of tied operands for each register.
1052 unsigned NumOps = mi->isInlineAsm()
1053 ? mi->getNumOperands() : TID.getNumOperands();
1054 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1055 unsigned DstIdx = 0;
1056 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1061 ++NumTwoAddressInstrs;
1062 DEBUG(dbgs() << '\t' << *mi);
1065 assert(mi->getOperand(SrcIdx).isReg() &&
1066 mi->getOperand(SrcIdx).getReg() &&
1067 mi->getOperand(SrcIdx).isUse() &&
1068 "two address instruction invalid");
1070 unsigned regB = mi->getOperand(SrcIdx).getReg();
1071 TiedOperandMap::iterator OI = TiedOperands.find(regB);
1072 if (OI == TiedOperands.end()) {
1073 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
1074 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
1076 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
1079 // Now iterate over the information collected above.
1080 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1081 OE = TiedOperands.end(); OI != OE; ++OI) {
1082 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1084 // If the instruction has a single pair of tied operands, try some
1085 // transformations that may either eliminate the tied operands or
1086 // improve the opportunities for coalescing away the register copy.
1087 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1088 unsigned SrcIdx = TiedPairs[0].first;
1089 unsigned DstIdx = TiedPairs[0].second;
1091 // If the registers are already equal, nothing needs to be done.
1092 if (mi->getOperand(SrcIdx).getReg() ==
1093 mi->getOperand(DstIdx).getReg())
1094 break; // Done with this instruction.
1096 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
1097 break; // The tied operands have been eliminated.
1100 bool RemovedKillFlag = false;
1101 bool AllUsesCopied = true;
1102 unsigned LastCopiedReg = 0;
1103 unsigned regB = OI->first;
1104 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1105 unsigned SrcIdx = TiedPairs[tpi].first;
1106 unsigned DstIdx = TiedPairs[tpi].second;
1107 unsigned regA = mi->getOperand(DstIdx).getReg();
1108 // Grab regB from the instruction because it may have changed if the
1109 // instruction was commuted.
1110 regB = mi->getOperand(SrcIdx).getReg();
1113 // The register is tied to multiple destinations (or else we would
1114 // not have continued this far), but this use of the register
1115 // already matches the tied destination. Leave it.
1116 AllUsesCopied = false;
1119 LastCopiedReg = regA;
1121 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1122 "cannot make instruction into two-address form");
1125 // First, verify that we don't have a use of "a" in the instruction
1126 // (a = b + a for example) because our transformation will not
1127 // work. This should never occur because we are in SSA form.
1128 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1129 assert(i == DstIdx ||
1130 !mi->getOperand(i).isReg() ||
1131 mi->getOperand(i).getReg() != regA);
1134 // Emit a copy or rematerialize the definition.
1135 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1136 MachineInstr *DefMI = MRI->getVRegDef(regB);
1137 // If it's safe and profitable, remat the definition instead of
1140 DefMI->getDesc().isAsCheapAsAMove() &&
1141 DefMI->isSafeToReMat(TII, AA, regB) &&
1142 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1143 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1144 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1145 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
1146 ReMatRegs.set(regB);
1149 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1153 MachineBasicBlock::iterator prevMI = prior(mi);
1154 // Update DistanceMap.
1155 DistanceMap.insert(std::make_pair(prevMI, Dist));
1156 DistanceMap[mi] = ++Dist;
1158 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1160 MachineOperand &MO = mi->getOperand(SrcIdx);
1161 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1162 "inconsistent operand info for 2-reg pass");
1164 MO.setIsKill(false);
1165 RemovedKillFlag = true;
1170 if (AllUsesCopied) {
1171 // Replace other (un-tied) uses of regB with LastCopiedReg.
1172 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1173 MachineOperand &MO = mi->getOperand(i);
1174 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1176 MO.setIsKill(false);
1177 RemovedKillFlag = true;
1179 MO.setReg(LastCopiedReg);
1183 // Update live variables for regB.
1184 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1185 LV->addVirtualRegisterKilled(regB, prior(mi));
1187 } else if (RemovedKillFlag) {
1188 // Some tied uses of regB matched their destination registers, so
1189 // regB is still used in this instruction, but a kill flag was
1190 // removed from a different tied use of regB, so now we need to add
1191 // a kill flag to one of the remaining uses of regB.
1192 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1193 MachineOperand &MO = mi->getOperand(i);
1194 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1201 // Schedule the source copy / remat inserted to form two-address
1202 // instruction. FIXME: Does it matter the distance map may not be
1203 // accurate after it's scheduled?
1204 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1208 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1211 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1212 if (mi->isInsertSubreg()) {
1213 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1214 // To %reg:subidx = COPY %subreg
1215 unsigned SubIdx = mi->getOperand(3).getImm();
1216 mi->RemoveOperand(3);
1217 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1218 mi->getOperand(0).setSubReg(SubIdx);
1219 mi->RemoveOperand(1);
1220 mi->setDesc(TII->get(TargetOpcode::COPY));
1221 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1224 // Clear TiedOperands here instead of at the top of the loop
1225 // since most instructions do not have tied operands.
1226 TiedOperands.clear();
1231 // Some remat'ed instructions are dead.
1232 int VReg = ReMatRegs.find_first();
1233 while (VReg != -1) {
1234 if (MRI->use_nodbg_empty(VReg)) {
1235 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1236 DefMI->eraseFromParent();
1238 VReg = ReMatRegs.find_next(VReg);
1241 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1242 // SSA form. It's now safe to de-SSA.
1243 MadeChange |= EliminateRegSequences();
1248 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1249 unsigned DstReg, unsigned SubIdx,
1250 MachineRegisterInfo *MRI,
1251 const TargetRegisterInfo &TRI) {
1252 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1253 RE = MRI->reg_end(); RI != RE; ) {
1254 MachineOperand &MO = RI.getOperand();
1256 MO.substVirtReg(DstReg, SubIdx, TRI);
1260 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1261 /// EXTRACT_SUBREG from the same register and to the same virtual register
1262 /// with different sub-register indices, attempt to combine the
1263 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1264 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1265 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1266 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1267 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1268 /// reg1026 to reg1029.
1270 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1272 SmallSet<unsigned, 4> Seen;
1273 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1274 unsigned SrcReg = Srcs[i];
1275 if (!Seen.insert(SrcReg))
1278 // Check that the instructions are all in the same basic block.
1279 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1280 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1281 if (SrcDefMI->getParent() != DstDefMI->getParent())
1284 // If there are no other uses than copies which feed into
1285 // the reg_sequence, then we might be able to coalesce them.
1286 bool CanCoalesce = true;
1287 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1288 for (MachineRegisterInfo::use_nodbg_iterator
1289 UI = MRI->use_nodbg_begin(SrcReg),
1290 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1291 MachineInstr *UseMI = &*UI;
1292 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1293 CanCoalesce = false;
1296 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1297 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1300 if (!CanCoalesce || SrcSubIndices.size() < 2)
1303 // Check that the source subregisters can be combined.
1304 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1305 unsigned NewSrcSubIdx = 0;
1306 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1310 // Check that the destination subregisters can also be combined.
1311 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1312 unsigned NewDstSubIdx = 0;
1313 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1317 // If neither source nor destination can be combined to the full register,
1318 // just give up. This could be improved if it ever matters.
1319 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1322 // Now that we know that all the uses are extract_subregs and that those
1323 // subregs can somehow be combined, scan all the extract_subregs again to
1324 // make sure the subregs are in the right order and can be composed.
1325 MachineInstr *SomeMI = 0;
1327 for (MachineRegisterInfo::use_nodbg_iterator
1328 UI = MRI->use_nodbg_begin(SrcReg),
1329 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1330 MachineInstr *UseMI = &*UI;
1331 assert(UseMI->isCopy());
1332 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1333 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1334 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1335 if ((NewDstSubIdx == 0 &&
1336 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1337 (NewSrcSubIdx == 0 &&
1338 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1339 CanCoalesce = false;
1342 // Keep track of one of the uses.
1348 // Insert a copy to replace the original.
1349 MachineBasicBlock::iterator InsertLoc = SomeMI;
1350 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1351 SomeMI->getDebugLoc(),
1352 TII->get(TargetOpcode::COPY))
1353 .addReg(DstReg, RegState::Define, NewDstSubIdx)
1354 .addReg(SrcReg, 0, NewSrcSubIdx);
1356 // Remove all the old extract instructions.
1357 for (MachineRegisterInfo::use_nodbg_iterator
1358 UI = MRI->use_nodbg_begin(SrcReg),
1359 UE = MRI->use_nodbg_end(); UI != UE; ) {
1360 MachineInstr *UseMI = &*UI;
1362 if (UseMI == CopyMI)
1364 assert(UseMI->isCopy());
1365 // Move any kills to the new copy or extract instruction.
1366 if (UseMI->getOperand(1).isKill()) {
1367 CopyMI->getOperand(1).setIsKill();
1369 // Update live variables
1370 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1372 UseMI->eraseFromParent();
1377 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1378 MachineRegisterInfo *MRI) {
1379 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1380 UE = MRI->use_end(); UI != UE; ++UI) {
1381 MachineInstr *UseMI = &*UI;
1382 if (UseMI != RegSeq && UseMI->isRegSequence())
1388 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1389 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1390 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1392 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1393 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1395 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1396 bool TwoAddressInstructionPass::EliminateRegSequences() {
1397 if (RegSequences.empty())
1400 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1401 MachineInstr *MI = RegSequences[i];
1402 unsigned DstReg = MI->getOperand(0).getReg();
1403 if (MI->getOperand(0).getSubReg() ||
1404 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1405 !(MI->getNumOperands() & 1)) {
1406 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1407 llvm_unreachable(0);
1410 bool IsImpDef = true;
1411 SmallVector<unsigned, 4> RealSrcs;
1412 SmallSet<unsigned, 4> Seen;
1413 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1414 unsigned SrcReg = MI->getOperand(i).getReg();
1415 if (MI->getOperand(i).getSubReg() ||
1416 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1417 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1418 llvm_unreachable(0);
1421 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
1422 if (DefMI->isImplicitDef()) {
1423 DefMI->eraseFromParent();
1428 // Remember COPY sources. These might be candidate for coalescing.
1429 if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1430 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1432 bool isKill = MI->getOperand(i).isKill();
1433 if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
1434 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI)) {
1435 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1436 // Also add an copy if the source is live-in the block. We don't want
1437 // to end up with a partial-redef of a livein, e.g.
1439 // reg1051:10<def> =
1445 // LiveIntervalAnalysis won't like it.
1447 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1448 // correctly up to date becomes very difficult. Insert a copy.
1450 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1451 // might insert a COPY that uses SrcReg after is was killed.
1453 for (unsigned j = i + 2; j < e; j += 2)
1454 if (MI->getOperand(j).getReg() == SrcReg) {
1455 MI->getOperand(j).setIsKill();
1460 MachineBasicBlock::iterator InsertLoc = MI;
1461 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1462 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1463 .addReg(DstReg, RegState::Define, MI->getOperand(i+1).getImm())
1464 .addReg(SrcReg, getKillRegState(isKill));
1465 MI->getOperand(i).setReg(0);
1467 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1468 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1472 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1473 unsigned SrcReg = MI->getOperand(i).getReg();
1474 if (!SrcReg) continue;
1475 unsigned SubIdx = MI->getOperand(i+1).getImm();
1476 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1480 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1481 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1482 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1483 MI->RemoveOperand(j);
1485 DEBUG(dbgs() << "Eliminated: " << *MI);
1486 MI->eraseFromParent();
1489 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1490 // INSERT_SUBREG instructions that must have <undef> flags added by
1491 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1493 CoalesceExtSubRegs(RealSrcs, DstReg);
1496 RegSequences.clear();