1044eb2f6SDimitry Andric //===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the TwoAddress instruction pass which is used
10009b1c42SEd Schouten // by most register allocators. Two-Address instructions are rewritten
11009b1c42SEd Schouten // from:
12009b1c42SEd Schouten //
13009b1c42SEd Schouten // A = B op C
14009b1c42SEd Schouten //
15009b1c42SEd Schouten // to:
16009b1c42SEd Schouten //
17009b1c42SEd Schouten // A = B
18009b1c42SEd Schouten // A op= C
19009b1c42SEd Schouten //
20009b1c42SEd Schouten // Note that if a register allocator chooses to use this pass, that it
21009b1c42SEd Schouten // has to be capable of handling the non-SSA nature of these rewritten
22009b1c42SEd Schouten // virtual registers.
23009b1c42SEd Schouten //
24009b1c42SEd Schouten // It is also worth noting that the duplicate operand of the two
25009b1c42SEd Schouten // address instruction is removed.
26009b1c42SEd Schouten //
27009b1c42SEd Schouten //===----------------------------------------------------------------------===//
28009b1c42SEd Schouten
29ac9a064cSDimitry Andric #include "llvm/CodeGen/TwoAddressInstructionPass.h"
304a16efa3SDimitry Andric #include "llvm/ADT/DenseMap.h"
31044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
32a7fe922bSDimitry Andric #include "llvm/ADT/SmallVector.h"
334a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
34044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
354a16efa3SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
36044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
37044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
38009b1c42SEd Schouten #include "llvm/CodeGen/LiveVariables.h"
39044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
40ac9a064cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
41044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
42009b1c42SEd Schouten #include "llvm/CodeGen/MachineFunctionPass.h"
43009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstr.h"
4466e41e3cSRoman Divacky #include "llvm/CodeGen/MachineInstrBuilder.h"
45ac9a064cSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
46044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
47009b1c42SEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
4801095a5dSDimitry Andric #include "llvm/CodeGen/Passes.h"
49044eb2f6SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
50044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
51044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
52044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
53044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
54044eb2f6SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
55044eb2f6SDimitry Andric #include "llvm/Pass.h"
56044eb2f6SDimitry Andric #include "llvm/Support/CodeGen.h"
5759d6cff9SDimitry Andric #include "llvm/Support/CommandLine.h"
58009b1c42SEd Schouten #include "llvm/Support/Debug.h"
59abdf259dSRoman Divacky #include "llvm/Support/ErrorHandling.h"
605a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
614a16efa3SDimitry Andric #include "llvm/Target/TargetMachine.h"
62044eb2f6SDimitry Andric #include <cassert>
63044eb2f6SDimitry Andric #include <iterator>
64044eb2f6SDimitry Andric #include <utility>
6501095a5dSDimitry Andric
66009b1c42SEd Schouten using namespace llvm;
67009b1c42SEd Schouten
68ab44ce3dSDimitry Andric #define DEBUG_TYPE "twoaddressinstruction"
695ca98fd9SDimitry Andric
70009b1c42SEd Schouten STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
71009b1c42SEd Schouten STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
72009b1c42SEd Schouten STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
73009b1c42SEd Schouten STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
7463faed5bSDimitry Andric STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
7563faed5bSDimitry Andric STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
76009b1c42SEd Schouten
7759d6cff9SDimitry Andric // Temporary flag to disable rescheduling.
7859d6cff9SDimitry Andric static cl::opt<bool>
7959d6cff9SDimitry Andric EnableRescheduling("twoaddr-reschedule",
8059d6cff9SDimitry Andric cl::desc("Coalesce copies by rescheduling (default=true)"),
8159d6cff9SDimitry Andric cl::init(true), cl::Hidden);
8259d6cff9SDimitry Andric
839df3605dSDimitry Andric // Limit the number of dataflow edges to traverse when evaluating the benefit
849df3605dSDimitry Andric // of commuting operands.
859df3605dSDimitry Andric static cl::opt<unsigned> MaxDataFlowEdge(
869df3605dSDimitry Andric "dataflow-edge-limit", cl::Hidden, cl::init(3),
879df3605dSDimitry Andric cl::desc("Maximum number of dataflow edges to traverse when evaluating "
889df3605dSDimitry Andric "the benefit of commuting operands"));
899df3605dSDimitry Andric
90009b1c42SEd Schouten namespace {
91044eb2f6SDimitry Andric
92ac9a064cSDimitry Andric class TwoAddressInstructionImpl {
937fa27ce4SDimitry Andric MachineFunction *MF = nullptr;
947fa27ce4SDimitry Andric const TargetInstrInfo *TII = nullptr;
957fa27ce4SDimitry Andric const TargetRegisterInfo *TRI = nullptr;
967fa27ce4SDimitry Andric const InstrItineraryData *InstrItins = nullptr;
977fa27ce4SDimitry Andric MachineRegisterInfo *MRI = nullptr;
987fa27ce4SDimitry Andric LiveVariables *LV = nullptr;
997fa27ce4SDimitry Andric LiveIntervals *LIS = nullptr;
1007fa27ce4SDimitry Andric AliasAnalysis *AA = nullptr;
101b1c73532SDimitry Andric CodeGenOptLevel OptLevel = CodeGenOptLevel::None;
102009b1c42SEd Schouten
103522600a2SDimitry Andric // The current basic block being processed.
1047fa27ce4SDimitry Andric MachineBasicBlock *MBB = nullptr;
105522600a2SDimitry Andric
106dd58ef01SDimitry Andric // Keep track the distance of a MI from the start of the current basic block.
107009b1c42SEd Schouten DenseMap<MachineInstr*, unsigned> DistanceMap;
108009b1c42SEd Schouten
109522600a2SDimitry Andric // Set of already processed instructions in the current block.
110522600a2SDimitry Andric SmallPtrSet<MachineInstr*, 8> Processed;
111522600a2SDimitry Andric
112dd58ef01SDimitry Andric // A map from virtual registers to physical registers which are likely targets
113dd58ef01SDimitry Andric // to be coalesced to due to copies from physical registers to virtual
114dd58ef01SDimitry Andric // registers. e.g. v1024 = move r0.
115b60736ecSDimitry Andric DenseMap<Register, Register> SrcRegMap;
116009b1c42SEd Schouten
117dd58ef01SDimitry Andric // A map from virtual registers to physical registers which are likely targets
118dd58ef01SDimitry Andric // to be coalesced to due to copies to physical registers from virtual
119dd58ef01SDimitry Andric // registers. e.g. r1 = move v1024.
120b60736ecSDimitry Andric DenseMap<Register, Register> DstRegMap;
121009b1c42SEd Schouten
122b1c73532SDimitry Andric MachineInstr *getSingleDef(Register Reg, MachineBasicBlock *BB) const;
123c0981da4SDimitry Andric
124b60736ecSDimitry Andric bool isRevCopyChain(Register FromReg, Register ToReg, int Maxlen);
125009b1c42SEd Schouten
126b60736ecSDimitry Andric bool noUseAfterLastDef(Register Reg, unsigned Dist, unsigned &LastDef);
1275a5ac124SDimitry Andric
128b1c73532SDimitry Andric bool isCopyToReg(MachineInstr &MI, Register &SrcReg, Register &DstReg,
129b1c73532SDimitry Andric bool &IsSrcPhys, bool &IsDstPhys) const;
130b1c73532SDimitry Andric
131b1c73532SDimitry Andric bool isPlainlyKilled(const MachineInstr *MI, LiveRange &LR) const;
132b1c73532SDimitry Andric bool isPlainlyKilled(const MachineInstr *MI, Register Reg) const;
133b1c73532SDimitry Andric bool isPlainlyKilled(const MachineOperand &MO) const;
134b1c73532SDimitry Andric
135b1c73532SDimitry Andric bool isKilled(MachineInstr &MI, Register Reg, bool allowFalsePositives) const;
136b1c73532SDimitry Andric
137b1c73532SDimitry Andric MachineInstr *findOnlyInterestingUse(Register Reg, MachineBasicBlock *MBB,
138b1c73532SDimitry Andric bool &IsCopy, Register &DstReg,
139b1c73532SDimitry Andric bool &IsDstPhys) const;
140b1c73532SDimitry Andric
141b1c73532SDimitry Andric bool regsAreCompatible(Register RegA, Register RegB) const;
142b1c73532SDimitry Andric
143b1c73532SDimitry Andric void removeMapRegEntry(const MachineOperand &MO,
144b1c73532SDimitry Andric DenseMap<Register, Register> &RegMap) const;
145b1c73532SDimitry Andric
146b1c73532SDimitry Andric void removeClobberedSrcRegMap(MachineInstr *MI);
147b1c73532SDimitry Andric
148b1c73532SDimitry Andric bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg) const;
149b1c73532SDimitry Andric
150b60736ecSDimitry Andric bool isProfitableToCommute(Register RegA, Register RegB, Register RegC,
151522600a2SDimitry Andric MachineInstr *MI, unsigned Dist);
152009b1c42SEd Schouten
153b915e9e0SDimitry Andric bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
154dd58ef01SDimitry Andric unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
155009b1c42SEd Schouten
156b60736ecSDimitry Andric bool isProfitableToConv3Addr(Register RegA, Register RegB);
157009b1c42SEd Schouten
158522600a2SDimitry Andric bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
159b60736ecSDimitry Andric MachineBasicBlock::iterator &nmi, Register RegA,
160c0981da4SDimitry Andric Register RegB, unsigned &Dist);
161009b1c42SEd Schouten
162b60736ecSDimitry Andric bool isDefTooClose(Register Reg, unsigned Dist, MachineInstr *MI);
16363faed5bSDimitry Andric
164522600a2SDimitry Andric bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
165b60736ecSDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg);
166522600a2SDimitry Andric bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
167b60736ecSDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg);
16863faed5bSDimitry Andric
169522600a2SDimitry Andric bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
17059850d08SRoman Divacky MachineBasicBlock::iterator &nmi,
17159850d08SRoman Divacky unsigned SrcIdx, unsigned DstIdx,
172c0981da4SDimitry Andric unsigned &Dist, bool shouldOnlyCommute);
1736b943ff3SDimitry Andric
174dd58ef01SDimitry Andric bool tryInstructionCommute(MachineInstr *MI,
175dd58ef01SDimitry Andric unsigned DstOpIdx,
176dd58ef01SDimitry Andric unsigned BaseOpIdx,
177dd58ef01SDimitry Andric bool BaseOpKilled,
178dd58ef01SDimitry Andric unsigned Dist);
179b60736ecSDimitry Andric void scanUses(Register DstReg);
18059850d08SRoman Divacky
181522600a2SDimitry Andric void processCopy(MachineInstr *MI);
18259850d08SRoman Divacky
183044eb2f6SDimitry Andric using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>;
184044eb2f6SDimitry Andric using TiedOperandMap = SmallDenseMap<unsigned, TiedPairList>;
185044eb2f6SDimitry Andric
18658b69754SDimitry Andric bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
18758b69754SDimitry Andric void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
1884a16efa3SDimitry Andric void eliminateRegSequence(MachineBasicBlock::iterator&);
189145449b1SDimitry Andric bool processStatepoint(MachineInstr *MI, TiedOperandMap &TiedOperands);
190abdf259dSRoman Divacky
191009b1c42SEd Schouten public:
192ac9a064cSDimitry Andric TwoAddressInstructionImpl(MachineFunction &MF, MachineFunctionPass *P);
193ac9a064cSDimitry Andric TwoAddressInstructionImpl(MachineFunction &MF,
194ac9a064cSDimitry Andric MachineFunctionAnalysisManager &MFAM);
setOptLevel(CodeGenOptLevel Level)195ac9a064cSDimitry Andric void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
196ac9a064cSDimitry Andric bool run();
197ac9a064cSDimitry Andric };
198ac9a064cSDimitry Andric
199ac9a064cSDimitry Andric class TwoAddressInstructionLegacyPass : public MachineFunctionPass {
200ac9a064cSDimitry Andric public:
201009b1c42SEd Schouten static char ID; // Pass identification, replacement for typeid
202044eb2f6SDimitry Andric
TwoAddressInstructionLegacyPass()203ac9a064cSDimitry Andric TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {
204ac9a064cSDimitry Andric initializeTwoAddressInstructionLegacyPassPass(
205ac9a064cSDimitry Andric *PassRegistry::getPassRegistry());
206ac9a064cSDimitry Andric }
207ac9a064cSDimitry Andric
208ac9a064cSDimitry Andric /// Pass entry point.
runOnMachineFunction(MachineFunction & MF)209ac9a064cSDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override {
210ac9a064cSDimitry Andric TwoAddressInstructionImpl Impl(MF, this);
211ac9a064cSDimitry Andric // Disable optimizations if requested. We cannot skip the whole pass as some
212ac9a064cSDimitry Andric // fixups are necessary for correctness.
213ac9a064cSDimitry Andric if (skipFunction(MF.getFunction()))
214ac9a064cSDimitry Andric Impl.setOptLevel(CodeGenOptLevel::None);
215ac9a064cSDimitry Andric return Impl.run();
216cf099d11SDimitry Andric }
217009b1c42SEd Schouten
getAnalysisUsage(AnalysisUsage & AU) const2185ca98fd9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
21959850d08SRoman Divacky AU.setPreservesCFG();
2206b3f41edSDimitry Andric AU.addUsedIfAvailable<AAResultsWrapperPass>();
221ac9a064cSDimitry Andric AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
222ac9a064cSDimitry Andric AU.addPreserved<LiveVariablesWrapperPass>();
223ac9a064cSDimitry Andric AU.addPreserved<SlotIndexesWrapperPass>();
224ac9a064cSDimitry Andric AU.addPreserved<LiveIntervalsWrapperPass>();
225009b1c42SEd Schouten AU.addPreservedID(MachineLoopInfoID);
226009b1c42SEd Schouten AU.addPreservedID(MachineDominatorsID);
227009b1c42SEd Schouten MachineFunctionPass::getAnalysisUsage(AU);
228009b1c42SEd Schouten }
229009b1c42SEd Schouten };
230044eb2f6SDimitry Andric
231522600a2SDimitry Andric } // end anonymous namespace
232009b1c42SEd Schouten
233ac9a064cSDimitry Andric PreservedAnalyses
run(MachineFunction & MF,MachineFunctionAnalysisManager & MFAM)234ac9a064cSDimitry Andric TwoAddressInstructionPass::run(MachineFunction &MF,
235ac9a064cSDimitry Andric MachineFunctionAnalysisManager &MFAM) {
236ac9a064cSDimitry Andric // Disable optimizations if requested. We cannot skip the whole pass as some
237ac9a064cSDimitry Andric // fixups are necessary for correctness.
238ac9a064cSDimitry Andric TwoAddressInstructionImpl Impl(MF, MFAM);
239ac9a064cSDimitry Andric if (MF.getFunction().hasOptNone())
240ac9a064cSDimitry Andric Impl.setOptLevel(CodeGenOptLevel::None);
241044eb2f6SDimitry Andric
242ac9a064cSDimitry Andric MFPropsModifier _(*this, MF);
243ac9a064cSDimitry Andric bool Changed = Impl.run();
244ac9a064cSDimitry Andric if (!Changed)
245ac9a064cSDimitry Andric return PreservedAnalyses::all();
246ac9a064cSDimitry Andric auto PA = getMachineFunctionPassPreservedAnalyses();
247ac9a064cSDimitry Andric PA.preserve<LiveIntervalsAnalysis>();
248ac9a064cSDimitry Andric PA.preserve<LiveVariablesAnalysis>();
249ac9a064cSDimitry Andric PA.preserve<MachineDominatorTreeAnalysis>();
250ac9a064cSDimitry Andric PA.preserve<MachineLoopAnalysis>();
251ac9a064cSDimitry Andric PA.preserve<SlotIndexesAnalysis>();
252ac9a064cSDimitry Andric PA.preserveSet<CFGAnalyses>();
253ac9a064cSDimitry Andric return PA;
254ac9a064cSDimitry Andric }
255044eb2f6SDimitry Andric
256ac9a064cSDimitry Andric char TwoAddressInstructionLegacyPass::ID = 0;
257ac9a064cSDimitry Andric
258ac9a064cSDimitry Andric char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionLegacyPass::ID;
259ac9a064cSDimitry Andric
260ac9a064cSDimitry Andric INITIALIZE_PASS_BEGIN(TwoAddressInstructionLegacyPass, DEBUG_TYPE,
261cf099d11SDimitry Andric "Two-Address instruction pass", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)262dd58ef01SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
263ac9a064cSDimitry Andric INITIALIZE_PASS_END(TwoAddressInstructionLegacyPass, DEBUG_TYPE,
264cf099d11SDimitry Andric "Two-Address instruction pass", false, false)
265009b1c42SEd Schouten
266ac9a064cSDimitry Andric TwoAddressInstructionImpl::TwoAddressInstructionImpl(
267ac9a064cSDimitry Andric MachineFunction &Func, MachineFunctionAnalysisManager &MFAM)
268ac9a064cSDimitry Andric : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
269ac9a064cSDimitry Andric TRI(Func.getSubtarget().getRegisterInfo()),
270ac9a064cSDimitry Andric InstrItins(Func.getSubtarget().getInstrItineraryData()),
271ac9a064cSDimitry Andric MRI(&Func.getRegInfo()),
272ac9a064cSDimitry Andric LV(MFAM.getCachedResult<LiveVariablesAnalysis>(Func)),
273ac9a064cSDimitry Andric LIS(MFAM.getCachedResult<LiveIntervalsAnalysis>(Func)),
274ac9a064cSDimitry Andric OptLevel(Func.getTarget().getOptLevel()) {
275ac9a064cSDimitry Andric auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(Func)
276ac9a064cSDimitry Andric .getManager();
277ac9a064cSDimitry Andric AA = FAM.getCachedResult<AAManager>(Func.getFunction());
278ac9a064cSDimitry Andric }
279ac9a064cSDimitry Andric
TwoAddressInstructionImpl(MachineFunction & Func,MachineFunctionPass * P)280ac9a064cSDimitry Andric TwoAddressInstructionImpl::TwoAddressInstructionImpl(MachineFunction &Func,
281ac9a064cSDimitry Andric MachineFunctionPass *P)
282ac9a064cSDimitry Andric : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
283ac9a064cSDimitry Andric TRI(Func.getSubtarget().getRegisterInfo()),
284ac9a064cSDimitry Andric InstrItins(Func.getSubtarget().getInstrItineraryData()),
285ac9a064cSDimitry Andric MRI(&Func.getRegInfo()), OptLevel(Func.getTarget().getOptLevel()) {
286ac9a064cSDimitry Andric auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
287ac9a064cSDimitry Andric LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
288ac9a064cSDimitry Andric auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
289ac9a064cSDimitry Andric LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
290ac9a064cSDimitry Andric if (auto *AAPass = P->getAnalysisIfAvailable<AAResultsWrapperPass>())
291ac9a064cSDimitry Andric AA = &AAPass->getAAResults();
292ac9a064cSDimitry Andric else
293ac9a064cSDimitry Andric AA = nullptr;
294ac9a064cSDimitry Andric }
295ac9a064cSDimitry Andric
296dd58ef01SDimitry Andric /// Return the MachineInstr* if it is the single def of the Reg in current BB.
297b1c73532SDimitry Andric MachineInstr *
getSingleDef(Register Reg,MachineBasicBlock * BB) const298ac9a064cSDimitry Andric TwoAddressInstructionImpl::getSingleDef(Register Reg,
299b1c73532SDimitry Andric MachineBasicBlock *BB) const {
3005a5ac124SDimitry Andric MachineInstr *Ret = nullptr;
3015a5ac124SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
3025a5ac124SDimitry Andric if (DefMI.getParent() != BB || DefMI.isDebugValue())
3035a5ac124SDimitry Andric continue;
3045a5ac124SDimitry Andric if (!Ret)
3055a5ac124SDimitry Andric Ret = &DefMI;
3065a5ac124SDimitry Andric else if (Ret != &DefMI)
3075a5ac124SDimitry Andric return nullptr;
3085a5ac124SDimitry Andric }
3095a5ac124SDimitry Andric return Ret;
3105a5ac124SDimitry Andric }
3115a5ac124SDimitry Andric
3125a5ac124SDimitry Andric /// Check if there is a reversed copy chain from FromReg to ToReg:
3135a5ac124SDimitry Andric /// %Tmp1 = copy %Tmp2;
3145a5ac124SDimitry Andric /// %FromReg = copy %Tmp1;
3155a5ac124SDimitry Andric /// %ToReg = add %FromReg ...
3165a5ac124SDimitry Andric /// %Tmp2 = copy %ToReg;
3175a5ac124SDimitry Andric /// MaxLen specifies the maximum length of the copy chain the func
3185a5ac124SDimitry Andric /// can walk through.
isRevCopyChain(Register FromReg,Register ToReg,int Maxlen)319ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isRevCopyChain(Register FromReg, Register ToReg,
3205a5ac124SDimitry Andric int Maxlen) {
321b60736ecSDimitry Andric Register TmpReg = FromReg;
3225a5ac124SDimitry Andric for (int i = 0; i < Maxlen; i++) {
323b1c73532SDimitry Andric MachineInstr *Def = getSingleDef(TmpReg, MBB);
3245a5ac124SDimitry Andric if (!Def || !Def->isCopy())
3255a5ac124SDimitry Andric return false;
3265a5ac124SDimitry Andric
3275a5ac124SDimitry Andric TmpReg = Def->getOperand(1).getReg();
3285a5ac124SDimitry Andric
3295a5ac124SDimitry Andric if (TmpReg == ToReg)
3305a5ac124SDimitry Andric return true;
3315a5ac124SDimitry Andric }
3325a5ac124SDimitry Andric return false;
3335a5ac124SDimitry Andric }
3345a5ac124SDimitry Andric
335dd58ef01SDimitry Andric /// Return true if there are no intervening uses between the last instruction
336dd58ef01SDimitry Andric /// in the MBB that defines the specified register and the two-address
337dd58ef01SDimitry Andric /// instruction which is being processed. It also returns the last def location
338dd58ef01SDimitry Andric /// by reference.
noUseAfterLastDef(Register Reg,unsigned Dist,unsigned & LastDef)339ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::noUseAfterLastDef(Register Reg, unsigned Dist,
340009b1c42SEd Schouten unsigned &LastDef) {
341009b1c42SEd Schouten LastDef = 0;
342009b1c42SEd Schouten unsigned LastUse = Dist;
3435ca98fd9SDimitry Andric for (MachineOperand &MO : MRI->reg_operands(Reg)) {
344009b1c42SEd Schouten MachineInstr *MI = MO.getParent();
3456fe5c7aaSRoman Divacky if (MI->getParent() != MBB || MI->isDebugValue())
346009b1c42SEd Schouten continue;
347009b1c42SEd Schouten DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
348009b1c42SEd Schouten if (DI == DistanceMap.end())
349009b1c42SEd Schouten continue;
350009b1c42SEd Schouten if (MO.isUse() && DI->second < LastUse)
351009b1c42SEd Schouten LastUse = DI->second;
352009b1c42SEd Schouten if (MO.isDef() && DI->second > LastDef)
353009b1c42SEd Schouten LastDef = DI->second;
354009b1c42SEd Schouten }
355009b1c42SEd Schouten
356009b1c42SEd Schouten return !(LastUse > LastDef && LastUse < Dist);
357009b1c42SEd Schouten }
358009b1c42SEd Schouten
359dd58ef01SDimitry Andric /// Return true if the specified MI is a copy instruction or an extract_subreg
360dd58ef01SDimitry Andric /// instruction. It also returns the source and destination registers and
361dd58ef01SDimitry Andric /// whether they are physical registers by reference.
isCopyToReg(MachineInstr & MI,Register & SrcReg,Register & DstReg,bool & IsSrcPhys,bool & IsDstPhys) const362ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &MI, Register &SrcReg,
363b1c73532SDimitry Andric Register &DstReg, bool &IsSrcPhys,
364b1c73532SDimitry Andric bool &IsDstPhys) const {
365009b1c42SEd Schouten SrcReg = 0;
366009b1c42SEd Schouten DstReg = 0;
36766e41e3cSRoman Divacky if (MI.isCopy()) {
368009b1c42SEd Schouten DstReg = MI.getOperand(0).getReg();
369009b1c42SEd Schouten SrcReg = MI.getOperand(1).getReg();
370d39c594dSDimitry Andric } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
371009b1c42SEd Schouten DstReg = MI.getOperand(0).getReg();
372009b1c42SEd Schouten SrcReg = MI.getOperand(2).getReg();
373b60736ecSDimitry Andric } else {
374d39c594dSDimitry Andric return false;
375b60736ecSDimitry Andric }
376009b1c42SEd Schouten
377b60736ecSDimitry Andric IsSrcPhys = SrcReg.isPhysical();
378b60736ecSDimitry Andric IsDstPhys = DstReg.isPhysical();
379009b1c42SEd Schouten return true;
380009b1c42SEd Schouten }
381009b1c42SEd Schouten
isPlainlyKilled(const MachineInstr * MI,LiveRange & LR) const382ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
383b1c73532SDimitry Andric LiveRange &LR) const {
384b1c73532SDimitry Andric // This is to match the kill flag version where undefs don't have kill flags.
385b1c73532SDimitry Andric if (!LR.hasAtLeastOneValue())
386b1c73532SDimitry Andric return false;
387b1c73532SDimitry Andric
388b1c73532SDimitry Andric SlotIndex useIdx = LIS->getInstructionIndex(*MI);
389b1c73532SDimitry Andric LiveInterval::const_iterator I = LR.find(useIdx);
390b1c73532SDimitry Andric assert(I != LR.end() && "Reg must be live-in to use.");
391b1c73532SDimitry Andric return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
392b1c73532SDimitry Andric }
393b1c73532SDimitry Andric
394dd58ef01SDimitry Andric /// Test if the given register value, which is used by the
395dd58ef01SDimitry Andric /// given instruction, is killed by the given instruction.
isPlainlyKilled(const MachineInstr * MI,Register Reg) const396ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
397b1c73532SDimitry Andric Register Reg) const {
3984a16efa3SDimitry Andric // FIXME: Sometimes tryInstructionTransform() will add instructions and
3994a16efa3SDimitry Andric // test whether they can be folded before keeping them. In this case it
4004a16efa3SDimitry Andric // sets a kill before recursively calling tryInstructionTransform() again.
4014a16efa3SDimitry Andric // If there is no interval available, we assume that this instruction is
4024a16efa3SDimitry Andric // one of those. A kill flag is manually inserted on the operand so the
4034a16efa3SDimitry Andric // check below will handle it.
404b1c73532SDimitry Andric if (LIS && !LIS->isNotInMIMap(*MI)) {
405b1c73532SDimitry Andric if (Reg.isVirtual())
406b1c73532SDimitry Andric return isPlainlyKilled(MI, LIS->getInterval(Reg));
407b1c73532SDimitry Andric // Reserved registers are considered always live.
408b1c73532SDimitry Andric if (MRI->isReserved(Reg))
4094a16efa3SDimitry Andric return false;
410b1c73532SDimitry Andric return all_of(TRI->regunits(Reg), [&](MCRegUnit U) {
411b1c73532SDimitry Andric return isPlainlyKilled(MI, LIS->getRegUnit(U));
412b1c73532SDimitry Andric });
4134a16efa3SDimitry Andric }
4144a16efa3SDimitry Andric
415ac9a064cSDimitry Andric return MI->killsRegister(Reg, /*TRI=*/nullptr);
4164a16efa3SDimitry Andric }
4174a16efa3SDimitry Andric
4187fa27ce4SDimitry Andric /// Test if the register used by the given operand is killed by the operand's
4197fa27ce4SDimitry Andric /// instruction.
isPlainlyKilled(const MachineOperand & MO) const420ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled(
421b1c73532SDimitry Andric const MachineOperand &MO) const {
422b1c73532SDimitry Andric return MO.isKill() || isPlainlyKilled(MO.getParent(), MO.getReg());
4237fa27ce4SDimitry Andric }
4247fa27ce4SDimitry Andric
425dd58ef01SDimitry Andric /// Test if the given register value, which is used by the given
426009b1c42SEd Schouten /// instruction, is killed by the given instruction. This looks through
427009b1c42SEd Schouten /// coalescable copies to see if the original value is potentially not killed.
428009b1c42SEd Schouten ///
429009b1c42SEd Schouten /// For example, in this code:
430009b1c42SEd Schouten ///
431009b1c42SEd Schouten /// %reg1034 = copy %reg1024
432044eb2f6SDimitry Andric /// %reg1035 = copy killed %reg1025
433044eb2f6SDimitry Andric /// %reg1036 = add killed %reg1034, killed %reg1035
434009b1c42SEd Schouten ///
435009b1c42SEd Schouten /// %reg1034 is not considered to be killed, since it is copied from a
436009b1c42SEd Schouten /// register which is not killed. Treating it as not killed lets the
437009b1c42SEd Schouten /// normal heuristics commute the (two-address) add, which lets
438009b1c42SEd Schouten /// coalescing eliminate the extra copy.
439009b1c42SEd Schouten ///
4404a16efa3SDimitry Andric /// If allowFalsePositives is true then likely kills are treated as kills even
4414a16efa3SDimitry Andric /// if it can't be proven that they are kills.
isKilled(MachineInstr & MI,Register Reg,bool allowFalsePositives) const442ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isKilled(MachineInstr &MI, Register Reg,
443b1c73532SDimitry Andric bool allowFalsePositives) const {
444009b1c42SEd Schouten MachineInstr *DefMI = &MI;
445044eb2f6SDimitry Andric while (true) {
4464a16efa3SDimitry Andric // All uses of physical registers are likely to be kills.
447b60736ecSDimitry Andric if (Reg.isPhysical() && (allowFalsePositives || MRI->hasOneUse(Reg)))
4484a16efa3SDimitry Andric return true;
449b1c73532SDimitry Andric if (!isPlainlyKilled(DefMI, Reg))
450009b1c42SEd Schouten return false;
451b60736ecSDimitry Andric if (Reg.isPhysical())
452009b1c42SEd Schouten return true;
453009b1c42SEd Schouten MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
454009b1c42SEd Schouten // If there are multiple defs, we can't do a simple analysis, so just
455009b1c42SEd Schouten // go with what the kill flag says.
4565ca98fd9SDimitry Andric if (std::next(Begin) != MRI->def_end())
457009b1c42SEd Schouten return true;
4585ca98fd9SDimitry Andric DefMI = Begin->getParent();
459009b1c42SEd Schouten bool IsSrcPhys, IsDstPhys;
460b60736ecSDimitry Andric Register SrcReg, DstReg;
461009b1c42SEd Schouten // If the def is something other than a copy, then it isn't going to
462009b1c42SEd Schouten // be coalesced, so follow the kill flag.
463b1c73532SDimitry Andric if (!isCopyToReg(*DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
464009b1c42SEd Schouten return true;
465009b1c42SEd Schouten Reg = SrcReg;
466009b1c42SEd Schouten }
467009b1c42SEd Schouten }
468009b1c42SEd Schouten
469dd58ef01SDimitry Andric /// Return true if the specified MI uses the specified register as a two-address
470dd58ef01SDimitry Andric /// use. If so, return the destination register by reference.
isTwoAddrUse(MachineInstr & MI,Register Reg,Register & DstReg)471b60736ecSDimitry Andric static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg) {
47259d6cff9SDimitry Andric for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
473009b1c42SEd Schouten const MachineOperand &MO = MI.getOperand(i);
474009b1c42SEd Schouten if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
475009b1c42SEd Schouten continue;
476009b1c42SEd Schouten unsigned ti;
477009b1c42SEd Schouten if (MI.isRegTiedToDefOperand(i, &ti)) {
478009b1c42SEd Schouten DstReg = MI.getOperand(ti).getReg();
479009b1c42SEd Schouten return true;
480009b1c42SEd Schouten }
481009b1c42SEd Schouten }
482009b1c42SEd Schouten return false;
483009b1c42SEd Schouten }
484009b1c42SEd Schouten
485f65dcba8SDimitry Andric /// Given a register, if all its uses are in the same basic block, return the
486f65dcba8SDimitry Andric /// last use instruction if it's a copy or a two-address use.
findOnlyInterestingUse(Register Reg,MachineBasicBlock * MBB,bool & IsCopy,Register & DstReg,bool & IsDstPhys) const487ac9a064cSDimitry Andric MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
488b1c73532SDimitry Andric Register Reg, MachineBasicBlock *MBB, bool &IsCopy, Register &DstReg,
489b1c73532SDimitry Andric bool &IsDstPhys) const {
490f65dcba8SDimitry Andric MachineOperand *UseOp = nullptr;
491f65dcba8SDimitry Andric for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
492f65dcba8SDimitry Andric MachineInstr *MI = MO.getParent();
493f65dcba8SDimitry Andric if (MI->getParent() != MBB)
4945ca98fd9SDimitry Andric return nullptr;
495b1c73532SDimitry Andric if (isPlainlyKilled(MI, Reg))
496f65dcba8SDimitry Andric UseOp = &MO;
497f65dcba8SDimitry Andric }
498f65dcba8SDimitry Andric if (!UseOp)
4995ca98fd9SDimitry Andric return nullptr;
500f65dcba8SDimitry Andric MachineInstr &UseMI = *UseOp->getParent();
501f65dcba8SDimitry Andric
502b60736ecSDimitry Andric Register SrcReg;
503009b1c42SEd Schouten bool IsSrcPhys;
504b1c73532SDimitry Andric if (isCopyToReg(UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
505009b1c42SEd Schouten IsCopy = true;
506009b1c42SEd Schouten return &UseMI;
507009b1c42SEd Schouten }
508009b1c42SEd Schouten IsDstPhys = false;
509009b1c42SEd Schouten if (isTwoAddrUse(UseMI, Reg, DstReg)) {
510b60736ecSDimitry Andric IsDstPhys = DstReg.isPhysical();
511009b1c42SEd Schouten return &UseMI;
512009b1c42SEd Schouten }
513c0981da4SDimitry Andric if (UseMI.isCommutable()) {
514c0981da4SDimitry Andric unsigned Src1 = TargetInstrInfo::CommuteAnyOperandIndex;
5157fa27ce4SDimitry Andric unsigned Src2 = UseOp->getOperandNo();
516c0981da4SDimitry Andric if (TII->findCommutedOpIndices(UseMI, Src1, Src2)) {
517c0981da4SDimitry Andric MachineOperand &MO = UseMI.getOperand(Src1);
518c0981da4SDimitry Andric if (MO.isReg() && MO.isUse() &&
519c0981da4SDimitry Andric isTwoAddrUse(UseMI, MO.getReg(), DstReg)) {
520c0981da4SDimitry Andric IsDstPhys = DstReg.isPhysical();
521c0981da4SDimitry Andric return &UseMI;
522c0981da4SDimitry Andric }
523c0981da4SDimitry Andric }
524c0981da4SDimitry Andric }
5255ca98fd9SDimitry Andric return nullptr;
526009b1c42SEd Schouten }
527009b1c42SEd Schouten
528dd58ef01SDimitry Andric /// Return the physical register the specified virtual register might be mapped
529dd58ef01SDimitry Andric /// to.
getMappedReg(Register Reg,DenseMap<Register,Register> & RegMap)530b60736ecSDimitry Andric static MCRegister getMappedReg(Register Reg,
531b60736ecSDimitry Andric DenseMap<Register, Register> &RegMap) {
532b60736ecSDimitry Andric while (Reg.isVirtual()) {
533b60736ecSDimitry Andric DenseMap<Register, Register>::iterator SI = RegMap.find(Reg);
534009b1c42SEd Schouten if (SI == RegMap.end())
535009b1c42SEd Schouten return 0;
536009b1c42SEd Schouten Reg = SI->second;
537009b1c42SEd Schouten }
538b60736ecSDimitry Andric if (Reg.isPhysical())
539009b1c42SEd Schouten return Reg;
540009b1c42SEd Schouten return 0;
541009b1c42SEd Schouten }
542009b1c42SEd Schouten
543dd58ef01SDimitry Andric /// Return true if the two registers are equal or aliased.
regsAreCompatible(Register RegA,Register RegB) const544ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::regsAreCompatible(Register RegA,
545b1c73532SDimitry Andric Register RegB) const {
546009b1c42SEd Schouten if (RegA == RegB)
547009b1c42SEd Schouten return true;
548009b1c42SEd Schouten if (!RegA || !RegB)
549009b1c42SEd Schouten return false;
550009b1c42SEd Schouten return TRI->regsOverlap(RegA, RegB);
551009b1c42SEd Schouten }
552009b1c42SEd Schouten
553c0981da4SDimitry Andric /// From RegMap remove entries mapped to a physical register which overlaps MO.
removeMapRegEntry(const MachineOperand & MO,DenseMap<Register,Register> & RegMap) const554ac9a064cSDimitry Andric void TwoAddressInstructionImpl::removeMapRegEntry(
555b1c73532SDimitry Andric const MachineOperand &MO, DenseMap<Register, Register> &RegMap) const {
556c0981da4SDimitry Andric assert(
557c0981da4SDimitry Andric (MO.isReg() || MO.isRegMask()) &&
558c0981da4SDimitry Andric "removeMapRegEntry must be called with a register or regmask operand.");
559c0981da4SDimitry Andric
560c0981da4SDimitry Andric SmallVector<Register, 2> Srcs;
561c0981da4SDimitry Andric for (auto SI : RegMap) {
562c0981da4SDimitry Andric Register ToReg = SI.second;
563c0981da4SDimitry Andric if (ToReg.isVirtual())
564c0981da4SDimitry Andric continue;
565c0981da4SDimitry Andric
566c0981da4SDimitry Andric if (MO.isReg()) {
567c0981da4SDimitry Andric Register Reg = MO.getReg();
568c0981da4SDimitry Andric if (TRI->regsOverlap(ToReg, Reg))
569c0981da4SDimitry Andric Srcs.push_back(SI.first);
570c0981da4SDimitry Andric } else if (MO.clobbersPhysReg(ToReg))
571c0981da4SDimitry Andric Srcs.push_back(SI.first);
572c0981da4SDimitry Andric }
573c0981da4SDimitry Andric
574c0981da4SDimitry Andric for (auto SrcReg : Srcs)
575c0981da4SDimitry Andric RegMap.erase(SrcReg);
576c0981da4SDimitry Andric }
577c0981da4SDimitry Andric
578c0981da4SDimitry Andric /// If a physical register is clobbered, old entries mapped to it should be
579c0981da4SDimitry Andric /// deleted. For example
580c0981da4SDimitry Andric ///
581c0981da4SDimitry Andric /// %2:gr64 = COPY killed $rdx
582c0981da4SDimitry Andric /// MUL64r %3:gr64, implicit-def $rax, implicit-def $rdx
583c0981da4SDimitry Andric ///
584c0981da4SDimitry Andric /// After the MUL instruction, $rdx contains different value than in the COPY
585c0981da4SDimitry Andric /// instruction. So %2 should not map to $rdx after MUL.
removeClobberedSrcRegMap(MachineInstr * MI)586ac9a064cSDimitry Andric void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *MI) {
587c0981da4SDimitry Andric if (MI->isCopy()) {
588c0981da4SDimitry Andric // If a virtual register is copied to its mapped physical register, it
589c0981da4SDimitry Andric // doesn't change the potential coalescing between them, so we don't remove
590c0981da4SDimitry Andric // entries mapped to the physical register. For example
591c0981da4SDimitry Andric //
592c0981da4SDimitry Andric // %100 = COPY $r8
593c0981da4SDimitry Andric // ...
594c0981da4SDimitry Andric // $r8 = COPY %100
595c0981da4SDimitry Andric //
596c0981da4SDimitry Andric // The first copy constructs SrcRegMap[%100] = $r8, the second copy doesn't
597c0981da4SDimitry Andric // destroy the content of $r8, and should not impact SrcRegMap.
598c0981da4SDimitry Andric Register Dst = MI->getOperand(0).getReg();
599c0981da4SDimitry Andric if (!Dst || Dst.isVirtual())
600c0981da4SDimitry Andric return;
601c0981da4SDimitry Andric
602c0981da4SDimitry Andric Register Src = MI->getOperand(1).getReg();
603b1c73532SDimitry Andric if (regsAreCompatible(Dst, getMappedReg(Src, SrcRegMap)))
604c0981da4SDimitry Andric return;
605c0981da4SDimitry Andric }
606c0981da4SDimitry Andric
607f65dcba8SDimitry Andric for (const MachineOperand &MO : MI->operands()) {
608c0981da4SDimitry Andric if (MO.isRegMask()) {
609b1c73532SDimitry Andric removeMapRegEntry(MO, SrcRegMap);
610c0981da4SDimitry Andric continue;
611c0981da4SDimitry Andric }
612c0981da4SDimitry Andric if (!MO.isReg() || !MO.isDef())
613c0981da4SDimitry Andric continue;
614c0981da4SDimitry Andric Register Reg = MO.getReg();
615c0981da4SDimitry Andric if (!Reg || Reg.isVirtual())
616c0981da4SDimitry Andric continue;
617b1c73532SDimitry Andric removeMapRegEntry(MO, SrcRegMap);
618c0981da4SDimitry Andric }
619c0981da4SDimitry Andric }
620c0981da4SDimitry Andric
621a7fe922bSDimitry Andric // Returns true if Reg is equal or aliased to at least one register in Set.
regOverlapsSet(const SmallVectorImpl<Register> & Set,Register Reg) const622ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::regOverlapsSet(
623b1c73532SDimitry Andric const SmallVectorImpl<Register> &Set, Register Reg) const {
624a7fe922bSDimitry Andric for (unsigned R : Set)
625a7fe922bSDimitry Andric if (TRI->regsOverlap(R, Reg))
626a7fe922bSDimitry Andric return true;
627a7fe922bSDimitry Andric
628a7fe922bSDimitry Andric return false;
629a7fe922bSDimitry Andric }
630a7fe922bSDimitry Andric
631dd58ef01SDimitry Andric /// Return true if it's potentially profitable to commute the two-address
632dd58ef01SDimitry Andric /// instruction that's being processed.
isProfitableToCommute(Register RegA,Register RegB,Register RegC,MachineInstr * MI,unsigned Dist)633ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isProfitableToCommute(Register RegA,
634b60736ecSDimitry Andric Register RegB,
635b60736ecSDimitry Andric Register RegC,
636b60736ecSDimitry Andric MachineInstr *MI,
637b60736ecSDimitry Andric unsigned Dist) {
638b1c73532SDimitry Andric if (OptLevel == CodeGenOptLevel::None)
63963faed5bSDimitry Andric return false;
64063faed5bSDimitry Andric
641009b1c42SEd Schouten // Determine if it's profitable to commute this two address instruction. In
642009b1c42SEd Schouten // general, we want no uses between this instruction and the definition of
643009b1c42SEd Schouten // the two-address register.
644009b1c42SEd Schouten // e.g.
645044eb2f6SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
646d8e91e46SDimitry Andric // %reg1029 = COPY %reg1028
647044eb2f6SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
648d8e91e46SDimitry Andric // insert => %reg1030 = COPY %reg1028
649044eb2f6SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
650d8e91e46SDimitry Andric // In this case, it might not be possible to coalesce the second COPY
651009b1c42SEd Schouten // instruction if the first one is coalesced. So it would be profitable to
652009b1c42SEd Schouten // commute it:
653044eb2f6SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
654d8e91e46SDimitry Andric // %reg1029 = COPY %reg1028
655044eb2f6SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
656d8e91e46SDimitry Andric // insert => %reg1030 = COPY %reg1029
657044eb2f6SDimitry Andric // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags
658009b1c42SEd Schouten
659b1c73532SDimitry Andric if (!isPlainlyKilled(MI, RegC))
660009b1c42SEd Schouten return false;
661009b1c42SEd Schouten
662009b1c42SEd Schouten // Ok, we have something like:
663044eb2f6SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
664009b1c42SEd Schouten // let's see if it's worth commuting it.
665009b1c42SEd Schouten
666009b1c42SEd Schouten // Look for situations like this:
667044eb2f6SDimitry Andric // %reg1024 = MOV r1
668044eb2f6SDimitry Andric // %reg1025 = MOV r0
669044eb2f6SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025
670009b1c42SEd Schouten // r0 = MOV %reg1026
671009b1c42SEd Schouten // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
672b60736ecSDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
67358b69754SDimitry Andric if (ToRegA) {
674b60736ecSDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
675b60736ecSDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
676b1c73532SDimitry Andric bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
677b1c73532SDimitry Andric bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
67867c32a98SDimitry Andric
67967c32a98SDimitry Andric // Compute if any of the following are true:
68067c32a98SDimitry Andric // -RegB is not tied to a register and RegC is compatible with RegA.
68167c32a98SDimitry Andric // -RegB is tied to the wrong physical register, but RegC is.
68267c32a98SDimitry Andric // -RegB is tied to the wrong physical register, and RegC isn't tied.
68367c32a98SDimitry Andric if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
68467c32a98SDimitry Andric return true;
68567c32a98SDimitry Andric // Don't compute if any of the following are true:
68667c32a98SDimitry Andric // -RegC is not tied to a register and RegB is compatible with RegA.
68767c32a98SDimitry Andric // -RegC is tied to the wrong physical register, but RegB is.
68867c32a98SDimitry Andric // -RegC is tied to the wrong physical register, and RegB isn't tied.
68967c32a98SDimitry Andric if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
69067c32a98SDimitry Andric return false;
69158b69754SDimitry Andric }
692009b1c42SEd Schouten
693b60736ecSDimitry Andric // If there is a use of RegC between its last def (could be livein) and this
694009b1c42SEd Schouten // instruction, then bail.
695009b1c42SEd Schouten unsigned LastDefC = 0;
696b60736ecSDimitry Andric if (!noUseAfterLastDef(RegC, Dist, LastDefC))
697009b1c42SEd Schouten return false;
698009b1c42SEd Schouten
699b60736ecSDimitry Andric // If there is a use of RegB between its last def (could be livein) and this
700009b1c42SEd Schouten // instruction, then go ahead and make this transformation.
701009b1c42SEd Schouten unsigned LastDefB = 0;
702b60736ecSDimitry Andric if (!noUseAfterLastDef(RegB, Dist, LastDefB))
703009b1c42SEd Schouten return true;
704009b1c42SEd Schouten
7055a5ac124SDimitry Andric // Look for situation like this:
7065a5ac124SDimitry Andric // %reg101 = MOV %reg100
7075a5ac124SDimitry Andric // %reg102 = ...
7085a5ac124SDimitry Andric // %reg103 = ADD %reg102, %reg101
7095a5ac124SDimitry Andric // ... = %reg103 ...
7105a5ac124SDimitry Andric // %reg100 = MOV %reg103
7115a5ac124SDimitry Andric // If there is a reversed copy chain from reg101 to reg103, commute the ADD
7125a5ac124SDimitry Andric // to eliminate an otherwise unavoidable copy.
7135a5ac124SDimitry Andric // FIXME:
7145a5ac124SDimitry Andric // We can extend the logic further: If an pair of operands in an insn has
7155a5ac124SDimitry Andric // been merged, the insn could be regarded as a virtual copy, and the virtual
7165a5ac124SDimitry Andric // copy could also be used to construct a copy chain.
7175a5ac124SDimitry Andric // To more generally minimize register copies, ideally the logic of two addr
7185a5ac124SDimitry Andric // instruction pass should be integrated with register allocation pass where
7195a5ac124SDimitry Andric // interference graph is available.
720b60736ecSDimitry Andric if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge))
7215a5ac124SDimitry Andric return true;
7225a5ac124SDimitry Andric
723b60736ecSDimitry Andric if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge))
7245a5ac124SDimitry Andric return false;
7255a5ac124SDimitry Andric
726344a3780SDimitry Andric // Look for other target specific commute preference.
727344a3780SDimitry Andric bool Commute;
728344a3780SDimitry Andric if (TII->hasCommutePreference(*MI, Commute))
729344a3780SDimitry Andric return Commute;
730344a3780SDimitry Andric
731009b1c42SEd Schouten // Since there are no intervening uses for both registers, then commute
732b60736ecSDimitry Andric // if the def of RegC is closer. Its live interval is shorter.
733009b1c42SEd Schouten return LastDefB && LastDefC && LastDefC > LastDefB;
734009b1c42SEd Schouten }
735009b1c42SEd Schouten
736dd58ef01SDimitry Andric /// Commute a two-address instruction and update the basic block, distance map,
737dd58ef01SDimitry Andric /// and live variables if needed. Return true if it is successful.
commuteInstruction(MachineInstr * MI,unsigned DstIdx,unsigned RegBIdx,unsigned RegCIdx,unsigned Dist)738ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *MI,
739b915e9e0SDimitry Andric unsigned DstIdx,
740dd58ef01SDimitry Andric unsigned RegBIdx,
741dd58ef01SDimitry Andric unsigned RegCIdx,
742dd58ef01SDimitry Andric unsigned Dist) {
7431d5ae102SDimitry Andric Register RegC = MI->getOperand(RegCIdx).getReg();
744eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
74501095a5dSDimitry Andric MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
746009b1c42SEd Schouten
7475ca98fd9SDimitry Andric if (NewMI == nullptr) {
748eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
749009b1c42SEd Schouten return false;
750009b1c42SEd Schouten }
751009b1c42SEd Schouten
752eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
7534a16efa3SDimitry Andric assert(NewMI == MI &&
7544a16efa3SDimitry Andric "TargetInstrInfo::commuteInstruction() should not return a new "
7554a16efa3SDimitry Andric "instruction unless it was requested.");
756009b1c42SEd Schouten
757009b1c42SEd Schouten // Update source register map.
758b60736ecSDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
759009b1c42SEd Schouten if (FromRegC) {
7601d5ae102SDimitry Andric Register RegA = MI->getOperand(DstIdx).getReg();
761009b1c42SEd Schouten SrcRegMap[RegA] = FromRegC;
762009b1c42SEd Schouten }
763009b1c42SEd Schouten
764009b1c42SEd Schouten return true;
765009b1c42SEd Schouten }
766009b1c42SEd Schouten
767dd58ef01SDimitry Andric /// Return true if it is profitable to convert the given 2-address instruction
768dd58ef01SDimitry Andric /// to a 3-address one.
isProfitableToConv3Addr(Register RegA,Register RegB)769ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isProfitableToConv3Addr(Register RegA,
770b60736ecSDimitry Andric Register RegB) {
771009b1c42SEd Schouten // Look for situations like this:
772044eb2f6SDimitry Andric // %reg1024 = MOV r1
773044eb2f6SDimitry Andric // %reg1025 = MOV r0
774044eb2f6SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025
775009b1c42SEd Schouten // r2 = MOV %reg1026
776009b1c42SEd Schouten // Turn ADD into a 3-address instruction to avoid a copy.
777b60736ecSDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
7786b943ff3SDimitry Andric if (!FromRegB)
7796b943ff3SDimitry Andric return false;
780b60736ecSDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
781b1c73532SDimitry Andric return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
782009b1c42SEd Schouten }
783009b1c42SEd Schouten
784dd58ef01SDimitry Andric /// Convert the specified two-address instruction into a three address one.
785dd58ef01SDimitry Andric /// Return true if this transformation was successful.
convertInstTo3Addr(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,Register RegA,Register RegB,unsigned & Dist)786ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::convertInstTo3Addr(
787b60736ecSDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
788c0981da4SDimitry Andric Register RegA, Register RegB, unsigned &Dist) {
789c0981da4SDimitry Andric MachineInstrSpan MIS(mi, MBB);
790c0981da4SDimitry Andric MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS);
791522600a2SDimitry Andric if (!NewMI)
792522600a2SDimitry Andric return false;
793522600a2SDimitry Andric
794eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
795eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
796009b1c42SEd Schouten
797b60736ecSDimitry Andric // If the old instruction is debug value tracked, an update is required.
798b60736ecSDimitry Andric if (auto OldInstrNum = mi->peekDebugInstrNum()) {
799b60736ecSDimitry Andric assert(mi->getNumExplicitDefs() == 1);
800b60736ecSDimitry Andric assert(NewMI->getNumExplicitDefs() == 1);
801b60736ecSDimitry Andric
802b60736ecSDimitry Andric // Find the old and new def location.
8037fa27ce4SDimitry Andric unsigned OldIdx = mi->defs().begin()->getOperandNo();
8047fa27ce4SDimitry Andric unsigned NewIdx = NewMI->defs().begin()->getOperandNo();
805b60736ecSDimitry Andric
806b60736ecSDimitry Andric // Record that one def has been replaced by the other.
807b60736ecSDimitry Andric unsigned NewInstrNum = NewMI->getDebugInstrNum();
808b60736ecSDimitry Andric MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx),
809b60736ecSDimitry Andric std::make_pair(NewInstrNum, NewIdx));
810b60736ecSDimitry Andric }
811009b1c42SEd Schouten
812522600a2SDimitry Andric MBB->erase(mi); // Nuke the old inst.
813009b1c42SEd Schouten
814c0981da4SDimitry Andric for (MachineInstr &MI : MIS)
815c0981da4SDimitry Andric DistanceMap.insert(std::make_pair(&MI, Dist++));
816c0981da4SDimitry Andric Dist--;
817009b1c42SEd Schouten mi = NewMI;
8185ca98fd9SDimitry Andric nmi = std::next(mi);
819cf099d11SDimitry Andric
820cf099d11SDimitry Andric // Update source and destination register maps.
821cf099d11SDimitry Andric SrcRegMap.erase(RegA);
822cf099d11SDimitry Andric DstRegMap.erase(RegB);
823009b1c42SEd Schouten return true;
824009b1c42SEd Schouten }
825009b1c42SEd Schouten
826dd58ef01SDimitry Andric /// Scan forward recursively for only uses, update maps if the use is a copy or
827dd58ef01SDimitry Andric /// a two-address instruction.
scanUses(Register DstReg)828ac9a064cSDimitry Andric void TwoAddressInstructionImpl::scanUses(Register DstReg) {
829b60736ecSDimitry Andric SmallVector<Register, 4> VirtRegPairs;
8306b943ff3SDimitry Andric bool IsDstPhys;
8316b943ff3SDimitry Andric bool IsCopy = false;
832b60736ecSDimitry Andric Register NewReg;
833b60736ecSDimitry Andric Register Reg = DstReg;
834b1c73532SDimitry Andric while (MachineInstr *UseMI =
835b1c73532SDimitry Andric findOnlyInterestingUse(Reg, MBB, IsCopy, NewReg, IsDstPhys)) {
83667c32a98SDimitry Andric if (IsCopy && !Processed.insert(UseMI).second)
8376b943ff3SDimitry Andric break;
8386b943ff3SDimitry Andric
8396b943ff3SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
8406b943ff3SDimitry Andric if (DI != DistanceMap.end())
8416b943ff3SDimitry Andric // Earlier in the same MBB.Reached via a back edge.
8426b943ff3SDimitry Andric break;
8436b943ff3SDimitry Andric
8446b943ff3SDimitry Andric if (IsDstPhys) {
8456b943ff3SDimitry Andric VirtRegPairs.push_back(NewReg);
8466b943ff3SDimitry Andric break;
8476b943ff3SDimitry Andric }
848c0981da4SDimitry Andric SrcRegMap[NewReg] = Reg;
8496b943ff3SDimitry Andric VirtRegPairs.push_back(NewReg);
8506b943ff3SDimitry Andric Reg = NewReg;
8516b943ff3SDimitry Andric }
8526b943ff3SDimitry Andric
8536b943ff3SDimitry Andric if (!VirtRegPairs.empty()) {
8546b943ff3SDimitry Andric unsigned ToReg = VirtRegPairs.back();
8556b943ff3SDimitry Andric VirtRegPairs.pop_back();
8566b943ff3SDimitry Andric while (!VirtRegPairs.empty()) {
857c0981da4SDimitry Andric unsigned FromReg = VirtRegPairs.pop_back_val();
8586b943ff3SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
8596b943ff3SDimitry Andric if (!isNew)
8606b943ff3SDimitry Andric assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
8616b943ff3SDimitry Andric ToReg = FromReg;
8626b943ff3SDimitry Andric }
8636b943ff3SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
8646b943ff3SDimitry Andric if (!isNew)
8656b943ff3SDimitry Andric assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
8666b943ff3SDimitry Andric }
8676b943ff3SDimitry Andric }
8686b943ff3SDimitry Andric
869dd58ef01SDimitry Andric /// If the specified instruction is not yet processed, process it if it's a
870dd58ef01SDimitry Andric /// copy. For a copy instruction, we find the physical registers the
871009b1c42SEd Schouten /// source and destination registers might be mapped to. These are kept in
872009b1c42SEd Schouten /// point-to maps used to determine future optimizations. e.g.
873009b1c42SEd Schouten /// v1024 = mov r0
874009b1c42SEd Schouten /// v1025 = mov r1
875009b1c42SEd Schouten /// v1026 = add v1024, v1025
876009b1c42SEd Schouten /// r1 = mov r1026
877009b1c42SEd Schouten /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
878009b1c42SEd Schouten /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
879009b1c42SEd Schouten /// potentially joined with r1 on the output side. It's worthwhile to commute
880009b1c42SEd Schouten /// 'add' to eliminate a copy.
processCopy(MachineInstr * MI)881ac9a064cSDimitry Andric void TwoAddressInstructionImpl::processCopy(MachineInstr *MI) {
882009b1c42SEd Schouten if (Processed.count(MI))
883009b1c42SEd Schouten return;
884009b1c42SEd Schouten
885009b1c42SEd Schouten bool IsSrcPhys, IsDstPhys;
886b60736ecSDimitry Andric Register SrcReg, DstReg;
887b1c73532SDimitry Andric if (!isCopyToReg(*MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
888009b1c42SEd Schouten return;
889009b1c42SEd Schouten
890b60736ecSDimitry Andric if (IsDstPhys && !IsSrcPhys) {
891009b1c42SEd Schouten DstRegMap.insert(std::make_pair(SrcReg, DstReg));
892b60736ecSDimitry Andric } else if (!IsDstPhys && IsSrcPhys) {
893009b1c42SEd Schouten bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
894009b1c42SEd Schouten if (!isNew)
895009b1c42SEd Schouten assert(SrcRegMap[DstReg] == SrcReg &&
896009b1c42SEd Schouten "Can't map to two src physical registers!");
897009b1c42SEd Schouten
898522600a2SDimitry Andric scanUses(DstReg);
899009b1c42SEd Schouten }
900009b1c42SEd Schouten
901009b1c42SEd Schouten Processed.insert(MI);
902009b1c42SEd Schouten }
903009b1c42SEd Schouten
904dd58ef01SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
905dd58ef01SDimitry Andric /// consider moving the instruction below the kill instruction in order to
906dd58ef01SDimitry Andric /// eliminate the need for the copy.
rescheduleMIBelowKill(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,Register Reg)907ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
908b60736ecSDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
909b60736ecSDimitry Andric Register Reg) {
9104a16efa3SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find
9114a16efa3SDimitry Andric // kills efficiently.
9124a16efa3SDimitry Andric if (!LV && !LIS)
91358b69754SDimitry Andric return false;
91458b69754SDimitry Andric
91563faed5bSDimitry Andric MachineInstr *MI = &*mi;
91663faed5bSDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
91763faed5bSDimitry Andric if (DI == DistanceMap.end())
91863faed5bSDimitry Andric // Must be created from unfolded load. Don't waste time trying this.
91963faed5bSDimitry Andric return false;
92063faed5bSDimitry Andric
9215ca98fd9SDimitry Andric MachineInstr *KillMI = nullptr;
9224a16efa3SDimitry Andric if (LIS) {
9234a16efa3SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg);
9244a16efa3SDimitry Andric assert(LI.end() != LI.begin() &&
9254a16efa3SDimitry Andric "Reg should not have empty live interval.");
9264a16efa3SDimitry Andric
9274a16efa3SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
9284a16efa3SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx);
9294a16efa3SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx)
9304a16efa3SDimitry Andric return false;
9314a16efa3SDimitry Andric
9324a16efa3SDimitry Andric --I;
9334a16efa3SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end);
9344a16efa3SDimitry Andric } else {
9354a16efa3SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB);
9364a16efa3SDimitry Andric }
93758b69754SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
93863faed5bSDimitry Andric // Don't mess with copies, they may be coalesced later.
93963faed5bSDimitry Andric return false;
94063faed5bSDimitry Andric
94163faed5bSDimitry Andric if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
94263faed5bSDimitry Andric KillMI->isBranch() || KillMI->isTerminator())
94363faed5bSDimitry Andric // Don't move pass calls, etc.
94463faed5bSDimitry Andric return false;
94563faed5bSDimitry Andric
946b60736ecSDimitry Andric Register DstReg;
94763faed5bSDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg))
94863faed5bSDimitry Andric return false;
94963faed5bSDimitry Andric
95063faed5bSDimitry Andric bool SeenStore = true;
9515a5ac124SDimitry Andric if (!MI->isSafeToMove(AA, SeenStore))
95263faed5bSDimitry Andric return false;
95363faed5bSDimitry Andric
95401095a5dSDimitry Andric if (TII->getInstrLatency(InstrItins, *MI) > 1)
95563faed5bSDimitry Andric // FIXME: Needs more sophisticated heuristics.
95663faed5bSDimitry Andric return false;
95763faed5bSDimitry Andric
958b60736ecSDimitry Andric SmallVector<Register, 2> Uses;
959b60736ecSDimitry Andric SmallVector<Register, 2> Kills;
960b60736ecSDimitry Andric SmallVector<Register, 2> Defs;
961dd58ef01SDimitry Andric for (const MachineOperand &MO : MI->operands()) {
96263faed5bSDimitry Andric if (!MO.isReg())
96363faed5bSDimitry Andric continue;
9641d5ae102SDimitry Andric Register MOReg = MO.getReg();
96563faed5bSDimitry Andric if (!MOReg)
96663faed5bSDimitry Andric continue;
96763faed5bSDimitry Andric if (MO.isDef())
968a7fe922bSDimitry Andric Defs.push_back(MOReg);
96963faed5bSDimitry Andric else {
970a7fe922bSDimitry Andric Uses.push_back(MOReg);
971b1c73532SDimitry Andric if (MOReg != Reg && isPlainlyKilled(MO))
972a7fe922bSDimitry Andric Kills.push_back(MOReg);
97363faed5bSDimitry Andric }
97463faed5bSDimitry Andric }
97563faed5bSDimitry Andric
97663faed5bSDimitry Andric // Move the copies connected to MI down as well.
9774a16efa3SDimitry Andric MachineBasicBlock::iterator Begin = MI;
9785ca98fd9SDimitry Andric MachineBasicBlock::iterator AfterMI = std::next(Begin);
9794a16efa3SDimitry Andric MachineBasicBlock::iterator End = AfterMI;
980d8e91e46SDimitry Andric while (End != MBB->end()) {
981d8e91e46SDimitry Andric End = skipDebugInstructionsForward(End, MBB->end());
982b1c73532SDimitry Andric if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
983a7fe922bSDimitry Andric Defs.push_back(End->getOperand(0).getReg());
984d8e91e46SDimitry Andric else
985d8e91e46SDimitry Andric break;
9864a16efa3SDimitry Andric ++End;
98763faed5bSDimitry Andric }
98863faed5bSDimitry Andric
98971d5a254SDimitry Andric // Check if the reschedule will not break dependencies.
99063faed5bSDimitry Andric unsigned NumVisited = 0;
99163faed5bSDimitry Andric MachineBasicBlock::iterator KillPos = KillMI;
99263faed5bSDimitry Andric ++KillPos;
993044eb2f6SDimitry Andric for (MachineInstr &OtherMI : make_range(End, KillPos)) {
994344a3780SDimitry Andric // Debug or pseudo instructions cannot be counted against the limit.
995344a3780SDimitry Andric if (OtherMI.isDebugOrPseudoInstr())
99663faed5bSDimitry Andric continue;
99763faed5bSDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
99863faed5bSDimitry Andric return false;
99963faed5bSDimitry Andric ++NumVisited;
100001095a5dSDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
100101095a5dSDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator())
100263faed5bSDimitry Andric // Don't move pass calls, etc.
100363faed5bSDimitry Andric return false;
100401095a5dSDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) {
100563faed5bSDimitry Andric if (!MO.isReg())
100663faed5bSDimitry Andric continue;
10071d5ae102SDimitry Andric Register MOReg = MO.getReg();
100863faed5bSDimitry Andric if (!MOReg)
100963faed5bSDimitry Andric continue;
101063faed5bSDimitry Andric if (MO.isDef()) {
1011b1c73532SDimitry Andric if (regOverlapsSet(Uses, MOReg))
101263faed5bSDimitry Andric // Physical register use would be clobbered.
101363faed5bSDimitry Andric return false;
1014b1c73532SDimitry Andric if (!MO.isDead() && regOverlapsSet(Defs, MOReg))
101563faed5bSDimitry Andric // May clobber a physical register def.
101663faed5bSDimitry Andric // FIXME: This may be too conservative. It's ok if the instruction
101763faed5bSDimitry Andric // is sunken completely below the use.
101863faed5bSDimitry Andric return false;
101963faed5bSDimitry Andric } else {
1020b1c73532SDimitry Andric if (regOverlapsSet(Defs, MOReg))
102163faed5bSDimitry Andric return false;
1022b1c73532SDimitry Andric bool isKill = isPlainlyKilled(MO);
1023b1c73532SDimitry Andric if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg)) ||
1024b1c73532SDimitry Andric regOverlapsSet(Kills, MOReg)))
102563faed5bSDimitry Andric // Don't want to extend other live ranges and update kills.
102663faed5bSDimitry Andric return false;
10274a16efa3SDimitry Andric if (MOReg == Reg && !isKill)
102858b69754SDimitry Andric // We can't schedule across a use of the register in question.
102958b69754SDimitry Andric return false;
103058b69754SDimitry Andric // Ensure that if this is register in question, its the kill we expect.
103101095a5dSDimitry Andric assert((MOReg != Reg || &OtherMI == KillMI) &&
103258b69754SDimitry Andric "Found multiple kills of a register in a basic block");
103363faed5bSDimitry Andric }
103463faed5bSDimitry Andric }
103563faed5bSDimitry Andric }
103663faed5bSDimitry Andric
103763faed5bSDimitry Andric // Move debug info as well.
1038eb11fae6SDimitry Andric while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr())
10394a16efa3SDimitry Andric --Begin;
10404a16efa3SDimitry Andric
10414a16efa3SDimitry Andric nmi = End;
10424a16efa3SDimitry Andric MachineBasicBlock::iterator InsertPos = KillPos;
10434a16efa3SDimitry Andric if (LIS) {
1044c0981da4SDimitry Andric // We have to move the copies (and any interleaved debug instructions)
1045c0981da4SDimitry Andric // first so that the MBB is still well-formed when calling handleMove().
10464a16efa3SDimitry Andric for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
104701095a5dSDimitry Andric auto CopyMI = MBBI++;
10484a16efa3SDimitry Andric MBB->splice(InsertPos, MBB, CopyMI);
1049c0981da4SDimitry Andric if (!CopyMI->isDebugOrPseudoInstr())
105001095a5dSDimitry Andric LIS->handleMove(*CopyMI);
10514a16efa3SDimitry Andric InsertPos = CopyMI;
10524a16efa3SDimitry Andric }
10535ca98fd9SDimitry Andric End = std::next(MachineBasicBlock::iterator(MI));
10544a16efa3SDimitry Andric }
105563faed5bSDimitry Andric
105663faed5bSDimitry Andric // Copies following MI may have been moved as well.
10574a16efa3SDimitry Andric MBB->splice(InsertPos, MBB, Begin, End);
105863faed5bSDimitry Andric DistanceMap.erase(DI);
105963faed5bSDimitry Andric
106063faed5bSDimitry Andric // Update live variables
10614a16efa3SDimitry Andric if (LIS) {
106201095a5dSDimitry Andric LIS->handleMove(*MI);
10634a16efa3SDimitry Andric } else {
106401095a5dSDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI);
106501095a5dSDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI);
10664a16efa3SDimitry Andric }
106763faed5bSDimitry Andric
1068eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
106963faed5bSDimitry Andric return true;
107063faed5bSDimitry Andric }
107163faed5bSDimitry Andric
1072dd58ef01SDimitry Andric /// Return true if the re-scheduling will put the given instruction too close
1073dd58ef01SDimitry Andric /// to the defs of its register dependencies.
isDefTooClose(Register Reg,unsigned Dist,MachineInstr * MI)1074ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::isDefTooClose(Register Reg, unsigned Dist,
1075522600a2SDimitry Andric MachineInstr *MI) {
10765ca98fd9SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
10775ca98fd9SDimitry Andric if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
107863faed5bSDimitry Andric continue;
10795ca98fd9SDimitry Andric if (&DefMI == MI)
108063faed5bSDimitry Andric return true; // MI is defining something KillMI uses
10815ca98fd9SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
108263faed5bSDimitry Andric if (DDI == DistanceMap.end())
108363faed5bSDimitry Andric return true; // Below MI
108463faed5bSDimitry Andric unsigned DefDist = DDI->second;
108563faed5bSDimitry Andric assert(Dist > DefDist && "Visited def already?");
108601095a5dSDimitry Andric if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
108763faed5bSDimitry Andric return true;
108863faed5bSDimitry Andric }
108963faed5bSDimitry Andric return false;
109063faed5bSDimitry Andric }
109163faed5bSDimitry Andric
1092dd58ef01SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1093dd58ef01SDimitry Andric /// consider moving the kill instruction above the current two-address
1094dd58ef01SDimitry Andric /// instruction in order to eliminate the need for the copy.
rescheduleKillAboveMI(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,Register Reg)1095ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1096b60736ecSDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
1097b60736ecSDimitry Andric Register Reg) {
10984a16efa3SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find
10994a16efa3SDimitry Andric // kills efficiently.
11004a16efa3SDimitry Andric if (!LV && !LIS)
110158b69754SDimitry Andric return false;
110258b69754SDimitry Andric
110363faed5bSDimitry Andric MachineInstr *MI = &*mi;
110463faed5bSDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
110563faed5bSDimitry Andric if (DI == DistanceMap.end())
110663faed5bSDimitry Andric // Must be created from unfolded load. Don't waste time trying this.
110763faed5bSDimitry Andric return false;
110863faed5bSDimitry Andric
11095ca98fd9SDimitry Andric MachineInstr *KillMI = nullptr;
11104a16efa3SDimitry Andric if (LIS) {
11114a16efa3SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg);
11124a16efa3SDimitry Andric assert(LI.end() != LI.begin() &&
11134a16efa3SDimitry Andric "Reg should not have empty live interval.");
11144a16efa3SDimitry Andric
11154a16efa3SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
11164a16efa3SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx);
11174a16efa3SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx)
11184a16efa3SDimitry Andric return false;
11194a16efa3SDimitry Andric
11204a16efa3SDimitry Andric --I;
11214a16efa3SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end);
11224a16efa3SDimitry Andric } else {
11234a16efa3SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB);
11244a16efa3SDimitry Andric }
112558b69754SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
112663faed5bSDimitry Andric // Don't mess with copies, they may be coalesced later.
112763faed5bSDimitry Andric return false;
112863faed5bSDimitry Andric
1129b60736ecSDimitry Andric Register DstReg;
113063faed5bSDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg))
113163faed5bSDimitry Andric return false;
113263faed5bSDimitry Andric
113363faed5bSDimitry Andric bool SeenStore = true;
11345a5ac124SDimitry Andric if (!KillMI->isSafeToMove(AA, SeenStore))
113563faed5bSDimitry Andric return false;
113663faed5bSDimitry Andric
1137b60736ecSDimitry Andric SmallVector<Register, 2> Uses;
1138b60736ecSDimitry Andric SmallVector<Register, 2> Kills;
1139b60736ecSDimitry Andric SmallVector<Register, 2> Defs;
1140b60736ecSDimitry Andric SmallVector<Register, 2> LiveDefs;
1141dd58ef01SDimitry Andric for (const MachineOperand &MO : KillMI->operands()) {
114263faed5bSDimitry Andric if (!MO.isReg())
114363faed5bSDimitry Andric continue;
11441d5ae102SDimitry Andric Register MOReg = MO.getReg();
114563faed5bSDimitry Andric if (MO.isUse()) {
114663faed5bSDimitry Andric if (!MOReg)
114763faed5bSDimitry Andric continue;
1148522600a2SDimitry Andric if (isDefTooClose(MOReg, DI->second, MI))
114963faed5bSDimitry Andric return false;
1150b1c73532SDimitry Andric bool isKill = isPlainlyKilled(MO);
11514a16efa3SDimitry Andric if (MOReg == Reg && !isKill)
115258b69754SDimitry Andric return false;
1153b60736ecSDimitry Andric Uses.push_back(MOReg);
11544a16efa3SDimitry Andric if (isKill && MOReg != Reg)
1155b60736ecSDimitry Andric Kills.push_back(MOReg);
1156b60736ecSDimitry Andric } else if (MOReg.isPhysical()) {
1157b60736ecSDimitry Andric Defs.push_back(MOReg);
115863faed5bSDimitry Andric if (!MO.isDead())
1159b60736ecSDimitry Andric LiveDefs.push_back(MOReg);
116063faed5bSDimitry Andric }
116163faed5bSDimitry Andric }
116263faed5bSDimitry Andric
116363faed5bSDimitry Andric // Check if the reschedule will not break depedencies.
116463faed5bSDimitry Andric unsigned NumVisited = 0;
116501095a5dSDimitry Andric for (MachineInstr &OtherMI :
1166044eb2f6SDimitry Andric make_range(mi, MachineBasicBlock::iterator(KillMI))) {
1167344a3780SDimitry Andric // Debug or pseudo instructions cannot be counted against the limit.
1168344a3780SDimitry Andric if (OtherMI.isDebugOrPseudoInstr())
116963faed5bSDimitry Andric continue;
117063faed5bSDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
117163faed5bSDimitry Andric return false;
117263faed5bSDimitry Andric ++NumVisited;
117301095a5dSDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
117401095a5dSDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator())
117563faed5bSDimitry Andric // Don't move pass calls, etc.
117663faed5bSDimitry Andric return false;
1177b60736ecSDimitry Andric SmallVector<Register, 2> OtherDefs;
117801095a5dSDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) {
117963faed5bSDimitry Andric if (!MO.isReg())
118063faed5bSDimitry Andric continue;
11811d5ae102SDimitry Andric Register MOReg = MO.getReg();
118263faed5bSDimitry Andric if (!MOReg)
118363faed5bSDimitry Andric continue;
118463faed5bSDimitry Andric if (MO.isUse()) {
1185b1c73532SDimitry Andric if (regOverlapsSet(Defs, MOReg))
118663faed5bSDimitry Andric // Moving KillMI can clobber the physical register if the def has
118763faed5bSDimitry Andric // not been seen.
118863faed5bSDimitry Andric return false;
1189b1c73532SDimitry Andric if (regOverlapsSet(Kills, MOReg))
119063faed5bSDimitry Andric // Don't want to extend other live ranges and update kills.
119163faed5bSDimitry Andric return false;
1192b1c73532SDimitry Andric if (&OtherMI != MI && MOReg == Reg && !isPlainlyKilled(MO))
119358b69754SDimitry Andric // We can't schedule across a use of the register in question.
119458b69754SDimitry Andric return false;
119563faed5bSDimitry Andric } else {
119663faed5bSDimitry Andric OtherDefs.push_back(MOReg);
119763faed5bSDimitry Andric }
119863faed5bSDimitry Andric }
119963faed5bSDimitry Andric
120099aabd70SDimitry Andric for (Register MOReg : OtherDefs) {
1201b1c73532SDimitry Andric if (regOverlapsSet(Uses, MOReg))
120263faed5bSDimitry Andric return false;
1203b1c73532SDimitry Andric if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg))
120463faed5bSDimitry Andric return false;
120563faed5bSDimitry Andric // Physical register def is seen.
1206b1c73532SDimitry Andric llvm::erase(Defs, MOReg);
120763faed5bSDimitry Andric }
120863faed5bSDimitry Andric }
120963faed5bSDimitry Andric
121063faed5bSDimitry Andric // Move the old kill above MI, don't forget to move debug info as well.
121163faed5bSDimitry Andric MachineBasicBlock::iterator InsertPos = mi;
1212eb11fae6SDimitry Andric while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr())
121363faed5bSDimitry Andric --InsertPos;
121463faed5bSDimitry Andric MachineBasicBlock::iterator From = KillMI;
12155ca98fd9SDimitry Andric MachineBasicBlock::iterator To = std::next(From);
1216eb11fae6SDimitry Andric while (std::prev(From)->isDebugInstr())
121763faed5bSDimitry Andric --From;
121863faed5bSDimitry Andric MBB->splice(InsertPos, MBB, From, To);
121963faed5bSDimitry Andric
12205ca98fd9SDimitry Andric nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
122163faed5bSDimitry Andric DistanceMap.erase(DI);
122263faed5bSDimitry Andric
122363faed5bSDimitry Andric // Update live variables
12244a16efa3SDimitry Andric if (LIS) {
122501095a5dSDimitry Andric LIS->handleMove(*KillMI);
12264a16efa3SDimitry Andric } else {
122701095a5dSDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI);
122801095a5dSDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI);
12294a16efa3SDimitry Andric }
123058b69754SDimitry Andric
1231eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
123263faed5bSDimitry Andric return true;
123363faed5bSDimitry Andric }
123463faed5bSDimitry Andric
1235dd58ef01SDimitry Andric /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1236dd58ef01SDimitry Andric /// given machine instruction to improve opportunities for coalescing and
1237dd58ef01SDimitry Andric /// elimination of a register to register copy.
1238dd58ef01SDimitry Andric ///
1239dd58ef01SDimitry Andric /// 'DstOpIdx' specifies the index of MI def operand.
1240dd58ef01SDimitry Andric /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1241dd58ef01SDimitry Andric /// operand is killed by the given instruction.
1242dd58ef01SDimitry Andric /// The 'Dist' arguments provides the distance of MI from the start of the
1243dd58ef01SDimitry Andric /// current basic block and it is used to determine if it is profitable
1244dd58ef01SDimitry Andric /// to commute operands in the instruction.
1245dd58ef01SDimitry Andric ///
1246dd58ef01SDimitry Andric /// Returns true if the transformation happened. Otherwise, returns false.
tryInstructionCommute(MachineInstr * MI,unsigned DstOpIdx,unsigned BaseOpIdx,bool BaseOpKilled,unsigned Dist)1247ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *MI,
1248dd58ef01SDimitry Andric unsigned DstOpIdx,
1249dd58ef01SDimitry Andric unsigned BaseOpIdx,
1250dd58ef01SDimitry Andric bool BaseOpKilled,
1251dd58ef01SDimitry Andric unsigned Dist) {
1252b915e9e0SDimitry Andric if (!MI->isCommutable())
1253b915e9e0SDimitry Andric return false;
1254b915e9e0SDimitry Andric
1255eb11fae6SDimitry Andric bool MadeChange = false;
12561d5ae102SDimitry Andric Register DstOpReg = MI->getOperand(DstOpIdx).getReg();
12571d5ae102SDimitry Andric Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1258dd58ef01SDimitry Andric unsigned OpsNum = MI->getDesc().getNumOperands();
1259dd58ef01SDimitry Andric unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1260dd58ef01SDimitry Andric for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1261dd58ef01SDimitry Andric // The call of findCommutedOpIndices below only checks if BaseOpIdx
1262dd58ef01SDimitry Andric // and OtherOpIdx are commutable, it does not really search for
1263dd58ef01SDimitry Andric // other commutable operands and does not change the values of passed
1264dd58ef01SDimitry Andric // variables.
1265b915e9e0SDimitry Andric if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
126601095a5dSDimitry Andric !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1267dd58ef01SDimitry Andric continue;
1268dd58ef01SDimitry Andric
12691d5ae102SDimitry Andric Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1270dd58ef01SDimitry Andric bool AggressiveCommute = false;
1271dd58ef01SDimitry Andric
1272dd58ef01SDimitry Andric // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1273dd58ef01SDimitry Andric // operands. This makes the live ranges of DstOp and OtherOp joinable.
1274b1c73532SDimitry Andric bool OtherOpKilled = isKilled(*MI, OtherOpReg, false);
1275eb11fae6SDimitry Andric bool DoCommute = !BaseOpKilled && OtherOpKilled;
1276dd58ef01SDimitry Andric
1277dd58ef01SDimitry Andric if (!DoCommute &&
1278dd58ef01SDimitry Andric isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1279dd58ef01SDimitry Andric DoCommute = true;
1280dd58ef01SDimitry Andric AggressiveCommute = true;
1281dd58ef01SDimitry Andric }
1282dd58ef01SDimitry Andric
1283dd58ef01SDimitry Andric // If it's profitable to commute, try to do so.
1284b915e9e0SDimitry Andric if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1285b915e9e0SDimitry Andric Dist)) {
1286eb11fae6SDimitry Andric MadeChange = true;
1287dd58ef01SDimitry Andric ++NumCommuted;
1288cfca06d7SDimitry Andric if (AggressiveCommute)
1289dd58ef01SDimitry Andric ++NumAggrCommuted;
1290cfca06d7SDimitry Andric
1291eb11fae6SDimitry Andric // There might be more than two commutable operands, update BaseOp and
1292eb11fae6SDimitry Andric // continue scanning.
1293e6d15924SDimitry Andric // FIXME: This assumes that the new instruction's operands are in the
1294e6d15924SDimitry Andric // same positions and were simply swapped.
1295eb11fae6SDimitry Andric BaseOpReg = OtherOpReg;
1296eb11fae6SDimitry Andric BaseOpKilled = OtherOpKilled;
1297e6d15924SDimitry Andric // Resamples OpsNum in case the number of operands was reduced. This
1298e6d15924SDimitry Andric // happens with X86.
1299e6d15924SDimitry Andric OpsNum = MI->getDesc().getNumOperands();
1300dd58ef01SDimitry Andric }
1301dd58ef01SDimitry Andric }
1302eb11fae6SDimitry Andric return MadeChange;
1303dd58ef01SDimitry Andric }
1304dd58ef01SDimitry Andric
1305dd58ef01SDimitry Andric /// For the case where an instruction has a single pair of tied register
1306dd58ef01SDimitry Andric /// operands, attempt some transformations that may either eliminate the tied
1307dd58ef01SDimitry Andric /// operands or improve the opportunities for coalescing away the register copy.
1308dd58ef01SDimitry Andric /// Returns true if no copy needs to be inserted to untie mi's operands
1309dd58ef01SDimitry Andric /// (either because they were untied, or because mi was rescheduled, and will
1310dd58ef01SDimitry Andric /// be visited again later). If the shouldOnlyCommute flag is true, only
1311dd58ef01SDimitry Andric /// instruction commutation is attempted.
tryInstructionTransform(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,unsigned SrcIdx,unsigned DstIdx,unsigned & Dist,bool shouldOnlyCommute)1312ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::tryInstructionTransform(
1313ac9a064cSDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi,
1314ac9a064cSDimitry Andric unsigned SrcIdx, unsigned DstIdx, unsigned &Dist, bool shouldOnlyCommute) {
1315b1c73532SDimitry Andric if (OptLevel == CodeGenOptLevel::None)
131663faed5bSDimitry Andric return false;
131763faed5bSDimitry Andric
131863faed5bSDimitry Andric MachineInstr &MI = *mi;
13191d5ae102SDimitry Andric Register regA = MI.getOperand(DstIdx).getReg();
13201d5ae102SDimitry Andric Register regB = MI.getOperand(SrcIdx).getReg();
132159850d08SRoman Divacky
1322b60736ecSDimitry Andric assert(regB.isVirtual() && "cannot make instruction into two-address form");
1323b1c73532SDimitry Andric bool regBKilled = isKilled(MI, regB, true);
132458b69754SDimitry Andric
1325b60736ecSDimitry Andric if (regA.isVirtual())
1326522600a2SDimitry Andric scanUses(regA);
132759850d08SRoman Divacky
1328dd58ef01SDimitry Andric bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
132959850d08SRoman Divacky
13301a82d4c0SDimitry Andric // If the instruction is convertible to 3 Addr, instead
1331706b4fc4SDimitry Andric // of returning try 3 Addr transformation aggressively and
13321a82d4c0SDimitry Andric // use this variable to check later. Because it might be better.
13331a82d4c0SDimitry Andric // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
13341a82d4c0SDimitry Andric // instead of the following code.
13351a82d4c0SDimitry Andric // addl %esi, %edi
13361a82d4c0SDimitry Andric // movl %edi, %eax
13371a82d4c0SDimitry Andric // ret
1338dd58ef01SDimitry Andric if (Commuted && !MI.isConvertibleTo3Addr())
133959850d08SRoman Divacky return false;
134059850d08SRoman Divacky
13414a16efa3SDimitry Andric if (shouldOnlyCommute)
13424a16efa3SDimitry Andric return false;
13434a16efa3SDimitry Andric
134463faed5bSDimitry Andric // If there is one more use of regB later in the same MBB, consider
134563faed5bSDimitry Andric // re-schedule this MI below it.
1346ee8648bdSDimitry Andric if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
134763faed5bSDimitry Andric ++NumReSchedDowns;
134863faed5bSDimitry Andric return true;
134963faed5bSDimitry Andric }
135063faed5bSDimitry Andric
1351dd58ef01SDimitry Andric // If we commuted, regB may have changed so we should re-sample it to avoid
1352dd58ef01SDimitry Andric // confusing the three address conversion below.
1353dd58ef01SDimitry Andric if (Commuted) {
1354dd58ef01SDimitry Andric regB = MI.getOperand(SrcIdx).getReg();
1355b1c73532SDimitry Andric regBKilled = isKilled(MI, regB, true);
1356dd58ef01SDimitry Andric }
1357dd58ef01SDimitry Andric
135863faed5bSDimitry Andric if (MI.isConvertibleTo3Addr()) {
135959850d08SRoman Divacky // This instruction is potentially convertible to a true
136059850d08SRoman Divacky // three-address instruction. Check if it is profitable.
13616b943ff3SDimitry Andric if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
136259850d08SRoman Divacky // Try to convert it.
1363522600a2SDimitry Andric if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
136459850d08SRoman Divacky ++NumConvertedTo3Addr;
136559850d08SRoman Divacky return true; // Done with this instruction.
136659850d08SRoman Divacky }
136759850d08SRoman Divacky }
136859850d08SRoman Divacky }
136966e41e3cSRoman Divacky
13701a82d4c0SDimitry Andric // Return if it is commuted but 3 addr conversion is failed.
1371ee8648bdSDimitry Andric if (Commuted)
13721a82d4c0SDimitry Andric return false;
13731a82d4c0SDimitry Andric
137463faed5bSDimitry Andric // If there is one more use of regB later in the same MBB, consider
137563faed5bSDimitry Andric // re-schedule it before this MI if it's legal.
137659d6cff9SDimitry Andric if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
137763faed5bSDimitry Andric ++NumReSchedUps;
137863faed5bSDimitry Andric return true;
137963faed5bSDimitry Andric }
138063faed5bSDimitry Andric
138166e41e3cSRoman Divacky // If this is an instruction with a load folded into it, try unfolding
138266e41e3cSRoman Divacky // the load, e.g. avoid this:
138366e41e3cSRoman Divacky // movq %rdx, %rcx
138466e41e3cSRoman Divacky // addq (%rax), %rcx
138566e41e3cSRoman Divacky // in favor of this:
138666e41e3cSRoman Divacky // movq (%rax), %rcx
138766e41e3cSRoman Divacky // addq %rdx, %rcx
138866e41e3cSRoman Divacky // because it's preferable to schedule a load than a register copy.
138963faed5bSDimitry Andric if (MI.mayLoad() && !regBKilled) {
139066e41e3cSRoman Divacky // Determine if a load can be unfolded.
139166e41e3cSRoman Divacky unsigned LoadRegIndex;
139266e41e3cSRoman Divacky unsigned NewOpc =
139363faed5bSDimitry Andric TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
139466e41e3cSRoman Divacky /*UnfoldLoad=*/true,
139566e41e3cSRoman Divacky /*UnfoldStore=*/false,
139666e41e3cSRoman Divacky &LoadRegIndex);
139766e41e3cSRoman Divacky if (NewOpc != 0) {
1398411bd29eSDimitry Andric const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1399411bd29eSDimitry Andric if (UnfoldMCID.getNumDefs() == 1) {
140066e41e3cSRoman Divacky // Unfold the load.
1401eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
140266e41e3cSRoman Divacky const TargetRegisterClass *RC =
140358b69754SDimitry Andric TRI->getAllocatableClass(
140458b69754SDimitry Andric TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
14051d5ae102SDimitry Andric Register Reg = MRI->createVirtualRegister(RC);
140666e41e3cSRoman Divacky SmallVector<MachineInstr *, 2> NewMIs;
140701095a5dSDimitry Andric if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
140801095a5dSDimitry Andric /*UnfoldLoad=*/true,
140901095a5dSDimitry Andric /*UnfoldStore=*/false, NewMIs)) {
1410eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
141166e41e3cSRoman Divacky return false;
141266e41e3cSRoman Divacky }
141366e41e3cSRoman Divacky assert(NewMIs.size() == 2 &&
141466e41e3cSRoman Divacky "Unfolded a load into multiple instructions!");
141566e41e3cSRoman Divacky // The load was previously folded, so this is the only use.
141666e41e3cSRoman Divacky NewMIs[1]->addRegisterKilled(Reg, TRI);
141766e41e3cSRoman Divacky
141866e41e3cSRoman Divacky // Tentatively insert the instructions into the block so that they
141966e41e3cSRoman Divacky // look "normal" to the transformation logic.
1420522600a2SDimitry Andric MBB->insert(mi, NewMIs[0]);
1421522600a2SDimitry Andric MBB->insert(mi, NewMIs[1]);
1422c0981da4SDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[0], Dist++));
1423c0981da4SDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[1], Dist));
142466e41e3cSRoman Divacky
1425eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
142666e41e3cSRoman Divacky << "2addr: NEW INST: " << *NewMIs[1]);
142766e41e3cSRoman Divacky
142866e41e3cSRoman Divacky // Transform the instruction, now that it no longer has a load.
1429ac9a064cSDimitry Andric unsigned NewDstIdx =
1430ac9a064cSDimitry Andric NewMIs[1]->findRegisterDefOperandIdx(regA, /*TRI=*/nullptr);
1431ac9a064cSDimitry Andric unsigned NewSrcIdx =
1432ac9a064cSDimitry Andric NewMIs[1]->findRegisterUseOperandIdx(regB, /*TRI=*/nullptr);
143366e41e3cSRoman Divacky MachineBasicBlock::iterator NewMI = NewMIs[1];
14344a16efa3SDimitry Andric bool TransformResult =
14354a16efa3SDimitry Andric tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
14364a16efa3SDimitry Andric (void)TransformResult;
14374a16efa3SDimitry Andric assert(!TransformResult &&
14384a16efa3SDimitry Andric "tryInstructionTransform() should return false.");
14394a16efa3SDimitry Andric if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
144066e41e3cSRoman Divacky // Success, or at least we made an improvement. Keep the unfolded
144166e41e3cSRoman Divacky // instructions and discard the original.
144266e41e3cSRoman Divacky if (LV) {
1443f65dcba8SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1444b60736ecSDimitry Andric if (MO.isReg() && MO.getReg().isVirtual()) {
144566e41e3cSRoman Divacky if (MO.isUse()) {
144666e41e3cSRoman Divacky if (MO.isKill()) {
1447ac9a064cSDimitry Andric if (NewMIs[0]->killsRegister(MO.getReg(), /*TRI=*/nullptr))
144801095a5dSDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
144966e41e3cSRoman Divacky else {
1450ac9a064cSDimitry Andric assert(NewMIs[1]->killsRegister(MO.getReg(),
1451ac9a064cSDimitry Andric /*TRI=*/nullptr) &&
145266e41e3cSRoman Divacky "Kill missing after load unfold!");
145301095a5dSDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
145466e41e3cSRoman Divacky }
145566e41e3cSRoman Divacky }
145601095a5dSDimitry Andric } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1457ac9a064cSDimitry Andric if (NewMIs[1]->registerDefIsDead(MO.getReg(),
1458ac9a064cSDimitry Andric /*TRI=*/nullptr))
145901095a5dSDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
146066e41e3cSRoman Divacky else {
1461ac9a064cSDimitry Andric assert(NewMIs[0]->registerDefIsDead(MO.getReg(),
1462ac9a064cSDimitry Andric /*TRI=*/nullptr) &&
146366e41e3cSRoman Divacky "Dead flag missing after load unfold!");
146401095a5dSDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
146566e41e3cSRoman Divacky }
146666e41e3cSRoman Divacky }
146766e41e3cSRoman Divacky }
146866e41e3cSRoman Divacky }
146901095a5dSDimitry Andric LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
147066e41e3cSRoman Divacky }
14714a16efa3SDimitry Andric
1472cfca06d7SDimitry Andric SmallVector<Register, 4> OrigRegs;
14734a16efa3SDimitry Andric if (LIS) {
1474dd58ef01SDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1475dd58ef01SDimitry Andric if (MO.isReg())
1476dd58ef01SDimitry Andric OrigRegs.push_back(MO.getReg());
14774a16efa3SDimitry Andric }
1478c0981da4SDimitry Andric
1479c0981da4SDimitry Andric LIS->RemoveMachineInstrFromMaps(MI);
14804a16efa3SDimitry Andric }
14814a16efa3SDimitry Andric
148263faed5bSDimitry Andric MI.eraseFromParent();
1483c0981da4SDimitry Andric DistanceMap.erase(&MI);
14844a16efa3SDimitry Andric
14854a16efa3SDimitry Andric // Update LiveIntervals.
14864a16efa3SDimitry Andric if (LIS) {
14874a16efa3SDimitry Andric MachineBasicBlock::iterator Begin(NewMIs[0]);
14884a16efa3SDimitry Andric MachineBasicBlock::iterator End(NewMIs[1]);
14894a16efa3SDimitry Andric LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
14904a16efa3SDimitry Andric }
14914a16efa3SDimitry Andric
149266e41e3cSRoman Divacky mi = NewMIs[1];
149366e41e3cSRoman Divacky } else {
149466e41e3cSRoman Divacky // Transforming didn't eliminate the tie and didn't lead to an
149566e41e3cSRoman Divacky // improvement. Clean up the unfolded instructions and keep the
149666e41e3cSRoman Divacky // original.
1497eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
149866e41e3cSRoman Divacky NewMIs[0]->eraseFromParent();
149966e41e3cSRoman Divacky NewMIs[1]->eraseFromParent();
1500c0981da4SDimitry Andric DistanceMap.erase(NewMIs[0]);
1501c0981da4SDimitry Andric DistanceMap.erase(NewMIs[1]);
1502c0981da4SDimitry Andric Dist--;
150366e41e3cSRoman Divacky }
150466e41e3cSRoman Divacky }
150566e41e3cSRoman Divacky }
150666e41e3cSRoman Divacky }
150766e41e3cSRoman Divacky
150859850d08SRoman Divacky return false;
150959850d08SRoman Divacky }
151059850d08SRoman Divacky
151158b69754SDimitry Andric // Collect tied operands of MI that need to be handled.
151258b69754SDimitry Andric // Rewrite trivial cases immediately.
151358b69754SDimitry Andric // Return true if any tied operands where found, including the trivial ones.
collectTiedOperands(MachineInstr * MI,TiedOperandMap & TiedOperands)1514ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::collectTiedOperands(
1515ac9a064cSDimitry Andric MachineInstr *MI, TiedOperandMap &TiedOperands) {
151658b69754SDimitry Andric bool AnyOps = false;
1517522600a2SDimitry Andric unsigned NumOps = MI->getNumOperands();
151858b69754SDimitry Andric
151958b69754SDimitry Andric for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
152058b69754SDimitry Andric unsigned DstIdx = 0;
152158b69754SDimitry Andric if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
152258b69754SDimitry Andric continue;
152358b69754SDimitry Andric AnyOps = true;
152458b69754SDimitry Andric MachineOperand &SrcMO = MI->getOperand(SrcIdx);
152558b69754SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx);
15261d5ae102SDimitry Andric Register SrcReg = SrcMO.getReg();
15271d5ae102SDimitry Andric Register DstReg = DstMO.getReg();
152858b69754SDimitry Andric // Tied constraint already satisfied?
152958b69754SDimitry Andric if (SrcReg == DstReg)
153058b69754SDimitry Andric continue;
153158b69754SDimitry Andric
153258b69754SDimitry Andric assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
153358b69754SDimitry Andric
1534044eb2f6SDimitry Andric // Deal with undef uses immediately - simply rewrite the src operand.
15355ca98fd9SDimitry Andric if (SrcMO.isUndef() && !DstMO.getSubReg()) {
153658b69754SDimitry Andric // Constrain the DstReg register class if required.
1537c0981da4SDimitry Andric if (DstReg.isVirtual()) {
1538c0981da4SDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
153958b69754SDimitry Andric MRI->constrainRegClass(DstReg, RC);
1540c0981da4SDimitry Andric }
154158b69754SDimitry Andric SrcMO.setReg(DstReg);
15425ca98fd9SDimitry Andric SrcMO.setSubReg(0);
1543eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
154458b69754SDimitry Andric continue;
154558b69754SDimitry Andric }
154658b69754SDimitry Andric TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
154758b69754SDimitry Andric }
154858b69754SDimitry Andric return AnyOps;
154958b69754SDimitry Andric }
155058b69754SDimitry Andric
155158b69754SDimitry Andric // Process a list of tied MI operands that all use the same source register.
155258b69754SDimitry Andric // The tied pairs are of the form (SrcIdx, DstIdx).
processTiedPairs(MachineInstr * MI,TiedPairList & TiedPairs,unsigned & Dist)1553ac9a064cSDimitry Andric void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *MI,
155458b69754SDimitry Andric TiedPairList &TiedPairs,
155558b69754SDimitry Andric unsigned &Dist) {
15564b4fe385SDimitry Andric bool IsEarlyClobber = llvm::any_of(TiedPairs, [MI](auto const &TP) {
1557344a3780SDimitry Andric return MI->getOperand(TP.second).isEarlyClobber();
15584b4fe385SDimitry Andric });
15594a16efa3SDimitry Andric
156058b69754SDimitry Andric bool RemovedKillFlag = false;
156158b69754SDimitry Andric bool AllUsesCopied = true;
156258b69754SDimitry Andric unsigned LastCopiedReg = 0;
15634a16efa3SDimitry Andric SlotIndex LastCopyIdx;
1564b60736ecSDimitry Andric Register RegB = 0;
15655ca98fd9SDimitry Andric unsigned SubRegB = 0;
1566344a3780SDimitry Andric for (auto &TP : TiedPairs) {
1567344a3780SDimitry Andric unsigned SrcIdx = TP.first;
1568344a3780SDimitry Andric unsigned DstIdx = TP.second;
156958b69754SDimitry Andric
157058b69754SDimitry Andric const MachineOperand &DstMO = MI->getOperand(DstIdx);
15711d5ae102SDimitry Andric Register RegA = DstMO.getReg();
157258b69754SDimitry Andric
157358b69754SDimitry Andric // Grab RegB from the instruction because it may have changed if the
157458b69754SDimitry Andric // instruction was commuted.
157558b69754SDimitry Andric RegB = MI->getOperand(SrcIdx).getReg();
15765ca98fd9SDimitry Andric SubRegB = MI->getOperand(SrcIdx).getSubReg();
157758b69754SDimitry Andric
157858b69754SDimitry Andric if (RegA == RegB) {
157958b69754SDimitry Andric // The register is tied to multiple destinations (or else we would
158058b69754SDimitry Andric // not have continued this far), but this use of the register
158158b69754SDimitry Andric // already matches the tied destination. Leave it.
158258b69754SDimitry Andric AllUsesCopied = false;
158358b69754SDimitry Andric continue;
158458b69754SDimitry Andric }
158558b69754SDimitry Andric LastCopiedReg = RegA;
158658b69754SDimitry Andric
1587b60736ecSDimitry Andric assert(RegB.isVirtual() && "cannot make instruction into two-address form");
158858b69754SDimitry Andric
158958b69754SDimitry Andric #ifndef NDEBUG
159058b69754SDimitry Andric // First, verify that we don't have a use of "a" in the instruction
159158b69754SDimitry Andric // (a = b + a for example) because our transformation will not
159258b69754SDimitry Andric // work. This should never occur because we are in SSA form.
159358b69754SDimitry Andric for (unsigned i = 0; i != MI->getNumOperands(); ++i)
159458b69754SDimitry Andric assert(i == DstIdx ||
159558b69754SDimitry Andric !MI->getOperand(i).isReg() ||
159658b69754SDimitry Andric MI->getOperand(i).getReg() != RegA);
159758b69754SDimitry Andric #endif
159858b69754SDimitry Andric
159958b69754SDimitry Andric // Emit a copy.
16005ca98fd9SDimitry Andric MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
16015ca98fd9SDimitry Andric TII->get(TargetOpcode::COPY), RegA);
16025ca98fd9SDimitry Andric // If this operand is folding a truncation, the truncation now moves to the
16035ca98fd9SDimitry Andric // copy so that the register classes remain valid for the operands.
16045ca98fd9SDimitry Andric MIB.addReg(RegB, 0, SubRegB);
16055ca98fd9SDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(RegB);
16065ca98fd9SDimitry Andric if (SubRegB) {
1607b60736ecSDimitry Andric if (RegA.isVirtual()) {
16085ca98fd9SDimitry Andric assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
16095ca98fd9SDimitry Andric SubRegB) &&
16105ca98fd9SDimitry Andric "tied subregister must be a truncation");
16115ca98fd9SDimitry Andric // The superreg class will not be used to constrain the subreg class.
16125ca98fd9SDimitry Andric RC = nullptr;
16131d5ae102SDimitry Andric } else {
16145ca98fd9SDimitry Andric assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
16155ca98fd9SDimitry Andric && "tied subregister must be a truncation");
16165ca98fd9SDimitry Andric }
16175ca98fd9SDimitry Andric }
161858b69754SDimitry Andric
161958b69754SDimitry Andric // Update DistanceMap.
162058b69754SDimitry Andric MachineBasicBlock::iterator PrevMI = MI;
162158b69754SDimitry Andric --PrevMI;
162201095a5dSDimitry Andric DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
162358b69754SDimitry Andric DistanceMap[MI] = ++Dist;
162458b69754SDimitry Andric
16254a16efa3SDimitry Andric if (LIS) {
162601095a5dSDimitry Andric LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
16274a16efa3SDimitry Andric
1628c0981da4SDimitry Andric SlotIndex endIdx =
1629c0981da4SDimitry Andric LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1630b60736ecSDimitry Andric if (RegA.isVirtual()) {
16314a16efa3SDimitry Andric LiveInterval &LI = LIS->getInterval(RegA);
16324a16efa3SDimitry Andric VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1633c0981da4SDimitry Andric LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1634c0981da4SDimitry Andric for (auto &S : LI.subranges()) {
1635c0981da4SDimitry Andric VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1636c0981da4SDimitry Andric S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1637c0981da4SDimitry Andric }
1638c0981da4SDimitry Andric } else {
16397fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(RegA)) {
16407fa27ce4SDimitry Andric if (LiveRange *LR = LIS->getCachedRegUnit(Unit)) {
1641c0981da4SDimitry Andric VNInfo *VNI =
1642c0981da4SDimitry Andric LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1643c0981da4SDimitry Andric LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1644c0981da4SDimitry Andric }
1645c0981da4SDimitry Andric }
16464a16efa3SDimitry Andric }
16474a16efa3SDimitry Andric }
164858b69754SDimitry Andric
1649eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
165058b69754SDimitry Andric
165158b69754SDimitry Andric MachineOperand &MO = MI->getOperand(SrcIdx);
165258b69754SDimitry Andric assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
165358b69754SDimitry Andric "inconsistent operand info for 2-reg pass");
1654b1c73532SDimitry Andric if (isPlainlyKilled(MO)) {
165558b69754SDimitry Andric MO.setIsKill(false);
165658b69754SDimitry Andric RemovedKillFlag = true;
165758b69754SDimitry Andric }
165858b69754SDimitry Andric
165958b69754SDimitry Andric // Make sure regA is a legal regclass for the SrcIdx operand.
1660b60736ecSDimitry Andric if (RegA.isVirtual() && RegB.isVirtual())
16615ca98fd9SDimitry Andric MRI->constrainRegClass(RegA, RC);
166258b69754SDimitry Andric MO.setReg(RegA);
16635ca98fd9SDimitry Andric // The getMatchingSuper asserts guarantee that the register class projected
16645ca98fd9SDimitry Andric // by SubRegB is compatible with RegA with no subregister. So regardless of
16655ca98fd9SDimitry Andric // whether the dest oper writes a subreg, the source oper should not.
16665ca98fd9SDimitry Andric MO.setSubReg(0);
166758b69754SDimitry Andric }
166858b69754SDimitry Andric
166958b69754SDimitry Andric if (AllUsesCopied) {
1670c0981da4SDimitry Andric LaneBitmask RemainingUses = LaneBitmask::getNone();
167158b69754SDimitry Andric // Replace other (un-tied) uses of regB with LastCopiedReg.
16727fa27ce4SDimitry Andric for (MachineOperand &MO : MI->all_uses()) {
16737fa27ce4SDimitry Andric if (MO.getReg() == RegB) {
1674c0981da4SDimitry Andric if (MO.getSubReg() == SubRegB && !IsEarlyClobber) {
1675b1c73532SDimitry Andric if (isPlainlyKilled(MO)) {
167658b69754SDimitry Andric MO.setIsKill(false);
167758b69754SDimitry Andric RemovedKillFlag = true;
167858b69754SDimitry Andric }
167958b69754SDimitry Andric MO.setReg(LastCopiedReg);
1680d8e91e46SDimitry Andric MO.setSubReg(0);
1681d8e91e46SDimitry Andric } else {
1682c0981da4SDimitry Andric RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg());
168358b69754SDimitry Andric }
168458b69754SDimitry Andric }
168558b69754SDimitry Andric }
168658b69754SDimitry Andric
168758b69754SDimitry Andric // Update live variables for regB.
1688c0981da4SDimitry Andric if (RemovedKillFlag && RemainingUses.none() && LV &&
1689c0981da4SDimitry Andric LV->getVarInfo(RegB).removeKill(*MI)) {
169058b69754SDimitry Andric MachineBasicBlock::iterator PrevMI = MI;
169158b69754SDimitry Andric --PrevMI;
169201095a5dSDimitry Andric LV->addVirtualRegisterKilled(RegB, *PrevMI);
169358b69754SDimitry Andric }
169458b69754SDimitry Andric
1695c0981da4SDimitry Andric if (RemovedKillFlag && RemainingUses.none())
1696c0981da4SDimitry Andric SrcRegMap[LastCopiedReg] = RegB;
1697c0981da4SDimitry Andric
16984a16efa3SDimitry Andric // Update LiveIntervals.
16994a16efa3SDimitry Andric if (LIS) {
1700c0981da4SDimitry Andric SlotIndex UseIdx = LIS->getInstructionIndex(*MI);
1701c0981da4SDimitry Andric auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) {
1702c0981da4SDimitry Andric LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx);
1703c0981da4SDimitry Andric if (!S)
1704c0981da4SDimitry Andric return true;
1705c0981da4SDimitry Andric if ((LaneMask & RemainingUses).any())
1706c0981da4SDimitry Andric return false;
1707c0981da4SDimitry Andric if (S->end.getBaseIndex() != UseIdx)
1708c0981da4SDimitry Andric return false;
1709c0981da4SDimitry Andric S->end = LastCopyIdx;
1710c0981da4SDimitry Andric return true;
1711c0981da4SDimitry Andric };
17124a16efa3SDimitry Andric
1713c0981da4SDimitry Andric LiveInterval &LI = LIS->getInterval(RegB);
1714c0981da4SDimitry Andric bool ShrinkLI = true;
1715c0981da4SDimitry Andric for (auto &S : LI.subranges())
1716c0981da4SDimitry Andric ShrinkLI &= Shrink(S, S.LaneMask);
1717c0981da4SDimitry Andric if (ShrinkLI)
1718c0981da4SDimitry Andric Shrink(LI, LaneBitmask::getAll());
17194a16efa3SDimitry Andric }
172058b69754SDimitry Andric } else if (RemovedKillFlag) {
172158b69754SDimitry Andric // Some tied uses of regB matched their destination registers, so
172258b69754SDimitry Andric // regB is still used in this instruction, but a kill flag was
172358b69754SDimitry Andric // removed from a different tied use of regB, so now we need to add
172458b69754SDimitry Andric // a kill flag to one of the remaining uses of regB.
17257fa27ce4SDimitry Andric for (MachineOperand &MO : MI->all_uses()) {
17267fa27ce4SDimitry Andric if (MO.getReg() == RegB) {
172758b69754SDimitry Andric MO.setIsKill(true);
172858b69754SDimitry Andric break;
172958b69754SDimitry Andric }
173058b69754SDimitry Andric }
173158b69754SDimitry Andric }
173258b69754SDimitry Andric }
173358b69754SDimitry Andric
1734145449b1SDimitry Andric // For every tied operand pair this function transforms statepoint from
1735145449b1SDimitry Andric // RegA = STATEPOINT ... RegB(tied-def N)
1736145449b1SDimitry Andric // to
1737145449b1SDimitry Andric // RegB = STATEPOINT ... RegB(tied-def N)
1738145449b1SDimitry Andric // and replaces all uses of RegA with RegB.
1739145449b1SDimitry Andric // No extra COPY instruction is necessary because tied use is killed at
1740145449b1SDimitry Andric // STATEPOINT.
processStatepoint(MachineInstr * MI,TiedOperandMap & TiedOperands)1741ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::processStatepoint(
1742145449b1SDimitry Andric MachineInstr *MI, TiedOperandMap &TiedOperands) {
1743145449b1SDimitry Andric
1744145449b1SDimitry Andric bool NeedCopy = false;
1745145449b1SDimitry Andric for (auto &TO : TiedOperands) {
1746145449b1SDimitry Andric Register RegB = TO.first;
1747145449b1SDimitry Andric if (TO.second.size() != 1) {
1748145449b1SDimitry Andric NeedCopy = true;
1749145449b1SDimitry Andric continue;
1750145449b1SDimitry Andric }
1751145449b1SDimitry Andric
1752145449b1SDimitry Andric unsigned SrcIdx = TO.second[0].first;
1753145449b1SDimitry Andric unsigned DstIdx = TO.second[0].second;
1754145449b1SDimitry Andric
1755145449b1SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx);
1756145449b1SDimitry Andric Register RegA = DstMO.getReg();
1757145449b1SDimitry Andric
1758145449b1SDimitry Andric assert(RegB == MI->getOperand(SrcIdx).getReg());
1759145449b1SDimitry Andric
1760145449b1SDimitry Andric if (RegA == RegB)
1761145449b1SDimitry Andric continue;
1762145449b1SDimitry Andric
1763e3b55780SDimitry Andric // CodeGenPrepare can sink pointer compare past statepoint, which
1764e3b55780SDimitry Andric // breaks assumption that statepoint kills tied-use register when
1765e3b55780SDimitry Andric // in SSA form (see note in IR/SafepointIRVerifier.cpp). Fall back
1766e3b55780SDimitry Andric // to generic tied register handling to avoid assertion failures.
1767e3b55780SDimitry Andric // TODO: Recompute LIS/LV information for new range here.
1768e3b55780SDimitry Andric if (LIS) {
1769e3b55780SDimitry Andric const auto &UseLI = LIS->getInterval(RegB);
1770e3b55780SDimitry Andric const auto &DefLI = LIS->getInterval(RegA);
1771e3b55780SDimitry Andric if (DefLI.overlaps(UseLI)) {
1772e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "LIS: " << printReg(RegB, TRI, 0)
1773e3b55780SDimitry Andric << " UseLI overlaps with DefLI\n");
1774e3b55780SDimitry Andric NeedCopy = true;
1775e3b55780SDimitry Andric continue;
1776e3b55780SDimitry Andric }
1777e3b55780SDimitry Andric } else if (LV && LV->getVarInfo(RegB).findKill(MI->getParent()) != MI) {
1778e3b55780SDimitry Andric // Note that MachineOperand::isKill does not work here, because it
1779e3b55780SDimitry Andric // is set only on first register use in instruction and for statepoint
1780e3b55780SDimitry Andric // tied-use register will usually be found in preceeding deopt bundle.
1781e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "LV: " << printReg(RegB, TRI, 0)
1782e3b55780SDimitry Andric << " not killed by statepoint\n");
1783e3b55780SDimitry Andric NeedCopy = true;
1784e3b55780SDimitry Andric continue;
1785e3b55780SDimitry Andric }
1786e3b55780SDimitry Andric
1787e3b55780SDimitry Andric if (!MRI->constrainRegClass(RegB, MRI->getRegClass(RegA))) {
1788e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "MRI: couldn't constrain" << printReg(RegB, TRI, 0)
1789e3b55780SDimitry Andric << " to register class of " << printReg(RegA, TRI, 0)
1790e3b55780SDimitry Andric << '\n');
1791e3b55780SDimitry Andric NeedCopy = true;
1792e3b55780SDimitry Andric continue;
1793e3b55780SDimitry Andric }
1794145449b1SDimitry Andric MRI->replaceRegWith(RegA, RegB);
1795145449b1SDimitry Andric
1796145449b1SDimitry Andric if (LIS) {
1797145449b1SDimitry Andric VNInfo::Allocator &A = LIS->getVNInfoAllocator();
1798145449b1SDimitry Andric LiveInterval &LI = LIS->getInterval(RegB);
1799e3b55780SDimitry Andric LiveInterval &Other = LIS->getInterval(RegA);
1800e3b55780SDimitry Andric SmallVector<VNInfo *> NewVNIs;
1801e3b55780SDimitry Andric for (const VNInfo *VNI : Other.valnos) {
1802e3b55780SDimitry Andric assert(VNI->id == NewVNIs.size() && "assumed");
1803e3b55780SDimitry Andric NewVNIs.push_back(LI.createValueCopy(VNI, A));
1804e3b55780SDimitry Andric }
1805e3b55780SDimitry Andric for (auto &S : Other) {
1806e3b55780SDimitry Andric VNInfo *VNI = NewVNIs[S.valno->id];
1807145449b1SDimitry Andric LiveRange::Segment NewSeg(S.start, S.end, VNI);
1808145449b1SDimitry Andric LI.addSegment(NewSeg);
1809145449b1SDimitry Andric }
1810145449b1SDimitry Andric LIS->removeInterval(RegA);
1811145449b1SDimitry Andric }
1812145449b1SDimitry Andric
1813145449b1SDimitry Andric if (LV) {
1814145449b1SDimitry Andric if (MI->getOperand(SrcIdx).isKill())
1815145449b1SDimitry Andric LV->removeVirtualRegisterKilled(RegB, *MI);
1816145449b1SDimitry Andric LiveVariables::VarInfo &SrcInfo = LV->getVarInfo(RegB);
1817145449b1SDimitry Andric LiveVariables::VarInfo &DstInfo = LV->getVarInfo(RegA);
1818145449b1SDimitry Andric SrcInfo.AliveBlocks |= DstInfo.AliveBlocks;
1819e3b55780SDimitry Andric DstInfo.AliveBlocks.clear();
1820145449b1SDimitry Andric for (auto *KillMI : DstInfo.Kills)
1821145449b1SDimitry Andric LV->addVirtualRegisterKilled(RegB, *KillMI, false);
1822145449b1SDimitry Andric }
1823145449b1SDimitry Andric }
1824145449b1SDimitry Andric return !NeedCopy;
1825145449b1SDimitry Andric }
1826145449b1SDimitry Andric
1827dd58ef01SDimitry Andric /// Reduce two-address instructions to two operands.
run()1828ac9a064cSDimitry Andric bool TwoAddressInstructionImpl::run() {
1829009b1c42SEd Schouten bool MadeChange = false;
1830009b1c42SEd Schouten
1831eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1832eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n');
1833009b1c42SEd Schouten
183430815c53SDimitry Andric // This pass takes the function out of SSA form.
183530815c53SDimitry Andric MRI->leaveSSA();
183630815c53SDimitry Andric
1837cfca06d7SDimitry Andric // This pass will rewrite the tied-def to meet the RegConstraint.
1838cfca06d7SDimitry Andric MF->getProperties()
1839cfca06d7SDimitry Andric .set(MachineFunctionProperties::Property::TiedOpsRewritten);
1840cfca06d7SDimitry Andric
184158b69754SDimitry Andric TiedOperandMap TiedOperands;
1842344a3780SDimitry Andric for (MachineBasicBlock &MBBI : *MF) {
1843344a3780SDimitry Andric MBB = &MBBI;
1844009b1c42SEd Schouten unsigned Dist = 0;
1845009b1c42SEd Schouten DistanceMap.clear();
1846009b1c42SEd Schouten SrcRegMap.clear();
1847009b1c42SEd Schouten DstRegMap.clear();
1848009b1c42SEd Schouten Processed.clear();
1849522600a2SDimitry Andric for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1850009b1c42SEd Schouten mi != me; ) {
18515ca98fd9SDimitry Andric MachineBasicBlock::iterator nmi = std::next(mi);
1852b60736ecSDimitry Andric // Skip debug instructions.
1853b60736ecSDimitry Andric if (mi->isDebugInstr()) {
18546fe5c7aaSRoman Divacky mi = nmi;
18556fe5c7aaSRoman Divacky continue;
18566fe5c7aaSRoman Divacky }
1857104bd817SRoman Divacky
18584a16efa3SDimitry Andric // Expand REG_SEQUENCE instructions. This will position mi at the first
18594a16efa3SDimitry Andric // expanded instruction.
1860abdf259dSRoman Divacky if (mi->isRegSequence())
18614a16efa3SDimitry Andric eliminateRegSequence(mi);
1862abdf259dSRoman Divacky
186301095a5dSDimitry Andric DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1864009b1c42SEd Schouten
1865522600a2SDimitry Andric processCopy(&*mi);
1866009b1c42SEd Schouten
186759850d08SRoman Divacky // First scan through all the tied register uses in this instruction
186859850d08SRoman Divacky // and record a list of pairs of tied operands for each register.
186901095a5dSDimitry Andric if (!collectTiedOperands(&*mi, TiedOperands)) {
1870c0981da4SDimitry Andric removeClobberedSrcRegMap(&*mi);
187158b69754SDimitry Andric mi = nmi;
1872009b1c42SEd Schouten continue;
1873009b1c42SEd Schouten }
1874009b1c42SEd Schouten
187558b69754SDimitry Andric ++NumTwoAddressInstrs;
187658b69754SDimitry Andric MadeChange = true;
1877eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << '\t' << *mi);
1878009b1c42SEd Schouten
187958b69754SDimitry Andric // If the instruction has a single pair of tied operands, try some
188058b69754SDimitry Andric // transformations that may either eliminate the tied operands or
188158b69754SDimitry Andric // improve the opportunities for coalescing away the register copy.
188258b69754SDimitry Andric if (TiedOperands.size() == 1) {
1883f8af5cf6SDimitry Andric SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
188458b69754SDimitry Andric = TiedOperands.begin()->second;
188558b69754SDimitry Andric if (TiedPairs.size() == 1) {
188658b69754SDimitry Andric unsigned SrcIdx = TiedPairs[0].first;
188758b69754SDimitry Andric unsigned DstIdx = TiedPairs[0].second;
18881d5ae102SDimitry Andric Register SrcReg = mi->getOperand(SrcIdx).getReg();
18891d5ae102SDimitry Andric Register DstReg = mi->getOperand(DstIdx).getReg();
189058b69754SDimitry Andric if (SrcReg != DstReg &&
18914a16efa3SDimitry Andric tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1892dd58ef01SDimitry Andric // The tied operands have been eliminated or shifted further down
1893dd58ef01SDimitry Andric // the block to ease elimination. Continue processing with 'nmi'.
189458b69754SDimitry Andric TiedOperands.clear();
1895c0981da4SDimitry Andric removeClobberedSrcRegMap(&*mi);
189658b69754SDimitry Andric mi = nmi;
189758b69754SDimitry Andric continue;
189858b69754SDimitry Andric }
189958b69754SDimitry Andric }
190059850d08SRoman Divacky }
1901009b1c42SEd Schouten
1902145449b1SDimitry Andric if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1903145449b1SDimitry Andric processStatepoint(&*mi, TiedOperands)) {
1904145449b1SDimitry Andric TiedOperands.clear();
1905145449b1SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1906145449b1SDimitry Andric mi = nmi;
1907145449b1SDimitry Andric continue;
1908145449b1SDimitry Andric }
1909145449b1SDimitry Andric
191059850d08SRoman Divacky // Now iterate over the information collected above.
1911dd58ef01SDimitry Andric for (auto &TO : TiedOperands) {
191201095a5dSDimitry Andric processTiedPairs(&*mi, TO.second, Dist);
1913eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
191458b69754SDimitry Andric }
1915009b1c42SEd Schouten
191666e41e3cSRoman Divacky // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
191766e41e3cSRoman Divacky if (mi->isInsertSubreg()) {
191866e41e3cSRoman Divacky // From %reg = INSERT_SUBREG %reg, %subreg, subidx
191966e41e3cSRoman Divacky // To %reg:subidx = COPY %subreg
192066e41e3cSRoman Divacky unsigned SubIdx = mi->getOperand(3).getImm();
1921145449b1SDimitry Andric mi->removeOperand(3);
192266e41e3cSRoman Divacky assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
192366e41e3cSRoman Divacky mi->getOperand(0).setSubReg(SubIdx);
192458b69754SDimitry Andric mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1925145449b1SDimitry Andric mi->removeOperand(1);
192666e41e3cSRoman Divacky mi->setDesc(TII->get(TargetOpcode::COPY));
1927eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1928c0981da4SDimitry Andric
1929c0981da4SDimitry Andric // Update LiveIntervals.
1930c0981da4SDimitry Andric if (LIS) {
1931c0981da4SDimitry Andric Register Reg = mi->getOperand(0).getReg();
1932c0981da4SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg);
1933c0981da4SDimitry Andric if (LI.hasSubRanges()) {
1934c0981da4SDimitry Andric // The COPY no longer defines subregs of %reg except for
1935c0981da4SDimitry Andric // %reg.subidx.
1936c0981da4SDimitry Andric LaneBitmask LaneMask =
1937c0981da4SDimitry Andric TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1938b1c73532SDimitry Andric SlotIndex Idx = LIS->getInstructionIndex(*mi).getRegSlot();
1939c0981da4SDimitry Andric for (auto &S : LI.subranges()) {
1940c0981da4SDimitry Andric if ((S.LaneMask & LaneMask).none()) {
1941b1c73532SDimitry Andric LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
1942b1c73532SDimitry Andric if (mi->getOperand(0).isUndef()) {
1943b1c73532SDimitry Andric S.removeValNo(DefSeg->valno);
1944b1c73532SDimitry Andric } else {
1945b1c73532SDimitry Andric LiveRange::iterator UseSeg = std::prev(DefSeg);
1946c0981da4SDimitry Andric S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1947c0981da4SDimitry Andric }
1948c0981da4SDimitry Andric }
1949b1c73532SDimitry Andric }
1950c0981da4SDimitry Andric
1951c0981da4SDimitry Andric // The COPY no longer has a use of %reg.
1952c0981da4SDimitry Andric LIS->shrinkToUses(&LI);
1953c0981da4SDimitry Andric } else {
1954c0981da4SDimitry Andric // The live interval for Reg did not have subranges but now it needs
1955c0981da4SDimitry Andric // them because we have introduced a subreg def. Recompute it.
1956c0981da4SDimitry Andric LIS->removeInterval(Reg);
1957c0981da4SDimitry Andric LIS->createAndComputeVirtRegInterval(Reg);
1958c0981da4SDimitry Andric }
1959c0981da4SDimitry Andric }
196066e41e3cSRoman Divacky }
196166e41e3cSRoman Divacky
196259850d08SRoman Divacky // Clear TiedOperands here instead of at the top of the loop
196359850d08SRoman Divacky // since most instructions do not have tied operands.
196459850d08SRoman Divacky TiedOperands.clear();
1965c0981da4SDimitry Andric removeClobberedSrcRegMap(&*mi);
1966009b1c42SEd Schouten mi = nmi;
1967009b1c42SEd Schouten }
1968009b1c42SEd Schouten }
1969009b1c42SEd Schouten
1970009b1c42SEd Schouten return MadeChange;
1971009b1c42SEd Schouten }
1972abdf259dSRoman Divacky
19734a16efa3SDimitry Andric /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1974abdf259dSRoman Divacky ///
19754a16efa3SDimitry Andric /// The instruction is turned into a sequence of sub-register copies:
19764a16efa3SDimitry Andric ///
19774a16efa3SDimitry Andric /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
19784a16efa3SDimitry Andric ///
19794a16efa3SDimitry Andric /// Becomes:
19804a16efa3SDimitry Andric ///
1981044eb2f6SDimitry Andric /// undef %dst:ssub0 = COPY %v1
1982044eb2f6SDimitry Andric /// %dst:ssub1 = COPY %v2
eliminateRegSequence(MachineBasicBlock::iterator & MBBI)1983ac9a064cSDimitry Andric void TwoAddressInstructionImpl::eliminateRegSequence(
1984ac9a064cSDimitry Andric MachineBasicBlock::iterator &MBBI) {
198501095a5dSDimitry Andric MachineInstr &MI = *MBBI;
19861d5ae102SDimitry Andric Register DstReg = MI.getOperand(0).getReg();
1987abdf259dSRoman Divacky
1988cfca06d7SDimitry Andric SmallVector<Register, 4> OrigRegs;
1989ac9a064cSDimitry Andric VNInfo *DefVN = nullptr;
19904a16efa3SDimitry Andric if (LIS) {
199101095a5dSDimitry Andric OrigRegs.push_back(MI.getOperand(0).getReg());
199201095a5dSDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
199301095a5dSDimitry Andric OrigRegs.push_back(MI.getOperand(i).getReg());
1994ac9a064cSDimitry Andric if (LIS->hasInterval(DstReg)) {
1995ac9a064cSDimitry Andric DefVN = LIS->getInterval(DstReg)
1996ac9a064cSDimitry Andric .Query(LIS->getInstructionIndex(MI))
1997ac9a064cSDimitry Andric .valueOut();
1998ac9a064cSDimitry Andric }
19994a16efa3SDimitry Andric }
20004a16efa3SDimitry Andric
2001ac9a064cSDimitry Andric LaneBitmask UndefLanes = LaneBitmask::getNone();
20024a16efa3SDimitry Andric bool DefEmitted = false;
200301095a5dSDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
200401095a5dSDimitry Andric MachineOperand &UseMO = MI.getOperand(i);
20051d5ae102SDimitry Andric Register SrcReg = UseMO.getReg();
200601095a5dSDimitry Andric unsigned SubIdx = MI.getOperand(i+1).getImm();
2007044eb2f6SDimitry Andric // Nothing needs to be inserted for undef operands.
20084df029ccSDimitry Andric if (UseMO.isUndef()) {
2009ac9a064cSDimitry Andric UndefLanes |= TRI->getSubRegIndexLaneMask(SubIdx);
2010abdf259dSRoman Divacky continue;
20114df029ccSDimitry Andric }
2012d39c594dSDimitry Andric
2013d39c594dSDimitry Andric // Defer any kill flag to the last operand using SrcReg. Otherwise, we
2014d39c594dSDimitry Andric // might insert a COPY that uses SrcReg after is was killed.
20154a16efa3SDimitry Andric bool isKill = UseMO.isKill();
2016d39c594dSDimitry Andric if (isKill)
2017d39c594dSDimitry Andric for (unsigned j = i + 2; j < e; j += 2)
201801095a5dSDimitry Andric if (MI.getOperand(j).getReg() == SrcReg) {
201901095a5dSDimitry Andric MI.getOperand(j).setIsKill();
20204a16efa3SDimitry Andric UseMO.setIsKill(false);
2021d39c594dSDimitry Andric isKill = false;
2022d39c594dSDimitry Andric break;
2023d39c594dSDimitry Andric }
2024d39c594dSDimitry Andric
20254a16efa3SDimitry Andric // Insert the sub-register copy.
202601095a5dSDimitry Andric MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
20274a16efa3SDimitry Andric TII->get(TargetOpcode::COPY))
2028cf099d11SDimitry Andric .addReg(DstReg, RegState::Define, SubIdx)
202971d5a254SDimitry Andric .add(UseMO);
20304a16efa3SDimitry Andric
2031044eb2f6SDimitry Andric // The first def needs an undef flag because there is no live register
20324a16efa3SDimitry Andric // before it.
20334a16efa3SDimitry Andric if (!DefEmitted) {
20344a16efa3SDimitry Andric CopyMI->getOperand(0).setIsUndef(true);
20354a16efa3SDimitry Andric // Return an iterator pointing to the first inserted instr.
20364a16efa3SDimitry Andric MBBI = CopyMI;
20374a16efa3SDimitry Andric }
20384a16efa3SDimitry Andric DefEmitted = true;
20394a16efa3SDimitry Andric
20404a16efa3SDimitry Andric // Update LiveVariables' kill info.
2041b60736ecSDimitry Andric if (LV && isKill && !SrcReg.isPhysical())
204201095a5dSDimitry Andric LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
20434a16efa3SDimitry Andric
2044eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI);
2045abdf259dSRoman Divacky }
2046abdf259dSRoman Divacky
20474a16efa3SDimitry Andric MachineBasicBlock::iterator EndMBBI =
20485ca98fd9SDimitry Andric std::next(MachineBasicBlock::iterator(MI));
2049abdf259dSRoman Divacky
20504a16efa3SDimitry Andric if (!DefEmitted) {
2051eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
205201095a5dSDimitry Andric MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
205301095a5dSDimitry Andric for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2054145449b1SDimitry Andric MI.removeOperand(j);
2055abdf259dSRoman Divacky } else {
20564df029ccSDimitry Andric if (LIS) {
2057ac9a064cSDimitry Andric // Force live interval recomputation if we moved to a partial definition
2058ac9a064cSDimitry Andric // of the register. Undef flags must be propagate to uses of undefined
2059ac9a064cSDimitry Andric // subregister for accurate interval computation.
2060ac9a064cSDimitry Andric if (UndefLanes.any() && DefVN && MRI->shouldTrackSubRegLiveness(DstReg)) {
2061ac9a064cSDimitry Andric auto &LI = LIS->getInterval(DstReg);
2062ac9a064cSDimitry Andric for (MachineOperand &UseOp : MRI->use_operands(DstReg)) {
2063ac9a064cSDimitry Andric unsigned SubReg = UseOp.getSubReg();
2064ac9a064cSDimitry Andric if (UseOp.isUndef() || !SubReg)
2065ac9a064cSDimitry Andric continue;
2066ac9a064cSDimitry Andric auto *VN =
2067ac9a064cSDimitry Andric LI.getVNInfoAt(LIS->getInstructionIndex(*UseOp.getParent()));
2068ac9a064cSDimitry Andric if (DefVN != VN)
2069ac9a064cSDimitry Andric continue;
2070ac9a064cSDimitry Andric LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
2071ac9a064cSDimitry Andric if ((UndefLanes & LaneMask).any())
2072ac9a064cSDimitry Andric UseOp.setIsUndef(true);
2073ac9a064cSDimitry Andric }
20744df029ccSDimitry Andric LIS->removeInterval(DstReg);
2075ac9a064cSDimitry Andric }
2076c0981da4SDimitry Andric LIS->RemoveMachineInstrFromMaps(MI);
20774df029ccSDimitry Andric }
2078c0981da4SDimitry Andric
2079eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Eliminated: " << MI);
208001095a5dSDimitry Andric MI.eraseFromParent();
2081abdf259dSRoman Divacky }
2082abdf259dSRoman Divacky
20834a16efa3SDimitry Andric // Udpate LiveIntervals.
20844a16efa3SDimitry Andric if (LIS)
20854a16efa3SDimitry Andric LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
2086abdf259dSRoman Divacky }
2087