blob: 34946ec1ce9ac89525eadc3f942c00d277a3fb05 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000046#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000048#include "llvm/Target/TargetInstrInfo.h"
49#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000050#include "llvm/Target/TargetOptions.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
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;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000070 LiveIntervals *LIS;
71 AliasAnalysis *AA;
72 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000073
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000074 // The current basic block being processed.
75 MachineBasicBlock *MBB;
76
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000077 // DistanceMap - Keep track the distance of a MI from the start of the
78 // current basic block.
79 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000080
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +000081 // Set of already processed instructions in the current block.
82 SmallPtrSet<MachineInstr*, 8> Processed;
83
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000084 // SrcRegMap - A map from virtual registers to physical registers which are
85 // likely targets to be coalesced to due to copies from physical registers to
86 // virtual registers. e.g. v1024 = move r0.
87 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000088
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000089 // DstRegMap - A map from virtual registers to physical registers which are
90 // likely targets to be coalesced to due to copies to physical registers from
91 // virtual registers. e.g. r1 = move v1024.
92 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000093
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000094 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000095 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000096
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000097 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengd498c8f2009-01-25 03:53:59 +000098
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000099 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000100 MachineInstr *MI, unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000101
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000102 bool commuteInstruction(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000103 unsigned RegB, unsigned RegC, unsigned Dist);
Evan Cheng870b8072009-03-01 02:03:43 +0000104
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000105 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000106
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000107 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
108 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000109 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000110
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000111 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000112
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000113 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000114 MachineBasicBlock::iterator &nmi,
115 unsigned Reg);
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000116 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000117 MachineBasicBlock::iterator &nmi,
118 unsigned Reg);
119
120 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng2a4410d2011-11-14 19:48:55 +0000121 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000122 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichc5a63492013-02-24 00:27:26 +0000123 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000124
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000125 void scanUses(unsigned DstReg);
Evan Chengf06e6c22011-03-02 01:08:17 +0000126
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000127 void processCopy(MachineInstr *MI);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000128
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000129 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
130 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
131 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
132 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +0000133 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000134
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000135public:
136 static char ID; // Pass identification, replacement for typeid
137 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
138 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
139 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000140
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000141 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
142 AU.setPreservesCFG();
143 AU.addRequired<AliasAnalysis>();
144 AU.addPreserved<LiveVariables>();
145 AU.addPreserved<SlotIndexes>();
146 AU.addPreserved<LiveIntervals>();
147 AU.addPreservedID(MachineLoopInfoID);
148 AU.addPreservedID(MachineDominatorsID);
149 MachineFunctionPass::getAnalysisUsage(AU);
150 }
Devang Patel794fd752007-05-01 21:15:47 +0000151
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000152 /// runOnMachineFunction - Pass entry point.
153 bool runOnMachineFunction(MachineFunction&);
154};
155} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000158INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
159 "Two-Address instruction pass", false, false)
160INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
161INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000162 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000163
Owen Anderson90c579d2010-08-06 18:33:48 +0000164char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000165
Cameron Zwarich4c579422013-02-23 04:49:20 +0000166static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
167
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000168/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000169/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000170/// past the instruction that would kill the above mentioned register to reduce
171/// register pressure.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000172bool TwoAddressInstructionPass::
173sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
174 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000175 // FIXME: Shouldn't we be trying to do this before we three-addressify the
176 // instruction? After this transformation is done, we no longer need
177 // the instruction to be in three-address form.
178
Evan Cheng875357d2008-03-13 06:37:55 +0000179 // Check if it's safe to move this instruction.
180 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000181 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000182 return false;
183
184 unsigned DefReg = 0;
185 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000186
Evan Cheng875357d2008-03-13 06:37:55 +0000187 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
188 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000189 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000190 continue;
191 unsigned MOReg = MO.getReg();
192 if (!MOReg)
193 continue;
194 if (MO.isUse() && MOReg != SavedReg)
195 UseRegs.insert(MO.getReg());
196 if (!MO.isDef())
197 continue;
198 if (MO.isImplicit())
199 // Don't try to move it if it implicitly defines a register.
200 return false;
201 if (DefReg)
202 // For now, don't move any instructions that define multiple registers.
203 return false;
204 DefReg = MO.getReg();
205 }
206
207 // Find the instruction that kills SavedReg.
208 MachineInstr *KillMI = NULL;
Cameron Zwarich4c579422013-02-23 04:49:20 +0000209 if (LIS) {
210 LiveInterval &LI = LIS->getInterval(SavedReg);
211 assert(LI.end() != LI.begin() &&
212 "Reg should not have empty live interval.");
213
214 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
215 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
216 if (I != LI.end() && I->start < MBBEndIdx)
217 return false;
218
219 --I;
220 KillMI = LIS->getInstructionFromIndex(I->end);
221 }
222 if (!KillMI) {
223 for (MachineRegisterInfo::use_nodbg_iterator
224 UI = MRI->use_nodbg_begin(SavedReg),
225 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
226 MachineOperand &UseMO = UI.getOperand();
227 if (!UseMO.isKill())
228 continue;
229 KillMI = UseMO.getParent();
230 break;
231 }
Evan Cheng875357d2008-03-13 06:37:55 +0000232 }
Bill Wendling637980e2008-05-10 00:12:52 +0000233
Eli Friedmanbde81d52011-09-23 22:41:57 +0000234 // If we find the instruction that kills SavedReg, and it is in an
235 // appropriate location, we can try to sink the current instruction
236 // past it.
237 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000238 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000239 return false;
240
Bill Wendling637980e2008-05-10 00:12:52 +0000241 // If any of the definitions are used by another instruction between the
242 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000243 //
Bill Wendling637980e2008-05-10 00:12:52 +0000244 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000245 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000246 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000247 MachineOperand *KillMO = NULL;
248 MachineBasicBlock::iterator KillPos = KillMI;
249 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000250
Evan Cheng7543e582008-06-18 07:49:14 +0000251 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000252 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000253 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000254 // DBG_VALUE cannot be counted against the limit.
255 if (OtherMI->isDebugValue())
256 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000257 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
258 return false;
259 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000260 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
261 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000262 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000263 continue;
264 unsigned MOReg = MO.getReg();
265 if (!MOReg)
266 continue;
267 if (DefReg == MOReg)
268 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000269
Cameron Zwarich4c579422013-02-23 04:49:20 +0000270 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng875357d2008-03-13 06:37:55 +0000271 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000272 // Save the operand that kills the register. We want to unset the kill
273 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000274 KillMO = &MO;
275 else if (UseRegs.count(MOReg))
276 // One of the uses is killed before the destination.
277 return false;
278 }
279 }
280 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000281 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000282
Cameron Zwarich4c579422013-02-23 04:49:20 +0000283 if (!LIS) {
284 // Update kill and LV information.
285 KillMO->setIsKill(false);
286 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
287 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000288
Cameron Zwarich4c579422013-02-23 04:49:20 +0000289 if (LV)
290 LV->replaceKillInstruction(SavedReg, KillMI, MI);
291 }
Evan Cheng875357d2008-03-13 06:37:55 +0000292
293 // Move instruction to its destination.
294 MBB->remove(MI);
295 MBB->insert(KillPos, MI);
296
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000297 if (LIS)
298 LIS->handleMove(MI);
299
Evan Cheng875357d2008-03-13 06:37:55 +0000300 ++Num3AddrSunk;
301 return true;
302}
303
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000304/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000305/// last instruction in the MBB that defines the specified register and the
306/// two-address instruction which is being processed. It also returns the last
307/// def location by reference
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000308bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000309 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000310 LastDef = 0;
311 unsigned LastUse = Dist;
312 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
313 E = MRI->reg_end(); I != E; ++I) {
314 MachineOperand &MO = I.getOperand();
315 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000316 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000317 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000318 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
319 if (DI == DistanceMap.end())
320 continue;
321 if (MO.isUse() && DI->second < LastUse)
322 LastUse = DI->second;
323 if (MO.isDef() && DI->second > LastDef)
324 LastDef = DI->second;
325 }
326
327 return !(LastUse > LastDef && LastUse < Dist);
328}
329
Evan Cheng870b8072009-03-01 02:03:43 +0000330/// isCopyToReg - Return true if the specified MI is a copy instruction or
331/// a extract_subreg instruction. It also returns the source and destination
332/// registers and whether they are physical registers by reference.
333static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
334 unsigned &SrcReg, unsigned &DstReg,
335 bool &IsSrcPhys, bool &IsDstPhys) {
336 SrcReg = 0;
337 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000338 if (MI.isCopy()) {
339 DstReg = MI.getOperand(0).getReg();
340 SrcReg = MI.getOperand(1).getReg();
341 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
342 DstReg = MI.getOperand(0).getReg();
343 SrcReg = MI.getOperand(2).getReg();
344 } else
345 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000346
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000347 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
348 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
349 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000350}
351
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000352/// isPLainlyKilled - Test if the given register value, which is used by the
353// given instruction, is killed by the given instruction.
354static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
355 LiveIntervals *LIS) {
356 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
357 !LIS->isNotInMIMap(MI)) {
358 // FIXME: Sometimes tryInstructionTransform() will add instructions and
359 // test whether they can be folded before keeping them. In this case it
360 // sets a kill before recursively calling tryInstructionTransform() again.
361 // If there is no interval available, we assume that this instruction is
362 // one of those. A kill flag is manually inserted on the operand so the
363 // check below will handle it.
364 LiveInterval &LI = LIS->getInterval(Reg);
365 // This is to match the kill flag version where undefs don't have kill
366 // flags.
367 if (!LI.hasAtLeastOneValue())
368 return false;
369
370 SlotIndex useIdx = LIS->getInstructionIndex(MI);
371 LiveInterval::const_iterator I = LI.find(useIdx);
372 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarichb4bd0222013-02-23 04:49:22 +0000373 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000374 }
375
376 return MI->killsRegister(Reg);
377}
378
Dan Gohman97121ba2009-04-08 00:15:30 +0000379/// isKilled - Test if the given register value, which is used by the given
380/// instruction, is killed by the given instruction. This looks through
381/// coalescable copies to see if the original value is potentially not killed.
382///
383/// For example, in this code:
384///
385/// %reg1034 = copy %reg1024
386/// %reg1035 = copy %reg1025<kill>
387/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
388///
389/// %reg1034 is not considered to be killed, since it is copied from a
390/// register which is not killed. Treating it as not killed lets the
391/// normal heuristics commute the (two-address) add, which lets
392/// coalescing eliminate the extra copy.
393///
Cameron Zwaricha931a122013-02-21 22:58:42 +0000394/// If allowFalsePositives is true then likely kills are treated as kills even
395/// if it can't be proven that they are kills.
Dan Gohman97121ba2009-04-08 00:15:30 +0000396static bool isKilled(MachineInstr &MI, unsigned Reg,
397 const MachineRegisterInfo *MRI,
Cameron Zwarich214df422013-02-21 04:33:02 +0000398 const TargetInstrInfo *TII,
Cameron Zwaricha931a122013-02-21 22:58:42 +0000399 LiveIntervals *LIS,
400 bool allowFalsePositives) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000401 MachineInstr *DefMI = &MI;
402 for (;;) {
Cameron Zwaricha931a122013-02-21 22:58:42 +0000403 // All uses of physical registers are likely to be kills.
404 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
405 (allowFalsePositives || MRI->hasOneUse(Reg)))
406 return true;
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000407 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohman97121ba2009-04-08 00:15:30 +0000408 return false;
409 if (TargetRegisterInfo::isPhysicalRegister(Reg))
410 return true;
411 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
412 // If there are multiple defs, we can't do a simple analysis, so just
413 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000414 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000415 return true;
416 DefMI = &*Begin;
417 bool IsSrcPhys, IsDstPhys;
418 unsigned SrcReg, DstReg;
419 // If the def is something other than a copy, then it isn't going to
420 // be coalesced, so follow the kill flag.
421 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
422 return true;
423 Reg = SrcReg;
424 }
425}
426
Evan Cheng870b8072009-03-01 02:03:43 +0000427/// isTwoAddrUse - Return true if the specified MI uses the specified register
428/// as a two-address use. If so, return the destination register by reference.
429static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000430 const MCInstrDesc &MCID = MI.getDesc();
431 unsigned NumOps = MI.isInlineAsm()
432 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000433 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000434 const MachineOperand &MO = MI.getOperand(i);
435 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
436 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000437 unsigned ti;
438 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000439 DstReg = MI.getOperand(ti).getReg();
440 return true;
441 }
442 }
443 return false;
444}
445
446/// findOnlyInterestingUse - Given a register, if has a single in-basic block
447/// use, return the use instruction if it's a copy or a two-address use.
448static
449MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
450 MachineRegisterInfo *MRI,
451 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000452 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000453 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000454 if (!MRI->hasOneNonDBGUse(Reg))
455 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000456 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000457 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000458 if (UseMI.getParent() != MBB)
459 return 0;
460 unsigned SrcReg;
461 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000462 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
463 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000464 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000465 }
Evan Cheng870b8072009-03-01 02:03:43 +0000466 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000467 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
468 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
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 return 0;
472}
473
474/// getMappedReg - Return the physical register the specified virtual register
475/// might be mapped to.
476static unsigned
477getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
478 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
479 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
480 if (SI == RegMap.end())
481 return 0;
482 Reg = SI->second;
483 }
484 if (TargetRegisterInfo::isPhysicalRegister(Reg))
485 return Reg;
486 return 0;
487}
488
489/// regsAreCompatible - Return true if the two registers are equal or aliased.
490///
491static bool
492regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
493 if (RegA == RegB)
494 return true;
495 if (!RegA || !RegB)
496 return false;
497 return TRI->regsOverlap(RegA, RegB);
498}
499
500
Manman Rend68e8cd2012-07-25 18:28:13 +0000501/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000502/// the two-address instruction that's being processed.
503bool
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000504TwoAddressInstructionPass::
505isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
506 MachineInstr *MI, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000507 if (OptLevel == CodeGenOpt::None)
508 return false;
509
Evan Chengd498c8f2009-01-25 03:53:59 +0000510 // Determine if it's profitable to commute this two address instruction. In
511 // general, we want no uses between this instruction and the definition of
512 // the two-address register.
513 // e.g.
514 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
515 // %reg1029<def> = MOV8rr %reg1028
516 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
517 // insert => %reg1030<def> = MOV8rr %reg1028
518 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
519 // In this case, it might not be possible to coalesce the second MOV8rr
520 // instruction if the first one is coalesced. So it would be profitable to
521 // commute it:
522 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
523 // %reg1029<def> = MOV8rr %reg1028
524 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
525 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000526 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000527
Cameron Zwarich17cec5a2013-02-21 07:02:30 +0000528 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengd498c8f2009-01-25 03:53:59 +0000529 return false;
530
531 // Ok, we have something like:
532 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
533 // let's see if it's worth commuting it.
534
Evan Cheng870b8072009-03-01 02:03:43 +0000535 // Look for situations like this:
536 // %reg1024<def> = MOV r1
537 // %reg1025<def> = MOV r0
538 // %reg1026<def> = ADD %reg1024, %reg1025
539 // r0 = MOV %reg1026
540 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000541 unsigned ToRegA = getMappedReg(regA, DstRegMap);
542 if (ToRegA) {
543 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
544 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
545 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
546 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
547 if (BComp != CComp)
548 return !BComp && CComp;
549 }
Evan Cheng870b8072009-03-01 02:03:43 +0000550
Evan Chengd498c8f2009-01-25 03:53:59 +0000551 // If there is a use of regC between its last def (could be livein) and this
552 // instruction, then bail.
553 unsigned LastDefC = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000554 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000555 return false;
556
557 // If there is a use of regB between its last def (could be livein) and this
558 // instruction, then go ahead and make this transformation.
559 unsigned LastDefB = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000560 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000561 return true;
562
563 // Since there are no intervening uses for both registers, then commute
564 // if the def of regC is closer. Its live interval is shorter.
565 return LastDefB && LastDefC && LastDefC > LastDefB;
566}
567
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000568/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000569/// block, distance map, and live variables if needed. Return true if it is
570/// successful.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000571bool TwoAddressInstructionPass::
572commuteInstruction(MachineBasicBlock::iterator &mi,
573 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000574 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000575 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000576 MachineInstr *NewMI = TII->commuteInstruction(MI);
577
578 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000579 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000580 return false;
581 }
582
David Greeneeb00b182010-01-05 01:24:21 +0000583 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwarich1ea93c72013-02-23 23:13:28 +0000584 assert(NewMI == MI &&
585 "TargetInstrInfo::commuteInstruction() should not return a new "
586 "instruction unless it was requested.");
Evan Cheng870b8072009-03-01 02:03:43 +0000587
588 // Update source register map.
589 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
590 if (FromRegC) {
591 unsigned RegA = MI->getOperand(0).getReg();
592 SrcRegMap[RegA] = FromRegC;
593 }
594
Evan Cheng81913712009-01-23 23:27:33 +0000595 return true;
596}
597
Evan Chenge6f350d2009-03-30 21:34:07 +0000598/// isProfitableToConv3Addr - Return true if it is profitable to convert the
599/// given 2-address instruction to a 3-address one.
600bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000601TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000602 // Look for situations like this:
603 // %reg1024<def> = MOV r1
604 // %reg1025<def> = MOV r0
605 // %reg1026<def> = ADD %reg1024, %reg1025
606 // r2 = MOV %reg1026
607 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000608 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
609 if (!FromRegB)
610 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000611 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000612 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000613}
614
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000615/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000616/// three address one. Return true if this transformation was successful.
617bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000618TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000619 MachineBasicBlock::iterator &nmi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000620 unsigned RegA, unsigned RegB,
621 unsigned Dist) {
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000622 // FIXME: Why does convertToThreeAddress() need an iterator reference?
623 MachineFunction::iterator MFI = MBB;
624 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
625 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000626 if (!NewMI)
627 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000628
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000629 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
630 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
631 bool Sunk = false;
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000632
Cameron Zwarich61892882013-02-20 22:10:02 +0000633 if (LIS)
634 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000635
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000636 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
637 // FIXME: Temporary workaround. If the new instruction doesn't
638 // uses RegB, convertToThreeAddress must have created more
639 // then one instruction.
640 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000641
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000642 MBB->erase(mi); // Nuke the old inst.
Evan Cheng4d96c632011-02-10 02:20:55 +0000643
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000644 if (!Sunk) {
645 DistanceMap.insert(std::make_pair(NewMI, Dist));
646 mi = NewMI;
647 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000648 }
649
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000650 // Update source and destination register maps.
651 SrcRegMap.erase(RegA);
652 DstRegMap.erase(RegB);
653 return true;
Evan Chenge6f350d2009-03-30 21:34:07 +0000654}
655
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000656/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000657/// is a copy or a two-address instruction.
658void
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000659TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Chengf06e6c22011-03-02 01:08:17 +0000660 SmallVector<unsigned, 4> VirtRegPairs;
661 bool IsDstPhys;
662 bool IsCopy = false;
663 unsigned NewReg = 0;
664 unsigned Reg = DstReg;
665 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
666 NewReg, IsDstPhys)) {
667 if (IsCopy && !Processed.insert(UseMI))
668 break;
669
670 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
671 if (DI != DistanceMap.end())
672 // Earlier in the same MBB.Reached via a back edge.
673 break;
674
675 if (IsDstPhys) {
676 VirtRegPairs.push_back(NewReg);
677 break;
678 }
679 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
680 if (!isNew)
681 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
682 VirtRegPairs.push_back(NewReg);
683 Reg = NewReg;
684 }
685
686 if (!VirtRegPairs.empty()) {
687 unsigned ToReg = VirtRegPairs.back();
688 VirtRegPairs.pop_back();
689 while (!VirtRegPairs.empty()) {
690 unsigned FromReg = VirtRegPairs.back();
691 VirtRegPairs.pop_back();
692 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
693 if (!isNew)
694 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
695 ToReg = FromReg;
696 }
697 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
698 if (!isNew)
699 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
700 }
701}
702
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000703/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000704/// if it's a copy. For a copy instruction, we find the physical registers the
705/// source and destination registers might be mapped to. These are kept in
706/// point-to maps used to determine future optimizations. e.g.
707/// v1024 = mov r0
708/// v1025 = mov r1
709/// v1026 = add v1024, v1025
710/// r1 = mov r1026
711/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
712/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
713/// potentially joined with r1 on the output side. It's worthwhile to commute
714/// 'add' to eliminate a copy.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000715void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Cheng870b8072009-03-01 02:03:43 +0000716 if (Processed.count(MI))
717 return;
718
719 bool IsSrcPhys, IsDstPhys;
720 unsigned SrcReg, DstReg;
721 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
722 return;
723
724 if (IsDstPhys && !IsSrcPhys)
725 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
726 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000727 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
728 if (!isNew)
729 assert(SrcRegMap[DstReg] == SrcReg &&
730 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000731
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000732 scanUses(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000733 }
734
735 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000736 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000737}
738
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000739/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000740/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
741/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000742bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000743rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000744 MachineBasicBlock::iterator &nmi,
745 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000746 // Bail immediately if we don't have LV or LIS available. We use them to find
747 // kills efficiently.
748 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000749 return false;
750
Evan Cheng2a4410d2011-11-14 19:48:55 +0000751 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000752 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000753 if (DI == DistanceMap.end())
754 // Must be created from unfolded load. Don't waste time trying this.
755 return false;
756
Cameron Zwarich80885e52013-02-23 04:49:13 +0000757 MachineInstr *KillMI = 0;
758 if (LIS) {
759 LiveInterval &LI = LIS->getInterval(Reg);
760 assert(LI.end() != LI.begin() &&
761 "Reg should not have empty live interval.");
762
763 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
764 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
765 if (I != LI.end() && I->start < MBBEndIdx)
766 return false;
767
768 --I;
769 KillMI = LIS->getInstructionFromIndex(I->end);
770 } else {
771 KillMI = LV->getVarInfo(Reg).findKill(MBB);
772 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000773 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000774 // Don't mess with copies, they may be coalesced later.
775 return false;
776
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000777 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
778 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000779 // Don't move pass calls, etc.
780 return false;
781
782 unsigned DstReg;
783 if (isTwoAddrUse(*KillMI, Reg, DstReg))
784 return false;
785
Evan Chengf1784182011-11-15 06:26:51 +0000786 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000787 if (!MI->isSafeToMove(TII, AA, SeenStore))
788 return false;
789
790 if (TII->getInstrLatency(InstrItins, MI) > 1)
791 // FIXME: Needs more sophisticated heuristics.
792 return false;
793
794 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000795 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000796 SmallSet<unsigned, 2> Defs;
797 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
798 const MachineOperand &MO = MI->getOperand(i);
799 if (!MO.isReg())
800 continue;
801 unsigned MOReg = MO.getReg();
802 if (!MOReg)
803 continue;
804 if (MO.isDef())
805 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000806 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000807 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000808 if (MOReg != Reg && (MO.isKill() ||
809 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Cheng9bad88a2011-11-16 03:47:42 +0000810 Kills.insert(MOReg);
811 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000812 }
813
814 // Move the copies connected to MI down as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000815 MachineBasicBlock::iterator Begin = MI;
816 MachineBasicBlock::iterator AfterMI = llvm::next(Begin);
817
818 MachineBasicBlock::iterator End = AfterMI;
819 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
820 Defs.insert(End->getOperand(0).getReg());
821 ++End;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000822 }
823
824 // Check if the reschedule will not break depedencies.
825 unsigned NumVisited = 0;
826 MachineBasicBlock::iterator KillPos = KillMI;
827 ++KillPos;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000828 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000829 MachineInstr *OtherMI = I;
830 // DBG_VALUE cannot be counted against the limit.
831 if (OtherMI->isDebugValue())
832 continue;
833 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
834 return false;
835 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000836 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
837 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000838 // Don't move pass calls, etc.
839 return false;
840 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
841 const MachineOperand &MO = OtherMI->getOperand(i);
842 if (!MO.isReg())
843 continue;
844 unsigned MOReg = MO.getReg();
845 if (!MOReg)
846 continue;
847 if (MO.isDef()) {
848 if (Uses.count(MOReg))
849 // Physical register use would be clobbered.
850 return false;
851 if (!MO.isDead() && Defs.count(MOReg))
852 // May clobber a physical register def.
853 // FIXME: This may be too conservative. It's ok if the instruction
854 // is sunken completely below the use.
855 return false;
856 } else {
857 if (Defs.count(MOReg))
858 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000859 bool isKill = MO.isKill() ||
860 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Cheng9bad88a2011-11-16 03:47:42 +0000861 if (MOReg != Reg &&
Cameron Zwarich80885e52013-02-23 04:49:13 +0000862 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000863 // Don't want to extend other live ranges and update kills.
864 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000865 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000866 // We can't schedule across a use of the register in question.
867 return false;
868 // Ensure that if this is register in question, its the kill we expect.
869 assert((MOReg != Reg || OtherMI == KillMI) &&
870 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000871 }
872 }
873 }
874
875 // Move debug info as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000876 while (Begin != MBB->begin() && llvm::prior(Begin)->isDebugValue())
877 --Begin;
878
879 nmi = End;
880 MachineBasicBlock::iterator InsertPos = KillPos;
881 if (LIS) {
882 // We have to move the copies first so that the MBB is still well-formed
883 // when calling handleMove().
884 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
885 MachineInstr *CopyMI = MBBI;
886 ++MBBI;
887 MBB->splice(InsertPos, MBB, CopyMI);
888 LIS->handleMove(CopyMI);
889 InsertPos = CopyMI;
890 }
891 End = llvm::next(MachineBasicBlock::iterator(MI));
892 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000893
894 // Copies following MI may have been moved as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000895 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000896 DistanceMap.erase(DI);
897
Chandler Carruth7d532c82012-07-15 03:29:46 +0000898 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +0000899 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000900 LIS->handleMove(MI);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000901 } else {
902 LV->removeVirtualRegisterKilled(Reg, KillMI);
903 LV->addVirtualRegisterKilled(Reg, MI);
904 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000905
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000906 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000907 return true;
908}
909
910/// isDefTooClose - Return true if the re-scheduling will put the given
911/// instruction too close to the defs of its register dependencies.
912bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000913 MachineInstr *MI) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000914 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
915 DE = MRI->def_end(); DI != DE; ++DI) {
916 MachineInstr *DefMI = &*DI;
917 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
918 continue;
919 if (DefMI == MI)
920 return true; // MI is defining something KillMI uses
921 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
922 if (DDI == DistanceMap.end())
923 return true; // Below MI
924 unsigned DefDist = DDI->second;
925 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000926 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000927 return true;
928 }
929 return false;
930}
931
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000932/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000933/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
934/// current two-address instruction in order to eliminate the need for the
935/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000936bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000937rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000938 MachineBasicBlock::iterator &nmi,
939 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000940 // Bail immediately if we don't have LV or LIS available. We use them to find
941 // kills efficiently.
942 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000943 return false;
944
Evan Cheng2a4410d2011-11-14 19:48:55 +0000945 MachineInstr *MI = &*mi;
946 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
947 if (DI == DistanceMap.end())
948 // Must be created from unfolded load. Don't waste time trying this.
949 return false;
950
Cameron Zwarich80885e52013-02-23 04:49:13 +0000951 MachineInstr *KillMI = 0;
952 if (LIS) {
953 LiveInterval &LI = LIS->getInterval(Reg);
954 assert(LI.end() != LI.begin() &&
955 "Reg should not have empty live interval.");
956
957 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
958 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
959 if (I != LI.end() && I->start < MBBEndIdx)
960 return false;
961
962 --I;
963 KillMI = LIS->getInstructionFromIndex(I->end);
964 } else {
965 KillMI = LV->getVarInfo(Reg).findKill(MBB);
966 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000967 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000968 // Don't mess with copies, they may be coalesced later.
969 return false;
970
971 unsigned DstReg;
972 if (isTwoAddrUse(*KillMI, Reg, DstReg))
973 return false;
974
Evan Chengf1784182011-11-15 06:26:51 +0000975 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000976 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
977 return false;
978
979 SmallSet<unsigned, 2> Uses;
980 SmallSet<unsigned, 2> Kills;
981 SmallSet<unsigned, 2> Defs;
982 SmallSet<unsigned, 2> LiveDefs;
983 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
984 const MachineOperand &MO = KillMI->getOperand(i);
985 if (!MO.isReg())
986 continue;
987 unsigned MOReg = MO.getReg();
988 if (MO.isUse()) {
989 if (!MOReg)
990 continue;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000991 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000992 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000993 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
994 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000995 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000996 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000997 if (isKill && MOReg != Reg)
Evan Cheng2a4410d2011-11-14 19:48:55 +0000998 Kills.insert(MOReg);
999 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1000 Defs.insert(MOReg);
1001 if (!MO.isDead())
1002 LiveDefs.insert(MOReg);
1003 }
1004 }
1005
1006 // Check if the reschedule will not break depedencies.
1007 unsigned NumVisited = 0;
1008 MachineBasicBlock::iterator KillPos = KillMI;
1009 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1010 MachineInstr *OtherMI = I;
1011 // DBG_VALUE cannot be counted against the limit.
1012 if (OtherMI->isDebugValue())
1013 continue;
1014 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1015 return false;
1016 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001017 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1018 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001019 // Don't move pass calls, etc.
1020 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +00001021 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001022 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1023 const MachineOperand &MO = OtherMI->getOperand(i);
1024 if (!MO.isReg())
1025 continue;
1026 unsigned MOReg = MO.getReg();
1027 if (!MOReg)
1028 continue;
1029 if (MO.isUse()) {
1030 if (Defs.count(MOReg))
1031 // Moving KillMI can clobber the physical register if the def has
1032 // not been seen.
1033 return false;
1034 if (Kills.count(MOReg))
1035 // Don't want to extend other live ranges and update kills.
1036 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +00001037 if (OtherMI != MI && MOReg == Reg &&
1038 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruth7d532c82012-07-15 03:29:46 +00001039 // We can't schedule across a use of the register in question.
1040 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001041 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +00001042 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001043 }
1044 }
Evan Chengae7db7a2011-11-16 03:05:12 +00001045
1046 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1047 unsigned MOReg = OtherDefs[i];
1048 if (Uses.count(MOReg))
1049 return false;
1050 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1051 LiveDefs.count(MOReg))
1052 return false;
1053 // Physical register def is seen.
1054 Defs.erase(MOReg);
1055 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001056 }
1057
1058 // Move the old kill above MI, don't forget to move debug info as well.
1059 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +00001060 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1061 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001062 MachineBasicBlock::iterator From = KillMI;
1063 MachineBasicBlock::iterator To = llvm::next(From);
1064 while (llvm::prior(From)->isDebugValue())
1065 --From;
1066 MBB->splice(InsertPos, MBB, From, To);
1067
Evan Cheng2bee6a82011-11-16 03:33:08 +00001068 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001069 DistanceMap.erase(DI);
1070
Chandler Carruth7d532c82012-07-15 03:29:46 +00001071 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +00001072 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001073 LIS->handleMove(KillMI);
Cameron Zwarich80885e52013-02-23 04:49:13 +00001074 } else {
1075 LV->removeVirtualRegisterKilled(Reg, KillMI);
1076 LV->addVirtualRegisterKilled(Reg, MI);
1077 }
Chandler Carruth7d532c82012-07-15 03:29:46 +00001078
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001079 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001080 return true;
1081}
1082
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001083/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +00001084/// pair of tied register operands, attempt some transformations that may
1085/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001086/// coalescing away the register copy. Returns true if no copy needs to be
1087/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001088/// because mi was rescheduled, and will be visited again later). If the
1089/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilsoncc80df92009-09-03 20:58:42 +00001090bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001091tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001092 MachineBasicBlock::iterator &nmi,
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001093 unsigned SrcIdx, unsigned DstIdx,
1094 unsigned Dist, bool shouldOnlyCommute) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001095 if (OptLevel == CodeGenOpt::None)
1096 return false;
1097
Evan Cheng2a4410d2011-11-14 19:48:55 +00001098 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001099 unsigned regA = MI.getOperand(DstIdx).getReg();
1100 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001101
1102 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1103 "cannot make instruction into two-address form");
Cameron Zwaricha931a122013-02-21 22:58:42 +00001104 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001105
Evan Chengd99d68b2012-05-03 01:45:13 +00001106 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001107 scanUses(regA);
Evan Chengd99d68b2012-05-03 01:45:13 +00001108
Bob Wilsoncc80df92009-09-03 20:58:42 +00001109 // Check if it is profitable to commute the operands.
1110 unsigned SrcOp1, SrcOp2;
1111 unsigned regC = 0;
1112 unsigned regCIdx = ~0U;
1113 bool TryCommute = false;
1114 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001115 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001116 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001117 if (SrcIdx == SrcOp1)
1118 regCIdx = SrcOp2;
1119 else if (SrcIdx == SrcOp2)
1120 regCIdx = SrcOp1;
1121
1122 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001123 regC = MI.getOperand(regCIdx).getReg();
Cameron Zwaricha931a122013-02-21 22:58:42 +00001124 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001125 // If C dies but B does not, swap the B and C operands.
1126 // This makes the live ranges of A and C joinable.
1127 TryCommute = true;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001128 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001129 TryCommute = true;
1130 AggressiveCommute = true;
1131 }
1132 }
1133 }
1134
1135 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001136 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001137 ++NumCommuted;
1138 if (AggressiveCommute)
1139 ++NumAggrCommuted;
1140 return false;
1141 }
1142
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001143 if (shouldOnlyCommute)
1144 return false;
1145
Evan Cheng2a4410d2011-11-14 19:48:55 +00001146 // If there is one more use of regB later in the same MBB, consider
1147 // re-schedule this MI below it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001148 if (rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001149 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001150 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001151 }
1152
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001153 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001154 // This instruction is potentially convertible to a true
1155 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001156 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001157 // Try to convert it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001158 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001159 ++NumConvertedTo3Addr;
1160 return true; // Done with this instruction.
1161 }
1162 }
1163 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001164
Evan Cheng2a4410d2011-11-14 19:48:55 +00001165 // If there is one more use of regB later in the same MBB, consider
1166 // re-schedule it before this MI if it's legal.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001167 if (rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001168 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001169 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001170 }
1171
Dan Gohman584fedf2010-06-21 22:17:20 +00001172 // If this is an instruction with a load folded into it, try unfolding
1173 // the load, e.g. avoid this:
1174 // movq %rdx, %rcx
1175 // addq (%rax), %rcx
1176 // in favor of this:
1177 // movq (%rax), %rcx
1178 // addq %rdx, %rcx
1179 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001180 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001181 // Determine if a load can be unfolded.
1182 unsigned LoadRegIndex;
1183 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001184 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001185 /*UnfoldLoad=*/true,
1186 /*UnfoldStore=*/false,
1187 &LoadRegIndex);
1188 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001189 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1190 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001191 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001192 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001193 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001194 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001195 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001196 unsigned Reg = MRI->createVirtualRegister(RC);
1197 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001198 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001199 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1200 NewMIs)) {
1201 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1202 return false;
1203 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001204 assert(NewMIs.size() == 2 &&
1205 "Unfolded a load into multiple instructions!");
1206 // The load was previously folded, so this is the only use.
1207 NewMIs[1]->addRegisterKilled(Reg, TRI);
1208
1209 // Tentatively insert the instructions into the block so that they
1210 // look "normal" to the transformation logic.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001211 MBB->insert(mi, NewMIs[0]);
1212 MBB->insert(mi, NewMIs[1]);
Dan Gohman584fedf2010-06-21 22:17:20 +00001213
1214 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1215 << "2addr: NEW INST: " << *NewMIs[1]);
1216
1217 // Transform the instruction, now that it no longer has a load.
1218 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1219 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1220 MachineBasicBlock::iterator NewMI = NewMIs[1];
1221 bool TransformSuccess =
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001222 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Dan Gohman584fedf2010-06-21 22:17:20 +00001223 if (TransformSuccess ||
1224 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1225 // Success, or at least we made an improvement. Keep the unfolded
1226 // instructions and discard the original.
1227 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001228 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1229 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001230 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001231 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1232 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001233 if (MO.isKill()) {
1234 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001235 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001236 else {
1237 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1238 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001239 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001240 }
1241 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001242 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001243 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1244 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1245 else {
1246 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1247 "Dead flag missing after load unfold!");
1248 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1249 }
1250 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001251 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001252 }
1253 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1254 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001255
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001256 SmallVector<unsigned, 4> OrigRegs;
1257 if (LIS) {
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001258 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1259 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1260 if (MOI->isReg())
1261 OrigRegs.push_back(MOI->getReg());
1262 }
1263 }
1264
Evan Cheng2a4410d2011-11-14 19:48:55 +00001265 MI.eraseFromParent();
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001266
1267 // Update LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001268 if (LIS) {
1269 MachineBasicBlock::iterator Begin(NewMIs[0]);
1270 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001271 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001272 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001273
Dan Gohman584fedf2010-06-21 22:17:20 +00001274 mi = NewMIs[1];
1275 if (TransformSuccess)
1276 return true;
1277 } else {
1278 // Transforming didn't eliminate the tie and didn't lead to an
1279 // improvement. Clean up the unfolded instructions and keep the
1280 // original.
1281 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1282 NewMIs[0]->eraseFromParent();
1283 NewMIs[1]->eraseFromParent();
1284 }
1285 }
1286 }
1287 }
1288
Bob Wilsoncc80df92009-09-03 20:58:42 +00001289 return false;
1290}
1291
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001292// Collect tied operands of MI that need to be handled.
1293// Rewrite trivial cases immediately.
1294// Return true if any tied operands where found, including the trivial ones.
1295bool TwoAddressInstructionPass::
1296collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1297 const MCInstrDesc &MCID = MI->getDesc();
1298 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001299 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001300
1301 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1302 unsigned DstIdx = 0;
1303 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1304 continue;
1305 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001306 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1307 MachineOperand &DstMO = MI->getOperand(DstIdx);
1308 unsigned SrcReg = SrcMO.getReg();
1309 unsigned DstReg = DstMO.getReg();
1310 // Tied constraint already satisfied?
1311 if (SrcReg == DstReg)
1312 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001313
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001314 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001315
1316 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001317 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001318 // Constrain the DstReg register class if required.
1319 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1320 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1321 TRI, *MF))
1322 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001323 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001324 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1325 continue;
1326 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001327 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001328 }
1329 return AnyOps;
1330}
1331
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001332// Process a list of tied MI operands that all use the same source register.
1333// The tied pairs are of the form (SrcIdx, DstIdx).
1334void
1335TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1336 TiedPairList &TiedPairs,
1337 unsigned &Dist) {
1338 bool IsEarlyClobber = false;
Cameron Zwarich6cf93d72013-02-20 06:46:46 +00001339 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1340 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1341 IsEarlyClobber |= DstMO.isEarlyClobber();
1342 }
1343
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001344 bool RemovedKillFlag = false;
1345 bool AllUsesCopied = true;
1346 unsigned LastCopiedReg = 0;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001347 SlotIndex LastCopyIdx;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001348 unsigned RegB = 0;
1349 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1350 unsigned SrcIdx = TiedPairs[tpi].first;
1351 unsigned DstIdx = TiedPairs[tpi].second;
1352
1353 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1354 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001355
1356 // Grab RegB from the instruction because it may have changed if the
1357 // instruction was commuted.
1358 RegB = MI->getOperand(SrcIdx).getReg();
1359
1360 if (RegA == RegB) {
1361 // The register is tied to multiple destinations (or else we would
1362 // not have continued this far), but this use of the register
1363 // already matches the tied destination. Leave it.
1364 AllUsesCopied = false;
1365 continue;
1366 }
1367 LastCopiedReg = RegA;
1368
1369 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1370 "cannot make instruction into two-address form");
1371
1372#ifndef NDEBUG
1373 // First, verify that we don't have a use of "a" in the instruction
1374 // (a = b + a for example) because our transformation will not
1375 // work. This should never occur because we are in SSA form.
1376 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1377 assert(i == DstIdx ||
1378 !MI->getOperand(i).isReg() ||
1379 MI->getOperand(i).getReg() != RegA);
1380#endif
1381
1382 // Emit a copy.
1383 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1384 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1385
1386 // Update DistanceMap.
1387 MachineBasicBlock::iterator PrevMI = MI;
1388 --PrevMI;
1389 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1390 DistanceMap[MI] = ++Dist;
1391
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001392 if (LIS) {
1393 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1394
1395 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1396 LiveInterval &LI = LIS->getInterval(RegA);
1397 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1398 SlotIndex endIdx =
1399 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1400 LI.addRange(LiveRange(LastCopyIdx, endIdx, VNI));
1401 }
1402 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001403
1404 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1405
1406 MachineOperand &MO = MI->getOperand(SrcIdx);
1407 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1408 "inconsistent operand info for 2-reg pass");
1409 if (MO.isKill()) {
1410 MO.setIsKill(false);
1411 RemovedKillFlag = true;
1412 }
1413
1414 // Make sure regA is a legal regclass for the SrcIdx operand.
1415 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1416 TargetRegisterInfo::isVirtualRegister(RegB))
1417 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1418
1419 MO.setReg(RegA);
1420
1421 // Propagate SrcRegMap.
1422 SrcRegMap[RegA] = RegB;
1423 }
1424
1425
1426 if (AllUsesCopied) {
1427 if (!IsEarlyClobber) {
1428 // Replace other (un-tied) uses of regB with LastCopiedReg.
1429 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1430 MachineOperand &MO = MI->getOperand(i);
1431 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1432 if (MO.isKill()) {
1433 MO.setIsKill(false);
1434 RemovedKillFlag = true;
1435 }
1436 MO.setReg(LastCopiedReg);
1437 }
1438 }
1439 }
1440
1441 // Update live variables for regB.
1442 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1443 MachineBasicBlock::iterator PrevMI = MI;
1444 --PrevMI;
1445 LV->addVirtualRegisterKilled(RegB, PrevMI);
1446 }
1447
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001448 // Update LiveIntervals.
1449 if (LIS) {
1450 LiveInterval &LI = LIS->getInterval(RegB);
1451 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1452 LiveInterval::const_iterator I = LI.find(MIIdx);
1453 assert(I != LI.end() && "RegB must be live-in to use.");
1454
1455 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1456 if (I->end == UseIdx)
1457 LI.removeRange(LastCopyIdx, UseIdx);
1458 }
1459
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001460 } else if (RemovedKillFlag) {
1461 // Some tied uses of regB matched their destination registers, so
1462 // regB is still used in this instruction, but a kill flag was
1463 // removed from a different tied use of regB, so now we need to add
1464 // a kill flag to one of the remaining uses of regB.
1465 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1466 MachineOperand &MO = MI->getOperand(i);
1467 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1468 MO.setIsKill(true);
1469 break;
1470 }
1471 }
1472 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001473}
1474
Bill Wendling637980e2008-05-10 00:12:52 +00001475/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001476///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001477bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1478 MF = &Func;
1479 const TargetMachine &TM = MF->getTarget();
1480 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001481 TII = TM.getInstrInfo();
1482 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001483 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001484 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001485 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001486 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001487 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001488
Misha Brukman75fa4e42004-07-22 15:26:23 +00001489 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001490
David Greeneeb00b182010-01-05 01:24:21 +00001491 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001492 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001493 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001494
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001495 // This pass takes the function out of SSA form.
1496 MRI->leaveSSA();
1497
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001498 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001499 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1500 MBBI != MBBE; ++MBBI) {
1501 MBB = MBBI;
Evan Cheng7543e582008-06-18 07:49:14 +00001502 unsigned Dist = 0;
1503 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001504 SrcRegMap.clear();
1505 DstRegMap.clear();
1506 Processed.clear();
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001507 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001508 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001509 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001510 if (mi->isDebugValue()) {
1511 mi = nmi;
1512 continue;
1513 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001514
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001515 // Expand REG_SEQUENCE instructions. This will position mi at the first
1516 // expanded instruction.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001517 if (mi->isRegSequence())
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001518 eliminateRegSequence(mi);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001519
Evan Cheng7543e582008-06-18 07:49:14 +00001520 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001521
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001522 processCopy(&*mi);
Evan Cheng870b8072009-03-01 02:03:43 +00001523
Bob Wilsoncc80df92009-09-03 20:58:42 +00001524 // First scan through all the tied register uses in this instruction
1525 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001526 if (!collectTiedOperands(mi, TiedOperands)) {
1527 mi = nmi;
1528 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001529 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001530
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001531 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001532 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001533 DEBUG(dbgs() << '\t' << *mi);
1534
Chandler Carruth32d75be2012-07-18 18:58:22 +00001535 // If the instruction has a single pair of tied operands, try some
1536 // transformations that may either eliminate the tied operands or
1537 // improve the opportunities for coalescing away the register copy.
1538 if (TiedOperands.size() == 1) {
1539 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1540 = TiedOperands.begin()->second;
1541 if (TiedPairs.size() == 1) {
1542 unsigned SrcIdx = TiedPairs[0].first;
1543 unsigned DstIdx = TiedPairs[0].second;
1544 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1545 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1546 if (SrcReg != DstReg &&
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001547 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
Chandler Carruth32d75be2012-07-18 18:58:22 +00001548 // The tied operands have been eliminated or shifted further down the
1549 // block to ease elimination. Continue processing with 'nmi'.
1550 TiedOperands.clear();
1551 mi = nmi;
1552 continue;
1553 }
1554 }
1555 }
1556
Bob Wilsoncc80df92009-09-03 20:58:42 +00001557 // Now iterate over the information collected above.
1558 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1559 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001560 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001561 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001562 }
Bill Wendling637980e2008-05-10 00:12:52 +00001563
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001564 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1565 if (mi->isInsertSubreg()) {
1566 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1567 // To %reg:subidx = COPY %subreg
1568 unsigned SubIdx = mi->getOperand(3).getImm();
1569 mi->RemoveOperand(3);
1570 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1571 mi->getOperand(0).setSubReg(SubIdx);
1572 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1573 mi->RemoveOperand(1);
1574 mi->setDesc(TII->get(TargetOpcode::COPY));
1575 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001576 }
1577
Bob Wilsoncc80df92009-09-03 20:58:42 +00001578 // Clear TiedOperands here instead of at the top of the loop
1579 // since most instructions do not have tied operands.
1580 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001581 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001582 }
1583 }
1584
Cameron Zwarich767e0432013-02-20 06:46:34 +00001585 if (LIS)
1586 MF->verify(this, "After two-address instruction pass");
1587
Misha Brukman75fa4e42004-07-22 15:26:23 +00001588 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001589}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001590
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001591/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001592///
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001593/// The instruction is turned into a sequence of sub-register copies:
1594///
1595/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1596///
1597/// Becomes:
1598///
1599/// %dst:ssub0<def,undef> = COPY %v1
1600/// %dst:ssub1<def> = COPY %v2
1601///
1602void TwoAddressInstructionPass::
1603eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1604 MachineInstr *MI = MBBI;
1605 unsigned DstReg = MI->getOperand(0).getReg();
1606 if (MI->getOperand(0).getSubReg() ||
1607 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1608 !(MI->getNumOperands() & 1)) {
1609 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1610 llvm_unreachable(0);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001611 }
1612
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001613 SmallVector<unsigned, 4> OrigRegs;
1614 if (LIS) {
1615 OrigRegs.push_back(MI->getOperand(0).getReg());
1616 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1617 OrigRegs.push_back(MI->getOperand(i).getReg());
1618 }
1619
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001620 bool DefEmitted = false;
1621 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1622 MachineOperand &UseMO = MI->getOperand(i);
1623 unsigned SrcReg = UseMO.getReg();
1624 unsigned SubIdx = MI->getOperand(i+1).getImm();
1625 // Nothing needs to be inserted for <undef> operands.
1626 if (UseMO.isUndef())
1627 continue;
1628
1629 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1630 // might insert a COPY that uses SrcReg after is was killed.
1631 bool isKill = UseMO.isKill();
1632 if (isKill)
1633 for (unsigned j = i + 2; j < e; j += 2)
1634 if (MI->getOperand(j).getReg() == SrcReg) {
1635 MI->getOperand(j).setIsKill();
1636 UseMO.setIsKill(false);
1637 isKill = false;
1638 break;
1639 }
1640
1641 // Insert the sub-register copy.
1642 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1643 TII->get(TargetOpcode::COPY))
1644 .addReg(DstReg, RegState::Define, SubIdx)
1645 .addOperand(UseMO);
1646
1647 // The first def needs an <undef> flag because there is no live register
1648 // before it.
1649 if (!DefEmitted) {
1650 CopyMI->getOperand(0).setIsUndef(true);
1651 // Return an iterator pointing to the first inserted instr.
1652 MBBI = CopyMI;
1653 }
1654 DefEmitted = true;
1655
1656 // Update LiveVariables' kill info.
1657 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1658 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1659
1660 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1661 }
1662
David Blaikiefdf45172013-02-20 07:39:20 +00001663 MachineBasicBlock::iterator EndMBBI =
1664 llvm::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001665
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001666 if (!DefEmitted) {
1667 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1668 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1669 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1670 MI->RemoveOperand(j);
1671 } else {
1672 DEBUG(dbgs() << "Eliminated: " << *MI);
1673 MI->eraseFromParent();
1674 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001675
1676 // Udpate LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001677 if (LIS)
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001678 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001679}