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
, unsigned RegB
);
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator
&mi
,
111 MachineBasicBlock::iterator
&nmi
,
112 MachineFunction::iterator
&mbbi
,
113 unsigned RegA
, 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
,
128 SmallPtrSet
<MachineInstr
*, 8> &Processed
);
130 void ScanUses(unsigned DstReg
, MachineBasicBlock
*MBB
,
131 SmallPtrSet
<MachineInstr
*, 8> &Processed
);
133 void ProcessCopy(MachineInstr
*MI
, MachineBasicBlock
*MBB
,
134 SmallPtrSet
<MachineInstr
*, 8> &Processed
);
136 void CoalesceExtSubRegs(SmallVector
<unsigned,4> &Srcs
, unsigned DstReg
);
138 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
139 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
140 /// sub-register references of the register defined by REG_SEQUENCE.
141 bool EliminateRegSequences();
144 static char ID
; // Pass identification, replacement for typeid
145 TwoAddressInstructionPass() : MachineFunctionPass(ID
) {
146 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
149 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
150 AU
.setPreservesCFG();
151 AU
.addRequired
<AliasAnalysis
>();
152 AU
.addPreserved
<LiveVariables
>();
153 AU
.addPreservedID(MachineLoopInfoID
);
154 AU
.addPreservedID(MachineDominatorsID
);
155 AU
.addPreservedID(PHIEliminationID
);
156 MachineFunctionPass::getAnalysisUsage(AU
);
159 /// runOnMachineFunction - Pass entry point.
160 bool runOnMachineFunction(MachineFunction
&);
164 char TwoAddressInstructionPass::ID
= 0;
165 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass
, "twoaddressinstruction",
166 "Two-Address instruction pass", false, false)
167 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
168 INITIALIZE_PASS_END(TwoAddressInstructionPass
, "twoaddressinstruction",
169 "Two-Address instruction pass", false, false)
171 char &llvm::TwoAddressInstructionPassID
= TwoAddressInstructionPass::ID
;
173 /// Sink3AddrInstruction - A two-address instruction has been converted to a
174 /// three-address instruction to avoid clobbering a register. Try to sink it
175 /// past the instruction that would kill the above mentioned register to reduce
176 /// register pressure.
177 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock
*MBB
,
178 MachineInstr
*MI
, unsigned SavedReg
,
179 MachineBasicBlock::iterator OldPos
) {
180 // Check if it's safe to move this instruction.
181 bool SeenStore
= true; // Be conservative.
182 if (!MI
->isSafeToMove(TII
, AA
, SeenStore
))
186 SmallSet
<unsigned, 4> UseRegs
;
188 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
189 const MachineOperand
&MO
= MI
->getOperand(i
);
192 unsigned MOReg
= MO
.getReg();
195 if (MO
.isUse() && MOReg
!= SavedReg
)
196 UseRegs
.insert(MO
.getReg());
200 // Don't try to move it if it implicitly defines a register.
203 // For now, don't move any instructions that define multiple registers.
205 DefReg
= MO
.getReg();
208 // Find the instruction that kills SavedReg.
209 MachineInstr
*KillMI
= NULL
;
210 for (MachineRegisterInfo::use_nodbg_iterator
211 UI
= MRI
->use_nodbg_begin(SavedReg
),
212 UE
= MRI
->use_nodbg_end(); UI
!= UE
; ++UI
) {
213 MachineOperand
&UseMO
= UI
.getOperand();
216 KillMI
= UseMO
.getParent();
220 if (!KillMI
|| KillMI
->getParent() != MBB
|| KillMI
== MI
)
223 // If any of the definitions are used by another instruction between the
224 // position and the kill use, then it's not safe to sink it.
226 // FIXME: This can be sped up if there is an easy way to query whether an
227 // instruction is before or after another instruction. Then we can use
228 // MachineRegisterInfo def / use instead.
229 MachineOperand
*KillMO
= NULL
;
230 MachineBasicBlock::iterator KillPos
= KillMI
;
233 unsigned NumVisited
= 0;
234 for (MachineBasicBlock::iterator I
= llvm::next(OldPos
); I
!= KillPos
; ++I
) {
235 MachineInstr
*OtherMI
= I
;
236 // DBG_VALUE cannot be counted against the limit.
237 if (OtherMI
->isDebugValue())
239 if (NumVisited
> 30) // FIXME: Arbitrary limit to reduce compile time cost.
242 for (unsigned i
= 0, e
= OtherMI
->getNumOperands(); i
!= e
; ++i
) {
243 MachineOperand
&MO
= OtherMI
->getOperand(i
);
246 unsigned MOReg
= MO
.getReg();
253 if (OtherMI
== KillMI
&& MOReg
== SavedReg
)
254 // Save the operand that kills the register. We want to unset the kill
255 // marker if we can sink MI past it.
257 else if (UseRegs
.count(MOReg
))
258 // One of the uses is killed before the destination.
264 // Update kill and LV information.
265 KillMO
->setIsKill(false);
266 KillMO
= MI
->findRegisterUseOperand(SavedReg
, false, TRI
);
267 KillMO
->setIsKill(true);
270 LV
->replaceKillInstruction(SavedReg
, KillMI
, MI
);
272 // Move instruction to its destination.
274 MBB
->insert(KillPos
, MI
);
280 /// isTwoAddrUse - Return true if the specified MI is using the specified
281 /// register as a two-address operand.
282 static bool isTwoAddrUse(MachineInstr
*UseMI
, unsigned Reg
) {
283 const TargetInstrDesc
&TID
= UseMI
->getDesc();
284 for (unsigned i
= 0, e
= TID
.getNumOperands(); i
!= e
; ++i
) {
285 MachineOperand
&MO
= UseMI
->getOperand(i
);
286 if (MO
.isReg() && MO
.getReg() == Reg
&&
287 (MO
.isDef() || UseMI
->isRegTiedToDefOperand(i
)))
288 // Earlier use is a two-address one.
294 /// isProfitableToReMat - Return true if the heuristics determines it is likely
295 /// to be profitable to re-materialize the definition of Reg rather than copy
298 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg
,
299 const TargetRegisterClass
*RC
,
300 MachineInstr
*MI
, MachineInstr
*DefMI
,
301 MachineBasicBlock
*MBB
, unsigned Loc
) {
302 bool OtherUse
= false;
303 for (MachineRegisterInfo::use_nodbg_iterator UI
= MRI
->use_nodbg_begin(Reg
),
304 UE
= MRI
->use_nodbg_end(); UI
!= UE
; ++UI
) {
305 MachineOperand
&UseMO
= UI
.getOperand();
306 MachineInstr
*UseMI
= UseMO
.getParent();
307 MachineBasicBlock
*UseMBB
= UseMI
->getParent();
309 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(UseMI
);
310 if (DI
!= DistanceMap
.end() && DI
->second
== Loc
)
311 continue; // Current use.
313 // There is at least one other use in the MBB that will clobber the
315 if (isTwoAddrUse(UseMI
, Reg
))
320 // If other uses in MBB are not two-address uses, then don't remat.
324 // No other uses in the same block, remat if it's defined in the same
325 // block so it does not unnecessarily extend the live range.
326 return MBB
== DefMI
->getParent();
329 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
330 /// last instruction in the MBB that defines the specified register and the
331 /// two-address instruction which is being processed. It also returns the last
332 /// def location by reference
333 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg
,
334 MachineBasicBlock
*MBB
, unsigned Dist
,
337 unsigned LastUse
= Dist
;
338 for (MachineRegisterInfo::reg_iterator I
= MRI
->reg_begin(Reg
),
339 E
= MRI
->reg_end(); I
!= E
; ++I
) {
340 MachineOperand
&MO
= I
.getOperand();
341 MachineInstr
*MI
= MO
.getParent();
342 if (MI
->getParent() != MBB
|| MI
->isDebugValue())
344 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(MI
);
345 if (DI
== DistanceMap
.end())
347 if (MO
.isUse() && DI
->second
< LastUse
)
348 LastUse
= DI
->second
;
349 if (MO
.isDef() && DI
->second
> LastDef
)
350 LastDef
= DI
->second
;
353 return !(LastUse
> LastDef
&& LastUse
< Dist
);
356 MachineInstr
*TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg
,
357 MachineBasicBlock
*MBB
,
359 unsigned LastUseDist
= 0;
360 MachineInstr
*LastUse
= 0;
361 for (MachineRegisterInfo::reg_iterator I
= MRI
->reg_begin(Reg
),
362 E
= MRI
->reg_end(); I
!= E
; ++I
) {
363 MachineOperand
&MO
= I
.getOperand();
364 MachineInstr
*MI
= MO
.getParent();
365 if (MI
->getParent() != MBB
|| MI
->isDebugValue())
367 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(MI
);
368 if (DI
== DistanceMap
.end())
370 if (DI
->second
>= Dist
)
373 if (MO
.isUse() && DI
->second
> LastUseDist
) {
375 LastUseDist
= DI
->second
;
381 /// isCopyToReg - Return true if the specified MI is a copy instruction or
382 /// a extract_subreg instruction. It also returns the source and destination
383 /// registers and whether they are physical registers by reference.
384 static bool isCopyToReg(MachineInstr
&MI
, const TargetInstrInfo
*TII
,
385 unsigned &SrcReg
, unsigned &DstReg
,
386 bool &IsSrcPhys
, bool &IsDstPhys
) {
390 DstReg
= MI
.getOperand(0).getReg();
391 SrcReg
= MI
.getOperand(1).getReg();
392 } else if (MI
.isInsertSubreg() || MI
.isSubregToReg()) {
393 DstReg
= MI
.getOperand(0).getReg();
394 SrcReg
= MI
.getOperand(2).getReg();
398 IsSrcPhys
= TargetRegisterInfo::isPhysicalRegister(SrcReg
);
399 IsDstPhys
= TargetRegisterInfo::isPhysicalRegister(DstReg
);
403 /// isKilled - Test if the given register value, which is used by the given
404 /// instruction, is killed by the given instruction. This looks through
405 /// coalescable copies to see if the original value is potentially not killed.
407 /// For example, in this code:
409 /// %reg1034 = copy %reg1024
410 /// %reg1035 = copy %reg1025<kill>
411 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
413 /// %reg1034 is not considered to be killed, since it is copied from a
414 /// register which is not killed. Treating it as not killed lets the
415 /// normal heuristics commute the (two-address) add, which lets
416 /// coalescing eliminate the extra copy.
418 static bool isKilled(MachineInstr
&MI
, unsigned Reg
,
419 const MachineRegisterInfo
*MRI
,
420 const TargetInstrInfo
*TII
) {
421 MachineInstr
*DefMI
= &MI
;
423 if (!DefMI
->killsRegister(Reg
))
425 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
427 MachineRegisterInfo::def_iterator Begin
= MRI
->def_begin(Reg
);
428 // If there are multiple defs, we can't do a simple analysis, so just
429 // go with what the kill flag says.
430 if (llvm::next(Begin
) != MRI
->def_end())
433 bool IsSrcPhys
, IsDstPhys
;
434 unsigned SrcReg
, DstReg
;
435 // If the def is something other than a copy, then it isn't going to
436 // be coalesced, so follow the kill flag.
437 if (!isCopyToReg(*DefMI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
))
443 /// isTwoAddrUse - Return true if the specified MI uses the specified register
444 /// as a two-address use. If so, return the destination register by reference.
445 static bool isTwoAddrUse(MachineInstr
&MI
, unsigned Reg
, unsigned &DstReg
) {
446 const TargetInstrDesc
&TID
= MI
.getDesc();
447 unsigned NumOps
= MI
.isInlineAsm() ? MI
.getNumOperands():TID
.getNumOperands();
448 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
449 const MachineOperand
&MO
= MI
.getOperand(i
);
450 if (!MO
.isReg() || !MO
.isUse() || MO
.getReg() != Reg
)
453 if (MI
.isRegTiedToDefOperand(i
, &ti
)) {
454 DstReg
= MI
.getOperand(ti
).getReg();
461 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
462 /// use, return the use instruction if it's a copy or a two-address use.
464 MachineInstr
*findOnlyInterestingUse(unsigned Reg
, MachineBasicBlock
*MBB
,
465 MachineRegisterInfo
*MRI
,
466 const TargetInstrInfo
*TII
,
468 unsigned &DstReg
, bool &IsDstPhys
) {
469 if (!MRI
->hasOneNonDBGUse(Reg
))
470 // None or more than one use.
472 MachineInstr
&UseMI
= *MRI
->use_nodbg_begin(Reg
);
473 if (UseMI
.getParent() != MBB
)
477 if (isCopyToReg(UseMI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
)) {
482 if (isTwoAddrUse(UseMI
, Reg
, DstReg
)) {
483 IsDstPhys
= TargetRegisterInfo::isPhysicalRegister(DstReg
);
489 /// getMappedReg - Return the physical register the specified virtual register
490 /// might be mapped to.
492 getMappedReg(unsigned Reg
, DenseMap
<unsigned, unsigned> &RegMap
) {
493 while (TargetRegisterInfo::isVirtualRegister(Reg
)) {
494 DenseMap
<unsigned, unsigned>::iterator SI
= RegMap
.find(Reg
);
495 if (SI
== RegMap
.end())
499 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
504 /// regsAreCompatible - Return true if the two registers are equal or aliased.
507 regsAreCompatible(unsigned RegA
, unsigned RegB
, const TargetRegisterInfo
*TRI
) {
512 return TRI
->regsOverlap(RegA
, RegB
);
516 /// isProfitableToReMat - Return true if it's potentially profitable to commute
517 /// the two-address instruction that's being processed.
519 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB
, unsigned regC
,
520 MachineInstr
*MI
, MachineBasicBlock
*MBB
,
522 // Determine if it's profitable to commute this two address instruction. In
523 // general, we want no uses between this instruction and the definition of
524 // the two-address register.
526 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
527 // %reg1029<def> = MOV8rr %reg1028
528 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
529 // insert => %reg1030<def> = MOV8rr %reg1028
530 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
531 // In this case, it might not be possible to coalesce the second MOV8rr
532 // instruction if the first one is coalesced. So it would be profitable to
534 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
535 // %reg1029<def> = MOV8rr %reg1028
536 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
537 // insert => %reg1030<def> = MOV8rr %reg1029
538 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
540 if (!MI
->killsRegister(regC
))
543 // Ok, we have something like:
544 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
545 // let's see if it's worth commuting it.
547 // Look for situations like this:
548 // %reg1024<def> = MOV r1
549 // %reg1025<def> = MOV r0
550 // %reg1026<def> = ADD %reg1024, %reg1025
552 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
553 unsigned FromRegB
= getMappedReg(regB
, SrcRegMap
);
554 unsigned FromRegC
= getMappedReg(regC
, SrcRegMap
);
555 unsigned ToRegB
= getMappedReg(regB
, DstRegMap
);
556 unsigned ToRegC
= getMappedReg(regC
, DstRegMap
);
557 if ((FromRegB
&& ToRegB
&& !regsAreCompatible(FromRegB
, ToRegB
, TRI
)) &&
558 ((!FromRegC
&& !ToRegC
) ||
559 regsAreCompatible(FromRegB
, ToRegC
, TRI
) ||
560 regsAreCompatible(FromRegC
, ToRegB
, TRI
)))
563 // If there is a use of regC between its last def (could be livein) and this
564 // instruction, then bail.
565 unsigned LastDefC
= 0;
566 if (!NoUseAfterLastDef(regC
, MBB
, Dist
, LastDefC
))
569 // If there is a use of regB between its last def (could be livein) and this
570 // instruction, then go ahead and make this transformation.
571 unsigned LastDefB
= 0;
572 if (!NoUseAfterLastDef(regB
, MBB
, Dist
, LastDefB
))
575 // Since there are no intervening uses for both registers, then commute
576 // if the def of regC is closer. Its live interval is shorter.
577 return LastDefB
&& LastDefC
&& LastDefC
> LastDefB
;
580 /// CommuteInstruction - Commute a two-address instruction and update the basic
581 /// block, distance map, and live variables if needed. Return true if it is
584 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator
&mi
,
585 MachineFunction::iterator
&mbbi
,
586 unsigned RegB
, unsigned RegC
, unsigned Dist
) {
587 MachineInstr
*MI
= mi
;
588 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI
);
589 MachineInstr
*NewMI
= TII
->commuteInstruction(MI
);
592 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
596 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI
);
597 // If the instruction changed to commute it, update livevar.
600 // Update live variables
601 LV
->replaceKillInstruction(RegC
, MI
, NewMI
);
603 mbbi
->insert(mi
, NewMI
); // Insert the new inst
604 mbbi
->erase(mi
); // Nuke the old inst.
606 DistanceMap
.insert(std::make_pair(NewMI
, Dist
));
609 // Update source register map.
610 unsigned FromRegC
= getMappedReg(RegC
, SrcRegMap
);
612 unsigned RegA
= MI
->getOperand(0).getReg();
613 SrcRegMap
[RegA
] = FromRegC
;
619 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
620 /// given 2-address instruction to a 3-address one.
622 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA
,unsigned RegB
){
623 // Look for situations like this:
624 // %reg1024<def> = MOV r1
625 // %reg1025<def> = MOV r0
626 // %reg1026<def> = ADD %reg1024, %reg1025
628 // Turn ADD into a 3-address instruction to avoid a copy.
629 unsigned FromRegB
= getMappedReg(RegB
, SrcRegMap
);
632 unsigned ToRegA
= getMappedReg(RegA
, DstRegMap
);
633 return (ToRegA
&& !regsAreCompatible(FromRegB
, ToRegA
, TRI
));
636 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
637 /// three address one. Return true if this transformation was successful.
639 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator
&mi
,
640 MachineBasicBlock::iterator
&nmi
,
641 MachineFunction::iterator
&mbbi
,
642 unsigned RegA
, unsigned RegB
,
644 MachineInstr
*NewMI
= TII
->convertToThreeAddress(mbbi
, mi
, LV
);
646 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi
);
647 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI
);
650 if (NewMI
->findRegisterUseOperand(RegB
, false, TRI
))
651 // FIXME: Temporary workaround. If the new instruction doesn't
652 // uses RegB, convertToThreeAddress must have created more
653 // then one instruction.
654 Sunk
= Sink3AddrInstruction(mbbi
, NewMI
, RegB
, mi
);
656 mbbi
->erase(mi
); // Nuke the old inst.
659 DistanceMap
.insert(std::make_pair(NewMI
, Dist
));
661 nmi
= llvm::next(mi
);
664 // Update source and destination register maps.
665 SrcRegMap
.erase(RegA
);
666 DstRegMap
.erase(RegB
);
673 /// ScanUses - Scan forward recursively for only uses, update maps if the use
674 /// is a copy or a two-address instruction.
676 TwoAddressInstructionPass::ScanUses(unsigned DstReg
, MachineBasicBlock
*MBB
,
677 SmallPtrSet
<MachineInstr
*, 8> &Processed
) {
678 SmallVector
<unsigned, 4> VirtRegPairs
;
682 unsigned Reg
= DstReg
;
683 while (MachineInstr
*UseMI
= findOnlyInterestingUse(Reg
, MBB
, MRI
, TII
,IsCopy
,
684 NewReg
, IsDstPhys
)) {
685 if (IsCopy
&& !Processed
.insert(UseMI
))
688 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(UseMI
);
689 if (DI
!= DistanceMap
.end())
690 // Earlier in the same MBB.Reached via a back edge.
694 VirtRegPairs
.push_back(NewReg
);
697 bool isNew
= SrcRegMap
.insert(std::make_pair(NewReg
, Reg
)).second
;
699 assert(SrcRegMap
[NewReg
] == Reg
&& "Can't map to two src registers!");
700 VirtRegPairs
.push_back(NewReg
);
704 if (!VirtRegPairs
.empty()) {
705 unsigned ToReg
= VirtRegPairs
.back();
706 VirtRegPairs
.pop_back();
707 while (!VirtRegPairs
.empty()) {
708 unsigned FromReg
= VirtRegPairs
.back();
709 VirtRegPairs
.pop_back();
710 bool isNew
= DstRegMap
.insert(std::make_pair(FromReg
, ToReg
)).second
;
712 assert(DstRegMap
[FromReg
] == ToReg
&&"Can't map to two dst registers!");
715 bool isNew
= DstRegMap
.insert(std::make_pair(DstReg
, ToReg
)).second
;
717 assert(DstRegMap
[DstReg
] == ToReg
&& "Can't map to two dst registers!");
721 /// ProcessCopy - If the specified instruction is not yet processed, process it
722 /// if it's a copy. For a copy instruction, we find the physical registers the
723 /// source and destination registers might be mapped to. These are kept in
724 /// point-to maps used to determine future optimizations. e.g.
727 /// v1026 = add v1024, v1025
729 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
730 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
731 /// potentially joined with r1 on the output side. It's worthwhile to commute
732 /// 'add' to eliminate a copy.
733 void TwoAddressInstructionPass::ProcessCopy(MachineInstr
*MI
,
734 MachineBasicBlock
*MBB
,
735 SmallPtrSet
<MachineInstr
*, 8> &Processed
) {
736 if (Processed
.count(MI
))
739 bool IsSrcPhys
, IsDstPhys
;
740 unsigned SrcReg
, DstReg
;
741 if (!isCopyToReg(*MI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
))
744 if (IsDstPhys
&& !IsSrcPhys
)
745 DstRegMap
.insert(std::make_pair(SrcReg
, DstReg
));
746 else if (!IsDstPhys
&& IsSrcPhys
) {
747 bool isNew
= SrcRegMap
.insert(std::make_pair(DstReg
, SrcReg
)).second
;
749 assert(SrcRegMap
[DstReg
] == SrcReg
&&
750 "Can't map to two src physical registers!");
752 ScanUses(DstReg
, MBB
, Processed
);
755 Processed
.insert(MI
);
759 /// isSafeToDelete - If the specified instruction does not produce any side
760 /// effects and all of its defs are dead, then it's safe to delete.
761 static bool isSafeToDelete(MachineInstr
*MI
,
762 const TargetInstrInfo
*TII
,
763 SmallVector
<unsigned, 4> &Kills
) {
764 const TargetInstrDesc
&TID
= MI
->getDesc();
765 if (TID
.mayStore() || TID
.isCall())
767 if (TID
.isTerminator() || MI
->hasUnmodeledSideEffects())
770 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
771 MachineOperand
&MO
= MI
->getOperand(i
);
774 if (MO
.isDef() && !MO
.isDead())
776 if (MO
.isUse() && MO
.isKill())
777 Kills
.push_back(MO
.getReg());
782 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
783 /// killed by instructions in MBB preceding the current instruction at
784 /// position Dist. If so, return true and record information about the
785 /// preceding kills in NewKills.
786 bool TwoAddressInstructionPass::
787 canUpdateDeletedKills(SmallVector
<unsigned, 4> &Kills
,
788 SmallVector
<NewKill
, 4> &NewKills
,
789 MachineBasicBlock
*MBB
, unsigned Dist
) {
790 while (!Kills
.empty()) {
791 unsigned Kill
= Kills
.back();
793 if (TargetRegisterInfo::isPhysicalRegister(Kill
))
796 MachineInstr
*LastKill
= FindLastUseInMBB(Kill
, MBB
, Dist
);
800 bool isModRef
= LastKill
->definesRegister(Kill
);
801 NewKills
.push_back(std::make_pair(std::make_pair(Kill
, isModRef
),
807 /// DeleteUnusedInstr - If an instruction with a tied register operand can
808 /// be safely deleted, just delete it.
810 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator
&mi
,
811 MachineBasicBlock::iterator
&nmi
,
812 MachineFunction::iterator
&mbbi
,
814 // Check if the instruction has no side effects and if all its defs are dead.
815 SmallVector
<unsigned, 4> Kills
;
816 if (!isSafeToDelete(mi
, TII
, Kills
))
819 // If this instruction kills some virtual registers, we need to
820 // update the kill information. If it's not possible to do so,
822 SmallVector
<NewKill
, 4> NewKills
;
823 if (!canUpdateDeletedKills(Kills
, NewKills
, &*mbbi
, Dist
))
827 while (!NewKills
.empty()) {
828 MachineInstr
*NewKill
= NewKills
.back().second
;
829 unsigned Kill
= NewKills
.back().first
.first
;
830 bool isDead
= NewKills
.back().first
.second
;
832 if (LV
->removeVirtualRegisterKilled(Kill
, mi
)) {
834 LV
->addVirtualRegisterDead(Kill
, NewKill
);
836 LV
->addVirtualRegisterKilled(Kill
, NewKill
);
841 mbbi
->erase(mi
); // Nuke the old inst.
846 /// TryInstructionTransform - For the case where an instruction has a single
847 /// pair of tied register operands, attempt some transformations that may
848 /// either eliminate the tied operands or improve the opportunities for
849 /// coalescing away the register copy. Returns true if the tied operands
850 /// are eliminated altogether.
851 bool TwoAddressInstructionPass::
852 TryInstructionTransform(MachineBasicBlock::iterator
&mi
,
853 MachineBasicBlock::iterator
&nmi
,
854 MachineFunction::iterator
&mbbi
,
855 unsigned SrcIdx
, unsigned DstIdx
, unsigned Dist
,
856 SmallPtrSet
<MachineInstr
*, 8> &Processed
) {
857 const TargetInstrDesc
&TID
= mi
->getDesc();
858 unsigned regA
= mi
->getOperand(DstIdx
).getReg();
859 unsigned regB
= mi
->getOperand(SrcIdx
).getReg();
861 assert(TargetRegisterInfo::isVirtualRegister(regB
) &&
862 "cannot make instruction into two-address form");
864 // If regA is dead and the instruction can be deleted, just delete
865 // it so it doesn't clobber regB.
866 bool regBKilled
= isKilled(*mi
, regB
, MRI
, TII
);
867 if (!regBKilled
&& mi
->getOperand(DstIdx
).isDead() &&
868 DeleteUnusedInstr(mi
, nmi
, mbbi
, Dist
)) {
870 return true; // Done with this instruction.
873 // Check if it is profitable to commute the operands.
874 unsigned SrcOp1
, SrcOp2
;
876 unsigned regCIdx
= ~0U;
877 bool TryCommute
= false;
878 bool AggressiveCommute
= false;
879 if (TID
.isCommutable() && mi
->getNumOperands() >= 3 &&
880 TII
->findCommutedOpIndices(mi
, SrcOp1
, SrcOp2
)) {
881 if (SrcIdx
== SrcOp1
)
883 else if (SrcIdx
== SrcOp2
)
886 if (regCIdx
!= ~0U) {
887 regC
= mi
->getOperand(regCIdx
).getReg();
888 if (!regBKilled
&& isKilled(*mi
, regC
, MRI
, TII
))
889 // If C dies but B does not, swap the B and C operands.
890 // This makes the live ranges of A and C joinable.
892 else if (isProfitableToCommute(regB
, regC
, mi
, mbbi
, Dist
)) {
894 AggressiveCommute
= true;
899 // If it's profitable to commute, try to do so.
900 if (TryCommute
&& CommuteInstruction(mi
, mbbi
, regB
, regC
, Dist
)) {
902 if (AggressiveCommute
)
907 if (TargetRegisterInfo::isVirtualRegister(regA
))
908 ScanUses(regA
, &*mbbi
, Processed
);
910 if (TID
.isConvertibleTo3Addr()) {
911 // This instruction is potentially convertible to a true
912 // three-address instruction. Check if it is profitable.
913 if (!regBKilled
|| isProfitableToConv3Addr(regA
, regB
)) {
914 // Try to convert it.
915 if (ConvertInstTo3Addr(mi
, nmi
, mbbi
, regA
, regB
, Dist
)) {
916 ++NumConvertedTo3Addr
;
917 return true; // Done with this instruction.
922 // If this is an instruction with a load folded into it, try unfolding
923 // the load, e.g. avoid this:
929 // because it's preferable to schedule a load than a register copy.
930 if (TID
.mayLoad() && !regBKilled
) {
931 // Determine if a load can be unfolded.
932 unsigned LoadRegIndex
;
934 TII
->getOpcodeAfterMemoryUnfold(mi
->getOpcode(),
936 /*UnfoldStore=*/false,
939 const TargetInstrDesc
&UnfoldTID
= TII
->get(NewOpc
);
940 if (UnfoldTID
.getNumDefs() == 1) {
941 MachineFunction
&MF
= *mbbi
->getParent();
944 DEBUG(dbgs() << "2addr: UNFOLDING: " << *mi
);
945 const TargetRegisterClass
*RC
=
946 UnfoldTID
.OpInfo
[LoadRegIndex
].getRegClass(TRI
);
947 unsigned Reg
= MRI
->createVirtualRegister(RC
);
948 SmallVector
<MachineInstr
*, 2> NewMIs
;
949 if (!TII
->unfoldMemoryOperand(MF
, mi
, Reg
,
950 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
952 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
955 assert(NewMIs
.size() == 2 &&
956 "Unfolded a load into multiple instructions!");
957 // The load was previously folded, so this is the only use.
958 NewMIs
[1]->addRegisterKilled(Reg
, TRI
);
960 // Tentatively insert the instructions into the block so that they
961 // look "normal" to the transformation logic.
962 mbbi
->insert(mi
, NewMIs
[0]);
963 mbbi
->insert(mi
, NewMIs
[1]);
965 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs
[0]
966 << "2addr: NEW INST: " << *NewMIs
[1]);
968 // Transform the instruction, now that it no longer has a load.
969 unsigned NewDstIdx
= NewMIs
[1]->findRegisterDefOperandIdx(regA
);
970 unsigned NewSrcIdx
= NewMIs
[1]->findRegisterUseOperandIdx(regB
);
971 MachineBasicBlock::iterator NewMI
= NewMIs
[1];
972 bool TransformSuccess
=
973 TryInstructionTransform(NewMI
, mi
, mbbi
,
974 NewSrcIdx
, NewDstIdx
, Dist
, Processed
);
975 if (TransformSuccess
||
976 NewMIs
[1]->getOperand(NewSrcIdx
).isKill()) {
977 // Success, or at least we made an improvement. Keep the unfolded
978 // instructions and discard the original.
980 for (unsigned i
= 0, e
= mi
->getNumOperands(); i
!= e
; ++i
) {
981 MachineOperand
&MO
= mi
->getOperand(i
);
983 TargetRegisterInfo::isVirtualRegister(MO
.getReg())) {
986 if (NewMIs
[0]->killsRegister(MO
.getReg()))
987 LV
->replaceKillInstruction(MO
.getReg(), mi
, NewMIs
[0]);
989 assert(NewMIs
[1]->killsRegister(MO
.getReg()) &&
990 "Kill missing after load unfold!");
991 LV
->replaceKillInstruction(MO
.getReg(), mi
, NewMIs
[1]);
994 } else if (LV
->removeVirtualRegisterDead(MO
.getReg(), mi
)) {
995 if (NewMIs
[1]->registerDefIsDead(MO
.getReg()))
996 LV
->addVirtualRegisterDead(MO
.getReg(), NewMIs
[1]);
998 assert(NewMIs
[0]->registerDefIsDead(MO
.getReg()) &&
999 "Dead flag missing after load unfold!");
1000 LV
->addVirtualRegisterDead(MO
.getReg(), NewMIs
[0]);
1005 LV
->addVirtualRegisterKilled(Reg
, NewMIs
[1]);
1007 mi
->eraseFromParent();
1009 if (TransformSuccess
)
1012 // Transforming didn't eliminate the tie and didn't lead to an
1013 // improvement. Clean up the unfolded instructions and keep the
1015 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1016 NewMIs
[0]->eraseFromParent();
1017 NewMIs
[1]->eraseFromParent();
1026 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1028 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction
&MF
) {
1029 DEBUG(dbgs() << "Machine Function\n");
1030 const TargetMachine
&TM
= MF
.getTarget();
1031 MRI
= &MF
.getRegInfo();
1032 TII
= TM
.getInstrInfo();
1033 TRI
= TM
.getRegisterInfo();
1034 LV
= getAnalysisIfAvailable
<LiveVariables
>();
1035 AA
= &getAnalysis
<AliasAnalysis
>();
1037 bool MadeChange
= false;
1039 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1040 DEBUG(dbgs() << "********** Function: "
1041 << MF
.getFunction()->getName() << '\n');
1043 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1044 BitVector
ReMatRegs(MRI
->getNumVirtRegs());
1046 typedef DenseMap
<unsigned, SmallVector
<std::pair
<unsigned, unsigned>, 4> >
1048 TiedOperandMap
TiedOperands(4);
1050 SmallPtrSet
<MachineInstr
*, 8> Processed
;
1051 for (MachineFunction::iterator mbbi
= MF
.begin(), mbbe
= MF
.end();
1052 mbbi
!= mbbe
; ++mbbi
) {
1054 DistanceMap
.clear();
1058 for (MachineBasicBlock::iterator mi
= mbbi
->begin(), me
= mbbi
->end();
1060 MachineBasicBlock::iterator nmi
= llvm::next(mi
);
1061 if (mi
->isDebugValue()) {
1066 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1067 if (mi
->isRegSequence())
1068 RegSequences
.push_back(&*mi
);
1070 const TargetInstrDesc
&TID
= mi
->getDesc();
1071 bool FirstTied
= true;
1073 DistanceMap
.insert(std::make_pair(mi
, ++Dist
));
1075 ProcessCopy(&*mi
, &*mbbi
, Processed
);
1077 // First scan through all the tied register uses in this instruction
1078 // and record a list of pairs of tied operands for each register.
1079 unsigned NumOps
= mi
->isInlineAsm()
1080 ? mi
->getNumOperands() : TID
.getNumOperands();
1081 for (unsigned SrcIdx
= 0; SrcIdx
< NumOps
; ++SrcIdx
) {
1082 unsigned DstIdx
= 0;
1083 if (!mi
->isRegTiedToDefOperand(SrcIdx
, &DstIdx
))
1088 ++NumTwoAddressInstrs
;
1089 DEBUG(dbgs() << '\t' << *mi
);
1092 assert(mi
->getOperand(SrcIdx
).isReg() &&
1093 mi
->getOperand(SrcIdx
).getReg() &&
1094 mi
->getOperand(SrcIdx
).isUse() &&
1095 "two address instruction invalid");
1097 unsigned regB
= mi
->getOperand(SrcIdx
).getReg();
1098 TiedOperandMap::iterator OI
= TiedOperands
.find(regB
);
1099 if (OI
== TiedOperands
.end()) {
1100 SmallVector
<std::pair
<unsigned, unsigned>, 4> TiedPair
;
1101 OI
= TiedOperands
.insert(std::make_pair(regB
, TiedPair
)).first
;
1103 OI
->second
.push_back(std::make_pair(SrcIdx
, DstIdx
));
1106 // Now iterate over the information collected above.
1107 for (TiedOperandMap::iterator OI
= TiedOperands
.begin(),
1108 OE
= TiedOperands
.end(); OI
!= OE
; ++OI
) {
1109 SmallVector
<std::pair
<unsigned, unsigned>, 4> &TiedPairs
= OI
->second
;
1111 // If the instruction has a single pair of tied operands, try some
1112 // transformations that may either eliminate the tied operands or
1113 // improve the opportunities for coalescing away the register copy.
1114 if (TiedOperands
.size() == 1 && TiedPairs
.size() == 1) {
1115 unsigned SrcIdx
= TiedPairs
[0].first
;
1116 unsigned DstIdx
= TiedPairs
[0].second
;
1118 // If the registers are already equal, nothing needs to be done.
1119 if (mi
->getOperand(SrcIdx
).getReg() ==
1120 mi
->getOperand(DstIdx
).getReg())
1121 break; // Done with this instruction.
1123 if (TryInstructionTransform(mi
, nmi
, mbbi
, SrcIdx
, DstIdx
, Dist
,
1125 break; // The tied operands have been eliminated.
1128 bool RemovedKillFlag
= false;
1129 bool AllUsesCopied
= true;
1130 unsigned LastCopiedReg
= 0;
1131 unsigned regB
= OI
->first
;
1132 for (unsigned tpi
= 0, tpe
= TiedPairs
.size(); tpi
!= tpe
; ++tpi
) {
1133 unsigned SrcIdx
= TiedPairs
[tpi
].first
;
1134 unsigned DstIdx
= TiedPairs
[tpi
].second
;
1135 unsigned regA
= mi
->getOperand(DstIdx
).getReg();
1136 // Grab regB from the instruction because it may have changed if the
1137 // instruction was commuted.
1138 regB
= mi
->getOperand(SrcIdx
).getReg();
1141 // The register is tied to multiple destinations (or else we would
1142 // not have continued this far), but this use of the register
1143 // already matches the tied destination. Leave it.
1144 AllUsesCopied
= false;
1147 LastCopiedReg
= regA
;
1149 assert(TargetRegisterInfo::isVirtualRegister(regB
) &&
1150 "cannot make instruction into two-address form");
1153 // First, verify that we don't have a use of "a" in the instruction
1154 // (a = b + a for example) because our transformation will not
1155 // work. This should never occur because we are in SSA form.
1156 for (unsigned i
= 0; i
!= mi
->getNumOperands(); ++i
)
1157 assert(i
== DstIdx
||
1158 !mi
->getOperand(i
).isReg() ||
1159 mi
->getOperand(i
).getReg() != regA
);
1162 // Emit a copy or rematerialize the definition.
1163 const TargetRegisterClass
*rc
= MRI
->getRegClass(regB
);
1164 MachineInstr
*DefMI
= MRI
->getVRegDef(regB
);
1165 // If it's safe and profitable, remat the definition instead of
1168 DefMI
->getDesc().isAsCheapAsAMove() &&
1169 DefMI
->isSafeToReMat(TII
, AA
, regB
) &&
1170 isProfitableToReMat(regB
, rc
, mi
, DefMI
, mbbi
, Dist
)){
1171 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI
<< "\n");
1172 unsigned regASubIdx
= mi
->getOperand(DstIdx
).getSubReg();
1173 TII
->reMaterialize(*mbbi
, mi
, regA
, regASubIdx
, DefMI
, *TRI
);
1174 ReMatRegs
.set(TargetRegisterInfo::virtReg2Index(regB
));
1177 BuildMI(*mbbi
, mi
, mi
->getDebugLoc(), TII
->get(TargetOpcode::COPY
),
1181 MachineBasicBlock::iterator prevMI
= prior(mi
);
1182 // Update DistanceMap.
1183 DistanceMap
.insert(std::make_pair(prevMI
, Dist
));
1184 DistanceMap
[mi
] = ++Dist
;
1186 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI
);
1188 MachineOperand
&MO
= mi
->getOperand(SrcIdx
);
1189 assert(MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse() &&
1190 "inconsistent operand info for 2-reg pass");
1192 MO
.setIsKill(false);
1193 RemovedKillFlag
= true;
1198 if (AllUsesCopied
) {
1199 // Replace other (un-tied) uses of regB with LastCopiedReg.
1200 for (unsigned i
= 0, e
= mi
->getNumOperands(); i
!= e
; ++i
) {
1201 MachineOperand
&MO
= mi
->getOperand(i
);
1202 if (MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse()) {
1204 MO
.setIsKill(false);
1205 RemovedKillFlag
= true;
1207 MO
.setReg(LastCopiedReg
);
1211 // Update live variables for regB.
1212 if (RemovedKillFlag
&& LV
&& LV
->getVarInfo(regB
).removeKill(mi
))
1213 LV
->addVirtualRegisterKilled(regB
, prior(mi
));
1215 } else if (RemovedKillFlag
) {
1216 // Some tied uses of regB matched their destination registers, so
1217 // regB is still used in this instruction, but a kill flag was
1218 // removed from a different tied use of regB, so now we need to add
1219 // a kill flag to one of the remaining uses of regB.
1220 for (unsigned i
= 0, e
= mi
->getNumOperands(); i
!= e
; ++i
) {
1221 MachineOperand
&MO
= mi
->getOperand(i
);
1222 if (MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse()) {
1229 // Schedule the source copy / remat inserted to form two-address
1230 // instruction. FIXME: Does it matter the distance map may not be
1231 // accurate after it's scheduled?
1232 TII
->scheduleTwoAddrSource(prior(mi
), mi
, *TRI
);
1236 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi
);
1239 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1240 if (mi
->isInsertSubreg()) {
1241 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1242 // To %reg:subidx = COPY %subreg
1243 unsigned SubIdx
= mi
->getOperand(3).getImm();
1244 mi
->RemoveOperand(3);
1245 assert(mi
->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1246 mi
->getOperand(0).setSubReg(SubIdx
);
1247 mi
->RemoveOperand(1);
1248 mi
->setDesc(TII
->get(TargetOpcode::COPY
));
1249 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi
);
1252 // Clear TiedOperands here instead of at the top of the loop
1253 // since most instructions do not have tied operands.
1254 TiedOperands
.clear();
1259 // Some remat'ed instructions are dead.
1260 for (int i
= ReMatRegs
.find_first(); i
!= -1; i
= ReMatRegs
.find_next(i
)) {
1261 unsigned VReg
= TargetRegisterInfo::index2VirtReg(i
);
1262 if (MRI
->use_nodbg_empty(VReg
)) {
1263 MachineInstr
*DefMI
= MRI
->getVRegDef(VReg
);
1264 DefMI
->eraseFromParent();
1268 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1269 // SSA form. It's now safe to de-SSA.
1270 MadeChange
|= EliminateRegSequences();
1275 static void UpdateRegSequenceSrcs(unsigned SrcReg
,
1276 unsigned DstReg
, unsigned SubIdx
,
1277 MachineRegisterInfo
*MRI
,
1278 const TargetRegisterInfo
&TRI
) {
1279 for (MachineRegisterInfo::reg_iterator RI
= MRI
->reg_begin(SrcReg
),
1280 RE
= MRI
->reg_end(); RI
!= RE
; ) {
1281 MachineOperand
&MO
= RI
.getOperand();
1283 MO
.substVirtReg(DstReg
, SubIdx
, TRI
);
1287 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1288 /// EXTRACT_SUBREG from the same register and to the same virtual register
1289 /// with different sub-register indices, attempt to combine the
1290 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1291 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1292 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1293 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1294 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1295 /// reg1026 to reg1029.
1297 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector
<unsigned,4> &Srcs
,
1299 SmallSet
<unsigned, 4> Seen
;
1300 for (unsigned i
= 0, e
= Srcs
.size(); i
!= e
; ++i
) {
1301 unsigned SrcReg
= Srcs
[i
];
1302 if (!Seen
.insert(SrcReg
))
1305 // Check that the instructions are all in the same basic block.
1306 MachineInstr
*SrcDefMI
= MRI
->getVRegDef(SrcReg
);
1307 MachineInstr
*DstDefMI
= MRI
->getVRegDef(DstReg
);
1308 if (SrcDefMI
->getParent() != DstDefMI
->getParent())
1311 // If there are no other uses than copies which feed into
1312 // the reg_sequence, then we might be able to coalesce them.
1313 bool CanCoalesce
= true;
1314 SmallVector
<unsigned, 4> SrcSubIndices
, DstSubIndices
;
1315 for (MachineRegisterInfo::use_nodbg_iterator
1316 UI
= MRI
->use_nodbg_begin(SrcReg
),
1317 UE
= MRI
->use_nodbg_end(); UI
!= UE
; ++UI
) {
1318 MachineInstr
*UseMI
= &*UI
;
1319 if (!UseMI
->isCopy() || UseMI
->getOperand(0).getReg() != DstReg
) {
1320 CanCoalesce
= false;
1323 SrcSubIndices
.push_back(UseMI
->getOperand(1).getSubReg());
1324 DstSubIndices
.push_back(UseMI
->getOperand(0).getSubReg());
1327 if (!CanCoalesce
|| SrcSubIndices
.size() < 2)
1330 // Check that the source subregisters can be combined.
1331 std::sort(SrcSubIndices
.begin(), SrcSubIndices
.end());
1332 unsigned NewSrcSubIdx
= 0;
1333 if (!TRI
->canCombineSubRegIndices(MRI
->getRegClass(SrcReg
), SrcSubIndices
,
1337 // Check that the destination subregisters can also be combined.
1338 std::sort(DstSubIndices
.begin(), DstSubIndices
.end());
1339 unsigned NewDstSubIdx
= 0;
1340 if (!TRI
->canCombineSubRegIndices(MRI
->getRegClass(DstReg
), DstSubIndices
,
1344 // If neither source nor destination can be combined to the full register,
1345 // just give up. This could be improved if it ever matters.
1346 if (NewSrcSubIdx
!= 0 && NewDstSubIdx
!= 0)
1349 // Now that we know that all the uses are extract_subregs and that those
1350 // subregs can somehow be combined, scan all the extract_subregs again to
1351 // make sure the subregs are in the right order and can be composed.
1352 MachineInstr
*SomeMI
= 0;
1354 for (MachineRegisterInfo::use_nodbg_iterator
1355 UI
= MRI
->use_nodbg_begin(SrcReg
),
1356 UE
= MRI
->use_nodbg_end(); UI
!= UE
; ++UI
) {
1357 MachineInstr
*UseMI
= &*UI
;
1358 assert(UseMI
->isCopy());
1359 unsigned DstSubIdx
= UseMI
->getOperand(0).getSubReg();
1360 unsigned SrcSubIdx
= UseMI
->getOperand(1).getSubReg();
1361 assert(DstSubIdx
!= 0 && "missing subreg from RegSequence elimination");
1362 if ((NewDstSubIdx
== 0 &&
1363 TRI
->composeSubRegIndices(NewSrcSubIdx
, DstSubIdx
) != SrcSubIdx
) ||
1364 (NewSrcSubIdx
== 0 &&
1365 TRI
->composeSubRegIndices(NewDstSubIdx
, SrcSubIdx
) != DstSubIdx
)) {
1366 CanCoalesce
= false;
1369 // Keep track of one of the uses.
1375 // Insert a copy to replace the original.
1376 MachineInstr
*CopyMI
= BuildMI(*SomeMI
->getParent(), SomeMI
,
1377 SomeMI
->getDebugLoc(),
1378 TII
->get(TargetOpcode::COPY
))
1379 .addReg(DstReg
, RegState::Define
, NewDstSubIdx
)
1380 .addReg(SrcReg
, 0, NewSrcSubIdx
);
1382 // Remove all the old extract instructions.
1383 for (MachineRegisterInfo::use_nodbg_iterator
1384 UI
= MRI
->use_nodbg_begin(SrcReg
),
1385 UE
= MRI
->use_nodbg_end(); UI
!= UE
; ) {
1386 MachineInstr
*UseMI
= &*UI
;
1388 if (UseMI
== CopyMI
)
1390 assert(UseMI
->isCopy());
1391 // Move any kills to the new copy or extract instruction.
1392 if (UseMI
->getOperand(1).isKill()) {
1393 CopyMI
->getOperand(1).setIsKill();
1395 // Update live variables
1396 LV
->replaceKillInstruction(SrcReg
, UseMI
, &*CopyMI
);
1398 UseMI
->eraseFromParent();
1403 static bool HasOtherRegSequenceUses(unsigned Reg
, MachineInstr
*RegSeq
,
1404 MachineRegisterInfo
*MRI
) {
1405 for (MachineRegisterInfo::use_iterator UI
= MRI
->use_begin(Reg
),
1406 UE
= MRI
->use_end(); UI
!= UE
; ++UI
) {
1407 MachineInstr
*UseMI
= &*UI
;
1408 if (UseMI
!= RegSeq
&& UseMI
->isRegSequence())
1414 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1415 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1416 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1418 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1419 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1421 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1422 bool TwoAddressInstructionPass::EliminateRegSequences() {
1423 if (RegSequences
.empty())
1426 for (unsigned i
= 0, e
= RegSequences
.size(); i
!= e
; ++i
) {
1427 MachineInstr
*MI
= RegSequences
[i
];
1428 unsigned DstReg
= MI
->getOperand(0).getReg();
1429 if (MI
->getOperand(0).getSubReg() ||
1430 TargetRegisterInfo::isPhysicalRegister(DstReg
) ||
1431 !(MI
->getNumOperands() & 1)) {
1432 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI
);
1433 llvm_unreachable(0);
1436 bool IsImpDef
= true;
1437 SmallVector
<unsigned, 4> RealSrcs
;
1438 SmallSet
<unsigned, 4> Seen
;
1439 for (unsigned i
= 1, e
= MI
->getNumOperands(); i
< e
; i
+= 2) {
1440 unsigned SrcReg
= MI
->getOperand(i
).getReg();
1441 unsigned SubIdx
= MI
->getOperand(i
+1).getImm();
1442 if (MI
->getOperand(i
).getSubReg() ||
1443 TargetRegisterInfo::isPhysicalRegister(SrcReg
)) {
1444 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI
);
1445 llvm_unreachable(0);
1448 MachineInstr
*DefMI
= MRI
->getVRegDef(SrcReg
);
1449 if (DefMI
->isImplicitDef()) {
1450 DefMI
->eraseFromParent();
1455 // Remember COPY sources. These might be candidate for coalescing.
1456 if (DefMI
->isCopy() && DefMI
->getOperand(1).getSubReg())
1457 RealSrcs
.push_back(DefMI
->getOperand(1).getReg());
1459 bool isKill
= MI
->getOperand(i
).isKill();
1460 if (!Seen
.insert(SrcReg
) || MI
->getParent() != DefMI
->getParent() ||
1461 !isKill
|| HasOtherRegSequenceUses(SrcReg
, MI
, MRI
) ||
1462 !TRI
->getMatchingSuperRegClass(MRI
->getRegClass(DstReg
),
1463 MRI
->getRegClass(SrcReg
), SubIdx
)) {
1464 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1465 // Also add an copy if the source is live-in the block. We don't want
1466 // to end up with a partial-redef of a livein, e.g.
1468 // reg1051:10<def> =
1474 // LiveIntervalAnalysis won't like it.
1476 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1477 // correctly up to date becomes very difficult. Insert a copy.
1479 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1480 // might insert a COPY that uses SrcReg after is was killed.
1482 for (unsigned j
= i
+ 2; j
< e
; j
+= 2)
1483 if (MI
->getOperand(j
).getReg() == SrcReg
) {
1484 MI
->getOperand(j
).setIsKill();
1489 MachineBasicBlock::iterator InsertLoc
= MI
;
1490 MachineInstr
*CopyMI
= BuildMI(*MI
->getParent(), InsertLoc
,
1491 MI
->getDebugLoc(), TII
->get(TargetOpcode::COPY
))
1492 .addReg(DstReg
, RegState::Define
, SubIdx
)
1493 .addReg(SrcReg
, getKillRegState(isKill
));
1494 MI
->getOperand(i
).setReg(0);
1496 LV
->replaceKillInstruction(SrcReg
, MI
, CopyMI
);
1497 DEBUG(dbgs() << "Inserted: " << *CopyMI
);
1501 for (unsigned i
= 1, e
= MI
->getNumOperands(); i
< e
; i
+= 2) {
1502 unsigned SrcReg
= MI
->getOperand(i
).getReg();
1503 if (!SrcReg
) continue;
1504 unsigned SubIdx
= MI
->getOperand(i
+1).getImm();
1505 UpdateRegSequenceSrcs(SrcReg
, DstReg
, SubIdx
, MRI
, *TRI
);
1509 DEBUG(dbgs() << "Turned: " << *MI
<< " into an IMPLICIT_DEF");
1510 MI
->setDesc(TII
->get(TargetOpcode::IMPLICIT_DEF
));
1511 for (int j
= MI
->getNumOperands() - 1, ee
= 0; j
> ee
; --j
)
1512 MI
->RemoveOperand(j
);
1514 DEBUG(dbgs() << "Eliminated: " << *MI
);
1515 MI
->eraseFromParent();
1518 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1519 // INSERT_SUBREG instructions that must have <undef> flags added by
1520 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1522 CoalesceExtSubRegs(RealSrcs
, DstReg
);
1525 RegSequences
.clear();