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/ADT/DenseMap.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
36 #include "llvm/CodeGen/LiveVariables.h"
37 #include "llvm/CodeGen/MachineFunctionPass.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/Passes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCInstrItineraries.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #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 // Keep track the distance of a MI from the start of the current basic block.
87 DenseMap<MachineInstr*, unsigned> DistanceMap;
89 // Set of already processed instructions in the current block.
90 SmallPtrSet<MachineInstr*, 8> Processed;
92 // A map from virtual registers to physical registers which are likely targets
93 // to be coalesced to due to copies from physical registers to virtual
94 // registers. e.g. v1024 = move r0.
95 DenseMap<unsigned, unsigned> SrcRegMap;
97 // A map from virtual registers to physical registers which are likely targets
98 // to be coalesced to due to copies to physical registers from virtual
99 // registers. e.g. r1 = move v1024.
100 DenseMap<unsigned, unsigned> DstRegMap;
102 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
103 MachineBasicBlock::iterator OldPos);
105 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
107 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
109 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
110 MachineInstr *MI, unsigned Dist);
112 bool commuteInstruction(MachineInstr *MI,
113 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
115 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
117 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
119 unsigned RegA, unsigned RegB, unsigned Dist);
121 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
123 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
126 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
127 MachineBasicBlock::iterator &nmi,
130 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
131 MachineBasicBlock::iterator &nmi,
132 unsigned SrcIdx, unsigned DstIdx,
133 unsigned Dist, bool shouldOnlyCommute);
135 bool tryInstructionCommute(MachineInstr *MI,
140 void scanUses(unsigned DstReg);
142 void processCopy(MachineInstr *MI);
144 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
145 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
146 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
147 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
148 void eliminateRegSequence(MachineBasicBlock::iterator&);
151 static char ID; // Pass identification, replacement for typeid
152 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
157 AU.setPreservesCFG();
158 AU.addRequired<AAResultsWrapperPass>();
159 AU.addUsedIfAvailable<LiveVariables>();
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 /// 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 /// A two-address instruction has been converted to a three-address instruction
185 /// to avoid clobbering a register. Try to sink it past the instruction that
186 /// would kill the above mentioned register to reduce register pressure.
187 bool TwoAddressInstructionPass::
188 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
189 MachineBasicBlock::iterator OldPos) {
190 // FIXME: Shouldn't we be trying to do this before we three-addressify the
191 // instruction? After this transformation is done, we no longer need
192 // the instruction to be in three-address form.
194 // Check if it's safe to move this instruction.
195 bool SeenStore = true; // Be conservative.
196 if (!MI->isSafeToMove(AA, SeenStore))
200 SmallSet<unsigned, 4> UseRegs;
202 for (const MachineOperand &MO : MI->operands()) {
205 unsigned MOReg = MO.getReg();
208 if (MO.isUse() && MOReg != SavedReg)
209 UseRegs.insert(MO.getReg());
213 // Don't try to move it if it implicitly defines a register.
216 // For now, don't move any instructions that define multiple registers.
218 DefReg = MO.getReg();
221 // Find the instruction that kills SavedReg.
222 MachineInstr *KillMI = nullptr;
224 LiveInterval &LI = LIS->getInterval(SavedReg);
225 assert(LI.end() != LI.begin() &&
226 "Reg should not have empty live interval.");
228 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
229 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
230 if (I != LI.end() && I->start < MBBEndIdx)
234 KillMI = LIS->getInstructionFromIndex(I->end);
237 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
240 KillMI = UseMO.getParent();
245 // If we find the instruction that kills SavedReg, and it is in an
246 // appropriate location, we can try to sink the current instruction
248 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
249 MachineBasicBlock::iterator(KillMI) == OldPos || KillMI->isTerminator())
252 // If any of the definitions are used by another instruction between the
253 // position and the kill use, then it's not safe to sink it.
255 // FIXME: This can be sped up if there is an easy way to query whether an
256 // instruction is before or after another instruction. Then we can use
257 // MachineRegisterInfo def / use instead.
258 MachineOperand *KillMO = nullptr;
259 MachineBasicBlock::iterator KillPos = KillMI;
262 unsigned NumVisited = 0;
263 for (MachineInstr &OtherMI : llvm::make_range(std::next(OldPos), KillPos)) {
264 // DBG_VALUE cannot be counted against the limit.
265 if (OtherMI.isDebugValue())
267 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
270 for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
271 MachineOperand &MO = OtherMI.getOperand(i);
274 unsigned MOReg = MO.getReg();
280 if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
281 if (&OtherMI == KillMI && MOReg == SavedReg)
282 // Save the operand that kills the register. We want to unset the kill
283 // marker if we can sink MI past it.
285 else if (UseRegs.count(MOReg))
286 // One of the uses is killed before the destination.
291 assert(KillMO && "Didn't find kill");
294 // Update kill and LV information.
295 KillMO->setIsKill(false);
296 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
297 KillMO->setIsKill(true);
300 LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
303 // Move instruction to its destination.
305 MBB->insert(KillPos, MI);
308 LIS->handleMove(*MI);
314 /// Return the MachineInstr* if it is the single def of the Reg in current BB.
315 static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
316 const MachineRegisterInfo *MRI) {
317 MachineInstr *Ret = nullptr;
318 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
319 if (DefMI.getParent() != BB || DefMI.isDebugValue())
323 else if (Ret != &DefMI)
329 /// Check if there is a reversed copy chain from FromReg to ToReg:
330 /// %Tmp1 = copy %Tmp2;
331 /// %FromReg = copy %Tmp1;
332 /// %ToReg = add %FromReg ...
333 /// %Tmp2 = copy %ToReg;
334 /// MaxLen specifies the maximum length of the copy chain the func
335 /// can walk through.
336 bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
338 unsigned TmpReg = FromReg;
339 for (int i = 0; i < Maxlen; i++) {
340 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
341 if (!Def || !Def->isCopy())
344 TmpReg = Def->getOperand(1).getReg();
352 /// Return true if there are no intervening uses between the last instruction
353 /// in the MBB that defines the specified register and the two-address
354 /// instruction which is being processed. It also returns the last def location
356 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
359 unsigned LastUse = Dist;
360 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
361 MachineInstr *MI = MO.getParent();
362 if (MI->getParent() != MBB || MI->isDebugValue())
364 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
365 if (DI == DistanceMap.end())
367 if (MO.isUse() && DI->second < LastUse)
368 LastUse = DI->second;
369 if (MO.isDef() && DI->second > LastDef)
370 LastDef = DI->second;
373 return !(LastUse > LastDef && LastUse < Dist);
376 /// Return true if the specified MI is a copy instruction or an extract_subreg
377 /// instruction. It also returns the source and destination registers and
378 /// whether they are physical registers by reference.
379 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
380 unsigned &SrcReg, unsigned &DstReg,
381 bool &IsSrcPhys, bool &IsDstPhys) {
385 DstReg = MI.getOperand(0).getReg();
386 SrcReg = MI.getOperand(1).getReg();
387 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
388 DstReg = MI.getOperand(0).getReg();
389 SrcReg = MI.getOperand(2).getReg();
393 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
394 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
398 /// Test if the given register value, which is used by the
399 /// given instruction, is killed by the given instruction.
400 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
401 LiveIntervals *LIS) {
402 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
403 !LIS->isNotInMIMap(*MI)) {
404 // FIXME: Sometimes tryInstructionTransform() will add instructions and
405 // test whether they can be folded before keeping them. In this case it
406 // sets a kill before recursively calling tryInstructionTransform() again.
407 // If there is no interval available, we assume that this instruction is
408 // one of those. A kill flag is manually inserted on the operand so the
409 // check below will handle it.
410 LiveInterval &LI = LIS->getInterval(Reg);
411 // This is to match the kill flag version where undefs don't have kill
413 if (!LI.hasAtLeastOneValue())
416 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
417 LiveInterval::const_iterator I = LI.find(useIdx);
418 assert(I != LI.end() && "Reg must be live-in to use.");
419 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
422 return MI->killsRegister(Reg);
425 /// Test if the given register value, which is used by the given
426 /// instruction, is killed by the given instruction. This looks through
427 /// coalescable copies to see if the original value is potentially not killed.
429 /// For example, in this code:
431 /// %reg1034 = copy %reg1024
432 /// %reg1035 = copy %reg1025<kill>
433 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
435 /// %reg1034 is not considered to be killed, since it is copied from a
436 /// register which is not killed. Treating it as not killed lets the
437 /// normal heuristics commute the (two-address) add, which lets
438 /// coalescing eliminate the extra copy.
440 /// If allowFalsePositives is true then likely kills are treated as kills even
441 /// if it can't be proven that they are kills.
442 static bool isKilled(MachineInstr &MI, unsigned Reg,
443 const MachineRegisterInfo *MRI,
444 const TargetInstrInfo *TII,
446 bool allowFalsePositives) {
447 MachineInstr *DefMI = &MI;
449 // All uses of physical registers are likely to be kills.
450 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
451 (allowFalsePositives || MRI->hasOneUse(Reg)))
453 if (!isPlainlyKilled(DefMI, Reg, LIS))
455 if (TargetRegisterInfo::isPhysicalRegister(Reg))
457 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
458 // If there are multiple defs, we can't do a simple analysis, so just
459 // go with what the kill flag says.
460 if (std::next(Begin) != MRI->def_end())
462 DefMI = Begin->getParent();
463 bool IsSrcPhys, IsDstPhys;
464 unsigned SrcReg, DstReg;
465 // If the def is something other than a copy, then it isn't going to
466 // be coalesced, so follow the kill flag.
467 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
473 /// Return true if the specified MI uses the specified register as a two-address
474 /// use. If so, return the destination register by reference.
475 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
476 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
477 const MachineOperand &MO = MI.getOperand(i);
478 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
481 if (MI.isRegTiedToDefOperand(i, &ti)) {
482 DstReg = MI.getOperand(ti).getReg();
489 /// Given a register, if has a single in-basic block use, return the use
490 /// instruction if it's a copy or a two-address use.
492 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
493 MachineRegisterInfo *MRI,
494 const TargetInstrInfo *TII,
496 unsigned &DstReg, bool &IsDstPhys) {
497 if (!MRI->hasOneNonDBGUse(Reg))
498 // None or more than one use.
500 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
501 if (UseMI.getParent() != MBB)
505 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
510 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
511 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
517 /// Return the physical register the specified virtual register might be mapped
520 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
521 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
522 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
523 if (SI == RegMap.end())
527 if (TargetRegisterInfo::isPhysicalRegister(Reg))
532 /// Return true if the two registers are equal or aliased.
534 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
539 return TRI->regsOverlap(RegA, RegB);
542 // Returns true if Reg is equal or aliased to at least one register in Set.
543 static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
544 const TargetRegisterInfo *TRI) {
545 for (unsigned R : Set)
546 if (TRI->regsOverlap(R, Reg))
552 /// Return true if it's potentially profitable to commute the two-address
553 /// instruction that's being processed.
555 TwoAddressInstructionPass::
556 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
557 MachineInstr *MI, unsigned Dist) {
558 if (OptLevel == CodeGenOpt::None)
561 // Determine if it's profitable to commute this two address instruction. In
562 // general, we want no uses between this instruction and the definition of
563 // the two-address register.
565 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
566 // %reg1029<def> = MOV8rr %reg1028
567 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
568 // insert => %reg1030<def> = MOV8rr %reg1028
569 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
570 // In this case, it might not be possible to coalesce the second MOV8rr
571 // instruction if the first one is coalesced. So it would be profitable to
573 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
574 // %reg1029<def> = MOV8rr %reg1028
575 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
576 // insert => %reg1030<def> = MOV8rr %reg1029
577 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
579 if (!isPlainlyKilled(MI, regC, LIS))
582 // Ok, we have something like:
583 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
584 // let's see if it's worth commuting it.
586 // Look for situations like this:
587 // %reg1024<def> = MOV r1
588 // %reg1025<def> = MOV r0
589 // %reg1026<def> = ADD %reg1024, %reg1025
591 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
592 unsigned ToRegA = getMappedReg(regA, DstRegMap);
594 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
595 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
596 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
597 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
599 // Compute if any of the following are true:
600 // -RegB is not tied to a register and RegC is compatible with RegA.
601 // -RegB is tied to the wrong physical register, but RegC is.
602 // -RegB is tied to the wrong physical register, and RegC isn't tied.
603 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
605 // Don't compute if any of the following are true:
606 // -RegC is not tied to a register and RegB is compatible with RegA.
607 // -RegC is tied to the wrong physical register, but RegB is.
608 // -RegC is tied to the wrong physical register, and RegB isn't tied.
609 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
613 // If there is a use of regC between its last def (could be livein) and this
614 // instruction, then bail.
615 unsigned LastDefC = 0;
616 if (!noUseAfterLastDef(regC, Dist, LastDefC))
619 // If there is a use of regB between its last def (could be livein) and this
620 // instruction, then go ahead and make this transformation.
621 unsigned LastDefB = 0;
622 if (!noUseAfterLastDef(regB, Dist, LastDefB))
625 // Look for situation like this:
626 // %reg101 = MOV %reg100
628 // %reg103 = ADD %reg102, %reg101
630 // %reg100 = MOV %reg103
631 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
632 // to eliminate an otherwise unavoidable copy.
634 // We can extend the logic further: If an pair of operands in an insn has
635 // been merged, the insn could be regarded as a virtual copy, and the virtual
636 // copy could also be used to construct a copy chain.
637 // To more generally minimize register copies, ideally the logic of two addr
638 // instruction pass should be integrated with register allocation pass where
639 // interference graph is available.
640 if (isRevCopyChain(regC, regA, 3))
643 if (isRevCopyChain(regB, regA, 3))
646 // Since there are no intervening uses for both registers, then commute
647 // if the def of regC is closer. Its live interval is shorter.
648 return LastDefB && LastDefC && LastDefC > LastDefB;
651 /// Commute a two-address instruction and update the basic block, distance map,
652 /// and live variables if needed. Return true if it is successful.
653 bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
657 unsigned RegC = MI->getOperand(RegCIdx).getReg();
658 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
659 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
661 if (NewMI == nullptr) {
662 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
666 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
667 assert(NewMI == MI &&
668 "TargetInstrInfo::commuteInstruction() should not return a new "
669 "instruction unless it was requested.");
671 // Update source register map.
672 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
674 unsigned RegA = MI->getOperand(0).getReg();
675 SrcRegMap[RegA] = FromRegC;
681 /// Return true if it is profitable to convert the given 2-address instruction
682 /// to a 3-address one.
684 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
685 // Look for situations like this:
686 // %reg1024<def> = MOV r1
687 // %reg1025<def> = MOV r0
688 // %reg1026<def> = ADD %reg1024, %reg1025
690 // Turn ADD into a 3-address instruction to avoid a copy.
691 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
694 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
695 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
698 /// Convert the specified two-address instruction into a three address one.
699 /// Return true if this transformation was successful.
701 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
702 MachineBasicBlock::iterator &nmi,
703 unsigned RegA, unsigned RegB,
705 // FIXME: Why does convertToThreeAddress() need an iterator reference?
706 MachineFunction::iterator MFI = MBB->getIterator();
707 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
708 assert(MBB->getIterator() == MFI &&
709 "convertToThreeAddress changed iterator reference");
713 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
714 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
718 LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
720 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
721 // FIXME: Temporary workaround. If the new instruction doesn't
722 // uses RegB, convertToThreeAddress must have created more
723 // then one instruction.
724 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
726 MBB->erase(mi); // Nuke the old inst.
729 DistanceMap.insert(std::make_pair(NewMI, Dist));
734 // Update source and destination register maps.
735 SrcRegMap.erase(RegA);
736 DstRegMap.erase(RegB);
740 /// Scan forward recursively for only uses, update maps if the use is a copy or
741 /// a two-address instruction.
743 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
744 SmallVector<unsigned, 4> VirtRegPairs;
748 unsigned Reg = DstReg;
749 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
750 NewReg, IsDstPhys)) {
751 if (IsCopy && !Processed.insert(UseMI).second)
754 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
755 if (DI != DistanceMap.end())
756 // Earlier in the same MBB.Reached via a back edge.
760 VirtRegPairs.push_back(NewReg);
763 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
765 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
766 VirtRegPairs.push_back(NewReg);
770 if (!VirtRegPairs.empty()) {
771 unsigned ToReg = VirtRegPairs.back();
772 VirtRegPairs.pop_back();
773 while (!VirtRegPairs.empty()) {
774 unsigned FromReg = VirtRegPairs.back();
775 VirtRegPairs.pop_back();
776 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
778 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
781 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
783 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
787 /// If the specified instruction is not yet processed, process it if it's a
788 /// copy. For a copy instruction, we find the physical registers the
789 /// source and destination registers might be mapped to. These are kept in
790 /// point-to maps used to determine future optimizations. e.g.
793 /// v1026 = add v1024, v1025
795 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
796 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
797 /// potentially joined with r1 on the output side. It's worthwhile to commute
798 /// 'add' to eliminate a copy.
799 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
800 if (Processed.count(MI))
803 bool IsSrcPhys, IsDstPhys;
804 unsigned SrcReg, DstReg;
805 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
808 if (IsDstPhys && !IsSrcPhys)
809 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
810 else if (!IsDstPhys && IsSrcPhys) {
811 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
813 assert(SrcRegMap[DstReg] == SrcReg &&
814 "Can't map to two src physical registers!");
819 Processed.insert(MI);
822 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
823 /// consider moving the instruction below the kill instruction in order to
824 /// eliminate the need for the copy.
825 bool TwoAddressInstructionPass::
826 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
827 MachineBasicBlock::iterator &nmi,
829 // Bail immediately if we don't have LV or LIS available. We use them to find
830 // kills efficiently.
834 MachineInstr *MI = &*mi;
835 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
836 if (DI == DistanceMap.end())
837 // Must be created from unfolded load. Don't waste time trying this.
840 MachineInstr *KillMI = nullptr;
842 LiveInterval &LI = LIS->getInterval(Reg);
843 assert(LI.end() != LI.begin() &&
844 "Reg should not have empty live interval.");
846 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
847 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
848 if (I != LI.end() && I->start < MBBEndIdx)
852 KillMI = LIS->getInstructionFromIndex(I->end);
854 KillMI = LV->getVarInfo(Reg).findKill(MBB);
856 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
857 // Don't mess with copies, they may be coalesced later.
860 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
861 KillMI->isBranch() || KillMI->isTerminator())
862 // Don't move pass calls, etc.
866 if (isTwoAddrUse(*KillMI, Reg, DstReg))
869 bool SeenStore = true;
870 if (!MI->isSafeToMove(AA, SeenStore))
873 if (TII->getInstrLatency(InstrItins, *MI) > 1)
874 // FIXME: Needs more sophisticated heuristics.
877 SmallVector<unsigned, 2> Uses;
878 SmallVector<unsigned, 2> Kills;
879 SmallVector<unsigned, 2> Defs;
880 for (const MachineOperand &MO : MI->operands()) {
883 unsigned MOReg = MO.getReg();
887 Defs.push_back(MOReg);
889 Uses.push_back(MOReg);
890 if (MOReg != Reg && (MO.isKill() ||
891 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
892 Kills.push_back(MOReg);
896 // Move the copies connected to MI down as well.
897 MachineBasicBlock::iterator Begin = MI;
898 MachineBasicBlock::iterator AfterMI = std::next(Begin);
900 MachineBasicBlock::iterator End = AfterMI;
901 while (End->isCopy() &&
902 regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) {
903 Defs.push_back(End->getOperand(0).getReg());
907 // Check if the reschedule will not break depedencies.
908 unsigned NumVisited = 0;
909 MachineBasicBlock::iterator KillPos = KillMI;
911 for (MachineInstr &OtherMI : llvm::make_range(End, KillPos)) {
912 // DBG_VALUE cannot be counted against the limit.
913 if (OtherMI.isDebugValue())
915 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
918 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
919 OtherMI.isBranch() || OtherMI.isTerminator())
920 // Don't move pass calls, etc.
922 for (const MachineOperand &MO : OtherMI.operands()) {
925 unsigned MOReg = MO.getReg();
929 if (regOverlapsSet(Uses, MOReg, TRI))
930 // Physical register use would be clobbered.
932 if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
933 // May clobber a physical register def.
934 // FIXME: This may be too conservative. It's ok if the instruction
935 // is sunken completely below the use.
938 if (regOverlapsSet(Defs, MOReg, TRI))
941 MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
942 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
943 regOverlapsSet(Kills, MOReg, TRI)))
944 // Don't want to extend other live ranges and update kills.
946 if (MOReg == Reg && !isKill)
947 // We can't schedule across a use of the register in question.
949 // Ensure that if this is register in question, its the kill we expect.
950 assert((MOReg != Reg || &OtherMI == KillMI) &&
951 "Found multiple kills of a register in a basic block");
956 // Move debug info as well.
957 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
961 MachineBasicBlock::iterator InsertPos = KillPos;
963 // We have to move the copies first so that the MBB is still well-formed
964 // when calling handleMove().
965 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
966 auto 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
980 LIS->handleMove(*MI);
982 LV->removeVirtualRegisterKilled(Reg, *KillMI);
983 LV->addVirtualRegisterKilled(Reg, *MI);
986 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
990 /// Return true if the re-scheduling will put the given instruction too close
991 /// 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 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1011 /// consider moving the kill instruction above the current two-address
1012 /// instruction in order to eliminate the need for the copy.
1013 bool TwoAddressInstructionPass::
1014 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
1015 MachineBasicBlock::iterator &nmi,
1017 // Bail immediately if we don't have LV or LIS available. We use them to find
1018 // kills efficiently.
1022 MachineInstr *MI = &*mi;
1023 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1024 if (DI == DistanceMap.end())
1025 // Must be created from unfolded load. Don't waste time trying this.
1028 MachineInstr *KillMI = nullptr;
1030 LiveInterval &LI = LIS->getInterval(Reg);
1031 assert(LI.end() != LI.begin() &&
1032 "Reg should not have empty live interval.");
1034 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1035 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1036 if (I != LI.end() && I->start < MBBEndIdx)
1040 KillMI = LIS->getInstructionFromIndex(I->end);
1042 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1044 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1045 // Don't mess with copies, they may be coalesced later.
1049 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1052 bool SeenStore = true;
1053 if (!KillMI->isSafeToMove(AA, SeenStore))
1056 SmallSet<unsigned, 2> Uses;
1057 SmallSet<unsigned, 2> Kills;
1058 SmallSet<unsigned, 2> Defs;
1059 SmallSet<unsigned, 2> LiveDefs;
1060 for (const MachineOperand &MO : KillMI->operands()) {
1063 unsigned MOReg = MO.getReg();
1067 if (isDefTooClose(MOReg, DI->second, MI))
1069 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1070 if (MOReg == Reg && !isKill)
1073 if (isKill && MOReg != Reg)
1074 Kills.insert(MOReg);
1075 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1078 LiveDefs.insert(MOReg);
1082 // Check if the reschedule will not break depedencies.
1083 unsigned NumVisited = 0;
1084 for (MachineInstr &OtherMI :
1085 llvm::make_range(mi, MachineBasicBlock::iterator(KillMI))) {
1086 // DBG_VALUE cannot be counted against the limit.
1087 if (OtherMI.isDebugValue())
1089 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1092 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1093 OtherMI.isBranch() || OtherMI.isTerminator())
1094 // Don't move pass calls, etc.
1096 SmallVector<unsigned, 2> OtherDefs;
1097 for (const MachineOperand &MO : OtherMI.operands()) {
1100 unsigned MOReg = MO.getReg();
1104 if (Defs.count(MOReg))
1105 // Moving KillMI can clobber the physical register if the def has
1108 if (Kills.count(MOReg))
1109 // Don't want to extend other live ranges and update kills.
1111 if (&OtherMI != MI && MOReg == Reg &&
1112 !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
1113 // We can't schedule across a use of the register in question.
1116 OtherDefs.push_back(MOReg);
1120 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1121 unsigned MOReg = OtherDefs[i];
1122 if (Uses.count(MOReg))
1124 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1125 LiveDefs.count(MOReg))
1127 // Physical register def is seen.
1132 // Move the old kill above MI, don't forget to move debug info as well.
1133 MachineBasicBlock::iterator InsertPos = mi;
1134 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
1136 MachineBasicBlock::iterator From = KillMI;
1137 MachineBasicBlock::iterator To = std::next(From);
1138 while (std::prev(From)->isDebugValue())
1140 MBB->splice(InsertPos, MBB, From, To);
1142 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1143 DistanceMap.erase(DI);
1145 // Update live variables
1147 LIS->handleMove(*KillMI);
1149 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1150 LV->addVirtualRegisterKilled(Reg, *MI);
1153 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1157 /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1158 /// given machine instruction to improve opportunities for coalescing and
1159 /// elimination of a register to register copy.
1161 /// 'DstOpIdx' specifies the index of MI def operand.
1162 /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1163 /// operand is killed by the given instruction.
1164 /// The 'Dist' arguments provides the distance of MI from the start of the
1165 /// current basic block and it is used to determine if it is profitable
1166 /// to commute operands in the instruction.
1168 /// Returns true if the transformation happened. Otherwise, returns false.
1169 bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1174 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1175 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1176 unsigned OpsNum = MI->getDesc().getNumOperands();
1177 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1178 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1179 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1180 // and OtherOpIdx are commutable, it does not really search for
1181 // other commutable operands and does not change the values of passed
1183 if (OtherOpIdx == BaseOpIdx ||
1184 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1187 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1188 bool AggressiveCommute = false;
1190 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1191 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1193 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1196 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1198 AggressiveCommute = true;
1201 // If it's profitable to commute, try to do so.
1202 if (DoCommute && commuteInstruction(MI, BaseOpIdx, OtherOpIdx, Dist)) {
1204 if (AggressiveCommute)
1212 /// For the case where an instruction has a single pair of tied register
1213 /// operands, attempt some transformations that may either eliminate the tied
1214 /// operands or improve the opportunities for coalescing away the register copy.
1215 /// Returns true if no copy needs to be inserted to untie mi's operands
1216 /// (either because they were untied, or because mi was rescheduled, and will
1217 /// be visited again later). If the shouldOnlyCommute flag is true, only
1218 /// instruction commutation is attempted.
1219 bool TwoAddressInstructionPass::
1220 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1221 MachineBasicBlock::iterator &nmi,
1222 unsigned SrcIdx, unsigned DstIdx,
1223 unsigned Dist, bool shouldOnlyCommute) {
1224 if (OptLevel == CodeGenOpt::None)
1227 MachineInstr &MI = *mi;
1228 unsigned regA = MI.getOperand(DstIdx).getReg();
1229 unsigned regB = MI.getOperand(SrcIdx).getReg();
1231 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1232 "cannot make instruction into two-address form");
1233 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1235 if (TargetRegisterInfo::isVirtualRegister(regA))
1238 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1240 // If the instruction is convertible to 3 Addr, instead
1241 // of returning try 3 Addr transformation aggresively and
1242 // use this variable to check later. Because it might be better.
1243 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1244 // instead of the following code.
1248 if (Commuted && !MI.isConvertibleTo3Addr())
1251 if (shouldOnlyCommute)
1254 // If there is one more use of regB later in the same MBB, consider
1255 // re-schedule this MI below it.
1256 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1261 // If we commuted, regB may have changed so we should re-sample it to avoid
1262 // confusing the three address conversion below.
1264 regB = MI.getOperand(SrcIdx).getReg();
1265 regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1268 if (MI.isConvertibleTo3Addr()) {
1269 // This instruction is potentially convertible to a true
1270 // three-address instruction. Check if it is profitable.
1271 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1272 // Try to convert it.
1273 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1274 ++NumConvertedTo3Addr;
1275 return true; // Done with this instruction.
1280 // Return if it is commuted but 3 addr conversion is failed.
1284 // If there is one more use of regB later in the same MBB, consider
1285 // re-schedule it before this MI if it's legal.
1286 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1291 // If this is an instruction with a load folded into it, try unfolding
1292 // the load, e.g. avoid this:
1294 // addq (%rax), %rcx
1295 // in favor of this:
1296 // movq (%rax), %rcx
1298 // because it's preferable to schedule a load than a register copy.
1299 if (MI.mayLoad() && !regBKilled) {
1300 // Determine if a load can be unfolded.
1301 unsigned LoadRegIndex;
1303 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1304 /*UnfoldLoad=*/true,
1305 /*UnfoldStore=*/false,
1308 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1309 if (UnfoldMCID.getNumDefs() == 1) {
1311 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1312 const TargetRegisterClass *RC =
1313 TRI->getAllocatableClass(
1314 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1315 unsigned Reg = MRI->createVirtualRegister(RC);
1316 SmallVector<MachineInstr *, 2> NewMIs;
1317 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1318 /*UnfoldLoad=*/true,
1319 /*UnfoldStore=*/false, NewMIs)) {
1320 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1323 assert(NewMIs.size() == 2 &&
1324 "Unfolded a load into multiple instructions!");
1325 // The load was previously folded, so this is the only use.
1326 NewMIs[1]->addRegisterKilled(Reg, TRI);
1328 // Tentatively insert the instructions into the block so that they
1329 // look "normal" to the transformation logic.
1330 MBB->insert(mi, NewMIs[0]);
1331 MBB->insert(mi, NewMIs[1]);
1333 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1334 << "2addr: NEW INST: " << *NewMIs[1]);
1336 // Transform the instruction, now that it no longer has a load.
1337 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1338 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1339 MachineBasicBlock::iterator NewMI = NewMIs[1];
1340 bool TransformResult =
1341 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1342 (void)TransformResult;
1343 assert(!TransformResult &&
1344 "tryInstructionTransform() should return false.");
1345 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1346 // Success, or at least we made an improvement. Keep the unfolded
1347 // instructions and discard the original.
1349 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1350 MachineOperand &MO = MI.getOperand(i);
1352 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1355 if (NewMIs[0]->killsRegister(MO.getReg()))
1356 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1358 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1359 "Kill missing after load unfold!");
1360 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1363 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1364 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1365 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1367 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1368 "Dead flag missing after load unfold!");
1369 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1374 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1377 SmallVector<unsigned, 4> OrigRegs;
1379 for (const MachineOperand &MO : MI.operands()) {
1381 OrigRegs.push_back(MO.getReg());
1385 MI.eraseFromParent();
1387 // Update LiveIntervals.
1389 MachineBasicBlock::iterator Begin(NewMIs[0]);
1390 MachineBasicBlock::iterator End(NewMIs[1]);
1391 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1396 // Transforming didn't eliminate the tie and didn't lead to an
1397 // improvement. Clean up the unfolded instructions and keep the
1399 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1400 NewMIs[0]->eraseFromParent();
1401 NewMIs[1]->eraseFromParent();
1410 // Collect tied operands of MI that need to be handled.
1411 // Rewrite trivial cases immediately.
1412 // Return true if any tied operands where found, including the trivial ones.
1413 bool TwoAddressInstructionPass::
1414 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1415 const MCInstrDesc &MCID = MI->getDesc();
1416 bool AnyOps = false;
1417 unsigned NumOps = MI->getNumOperands();
1419 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1420 unsigned DstIdx = 0;
1421 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1424 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1425 MachineOperand &DstMO = MI->getOperand(DstIdx);
1426 unsigned SrcReg = SrcMO.getReg();
1427 unsigned DstReg = DstMO.getReg();
1428 // Tied constraint already satisfied?
1429 if (SrcReg == DstReg)
1432 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1434 // Deal with <undef> uses immediately - simply rewrite the src operand.
1435 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1436 // Constrain the DstReg register class if required.
1437 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1438 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1440 MRI->constrainRegClass(DstReg, RC);
1441 SrcMO.setReg(DstReg);
1443 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1446 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1451 // Process a list of tied MI operands that all use the same source register.
1452 // The tied pairs are of the form (SrcIdx, DstIdx).
1454 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1455 TiedPairList &TiedPairs,
1457 bool IsEarlyClobber = false;
1458 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1459 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1460 IsEarlyClobber |= DstMO.isEarlyClobber();
1463 bool RemovedKillFlag = false;
1464 bool AllUsesCopied = true;
1465 unsigned LastCopiedReg = 0;
1466 SlotIndex LastCopyIdx;
1468 unsigned SubRegB = 0;
1469 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1470 unsigned SrcIdx = TiedPairs[tpi].first;
1471 unsigned DstIdx = TiedPairs[tpi].second;
1473 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1474 unsigned RegA = DstMO.getReg();
1476 // Grab RegB from the instruction because it may have changed if the
1477 // instruction was commuted.
1478 RegB = MI->getOperand(SrcIdx).getReg();
1479 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1482 // The register is tied to multiple destinations (or else we would
1483 // not have continued this far), but this use of the register
1484 // already matches the tied destination. Leave it.
1485 AllUsesCopied = false;
1488 LastCopiedReg = RegA;
1490 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1491 "cannot make instruction into two-address form");
1494 // First, verify that we don't have a use of "a" in the instruction
1495 // (a = b + a for example) because our transformation will not
1496 // work. This should never occur because we are in SSA form.
1497 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1498 assert(i == DstIdx ||
1499 !MI->getOperand(i).isReg() ||
1500 MI->getOperand(i).getReg() != RegA);
1504 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1505 TII->get(TargetOpcode::COPY), RegA);
1506 // If this operand is folding a truncation, the truncation now moves to the
1507 // copy so that the register classes remain valid for the operands.
1508 MIB.addReg(RegB, 0, SubRegB);
1509 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1511 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1512 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1514 "tied subregister must be a truncation");
1515 // The superreg class will not be used to constrain the subreg class.
1519 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1520 && "tied subregister must be a truncation");
1524 // Update DistanceMap.
1525 MachineBasicBlock::iterator PrevMI = MI;
1527 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
1528 DistanceMap[MI] = ++Dist;
1531 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1533 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1534 LiveInterval &LI = LIS->getInterval(RegA);
1535 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1537 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1538 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1542 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1544 MachineOperand &MO = MI->getOperand(SrcIdx);
1545 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1546 "inconsistent operand info for 2-reg pass");
1548 MO.setIsKill(false);
1549 RemovedKillFlag = true;
1552 // Make sure regA is a legal regclass for the SrcIdx operand.
1553 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1554 TargetRegisterInfo::isVirtualRegister(RegB))
1555 MRI->constrainRegClass(RegA, RC);
1557 // The getMatchingSuper asserts guarantee that the register class projected
1558 // by SubRegB is compatible with RegA with no subregister. So regardless of
1559 // whether the dest oper writes a subreg, the source oper should not.
1562 // Propagate SrcRegMap.
1563 SrcRegMap[RegA] = RegB;
1566 if (AllUsesCopied) {
1567 if (!IsEarlyClobber) {
1568 // Replace other (un-tied) uses of regB with LastCopiedReg.
1569 for (MachineOperand &MO : MI->operands()) {
1570 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1573 MO.setIsKill(false);
1574 RemovedKillFlag = true;
1576 MO.setReg(LastCopiedReg);
1582 // Update live variables for regB.
1583 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(*MI)) {
1584 MachineBasicBlock::iterator PrevMI = MI;
1586 LV->addVirtualRegisterKilled(RegB, *PrevMI);
1589 // Update LiveIntervals.
1591 LiveInterval &LI = LIS->getInterval(RegB);
1592 SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
1593 LiveInterval::const_iterator I = LI.find(MIIdx);
1594 assert(I != LI.end() && "RegB must be live-in to use.");
1596 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1597 if (I->end == UseIdx)
1598 LI.removeSegment(LastCopyIdx, UseIdx);
1601 } else if (RemovedKillFlag) {
1602 // Some tied uses of regB matched their destination registers, so
1603 // regB is still used in this instruction, but a kill flag was
1604 // removed from a different tied use of regB, so now we need to add
1605 // a kill flag to one of the remaining uses of regB.
1606 for (MachineOperand &MO : MI->operands()) {
1607 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1615 /// Reduce two-address instructions to two operands.
1616 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1618 const TargetMachine &TM = MF->getTarget();
1619 MRI = &MF->getRegInfo();
1620 TII = MF->getSubtarget().getInstrInfo();
1621 TRI = MF->getSubtarget().getRegisterInfo();
1622 InstrItins = MF->getSubtarget().getInstrItineraryData();
1623 LV = getAnalysisIfAvailable<LiveVariables>();
1624 LIS = getAnalysisIfAvailable<LiveIntervals>();
1625 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1626 OptLevel = TM.getOptLevel();
1628 bool MadeChange = false;
1630 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1631 DEBUG(dbgs() << "********** Function: "
1632 << MF->getName() << '\n');
1634 // This pass takes the function out of SSA form.
1637 TiedOperandMap TiedOperands;
1638 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1639 MBBI != MBBE; ++MBBI) {
1642 DistanceMap.clear();
1646 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1648 MachineBasicBlock::iterator nmi = std::next(mi);
1649 if (mi->isDebugValue()) {
1654 // Expand REG_SEQUENCE instructions. This will position mi at the first
1655 // expanded instruction.
1656 if (mi->isRegSequence())
1657 eliminateRegSequence(mi);
1659 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1663 // First scan through all the tied register uses in this instruction
1664 // and record a list of pairs of tied operands for each register.
1665 if (!collectTiedOperands(&*mi, TiedOperands)) {
1670 ++NumTwoAddressInstrs;
1672 DEBUG(dbgs() << '\t' << *mi);
1674 // If the instruction has a single pair of tied operands, try some
1675 // transformations that may either eliminate the tied operands or
1676 // improve the opportunities for coalescing away the register copy.
1677 if (TiedOperands.size() == 1) {
1678 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
1679 = TiedOperands.begin()->second;
1680 if (TiedPairs.size() == 1) {
1681 unsigned SrcIdx = TiedPairs[0].first;
1682 unsigned DstIdx = TiedPairs[0].second;
1683 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1684 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1685 if (SrcReg != DstReg &&
1686 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1687 // The tied operands have been eliminated or shifted further down
1688 // the block to ease elimination. Continue processing with 'nmi'.
1689 TiedOperands.clear();
1696 // Now iterate over the information collected above.
1697 for (auto &TO : TiedOperands) {
1698 processTiedPairs(&*mi, TO.second, Dist);
1699 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1702 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1703 if (mi->isInsertSubreg()) {
1704 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1705 // To %reg:subidx = COPY %subreg
1706 unsigned SubIdx = mi->getOperand(3).getImm();
1707 mi->RemoveOperand(3);
1708 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1709 mi->getOperand(0).setSubReg(SubIdx);
1710 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1711 mi->RemoveOperand(1);
1712 mi->setDesc(TII->get(TargetOpcode::COPY));
1713 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1716 // Clear TiedOperands here instead of at the top of the loop
1717 // since most instructions do not have tied operands.
1718 TiedOperands.clear();
1724 MF->verify(this, "After two-address instruction pass");
1729 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1731 /// The instruction is turned into a sequence of sub-register copies:
1733 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1737 /// %dst:ssub0<def,undef> = COPY %v1
1738 /// %dst:ssub1<def> = COPY %v2
1740 void TwoAddressInstructionPass::
1741 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1742 MachineInstr &MI = *MBBI;
1743 unsigned DstReg = MI.getOperand(0).getReg();
1744 if (MI.getOperand(0).getSubReg() ||
1745 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1746 !(MI.getNumOperands() & 1)) {
1747 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
1748 llvm_unreachable(nullptr);
1751 SmallVector<unsigned, 4> OrigRegs;
1753 OrigRegs.push_back(MI.getOperand(0).getReg());
1754 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
1755 OrigRegs.push_back(MI.getOperand(i).getReg());
1758 bool DefEmitted = false;
1759 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
1760 MachineOperand &UseMO = MI.getOperand(i);
1761 unsigned SrcReg = UseMO.getReg();
1762 unsigned SubIdx = MI.getOperand(i+1).getImm();
1763 // Nothing needs to be inserted for <undef> operands.
1764 if (UseMO.isUndef())
1767 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1768 // might insert a COPY that uses SrcReg after is was killed.
1769 bool isKill = UseMO.isKill();
1771 for (unsigned j = i + 2; j < e; j += 2)
1772 if (MI.getOperand(j).getReg() == SrcReg) {
1773 MI.getOperand(j).setIsKill();
1774 UseMO.setIsKill(false);
1779 // Insert the sub-register copy.
1780 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1781 TII->get(TargetOpcode::COPY))
1782 .addReg(DstReg, RegState::Define, SubIdx)
1785 // The first def needs an <undef> flag because there is no live register
1788 CopyMI->getOperand(0).setIsUndef(true);
1789 // Return an iterator pointing to the first inserted instr.
1794 // Update LiveVariables' kill info.
1795 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1796 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
1798 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1801 MachineBasicBlock::iterator EndMBBI =
1802 std::next(MachineBasicBlock::iterator(MI));
1805 DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
1806 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1807 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
1808 MI.RemoveOperand(j);
1810 DEBUG(dbgs() << "Eliminated: " << MI);
1811 MI.eraseFromParent();
1814 // Udpate LiveIntervals.
1816 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);