blob: ddb465a77bc5eb0aa01279ad90ffeee441bdfee6 [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 Olesen0de4fd22012-10-26 23:05:10 +000075 // The current basic block being processed.
76 MachineBasicBlock *MBB;
77
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000078 // DistanceMap - Keep track the distance of a MI from the start of the
79 // current basic block.
80 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000081
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +000082 // Set of already processed instructions in the current block.
83 SmallPtrSet<MachineInstr*, 8> Processed;
84
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000085 // SrcRegMap - A map from virtual registers to physical registers which are
86 // likely targets to be coalesced to due to copies from physical registers to
87 // virtual registers. e.g. v1024 = move r0.
88 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000089
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000090 // DstRegMap - A map from virtual registers to physical registers which are
91 // likely targets to be coalesced to due to copies to physical registers from
92 // virtual registers. e.g. r1 = move v1024.
93 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000094
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000095 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
96 /// during the initial walk of the machine function.
97 SmallVector<MachineInstr*, 16> RegSequences;
Evan Cheng3d720fb2010-05-05 18:45:40 +000098
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000099 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000100 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +0000101
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000102 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengd498c8f2009-01-25 03:53:59 +0000103
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000104 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000105 MachineInstr *MI, unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000106
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000107 bool commuteInstruction(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000108 unsigned RegB, unsigned RegC, unsigned Dist);
Evan Cheng870b8072009-03-01 02:03:43 +0000109
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000110 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000111
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000112 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
113 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000114 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000115
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000116 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000117
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000118 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000119 MachineBasicBlock::iterator &nmi,
120 unsigned Reg);
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000121 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000122 MachineBasicBlock::iterator &nmi,
123 unsigned Reg);
124
125 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng2a4410d2011-11-14 19:48:55 +0000126 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000127 unsigned SrcIdx, unsigned DstIdx,
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +0000128 unsigned Dist);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000129
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000130 void scanUses(unsigned DstReg);
Evan Chengf06e6c22011-03-02 01:08:17 +0000131
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000132 void processCopy(MachineInstr *MI);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000133
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000134 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
135 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
136 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
137 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000138
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000139 /// eliminateRegSequences - Eliminate REG_SEQUENCE instructions as part of
140 /// the de-ssa process. This replaces sources of REG_SEQUENCE as sub-register
141 /// references of the register defined by REG_SEQUENCE.
142 bool eliminateRegSequences();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000143
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000144public:
145 static char ID; // Pass identification, replacement for typeid
146 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
147 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
148 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000149
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000150 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
151 AU.setPreservesCFG();
152 AU.addRequired<AliasAnalysis>();
153 AU.addPreserved<LiveVariables>();
154 AU.addPreserved<SlotIndexes>();
155 AU.addPreserved<LiveIntervals>();
156 AU.addPreservedID(MachineLoopInfoID);
157 AU.addPreservedID(MachineDominatorsID);
158 MachineFunctionPass::getAnalysisUsage(AU);
159 }
Devang Patel794fd752007-05-01 21:15:47 +0000160
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000161 /// runOnMachineFunction - Pass entry point.
162 bool runOnMachineFunction(MachineFunction&);
163};
164} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000165
Dan Gohman844731a2008-05-13 00:00:25 +0000166char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000167INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
168 "Two-Address instruction pass", false, false)
169INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000171 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000172
Owen Anderson90c579d2010-08-06 18:33:48 +0000173char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000174
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000175/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000176/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000177/// past the instruction that would kill the above mentioned register to reduce
178/// register pressure.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000179bool TwoAddressInstructionPass::
180sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
181 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000182 // FIXME: Shouldn't we be trying to do this before we three-addressify the
183 // instruction? After this transformation is done, we no longer need
184 // the instruction to be in three-address form.
185
Evan Cheng875357d2008-03-13 06:37:55 +0000186 // Check if it's safe to move this instruction.
187 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000188 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000189 return false;
190
191 unsigned DefReg = 0;
192 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000193
Evan Cheng875357d2008-03-13 06:37:55 +0000194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000196 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000197 continue;
198 unsigned MOReg = MO.getReg();
199 if (!MOReg)
200 continue;
201 if (MO.isUse() && MOReg != SavedReg)
202 UseRegs.insert(MO.getReg());
203 if (!MO.isDef())
204 continue;
205 if (MO.isImplicit())
206 // Don't try to move it if it implicitly defines a register.
207 return false;
208 if (DefReg)
209 // For now, don't move any instructions that define multiple registers.
210 return false;
211 DefReg = MO.getReg();
212 }
213
214 // Find the instruction that kills SavedReg.
215 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000216 for (MachineRegisterInfo::use_nodbg_iterator
217 UI = MRI->use_nodbg_begin(SavedReg),
218 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000219 MachineOperand &UseMO = UI.getOperand();
220 if (!UseMO.isKill())
221 continue;
222 KillMI = UseMO.getParent();
223 break;
224 }
Bill Wendling637980e2008-05-10 00:12:52 +0000225
Eli Friedmanbde81d52011-09-23 22:41:57 +0000226 // If we find the instruction that kills SavedReg, and it is in an
227 // appropriate location, we can try to sink the current instruction
228 // past it.
229 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000230 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000231 return false;
232
Bill Wendling637980e2008-05-10 00:12:52 +0000233 // If any of the definitions are used by another instruction between the
234 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000235 //
Bill Wendling637980e2008-05-10 00:12:52 +0000236 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000237 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000238 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000239 MachineOperand *KillMO = NULL;
240 MachineBasicBlock::iterator KillPos = KillMI;
241 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000242
Evan Cheng7543e582008-06-18 07:49:14 +0000243 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000244 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000245 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000246 // DBG_VALUE cannot be counted against the limit.
247 if (OtherMI->isDebugValue())
248 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000249 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
250 return false;
251 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000252 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
253 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000254 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000255 continue;
256 unsigned MOReg = MO.getReg();
257 if (!MOReg)
258 continue;
259 if (DefReg == MOReg)
260 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000261
Evan Cheng875357d2008-03-13 06:37:55 +0000262 if (MO.isKill()) {
263 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000264 // Save the operand that kills the register. We want to unset the kill
265 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000266 KillMO = &MO;
267 else if (UseRegs.count(MOReg))
268 // One of the uses is killed before the destination.
269 return false;
270 }
271 }
272 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000273 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000274
Evan Cheng875357d2008-03-13 06:37:55 +0000275 // Update kill and LV information.
276 KillMO->setIsKill(false);
277 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
278 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000279
Evan Cheng9f1c8312008-07-03 09:09:37 +0000280 if (LV)
281 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000282
283 // Move instruction to its destination.
284 MBB->remove(MI);
285 MBB->insert(KillPos, MI);
286
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000287 if (LIS)
288 LIS->handleMove(MI);
289
Evan Cheng875357d2008-03-13 06:37:55 +0000290 ++Num3AddrSunk;
291 return true;
292}
293
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000294/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000295/// last instruction in the MBB that defines the specified register and the
296/// two-address instruction which is being processed. It also returns the last
297/// def location by reference
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000298bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000299 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000300 LastDef = 0;
301 unsigned LastUse = Dist;
302 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
303 E = MRI->reg_end(); I != E; ++I) {
304 MachineOperand &MO = I.getOperand();
305 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000306 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000307 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000308 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
309 if (DI == DistanceMap.end())
310 continue;
311 if (MO.isUse() && DI->second < LastUse)
312 LastUse = DI->second;
313 if (MO.isDef() && DI->second > LastDef)
314 LastDef = DI->second;
315 }
316
317 return !(LastUse > LastDef && LastUse < Dist);
318}
319
Evan Cheng870b8072009-03-01 02:03:43 +0000320/// isCopyToReg - Return true if the specified MI is a copy instruction or
321/// a extract_subreg instruction. It also returns the source and destination
322/// registers and whether they are physical registers by reference.
323static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
324 unsigned &SrcReg, unsigned &DstReg,
325 bool &IsSrcPhys, bool &IsDstPhys) {
326 SrcReg = 0;
327 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000328 if (MI.isCopy()) {
329 DstReg = MI.getOperand(0).getReg();
330 SrcReg = MI.getOperand(1).getReg();
331 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
332 DstReg = MI.getOperand(0).getReg();
333 SrcReg = MI.getOperand(2).getReg();
334 } else
335 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000336
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000337 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
338 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
339 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000340}
341
Dan Gohman97121ba2009-04-08 00:15:30 +0000342/// isKilled - Test if the given register value, which is used by the given
343/// instruction, is killed by the given instruction. This looks through
344/// coalescable copies to see if the original value is potentially not killed.
345///
346/// For example, in this code:
347///
348/// %reg1034 = copy %reg1024
349/// %reg1035 = copy %reg1025<kill>
350/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
351///
352/// %reg1034 is not considered to be killed, since it is copied from a
353/// register which is not killed. Treating it as not killed lets the
354/// normal heuristics commute the (two-address) add, which lets
355/// coalescing eliminate the extra copy.
356///
357static bool isKilled(MachineInstr &MI, unsigned Reg,
358 const MachineRegisterInfo *MRI,
359 const TargetInstrInfo *TII) {
360 MachineInstr *DefMI = &MI;
361 for (;;) {
362 if (!DefMI->killsRegister(Reg))
363 return false;
364 if (TargetRegisterInfo::isPhysicalRegister(Reg))
365 return true;
366 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
367 // If there are multiple defs, we can't do a simple analysis, so just
368 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000369 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000370 return true;
371 DefMI = &*Begin;
372 bool IsSrcPhys, IsDstPhys;
373 unsigned SrcReg, DstReg;
374 // If the def is something other than a copy, then it isn't going to
375 // be coalesced, so follow the kill flag.
376 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
377 return true;
378 Reg = SrcReg;
379 }
380}
381
Evan Cheng870b8072009-03-01 02:03:43 +0000382/// isTwoAddrUse - Return true if the specified MI uses the specified register
383/// as a two-address use. If so, return the destination register by reference.
384static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000385 const MCInstrDesc &MCID = MI.getDesc();
386 unsigned NumOps = MI.isInlineAsm()
387 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000388 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000389 const MachineOperand &MO = MI.getOperand(i);
390 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
391 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000392 unsigned ti;
393 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000394 DstReg = MI.getOperand(ti).getReg();
395 return true;
396 }
397 }
398 return false;
399}
400
401/// findOnlyInterestingUse - Given a register, if has a single in-basic block
402/// use, return the use instruction if it's a copy or a two-address use.
403static
404MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
405 MachineRegisterInfo *MRI,
406 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000407 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000408 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000409 if (!MRI->hasOneNonDBGUse(Reg))
410 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000411 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000412 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000413 if (UseMI.getParent() != MBB)
414 return 0;
415 unsigned SrcReg;
416 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000417 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
418 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000419 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000420 }
Evan Cheng870b8072009-03-01 02:03:43 +0000421 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000422 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
423 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000424 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000425 }
Evan Cheng870b8072009-03-01 02:03:43 +0000426 return 0;
427}
428
429/// getMappedReg - Return the physical register the specified virtual register
430/// might be mapped to.
431static unsigned
432getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
433 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
434 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
435 if (SI == RegMap.end())
436 return 0;
437 Reg = SI->second;
438 }
439 if (TargetRegisterInfo::isPhysicalRegister(Reg))
440 return Reg;
441 return 0;
442}
443
444/// regsAreCompatible - Return true if the two registers are equal or aliased.
445///
446static bool
447regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
448 if (RegA == RegB)
449 return true;
450 if (!RegA || !RegB)
451 return false;
452 return TRI->regsOverlap(RegA, RegB);
453}
454
455
Manman Rend68e8cd2012-07-25 18:28:13 +0000456/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000457/// the two-address instruction that's being processed.
458bool
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000459TwoAddressInstructionPass::
460isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
461 MachineInstr *MI, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000462 if (OptLevel == CodeGenOpt::None)
463 return false;
464
Evan Chengd498c8f2009-01-25 03:53:59 +0000465 // Determine if it's profitable to commute this two address instruction. In
466 // general, we want no uses between this instruction and the definition of
467 // the two-address register.
468 // e.g.
469 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
470 // %reg1029<def> = MOV8rr %reg1028
471 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
472 // insert => %reg1030<def> = MOV8rr %reg1028
473 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
474 // In this case, it might not be possible to coalesce the second MOV8rr
475 // instruction if the first one is coalesced. So it would be profitable to
476 // commute it:
477 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
478 // %reg1029<def> = MOV8rr %reg1028
479 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
480 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000481 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000482
483 if (!MI->killsRegister(regC))
484 return false;
485
486 // Ok, we have something like:
487 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
488 // let's see if it's worth commuting it.
489
Evan Cheng870b8072009-03-01 02:03:43 +0000490 // Look for situations like this:
491 // %reg1024<def> = MOV r1
492 // %reg1025<def> = MOV r0
493 // %reg1026<def> = ADD %reg1024, %reg1025
494 // r0 = MOV %reg1026
495 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000496 unsigned ToRegA = getMappedReg(regA, DstRegMap);
497 if (ToRegA) {
498 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
499 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
500 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
501 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
502 if (BComp != CComp)
503 return !BComp && CComp;
504 }
Evan Cheng870b8072009-03-01 02:03:43 +0000505
Evan Chengd498c8f2009-01-25 03:53:59 +0000506 // If there is a use of regC between its last def (could be livein) and this
507 // instruction, then bail.
508 unsigned LastDefC = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000509 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000510 return false;
511
512 // If there is a use of regB between its last def (could be livein) and this
513 // instruction, then go ahead and make this transformation.
514 unsigned LastDefB = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000515 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000516 return true;
517
518 // Since there are no intervening uses for both registers, then commute
519 // if the def of regC is closer. Its live interval is shorter.
520 return LastDefB && LastDefC && LastDefC > LastDefB;
521}
522
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000523/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000524/// block, distance map, and live variables if needed. Return true if it is
525/// successful.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000526bool TwoAddressInstructionPass::
527commuteInstruction(MachineBasicBlock::iterator &mi,
528 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000529 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000530 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000531 MachineInstr *NewMI = TII->commuteInstruction(MI);
532
533 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000534 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000535 return false;
536 }
537
David Greeneeb00b182010-01-05 01:24:21 +0000538 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000539 // If the instruction changed to commute it, update livevar.
540 if (NewMI != MI) {
541 if (LV)
542 // Update live variables
543 LV->replaceKillInstruction(RegC, MI, NewMI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000544 if (Indexes)
545 Indexes->replaceMachineInstrInMaps(MI, NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000546
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000547 MBB->insert(mi, NewMI); // Insert the new inst
548 MBB->erase(mi); // Nuke the old inst.
Evan Cheng81913712009-01-23 23:27:33 +0000549 mi = NewMI;
550 DistanceMap.insert(std::make_pair(NewMI, Dist));
551 }
Evan Cheng870b8072009-03-01 02:03:43 +0000552
553 // Update source register map.
554 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
555 if (FromRegC) {
556 unsigned RegA = MI->getOperand(0).getReg();
557 SrcRegMap[RegA] = FromRegC;
558 }
559
Evan Cheng81913712009-01-23 23:27:33 +0000560 return true;
561}
562
Evan Chenge6f350d2009-03-30 21:34:07 +0000563/// isProfitableToConv3Addr - Return true if it is profitable to convert the
564/// given 2-address instruction to a 3-address one.
565bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000566TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000567 // Look for situations like this:
568 // %reg1024<def> = MOV r1
569 // %reg1025<def> = MOV r0
570 // %reg1026<def> = ADD %reg1024, %reg1025
571 // r2 = MOV %reg1026
572 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000573 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
574 if (!FromRegB)
575 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000576 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000577 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000578}
579
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000580/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000581/// three address one. Return true if this transformation was successful.
582bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000583TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000584 MachineBasicBlock::iterator &nmi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000585 unsigned RegA, unsigned RegB,
586 unsigned Dist) {
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000587 // FIXME: Why does convertToThreeAddress() need an iterator reference?
588 MachineFunction::iterator MFI = MBB;
589 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
590 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Evan Chenge6f350d2009-03-30 21:34:07 +0000591 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000592 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
593 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000594 bool Sunk = false;
595
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000596 if (Indexes)
597 Indexes->replaceMachineInstrInMaps(mi, NewMI);
598
Evan Chenge6f350d2009-03-30 21:34:07 +0000599 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
600 // FIXME: Temporary workaround. If the new instruction doesn't
601 // uses RegB, convertToThreeAddress must have created more
602 // then one instruction.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000603 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000604
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000605 MBB->erase(mi); // Nuke the old inst.
Evan Chenge6f350d2009-03-30 21:34:07 +0000606
607 if (!Sunk) {
608 DistanceMap.insert(std::make_pair(NewMI, Dist));
609 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000610 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000611 }
Evan Cheng4d96c632011-02-10 02:20:55 +0000612
613 // Update source and destination register maps.
614 SrcRegMap.erase(RegA);
615 DstRegMap.erase(RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000616 return true;
617 }
618
619 return false;
620}
621
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000622/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000623/// is a copy or a two-address instruction.
624void
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000625TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Chengf06e6c22011-03-02 01:08:17 +0000626 SmallVector<unsigned, 4> VirtRegPairs;
627 bool IsDstPhys;
628 bool IsCopy = false;
629 unsigned NewReg = 0;
630 unsigned Reg = DstReg;
631 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
632 NewReg, IsDstPhys)) {
633 if (IsCopy && !Processed.insert(UseMI))
634 break;
635
636 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
637 if (DI != DistanceMap.end())
638 // Earlier in the same MBB.Reached via a back edge.
639 break;
640
641 if (IsDstPhys) {
642 VirtRegPairs.push_back(NewReg);
643 break;
644 }
645 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
646 if (!isNew)
647 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
648 VirtRegPairs.push_back(NewReg);
649 Reg = NewReg;
650 }
651
652 if (!VirtRegPairs.empty()) {
653 unsigned ToReg = VirtRegPairs.back();
654 VirtRegPairs.pop_back();
655 while (!VirtRegPairs.empty()) {
656 unsigned FromReg = VirtRegPairs.back();
657 VirtRegPairs.pop_back();
658 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
659 if (!isNew)
660 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
661 ToReg = FromReg;
662 }
663 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
664 if (!isNew)
665 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
666 }
667}
668
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000669/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000670/// if it's a copy. For a copy instruction, we find the physical registers the
671/// source and destination registers might be mapped to. These are kept in
672/// point-to maps used to determine future optimizations. e.g.
673/// v1024 = mov r0
674/// v1025 = mov r1
675/// v1026 = add v1024, v1025
676/// r1 = mov r1026
677/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
678/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
679/// potentially joined with r1 on the output side. It's worthwhile to commute
680/// 'add' to eliminate a copy.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000681void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Cheng870b8072009-03-01 02:03:43 +0000682 if (Processed.count(MI))
683 return;
684
685 bool IsSrcPhys, IsDstPhys;
686 unsigned SrcReg, DstReg;
687 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
688 return;
689
690 if (IsDstPhys && !IsSrcPhys)
691 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
692 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000693 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
694 if (!isNew)
695 assert(SrcRegMap[DstReg] == SrcReg &&
696 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000697
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000698 scanUses(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000699 }
700
701 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000702 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000703}
704
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000705/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000706/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
707/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000708bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000709rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000710 MachineBasicBlock::iterator &nmi,
711 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000712 // Bail immediately if we don't have LV available. We use it to find kills
713 // efficiently.
714 if (!LV)
715 return false;
716
Evan Cheng2a4410d2011-11-14 19:48:55 +0000717 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000718 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000719 if (DI == DistanceMap.end())
720 // Must be created from unfolded load. Don't waste time trying this.
721 return false;
722
Chandler Carruth7d532c82012-07-15 03:29:46 +0000723 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
724 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000725 // Don't mess with copies, they may be coalesced later.
726 return false;
727
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000728 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
729 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000730 // Don't move pass calls, etc.
731 return false;
732
733 unsigned DstReg;
734 if (isTwoAddrUse(*KillMI, Reg, DstReg))
735 return false;
736
Evan Chengf1784182011-11-15 06:26:51 +0000737 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000738 if (!MI->isSafeToMove(TII, AA, SeenStore))
739 return false;
740
741 if (TII->getInstrLatency(InstrItins, MI) > 1)
742 // FIXME: Needs more sophisticated heuristics.
743 return false;
744
745 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000746 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000747 SmallSet<unsigned, 2> Defs;
748 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
749 const MachineOperand &MO = MI->getOperand(i);
750 if (!MO.isReg())
751 continue;
752 unsigned MOReg = MO.getReg();
753 if (!MOReg)
754 continue;
755 if (MO.isDef())
756 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000757 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000758 Uses.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000759 if (MO.isKill() && MOReg != Reg)
760 Kills.insert(MOReg);
761 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000762 }
763
764 // Move the copies connected to MI down as well.
765 MachineBasicBlock::iterator From = MI;
766 MachineBasicBlock::iterator To = llvm::next(From);
767 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
768 Defs.insert(To->getOperand(0).getReg());
769 ++To;
770 }
771
772 // Check if the reschedule will not break depedencies.
773 unsigned NumVisited = 0;
774 MachineBasicBlock::iterator KillPos = KillMI;
775 ++KillPos;
776 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
777 MachineInstr *OtherMI = I;
778 // DBG_VALUE cannot be counted against the limit.
779 if (OtherMI->isDebugValue())
780 continue;
781 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
782 return false;
783 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000784 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
785 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000786 // Don't move pass calls, etc.
787 return false;
788 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
789 const MachineOperand &MO = OtherMI->getOperand(i);
790 if (!MO.isReg())
791 continue;
792 unsigned MOReg = MO.getReg();
793 if (!MOReg)
794 continue;
795 if (MO.isDef()) {
796 if (Uses.count(MOReg))
797 // Physical register use would be clobbered.
798 return false;
799 if (!MO.isDead() && Defs.count(MOReg))
800 // May clobber a physical register def.
801 // FIXME: This may be too conservative. It's ok if the instruction
802 // is sunken completely below the use.
803 return false;
804 } else {
805 if (Defs.count(MOReg))
806 return false;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000807 if (MOReg != Reg &&
808 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000809 // Don't want to extend other live ranges and update kills.
810 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000811 if (MOReg == Reg && !MO.isKill())
812 // We can't schedule across a use of the register in question.
813 return false;
814 // Ensure that if this is register in question, its the kill we expect.
815 assert((MOReg != Reg || OtherMI == KillMI) &&
816 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000817 }
818 }
819 }
820
821 // Move debug info as well.
Evan Cheng8aee7d82011-11-14 21:11:15 +0000822 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
823 --From;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000824
825 // Copies following MI may have been moved as well.
826 nmi = To;
827 MBB->splice(KillPos, MBB, From, To);
828 DistanceMap.erase(DI);
829
Chandler Carruth7d532c82012-07-15 03:29:46 +0000830 // Update live variables
831 LV->removeVirtualRegisterKilled(Reg, KillMI);
832 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000833 if (LIS)
834 LIS->handleMove(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000835
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000836 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000837 return true;
838}
839
840/// isDefTooClose - Return true if the re-scheduling will put the given
841/// instruction too close to the defs of its register dependencies.
842bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000843 MachineInstr *MI) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000844 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
845 DE = MRI->def_end(); DI != DE; ++DI) {
846 MachineInstr *DefMI = &*DI;
847 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
848 continue;
849 if (DefMI == MI)
850 return true; // MI is defining something KillMI uses
851 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
852 if (DDI == DistanceMap.end())
853 return true; // Below MI
854 unsigned DefDist = DDI->second;
855 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000856 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000857 return true;
858 }
859 return false;
860}
861
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000862/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000863/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
864/// current two-address instruction in order to eliminate the need for the
865/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000866bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000867rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000868 MachineBasicBlock::iterator &nmi,
869 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000870 // Bail immediately if we don't have LV available. We use it to find kills
871 // efficiently.
872 if (!LV)
873 return false;
874
Evan Cheng2a4410d2011-11-14 19:48:55 +0000875 MachineInstr *MI = &*mi;
876 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
877 if (DI == DistanceMap.end())
878 // Must be created from unfolded load. Don't waste time trying this.
879 return false;
880
Chandler Carruth7d532c82012-07-15 03:29:46 +0000881 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
882 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000883 // Don't mess with copies, they may be coalesced later.
884 return false;
885
886 unsigned DstReg;
887 if (isTwoAddrUse(*KillMI, Reg, DstReg))
888 return false;
889
Evan Chengf1784182011-11-15 06:26:51 +0000890 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000891 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
892 return false;
893
894 SmallSet<unsigned, 2> Uses;
895 SmallSet<unsigned, 2> Kills;
896 SmallSet<unsigned, 2> Defs;
897 SmallSet<unsigned, 2> LiveDefs;
898 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
899 const MachineOperand &MO = KillMI->getOperand(i);
900 if (!MO.isReg())
901 continue;
902 unsigned MOReg = MO.getReg();
903 if (MO.isUse()) {
904 if (!MOReg)
905 continue;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000906 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000907 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000908 if (MOReg == Reg && !MO.isKill())
909 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000910 Uses.insert(MOReg);
911 if (MO.isKill() && MOReg != Reg)
912 Kills.insert(MOReg);
913 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
914 Defs.insert(MOReg);
915 if (!MO.isDead())
916 LiveDefs.insert(MOReg);
917 }
918 }
919
920 // Check if the reschedule will not break depedencies.
921 unsigned NumVisited = 0;
922 MachineBasicBlock::iterator KillPos = KillMI;
923 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
924 MachineInstr *OtherMI = I;
925 // DBG_VALUE cannot be counted against the limit.
926 if (OtherMI->isDebugValue())
927 continue;
928 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
929 return false;
930 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000931 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
932 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000933 // Don't move pass calls, etc.
934 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +0000935 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000936 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
937 const MachineOperand &MO = OtherMI->getOperand(i);
938 if (!MO.isReg())
939 continue;
940 unsigned MOReg = MO.getReg();
941 if (!MOReg)
942 continue;
943 if (MO.isUse()) {
944 if (Defs.count(MOReg))
945 // Moving KillMI can clobber the physical register if the def has
946 // not been seen.
947 return false;
948 if (Kills.count(MOReg))
949 // Don't want to extend other live ranges and update kills.
950 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000951 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
952 // We can't schedule across a use of the register in question.
953 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000954 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +0000955 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000956 }
957 }
Evan Chengae7db7a2011-11-16 03:05:12 +0000958
959 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
960 unsigned MOReg = OtherDefs[i];
961 if (Uses.count(MOReg))
962 return false;
963 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
964 LiveDefs.count(MOReg))
965 return false;
966 // Physical register def is seen.
967 Defs.erase(MOReg);
968 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000969 }
970
971 // Move the old kill above MI, don't forget to move debug info as well.
972 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +0000973 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
974 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000975 MachineBasicBlock::iterator From = KillMI;
976 MachineBasicBlock::iterator To = llvm::next(From);
977 while (llvm::prior(From)->isDebugValue())
978 --From;
979 MBB->splice(InsertPos, MBB, From, To);
980
Evan Cheng2bee6a82011-11-16 03:33:08 +0000981 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +0000982 DistanceMap.erase(DI);
983
Chandler Carruth7d532c82012-07-15 03:29:46 +0000984 // Update live variables
985 LV->removeVirtualRegisterKilled(Reg, KillMI);
986 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000987 if (LIS)
988 LIS->handleMove(KillMI);
Chandler Carruth7d532c82012-07-15 03:29:46 +0000989
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000990 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000991 return true;
992}
993
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000994/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +0000995/// pair of tied register operands, attempt some transformations that may
996/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +0000997/// coalescing away the register copy. Returns true if no copy needs to be
998/// inserted to untie mi's operands (either because they were untied, or
999/// because mi was rescheduled, and will be visited again later).
Bob Wilsoncc80df92009-09-03 20:58:42 +00001000bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001001tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001002 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +00001003 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001004 if (OptLevel == CodeGenOpt::None)
1005 return false;
1006
Evan Cheng2a4410d2011-11-14 19:48:55 +00001007 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001008 unsigned regA = MI.getOperand(DstIdx).getReg();
1009 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001010
1011 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1012 "cannot make instruction into two-address form");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001013 bool regBKilled = isKilled(MI, regB, MRI, TII);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001014
Evan Chengd99d68b2012-05-03 01:45:13 +00001015 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001016 scanUses(regA);
Evan Chengd99d68b2012-05-03 01:45:13 +00001017
Bob Wilsoncc80df92009-09-03 20:58:42 +00001018 // Check if it is profitable to commute the operands.
1019 unsigned SrcOp1, SrcOp2;
1020 unsigned regC = 0;
1021 unsigned regCIdx = ~0U;
1022 bool TryCommute = false;
1023 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001024 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001025 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001026 if (SrcIdx == SrcOp1)
1027 regCIdx = SrcOp2;
1028 else if (SrcIdx == SrcOp2)
1029 regCIdx = SrcOp1;
1030
1031 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001032 regC = MI.getOperand(regCIdx).getReg();
1033 if (!regBKilled && isKilled(MI, regC, MRI, TII))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001034 // If C dies but B does not, swap the B and C operands.
1035 // This makes the live ranges of A and C joinable.
1036 TryCommute = true;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001037 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001038 TryCommute = true;
1039 AggressiveCommute = true;
1040 }
1041 }
1042 }
1043
1044 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001045 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001046 ++NumCommuted;
1047 if (AggressiveCommute)
1048 ++NumAggrCommuted;
1049 return false;
1050 }
1051
Evan Cheng2a4410d2011-11-14 19:48:55 +00001052 // If there is one more use of regB later in the same MBB, consider
1053 // re-schedule this MI below it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001054 if (rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001055 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001056 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001057 }
1058
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001059 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001060 // This instruction is potentially convertible to a true
1061 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001062 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001063 // Try to convert it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001064 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001065 ++NumConvertedTo3Addr;
1066 return true; // Done with this instruction.
1067 }
1068 }
1069 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001070
Evan Cheng2a4410d2011-11-14 19:48:55 +00001071 // If there is one more use of regB later in the same MBB, consider
1072 // re-schedule it before this MI if it's legal.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001073 if (rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001074 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001075 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001076 }
1077
Dan Gohman584fedf2010-06-21 22:17:20 +00001078 // If this is an instruction with a load folded into it, try unfolding
1079 // the load, e.g. avoid this:
1080 // movq %rdx, %rcx
1081 // addq (%rax), %rcx
1082 // in favor of this:
1083 // movq (%rax), %rcx
1084 // addq %rdx, %rcx
1085 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001086 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001087 // Determine if a load can be unfolded.
1088 unsigned LoadRegIndex;
1089 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001090 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001091 /*UnfoldLoad=*/true,
1092 /*UnfoldStore=*/false,
1093 &LoadRegIndex);
1094 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001095 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1096 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001097 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001098 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001099 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001100 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001101 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001102 unsigned Reg = MRI->createVirtualRegister(RC);
1103 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001104 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001105 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1106 NewMIs)) {
1107 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1108 return false;
1109 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001110 assert(NewMIs.size() == 2 &&
1111 "Unfolded a load into multiple instructions!");
1112 // The load was previously folded, so this is the only use.
1113 NewMIs[1]->addRegisterKilled(Reg, TRI);
1114
1115 // Tentatively insert the instructions into the block so that they
1116 // look "normal" to the transformation logic.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001117 MBB->insert(mi, NewMIs[0]);
1118 MBB->insert(mi, NewMIs[1]);
Dan Gohman584fedf2010-06-21 22:17:20 +00001119
1120 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1121 << "2addr: NEW INST: " << *NewMIs[1]);
1122
1123 // Transform the instruction, now that it no longer has a load.
1124 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1125 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1126 MachineBasicBlock::iterator NewMI = NewMIs[1];
1127 bool TransformSuccess =
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001128 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist);
Dan Gohman584fedf2010-06-21 22:17:20 +00001129 if (TransformSuccess ||
1130 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1131 // Success, or at least we made an improvement. Keep the unfolded
1132 // instructions and discard the original.
1133 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001134 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1135 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001136 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001137 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1138 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001139 if (MO.isKill()) {
1140 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001141 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001142 else {
1143 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1144 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001145 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001146 }
1147 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001148 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001149 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1150 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1151 else {
1152 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1153 "Dead flag missing after load unfold!");
1154 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1155 }
1156 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001157 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001158 }
1159 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1160 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001161 MI.eraseFromParent();
Dan Gohman584fedf2010-06-21 22:17:20 +00001162 mi = NewMIs[1];
1163 if (TransformSuccess)
1164 return true;
1165 } else {
1166 // Transforming didn't eliminate the tie and didn't lead to an
1167 // improvement. Clean up the unfolded instructions and keep the
1168 // original.
1169 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1170 NewMIs[0]->eraseFromParent();
1171 NewMIs[1]->eraseFromParent();
1172 }
1173 }
1174 }
1175 }
1176
Bob Wilsoncc80df92009-09-03 20:58:42 +00001177 return false;
1178}
1179
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001180// Collect tied operands of MI that need to be handled.
1181// Rewrite trivial cases immediately.
1182// Return true if any tied operands where found, including the trivial ones.
1183bool TwoAddressInstructionPass::
1184collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1185 const MCInstrDesc &MCID = MI->getDesc();
1186 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001187 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001188
1189 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1190 unsigned DstIdx = 0;
1191 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1192 continue;
1193 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001194 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1195 MachineOperand &DstMO = MI->getOperand(DstIdx);
1196 unsigned SrcReg = SrcMO.getReg();
1197 unsigned DstReg = DstMO.getReg();
1198 // Tied constraint already satisfied?
1199 if (SrcReg == DstReg)
1200 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001201
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001202 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001203
1204 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001205 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001206 // Constrain the DstReg register class if required.
1207 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1208 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1209 TRI, *MF))
1210 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001211 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001212 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1213 continue;
1214 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001215 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001216 }
1217 return AnyOps;
1218}
1219
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001220// Process a list of tied MI operands that all use the same source register.
1221// The tied pairs are of the form (SrcIdx, DstIdx).
1222void
1223TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1224 TiedPairList &TiedPairs,
1225 unsigned &Dist) {
1226 bool IsEarlyClobber = false;
1227 bool RemovedKillFlag = false;
1228 bool AllUsesCopied = true;
1229 unsigned LastCopiedReg = 0;
1230 unsigned RegB = 0;
1231 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1232 unsigned SrcIdx = TiedPairs[tpi].first;
1233 unsigned DstIdx = TiedPairs[tpi].second;
1234
1235 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1236 unsigned RegA = DstMO.getReg();
1237 IsEarlyClobber |= DstMO.isEarlyClobber();
1238
1239 // Grab RegB from the instruction because it may have changed if the
1240 // instruction was commuted.
1241 RegB = MI->getOperand(SrcIdx).getReg();
1242
1243 if (RegA == RegB) {
1244 // The register is tied to multiple destinations (or else we would
1245 // not have continued this far), but this use of the register
1246 // already matches the tied destination. Leave it.
1247 AllUsesCopied = false;
1248 continue;
1249 }
1250 LastCopiedReg = RegA;
1251
1252 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1253 "cannot make instruction into two-address form");
1254
1255#ifndef NDEBUG
1256 // First, verify that we don't have a use of "a" in the instruction
1257 // (a = b + a for example) because our transformation will not
1258 // work. This should never occur because we are in SSA form.
1259 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1260 assert(i == DstIdx ||
1261 !MI->getOperand(i).isReg() ||
1262 MI->getOperand(i).getReg() != RegA);
1263#endif
1264
1265 // Emit a copy.
1266 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1267 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1268
1269 // Update DistanceMap.
1270 MachineBasicBlock::iterator PrevMI = MI;
1271 --PrevMI;
1272 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1273 DistanceMap[MI] = ++Dist;
1274
1275 SlotIndex CopyIdx;
1276 if (Indexes)
1277 CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1278
1279 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1280
1281 MachineOperand &MO = MI->getOperand(SrcIdx);
1282 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1283 "inconsistent operand info for 2-reg pass");
1284 if (MO.isKill()) {
1285 MO.setIsKill(false);
1286 RemovedKillFlag = true;
1287 }
1288
1289 // Make sure regA is a legal regclass for the SrcIdx operand.
1290 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1291 TargetRegisterInfo::isVirtualRegister(RegB))
1292 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1293
1294 MO.setReg(RegA);
1295
1296 // Propagate SrcRegMap.
1297 SrcRegMap[RegA] = RegB;
1298 }
1299
1300
1301 if (AllUsesCopied) {
1302 if (!IsEarlyClobber) {
1303 // Replace other (un-tied) uses of regB with LastCopiedReg.
1304 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1305 MachineOperand &MO = MI->getOperand(i);
1306 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1307 if (MO.isKill()) {
1308 MO.setIsKill(false);
1309 RemovedKillFlag = true;
1310 }
1311 MO.setReg(LastCopiedReg);
1312 }
1313 }
1314 }
1315
1316 // Update live variables for regB.
1317 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1318 MachineBasicBlock::iterator PrevMI = MI;
1319 --PrevMI;
1320 LV->addVirtualRegisterKilled(RegB, PrevMI);
1321 }
1322
1323 } else if (RemovedKillFlag) {
1324 // Some tied uses of regB matched their destination registers, so
1325 // regB is still used in this instruction, but a kill flag was
1326 // removed from a different tied use of regB, so now we need to add
1327 // a kill flag to one of the remaining uses of regB.
1328 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1329 MachineOperand &MO = MI->getOperand(i);
1330 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1331 MO.setIsKill(true);
1332 break;
1333 }
1334 }
1335 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001336}
1337
Bill Wendling637980e2008-05-10 00:12:52 +00001338/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001339///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001340bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1341 MF = &Func;
1342 const TargetMachine &TM = MF->getTarget();
1343 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001344 TII = TM.getInstrInfo();
1345 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001346 InstrItins = TM.getInstrItineraryData();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001347 Indexes = getAnalysisIfAvailable<SlotIndexes>();
Duncan Sands1465d612009-01-28 13:14:17 +00001348 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001349 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001350 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001351 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001352
Misha Brukman75fa4e42004-07-22 15:26:23 +00001353 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001354
David Greeneeb00b182010-01-05 01:24:21 +00001355 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001356 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001357 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001358
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001359 // This pass takes the function out of SSA form.
1360 MRI->leaveSSA();
1361
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001362 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001363 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1364 MBBI != MBBE; ++MBBI) {
1365 MBB = MBBI;
Evan Cheng7543e582008-06-18 07:49:14 +00001366 unsigned Dist = 0;
1367 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001368 SrcRegMap.clear();
1369 DstRegMap.clear();
1370 Processed.clear();
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001371 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001372 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001373 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001374 if (mi->isDebugValue()) {
1375 mi = nmi;
1376 continue;
1377 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001378
Evan Cheng3d720fb2010-05-05 18:45:40 +00001379 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1380 if (mi->isRegSequence())
1381 RegSequences.push_back(&*mi);
1382
Evan Cheng7543e582008-06-18 07:49:14 +00001383 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001384
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001385 processCopy(&*mi);
Evan Cheng870b8072009-03-01 02:03:43 +00001386
Bob Wilsoncc80df92009-09-03 20:58:42 +00001387 // First scan through all the tied register uses in this instruction
1388 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001389 if (!collectTiedOperands(mi, TiedOperands)) {
1390 mi = nmi;
1391 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001392 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001393
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001394 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001395 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001396 DEBUG(dbgs() << '\t' << *mi);
1397
Chandler Carruth32d75be2012-07-18 18:58:22 +00001398 // If the instruction has a single pair of tied operands, try some
1399 // transformations that may either eliminate the tied operands or
1400 // improve the opportunities for coalescing away the register copy.
1401 if (TiedOperands.size() == 1) {
1402 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1403 = TiedOperands.begin()->second;
1404 if (TiedPairs.size() == 1) {
1405 unsigned SrcIdx = TiedPairs[0].first;
1406 unsigned DstIdx = TiedPairs[0].second;
1407 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1408 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1409 if (SrcReg != DstReg &&
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001410 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist)) {
Chandler Carruth32d75be2012-07-18 18:58:22 +00001411 // The tied operands have been eliminated or shifted further down the
1412 // block to ease elimination. Continue processing with 'nmi'.
1413 TiedOperands.clear();
1414 mi = nmi;
1415 continue;
1416 }
1417 }
1418 }
1419
Bob Wilsoncc80df92009-09-03 20:58:42 +00001420 // Now iterate over the information collected above.
1421 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1422 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001423 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001424 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001425 }
Bill Wendling637980e2008-05-10 00:12:52 +00001426
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001427 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1428 if (mi->isInsertSubreg()) {
1429 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1430 // To %reg:subidx = COPY %subreg
1431 unsigned SubIdx = mi->getOperand(3).getImm();
1432 mi->RemoveOperand(3);
1433 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1434 mi->getOperand(0).setSubReg(SubIdx);
1435 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1436 mi->RemoveOperand(1);
1437 mi->setDesc(TII->get(TargetOpcode::COPY));
1438 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001439 }
1440
Bob Wilsoncc80df92009-09-03 20:58:42 +00001441 // Clear TiedOperands here instead of at the top of the loop
1442 // since most instructions do not have tied operands.
1443 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001444 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001445 }
1446 }
1447
Evan Cheng3d720fb2010-05-05 18:45:40 +00001448 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1449 // SSA form. It's now safe to de-SSA.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001450 MadeChange |= eliminateRegSequences();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001451
Misha Brukman75fa4e42004-07-22 15:26:23 +00001452 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001453}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001454
1455static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001456 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001457 MachineRegisterInfo *MRI,
1458 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001459 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001460 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001461 MachineOperand &MO = RI.getOperand();
1462 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001463 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001464 }
1465}
1466
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001467// Find the first def of Reg, assuming they are all in the same basic block.
1468static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1469 SmallPtrSet<MachineInstr*, 8> Defs;
1470 MachineInstr *First = 0;
1471 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1472 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1473 First = MI;
1474 if (!First)
1475 return 0;
1476
1477 MachineBasicBlock *MBB = First->getParent();
1478 MachineBasicBlock::iterator A = First, B = First;
1479 bool Moving;
1480 do {
1481 Moving = false;
1482 if (A != MBB->begin()) {
1483 Moving = true;
1484 --A;
1485 if (Defs.erase(A)) First = A;
1486 }
1487 if (B != MBB->end()) {
1488 Defs.erase(B);
1489 ++B;
1490 Moving = true;
1491 }
1492 } while (Moving && !Defs.empty());
1493 assert(Defs.empty() && "Instructions outside basic block!");
1494 return First;
1495}
1496
Evan Chengc6dcce32010-05-17 23:24:12 +00001497static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1498 MachineRegisterInfo *MRI) {
1499 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1500 UE = MRI->use_end(); UI != UE; ++UI) {
1501 MachineInstr *UseMI = &*UI;
1502 if (UseMI != RegSeq && UseMI->isRegSequence())
1503 return true;
1504 }
1505 return false;
1506}
1507
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001508/// eliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
Evan Cheng3d720fb2010-05-05 18:45:40 +00001509/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1510/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1511///
1512/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1513/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1514/// =>
1515/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001516bool TwoAddressInstructionPass::eliminateRegSequences() {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001517 if (RegSequences.empty())
1518 return false;
1519
1520 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1521 MachineInstr *MI = RegSequences[i];
1522 unsigned DstReg = MI->getOperand(0).getReg();
1523 if (MI->getOperand(0).getSubReg() ||
1524 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1525 !(MI->getNumOperands() & 1)) {
1526 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1527 llvm_unreachable(0);
1528 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001529
Evan Cheng44bfdd32010-05-17 22:09:49 +00001530 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001531 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001532 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001533 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001534 // Nothing needs to be inserted for <undef> operands.
1535 if (MI->getOperand(i).isUndef()) {
1536 MI->getOperand(i).setReg(0);
1537 continue;
1538 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001539 unsigned SrcReg = MI->getOperand(i).getReg();
Pete Cooperef74ca62012-04-04 21:03:25 +00001540 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
Bob Wilson495de3b2010-12-17 01:21:12 +00001541 unsigned SubIdx = MI->getOperand(i+1).getImm();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001542 // DefMI of NULL means the value does not have a vreg in this block
1543 // i.e., its a physical register or a subreg.
1544 // In either case we force a copy to be generated.
1545 MachineInstr *DefMI = NULL;
1546 if (!MI->getOperand(i).getSubReg() &&
1547 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
Manman Ren5f917cd2012-07-02 18:55:36 +00001548 DefMI = MRI->getUniqueVRegDef(SrcReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001549 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001550
Pete Coopercd7f02b2012-01-18 04:16:16 +00001551 if (DefMI && DefMI->isImplicitDef()) {
Evan Chengb990a2f2010-05-14 23:21:14 +00001552 DefMI->eraseFromParent();
1553 continue;
1554 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001555 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001556
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001557 // Remember COPY sources. These might be candidate for coalescing.
Pete Coopercd7f02b2012-01-18 04:16:16 +00001558 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
Evan Chengb990a2f2010-05-14 23:21:14 +00001559 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1560
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001561 bool isKill = MI->getOperand(i).isKill();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001562 if (!DefMI || !Seen.insert(SrcReg) ||
1563 MI->getParent() != DefMI->getParent() ||
Bob Wilson495de3b2010-12-17 01:21:12 +00001564 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1565 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1566 MRI->getRegClass(SrcReg), SubIdx)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001567 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001568 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001569 // to end up with a partial-redef of a livein, e.g.
1570 // BB0:
1571 // reg1051:10<def> =
1572 // ...
1573 // BB1:
1574 // ... = reg1051:10
1575 // BB2:
1576 // reg1051:9<def> =
1577 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001578 //
1579 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1580 // correctly up to date becomes very difficult. Insert a copy.
Jakob Stoklund Olesene4b9c4f2010-08-09 20:19:16 +00001581
1582 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1583 // might insert a COPY that uses SrcReg after is was killed.
1584 if (isKill)
1585 for (unsigned j = i + 2; j < e; j += 2)
1586 if (MI->getOperand(j).getReg() == SrcReg) {
1587 MI->getOperand(j).setIsKill();
1588 isKill = false;
1589 break;
1590 }
1591
Evan Cheng054dbb82010-05-13 00:00:35 +00001592 MachineBasicBlock::iterator InsertLoc = MI;
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001593 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1594 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
Bob Wilson495de3b2010-12-17 01:21:12 +00001595 .addReg(DstReg, RegState::Define, SubIdx)
Pete Cooperef74ca62012-04-04 21:03:25 +00001596 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001597 MI->getOperand(i).setReg(0);
Pete Coopercd7f02b2012-01-18 04:16:16 +00001598 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001599 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1600 DEBUG(dbgs() << "Inserted: " << *CopyMI);
Evan Cheng0bcccac2010-05-11 00:04:31 +00001601 }
1602 }
1603
1604 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1605 unsigned SrcReg = MI->getOperand(i).getReg();
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001606 if (!SrcReg) continue;
Evan Cheng53c779b2010-05-17 20:57:12 +00001607 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001608 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001609 }
1610
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001611 // Set <def,undef> flags on the first DstReg def in the basic block.
1612 // It marks the beginning of the live range. All the other defs are
1613 // read-modify-write.
1614 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1615 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1616 MachineOperand &MO = Def->getOperand(i);
1617 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1618 MO.setIsUndef();
1619 }
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001620 DEBUG(dbgs() << "First def: " << *Def);
1621 }
1622
Evan Cheng44bfdd32010-05-17 22:09:49 +00001623 if (IsImpDef) {
1624 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1625 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1626 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
Andrew Trick8247e0d2012-02-03 05:12:30 +00001627 MI->RemoveOperand(j);
Evan Cheng44bfdd32010-05-17 22:09:49 +00001628 } else {
1629 DEBUG(dbgs() << "Eliminated: " << *MI);
1630 MI->eraseFromParent();
1631 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001632 }
1633
Evan Chengfc6e6a92010-05-10 21:24:55 +00001634 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001635 return true;
1636}