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 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveVariables.h"
39 #include "llvm/CodeGen/MachineFunctionPass.h"
40 #include "llvm/CodeGen/MachineInstr.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/MC/MCInstrItineraries.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
55 #define DEBUG_TYPE "twoaddrinstr"
57 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
58 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
59 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
60 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
61 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
62 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
63 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
65 // Temporary flag to disable rescheduling.
67 EnableRescheduling("twoaddr-reschedule",
68 cl::desc("Coalesce copies by rescheduling (default=true)"),
69 cl::init(true), cl::Hidden);
72 class TwoAddressInstructionPass : public MachineFunctionPass {
74 const TargetInstrInfo *TII;
75 const TargetRegisterInfo *TRI;
76 const InstrItineraryData *InstrItins;
77 MachineRegisterInfo *MRI;
81 CodeGenOpt::Level OptLevel;
83 // The current basic block being processed.
84 MachineBasicBlock *MBB;
86 // DistanceMap - Keep track the distance of a MI from the start of the
87 // current basic block.
88 DenseMap<MachineInstr*, unsigned> DistanceMap;
90 // Set of already processed instructions in the current block.
91 SmallPtrSet<MachineInstr*, 8> Processed;
93 // SrcRegMap - A map from virtual registers to physical registers which are
94 // likely targets to be coalesced to due to copies from physical registers to
95 // virtual registers. e.g. v1024 = move r0.
96 DenseMap<unsigned, unsigned> SrcRegMap;
98 // DstRegMap - A map from virtual registers to physical registers which are
99 // likely targets to be coalesced to due to copies to physical registers from
100 // virtual registers. e.g. r1 = move v1024.
101 DenseMap<unsigned, unsigned> DstRegMap;
103 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
104 MachineBasicBlock::iterator OldPos);
106 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
108 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
110 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
111 MachineInstr *MI, unsigned Dist);
113 bool commuteInstruction(MachineInstr *MI,
114 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
116 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
118 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
119 MachineBasicBlock::iterator &nmi,
120 unsigned RegA, unsigned RegB, unsigned Dist);
122 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
124 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
125 MachineBasicBlock::iterator &nmi,
127 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
128 MachineBasicBlock::iterator &nmi,
131 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
132 MachineBasicBlock::iterator &nmi,
133 unsigned SrcIdx, unsigned DstIdx,
134 unsigned Dist, bool shouldOnlyCommute);
136 bool tryInstructionCommute(MachineInstr *MI,
141 void scanUses(unsigned DstReg);
143 void processCopy(MachineInstr *MI);
145 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
146 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
147 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
148 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
149 void eliminateRegSequence(MachineBasicBlock::iterator&);
152 static char ID; // Pass identification, replacement for typeid
153 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
154 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
157 void getAnalysisUsage(AnalysisUsage &AU) const override {
158 AU.setPreservesCFG();
159 AU.addRequired<AAResultsWrapperPass>();
160 AU.addPreserved<LiveVariables>();
161 AU.addPreserved<SlotIndexes>();
162 AU.addPreserved<LiveIntervals>();
163 AU.addPreservedID(MachineLoopInfoID);
164 AU.addPreservedID(MachineDominatorsID);
165 MachineFunctionPass::getAnalysisUsage(AU);
168 /// runOnMachineFunction - Pass entry point.
169 bool runOnMachineFunction(MachineFunction&) override;
171 } // end anonymous namespace
173 char TwoAddressInstructionPass::ID = 0;
174 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
175 "Two-Address instruction pass", false, false)
176 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
177 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
178 "Two-Address instruction pass", false, false)
180 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
182 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
184 /// sink3AddrInstruction - A two-address instruction has been converted to a
185 /// three-address instruction to avoid clobbering a register. Try to sink it
186 /// past the instruction that would kill the above mentioned register to reduce
187 /// register pressure.
188 bool TwoAddressInstructionPass::
189 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
190 MachineBasicBlock::iterator OldPos) {
191 // FIXME: Shouldn't we be trying to do this before we three-addressify the
192 // instruction? After this transformation is done, we no longer need
193 // the instruction to be in three-address form.
195 // Check if it's safe to move this instruction.
196 bool SeenStore = true; // Be conservative.
197 if (!MI->isSafeToMove(AA, SeenStore))
201 SmallSet<unsigned, 4> UseRegs;
203 for (const MachineOperand &MO : MI->operands()) {
206 unsigned MOReg = MO.getReg();
209 if (MO.isUse() && MOReg != SavedReg)
210 UseRegs.insert(MO.getReg());
214 // Don't try to move it if it implicitly defines a register.
217 // For now, don't move any instructions that define multiple registers.
219 DefReg = MO.getReg();
222 // Find the instruction that kills SavedReg.
223 MachineInstr *KillMI = nullptr;
225 LiveInterval &LI = LIS->getInterval(SavedReg);
226 assert(LI.end() != LI.begin() &&
227 "Reg should not have empty live interval.");
229 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
230 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
231 if (I != LI.end() && I->start < MBBEndIdx)
235 KillMI = LIS->getInstructionFromIndex(I->end);
238 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
241 KillMI = UseMO.getParent();
246 // If we find the instruction that kills SavedReg, and it is in an
247 // appropriate location, we can try to sink the current instruction
249 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
250 KillMI == OldPos || KillMI->isTerminator())
253 // If any of the definitions are used by another instruction between the
254 // position and the kill use, then it's not safe to sink it.
256 // FIXME: This can be sped up if there is an easy way to query whether an
257 // instruction is before or after another instruction. Then we can use
258 // MachineRegisterInfo def / use instead.
259 MachineOperand *KillMO = nullptr;
260 MachineBasicBlock::iterator KillPos = KillMI;
263 unsigned NumVisited = 0;
264 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
265 MachineInstr *OtherMI = I;
266 // DBG_VALUE cannot be counted against the limit.
267 if (OtherMI->isDebugValue())
269 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
272 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
273 MachineOperand &MO = OtherMI->getOperand(i);
276 unsigned MOReg = MO.getReg();
282 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
283 if (OtherMI == KillMI && MOReg == SavedReg)
284 // Save the operand that kills the register. We want to unset the kill
285 // marker if we can sink MI past it.
287 else if (UseRegs.count(MOReg))
288 // One of the uses is killed before the destination.
293 assert(KillMO && "Didn't find kill");
296 // Update kill and LV information.
297 KillMO->setIsKill(false);
298 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
299 KillMO->setIsKill(true);
302 LV->replaceKillInstruction(SavedReg, KillMI, MI);
305 // Move instruction to its destination.
307 MBB->insert(KillPos, MI);
316 /// getSingleDef -- return the MachineInstr* if it is the single def of the Reg
318 static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
319 const MachineRegisterInfo *MRI) {
320 MachineInstr *Ret = nullptr;
321 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
322 if (DefMI.getParent() != BB || DefMI.isDebugValue())
326 else if (Ret != &DefMI)
332 /// Check if there is a reversed copy chain from FromReg to ToReg:
333 /// %Tmp1 = copy %Tmp2;
334 /// %FromReg = copy %Tmp1;
335 /// %ToReg = add %FromReg ...
336 /// %Tmp2 = copy %ToReg;
337 /// MaxLen specifies the maximum length of the copy chain the func
338 /// can walk through.
339 bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
341 unsigned TmpReg = FromReg;
342 for (int i = 0; i < Maxlen; i++) {
343 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
344 if (!Def || !Def->isCopy())
347 TmpReg = Def->getOperand(1).getReg();
355 /// noUseAfterLastDef - Return true if there are no intervening uses between the
356 /// last instruction in the MBB that defines the specified register and the
357 /// two-address instruction which is being processed. It also returns the last
358 /// def location by reference
359 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
362 unsigned LastUse = Dist;
363 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
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 (MO.isUse() && DI->second < LastUse)
371 LastUse = DI->second;
372 if (MO.isDef() && DI->second > LastDef)
373 LastDef = DI->second;
376 return !(LastUse > LastDef && LastUse < Dist);
379 /// isCopyToReg - Return true if the specified MI is a copy instruction or
380 /// a extract_subreg instruction. It also returns the source and destination
381 /// registers and whether they are physical registers by reference.
382 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
383 unsigned &SrcReg, unsigned &DstReg,
384 bool &IsSrcPhys, bool &IsDstPhys) {
388 DstReg = MI.getOperand(0).getReg();
389 SrcReg = MI.getOperand(1).getReg();
390 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
391 DstReg = MI.getOperand(0).getReg();
392 SrcReg = MI.getOperand(2).getReg();
396 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
397 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
401 /// isPLainlyKilled - Test if the given register value, which is used by the
402 // given instruction, is killed by the given instruction.
403 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
404 LiveIntervals *LIS) {
405 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
406 !LIS->isNotInMIMap(MI)) {
407 // FIXME: Sometimes tryInstructionTransform() will add instructions and
408 // test whether they can be folded before keeping them. In this case it
409 // sets a kill before recursively calling tryInstructionTransform() again.
410 // If there is no interval available, we assume that this instruction is
411 // one of those. A kill flag is manually inserted on the operand so the
412 // check below will handle it.
413 LiveInterval &LI = LIS->getInterval(Reg);
414 // This is to match the kill flag version where undefs don't have kill
416 if (!LI.hasAtLeastOneValue())
419 SlotIndex useIdx = LIS->getInstructionIndex(MI);
420 LiveInterval::const_iterator I = LI.find(useIdx);
421 assert(I != LI.end() && "Reg must be live-in to use.");
422 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
425 return MI->killsRegister(Reg);
428 /// isKilled - Test if the given register value, which is used by the given
429 /// instruction, is killed by the given instruction. This looks through
430 /// coalescable copies to see if the original value is potentially not killed.
432 /// For example, in this code:
434 /// %reg1034 = copy %reg1024
435 /// %reg1035 = copy %reg1025<kill>
436 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
438 /// %reg1034 is not considered to be killed, since it is copied from a
439 /// register which is not killed. Treating it as not killed lets the
440 /// normal heuristics commute the (two-address) add, which lets
441 /// coalescing eliminate the extra copy.
443 /// If allowFalsePositives is true then likely kills are treated as kills even
444 /// if it can't be proven that they are kills.
445 static bool isKilled(MachineInstr &MI, unsigned Reg,
446 const MachineRegisterInfo *MRI,
447 const TargetInstrInfo *TII,
449 bool allowFalsePositives) {
450 MachineInstr *DefMI = &MI;
452 // All uses of physical registers are likely to be kills.
453 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
454 (allowFalsePositives || MRI->hasOneUse(Reg)))
456 if (!isPlainlyKilled(DefMI, Reg, LIS))
458 if (TargetRegisterInfo::isPhysicalRegister(Reg))
460 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
461 // If there are multiple defs, we can't do a simple analysis, so just
462 // go with what the kill flag says.
463 if (std::next(Begin) != MRI->def_end())
465 DefMI = Begin->getParent();
466 bool IsSrcPhys, IsDstPhys;
467 unsigned SrcReg, DstReg;
468 // If the def is something other than a copy, then it isn't going to
469 // be coalesced, so follow the kill flag.
470 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
476 /// isTwoAddrUse - Return true if the specified MI uses the specified register
477 /// as a two-address use. If so, return the destination register by reference.
478 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
479 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
480 const MachineOperand &MO = MI.getOperand(i);
481 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
484 if (MI.isRegTiedToDefOperand(i, &ti)) {
485 DstReg = MI.getOperand(ti).getReg();
492 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
493 /// use, return the use instruction if it's a copy or a two-address use.
495 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
496 MachineRegisterInfo *MRI,
497 const TargetInstrInfo *TII,
499 unsigned &DstReg, bool &IsDstPhys) {
500 if (!MRI->hasOneNonDBGUse(Reg))
501 // None or more than one use.
503 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
504 if (UseMI.getParent() != MBB)
508 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
513 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
514 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
520 /// getMappedReg - Return the physical register the specified virtual register
521 /// might be mapped to.
523 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
524 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
525 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
526 if (SI == RegMap.end())
530 if (TargetRegisterInfo::isPhysicalRegister(Reg))
535 /// regsAreCompatible - Return true if the two registers are equal or aliased.
538 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
543 return TRI->regsOverlap(RegA, RegB);
547 /// isProfitableToCommute - Return true if it's potentially profitable to commute
548 /// the two-address instruction that's being processed.
550 TwoAddressInstructionPass::
551 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
552 MachineInstr *MI, unsigned Dist) {
553 if (OptLevel == CodeGenOpt::None)
556 // Determine if it's profitable to commute this two address instruction. In
557 // general, we want no uses between this instruction and the definition of
558 // the two-address register.
560 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
561 // %reg1029<def> = MOV8rr %reg1028
562 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
563 // insert => %reg1030<def> = MOV8rr %reg1028
564 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
565 // In this case, it might not be possible to coalesce the second MOV8rr
566 // instruction if the first one is coalesced. So it would be profitable to
568 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
569 // %reg1029<def> = MOV8rr %reg1028
570 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
571 // insert => %reg1030<def> = MOV8rr %reg1029
572 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
574 if (!isPlainlyKilled(MI, regC, LIS))
577 // Ok, we have something like:
578 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
579 // let's see if it's worth commuting it.
581 // Look for situations like this:
582 // %reg1024<def> = MOV r1
583 // %reg1025<def> = MOV r0
584 // %reg1026<def> = ADD %reg1024, %reg1025
586 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
587 unsigned ToRegA = getMappedReg(regA, DstRegMap);
589 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
590 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
591 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
592 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
594 // Compute if any of the following are true:
595 // -RegB is not tied to a register and RegC is compatible with RegA.
596 // -RegB is tied to the wrong physical register, but RegC is.
597 // -RegB is tied to the wrong physical register, and RegC isn't tied.
598 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
600 // Don't compute if any of the following are true:
601 // -RegC is not tied to a register and RegB is compatible with RegA.
602 // -RegC is tied to the wrong physical register, but RegB is.
603 // -RegC is tied to the wrong physical register, and RegB isn't tied.
604 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
608 // If there is a use of regC between its last def (could be livein) and this
609 // instruction, then bail.
610 unsigned LastDefC = 0;
611 if (!noUseAfterLastDef(regC, Dist, LastDefC))
614 // If there is a use of regB between its last def (could be livein) and this
615 // instruction, then go ahead and make this transformation.
616 unsigned LastDefB = 0;
617 if (!noUseAfterLastDef(regB, Dist, LastDefB))
620 // Look for situation like this:
621 // %reg101 = MOV %reg100
623 // %reg103 = ADD %reg102, %reg101
625 // %reg100 = MOV %reg103
626 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
627 // to eliminate an otherwise unavoidable copy.
629 // We can extend the logic further: If an pair of operands in an insn has
630 // been merged, the insn could be regarded as a virtual copy, and the virtual
631 // copy could also be used to construct a copy chain.
632 // To more generally minimize register copies, ideally the logic of two addr
633 // instruction pass should be integrated with register allocation pass where
634 // interference graph is available.
635 if (isRevCopyChain(regC, regA, 3))
638 if (isRevCopyChain(regB, regA, 3))
641 // Since there are no intervening uses for both registers, then commute
642 // if the def of regC is closer. Its live interval is shorter.
643 return LastDefB && LastDefC && LastDefC > LastDefB;
646 /// commuteInstruction - Commute a two-address instruction and update the basic
647 /// block, distance map, and live variables if needed. Return true if it is
649 bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
653 unsigned RegC = MI->getOperand(RegCIdx).getReg();
654 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
655 MachineInstr *NewMI = TII->commuteInstruction(MI, false, RegBIdx, RegCIdx);
657 if (NewMI == nullptr) {
658 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
662 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
663 assert(NewMI == MI &&
664 "TargetInstrInfo::commuteInstruction() should not return a new "
665 "instruction unless it was requested.");
667 // Update source register map.
668 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
670 unsigned RegA = MI->getOperand(0).getReg();
671 SrcRegMap[RegA] = FromRegC;
677 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
678 /// given 2-address instruction to a 3-address one.
680 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
681 // Look for situations like this:
682 // %reg1024<def> = MOV r1
683 // %reg1025<def> = MOV r0
684 // %reg1026<def> = ADD %reg1024, %reg1025
686 // Turn ADD into a 3-address instruction to avoid a copy.
687 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
690 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
691 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
694 /// convertInstTo3Addr - Convert the specified two-address instruction into a
695 /// three address one. Return true if this transformation was successful.
697 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
698 MachineBasicBlock::iterator &nmi,
699 unsigned RegA, unsigned RegB,
701 // FIXME: Why does convertToThreeAddress() need an iterator reference?
702 MachineFunction::iterator MFI = MBB->getIterator();
703 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
704 assert(MBB->getIterator() == MFI &&
705 "convertToThreeAddress changed iterator reference");
709 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
710 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
714 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
716 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
717 // FIXME: Temporary workaround. If the new instruction doesn't
718 // uses RegB, convertToThreeAddress must have created more
719 // then one instruction.
720 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
722 MBB->erase(mi); // Nuke the old inst.
725 DistanceMap.insert(std::make_pair(NewMI, Dist));
730 // Update source and destination register maps.
731 SrcRegMap.erase(RegA);
732 DstRegMap.erase(RegB);
736 /// scanUses - Scan forward recursively for only uses, update maps if the use
737 /// is a copy or a two-address instruction.
739 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
740 SmallVector<unsigned, 4> VirtRegPairs;
744 unsigned Reg = DstReg;
745 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
746 NewReg, IsDstPhys)) {
747 if (IsCopy && !Processed.insert(UseMI).second)
750 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
751 if (DI != DistanceMap.end())
752 // Earlier in the same MBB.Reached via a back edge.
756 VirtRegPairs.push_back(NewReg);
759 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
761 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
762 VirtRegPairs.push_back(NewReg);
766 if (!VirtRegPairs.empty()) {
767 unsigned ToReg = VirtRegPairs.back();
768 VirtRegPairs.pop_back();
769 while (!VirtRegPairs.empty()) {
770 unsigned FromReg = VirtRegPairs.back();
771 VirtRegPairs.pop_back();
772 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
774 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
777 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
779 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
783 /// processCopy - If the specified instruction is not yet processed, process it
784 /// if it's a copy. For a copy instruction, we find the physical registers the
785 /// source and destination registers might be mapped to. These are kept in
786 /// point-to maps used to determine future optimizations. e.g.
789 /// v1026 = add v1024, v1025
791 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
792 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
793 /// potentially joined with r1 on the output side. It's worthwhile to commute
794 /// 'add' to eliminate a copy.
795 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
796 if (Processed.count(MI))
799 bool IsSrcPhys, IsDstPhys;
800 unsigned SrcReg, DstReg;
801 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
804 if (IsDstPhys && !IsSrcPhys)
805 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
806 else if (!IsDstPhys && IsSrcPhys) {
807 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
809 assert(SrcRegMap[DstReg] == SrcReg &&
810 "Can't map to two src physical registers!");
815 Processed.insert(MI);
819 /// rescheduleMIBelowKill - If there is one more local instruction that reads
820 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
821 /// instruction in order to eliminate the need for the copy.
822 bool TwoAddressInstructionPass::
823 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
824 MachineBasicBlock::iterator &nmi,
826 // Bail immediately if we don't have LV or LIS available. We use them to find
827 // kills efficiently.
831 MachineInstr *MI = &*mi;
832 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
833 if (DI == DistanceMap.end())
834 // Must be created from unfolded load. Don't waste time trying this.
837 MachineInstr *KillMI = nullptr;
839 LiveInterval &LI = LIS->getInterval(Reg);
840 assert(LI.end() != LI.begin() &&
841 "Reg should not have empty live interval.");
843 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
844 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
845 if (I != LI.end() && I->start < MBBEndIdx)
849 KillMI = LIS->getInstructionFromIndex(I->end);
851 KillMI = LV->getVarInfo(Reg).findKill(MBB);
853 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
854 // Don't mess with copies, they may be coalesced later.
857 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
858 KillMI->isBranch() || KillMI->isTerminator())
859 // Don't move pass calls, etc.
863 if (isTwoAddrUse(*KillMI, Reg, DstReg))
866 bool SeenStore = true;
867 if (!MI->isSafeToMove(AA, SeenStore))
870 if (TII->getInstrLatency(InstrItins, MI) > 1)
871 // FIXME: Needs more sophisticated heuristics.
874 SmallSet<unsigned, 2> Uses;
875 SmallSet<unsigned, 2> Kills;
876 SmallSet<unsigned, 2> Defs;
877 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
878 const MachineOperand &MO = MI->getOperand(i);
881 unsigned MOReg = MO.getReg();
888 if (MOReg != Reg && (MO.isKill() ||
889 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
894 // Move the copies connected to MI down as well.
895 MachineBasicBlock::iterator Begin = MI;
896 MachineBasicBlock::iterator AfterMI = std::next(Begin);
898 MachineBasicBlock::iterator End = AfterMI;
899 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
900 Defs.insert(End->getOperand(0).getReg());
904 // Check if the reschedule will not break depedencies.
905 unsigned NumVisited = 0;
906 MachineBasicBlock::iterator KillPos = KillMI;
908 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
909 MachineInstr *OtherMI = I;
910 // DBG_VALUE cannot be counted against the limit.
911 if (OtherMI->isDebugValue())
913 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
916 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
917 OtherMI->isBranch() || OtherMI->isTerminator())
918 // Don't move pass calls, etc.
920 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
921 const MachineOperand &MO = OtherMI->getOperand(i);
924 unsigned MOReg = MO.getReg();
928 if (Uses.count(MOReg))
929 // Physical register use would be clobbered.
931 if (!MO.isDead() && Defs.count(MOReg))
932 // May clobber a physical register def.
933 // FIXME: This may be too conservative. It's ok if the instruction
934 // is sunken completely below the use.
937 if (Defs.count(MOReg))
939 bool isKill = MO.isKill() ||
940 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
942 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
943 // Don't want to extend other live ranges and update kills.
945 if (MOReg == Reg && !isKill)
946 // We can't schedule across a use of the register in question.
948 // Ensure that if this is register in question, its the kill we expect.
949 assert((MOReg != Reg || OtherMI == KillMI) &&
950 "Found multiple kills of a register in a basic block");
955 // Move debug info as well.
956 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
960 MachineBasicBlock::iterator InsertPos = KillPos;
962 // We have to move the copies first so that the MBB is still well-formed
963 // when calling handleMove().
964 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
965 MachineInstr *CopyMI = MBBI;
967 MBB->splice(InsertPos, MBB, CopyMI);
968 LIS->handleMove(CopyMI);
971 End = std::next(MachineBasicBlock::iterator(MI));
974 // Copies following MI may have been moved as well.
975 MBB->splice(InsertPos, MBB, Begin, End);
976 DistanceMap.erase(DI);
978 // Update live variables
982 LV->removeVirtualRegisterKilled(Reg, KillMI);
983 LV->addVirtualRegisterKilled(Reg, MI);
986 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
990 /// isDefTooClose - Return true if the re-scheduling will put the given
991 /// instruction too close to the defs of its register dependencies.
992 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
994 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
995 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
998 return true; // MI is defining something KillMI uses
999 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
1000 if (DDI == DistanceMap.end())
1001 return true; // Below MI
1002 unsigned DefDist = DDI->second;
1003 assert(Dist > DefDist && "Visited def already?");
1004 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
1010 /// rescheduleKillAboveMI - If there is one more local instruction that reads
1011 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1012 /// current two-address instruction in order to eliminate the need for the
1014 bool TwoAddressInstructionPass::
1015 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
1016 MachineBasicBlock::iterator &nmi,
1018 // Bail immediately if we don't have LV or LIS available. We use them to find
1019 // kills efficiently.
1023 MachineInstr *MI = &*mi;
1024 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1025 if (DI == DistanceMap.end())
1026 // Must be created from unfolded load. Don't waste time trying this.
1029 MachineInstr *KillMI = nullptr;
1031 LiveInterval &LI = LIS->getInterval(Reg);
1032 assert(LI.end() != LI.begin() &&
1033 "Reg should not have empty live interval.");
1035 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1036 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1037 if (I != LI.end() && I->start < MBBEndIdx)
1041 KillMI = LIS->getInstructionFromIndex(I->end);
1043 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1045 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1046 // Don't mess with copies, they may be coalesced later.
1050 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1053 bool SeenStore = true;
1054 if (!KillMI->isSafeToMove(AA, SeenStore))
1057 SmallSet<unsigned, 2> Uses;
1058 SmallSet<unsigned, 2> Kills;
1059 SmallSet<unsigned, 2> Defs;
1060 SmallSet<unsigned, 2> LiveDefs;
1061 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1062 const MachineOperand &MO = KillMI->getOperand(i);
1065 unsigned MOReg = MO.getReg();
1069 if (isDefTooClose(MOReg, DI->second, MI))
1071 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1072 if (MOReg == Reg && !isKill)
1075 if (isKill && MOReg != Reg)
1076 Kills.insert(MOReg);
1077 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1080 LiveDefs.insert(MOReg);
1084 // Check if the reschedule will not break depedencies.
1085 unsigned NumVisited = 0;
1086 MachineBasicBlock::iterator KillPos = KillMI;
1087 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1088 MachineInstr *OtherMI = I;
1089 // DBG_VALUE cannot be counted against the limit.
1090 if (OtherMI->isDebugValue())
1092 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1095 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1096 OtherMI->isBranch() || OtherMI->isTerminator())
1097 // Don't move pass calls, etc.
1099 SmallVector<unsigned, 2> OtherDefs;
1100 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1101 const MachineOperand &MO = OtherMI->getOperand(i);
1104 unsigned MOReg = MO.getReg();
1108 if (Defs.count(MOReg))
1109 // Moving KillMI can clobber the physical register if the def has
1112 if (Kills.count(MOReg))
1113 // Don't want to extend other live ranges and update kills.
1115 if (OtherMI != MI && MOReg == Reg &&
1116 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
1117 // We can't schedule across a use of the register in question.
1120 OtherDefs.push_back(MOReg);
1124 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1125 unsigned MOReg = OtherDefs[i];
1126 if (Uses.count(MOReg))
1128 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1129 LiveDefs.count(MOReg))
1131 // Physical register def is seen.
1136 // Move the old kill above MI, don't forget to move debug info as well.
1137 MachineBasicBlock::iterator InsertPos = mi;
1138 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
1140 MachineBasicBlock::iterator From = KillMI;
1141 MachineBasicBlock::iterator To = std::next(From);
1142 while (std::prev(From)->isDebugValue())
1144 MBB->splice(InsertPos, MBB, From, To);
1146 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1147 DistanceMap.erase(DI);
1149 // Update live variables
1151 LIS->handleMove(KillMI);
1153 LV->removeVirtualRegisterKilled(Reg, KillMI);
1154 LV->addVirtualRegisterKilled(Reg, MI);
1157 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1161 /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1162 /// given machine instruction to improve opportunities for coalescing and
1163 /// elimination of a register to register copy.
1165 /// 'DstOpIdx' specifies the index of MI def operand.
1166 /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1167 /// operand is killed by the given instruction.
1168 /// The 'Dist' arguments provides the distance of MI from the start of the
1169 /// current basic block and it is used to determine if it is profitable
1170 /// to commute operands in the instruction.
1172 /// Returns true if the transformation happened. Otherwise, returns false.
1173 bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1178 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1179 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1180 unsigned OpsNum = MI->getDesc().getNumOperands();
1181 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1182 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1183 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1184 // and OtherOpIdx are commutable, it does not really searches for
1185 // other commutable operands and does not change the values of passed
1187 if (OtherOpIdx == BaseOpIdx ||
1188 !TII->findCommutedOpIndices(MI, BaseOpIdx, OtherOpIdx))
1191 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1192 bool AggressiveCommute = false;
1194 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1195 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1197 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1200 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1202 AggressiveCommute = true;
1205 // If it's profitable to commute, try to do so.
1206 if (DoCommute && commuteInstruction(MI, BaseOpIdx, OtherOpIdx, Dist)) {
1208 if (AggressiveCommute)
1216 /// tryInstructionTransform - For the case where an instruction has a single
1217 /// pair of tied register operands, attempt some transformations that may
1218 /// either eliminate the tied operands or improve the opportunities for
1219 /// coalescing away the register copy. Returns true if no copy needs to be
1220 /// inserted to untie mi's operands (either because they were untied, or
1221 /// because mi was rescheduled, and will be visited again later). If the
1222 /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
1223 bool TwoAddressInstructionPass::
1224 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1225 MachineBasicBlock::iterator &nmi,
1226 unsigned SrcIdx, unsigned DstIdx,
1227 unsigned Dist, bool shouldOnlyCommute) {
1228 if (OptLevel == CodeGenOpt::None)
1231 MachineInstr &MI = *mi;
1232 unsigned regA = MI.getOperand(DstIdx).getReg();
1233 unsigned regB = MI.getOperand(SrcIdx).getReg();
1235 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1236 "cannot make instruction into two-address form");
1237 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1239 if (TargetRegisterInfo::isVirtualRegister(regA))
1242 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1244 // If the instruction is convertible to 3 Addr, instead
1245 // of returning try 3 Addr transformation aggresively and
1246 // use this variable to check later. Because it might be better.
1247 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1248 // instead of the following code.
1252 if (Commuted && !MI.isConvertibleTo3Addr())
1255 if (shouldOnlyCommute)
1258 // If there is one more use of regB later in the same MBB, consider
1259 // re-schedule this MI below it.
1260 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1265 // If we commuted, regB may have changed so we should re-sample it to avoid
1266 // confusing the three address conversion below.
1268 regB = MI.getOperand(SrcIdx).getReg();
1269 regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1272 if (MI.isConvertibleTo3Addr()) {
1273 // This instruction is potentially convertible to a true
1274 // three-address instruction. Check if it is profitable.
1275 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1276 // Try to convert it.
1277 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1278 ++NumConvertedTo3Addr;
1279 return true; // Done with this instruction.
1284 // Return if it is commuted but 3 addr conversion is failed.
1288 // If there is one more use of regB later in the same MBB, consider
1289 // re-schedule it before this MI if it's legal.
1290 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1295 // If this is an instruction with a load folded into it, try unfolding
1296 // the load, e.g. avoid this:
1298 // addq (%rax), %rcx
1299 // in favor of this:
1300 // movq (%rax), %rcx
1302 // because it's preferable to schedule a load than a register copy.
1303 if (MI.mayLoad() && !regBKilled) {
1304 // Determine if a load can be unfolded.
1305 unsigned LoadRegIndex;
1307 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1308 /*UnfoldLoad=*/true,
1309 /*UnfoldStore=*/false,
1312 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1313 if (UnfoldMCID.getNumDefs() == 1) {
1315 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1316 const TargetRegisterClass *RC =
1317 TRI->getAllocatableClass(
1318 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1319 unsigned Reg = MRI->createVirtualRegister(RC);
1320 SmallVector<MachineInstr *, 2> NewMIs;
1321 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
1322 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1324 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1327 assert(NewMIs.size() == 2 &&
1328 "Unfolded a load into multiple instructions!");
1329 // The load was previously folded, so this is the only use.
1330 NewMIs[1]->addRegisterKilled(Reg, TRI);
1332 // Tentatively insert the instructions into the block so that they
1333 // look "normal" to the transformation logic.
1334 MBB->insert(mi, NewMIs[0]);
1335 MBB->insert(mi, NewMIs[1]);
1337 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1338 << "2addr: NEW INST: " << *NewMIs[1]);
1340 // Transform the instruction, now that it no longer has a load.
1341 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1342 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1343 MachineBasicBlock::iterator NewMI = NewMIs[1];
1344 bool TransformResult =
1345 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1346 (void)TransformResult;
1347 assert(!TransformResult &&
1348 "tryInstructionTransform() should return false.");
1349 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1350 // Success, or at least we made an improvement. Keep the unfolded
1351 // instructions and discard the original.
1353 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1354 MachineOperand &MO = MI.getOperand(i);
1356 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1359 if (NewMIs[0]->killsRegister(MO.getReg()))
1360 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1362 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1363 "Kill missing after load unfold!");
1364 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1367 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1368 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1369 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1371 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1372 "Dead flag missing after load unfold!");
1373 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1378 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1381 SmallVector<unsigned, 4> OrigRegs;
1383 for (const MachineOperand &MO : MI.operands()) {
1385 OrigRegs.push_back(MO.getReg());
1389 MI.eraseFromParent();
1391 // Update LiveIntervals.
1393 MachineBasicBlock::iterator Begin(NewMIs[0]);
1394 MachineBasicBlock::iterator End(NewMIs[1]);
1395 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1400 // Transforming didn't eliminate the tie and didn't lead to an
1401 // improvement. Clean up the unfolded instructions and keep the
1403 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1404 NewMIs[0]->eraseFromParent();
1405 NewMIs[1]->eraseFromParent();
1414 // Collect tied operands of MI that need to be handled.
1415 // Rewrite trivial cases immediately.
1416 // Return true if any tied operands where found, including the trivial ones.
1417 bool TwoAddressInstructionPass::
1418 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1419 const MCInstrDesc &MCID = MI->getDesc();
1420 bool AnyOps = false;
1421 unsigned NumOps = MI->getNumOperands();
1423 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1424 unsigned DstIdx = 0;
1425 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1428 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1429 MachineOperand &DstMO = MI->getOperand(DstIdx);
1430 unsigned SrcReg = SrcMO.getReg();
1431 unsigned DstReg = DstMO.getReg();
1432 // Tied constraint already satisfied?
1433 if (SrcReg == DstReg)
1436 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1438 // Deal with <undef> uses immediately - simply rewrite the src operand.
1439 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1440 // Constrain the DstReg register class if required.
1441 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1442 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1444 MRI->constrainRegClass(DstReg, RC);
1445 SrcMO.setReg(DstReg);
1447 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1450 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1455 // Process a list of tied MI operands that all use the same source register.
1456 // The tied pairs are of the form (SrcIdx, DstIdx).
1458 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1459 TiedPairList &TiedPairs,
1461 bool IsEarlyClobber = false;
1462 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1463 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1464 IsEarlyClobber |= DstMO.isEarlyClobber();
1467 bool RemovedKillFlag = false;
1468 bool AllUsesCopied = true;
1469 unsigned LastCopiedReg = 0;
1470 SlotIndex LastCopyIdx;
1472 unsigned SubRegB = 0;
1473 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1474 unsigned SrcIdx = TiedPairs[tpi].first;
1475 unsigned DstIdx = TiedPairs[tpi].second;
1477 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1478 unsigned RegA = DstMO.getReg();
1480 // Grab RegB from the instruction because it may have changed if the
1481 // instruction was commuted.
1482 RegB = MI->getOperand(SrcIdx).getReg();
1483 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1486 // The register is tied to multiple destinations (or else we would
1487 // not have continued this far), but this use of the register
1488 // already matches the tied destination. Leave it.
1489 AllUsesCopied = false;
1492 LastCopiedReg = RegA;
1494 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1495 "cannot make instruction into two-address form");
1498 // First, verify that we don't have a use of "a" in the instruction
1499 // (a = b + a for example) because our transformation will not
1500 // work. This should never occur because we are in SSA form.
1501 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1502 assert(i == DstIdx ||
1503 !MI->getOperand(i).isReg() ||
1504 MI->getOperand(i).getReg() != RegA);
1508 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1509 TII->get(TargetOpcode::COPY), RegA);
1510 // If this operand is folding a truncation, the truncation now moves to the
1511 // copy so that the register classes remain valid for the operands.
1512 MIB.addReg(RegB, 0, SubRegB);
1513 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1515 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1516 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1518 "tied subregister must be a truncation");
1519 // The superreg class will not be used to constrain the subreg class.
1523 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1524 && "tied subregister must be a truncation");
1528 // Update DistanceMap.
1529 MachineBasicBlock::iterator PrevMI = MI;
1531 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1532 DistanceMap[MI] = ++Dist;
1535 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1537 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1538 LiveInterval &LI = LIS->getInterval(RegA);
1539 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1541 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1542 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1546 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1548 MachineOperand &MO = MI->getOperand(SrcIdx);
1549 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1550 "inconsistent operand info for 2-reg pass");
1552 MO.setIsKill(false);
1553 RemovedKillFlag = true;
1556 // Make sure regA is a legal regclass for the SrcIdx operand.
1557 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1558 TargetRegisterInfo::isVirtualRegister(RegB))
1559 MRI->constrainRegClass(RegA, RC);
1561 // The getMatchingSuper asserts guarantee that the register class projected
1562 // by SubRegB is compatible with RegA with no subregister. So regardless of
1563 // whether the dest oper writes a subreg, the source oper should not.
1566 // Propagate SrcRegMap.
1567 SrcRegMap[RegA] = RegB;
1570 if (AllUsesCopied) {
1571 if (!IsEarlyClobber) {
1572 // Replace other (un-tied) uses of regB with LastCopiedReg.
1573 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1574 MachineOperand &MO = MI->getOperand(i);
1575 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1578 MO.setIsKill(false);
1579 RemovedKillFlag = true;
1581 MO.setReg(LastCopiedReg);
1587 // Update live variables for regB.
1588 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1589 MachineBasicBlock::iterator PrevMI = MI;
1591 LV->addVirtualRegisterKilled(RegB, PrevMI);
1594 // Update LiveIntervals.
1596 LiveInterval &LI = LIS->getInterval(RegB);
1597 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1598 LiveInterval::const_iterator I = LI.find(MIIdx);
1599 assert(I != LI.end() && "RegB must be live-in to use.");
1601 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1602 if (I->end == UseIdx)
1603 LI.removeSegment(LastCopyIdx, UseIdx);
1606 } else if (RemovedKillFlag) {
1607 // Some tied uses of regB matched their destination registers, so
1608 // regB is still used in this instruction, but a kill flag was
1609 // removed from a different tied use of regB, so now we need to add
1610 // a kill flag to one of the remaining uses of regB.
1611 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1612 MachineOperand &MO = MI->getOperand(i);
1613 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1621 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1623 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1625 const TargetMachine &TM = MF->getTarget();
1626 MRI = &MF->getRegInfo();
1627 TII = MF->getSubtarget().getInstrInfo();
1628 TRI = MF->getSubtarget().getRegisterInfo();
1629 InstrItins = MF->getSubtarget().getInstrItineraryData();
1630 LV = getAnalysisIfAvailable<LiveVariables>();
1631 LIS = getAnalysisIfAvailable<LiveIntervals>();
1632 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1633 OptLevel = TM.getOptLevel();
1635 bool MadeChange = false;
1637 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1638 DEBUG(dbgs() << "********** Function: "
1639 << MF->getName() << '\n');
1641 // This pass takes the function out of SSA form.
1644 TiedOperandMap TiedOperands;
1645 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1646 MBBI != MBBE; ++MBBI) {
1649 DistanceMap.clear();
1653 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1655 MachineBasicBlock::iterator nmi = std::next(mi);
1656 if (mi->isDebugValue()) {
1661 // Expand REG_SEQUENCE instructions. This will position mi at the first
1662 // expanded instruction.
1663 if (mi->isRegSequence())
1664 eliminateRegSequence(mi);
1666 DistanceMap.insert(std::make_pair(mi, ++Dist));
1670 // First scan through all the tied register uses in this instruction
1671 // and record a list of pairs of tied operands for each register.
1672 if (!collectTiedOperands(mi, TiedOperands)) {
1677 ++NumTwoAddressInstrs;
1679 DEBUG(dbgs() << '\t' << *mi);
1681 // If the instruction has a single pair of tied operands, try some
1682 // transformations that may either eliminate the tied operands or
1683 // improve the opportunities for coalescing away the register copy.
1684 if (TiedOperands.size() == 1) {
1685 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
1686 = TiedOperands.begin()->second;
1687 if (TiedPairs.size() == 1) {
1688 unsigned SrcIdx = TiedPairs[0].first;
1689 unsigned DstIdx = TiedPairs[0].second;
1690 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1691 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1692 if (SrcReg != DstReg &&
1693 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1694 // The tied operands have been eliminated or shifted further down
1695 // the block to ease elimination. Continue processing with 'nmi'.
1696 TiedOperands.clear();
1703 // Now iterate over the information collected above.
1704 for (auto &TO : TiedOperands) {
1705 processTiedPairs(mi, TO.second, Dist);
1706 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1709 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1710 if (mi->isInsertSubreg()) {
1711 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1712 // To %reg:subidx = COPY %subreg
1713 unsigned SubIdx = mi->getOperand(3).getImm();
1714 mi->RemoveOperand(3);
1715 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1716 mi->getOperand(0).setSubReg(SubIdx);
1717 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1718 mi->RemoveOperand(1);
1719 mi->setDesc(TII->get(TargetOpcode::COPY));
1720 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1723 // Clear TiedOperands here instead of at the top of the loop
1724 // since most instructions do not have tied operands.
1725 TiedOperands.clear();
1731 MF->verify(this, "After two-address instruction pass");
1736 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1738 /// The instruction is turned into a sequence of sub-register copies:
1740 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1744 /// %dst:ssub0<def,undef> = COPY %v1
1745 /// %dst:ssub1<def> = COPY %v2
1747 void TwoAddressInstructionPass::
1748 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1749 MachineInstr *MI = MBBI;
1750 unsigned DstReg = MI->getOperand(0).getReg();
1751 if (MI->getOperand(0).getSubReg() ||
1752 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1753 !(MI->getNumOperands() & 1)) {
1754 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1755 llvm_unreachable(nullptr);
1758 SmallVector<unsigned, 4> OrigRegs;
1760 OrigRegs.push_back(MI->getOperand(0).getReg());
1761 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1762 OrigRegs.push_back(MI->getOperand(i).getReg());
1765 bool DefEmitted = false;
1766 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1767 MachineOperand &UseMO = MI->getOperand(i);
1768 unsigned SrcReg = UseMO.getReg();
1769 unsigned SubIdx = MI->getOperand(i+1).getImm();
1770 // Nothing needs to be inserted for <undef> operands.
1771 if (UseMO.isUndef())
1774 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1775 // might insert a COPY that uses SrcReg after is was killed.
1776 bool isKill = UseMO.isKill();
1778 for (unsigned j = i + 2; j < e; j += 2)
1779 if (MI->getOperand(j).getReg() == SrcReg) {
1780 MI->getOperand(j).setIsKill();
1781 UseMO.setIsKill(false);
1786 // Insert the sub-register copy.
1787 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1788 TII->get(TargetOpcode::COPY))
1789 .addReg(DstReg, RegState::Define, SubIdx)
1792 // The first def needs an <undef> flag because there is no live register
1795 CopyMI->getOperand(0).setIsUndef(true);
1796 // Return an iterator pointing to the first inserted instr.
1801 // Update LiveVariables' kill info.
1802 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1803 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1805 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1808 MachineBasicBlock::iterator EndMBBI =
1809 std::next(MachineBasicBlock::iterator(MI));
1812 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1813 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1814 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1815 MI->RemoveOperand(j);
1817 DEBUG(dbgs() << "Eliminated: " << *MI);
1818 MI->eraseFromParent();
1821 // Udpate LiveIntervals.
1823 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);