blob: 5a40a1d5bab23f5afd6a132abbd2a0b967382684 [file] [log] [blame]
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00007//
8//===----------------------------------------------------------------------===//
9//
Alkis Evlogimenos50c047d2004-01-04 23:09:24 +000010// This file implements the TwoAddress instruction pass which is used
11// by most register allocators. Two-Address instructions are rewritten
12// from:
13//
14// A = B op C
15//
16// to:
17//
18// A = B
Alkis Evlogimenos14be6402004-02-04 22:17:40 +000019// A op= C
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000020//
Alkis Evlogimenos14be6402004-02-04 22:17:40 +000021// Note that if a register allocator chooses to use this pass, that it
22// has to be capable of handling the non-SSA nature of these rewritten
23// virtual registers.
24//
25// It is also worth noting that the duplicate operand of the two
26// address instruction is removed.
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000027//
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000028//===----------------------------------------------------------------------===//
29
30#define DEBUG_TYPE "twoaddrinstr"
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000031#include "llvm/CodeGen/Passes.h"
Chris Lattner1e313632004-07-21 23:17:57 +000032#include "llvm/Function.h"
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000033#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000034#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000039#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000040#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000041#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000042#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000044#include "llvm/Target/TargetOptions.h"
Evan Cheng875357d2008-03-13 06:37:55 +000045#include "llvm/Support/Debug.h"
Evan Cheng3d720fb2010-05-05 18:45:40 +000046#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000047#include "llvm/ADT/BitVector.h"
48#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000049#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
51#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000052using namespace llvm;
53
Chris Lattnercd3245a2006-12-19 22:41:21 +000054STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
55STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000056STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000057STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000058STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng2a4410d2011-11-14 19:48:55 +000059STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
60STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng875357d2008-03-13 06:37:55 +000061
62namespace {
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000063class TwoAddressInstructionPass : public MachineFunctionPass {
64 MachineFunction *MF;
65 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
67 const InstrItineraryData *InstrItins;
68 MachineRegisterInfo *MRI;
69 LiveVariables *LV;
70 SlotIndexes *Indexes;
71 LiveIntervals *LIS;
72 AliasAnalysis *AA;
73 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000074
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000075 // DistanceMap - Keep track the distance of a MI from the start of the
76 // current basic block.
77 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000078
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000079 // SrcRegMap - A map from virtual registers to physical registers which are
80 // likely targets to be coalesced to due to copies from physical registers to
81 // virtual registers. e.g. v1024 = move r0.
82 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000083
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000084 // DstRegMap - A map from virtual registers to physical registers which are
85 // likely targets to be coalesced to due to copies to physical registers from
86 // virtual registers. e.g. r1 = move v1024.
87 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000088
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000089 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
90 /// during the initial walk of the machine function.
91 SmallVector<MachineInstr*, 16> RegSequences;
Evan Cheng3d720fb2010-05-05 18:45:40 +000092
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000093 bool sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
94 unsigned Reg,
95 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000096
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000097 bool noUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
98 unsigned &LastDef);
Evan Chengd498c8f2009-01-25 03:53:59 +000099
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000100 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
101 MachineInstr *MI, MachineBasicBlock *MBB,
102 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000103
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000104 bool commuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
106 unsigned RegB, unsigned RegC, unsigned Dist);
Evan Cheng870b8072009-03-01 02:03:43 +0000107
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000108 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000109
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000110 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
113 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000114
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000115 bool isDefTooClose(unsigned Reg, unsigned Dist,
116 MachineInstr *MI, MachineBasicBlock *MBB);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000117
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000118 bool rescheduleMIBelowKill(MachineBasicBlock *MBB,
119 MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
121 unsigned Reg);
122 bool rescheduleKillAboveMI(MachineBasicBlock *MBB,
123 MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
125 unsigned Reg);
126
127 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng2a4410d2011-11-14 19:48:55 +0000128 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000129 MachineFunction::iterator &mbbi,
130 unsigned SrcIdx, unsigned DstIdx,
131 unsigned Dist,
132 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000133
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000134 void scanUses(unsigned DstReg, MachineBasicBlock *MBB,
135 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Chengf06e6c22011-03-02 01:08:17 +0000136
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000137 void processCopy(MachineInstr *MI, MachineBasicBlock *MBB,
138 SmallPtrSet<MachineInstr*, 8> &Processed);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000139
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000140 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
142 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
143 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000144
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000145 /// eliminateRegSequences - Eliminate REG_SEQUENCE instructions as part of
146 /// the de-ssa process. This replaces sources of REG_SEQUENCE as sub-register
147 /// references of the register defined by REG_SEQUENCE.
148 bool eliminateRegSequences();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000149
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000150public:
151 static char ID; // Pass identification, replacement for typeid
152 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
154 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000155
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000156 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
157 AU.setPreservesCFG();
158 AU.addRequired<AliasAnalysis>();
159 AU.addPreserved<LiveVariables>();
160 AU.addPreserved<SlotIndexes>();
161 AU.addPreserved<LiveIntervals>();
162 AU.addPreservedID(MachineLoopInfoID);
163 AU.addPreservedID(MachineDominatorsID);
164 MachineFunctionPass::getAnalysisUsage(AU);
165 }
Devang Patel794fd752007-05-01 21:15:47 +0000166
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000167 /// runOnMachineFunction - Pass entry point.
168 bool runOnMachineFunction(MachineFunction&);
169};
170} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000171
Dan Gohman844731a2008-05-13 00:00:25 +0000172char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000173INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
174 "Two-Address instruction pass", false, false)
175INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
176INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000177 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000178
Owen Anderson90c579d2010-08-06 18:33:48 +0000179char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000180
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000181/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000182/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000183/// past the instruction that would kill the above mentioned register to reduce
184/// register pressure.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000185bool TwoAddressInstructionPass::sink3AddrInstruction(MachineBasicBlock *MBB,
Evan Cheng875357d2008-03-13 06:37:55 +0000186 MachineInstr *MI, unsigned SavedReg,
187 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000188 // FIXME: Shouldn't we be trying to do this before we three-addressify the
189 // instruction? After this transformation is done, we no longer need
190 // the instruction to be in three-address form.
191
Evan Cheng875357d2008-03-13 06:37:55 +0000192 // Check if it's safe to move this instruction.
193 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000194 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000195 return false;
196
197 unsigned DefReg = 0;
198 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000199
Evan Cheng875357d2008-03-13 06:37:55 +0000200 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
201 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000202 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000203 continue;
204 unsigned MOReg = MO.getReg();
205 if (!MOReg)
206 continue;
207 if (MO.isUse() && MOReg != SavedReg)
208 UseRegs.insert(MO.getReg());
209 if (!MO.isDef())
210 continue;
211 if (MO.isImplicit())
212 // Don't try to move it if it implicitly defines a register.
213 return false;
214 if (DefReg)
215 // For now, don't move any instructions that define multiple registers.
216 return false;
217 DefReg = MO.getReg();
218 }
219
220 // Find the instruction that kills SavedReg.
221 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000222 for (MachineRegisterInfo::use_nodbg_iterator
223 UI = MRI->use_nodbg_begin(SavedReg),
224 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000225 MachineOperand &UseMO = UI.getOperand();
226 if (!UseMO.isKill())
227 continue;
228 KillMI = UseMO.getParent();
229 break;
230 }
Bill Wendling637980e2008-05-10 00:12:52 +0000231
Eli Friedmanbde81d52011-09-23 22:41:57 +0000232 // If we find the instruction that kills SavedReg, and it is in an
233 // appropriate location, we can try to sink the current instruction
234 // past it.
235 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000236 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000237 return false;
238
Bill Wendling637980e2008-05-10 00:12:52 +0000239 // If any of the definitions are used by another instruction between the
240 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000241 //
Bill Wendling637980e2008-05-10 00:12:52 +0000242 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000243 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000244 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000245 MachineOperand *KillMO = NULL;
246 MachineBasicBlock::iterator KillPos = KillMI;
247 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000248
Evan Cheng7543e582008-06-18 07:49:14 +0000249 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000250 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000251 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000252 // DBG_VALUE cannot be counted against the limit.
253 if (OtherMI->isDebugValue())
254 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000255 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
256 return false;
257 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000258 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
259 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000260 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000261 continue;
262 unsigned MOReg = MO.getReg();
263 if (!MOReg)
264 continue;
265 if (DefReg == MOReg)
266 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000267
Evan Cheng875357d2008-03-13 06:37:55 +0000268 if (MO.isKill()) {
269 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000270 // Save the operand that kills the register. We want to unset the kill
271 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000272 KillMO = &MO;
273 else if (UseRegs.count(MOReg))
274 // One of the uses is killed before the destination.
275 return false;
276 }
277 }
278 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000279 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000280
Evan Cheng875357d2008-03-13 06:37:55 +0000281 // Update kill and LV information.
282 KillMO->setIsKill(false);
283 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
284 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000285
Evan Cheng9f1c8312008-07-03 09:09:37 +0000286 if (LV)
287 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000288
289 // Move instruction to its destination.
290 MBB->remove(MI);
291 MBB->insert(KillPos, MI);
292
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000293 if (LIS)
294 LIS->handleMove(MI);
295
Evan Cheng875357d2008-03-13 06:37:55 +0000296 ++Num3AddrSunk;
297 return true;
298}
299
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000300/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000301/// last instruction in the MBB that defines the specified register and the
302/// two-address instruction which is being processed. It also returns the last
303/// def location by reference
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000304bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg,
305 MachineBasicBlock *MBB,
306 unsigned Dist,
307 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000308 LastDef = 0;
309 unsigned LastUse = Dist;
310 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
311 E = MRI->reg_end(); I != E; ++I) {
312 MachineOperand &MO = I.getOperand();
313 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000314 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000315 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000316 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
317 if (DI == DistanceMap.end())
318 continue;
319 if (MO.isUse() && DI->second < LastUse)
320 LastUse = DI->second;
321 if (MO.isDef() && DI->second > LastDef)
322 LastDef = DI->second;
323 }
324
325 return !(LastUse > LastDef && LastUse < Dist);
326}
327
Evan Cheng870b8072009-03-01 02:03:43 +0000328/// isCopyToReg - Return true if the specified MI is a copy instruction or
329/// a extract_subreg instruction. It also returns the source and destination
330/// registers and whether they are physical registers by reference.
331static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
332 unsigned &SrcReg, unsigned &DstReg,
333 bool &IsSrcPhys, bool &IsDstPhys) {
334 SrcReg = 0;
335 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000336 if (MI.isCopy()) {
337 DstReg = MI.getOperand(0).getReg();
338 SrcReg = MI.getOperand(1).getReg();
339 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
340 DstReg = MI.getOperand(0).getReg();
341 SrcReg = MI.getOperand(2).getReg();
342 } else
343 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000344
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000345 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
346 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
347 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000348}
349
Dan Gohman97121ba2009-04-08 00:15:30 +0000350/// isKilled - Test if the given register value, which is used by the given
351/// instruction, is killed by the given instruction. This looks through
352/// coalescable copies to see if the original value is potentially not killed.
353///
354/// For example, in this code:
355///
356/// %reg1034 = copy %reg1024
357/// %reg1035 = copy %reg1025<kill>
358/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
359///
360/// %reg1034 is not considered to be killed, since it is copied from a
361/// register which is not killed. Treating it as not killed lets the
362/// normal heuristics commute the (two-address) add, which lets
363/// coalescing eliminate the extra copy.
364///
365static bool isKilled(MachineInstr &MI, unsigned Reg,
366 const MachineRegisterInfo *MRI,
367 const TargetInstrInfo *TII) {
368 MachineInstr *DefMI = &MI;
369 for (;;) {
370 if (!DefMI->killsRegister(Reg))
371 return false;
372 if (TargetRegisterInfo::isPhysicalRegister(Reg))
373 return true;
374 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
375 // If there are multiple defs, we can't do a simple analysis, so just
376 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000377 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000378 return true;
379 DefMI = &*Begin;
380 bool IsSrcPhys, IsDstPhys;
381 unsigned SrcReg, DstReg;
382 // If the def is something other than a copy, then it isn't going to
383 // be coalesced, so follow the kill flag.
384 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
385 return true;
386 Reg = SrcReg;
387 }
388}
389
Evan Cheng870b8072009-03-01 02:03:43 +0000390/// isTwoAddrUse - Return true if the specified MI uses the specified register
391/// as a two-address use. If so, return the destination register by reference.
392static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000393 const MCInstrDesc &MCID = MI.getDesc();
394 unsigned NumOps = MI.isInlineAsm()
395 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000396 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000397 const MachineOperand &MO = MI.getOperand(i);
398 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
399 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000400 unsigned ti;
401 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000402 DstReg = MI.getOperand(ti).getReg();
403 return true;
404 }
405 }
406 return false;
407}
408
409/// findOnlyInterestingUse - Given a register, if has a single in-basic block
410/// use, return the use instruction if it's a copy or a two-address use.
411static
412MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
413 MachineRegisterInfo *MRI,
414 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000415 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000416 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000417 if (!MRI->hasOneNonDBGUse(Reg))
418 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000419 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000420 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000421 if (UseMI.getParent() != MBB)
422 return 0;
423 unsigned SrcReg;
424 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000425 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
426 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000427 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000428 }
Evan Cheng870b8072009-03-01 02:03:43 +0000429 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000430 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
431 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000432 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000433 }
Evan Cheng870b8072009-03-01 02:03:43 +0000434 return 0;
435}
436
437/// getMappedReg - Return the physical register the specified virtual register
438/// might be mapped to.
439static unsigned
440getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
441 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
442 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
443 if (SI == RegMap.end())
444 return 0;
445 Reg = SI->second;
446 }
447 if (TargetRegisterInfo::isPhysicalRegister(Reg))
448 return Reg;
449 return 0;
450}
451
452/// regsAreCompatible - Return true if the two registers are equal or aliased.
453///
454static bool
455regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
456 if (RegA == RegB)
457 return true;
458 if (!RegA || !RegB)
459 return false;
460 return TRI->regsOverlap(RegA, RegB);
461}
462
463
Manman Rend68e8cd2012-07-25 18:28:13 +0000464/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000465/// the two-address instruction that's being processed.
466bool
Evan Chengd99d68b2012-05-03 01:45:13 +0000467TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
468 unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000469 MachineInstr *MI, MachineBasicBlock *MBB,
470 unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000471 if (OptLevel == CodeGenOpt::None)
472 return false;
473
Evan Chengd498c8f2009-01-25 03:53:59 +0000474 // Determine if it's profitable to commute this two address instruction. In
475 // general, we want no uses between this instruction and the definition of
476 // the two-address register.
477 // e.g.
478 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
479 // %reg1029<def> = MOV8rr %reg1028
480 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
481 // insert => %reg1030<def> = MOV8rr %reg1028
482 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
483 // In this case, it might not be possible to coalesce the second MOV8rr
484 // instruction if the first one is coalesced. So it would be profitable to
485 // commute it:
486 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
487 // %reg1029<def> = MOV8rr %reg1028
488 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
489 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000490 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000491
492 if (!MI->killsRegister(regC))
493 return false;
494
495 // Ok, we have something like:
496 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
497 // let's see if it's worth commuting it.
498
Evan Cheng870b8072009-03-01 02:03:43 +0000499 // Look for situations like this:
500 // %reg1024<def> = MOV r1
501 // %reg1025<def> = MOV r0
502 // %reg1026<def> = ADD %reg1024, %reg1025
503 // r0 = MOV %reg1026
504 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000505 unsigned ToRegA = getMappedReg(regA, DstRegMap);
506 if (ToRegA) {
507 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
508 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
509 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
510 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
511 if (BComp != CComp)
512 return !BComp && CComp;
513 }
Evan Cheng870b8072009-03-01 02:03:43 +0000514
Evan Chengd498c8f2009-01-25 03:53:59 +0000515 // If there is a use of regC between its last def (could be livein) and this
516 // instruction, then bail.
517 unsigned LastDefC = 0;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000518 if (!noUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000519 return false;
520
521 // If there is a use of regB between its last def (could be livein) and this
522 // instruction, then go ahead and make this transformation.
523 unsigned LastDefB = 0;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000524 if (!noUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000525 return true;
526
527 // Since there are no intervening uses for both registers, then commute
528 // if the def of regC is closer. Its live interval is shorter.
529 return LastDefB && LastDefC && LastDefC > LastDefB;
530}
531
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000532/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000533/// block, distance map, and live variables if needed. Return true if it is
534/// successful.
535bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000536TwoAddressInstructionPass::commuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000537 MachineFunction::iterator &mbbi,
538 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000539 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000540 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000541 MachineInstr *NewMI = TII->commuteInstruction(MI);
542
543 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000544 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000545 return false;
546 }
547
David Greeneeb00b182010-01-05 01:24:21 +0000548 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000549 // If the instruction changed to commute it, update livevar.
550 if (NewMI != MI) {
551 if (LV)
552 // Update live variables
553 LV->replaceKillInstruction(RegC, MI, NewMI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000554 if (Indexes)
555 Indexes->replaceMachineInstrInMaps(MI, NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000556
557 mbbi->insert(mi, NewMI); // Insert the new inst
558 mbbi->erase(mi); // Nuke the old inst.
559 mi = NewMI;
560 DistanceMap.insert(std::make_pair(NewMI, Dist));
561 }
Evan Cheng870b8072009-03-01 02:03:43 +0000562
563 // Update source register map.
564 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
565 if (FromRegC) {
566 unsigned RegA = MI->getOperand(0).getReg();
567 SrcRegMap[RegA] = FromRegC;
568 }
569
Evan Cheng81913712009-01-23 23:27:33 +0000570 return true;
571}
572
Evan Chenge6f350d2009-03-30 21:34:07 +0000573/// isProfitableToConv3Addr - Return true if it is profitable to convert the
574/// given 2-address instruction to a 3-address one.
575bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000576TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000577 // Look for situations like this:
578 // %reg1024<def> = MOV r1
579 // %reg1025<def> = MOV r0
580 // %reg1026<def> = ADD %reg1024, %reg1025
581 // r2 = MOV %reg1026
582 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000583 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
584 if (!FromRegB)
585 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000586 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000587 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000588}
589
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000590/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000591/// three address one. Return true if this transformation was successful.
592bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000593TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000594 MachineBasicBlock::iterator &nmi,
595 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000596 unsigned RegA, unsigned RegB,
597 unsigned Dist) {
Evan Chenge6f350d2009-03-30 21:34:07 +0000598 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
599 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000600 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
601 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000602 bool Sunk = false;
603
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000604 if (Indexes)
605 Indexes->replaceMachineInstrInMaps(mi, NewMI);
606
Evan Chenge6f350d2009-03-30 21:34:07 +0000607 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
608 // FIXME: Temporary workaround. If the new instruction doesn't
609 // uses RegB, convertToThreeAddress must have created more
610 // then one instruction.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000611 Sunk = sink3AddrInstruction(mbbi, NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000612
613 mbbi->erase(mi); // Nuke the old inst.
614
615 if (!Sunk) {
616 DistanceMap.insert(std::make_pair(NewMI, Dist));
617 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000618 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000619 }
Evan Cheng4d96c632011-02-10 02:20:55 +0000620
621 // Update source and destination register maps.
622 SrcRegMap.erase(RegA);
623 DstRegMap.erase(RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000624 return true;
625 }
626
627 return false;
628}
629
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000630/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000631/// is a copy or a two-address instruction.
632void
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000633TwoAddressInstructionPass::scanUses(unsigned DstReg, MachineBasicBlock *MBB,
Evan Chengf06e6c22011-03-02 01:08:17 +0000634 SmallPtrSet<MachineInstr*, 8> &Processed) {
635 SmallVector<unsigned, 4> VirtRegPairs;
636 bool IsDstPhys;
637 bool IsCopy = false;
638 unsigned NewReg = 0;
639 unsigned Reg = DstReg;
640 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
641 NewReg, IsDstPhys)) {
642 if (IsCopy && !Processed.insert(UseMI))
643 break;
644
645 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
646 if (DI != DistanceMap.end())
647 // Earlier in the same MBB.Reached via a back edge.
648 break;
649
650 if (IsDstPhys) {
651 VirtRegPairs.push_back(NewReg);
652 break;
653 }
654 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
655 if (!isNew)
656 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
657 VirtRegPairs.push_back(NewReg);
658 Reg = NewReg;
659 }
660
661 if (!VirtRegPairs.empty()) {
662 unsigned ToReg = VirtRegPairs.back();
663 VirtRegPairs.pop_back();
664 while (!VirtRegPairs.empty()) {
665 unsigned FromReg = VirtRegPairs.back();
666 VirtRegPairs.pop_back();
667 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
668 if (!isNew)
669 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
670 ToReg = FromReg;
671 }
672 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
673 if (!isNew)
674 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
675 }
676}
677
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000678/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000679/// if it's a copy. For a copy instruction, we find the physical registers the
680/// source and destination registers might be mapped to. These are kept in
681/// point-to maps used to determine future optimizations. e.g.
682/// v1024 = mov r0
683/// v1025 = mov r1
684/// v1026 = add v1024, v1025
685/// r1 = mov r1026
686/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
687/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
688/// potentially joined with r1 on the output side. It's worthwhile to commute
689/// 'add' to eliminate a copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000690void TwoAddressInstructionPass::processCopy(MachineInstr *MI,
Evan Cheng870b8072009-03-01 02:03:43 +0000691 MachineBasicBlock *MBB,
692 SmallPtrSet<MachineInstr*, 8> &Processed) {
693 if (Processed.count(MI))
694 return;
695
696 bool IsSrcPhys, IsDstPhys;
697 unsigned SrcReg, DstReg;
698 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
699 return;
700
701 if (IsDstPhys && !IsSrcPhys)
702 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
703 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000704 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
705 if (!isNew)
706 assert(SrcRegMap[DstReg] == SrcReg &&
707 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000708
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000709 scanUses(DstReg, MBB, Processed);
Evan Cheng870b8072009-03-01 02:03:43 +0000710 }
711
712 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000713 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000714}
715
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000716/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000717/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
718/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000719bool TwoAddressInstructionPass::
720rescheduleMIBelowKill(MachineBasicBlock *MBB,
721 MachineBasicBlock::iterator &mi,
722 MachineBasicBlock::iterator &nmi,
723 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000724 // Bail immediately if we don't have LV available. We use it to find kills
725 // efficiently.
726 if (!LV)
727 return false;
728
Evan Cheng2a4410d2011-11-14 19:48:55 +0000729 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000730 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000731 if (DI == DistanceMap.end())
732 // Must be created from unfolded load. Don't waste time trying this.
733 return false;
734
Chandler Carruth7d532c82012-07-15 03:29:46 +0000735 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
736 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000737 // Don't mess with copies, they may be coalesced later.
738 return false;
739
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000740 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
741 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000742 // Don't move pass calls, etc.
743 return false;
744
745 unsigned DstReg;
746 if (isTwoAddrUse(*KillMI, Reg, DstReg))
747 return false;
748
Evan Chengf1784182011-11-15 06:26:51 +0000749 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000750 if (!MI->isSafeToMove(TII, AA, SeenStore))
751 return false;
752
753 if (TII->getInstrLatency(InstrItins, MI) > 1)
754 // FIXME: Needs more sophisticated heuristics.
755 return false;
756
757 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000758 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000759 SmallSet<unsigned, 2> Defs;
760 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
761 const MachineOperand &MO = MI->getOperand(i);
762 if (!MO.isReg())
763 continue;
764 unsigned MOReg = MO.getReg();
765 if (!MOReg)
766 continue;
767 if (MO.isDef())
768 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000769 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000770 Uses.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000771 if (MO.isKill() && MOReg != Reg)
772 Kills.insert(MOReg);
773 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000774 }
775
776 // Move the copies connected to MI down as well.
777 MachineBasicBlock::iterator From = MI;
778 MachineBasicBlock::iterator To = llvm::next(From);
779 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
780 Defs.insert(To->getOperand(0).getReg());
781 ++To;
782 }
783
784 // Check if the reschedule will not break depedencies.
785 unsigned NumVisited = 0;
786 MachineBasicBlock::iterator KillPos = KillMI;
787 ++KillPos;
788 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
789 MachineInstr *OtherMI = I;
790 // DBG_VALUE cannot be counted against the limit.
791 if (OtherMI->isDebugValue())
792 continue;
793 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
794 return false;
795 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000796 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
797 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000798 // Don't move pass calls, etc.
799 return false;
800 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
801 const MachineOperand &MO = OtherMI->getOperand(i);
802 if (!MO.isReg())
803 continue;
804 unsigned MOReg = MO.getReg();
805 if (!MOReg)
806 continue;
807 if (MO.isDef()) {
808 if (Uses.count(MOReg))
809 // Physical register use would be clobbered.
810 return false;
811 if (!MO.isDead() && Defs.count(MOReg))
812 // May clobber a physical register def.
813 // FIXME: This may be too conservative. It's ok if the instruction
814 // is sunken completely below the use.
815 return false;
816 } else {
817 if (Defs.count(MOReg))
818 return false;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000819 if (MOReg != Reg &&
820 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000821 // Don't want to extend other live ranges and update kills.
822 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000823 if (MOReg == Reg && !MO.isKill())
824 // We can't schedule across a use of the register in question.
825 return false;
826 // Ensure that if this is register in question, its the kill we expect.
827 assert((MOReg != Reg || OtherMI == KillMI) &&
828 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000829 }
830 }
831 }
832
833 // Move debug info as well.
Evan Cheng8aee7d82011-11-14 21:11:15 +0000834 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
835 --From;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000836
837 // Copies following MI may have been moved as well.
838 nmi = To;
839 MBB->splice(KillPos, MBB, From, To);
840 DistanceMap.erase(DI);
841
Chandler Carruth7d532c82012-07-15 03:29:46 +0000842 // Update live variables
843 LV->removeVirtualRegisterKilled(Reg, KillMI);
844 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000845 if (LIS)
846 LIS->handleMove(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000847
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000848 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000849 return true;
850}
851
852/// isDefTooClose - Return true if the re-scheduling will put the given
853/// instruction too close to the defs of its register dependencies.
854bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
855 MachineInstr *MI,
856 MachineBasicBlock *MBB) {
857 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
858 DE = MRI->def_end(); DI != DE; ++DI) {
859 MachineInstr *DefMI = &*DI;
860 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
861 continue;
862 if (DefMI == MI)
863 return true; // MI is defining something KillMI uses
864 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
865 if (DDI == DistanceMap.end())
866 return true; // Below MI
867 unsigned DefDist = DDI->second;
868 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000869 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000870 return true;
871 }
872 return false;
873}
874
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000875/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000876/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
877/// current two-address instruction in order to eliminate the need for the
878/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000879bool TwoAddressInstructionPass::
880rescheduleKillAboveMI(MachineBasicBlock *MBB,
881 MachineBasicBlock::iterator &mi,
882 MachineBasicBlock::iterator &nmi,
883 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000884 // Bail immediately if we don't have LV available. We use it to find kills
885 // efficiently.
886 if (!LV)
887 return false;
888
Evan Cheng2a4410d2011-11-14 19:48:55 +0000889 MachineInstr *MI = &*mi;
890 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
891 if (DI == DistanceMap.end())
892 // Must be created from unfolded load. Don't waste time trying this.
893 return false;
894
Chandler Carruth7d532c82012-07-15 03:29:46 +0000895 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
896 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000897 // Don't mess with copies, they may be coalesced later.
898 return false;
899
900 unsigned DstReg;
901 if (isTwoAddrUse(*KillMI, Reg, DstReg))
902 return false;
903
Evan Chengf1784182011-11-15 06:26:51 +0000904 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000905 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
906 return false;
907
908 SmallSet<unsigned, 2> Uses;
909 SmallSet<unsigned, 2> Kills;
910 SmallSet<unsigned, 2> Defs;
911 SmallSet<unsigned, 2> LiveDefs;
912 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
913 const MachineOperand &MO = KillMI->getOperand(i);
914 if (!MO.isReg())
915 continue;
916 unsigned MOReg = MO.getReg();
917 if (MO.isUse()) {
918 if (!MOReg)
919 continue;
920 if (isDefTooClose(MOReg, DI->second, MI, MBB))
921 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000922 if (MOReg == Reg && !MO.isKill())
923 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000924 Uses.insert(MOReg);
925 if (MO.isKill() && MOReg != Reg)
926 Kills.insert(MOReg);
927 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
928 Defs.insert(MOReg);
929 if (!MO.isDead())
930 LiveDefs.insert(MOReg);
931 }
932 }
933
934 // Check if the reschedule will not break depedencies.
935 unsigned NumVisited = 0;
936 MachineBasicBlock::iterator KillPos = KillMI;
937 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
938 MachineInstr *OtherMI = I;
939 // DBG_VALUE cannot be counted against the limit.
940 if (OtherMI->isDebugValue())
941 continue;
942 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
943 return false;
944 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000945 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
946 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000947 // Don't move pass calls, etc.
948 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +0000949 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000950 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
951 const MachineOperand &MO = OtherMI->getOperand(i);
952 if (!MO.isReg())
953 continue;
954 unsigned MOReg = MO.getReg();
955 if (!MOReg)
956 continue;
957 if (MO.isUse()) {
958 if (Defs.count(MOReg))
959 // Moving KillMI can clobber the physical register if the def has
960 // not been seen.
961 return false;
962 if (Kills.count(MOReg))
963 // Don't want to extend other live ranges and update kills.
964 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000965 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
966 // We can't schedule across a use of the register in question.
967 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000968 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +0000969 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000970 }
971 }
Evan Chengae7db7a2011-11-16 03:05:12 +0000972
973 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
974 unsigned MOReg = OtherDefs[i];
975 if (Uses.count(MOReg))
976 return false;
977 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
978 LiveDefs.count(MOReg))
979 return false;
980 // Physical register def is seen.
981 Defs.erase(MOReg);
982 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000983 }
984
985 // Move the old kill above MI, don't forget to move debug info as well.
986 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +0000987 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
988 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000989 MachineBasicBlock::iterator From = KillMI;
990 MachineBasicBlock::iterator To = llvm::next(From);
991 while (llvm::prior(From)->isDebugValue())
992 --From;
993 MBB->splice(InsertPos, MBB, From, To);
994
Evan Cheng2bee6a82011-11-16 03:33:08 +0000995 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +0000996 DistanceMap.erase(DI);
997
Chandler Carruth7d532c82012-07-15 03:29:46 +0000998 // Update live variables
999 LV->removeVirtualRegisterKilled(Reg, KillMI);
1000 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001001 if (LIS)
1002 LIS->handleMove(KillMI);
Chandler Carruth7d532c82012-07-15 03:29:46 +00001003
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001004 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001005 return true;
1006}
1007
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001008/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +00001009/// pair of tied register operands, attempt some transformations that may
1010/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001011/// coalescing away the register copy. Returns true if no copy needs to be
1012/// inserted to untie mi's operands (either because they were untied, or
1013/// because mi was rescheduled, and will be visited again later).
Bob Wilsoncc80df92009-09-03 20:58:42 +00001014bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001015tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001016 MachineBasicBlock::iterator &nmi,
1017 MachineFunction::iterator &mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001018 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1019 SmallPtrSet<MachineInstr*, 8> &Processed) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001020 if (OptLevel == CodeGenOpt::None)
1021 return false;
1022
Evan Cheng2a4410d2011-11-14 19:48:55 +00001023 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001024 unsigned regA = MI.getOperand(DstIdx).getReg();
1025 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001026
1027 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1028 "cannot make instruction into two-address form");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001029 bool regBKilled = isKilled(MI, regB, MRI, TII);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001030
Evan Chengd99d68b2012-05-03 01:45:13 +00001031 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001032 scanUses(regA, &*mbbi, Processed);
Evan Chengd99d68b2012-05-03 01:45:13 +00001033
Bob Wilsoncc80df92009-09-03 20:58:42 +00001034 // Check if it is profitable to commute the operands.
1035 unsigned SrcOp1, SrcOp2;
1036 unsigned regC = 0;
1037 unsigned regCIdx = ~0U;
1038 bool TryCommute = false;
1039 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001040 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001041 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001042 if (SrcIdx == SrcOp1)
1043 regCIdx = SrcOp2;
1044 else if (SrcIdx == SrcOp2)
1045 regCIdx = SrcOp1;
1046
1047 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001048 regC = MI.getOperand(regCIdx).getReg();
1049 if (!regBKilled && isKilled(MI, regC, MRI, TII))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001050 // If C dies but B does not, swap the B and C operands.
1051 // This makes the live ranges of A and C joinable.
1052 TryCommute = true;
Evan Chengd99d68b2012-05-03 01:45:13 +00001053 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001054 TryCommute = true;
1055 AggressiveCommute = true;
1056 }
1057 }
1058 }
1059
1060 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001061 if (TryCommute && commuteInstruction(mi, mbbi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001062 ++NumCommuted;
1063 if (AggressiveCommute)
1064 ++NumAggrCommuted;
1065 return false;
1066 }
1067
Evan Cheng2a4410d2011-11-14 19:48:55 +00001068 // If there is one more use of regB later in the same MBB, consider
1069 // re-schedule this MI below it.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001070 if (rescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001071 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001072 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001073 }
1074
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001075 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001076 // This instruction is potentially convertible to a true
1077 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001078 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001079 // Try to convert it.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001080 if (convertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001081 ++NumConvertedTo3Addr;
1082 return true; // Done with this instruction.
1083 }
1084 }
1085 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001086
Evan Cheng2a4410d2011-11-14 19:48:55 +00001087 // If there is one more use of regB later in the same MBB, consider
1088 // re-schedule it before this MI if it's legal.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001089 if (rescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001090 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001091 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001092 }
1093
Dan Gohman584fedf2010-06-21 22:17:20 +00001094 // If this is an instruction with a load folded into it, try unfolding
1095 // the load, e.g. avoid this:
1096 // movq %rdx, %rcx
1097 // addq (%rax), %rcx
1098 // in favor of this:
1099 // movq (%rax), %rcx
1100 // addq %rdx, %rcx
1101 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001102 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001103 // Determine if a load can be unfolded.
1104 unsigned LoadRegIndex;
1105 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001106 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001107 /*UnfoldLoad=*/true,
1108 /*UnfoldStore=*/false,
1109 &LoadRegIndex);
1110 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001111 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1112 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001113 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001114 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001115 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001116 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001117 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001118 unsigned Reg = MRI->createVirtualRegister(RC);
1119 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001120 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001121 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1122 NewMIs)) {
1123 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1124 return false;
1125 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001126 assert(NewMIs.size() == 2 &&
1127 "Unfolded a load into multiple instructions!");
1128 // The load was previously folded, so this is the only use.
1129 NewMIs[1]->addRegisterKilled(Reg, TRI);
1130
1131 // Tentatively insert the instructions into the block so that they
1132 // look "normal" to the transformation logic.
1133 mbbi->insert(mi, NewMIs[0]);
1134 mbbi->insert(mi, NewMIs[1]);
1135
1136 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1137 << "2addr: NEW INST: " << *NewMIs[1]);
1138
1139 // Transform the instruction, now that it no longer has a load.
1140 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1141 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1142 MachineBasicBlock::iterator NewMI = NewMIs[1];
1143 bool TransformSuccess =
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001144 tryInstructionTransform(NewMI, mi, mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001145 NewSrcIdx, NewDstIdx, Dist, Processed);
Dan Gohman584fedf2010-06-21 22:17:20 +00001146 if (TransformSuccess ||
1147 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1148 // Success, or at least we made an improvement. Keep the unfolded
1149 // instructions and discard the original.
1150 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001151 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1152 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001153 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001154 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1155 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001156 if (MO.isKill()) {
1157 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001158 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001159 else {
1160 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1161 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001162 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001163 }
1164 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001165 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001166 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1167 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1168 else {
1169 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1170 "Dead flag missing after load unfold!");
1171 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1172 }
1173 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001174 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001175 }
1176 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1177 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001178 MI.eraseFromParent();
Dan Gohman584fedf2010-06-21 22:17:20 +00001179 mi = NewMIs[1];
1180 if (TransformSuccess)
1181 return true;
1182 } else {
1183 // Transforming didn't eliminate the tie and didn't lead to an
1184 // improvement. Clean up the unfolded instructions and keep the
1185 // original.
1186 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1187 NewMIs[0]->eraseFromParent();
1188 NewMIs[1]->eraseFromParent();
1189 }
1190 }
1191 }
1192 }
1193
Bob Wilsoncc80df92009-09-03 20:58:42 +00001194 return false;
1195}
1196
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001197// Collect tied operands of MI that need to be handled.
1198// Rewrite trivial cases immediately.
1199// Return true if any tied operands where found, including the trivial ones.
1200bool TwoAddressInstructionPass::
1201collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1202 const MCInstrDesc &MCID = MI->getDesc();
1203 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001204 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001205
1206 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1207 unsigned DstIdx = 0;
1208 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1209 continue;
1210 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001211 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1212 MachineOperand &DstMO = MI->getOperand(DstIdx);
1213 unsigned SrcReg = SrcMO.getReg();
1214 unsigned DstReg = DstMO.getReg();
1215 // Tied constraint already satisfied?
1216 if (SrcReg == DstReg)
1217 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001218
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001219 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001220
1221 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001222 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001223 // Constrain the DstReg register class if required.
1224 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1225 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1226 TRI, *MF))
1227 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001228 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001229 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1230 continue;
1231 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001232 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001233 }
1234 return AnyOps;
1235}
1236
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001237// Process a list of tied MI operands that all use the same source register.
1238// The tied pairs are of the form (SrcIdx, DstIdx).
1239void
1240TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1241 TiedPairList &TiedPairs,
1242 unsigned &Dist) {
1243 bool IsEarlyClobber = false;
1244 bool RemovedKillFlag = false;
1245 bool AllUsesCopied = true;
1246 unsigned LastCopiedReg = 0;
1247 unsigned RegB = 0;
1248 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1249 unsigned SrcIdx = TiedPairs[tpi].first;
1250 unsigned DstIdx = TiedPairs[tpi].second;
1251
1252 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1253 unsigned RegA = DstMO.getReg();
1254 IsEarlyClobber |= DstMO.isEarlyClobber();
1255
1256 // Grab RegB from the instruction because it may have changed if the
1257 // instruction was commuted.
1258 RegB = MI->getOperand(SrcIdx).getReg();
1259
1260 if (RegA == RegB) {
1261 // The register is tied to multiple destinations (or else we would
1262 // not have continued this far), but this use of the register
1263 // already matches the tied destination. Leave it.
1264 AllUsesCopied = false;
1265 continue;
1266 }
1267 LastCopiedReg = RegA;
1268
1269 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1270 "cannot make instruction into two-address form");
1271
1272#ifndef NDEBUG
1273 // First, verify that we don't have a use of "a" in the instruction
1274 // (a = b + a for example) because our transformation will not
1275 // work. This should never occur because we are in SSA form.
1276 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1277 assert(i == DstIdx ||
1278 !MI->getOperand(i).isReg() ||
1279 MI->getOperand(i).getReg() != RegA);
1280#endif
1281
1282 // Emit a copy.
1283 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1284 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1285
1286 // Update DistanceMap.
1287 MachineBasicBlock::iterator PrevMI = MI;
1288 --PrevMI;
1289 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1290 DistanceMap[MI] = ++Dist;
1291
1292 SlotIndex CopyIdx;
1293 if (Indexes)
1294 CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1295
1296 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1297
1298 MachineOperand &MO = MI->getOperand(SrcIdx);
1299 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1300 "inconsistent operand info for 2-reg pass");
1301 if (MO.isKill()) {
1302 MO.setIsKill(false);
1303 RemovedKillFlag = true;
1304 }
1305
1306 // Make sure regA is a legal regclass for the SrcIdx operand.
1307 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1308 TargetRegisterInfo::isVirtualRegister(RegB))
1309 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1310
1311 MO.setReg(RegA);
1312
1313 // Propagate SrcRegMap.
1314 SrcRegMap[RegA] = RegB;
1315 }
1316
1317
1318 if (AllUsesCopied) {
1319 if (!IsEarlyClobber) {
1320 // Replace other (un-tied) uses of regB with LastCopiedReg.
1321 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1322 MachineOperand &MO = MI->getOperand(i);
1323 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1324 if (MO.isKill()) {
1325 MO.setIsKill(false);
1326 RemovedKillFlag = true;
1327 }
1328 MO.setReg(LastCopiedReg);
1329 }
1330 }
1331 }
1332
1333 // Update live variables for regB.
1334 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1335 MachineBasicBlock::iterator PrevMI = MI;
1336 --PrevMI;
1337 LV->addVirtualRegisterKilled(RegB, PrevMI);
1338 }
1339
1340 } else if (RemovedKillFlag) {
1341 // Some tied uses of regB matched their destination registers, so
1342 // regB is still used in this instruction, but a kill flag was
1343 // removed from a different tied use of regB, so now we need to add
1344 // a kill flag to one of the remaining uses of regB.
1345 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1346 MachineOperand &MO = MI->getOperand(i);
1347 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1348 MO.setIsKill(true);
1349 break;
1350 }
1351 }
1352 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001353}
1354
Bill Wendling637980e2008-05-10 00:12:52 +00001355/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001356///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001357bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1358 MF = &Func;
1359 const TargetMachine &TM = MF->getTarget();
1360 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001361 TII = TM.getInstrInfo();
1362 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001363 InstrItins = TM.getInstrItineraryData();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001364 Indexes = getAnalysisIfAvailable<SlotIndexes>();
Duncan Sands1465d612009-01-28 13:14:17 +00001365 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001366 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001367 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001368 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001369
Misha Brukman75fa4e42004-07-22 15:26:23 +00001370 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001371
David Greeneeb00b182010-01-05 01:24:21 +00001372 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001373 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001374 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001375
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001376 // This pass takes the function out of SSA form.
1377 MRI->leaveSSA();
1378
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001379 TiedOperandMap TiedOperands;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001380
Evan Cheng870b8072009-03-01 02:03:43 +00001381 SmallPtrSet<MachineInstr*, 8> Processed;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001382 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001383 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +00001384 unsigned Dist = 0;
1385 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001386 SrcRegMap.clear();
1387 DstRegMap.clear();
1388 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001389 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001390 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001391 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001392 if (mi->isDebugValue()) {
1393 mi = nmi;
1394 continue;
1395 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001396
Evan Cheng3d720fb2010-05-05 18:45:40 +00001397 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1398 if (mi->isRegSequence())
1399 RegSequences.push_back(&*mi);
1400
Evan Cheng7543e582008-06-18 07:49:14 +00001401 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001402
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001403 processCopy(&*mi, &*mbbi, Processed);
Evan Cheng870b8072009-03-01 02:03:43 +00001404
Bob Wilsoncc80df92009-09-03 20:58:42 +00001405 // First scan through all the tied register uses in this instruction
1406 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001407 if (!collectTiedOperands(mi, TiedOperands)) {
1408 mi = nmi;
1409 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001410 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001411
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001412 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001413 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001414 DEBUG(dbgs() << '\t' << *mi);
1415
Chandler Carruth32d75be2012-07-18 18:58:22 +00001416 // If the instruction has a single pair of tied operands, try some
1417 // transformations that may either eliminate the tied operands or
1418 // improve the opportunities for coalescing away the register copy.
1419 if (TiedOperands.size() == 1) {
1420 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1421 = TiedOperands.begin()->second;
1422 if (TiedPairs.size() == 1) {
1423 unsigned SrcIdx = TiedPairs[0].first;
1424 unsigned DstIdx = TiedPairs[0].second;
1425 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1426 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1427 if (SrcReg != DstReg &&
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001428 tryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
Chandler Carruth32d75be2012-07-18 18:58:22 +00001429 Processed)) {
1430 // The tied operands have been eliminated or shifted further down the
1431 // block to ease elimination. Continue processing with 'nmi'.
1432 TiedOperands.clear();
1433 mi = nmi;
1434 continue;
1435 }
1436 }
1437 }
1438
Bob Wilsoncc80df92009-09-03 20:58:42 +00001439 // Now iterate over the information collected above.
1440 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1441 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001442 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001443 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001444 }
Bill Wendling637980e2008-05-10 00:12:52 +00001445
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001446 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1447 if (mi->isInsertSubreg()) {
1448 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1449 // To %reg:subidx = COPY %subreg
1450 unsigned SubIdx = mi->getOperand(3).getImm();
1451 mi->RemoveOperand(3);
1452 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1453 mi->getOperand(0).setSubReg(SubIdx);
1454 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1455 mi->RemoveOperand(1);
1456 mi->setDesc(TII->get(TargetOpcode::COPY));
1457 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001458 }
1459
Bob Wilsoncc80df92009-09-03 20:58:42 +00001460 // Clear TiedOperands here instead of at the top of the loop
1461 // since most instructions do not have tied operands.
1462 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001463 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001464 }
1465 }
1466
Evan Cheng3d720fb2010-05-05 18:45:40 +00001467 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1468 // SSA form. It's now safe to de-SSA.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001469 MadeChange |= eliminateRegSequences();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001470
Misha Brukman75fa4e42004-07-22 15:26:23 +00001471 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001472}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001473
1474static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001475 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001476 MachineRegisterInfo *MRI,
1477 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001478 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001479 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001480 MachineOperand &MO = RI.getOperand();
1481 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001482 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001483 }
1484}
1485
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001486// Find the first def of Reg, assuming they are all in the same basic block.
1487static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1488 SmallPtrSet<MachineInstr*, 8> Defs;
1489 MachineInstr *First = 0;
1490 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1491 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1492 First = MI;
1493 if (!First)
1494 return 0;
1495
1496 MachineBasicBlock *MBB = First->getParent();
1497 MachineBasicBlock::iterator A = First, B = First;
1498 bool Moving;
1499 do {
1500 Moving = false;
1501 if (A != MBB->begin()) {
1502 Moving = true;
1503 --A;
1504 if (Defs.erase(A)) First = A;
1505 }
1506 if (B != MBB->end()) {
1507 Defs.erase(B);
1508 ++B;
1509 Moving = true;
1510 }
1511 } while (Moving && !Defs.empty());
1512 assert(Defs.empty() && "Instructions outside basic block!");
1513 return First;
1514}
1515
Evan Chengc6dcce32010-05-17 23:24:12 +00001516static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1517 MachineRegisterInfo *MRI) {
1518 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1519 UE = MRI->use_end(); UI != UE; ++UI) {
1520 MachineInstr *UseMI = &*UI;
1521 if (UseMI != RegSeq && UseMI->isRegSequence())
1522 return true;
1523 }
1524 return false;
1525}
1526
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001527/// eliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
Evan Cheng3d720fb2010-05-05 18:45:40 +00001528/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1529/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1530///
1531/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1532/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1533/// =>
1534/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001535bool TwoAddressInstructionPass::eliminateRegSequences() {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001536 if (RegSequences.empty())
1537 return false;
1538
1539 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1540 MachineInstr *MI = RegSequences[i];
1541 unsigned DstReg = MI->getOperand(0).getReg();
1542 if (MI->getOperand(0).getSubReg() ||
1543 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1544 !(MI->getNumOperands() & 1)) {
1545 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1546 llvm_unreachable(0);
1547 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001548
Evan Cheng44bfdd32010-05-17 22:09:49 +00001549 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001550 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001551 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001552 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001553 // Nothing needs to be inserted for <undef> operands.
1554 if (MI->getOperand(i).isUndef()) {
1555 MI->getOperand(i).setReg(0);
1556 continue;
1557 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001558 unsigned SrcReg = MI->getOperand(i).getReg();
Pete Cooperef74ca62012-04-04 21:03:25 +00001559 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
Bob Wilson495de3b2010-12-17 01:21:12 +00001560 unsigned SubIdx = MI->getOperand(i+1).getImm();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001561 // DefMI of NULL means the value does not have a vreg in this block
1562 // i.e., its a physical register or a subreg.
1563 // In either case we force a copy to be generated.
1564 MachineInstr *DefMI = NULL;
1565 if (!MI->getOperand(i).getSubReg() &&
1566 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
Manman Ren5f917cd2012-07-02 18:55:36 +00001567 DefMI = MRI->getUniqueVRegDef(SrcReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001568 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001569
Pete Coopercd7f02b2012-01-18 04:16:16 +00001570 if (DefMI && DefMI->isImplicitDef()) {
Evan Chengb990a2f2010-05-14 23:21:14 +00001571 DefMI->eraseFromParent();
1572 continue;
1573 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001574 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001575
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001576 // Remember COPY sources. These might be candidate for coalescing.
Pete Coopercd7f02b2012-01-18 04:16:16 +00001577 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
Evan Chengb990a2f2010-05-14 23:21:14 +00001578 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1579
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001580 bool isKill = MI->getOperand(i).isKill();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001581 if (!DefMI || !Seen.insert(SrcReg) ||
1582 MI->getParent() != DefMI->getParent() ||
Bob Wilson495de3b2010-12-17 01:21:12 +00001583 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1584 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1585 MRI->getRegClass(SrcReg), SubIdx)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001586 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001587 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001588 // to end up with a partial-redef of a livein, e.g.
1589 // BB0:
1590 // reg1051:10<def> =
1591 // ...
1592 // BB1:
1593 // ... = reg1051:10
1594 // BB2:
1595 // reg1051:9<def> =
1596 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001597 //
1598 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1599 // correctly up to date becomes very difficult. Insert a copy.
Jakob Stoklund Olesene4b9c4f2010-08-09 20:19:16 +00001600
1601 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1602 // might insert a COPY that uses SrcReg after is was killed.
1603 if (isKill)
1604 for (unsigned j = i + 2; j < e; j += 2)
1605 if (MI->getOperand(j).getReg() == SrcReg) {
1606 MI->getOperand(j).setIsKill();
1607 isKill = false;
1608 break;
1609 }
1610
Evan Cheng054dbb82010-05-13 00:00:35 +00001611 MachineBasicBlock::iterator InsertLoc = MI;
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001612 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1613 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
Bob Wilson495de3b2010-12-17 01:21:12 +00001614 .addReg(DstReg, RegState::Define, SubIdx)
Pete Cooperef74ca62012-04-04 21:03:25 +00001615 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001616 MI->getOperand(i).setReg(0);
Pete Coopercd7f02b2012-01-18 04:16:16 +00001617 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001618 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1619 DEBUG(dbgs() << "Inserted: " << *CopyMI);
Evan Cheng0bcccac2010-05-11 00:04:31 +00001620 }
1621 }
1622
1623 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1624 unsigned SrcReg = MI->getOperand(i).getReg();
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001625 if (!SrcReg) continue;
Evan Cheng53c779b2010-05-17 20:57:12 +00001626 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001627 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001628 }
1629
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001630 // Set <def,undef> flags on the first DstReg def in the basic block.
1631 // It marks the beginning of the live range. All the other defs are
1632 // read-modify-write.
1633 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1634 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1635 MachineOperand &MO = Def->getOperand(i);
1636 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1637 MO.setIsUndef();
1638 }
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001639 DEBUG(dbgs() << "First def: " << *Def);
1640 }
1641
Evan Cheng44bfdd32010-05-17 22:09:49 +00001642 if (IsImpDef) {
1643 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1644 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1645 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
Andrew Trick8247e0d2012-02-03 05:12:30 +00001646 MI->RemoveOperand(j);
Evan Cheng44bfdd32010-05-17 22:09:49 +00001647 } else {
1648 DEBUG(dbgs() << "Eliminated: " << *MI);
1649 MI->eraseFromParent();
1650 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001651 }
1652
Evan Chengfc6e6a92010-05-10 21:24:55 +00001653 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001654 return true;
1655}