blob: 3614bdb7bbd4463ac88699d0793390489c43c76f [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000038#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000039#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
41#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000042#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000043#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000045#include "llvm/MC/MCInstrItineraries.h"
Andrew Tricke2326ad2013-04-24 15:54:39 +000046#include "llvm/Support/CommandLine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000047#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000049#include "llvm/Target/TargetInstrInfo.h"
50#include "llvm/Target/TargetMachine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000051#include "llvm/Target/TargetRegisterInfo.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
Andrew Tricke2326ad2013-04-24 15:54:39 +000062// Temporary flag to disable rescheduling.
63static cl::opt<bool>
64EnableRescheduling("twoaddr-reschedule",
65 cl::desc("Coalesce copies by rescheduling (default=true)"), cl::init(true), cl::Hidden);
66
Evan Cheng875357d2008-03-13 06:37:55 +000067namespace {
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000068class TwoAddressInstructionPass : public MachineFunctionPass {
69 MachineFunction *MF;
70 const TargetInstrInfo *TII;
71 const TargetRegisterInfo *TRI;
72 const InstrItineraryData *InstrItins;
73 MachineRegisterInfo *MRI;
74 LiveVariables *LV;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000075 LiveIntervals *LIS;
76 AliasAnalysis *AA;
77 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000078
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000079 // The current basic block being processed.
80 MachineBasicBlock *MBB;
81
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000082 // DistanceMap - Keep track the distance of a MI from the start of the
83 // current basic block.
84 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000085
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +000086 // Set of already processed instructions in the current block.
87 SmallPtrSet<MachineInstr*, 8> Processed;
88
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000089 // SrcRegMap - A map from virtual registers to physical registers which are
90 // likely targets to be coalesced to due to copies from physical registers to
91 // virtual registers. e.g. v1024 = move r0.
92 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000093
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000094 // DstRegMap - A map from virtual registers to physical registers which are
95 // likely targets to be coalesced to due to copies to physical registers from
96 // virtual registers. e.g. r1 = move v1024.
97 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +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,
Cameron Zwarichc5a63492013-02-24 00:27:26 +0000128 unsigned Dist, bool shouldOnlyCommute);
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);
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +0000138 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000139
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000140public:
141 static char ID; // Pass identification, replacement for typeid
142 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
143 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
144 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000145
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000146 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147 AU.setPreservesCFG();
148 AU.addRequired<AliasAnalysis>();
149 AU.addPreserved<LiveVariables>();
150 AU.addPreserved<SlotIndexes>();
151 AU.addPreserved<LiveIntervals>();
152 AU.addPreservedID(MachineLoopInfoID);
153 AU.addPreservedID(MachineDominatorsID);
154 MachineFunctionPass::getAnalysisUsage(AU);
155 }
Devang Patel794fd752007-05-01 21:15:47 +0000156
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000157 /// runOnMachineFunction - Pass entry point.
158 bool runOnMachineFunction(MachineFunction&);
159};
160} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000161
Dan Gohman844731a2008-05-13 00:00:25 +0000162char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000163INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
164 "Two-Address instruction pass", false, false)
165INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
166INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000167 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000168
Owen Anderson90c579d2010-08-06 18:33:48 +0000169char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000170
Cameron Zwarich4c579422013-02-23 04:49:20 +0000171static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
172
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000173/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000174/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000175/// past the instruction that would kill the above mentioned register to reduce
176/// register pressure.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000177bool TwoAddressInstructionPass::
178sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
179 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000180 // FIXME: Shouldn't we be trying to do this before we three-addressify the
181 // instruction? After this transformation is done, we no longer need
182 // the instruction to be in three-address form.
183
Evan Cheng875357d2008-03-13 06:37:55 +0000184 // Check if it's safe to move this instruction.
185 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000186 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000187 return false;
188
189 unsigned DefReg = 0;
190 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000191
Evan Cheng875357d2008-03-13 06:37:55 +0000192 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
193 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000194 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000195 continue;
196 unsigned MOReg = MO.getReg();
197 if (!MOReg)
198 continue;
199 if (MO.isUse() && MOReg != SavedReg)
200 UseRegs.insert(MO.getReg());
201 if (!MO.isDef())
202 continue;
203 if (MO.isImplicit())
204 // Don't try to move it if it implicitly defines a register.
205 return false;
206 if (DefReg)
207 // For now, don't move any instructions that define multiple registers.
208 return false;
209 DefReg = MO.getReg();
210 }
211
212 // Find the instruction that kills SavedReg.
213 MachineInstr *KillMI = NULL;
Cameron Zwarich4c579422013-02-23 04:49:20 +0000214 if (LIS) {
215 LiveInterval &LI = LIS->getInterval(SavedReg);
216 assert(LI.end() != LI.begin() &&
217 "Reg should not have empty live interval.");
218
219 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
220 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
221 if (I != LI.end() && I->start < MBBEndIdx)
222 return false;
223
224 --I;
225 KillMI = LIS->getInstructionFromIndex(I->end);
226 }
227 if (!KillMI) {
228 for (MachineRegisterInfo::use_nodbg_iterator
229 UI = MRI->use_nodbg_begin(SavedReg),
230 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
231 MachineOperand &UseMO = UI.getOperand();
232 if (!UseMO.isKill())
233 continue;
234 KillMI = UseMO.getParent();
235 break;
236 }
Evan Cheng875357d2008-03-13 06:37:55 +0000237 }
Bill Wendling637980e2008-05-10 00:12:52 +0000238
Eli Friedmanbde81d52011-09-23 22:41:57 +0000239 // If we find the instruction that kills SavedReg, and it is in an
240 // appropriate location, we can try to sink the current instruction
241 // past it.
242 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000243 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000244 return false;
245
Bill Wendling637980e2008-05-10 00:12:52 +0000246 // If any of the definitions are used by another instruction between the
247 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000248 //
Bill Wendling637980e2008-05-10 00:12:52 +0000249 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000250 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000251 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000252 MachineOperand *KillMO = NULL;
253 MachineBasicBlock::iterator KillPos = KillMI;
254 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000255
Evan Cheng7543e582008-06-18 07:49:14 +0000256 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000257 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000258 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000259 // DBG_VALUE cannot be counted against the limit.
260 if (OtherMI->isDebugValue())
261 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000262 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
263 return false;
264 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000265 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
266 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000267 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000268 continue;
269 unsigned MOReg = MO.getReg();
270 if (!MOReg)
271 continue;
272 if (DefReg == MOReg)
273 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000274
Cameron Zwarich4c579422013-02-23 04:49:20 +0000275 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng875357d2008-03-13 06:37:55 +0000276 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000277 // Save the operand that kills the register. We want to unset the kill
278 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000279 KillMO = &MO;
280 else if (UseRegs.count(MOReg))
281 // One of the uses is killed before the destination.
282 return false;
283 }
284 }
285 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000286 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000287
Cameron Zwarich4c579422013-02-23 04:49:20 +0000288 if (!LIS) {
289 // Update kill and LV information.
290 KillMO->setIsKill(false);
291 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
292 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000293
Cameron Zwarich4c579422013-02-23 04:49:20 +0000294 if (LV)
295 LV->replaceKillInstruction(SavedReg, KillMI, MI);
296 }
Evan Cheng875357d2008-03-13 06:37:55 +0000297
298 // Move instruction to its destination.
299 MBB->remove(MI);
300 MBB->insert(KillPos, MI);
301
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000302 if (LIS)
303 LIS->handleMove(MI);
304
Evan Cheng875357d2008-03-13 06:37:55 +0000305 ++Num3AddrSunk;
306 return true;
307}
308
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000309/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000310/// last instruction in the MBB that defines the specified register and the
311/// two-address instruction which is being processed. It also returns the last
312/// def location by reference
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000313bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000314 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000315 LastDef = 0;
316 unsigned LastUse = Dist;
317 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
318 E = MRI->reg_end(); I != E; ++I) {
319 MachineOperand &MO = I.getOperand();
320 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000321 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000322 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000323 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
324 if (DI == DistanceMap.end())
325 continue;
326 if (MO.isUse() && DI->second < LastUse)
327 LastUse = DI->second;
328 if (MO.isDef() && DI->second > LastDef)
329 LastDef = DI->second;
330 }
331
332 return !(LastUse > LastDef && LastUse < Dist);
333}
334
Evan Cheng870b8072009-03-01 02:03:43 +0000335/// isCopyToReg - Return true if the specified MI is a copy instruction or
336/// a extract_subreg instruction. It also returns the source and destination
337/// registers and whether they are physical registers by reference.
338static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
339 unsigned &SrcReg, unsigned &DstReg,
340 bool &IsSrcPhys, bool &IsDstPhys) {
341 SrcReg = 0;
342 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000343 if (MI.isCopy()) {
344 DstReg = MI.getOperand(0).getReg();
345 SrcReg = MI.getOperand(1).getReg();
346 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
347 DstReg = MI.getOperand(0).getReg();
348 SrcReg = MI.getOperand(2).getReg();
349 } else
350 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000351
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000352 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
353 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
354 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000355}
356
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000357/// isPLainlyKilled - Test if the given register value, which is used by the
358// given instruction, is killed by the given instruction.
359static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
360 LiveIntervals *LIS) {
361 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
362 !LIS->isNotInMIMap(MI)) {
363 // FIXME: Sometimes tryInstructionTransform() will add instructions and
364 // test whether they can be folded before keeping them. In this case it
365 // sets a kill before recursively calling tryInstructionTransform() again.
366 // If there is no interval available, we assume that this instruction is
367 // one of those. A kill flag is manually inserted on the operand so the
368 // check below will handle it.
369 LiveInterval &LI = LIS->getInterval(Reg);
370 // This is to match the kill flag version where undefs don't have kill
371 // flags.
372 if (!LI.hasAtLeastOneValue())
373 return false;
374
375 SlotIndex useIdx = LIS->getInstructionIndex(MI);
376 LiveInterval::const_iterator I = LI.find(useIdx);
377 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarichb4bd0222013-02-23 04:49:22 +0000378 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000379 }
380
381 return MI->killsRegister(Reg);
382}
383
Dan Gohman97121ba2009-04-08 00:15:30 +0000384/// isKilled - Test if the given register value, which is used by the given
385/// instruction, is killed by the given instruction. This looks through
386/// coalescable copies to see if the original value is potentially not killed.
387///
388/// For example, in this code:
389///
390/// %reg1034 = copy %reg1024
391/// %reg1035 = copy %reg1025<kill>
392/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
393///
394/// %reg1034 is not considered to be killed, since it is copied from a
395/// register which is not killed. Treating it as not killed lets the
396/// normal heuristics commute the (two-address) add, which lets
397/// coalescing eliminate the extra copy.
398///
Cameron Zwaricha931a122013-02-21 22:58:42 +0000399/// If allowFalsePositives is true then likely kills are treated as kills even
400/// if it can't be proven that they are kills.
Dan Gohman97121ba2009-04-08 00:15:30 +0000401static bool isKilled(MachineInstr &MI, unsigned Reg,
402 const MachineRegisterInfo *MRI,
Cameron Zwarich214df422013-02-21 04:33:02 +0000403 const TargetInstrInfo *TII,
Cameron Zwaricha931a122013-02-21 22:58:42 +0000404 LiveIntervals *LIS,
405 bool allowFalsePositives) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000406 MachineInstr *DefMI = &MI;
407 for (;;) {
Cameron Zwaricha931a122013-02-21 22:58:42 +0000408 // All uses of physical registers are likely to be kills.
409 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
410 (allowFalsePositives || MRI->hasOneUse(Reg)))
411 return true;
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000412 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohman97121ba2009-04-08 00:15:30 +0000413 return false;
414 if (TargetRegisterInfo::isPhysicalRegister(Reg))
415 return true;
416 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
417 // If there are multiple defs, we can't do a simple analysis, so just
418 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000419 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000420 return true;
421 DefMI = &*Begin;
422 bool IsSrcPhys, IsDstPhys;
423 unsigned SrcReg, DstReg;
424 // If the def is something other than a copy, then it isn't going to
425 // be coalesced, so follow the kill flag.
426 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
427 return true;
428 Reg = SrcReg;
429 }
430}
431
Evan Cheng870b8072009-03-01 02:03:43 +0000432/// isTwoAddrUse - Return true if the specified MI uses the specified register
433/// as a two-address use. If so, return the destination register by reference.
434static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000435 const MCInstrDesc &MCID = MI.getDesc();
436 unsigned NumOps = MI.isInlineAsm()
437 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000438 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000439 const MachineOperand &MO = MI.getOperand(i);
440 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
441 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000442 unsigned ti;
443 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000444 DstReg = MI.getOperand(ti).getReg();
445 return true;
446 }
447 }
448 return false;
449}
450
451/// findOnlyInterestingUse - Given a register, if has a single in-basic block
452/// use, return the use instruction if it's a copy or a two-address use.
453static
454MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
455 MachineRegisterInfo *MRI,
456 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000457 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000458 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000459 if (!MRI->hasOneNonDBGUse(Reg))
460 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000461 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000462 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000463 if (UseMI.getParent() != MBB)
464 return 0;
465 unsigned SrcReg;
466 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000467 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
468 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000469 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000470 }
Evan Cheng870b8072009-03-01 02:03:43 +0000471 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000472 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
473 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000474 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000475 }
Evan Cheng870b8072009-03-01 02:03:43 +0000476 return 0;
477}
478
479/// getMappedReg - Return the physical register the specified virtual register
480/// might be mapped to.
481static unsigned
482getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
483 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
484 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
485 if (SI == RegMap.end())
486 return 0;
487 Reg = SI->second;
488 }
489 if (TargetRegisterInfo::isPhysicalRegister(Reg))
490 return Reg;
491 return 0;
492}
493
494/// regsAreCompatible - Return true if the two registers are equal or aliased.
495///
496static bool
497regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
498 if (RegA == RegB)
499 return true;
500 if (!RegA || !RegB)
501 return false;
502 return TRI->regsOverlap(RegA, RegB);
503}
504
505
Manman Rend68e8cd2012-07-25 18:28:13 +0000506/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000507/// the two-address instruction that's being processed.
508bool
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000509TwoAddressInstructionPass::
510isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
511 MachineInstr *MI, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000512 if (OptLevel == CodeGenOpt::None)
513 return false;
514
Evan Chengd498c8f2009-01-25 03:53:59 +0000515 // Determine if it's profitable to commute this two address instruction. In
516 // general, we want no uses between this instruction and the definition of
517 // the two-address register.
518 // e.g.
519 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
520 // %reg1029<def> = MOV8rr %reg1028
521 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
522 // insert => %reg1030<def> = MOV8rr %reg1028
523 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
524 // In this case, it might not be possible to coalesce the second MOV8rr
525 // instruction if the first one is coalesced. So it would be profitable to
526 // commute it:
527 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
528 // %reg1029<def> = MOV8rr %reg1028
529 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
530 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000531 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000532
Cameron Zwarich17cec5a2013-02-21 07:02:30 +0000533 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengd498c8f2009-01-25 03:53:59 +0000534 return false;
535
536 // Ok, we have something like:
537 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
538 // let's see if it's worth commuting it.
539
Evan Cheng870b8072009-03-01 02:03:43 +0000540 // Look for situations like this:
541 // %reg1024<def> = MOV r1
542 // %reg1025<def> = MOV r0
543 // %reg1026<def> = ADD %reg1024, %reg1025
544 // r0 = MOV %reg1026
545 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000546 unsigned ToRegA = getMappedReg(regA, DstRegMap);
547 if (ToRegA) {
548 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
549 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
550 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
551 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
552 if (BComp != CComp)
553 return !BComp && CComp;
554 }
Evan Cheng870b8072009-03-01 02:03:43 +0000555
Evan Chengd498c8f2009-01-25 03:53:59 +0000556 // If there is a use of regC between its last def (could be livein) and this
557 // instruction, then bail.
558 unsigned LastDefC = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000559 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000560 return false;
561
562 // If there is a use of regB between its last def (could be livein) and this
563 // instruction, then go ahead and make this transformation.
564 unsigned LastDefB = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000565 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000566 return true;
567
568 // Since there are no intervening uses for both registers, then commute
569 // if the def of regC is closer. Its live interval is shorter.
570 return LastDefB && LastDefC && LastDefC > LastDefB;
571}
572
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000573/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000574/// block, distance map, and live variables if needed. Return true if it is
575/// successful.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000576bool TwoAddressInstructionPass::
577commuteInstruction(MachineBasicBlock::iterator &mi,
578 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000579 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000580 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000581 MachineInstr *NewMI = TII->commuteInstruction(MI);
582
583 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000584 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000585 return false;
586 }
587
David Greeneeb00b182010-01-05 01:24:21 +0000588 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwarich1ea93c72013-02-23 23:13:28 +0000589 assert(NewMI == MI &&
590 "TargetInstrInfo::commuteInstruction() should not return a new "
591 "instruction unless it was requested.");
Evan Cheng870b8072009-03-01 02:03:43 +0000592
593 // Update source register map.
594 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
595 if (FromRegC) {
596 unsigned RegA = MI->getOperand(0).getReg();
597 SrcRegMap[RegA] = FromRegC;
598 }
599
Evan Cheng81913712009-01-23 23:27:33 +0000600 return true;
601}
602
Evan Chenge6f350d2009-03-30 21:34:07 +0000603/// isProfitableToConv3Addr - Return true if it is profitable to convert the
604/// given 2-address instruction to a 3-address one.
605bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000606TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000607 // Look for situations like this:
608 // %reg1024<def> = MOV r1
609 // %reg1025<def> = MOV r0
610 // %reg1026<def> = ADD %reg1024, %reg1025
611 // r2 = MOV %reg1026
612 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000613 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
614 if (!FromRegB)
615 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000616 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000617 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000618}
619
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000620/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000621/// three address one. Return true if this transformation was successful.
622bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000623TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000624 MachineBasicBlock::iterator &nmi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000625 unsigned RegA, unsigned RegB,
626 unsigned Dist) {
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000627 // FIXME: Why does convertToThreeAddress() need an iterator reference?
628 MachineFunction::iterator MFI = MBB;
629 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
630 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000631 if (!NewMI)
632 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000633
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000634 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
635 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
636 bool Sunk = false;
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000637
Cameron Zwarich61892882013-02-20 22:10:02 +0000638 if (LIS)
639 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000640
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000641 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
642 // FIXME: Temporary workaround. If the new instruction doesn't
643 // uses RegB, convertToThreeAddress must have created more
644 // then one instruction.
645 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000646
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000647 MBB->erase(mi); // Nuke the old inst.
Evan Cheng4d96c632011-02-10 02:20:55 +0000648
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000649 if (!Sunk) {
650 DistanceMap.insert(std::make_pair(NewMI, Dist));
651 mi = NewMI;
652 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000653 }
654
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000655 // Update source and destination register maps.
656 SrcRegMap.erase(RegA);
657 DstRegMap.erase(RegB);
658 return true;
Evan Chenge6f350d2009-03-30 21:34:07 +0000659}
660
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000661/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000662/// is a copy or a two-address instruction.
663void
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000664TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Chengf06e6c22011-03-02 01:08:17 +0000665 SmallVector<unsigned, 4> VirtRegPairs;
666 bool IsDstPhys;
667 bool IsCopy = false;
668 unsigned NewReg = 0;
669 unsigned Reg = DstReg;
670 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
671 NewReg, IsDstPhys)) {
672 if (IsCopy && !Processed.insert(UseMI))
673 break;
674
675 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
676 if (DI != DistanceMap.end())
677 // Earlier in the same MBB.Reached via a back edge.
678 break;
679
680 if (IsDstPhys) {
681 VirtRegPairs.push_back(NewReg);
682 break;
683 }
684 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
685 if (!isNew)
686 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
687 VirtRegPairs.push_back(NewReg);
688 Reg = NewReg;
689 }
690
691 if (!VirtRegPairs.empty()) {
692 unsigned ToReg = VirtRegPairs.back();
693 VirtRegPairs.pop_back();
694 while (!VirtRegPairs.empty()) {
695 unsigned FromReg = VirtRegPairs.back();
696 VirtRegPairs.pop_back();
697 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
698 if (!isNew)
699 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
700 ToReg = FromReg;
701 }
702 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
703 if (!isNew)
704 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
705 }
706}
707
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000708/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000709/// if it's a copy. For a copy instruction, we find the physical registers the
710/// source and destination registers might be mapped to. These are kept in
711/// point-to maps used to determine future optimizations. e.g.
712/// v1024 = mov r0
713/// v1025 = mov r1
714/// v1026 = add v1024, v1025
715/// r1 = mov r1026
716/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
717/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
718/// potentially joined with r1 on the output side. It's worthwhile to commute
719/// 'add' to eliminate a copy.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000720void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Cheng870b8072009-03-01 02:03:43 +0000721 if (Processed.count(MI))
722 return;
723
724 bool IsSrcPhys, IsDstPhys;
725 unsigned SrcReg, DstReg;
726 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
727 return;
728
729 if (IsDstPhys && !IsSrcPhys)
730 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
731 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000732 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
733 if (!isNew)
734 assert(SrcRegMap[DstReg] == SrcReg &&
735 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000736
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000737 scanUses(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000738 }
739
740 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000741 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000742}
743
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000744/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000745/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
746/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000747bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000748rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000749 MachineBasicBlock::iterator &nmi,
750 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000751 // Bail immediately if we don't have LV or LIS available. We use them to find
752 // kills efficiently.
753 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000754 return false;
755
Evan Cheng2a4410d2011-11-14 19:48:55 +0000756 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000757 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000758 if (DI == DistanceMap.end())
759 // Must be created from unfolded load. Don't waste time trying this.
760 return false;
761
Cameron Zwarich80885e52013-02-23 04:49:13 +0000762 MachineInstr *KillMI = 0;
763 if (LIS) {
764 LiveInterval &LI = LIS->getInterval(Reg);
765 assert(LI.end() != LI.begin() &&
766 "Reg should not have empty live interval.");
767
768 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
769 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
770 if (I != LI.end() && I->start < MBBEndIdx)
771 return false;
772
773 --I;
774 KillMI = LIS->getInstructionFromIndex(I->end);
775 } else {
776 KillMI = LV->getVarInfo(Reg).findKill(MBB);
777 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000778 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000779 // Don't mess with copies, they may be coalesced later.
780 return false;
781
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000782 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
783 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000784 // Don't move pass calls, etc.
785 return false;
786
787 unsigned DstReg;
788 if (isTwoAddrUse(*KillMI, Reg, DstReg))
789 return false;
790
Evan Chengf1784182011-11-15 06:26:51 +0000791 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000792 if (!MI->isSafeToMove(TII, AA, SeenStore))
793 return false;
794
795 if (TII->getInstrLatency(InstrItins, MI) > 1)
796 // FIXME: Needs more sophisticated heuristics.
797 return false;
798
799 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000800 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000801 SmallSet<unsigned, 2> Defs;
802 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
803 const MachineOperand &MO = MI->getOperand(i);
804 if (!MO.isReg())
805 continue;
806 unsigned MOReg = MO.getReg();
807 if (!MOReg)
808 continue;
809 if (MO.isDef())
810 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000811 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000812 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000813 if (MOReg != Reg && (MO.isKill() ||
814 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Cheng9bad88a2011-11-16 03:47:42 +0000815 Kills.insert(MOReg);
816 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000817 }
818
819 // Move the copies connected to MI down as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000820 MachineBasicBlock::iterator Begin = MI;
821 MachineBasicBlock::iterator AfterMI = llvm::next(Begin);
822
823 MachineBasicBlock::iterator End = AfterMI;
824 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
825 Defs.insert(End->getOperand(0).getReg());
826 ++End;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000827 }
828
829 // Check if the reschedule will not break depedencies.
830 unsigned NumVisited = 0;
831 MachineBasicBlock::iterator KillPos = KillMI;
832 ++KillPos;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000833 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000834 MachineInstr *OtherMI = I;
835 // DBG_VALUE cannot be counted against the limit.
836 if (OtherMI->isDebugValue())
837 continue;
838 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
839 return false;
840 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000841 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
842 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000843 // Don't move pass calls, etc.
844 return false;
845 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
846 const MachineOperand &MO = OtherMI->getOperand(i);
847 if (!MO.isReg())
848 continue;
849 unsigned MOReg = MO.getReg();
850 if (!MOReg)
851 continue;
852 if (MO.isDef()) {
853 if (Uses.count(MOReg))
854 // Physical register use would be clobbered.
855 return false;
856 if (!MO.isDead() && Defs.count(MOReg))
857 // May clobber a physical register def.
858 // FIXME: This may be too conservative. It's ok if the instruction
859 // is sunken completely below the use.
860 return false;
861 } else {
862 if (Defs.count(MOReg))
863 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000864 bool isKill = MO.isKill() ||
865 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Cheng9bad88a2011-11-16 03:47:42 +0000866 if (MOReg != Reg &&
Cameron Zwarich80885e52013-02-23 04:49:13 +0000867 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000868 // Don't want to extend other live ranges and update kills.
869 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000870 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000871 // We can't schedule across a use of the register in question.
872 return false;
873 // Ensure that if this is register in question, its the kill we expect.
874 assert((MOReg != Reg || OtherMI == KillMI) &&
875 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000876 }
877 }
878 }
879
880 // Move debug info as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000881 while (Begin != MBB->begin() && llvm::prior(Begin)->isDebugValue())
882 --Begin;
883
884 nmi = End;
885 MachineBasicBlock::iterator InsertPos = KillPos;
886 if (LIS) {
887 // We have to move the copies first so that the MBB is still well-formed
888 // when calling handleMove().
889 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
890 MachineInstr *CopyMI = MBBI;
891 ++MBBI;
892 MBB->splice(InsertPos, MBB, CopyMI);
893 LIS->handleMove(CopyMI);
894 InsertPos = CopyMI;
895 }
896 End = llvm::next(MachineBasicBlock::iterator(MI));
897 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000898
899 // Copies following MI may have been moved as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000900 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000901 DistanceMap.erase(DI);
902
Chandler Carruth7d532c82012-07-15 03:29:46 +0000903 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +0000904 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000905 LIS->handleMove(MI);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000906 } else {
907 LV->removeVirtualRegisterKilled(Reg, KillMI);
908 LV->addVirtualRegisterKilled(Reg, MI);
909 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000910
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000911 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000912 return true;
913}
914
915/// isDefTooClose - Return true if the re-scheduling will put the given
916/// instruction too close to the defs of its register dependencies.
917bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000918 MachineInstr *MI) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000919 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
920 DE = MRI->def_end(); DI != DE; ++DI) {
921 MachineInstr *DefMI = &*DI;
922 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
923 continue;
924 if (DefMI == MI)
925 return true; // MI is defining something KillMI uses
926 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
927 if (DDI == DistanceMap.end())
928 return true; // Below MI
929 unsigned DefDist = DDI->second;
930 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000931 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000932 return true;
933 }
934 return false;
935}
936
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000937/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000938/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
939/// current two-address instruction in order to eliminate the need for the
940/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000941bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000942rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000943 MachineBasicBlock::iterator &nmi,
944 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000945 // Bail immediately if we don't have LV or LIS available. We use them to find
946 // kills efficiently.
947 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000948 return false;
949
Evan Cheng2a4410d2011-11-14 19:48:55 +0000950 MachineInstr *MI = &*mi;
951 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
952 if (DI == DistanceMap.end())
953 // Must be created from unfolded load. Don't waste time trying this.
954 return false;
955
Cameron Zwarich80885e52013-02-23 04:49:13 +0000956 MachineInstr *KillMI = 0;
957 if (LIS) {
958 LiveInterval &LI = LIS->getInterval(Reg);
959 assert(LI.end() != LI.begin() &&
960 "Reg should not have empty live interval.");
961
962 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
963 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
964 if (I != LI.end() && I->start < MBBEndIdx)
965 return false;
966
967 --I;
968 KillMI = LIS->getInstructionFromIndex(I->end);
969 } else {
970 KillMI = LV->getVarInfo(Reg).findKill(MBB);
971 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000972 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000973 // Don't mess with copies, they may be coalesced later.
974 return false;
975
976 unsigned DstReg;
977 if (isTwoAddrUse(*KillMI, Reg, DstReg))
978 return false;
979
Evan Chengf1784182011-11-15 06:26:51 +0000980 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000981 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
982 return false;
983
984 SmallSet<unsigned, 2> Uses;
985 SmallSet<unsigned, 2> Kills;
986 SmallSet<unsigned, 2> Defs;
987 SmallSet<unsigned, 2> LiveDefs;
988 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
989 const MachineOperand &MO = KillMI->getOperand(i);
990 if (!MO.isReg())
991 continue;
992 unsigned MOReg = MO.getReg();
993 if (MO.isUse()) {
994 if (!MOReg)
995 continue;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000996 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000997 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000998 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
999 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +00001000 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001001 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +00001002 if (isKill && MOReg != Reg)
Evan Cheng2a4410d2011-11-14 19:48:55 +00001003 Kills.insert(MOReg);
1004 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1005 Defs.insert(MOReg);
1006 if (!MO.isDead())
1007 LiveDefs.insert(MOReg);
1008 }
1009 }
1010
1011 // Check if the reschedule will not break depedencies.
1012 unsigned NumVisited = 0;
1013 MachineBasicBlock::iterator KillPos = KillMI;
1014 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1015 MachineInstr *OtherMI = I;
1016 // DBG_VALUE cannot be counted against the limit.
1017 if (OtherMI->isDebugValue())
1018 continue;
1019 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1020 return false;
1021 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001022 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1023 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001024 // Don't move pass calls, etc.
1025 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +00001026 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001027 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1028 const MachineOperand &MO = OtherMI->getOperand(i);
1029 if (!MO.isReg())
1030 continue;
1031 unsigned MOReg = MO.getReg();
1032 if (!MOReg)
1033 continue;
1034 if (MO.isUse()) {
1035 if (Defs.count(MOReg))
1036 // Moving KillMI can clobber the physical register if the def has
1037 // not been seen.
1038 return false;
1039 if (Kills.count(MOReg))
1040 // Don't want to extend other live ranges and update kills.
1041 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +00001042 if (OtherMI != MI && MOReg == Reg &&
1043 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruth7d532c82012-07-15 03:29:46 +00001044 // We can't schedule across a use of the register in question.
1045 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001046 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +00001047 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001048 }
1049 }
Evan Chengae7db7a2011-11-16 03:05:12 +00001050
1051 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1052 unsigned MOReg = OtherDefs[i];
1053 if (Uses.count(MOReg))
1054 return false;
1055 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1056 LiveDefs.count(MOReg))
1057 return false;
1058 // Physical register def is seen.
1059 Defs.erase(MOReg);
1060 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001061 }
1062
1063 // Move the old kill above MI, don't forget to move debug info as well.
1064 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +00001065 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1066 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001067 MachineBasicBlock::iterator From = KillMI;
1068 MachineBasicBlock::iterator To = llvm::next(From);
1069 while (llvm::prior(From)->isDebugValue())
1070 --From;
1071 MBB->splice(InsertPos, MBB, From, To);
1072
Evan Cheng2bee6a82011-11-16 03:33:08 +00001073 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001074 DistanceMap.erase(DI);
1075
Chandler Carruth7d532c82012-07-15 03:29:46 +00001076 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +00001077 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001078 LIS->handleMove(KillMI);
Cameron Zwarich80885e52013-02-23 04:49:13 +00001079 } else {
1080 LV->removeVirtualRegisterKilled(Reg, KillMI);
1081 LV->addVirtualRegisterKilled(Reg, MI);
1082 }
Chandler Carruth7d532c82012-07-15 03:29:46 +00001083
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001084 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001085 return true;
1086}
1087
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001088/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +00001089/// pair of tied register operands, attempt some transformations that may
1090/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001091/// coalescing away the register copy. Returns true if no copy needs to be
1092/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001093/// because mi was rescheduled, and will be visited again later). If the
1094/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilsoncc80df92009-09-03 20:58:42 +00001095bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001096tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001097 MachineBasicBlock::iterator &nmi,
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001098 unsigned SrcIdx, unsigned DstIdx,
1099 unsigned Dist, bool shouldOnlyCommute) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001100 if (OptLevel == CodeGenOpt::None)
1101 return false;
1102
Evan Cheng2a4410d2011-11-14 19:48:55 +00001103 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001104 unsigned regA = MI.getOperand(DstIdx).getReg();
1105 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001106
1107 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1108 "cannot make instruction into two-address form");
Cameron Zwaricha931a122013-02-21 22:58:42 +00001109 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001110
Evan Chengd99d68b2012-05-03 01:45:13 +00001111 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001112 scanUses(regA);
Evan Chengd99d68b2012-05-03 01:45:13 +00001113
Bob Wilsoncc80df92009-09-03 20:58:42 +00001114 // Check if it is profitable to commute the operands.
1115 unsigned SrcOp1, SrcOp2;
1116 unsigned regC = 0;
1117 unsigned regCIdx = ~0U;
1118 bool TryCommute = false;
1119 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001120 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001121 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001122 if (SrcIdx == SrcOp1)
1123 regCIdx = SrcOp2;
1124 else if (SrcIdx == SrcOp2)
1125 regCIdx = SrcOp1;
1126
1127 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001128 regC = MI.getOperand(regCIdx).getReg();
Cameron Zwaricha931a122013-02-21 22:58:42 +00001129 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001130 // If C dies but B does not, swap the B and C operands.
1131 // This makes the live ranges of A and C joinable.
1132 TryCommute = true;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001133 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001134 TryCommute = true;
1135 AggressiveCommute = true;
1136 }
1137 }
1138 }
1139
1140 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001141 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001142 ++NumCommuted;
1143 if (AggressiveCommute)
1144 ++NumAggrCommuted;
1145 return false;
1146 }
1147
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001148 if (shouldOnlyCommute)
1149 return false;
1150
Evan Cheng2a4410d2011-11-14 19:48:55 +00001151 // If there is one more use of regB later in the same MBB, consider
1152 // re-schedule this MI below it.
Andrew Tricke2326ad2013-04-24 15:54:39 +00001153 if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001154 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001155 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001156 }
1157
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001158 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001159 // This instruction is potentially convertible to a true
1160 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001161 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001162 // Try to convert it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001163 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001164 ++NumConvertedTo3Addr;
1165 return true; // Done with this instruction.
1166 }
1167 }
1168 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001169
Evan Cheng2a4410d2011-11-14 19:48:55 +00001170 // If there is one more use of regB later in the same MBB, consider
1171 // re-schedule it before this MI if it's legal.
Andrew Tricke2326ad2013-04-24 15:54:39 +00001172 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001173 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001174 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001175 }
1176
Dan Gohman584fedf2010-06-21 22:17:20 +00001177 // If this is an instruction with a load folded into it, try unfolding
1178 // the load, e.g. avoid this:
1179 // movq %rdx, %rcx
1180 // addq (%rax), %rcx
1181 // in favor of this:
1182 // movq (%rax), %rcx
1183 // addq %rdx, %rcx
1184 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001185 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001186 // Determine if a load can be unfolded.
1187 unsigned LoadRegIndex;
1188 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001189 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001190 /*UnfoldLoad=*/true,
1191 /*UnfoldStore=*/false,
1192 &LoadRegIndex);
1193 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001194 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1195 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001196 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001197 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001198 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001199 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001200 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001201 unsigned Reg = MRI->createVirtualRegister(RC);
1202 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001203 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001204 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1205 NewMIs)) {
1206 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1207 return false;
1208 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001209 assert(NewMIs.size() == 2 &&
1210 "Unfolded a load into multiple instructions!");
1211 // The load was previously folded, so this is the only use.
1212 NewMIs[1]->addRegisterKilled(Reg, TRI);
1213
1214 // Tentatively insert the instructions into the block so that they
1215 // look "normal" to the transformation logic.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001216 MBB->insert(mi, NewMIs[0]);
1217 MBB->insert(mi, NewMIs[1]);
Dan Gohman584fedf2010-06-21 22:17:20 +00001218
1219 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1220 << "2addr: NEW INST: " << *NewMIs[1]);
1221
1222 // Transform the instruction, now that it no longer has a load.
1223 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1224 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1225 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001226 bool TransformResult =
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001227 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarichcc6137e2013-02-24 01:26:05 +00001228 (void)TransformResult;
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001229 assert(!TransformResult &&
1230 "tryInstructionTransform() should return false.");
1231 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001232 // Success, or at least we made an improvement. Keep the unfolded
1233 // instructions and discard the original.
1234 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001235 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1236 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001237 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001238 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1239 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001240 if (MO.isKill()) {
1241 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001242 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001243 else {
1244 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1245 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001246 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001247 }
1248 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001249 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001250 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1251 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1252 else {
1253 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1254 "Dead flag missing after load unfold!");
1255 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1256 }
1257 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001258 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001259 }
1260 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1261 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001262
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001263 SmallVector<unsigned, 4> OrigRegs;
1264 if (LIS) {
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001265 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1266 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1267 if (MOI->isReg())
1268 OrigRegs.push_back(MOI->getReg());
1269 }
1270 }
1271
Evan Cheng2a4410d2011-11-14 19:48:55 +00001272 MI.eraseFromParent();
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001273
1274 // Update LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001275 if (LIS) {
1276 MachineBasicBlock::iterator Begin(NewMIs[0]);
1277 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001278 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001279 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001280
Dan Gohman584fedf2010-06-21 22:17:20 +00001281 mi = NewMIs[1];
Dan Gohman584fedf2010-06-21 22:17:20 +00001282 } else {
1283 // Transforming didn't eliminate the tie and didn't lead to an
1284 // improvement. Clean up the unfolded instructions and keep the
1285 // original.
1286 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1287 NewMIs[0]->eraseFromParent();
1288 NewMIs[1]->eraseFromParent();
1289 }
1290 }
1291 }
1292 }
1293
Bob Wilsoncc80df92009-09-03 20:58:42 +00001294 return false;
1295}
1296
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001297// Collect tied operands of MI that need to be handled.
1298// Rewrite trivial cases immediately.
1299// Return true if any tied operands where found, including the trivial ones.
1300bool TwoAddressInstructionPass::
1301collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1302 const MCInstrDesc &MCID = MI->getDesc();
1303 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001304 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001305
1306 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1307 unsigned DstIdx = 0;
1308 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1309 continue;
1310 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001311 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1312 MachineOperand &DstMO = MI->getOperand(DstIdx);
1313 unsigned SrcReg = SrcMO.getReg();
1314 unsigned DstReg = DstMO.getReg();
1315 // Tied constraint already satisfied?
1316 if (SrcReg == DstReg)
1317 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001318
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001319 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001320
1321 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001322 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001323 // Constrain the DstReg register class if required.
1324 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1325 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1326 TRI, *MF))
1327 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001328 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001329 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1330 continue;
1331 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001332 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001333 }
1334 return AnyOps;
1335}
1336
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001337// Process a list of tied MI operands that all use the same source register.
1338// The tied pairs are of the form (SrcIdx, DstIdx).
1339void
1340TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1341 TiedPairList &TiedPairs,
1342 unsigned &Dist) {
1343 bool IsEarlyClobber = false;
Cameron Zwarich6cf93d72013-02-20 06:46:46 +00001344 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1345 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1346 IsEarlyClobber |= DstMO.isEarlyClobber();
1347 }
1348
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001349 bool RemovedKillFlag = false;
1350 bool AllUsesCopied = true;
1351 unsigned LastCopiedReg = 0;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001352 SlotIndex LastCopyIdx;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001353 unsigned RegB = 0;
1354 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1355 unsigned SrcIdx = TiedPairs[tpi].first;
1356 unsigned DstIdx = TiedPairs[tpi].second;
1357
1358 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1359 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001360
1361 // Grab RegB from the instruction because it may have changed if the
1362 // instruction was commuted.
1363 RegB = MI->getOperand(SrcIdx).getReg();
1364
1365 if (RegA == RegB) {
1366 // The register is tied to multiple destinations (or else we would
1367 // not have continued this far), but this use of the register
1368 // already matches the tied destination. Leave it.
1369 AllUsesCopied = false;
1370 continue;
1371 }
1372 LastCopiedReg = RegA;
1373
1374 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1375 "cannot make instruction into two-address form");
1376
1377#ifndef NDEBUG
1378 // First, verify that we don't have a use of "a" in the instruction
1379 // (a = b + a for example) because our transformation will not
1380 // work. This should never occur because we are in SSA form.
1381 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1382 assert(i == DstIdx ||
1383 !MI->getOperand(i).isReg() ||
1384 MI->getOperand(i).getReg() != RegA);
1385#endif
1386
1387 // Emit a copy.
1388 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1389 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1390
1391 // Update DistanceMap.
1392 MachineBasicBlock::iterator PrevMI = MI;
1393 --PrevMI;
1394 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1395 DistanceMap[MI] = ++Dist;
1396
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001397 if (LIS) {
1398 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1399
1400 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1401 LiveInterval &LI = LIS->getInterval(RegA);
1402 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1403 SlotIndex endIdx =
1404 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1405 LI.addRange(LiveRange(LastCopyIdx, endIdx, VNI));
1406 }
1407 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001408
1409 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1410
1411 MachineOperand &MO = MI->getOperand(SrcIdx);
1412 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1413 "inconsistent operand info for 2-reg pass");
1414 if (MO.isKill()) {
1415 MO.setIsKill(false);
1416 RemovedKillFlag = true;
1417 }
1418
1419 // Make sure regA is a legal regclass for the SrcIdx operand.
1420 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1421 TargetRegisterInfo::isVirtualRegister(RegB))
1422 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1423
1424 MO.setReg(RegA);
1425
1426 // Propagate SrcRegMap.
1427 SrcRegMap[RegA] = RegB;
1428 }
1429
1430
1431 if (AllUsesCopied) {
1432 if (!IsEarlyClobber) {
1433 // Replace other (un-tied) uses of regB with LastCopiedReg.
1434 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1435 MachineOperand &MO = MI->getOperand(i);
1436 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1437 if (MO.isKill()) {
1438 MO.setIsKill(false);
1439 RemovedKillFlag = true;
1440 }
1441 MO.setReg(LastCopiedReg);
1442 }
1443 }
1444 }
1445
1446 // Update live variables for regB.
1447 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1448 MachineBasicBlock::iterator PrevMI = MI;
1449 --PrevMI;
1450 LV->addVirtualRegisterKilled(RegB, PrevMI);
1451 }
1452
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001453 // Update LiveIntervals.
1454 if (LIS) {
1455 LiveInterval &LI = LIS->getInterval(RegB);
1456 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1457 LiveInterval::const_iterator I = LI.find(MIIdx);
1458 assert(I != LI.end() && "RegB must be live-in to use.");
1459
1460 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1461 if (I->end == UseIdx)
1462 LI.removeRange(LastCopyIdx, UseIdx);
1463 }
1464
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001465 } else if (RemovedKillFlag) {
1466 // Some tied uses of regB matched their destination registers, so
1467 // regB is still used in this instruction, but a kill flag was
1468 // removed from a different tied use of regB, so now we need to add
1469 // a kill flag to one of the remaining uses of regB.
1470 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1471 MachineOperand &MO = MI->getOperand(i);
1472 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1473 MO.setIsKill(true);
1474 break;
1475 }
1476 }
1477 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001478}
1479
Bill Wendling637980e2008-05-10 00:12:52 +00001480/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001481///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001482bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1483 MF = &Func;
1484 const TargetMachine &TM = MF->getTarget();
1485 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001486 TII = TM.getInstrInfo();
1487 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001488 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001489 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001490 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001491 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001492 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001493
Misha Brukman75fa4e42004-07-22 15:26:23 +00001494 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001495
David Greeneeb00b182010-01-05 01:24:21 +00001496 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001497 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001498 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001499
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001500 // This pass takes the function out of SSA form.
1501 MRI->leaveSSA();
1502
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001503 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001504 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1505 MBBI != MBBE; ++MBBI) {
1506 MBB = MBBI;
Evan Cheng7543e582008-06-18 07:49:14 +00001507 unsigned Dist = 0;
1508 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001509 SrcRegMap.clear();
1510 DstRegMap.clear();
1511 Processed.clear();
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001512 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001513 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001514 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001515 if (mi->isDebugValue()) {
1516 mi = nmi;
1517 continue;
1518 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001519
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001520 // Expand REG_SEQUENCE instructions. This will position mi at the first
1521 // expanded instruction.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001522 if (mi->isRegSequence())
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001523 eliminateRegSequence(mi);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001524
Evan Cheng7543e582008-06-18 07:49:14 +00001525 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001526
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001527 processCopy(&*mi);
Evan Cheng870b8072009-03-01 02:03:43 +00001528
Bob Wilsoncc80df92009-09-03 20:58:42 +00001529 // First scan through all the tied register uses in this instruction
1530 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001531 if (!collectTiedOperands(mi, TiedOperands)) {
1532 mi = nmi;
1533 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001534 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001535
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001536 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001537 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001538 DEBUG(dbgs() << '\t' << *mi);
1539
Chandler Carruth32d75be2012-07-18 18:58:22 +00001540 // If the instruction has a single pair of tied operands, try some
1541 // transformations that may either eliminate the tied operands or
1542 // improve the opportunities for coalescing away the register copy.
1543 if (TiedOperands.size() == 1) {
1544 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1545 = TiedOperands.begin()->second;
1546 if (TiedPairs.size() == 1) {
1547 unsigned SrcIdx = TiedPairs[0].first;
1548 unsigned DstIdx = TiedPairs[0].second;
1549 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1550 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1551 if (SrcReg != DstReg &&
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001552 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
Chandler Carruth32d75be2012-07-18 18:58:22 +00001553 // The tied operands have been eliminated or shifted further down the
1554 // block to ease elimination. Continue processing with 'nmi'.
1555 TiedOperands.clear();
1556 mi = nmi;
1557 continue;
1558 }
1559 }
1560 }
1561
Bob Wilsoncc80df92009-09-03 20:58:42 +00001562 // Now iterate over the information collected above.
1563 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1564 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001565 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001566 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001567 }
Bill Wendling637980e2008-05-10 00:12:52 +00001568
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001569 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1570 if (mi->isInsertSubreg()) {
1571 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1572 // To %reg:subidx = COPY %subreg
1573 unsigned SubIdx = mi->getOperand(3).getImm();
1574 mi->RemoveOperand(3);
1575 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1576 mi->getOperand(0).setSubReg(SubIdx);
1577 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1578 mi->RemoveOperand(1);
1579 mi->setDesc(TII->get(TargetOpcode::COPY));
1580 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001581 }
1582
Bob Wilsoncc80df92009-09-03 20:58:42 +00001583 // Clear TiedOperands here instead of at the top of the loop
1584 // since most instructions do not have tied operands.
1585 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001586 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001587 }
1588 }
1589
Cameron Zwarich767e0432013-02-20 06:46:34 +00001590 if (LIS)
1591 MF->verify(this, "After two-address instruction pass");
1592
Misha Brukman75fa4e42004-07-22 15:26:23 +00001593 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001594}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001595
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001596/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001597///
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001598/// The instruction is turned into a sequence of sub-register copies:
1599///
1600/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1601///
1602/// Becomes:
1603///
1604/// %dst:ssub0<def,undef> = COPY %v1
1605/// %dst:ssub1<def> = COPY %v2
1606///
1607void TwoAddressInstructionPass::
1608eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1609 MachineInstr *MI = MBBI;
1610 unsigned DstReg = MI->getOperand(0).getReg();
1611 if (MI->getOperand(0).getSubReg() ||
1612 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1613 !(MI->getNumOperands() & 1)) {
1614 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1615 llvm_unreachable(0);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001616 }
1617
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001618 SmallVector<unsigned, 4> OrigRegs;
1619 if (LIS) {
1620 OrigRegs.push_back(MI->getOperand(0).getReg());
1621 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1622 OrigRegs.push_back(MI->getOperand(i).getReg());
1623 }
1624
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001625 bool DefEmitted = false;
1626 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1627 MachineOperand &UseMO = MI->getOperand(i);
1628 unsigned SrcReg = UseMO.getReg();
1629 unsigned SubIdx = MI->getOperand(i+1).getImm();
1630 // Nothing needs to be inserted for <undef> operands.
1631 if (UseMO.isUndef())
1632 continue;
1633
1634 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1635 // might insert a COPY that uses SrcReg after is was killed.
1636 bool isKill = UseMO.isKill();
1637 if (isKill)
1638 for (unsigned j = i + 2; j < e; j += 2)
1639 if (MI->getOperand(j).getReg() == SrcReg) {
1640 MI->getOperand(j).setIsKill();
1641 UseMO.setIsKill(false);
1642 isKill = false;
1643 break;
1644 }
1645
1646 // Insert the sub-register copy.
1647 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1648 TII->get(TargetOpcode::COPY))
1649 .addReg(DstReg, RegState::Define, SubIdx)
1650 .addOperand(UseMO);
1651
1652 // The first def needs an <undef> flag because there is no live register
1653 // before it.
1654 if (!DefEmitted) {
1655 CopyMI->getOperand(0).setIsUndef(true);
1656 // Return an iterator pointing to the first inserted instr.
1657 MBBI = CopyMI;
1658 }
1659 DefEmitted = true;
1660
1661 // Update LiveVariables' kill info.
1662 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1663 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1664
1665 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1666 }
1667
David Blaikiefdf45172013-02-20 07:39:20 +00001668 MachineBasicBlock::iterator EndMBBI =
1669 llvm::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001670
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001671 if (!DefEmitted) {
1672 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1673 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1674 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1675 MI->RemoveOperand(j);
1676 } else {
1677 DEBUG(dbgs() << "Eliminated: " << *MI);
1678 MI->eraseFromParent();
1679 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001680
1681 // Udpate LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001682 if (LIS)
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001683 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001684}