blob: 2eb9f6034339ac517787d76ebe225c8ec3e32717 [file] [log] [blame]
David Goodwin83704852009-10-26 16:59:04 +00001//===----- CriticalAntiDepBreaker.cpp - Anti-dep breaker -------- ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the CriticalAntiDepBreaker class, which
11// implements register anti-dependence breaking along a blocks
12// critical path during post-RA scheduler.
13//
14//===----------------------------------------------------------------------===//
15
David Goodwin83704852009-10-26 16:59:04 +000016#include "CriticalAntiDepBreaker.h"
17#include "llvm/CodeGen/MachineBasicBlock.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
David Goodwin83704852009-10-26 16:59:04 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000025#include "llvm/Target/TargetSubtargetInfo.h"
David Goodwin83704852009-10-26 16:59:04 +000026
27using namespace llvm;
28
Chandler Carruth1b9dde02014-04-22 02:02:50 +000029#define DEBUG_TYPE "post-RA-sched"
30
Eric Christopherd9134482014-08-04 21:25:23 +000031CriticalAntiDepBreaker::CriticalAntiDepBreaker(MachineFunction &MFi,
32 const RegisterClassInfo &RCI)
33 : AntiDepBreaker(), MF(MFi), MRI(MF.getRegInfo()),
Eric Christopherfc6de422014-08-05 02:39:49 +000034 TII(MF.getSubtarget().getInstrInfo()),
35 TRI(MF.getSubtarget().getRegisterInfo()), RegClassInfo(RCI),
36 Classes(TRI->getNumRegs(), nullptr), KillIndices(TRI->getNumRegs(), 0),
37 DefIndices(TRI->getNumRegs(), 0), KeepRegs(TRI->getNumRegs(), false) {}
David Goodwin83704852009-10-26 16:59:04 +000038
39CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
40}
41
42void CriticalAntiDepBreaker::StartBlock(MachineBasicBlock *BB) {
David Goodwina45fe672009-12-09 17:18:22 +000043 const unsigned BBSize = BB->size();
Bill Wendling51a9c0a2010-07-15 19:58:14 +000044 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i) {
45 // Clear out the register class data.
Craig Topperc0196b12014-04-14 00:51:57 +000046 Classes[i] = nullptr;
Bill Wendling51a9c0a2010-07-15 19:58:14 +000047
48 // Initialize the indices to indicate that no registers are live.
David Goodwina45fe672009-12-09 17:18:22 +000049 KillIndices[i] = ~0u;
50 DefIndices[i] = BBSize;
51 }
David Goodwin83704852009-10-26 16:59:04 +000052
53 // Clear "do not change" set.
Benjamin Kramer5d1bca82012-03-17 20:22:57 +000054 KeepRegs.reset();
David Goodwin83704852009-10-26 16:59:04 +000055
Benjamin Kramer8e5af372012-03-16 15:46:47 +000056 bool IsReturnBlock = (BBSize != 0 && BB->back().isReturn());
David Goodwin83704852009-10-26 16:59:04 +000057
Jakob Stoklund Olesenc3386792013-02-05 18:21:52 +000058 // Examine the live-in regs of all successors.
Evan Chengf128bdc2010-06-16 07:35:02 +000059 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
60 SE = BB->succ_end(); SI != SE; ++SI)
61 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
62 E = (*SI)->livein_end(); I != E; ++I) {
Jakob Stoklund Olesen92a00832012-06-01 20:36:54 +000063 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
64 unsigned Reg = *AI;
65 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
66 KillIndices[Reg] = BBSize;
67 DefIndices[Reg] = ~0u;
Evan Chengf128bdc2010-06-16 07:35:02 +000068 }
69 }
70
David Goodwin83704852009-10-26 16:59:04 +000071 // Mark live-out callee-saved registers. In a return block this is
72 // all callee-saved registers. In non-return this is any
73 // callee-saved register that is not saved in the prolog.
74 const MachineFrameInfo *MFI = MF.getFrameInfo();
75 BitVector Pristine = MFI->getPristineRegs(BB);
Craig Topper840beec2014-04-04 05:16:06 +000076 for (const MCPhysReg *I = TRI->getCalleeSavedRegs(&MF); *I; ++I) {
Jakob Stoklund Olesen92a00832012-06-01 20:36:54 +000077 if (!IsReturnBlock && !Pristine.test(*I)) continue;
78 for (MCRegAliasIterator AI(*I, TRI, true); AI.isValid(); ++AI) {
79 unsigned Reg = *AI;
80 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
81 KillIndices[Reg] = BBSize;
82 DefIndices[Reg] = ~0u;
David Goodwin83704852009-10-26 16:59:04 +000083 }
84 }
85}
86
87void CriticalAntiDepBreaker::FinishBlock() {
88 RegRefs.clear();
Benjamin Kramer5d1bca82012-03-17 20:22:57 +000089 KeepRegs.reset();
David Goodwin83704852009-10-26 16:59:04 +000090}
91
92void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
93 unsigned InsertPosIndex) {
Dale Johannesen2061c842010-03-05 00:02:59 +000094 if (MI->isDebugValue())
95 return;
David Goodwin83704852009-10-26 16:59:04 +000096 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
97
Bob Wilsonc57c2202010-10-02 01:49:29 +000098 for (unsigned Reg = 0; Reg != TRI->getNumRegs(); ++Reg) {
99 if (KillIndices[Reg] != ~0u) {
100 // If Reg is currently live, then mark that it can't be renamed as
101 // we don't know the extent of its live-range anymore (now that it
102 // has been scheduled).
103 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
104 KillIndices[Reg] = Count;
105 } else if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
106 // Any register which was defined within the previous scheduling region
107 // may have been rescheduled and its lifetime may overlap with registers
108 // in ways not reflected in our current liveness state. For each such
109 // register, adjust the liveness state to be conservatively correct.
David Goodwin83704852009-10-26 16:59:04 +0000110 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
Bill Wendling51a9c0a2010-07-15 19:58:14 +0000111
David Goodwin83704852009-10-26 16:59:04 +0000112 // Move the def index to the end of the previous region, to reflect
113 // that the def could theoretically have been scheduled at the end.
114 DefIndices[Reg] = InsertPosIndex;
115 }
Bob Wilsonc57c2202010-10-02 01:49:29 +0000116 }
David Goodwin83704852009-10-26 16:59:04 +0000117
118 PrescanInstruction(MI);
119 ScanInstruction(MI, Count);
120}
121
122/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
123/// critical path.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000124static const SDep *CriticalPathStep(const SUnit *SU) {
Craig Topperc0196b12014-04-14 00:51:57 +0000125 const SDep *Next = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000126 unsigned NextDepth = 0;
127 // Find the predecessor edge with the greatest depth.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000128 for (SUnit::const_pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
David Goodwin83704852009-10-26 16:59:04 +0000129 P != PE; ++P) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000130 const SUnit *PredSU = P->getSUnit();
David Goodwin83704852009-10-26 16:59:04 +0000131 unsigned PredLatency = P->getLatency();
132 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
133 // In the case of a latency tie, prefer an anti-dependency edge over
134 // other types of edges.
135 if (NextDepth < PredTotalLatency ||
136 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
137 NextDepth = PredTotalLatency;
138 Next = &*P;
139 }
140 }
141 return Next;
142}
143
144void CriticalAntiDepBreaker::PrescanInstruction(MachineInstr *MI) {
Evan Chengf128bdc2010-06-16 07:35:02 +0000145 // It's not safe to change register allocation for source operands of
Sanjay Patel99475192014-06-24 21:11:51 +0000146 // instructions that have special allocation requirements. Also assume all
147 // registers used in a call must not be changed (ABI).
Evan Chengf128bdc2010-06-16 07:35:02 +0000148 // FIXME: The issue with predicated instruction is more complex. We are being
Bob Wilsonf3ecfd02010-09-10 22:42:21 +0000149 // conservative here because the kill markers cannot be trusted after
Evan Chengf128bdc2010-06-16 07:35:02 +0000150 // if-conversion:
151 // %R6<def> = LDR %SP, %reg0, 92, pred:14, pred:%reg0; mem:LD4[FixedStack14]
152 // ...
153 // STR %R0, %R6<kill>, %reg0, 0, pred:0, pred:%CPSR; mem:ST4[%395]
154 // %R6<def> = LDR %SP, %reg0, 100, pred:0, pred:%CPSR; mem:LD4[FixedStack12]
155 // STR %R0, %R6<kill>, %reg0, 0, pred:14, pred:%reg0; mem:ST4[%396](align=8)
156 //
157 // The first R6 kill is not really a kill since it's killed by a predicated
158 // instruction which may not be executed. The second R6 def may or may not
159 // re-define R6 so it's not safe to change it since the last R6 use cannot be
160 // changed.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000161 bool Special = MI->isCall() ||
162 MI->hasExtraSrcRegAllocReq() ||
Evan Chengf128bdc2010-06-16 07:35:02 +0000163 TII->isPredicated(MI);
164
David Goodwin83704852009-10-26 16:59:04 +0000165 // Scan the register operands for this instruction and update
166 // Classes and RegRefs.
167 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
168 MachineOperand &MO = MI->getOperand(i);
169 if (!MO.isReg()) continue;
170 unsigned Reg = MO.getReg();
171 if (Reg == 0) continue;
Craig Topperc0196b12014-04-14 00:51:57 +0000172 const TargetRegisterClass *NewRC = nullptr;
Jim Grosbach866b74b2010-05-14 21:20:46 +0000173
David Goodwin83704852009-10-26 16:59:04 +0000174 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000175 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin83704852009-10-26 16:59:04 +0000176
177 // For now, only allow the register to be changed if its register
178 // class is consistent across all uses.
179 if (!Classes[Reg] && NewRC)
180 Classes[Reg] = NewRC;
181 else if (!NewRC || Classes[Reg] != NewRC)
182 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
183
184 // Now check for aliases.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000185 for (MCRegAliasIterator AI(Reg, TRI, false); AI.isValid(); ++AI) {
David Goodwin83704852009-10-26 16:59:04 +0000186 // If an alias of the reg is used during the live range, give up.
187 // Note that this allows us to skip checking if AntiDepReg
188 // overlaps with any of the aliases, among other things.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000189 unsigned AliasReg = *AI;
David Goodwin83704852009-10-26 16:59:04 +0000190 if (Classes[AliasReg]) {
191 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
192 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
193 }
194 }
195
196 // If we're still willing to consider this register, note the reference.
197 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
198 RegRefs.insert(std::make_pair(Reg, &MO));
199
Sanjay Pateldc574ab2014-07-03 15:19:40 +0000200 // If this reg is tied and live (Classes[Reg] is set to -1), we can't change
201 // it or any of its sub or super regs. We need to use KeepRegs to mark the
202 // reg because not all uses of the same reg within an instruction are
203 // necessarily tagged as tied.
204 // Example: an x86 "xor %eax, %eax" will have one source operand tied to the
205 // def register but not the second (see PR20020 for details).
206 // FIXME: can this check be relaxed to account for undef uses
207 // of a register? In the above 'xor' example, the uses of %eax are undef, so
208 // earlier instructions could still replace %eax even though the 'xor'
209 // itself can't be changed.
210 if (MI->isRegTiedToUseOperand(i) &&
211 Classes[Reg] == reinterpret_cast<TargetRegisterClass *>(-1)) {
212 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
213 SubRegs.isValid(); ++SubRegs) {
214 KeepRegs.set(*SubRegs);
215 }
216 for (MCSuperRegIterator SuperRegs(Reg, TRI);
217 SuperRegs.isValid(); ++SuperRegs) {
218 KeepRegs.set(*SuperRegs);
219 }
220 }
221
Evan Chengf128bdc2010-06-16 07:35:02 +0000222 if (MO.isUse() && Special) {
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000223 if (!KeepRegs.test(Reg)) {
Chad Rosierabdb1d62013-05-22 23:17:36 +0000224 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
225 SubRegs.isValid(); ++SubRegs)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000226 KeepRegs.set(*SubRegs);
David Goodwin83704852009-10-26 16:59:04 +0000227 }
228 }
229 }
230}
231
232void CriticalAntiDepBreaker::ScanInstruction(MachineInstr *MI,
233 unsigned Count) {
234 // Update liveness.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000235 // Proceeding upwards, registers that are defed but not used in this
David Goodwin83704852009-10-26 16:59:04 +0000236 // instruction are now dead.
David Goodwin83704852009-10-26 16:59:04 +0000237
Evan Chengf128bdc2010-06-16 07:35:02 +0000238 if (!TII->isPredicated(MI)) {
239 // Predicated defs are modeled as read + write, i.e. similar to two
240 // address updates.
241 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
242 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000243
244 if (MO.isRegMask())
245 for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
246 if (MO.clobbersPhysReg(i)) {
247 DefIndices[i] = Count;
248 KillIndices[i] = ~0u;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000249 KeepRegs.reset(i);
Craig Topperc0196b12014-04-14 00:51:57 +0000250 Classes[i] = nullptr;
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000251 RegRefs.erase(i);
252 }
253
Evan Chengf128bdc2010-06-16 07:35:02 +0000254 if (!MO.isReg()) continue;
255 unsigned Reg = MO.getReg();
256 if (Reg == 0) continue;
257 if (!MO.isDef()) continue;
Sanjay Pateldc574ab2014-07-03 15:19:40 +0000258
259 // If we've already marked this reg as unchangeable, carry on.
260 if (KeepRegs.test(Reg)) continue;
261
Evan Chengf128bdc2010-06-16 07:35:02 +0000262 // Ignore two-addr defs.
263 if (MI->isRegTiedToUseOperand(i)) continue;
264
Sanjay Pateld26358e2014-08-06 15:58:15 +0000265 // For the reg itself and all subregs: update the def to current;
266 // reset the kill state, any restrictions, and references.
267 for (MCSubRegIterator SRI(Reg, TRI, true); SRI.isValid(); ++SRI) {
268 unsigned SubregReg = *SRI;
Evan Chengf128bdc2010-06-16 07:35:02 +0000269 DefIndices[SubregReg] = Count;
270 KillIndices[SubregReg] = ~0u;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000271 KeepRegs.reset(SubregReg);
Craig Topperc0196b12014-04-14 00:51:57 +0000272 Classes[SubregReg] = nullptr;
Evan Chengf128bdc2010-06-16 07:35:02 +0000273 RegRefs.erase(SubregReg);
274 }
275 // Conservatively mark super-registers as unusable.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000276 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR)
277 Classes[*SR] = reinterpret_cast<TargetRegisterClass *>(-1);
David Goodwin83704852009-10-26 16:59:04 +0000278 }
279 }
280 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
281 MachineOperand &MO = MI->getOperand(i);
282 if (!MO.isReg()) continue;
283 unsigned Reg = MO.getReg();
284 if (Reg == 0) continue;
285 if (!MO.isUse()) continue;
286
Craig Topperc0196b12014-04-14 00:51:57 +0000287 const TargetRegisterClass *NewRC = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000288 if (i < MI->getDesc().getNumOperands())
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000289 NewRC = TII->getRegClass(MI->getDesc(), i, TRI, MF);
David Goodwin83704852009-10-26 16:59:04 +0000290
291 // For now, only allow the register to be changed if its register
292 // class is consistent across all uses.
293 if (!Classes[Reg] && NewRC)
294 Classes[Reg] = NewRC;
295 else if (!NewRC || Classes[Reg] != NewRC)
296 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
297
298 RegRefs.insert(std::make_pair(Reg, &MO));
299
300 // It wasn't previously live but now it is, this is a kill.
Sanjay Pateld26358e2014-08-06 15:58:15 +0000301 // Repeat for all aliases.
302 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000303 unsigned AliasReg = *AI;
David Goodwin83704852009-10-26 16:59:04 +0000304 if (KillIndices[AliasReg] == ~0u) {
305 KillIndices[AliasReg] = Count;
306 DefIndices[AliasReg] = ~0u;
307 }
308 }
309 }
310}
311
Andrew Trick4b491872011-02-08 17:39:46 +0000312// Check all machine operands that reference the antidependent register and must
313// be replaced by NewReg. Return true if any of their parent instructions may
314// clobber the new register.
315//
316// Note: AntiDepReg may be referenced by a two-address instruction such that
317// it's use operand is tied to a def operand. We guard against the case in which
318// the two-address instruction also defines NewReg, as may happen with
319// pre/postincrement loads. In this case, both the use and def operands are in
320// RegRefs because the def is inserted by PrescanInstruction and not erased
Sanjay Patel99475192014-06-24 21:11:51 +0000321// during ScanInstruction. So checking for an instruction with definitions of
Andrew Trick4b491872011-02-08 17:39:46 +0000322// both NewReg and AntiDepReg covers it.
Andrew Trick82ae9a92010-11-02 18:16:45 +0000323bool
Andrew Trick4b491872011-02-08 17:39:46 +0000324CriticalAntiDepBreaker::isNewRegClobberedByRefs(RegRefIter RegRefBegin,
325 RegRefIter RegRefEnd,
326 unsigned NewReg)
Andrew Trick82ae9a92010-11-02 18:16:45 +0000327{
328 for (RegRefIter I = RegRefBegin; I != RegRefEnd; ++I ) {
Andrew Trick4b491872011-02-08 17:39:46 +0000329 MachineOperand *RefOper = I->second;
330
331 // Don't allow the instruction defining AntiDepReg to earlyclobber its
332 // operands, in case they may be assigned to NewReg. In this case antidep
333 // breaking must fail, but it's too rare to bother optimizing.
334 if (RefOper->isDef() && RefOper->isEarlyClobber())
Andrew Trick82ae9a92010-11-02 18:16:45 +0000335 return true;
Andrew Trick4b491872011-02-08 17:39:46 +0000336
Sanjay Patel99475192014-06-24 21:11:51 +0000337 // Handle cases in which this instruction defines NewReg.
Andrew Trick4b491872011-02-08 17:39:46 +0000338 MachineInstr *MI = RefOper->getParent();
339 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
340 const MachineOperand &CheckOper = MI->getOperand(i);
341
Jakob Stoklund Olesen38ce8892012-02-23 01:15:26 +0000342 if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
343 return true;
344
Andrew Trick4b491872011-02-08 17:39:46 +0000345 if (!CheckOper.isReg() || !CheckOper.isDef() ||
346 CheckOper.getReg() != NewReg)
347 continue;
348
349 // Don't allow the instruction to define NewReg and AntiDepReg.
350 // When AntiDepReg is renamed it will be an illegal op.
351 if (RefOper->isDef())
352 return true;
353
354 // Don't allow an instruction using AntiDepReg to be earlyclobbered by
Sanjay Patel99475192014-06-24 21:11:51 +0000355 // NewReg.
Andrew Trick4b491872011-02-08 17:39:46 +0000356 if (CheckOper.isEarlyClobber())
357 return true;
358
Sanjay Patel99475192014-06-24 21:11:51 +0000359 // Don't allow inline asm to define NewReg at all. Who knows what it's
Andrew Trick4b491872011-02-08 17:39:46 +0000360 // doing with it.
361 if (MI->isInlineAsm())
362 return true;
363 }
Andrew Trick82ae9a92010-11-02 18:16:45 +0000364 }
365 return false;
366}
367
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000368unsigned CriticalAntiDepBreaker::
369findSuitableFreeRegister(RegRefIter RegRefBegin,
370 RegRefIter RegRefEnd,
371 unsigned AntiDepReg,
372 unsigned LastNewReg,
373 const TargetRegisterClass *RC,
Craig Topper72cde632013-07-03 05:16:59 +0000374 SmallVectorImpl<unsigned> &Forbid)
Jim Grosbacheb431da2010-01-06 16:48:02 +0000375{
Jakob Stoklund Olesenbdb55e02012-11-29 03:34:17 +0000376 ArrayRef<MCPhysReg> Order = RegClassInfo.getOrder(RC);
Jakob Stoklund Olesen4f5f84c2011-06-16 21:56:21 +0000377 for (unsigned i = 0; i != Order.size(); ++i) {
378 unsigned NewReg = Order[i];
David Goodwin83704852009-10-26 16:59:04 +0000379 // Don't replace a register with itself.
380 if (NewReg == AntiDepReg) continue;
381 // Don't replace a register with one that was recently used to repair
382 // an anti-dependence with this AntiDepReg, because that would
383 // re-introduce that anti-dependence.
384 if (NewReg == LastNewReg) continue;
Andrew Trick82ae9a92010-11-02 18:16:45 +0000385 // If any instructions that define AntiDepReg also define the NewReg, it's
386 // not suitable. For example, Instruction with multiple definitions can
387 // result in this condition.
Andrew Trick4b491872011-02-08 17:39:46 +0000388 if (isNewRegClobberedByRefs(RegRefBegin, RegRefEnd, NewReg)) continue;
David Goodwin83704852009-10-26 16:59:04 +0000389 // If NewReg is dead and NewReg's most recent def is not before
390 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Jim Grosbacheb431da2010-01-06 16:48:02 +0000391 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u))
392 && "Kill and Def maps aren't consistent for AntiDepReg!");
393 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u))
394 && "Kill and Def maps aren't consistent for NewReg!");
David Goodwin83704852009-10-26 16:59:04 +0000395 if (KillIndices[NewReg] != ~0u ||
396 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
397 KillIndices[AntiDepReg] > DefIndices[NewReg])
398 continue;
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000399 // If NewReg overlaps any of the forbidden registers, we can't use it.
400 bool Forbidden = false;
Craig Toppere1c1d362013-07-03 05:11:49 +0000401 for (SmallVectorImpl<unsigned>::iterator it = Forbid.begin(),
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000402 ite = Forbid.end(); it != ite; ++it)
403 if (TRI->regsOverlap(NewReg, *it)) {
404 Forbidden = true;
405 break;
406 }
407 if (Forbidden) continue;
David Goodwin83704852009-10-26 16:59:04 +0000408 return NewReg;
409 }
410
411 // No registers are free and available!
412 return 0;
413}
414
415unsigned CriticalAntiDepBreaker::
Dan Gohman35bc4d42010-04-19 23:11:58 +0000416BreakAntiDependencies(const std::vector<SUnit>& SUnits,
417 MachineBasicBlock::iterator Begin,
418 MachineBasicBlock::iterator End,
Devang Patelf02a3762011-06-02 21:26:52 +0000419 unsigned InsertPosIndex,
420 DbgValueVector &DbgValues) {
David Goodwin83704852009-10-26 16:59:04 +0000421 // The code below assumes that there is at least one instruction,
422 // so just duck out immediately if the block is empty.
423 if (SUnits.empty()) return 0;
424
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000425 // Keep a map of the MachineInstr*'s back to the SUnit representing them.
426 // This is used for updating debug information.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000427 //
428 // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000429 DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
430
David Goodwin83704852009-10-26 16:59:04 +0000431 // Find the node at the bottom of the critical path.
Craig Topperc0196b12014-04-14 00:51:57 +0000432 const SUnit *Max = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000433 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000434 const SUnit *SU = &SUnits[i];
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000435 MISUnitMap[SU->getInstr()] = SU;
David Goodwin83704852009-10-26 16:59:04 +0000436 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
437 Max = SU;
438 }
439
440#ifndef NDEBUG
441 {
David Greene96b90532010-01-04 17:47:05 +0000442 DEBUG(dbgs() << "Critical path has total latency "
David Goodwin83704852009-10-26 16:59:04 +0000443 << (Max->getDepth() + Max->Latency) << "\n");
David Greene96b90532010-01-04 17:47:05 +0000444 DEBUG(dbgs() << "Available regs:");
David Goodwin83704852009-10-26 16:59:04 +0000445 for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
446 if (KillIndices[Reg] == ~0u)
David Greene96b90532010-01-04 17:47:05 +0000447 DEBUG(dbgs() << " " << TRI->getName(Reg));
David Goodwin83704852009-10-26 16:59:04 +0000448 }
David Greene96b90532010-01-04 17:47:05 +0000449 DEBUG(dbgs() << '\n');
David Goodwin83704852009-10-26 16:59:04 +0000450 }
451#endif
452
453 // Track progress along the critical path through the SUnit graph as we walk
454 // the instructions.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000455 const SUnit *CriticalPathSU = Max;
David Goodwin83704852009-10-26 16:59:04 +0000456 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
457
458 // Consider this pattern:
459 // A = ...
460 // ... = A
461 // A = ...
462 // ... = A
463 // A = ...
464 // ... = A
465 // A = ...
466 // ... = A
467 // There are three anti-dependencies here, and without special care,
468 // we'd break all of them using the same register:
469 // A = ...
470 // ... = A
471 // B = ...
472 // ... = B
473 // B = ...
474 // ... = B
475 // B = ...
476 // ... = B
477 // because at each anti-dependence, B is the first register that
478 // isn't A which is free. This re-introduces anti-dependencies
479 // at all but one of the original anti-dependencies that we were
480 // trying to break. To avoid this, keep track of the most recent
481 // register that each register was replaced with, avoid
482 // using it to repair an anti-dependence on the same register.
483 // This lets us produce this:
484 // A = ...
485 // ... = A
486 // B = ...
487 // ... = B
488 // C = ...
489 // ... = C
490 // B = ...
491 // ... = B
492 // This still has an anti-dependence on B, but at least it isn't on the
493 // original critical path.
494 //
495 // TODO: If we tracked more than one register here, we could potentially
496 // fix that remaining critical edge too. This is a little more involved,
497 // because unlike the most recent register, less recent registers should
498 // still be considered, though only if no other registers are available.
Bill Wendling51a9c0a2010-07-15 19:58:14 +0000499 std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);
David Goodwin83704852009-10-26 16:59:04 +0000500
501 // Attempt to break anti-dependence edges on the critical path. Walk the
502 // instructions from the bottom up, tracking information about liveness
503 // as we go to help determine which registers are available.
504 unsigned Broken = 0;
505 unsigned Count = InsertPosIndex - 1;
Sanjay Patel99475192014-06-24 21:11:51 +0000506 for (MachineBasicBlock::iterator I = End, E = Begin; I != E; --Count) {
David Goodwin83704852009-10-26 16:59:04 +0000507 MachineInstr *MI = --I;
Dale Johannesen2061c842010-03-05 00:02:59 +0000508 if (MI->isDebugValue())
509 continue;
David Goodwin83704852009-10-26 16:59:04 +0000510
511 // Check if this instruction has a dependence on the critical path that
512 // is an anti-dependence that we may be able to break. If it is, set
513 // AntiDepReg to the non-zero register associated with the anti-dependence.
514 //
515 // We limit our attention to the critical path as a heuristic to avoid
516 // breaking anti-dependence edges that aren't going to significantly
517 // impact the overall schedule. There are a limited number of registers
518 // and we want to save them for the important edges.
Jim Grosbach866b74b2010-05-14 21:20:46 +0000519 //
David Goodwin83704852009-10-26 16:59:04 +0000520 // TODO: Instructions with multiple defs could have multiple
521 // anti-dependencies. The current code here only knows how to break one
522 // edge per instruction. Note that we'd have to be able to break all of
523 // the anti-dependencies in an instruction in order to be effective.
524 unsigned AntiDepReg = 0;
525 if (MI == CriticalPathMI) {
Dan Gohman35bc4d42010-04-19 23:11:58 +0000526 if (const SDep *Edge = CriticalPathStep(CriticalPathSU)) {
527 const SUnit *NextSU = Edge->getSUnit();
David Goodwin83704852009-10-26 16:59:04 +0000528
529 // Only consider anti-dependence edges.
530 if (Edge->getKind() == SDep::Anti) {
531 AntiDepReg = Edge->getReg();
532 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Jakob Stoklund Olesenf67bf3e2012-10-15 22:41:03 +0000533 if (!MRI.isAllocatable(AntiDepReg))
David Goodwin83704852009-10-26 16:59:04 +0000534 // Don't break anti-dependencies on non-allocatable registers.
535 AntiDepReg = 0;
Benjamin Kramer5d1bca82012-03-17 20:22:57 +0000536 else if (KeepRegs.test(AntiDepReg))
Sanjay Patel99475192014-06-24 21:11:51 +0000537 // Don't break anti-dependencies if a use down below requires
David Goodwin83704852009-10-26 16:59:04 +0000538 // this exact register.
539 AntiDepReg = 0;
540 else {
541 // If the SUnit has other dependencies on the SUnit that it
542 // anti-depends on, don't bother breaking the anti-dependency
543 // since those edges would prevent such units from being
544 // scheduled past each other regardless.
545 //
546 // Also, if there are dependencies on other SUnits with the
547 // same register as the anti-dependency, don't attempt to
548 // break it.
Dan Gohman35bc4d42010-04-19 23:11:58 +0000549 for (SUnit::const_pred_iterator P = CriticalPathSU->Preds.begin(),
David Goodwin83704852009-10-26 16:59:04 +0000550 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
551 if (P->getSUnit() == NextSU ?
552 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
553 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
554 AntiDepReg = 0;
555 break;
556 }
557 }
558 }
559 CriticalPathSU = NextSU;
560 CriticalPathMI = CriticalPathSU->getInstr();
561 } else {
562 // We've reached the end of the critical path.
Craig Topperc0196b12014-04-14 00:51:57 +0000563 CriticalPathSU = nullptr;
564 CriticalPathMI = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000565 }
566 }
567
568 PrescanInstruction(MI);
569
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000570 SmallVector<unsigned, 2> ForbidRegs;
571
Evan Chengf128bdc2010-06-16 07:35:02 +0000572 // If MI's defs have a special allocation requirement, don't allow
573 // any def registers to be changed. Also assume all registers
574 // defined in a call must not be changed (ABI).
Sanjay Patel99475192014-06-24 21:11:51 +0000575 if (MI->isCall() || MI->hasExtraDefRegAllocReq() || TII->isPredicated(MI))
David Goodwin83704852009-10-26 16:59:04 +0000576 // If this instruction's defs have special allocation requirement, don't
577 // break this anti-dependency.
578 AntiDepReg = 0;
579 else if (AntiDepReg) {
580 // If this instruction has a use of AntiDepReg, breaking it
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000581 // is invalid. If the instruction defines other registers,
582 // save a list of them so that we don't pick a new register
583 // that overlaps any of them.
David Goodwin83704852009-10-26 16:59:04 +0000584 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
585 MachineOperand &MO = MI->getOperand(i);
586 if (!MO.isReg()) continue;
587 unsigned Reg = MO.getReg();
588 if (Reg == 0) continue;
Evan Chengf128bdc2010-06-16 07:35:02 +0000589 if (MO.isUse() && TRI->regsOverlap(AntiDepReg, Reg)) {
David Goodwin83704852009-10-26 16:59:04 +0000590 AntiDepReg = 0;
591 break;
592 }
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000593 if (MO.isDef() && Reg != AntiDepReg)
594 ForbidRegs.push_back(Reg);
David Goodwin83704852009-10-26 16:59:04 +0000595 }
596 }
597
598 // Determine AntiDepReg's register class, if it is live and is
599 // consistently used within a single class.
Craig Topperc0196b12014-04-14 00:51:57 +0000600 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg]
601 : nullptr;
602 assert((AntiDepReg == 0 || RC != nullptr) &&
David Goodwin83704852009-10-26 16:59:04 +0000603 "Register should be live if it's causing an anti-dependence!");
604 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
605 AntiDepReg = 0;
606
Alp Tokercb402912014-01-24 17:20:08 +0000607 // Look for a suitable register to use to break the anti-dependence.
David Goodwin83704852009-10-26 16:59:04 +0000608 //
609 // TODO: Instead of picking the first free register, consider which might
610 // be the best.
611 if (AntiDepReg != 0) {
Andrew Trick82ae9a92010-11-02 18:16:45 +0000612 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
613 std::multimap<unsigned, MachineOperand *>::iterator>
614 Range = RegRefs.equal_range(AntiDepReg);
615 if (unsigned NewReg = findSuitableFreeRegister(Range.first, Range.second,
616 AntiDepReg,
David Goodwin83704852009-10-26 16:59:04 +0000617 LastNewReg[AntiDepReg],
Bill Schmidt2e4ae4e2013-01-28 18:36:58 +0000618 RC, ForbidRegs)) {
David Greene96b90532010-01-04 17:47:05 +0000619 DEBUG(dbgs() << "Breaking anti-dependence edge on "
David Goodwin83704852009-10-26 16:59:04 +0000620 << TRI->getName(AntiDepReg)
621 << " with " << RegRefs.count(AntiDepReg) << " references"
622 << " using " << TRI->getName(NewReg) << "!\n");
623
624 // Update the references to the old register to refer to the new
625 // register.
David Goodwin83704852009-10-26 16:59:04 +0000626 for (std::multimap<unsigned, MachineOperand *>::iterator
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000627 Q = Range.first, QE = Range.second; Q != QE; ++Q) {
David Goodwin83704852009-10-26 16:59:04 +0000628 Q->second->setReg(NewReg);
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000629 // If the SU for the instruction being updated has debug information
630 // related to the anti-dependency register, make sure to update that
631 // as well.
632 const SUnit *SU = MISUnitMap[Q->second->getParent()];
Jim Grosbach84854832010-06-02 15:29:36 +0000633 if (!SU) continue;
Devang Patelf02a3762011-06-02 21:26:52 +0000634 for (DbgValueVector::iterator DVI = DbgValues.begin(),
635 DVE = DbgValues.end(); DVI != DVE; ++DVI)
636 if (DVI->second == Q->second->getParent())
637 UpdateDbgValue(DVI->first, AntiDepReg, NewReg);
Jim Grosbach12ac8f02010-06-01 23:48:44 +0000638 }
David Goodwin83704852009-10-26 16:59:04 +0000639
640 // We just went back in time and modified history; the
Bob Wilsonc57c2202010-10-02 01:49:29 +0000641 // liveness information for the anti-dependence reg is now
David Goodwin83704852009-10-26 16:59:04 +0000642 // inconsistent. Set the state as if it were dead.
643 Classes[NewReg] = Classes[AntiDepReg];
644 DefIndices[NewReg] = DefIndices[AntiDepReg];
645 KillIndices[NewReg] = KillIndices[AntiDepReg];
646 assert(((KillIndices[NewReg] == ~0u) !=
647 (DefIndices[NewReg] == ~0u)) &&
648 "Kill and Def maps aren't consistent for NewReg!");
649
Craig Topperc0196b12014-04-14 00:51:57 +0000650 Classes[AntiDepReg] = nullptr;
David Goodwin83704852009-10-26 16:59:04 +0000651 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
652 KillIndices[AntiDepReg] = ~0u;
653 assert(((KillIndices[AntiDepReg] == ~0u) !=
654 (DefIndices[AntiDepReg] == ~0u)) &&
655 "Kill and Def maps aren't consistent for AntiDepReg!");
656
657 RegRefs.erase(AntiDepReg);
658 LastNewReg[AntiDepReg] = NewReg;
659 ++Broken;
660 }
661 }
662
663 ScanInstruction(MI, Count);
664 }
665
666 return Broken;
667}