1 //===- AggressiveAntiDepBreaker.cpp - Anti-dep breaker --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the AggressiveAntiDepBreaker class, which
10 // implements register anti-dependence breaking during post-RA
11 // scheduling. It attempts to break all anti-dependencies within a
14 //===----------------------------------------------------------------------===//
16 #include "AggressiveAntiDepBreaker.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDAG.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MachineValueType.h"
35 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "post-RA-sched"
43 // If DebugDiv > 0 then only break antidep with (ID % DebugDiv) == DebugMod
45 DebugDiv("agg-antidep-debugdiv",
46 cl::desc("Debug control for aggressive anti-dep breaker"),
47 cl::init(0), cl::Hidden
);
50 DebugMod("agg-antidep-debugmod",
51 cl::desc("Debug control for aggressive anti-dep breaker"),
52 cl::init(0), cl::Hidden
);
54 AggressiveAntiDepState::AggressiveAntiDepState(const unsigned TargetRegs
,
55 MachineBasicBlock
*BB
)
56 : NumTargetRegs(TargetRegs
), GroupNodes(TargetRegs
, 0),
57 GroupNodeIndices(TargetRegs
, 0), KillIndices(TargetRegs
, 0),
58 DefIndices(TargetRegs
, 0) {
59 const unsigned BBSize
= BB
->size();
60 for (unsigned i
= 0; i
< NumTargetRegs
; ++i
) {
61 // Initialize all registers to be in their own group. Initially we
62 // assign the register to the same-indexed GroupNode.
63 GroupNodeIndices
[i
] = i
;
64 // Initialize the indices to indicate that no registers are live.
66 DefIndices
[i
] = BBSize
;
70 unsigned AggressiveAntiDepState::GetGroup(unsigned Reg
) {
71 unsigned Node
= GroupNodeIndices
[Reg
];
72 while (GroupNodes
[Node
] != Node
)
73 Node
= GroupNodes
[Node
];
78 void AggressiveAntiDepState::GetGroupRegs(
80 std::vector
<unsigned> &Regs
,
81 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
> *RegRefs
)
83 for (unsigned Reg
= 0; Reg
!= NumTargetRegs
; ++Reg
) {
84 if ((GetGroup(Reg
) == Group
) && (RegRefs
->count(Reg
) > 0))
89 unsigned AggressiveAntiDepState::UnionGroups(unsigned Reg1
, unsigned Reg2
) {
90 assert(GroupNodes
[0] == 0 && "GroupNode 0 not parent!");
91 assert(GroupNodeIndices
[0] == 0 && "Reg 0 not in Group 0!");
93 // find group for each register
94 unsigned Group1
= GetGroup(Reg1
);
95 unsigned Group2
= GetGroup(Reg2
);
97 // if either group is 0, then that must become the parent
98 unsigned Parent
= (Group1
== 0) ? Group1
: Group2
;
99 unsigned Other
= (Parent
== Group1
) ? Group2
: Group1
;
100 GroupNodes
.at(Other
) = Parent
;
104 unsigned AggressiveAntiDepState::LeaveGroup(unsigned Reg
) {
105 // Create a new GroupNode for Reg. Reg's existing GroupNode must
106 // stay as is because there could be other GroupNodes referring to
108 unsigned idx
= GroupNodes
.size();
109 GroupNodes
.push_back(idx
);
110 GroupNodeIndices
[Reg
] = idx
;
114 bool AggressiveAntiDepState::IsLive(unsigned Reg
) {
115 // KillIndex must be defined and DefIndex not defined for a register
117 return((KillIndices
[Reg
] != ~0u) && (DefIndices
[Reg
] == ~0u));
120 AggressiveAntiDepBreaker::AggressiveAntiDepBreaker(
121 MachineFunction
&MFi
, const RegisterClassInfo
&RCI
,
122 TargetSubtargetInfo::RegClassVector
&CriticalPathRCs
)
123 : AntiDepBreaker(), MF(MFi
), MRI(MF
.getRegInfo()),
124 TII(MF
.getSubtarget().getInstrInfo()),
125 TRI(MF
.getSubtarget().getRegisterInfo()), RegClassInfo(RCI
) {
126 /* Collect a bitset of all registers that are only broken if they
127 are on the critical path. */
128 for (unsigned i
= 0, e
= CriticalPathRCs
.size(); i
< e
; ++i
) {
129 BitVector CPSet
= TRI
->getAllocatableSet(MF
, CriticalPathRCs
[i
]);
130 if (CriticalPathSet
.none())
131 CriticalPathSet
= CPSet
;
133 CriticalPathSet
|= CPSet
;
136 LLVM_DEBUG(dbgs() << "AntiDep Critical-Path Registers:");
137 LLVM_DEBUG(for (unsigned r
138 : CriticalPathSet
.set_bits()) dbgs()
139 << " " << printReg(r
, TRI
));
140 LLVM_DEBUG(dbgs() << '\n');
143 AggressiveAntiDepBreaker::~AggressiveAntiDepBreaker() {
147 void AggressiveAntiDepBreaker::StartBlock(MachineBasicBlock
*BB
) {
149 State
= new AggressiveAntiDepState(TRI
->getNumRegs(), BB
);
151 bool IsReturnBlock
= BB
->isReturnBlock();
152 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
153 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
155 // Examine the live-in regs of all successors.
156 for (MachineBasicBlock
*Succ
: BB
->successors())
157 for (const auto &LI
: Succ
->liveins()) {
158 for (MCRegAliasIterator
AI(LI
.PhysReg
, TRI
, true); AI
.isValid(); ++AI
) {
160 State
->UnionGroups(Reg
, 0);
161 KillIndices
[Reg
] = BB
->size();
162 DefIndices
[Reg
] = ~0u;
166 // Mark live-out callee-saved registers. In a return block this is
167 // all callee-saved registers. In non-return this is any
168 // callee-saved register that is not saved in the prolog.
169 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
170 BitVector Pristine
= MFI
.getPristineRegs(MF
);
171 for (const MCPhysReg
*I
= MF
.getRegInfo().getCalleeSavedRegs(); *I
;
174 if (!IsReturnBlock
&& !Pristine
.test(Reg
))
176 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
177 unsigned AliasReg
= *AI
;
178 State
->UnionGroups(AliasReg
, 0);
179 KillIndices
[AliasReg
] = BB
->size();
180 DefIndices
[AliasReg
] = ~0u;
185 void AggressiveAntiDepBreaker::FinishBlock() {
190 void AggressiveAntiDepBreaker::Observe(MachineInstr
&MI
, unsigned Count
,
191 unsigned InsertPosIndex
) {
192 assert(Count
< InsertPosIndex
&& "Instruction index out of expected range!");
194 std::set
<unsigned> PassthruRegs
;
195 GetPassthruRegs(MI
, PassthruRegs
);
196 PrescanInstruction(MI
, Count
, PassthruRegs
);
197 ScanInstruction(MI
, Count
);
199 LLVM_DEBUG(dbgs() << "Observe: ");
200 LLVM_DEBUG(MI
.dump());
201 LLVM_DEBUG(dbgs() << "\tRegs:");
203 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
204 for (unsigned Reg
= 0; Reg
!= TRI
->getNumRegs(); ++Reg
) {
205 // If Reg is current live, then mark that it can't be renamed as
206 // we don't know the extent of its live-range anymore (now that it
207 // has been scheduled). If it is not live but was defined in the
208 // previous schedule region, then set its def index to the most
209 // conservative location (i.e. the beginning of the previous
211 if (State
->IsLive(Reg
)) {
212 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs()
213 << " " << printReg(Reg
, TRI
) << "=g" << State
->GetGroup(Reg
)
214 << "->g0(region live-out)");
215 State
->UnionGroups(Reg
, 0);
216 } else if ((DefIndices
[Reg
] < InsertPosIndex
)
217 && (DefIndices
[Reg
] >= Count
)) {
218 DefIndices
[Reg
] = Count
;
221 LLVM_DEBUG(dbgs() << '\n');
224 bool AggressiveAntiDepBreaker::IsImplicitDefUse(MachineInstr
&MI
,
225 MachineOperand
&MO
) {
226 if (!MO
.isReg() || !MO
.isImplicit())
229 Register Reg
= MO
.getReg();
233 MachineOperand
*Op
= nullptr;
235 Op
= MI
.findRegisterUseOperand(Reg
, true);
237 Op
= MI
.findRegisterDefOperand(Reg
);
239 return(Op
&& Op
->isImplicit());
242 void AggressiveAntiDepBreaker::GetPassthruRegs(
243 MachineInstr
&MI
, std::set
<unsigned> &PassthruRegs
) {
244 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
245 MachineOperand
&MO
= MI
.getOperand(i
);
246 if (!MO
.isReg()) continue;
247 if ((MO
.isDef() && MI
.isRegTiedToUseOperand(i
)) ||
248 IsImplicitDefUse(MI
, MO
)) {
249 const Register Reg
= MO
.getReg();
250 for (MCSubRegIterator
SubRegs(Reg
, TRI
, /*IncludeSelf=*/true);
251 SubRegs
.isValid(); ++SubRegs
)
252 PassthruRegs
.insert(*SubRegs
);
257 /// AntiDepEdges - Return in Edges the anti- and output- dependencies
258 /// in SU that we want to consider for breaking.
259 static void AntiDepEdges(const SUnit
*SU
, std::vector
<const SDep
*> &Edges
) {
260 SmallSet
<unsigned, 4> RegSet
;
261 for (const SDep
&Pred
: SU
->Preds
) {
262 if ((Pred
.getKind() == SDep::Anti
) || (Pred
.getKind() == SDep::Output
)) {
263 if (RegSet
.insert(Pred
.getReg()).second
)
264 Edges
.push_back(&Pred
);
269 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
271 static const SUnit
*CriticalPathStep(const SUnit
*SU
) {
272 const SDep
*Next
= nullptr;
273 unsigned NextDepth
= 0;
274 // Find the predecessor edge with the greatest depth.
276 for (const SDep
&Pred
: SU
->Preds
) {
277 const SUnit
*PredSU
= Pred
.getSUnit();
278 unsigned PredLatency
= Pred
.getLatency();
279 unsigned PredTotalLatency
= PredSU
->getDepth() + PredLatency
;
280 // In the case of a latency tie, prefer an anti-dependency edge over
281 // other types of edges.
282 if (NextDepth
< PredTotalLatency
||
283 (NextDepth
== PredTotalLatency
&& Pred
.getKind() == SDep::Anti
)) {
284 NextDepth
= PredTotalLatency
;
290 return (Next
) ? Next
->getSUnit() : nullptr;
293 void AggressiveAntiDepBreaker::HandleLastUse(unsigned Reg
, unsigned KillIdx
,
296 const char *footer
) {
297 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
298 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
299 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
300 RegRefs
= State
->GetRegRefs();
302 // FIXME: We must leave subregisters of live super registers as live, so that
303 // we don't clear out the register tracking information for subregisters of
304 // super registers we're still tracking (and with which we're unioning
305 // subregister definitions).
306 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
)
307 if (TRI
->isSuperRegister(Reg
, *AI
) && State
->IsLive(*AI
)) {
308 LLVM_DEBUG(if (!header
&& footer
) dbgs() << footer
);
312 if (!State
->IsLive(Reg
)) {
313 KillIndices
[Reg
] = KillIdx
;
314 DefIndices
[Reg
] = ~0u;
316 State
->LeaveGroup(Reg
);
317 LLVM_DEBUG(if (header
) {
318 dbgs() << header
<< printReg(Reg
, TRI
);
321 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(Reg
) << tag
);
322 // Repeat for subregisters. Note that we only do this if the superregister
323 // was not live because otherwise, regardless whether we have an explicit
324 // use of the subregister, the subregister's contents are needed for the
325 // uses of the superregister.
326 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
) {
327 unsigned SubregReg
= *SubRegs
;
328 if (!State
->IsLive(SubregReg
)) {
329 KillIndices
[SubregReg
] = KillIdx
;
330 DefIndices
[SubregReg
] = ~0u;
331 RegRefs
.erase(SubregReg
);
332 State
->LeaveGroup(SubregReg
);
333 LLVM_DEBUG(if (header
) {
334 dbgs() << header
<< printReg(Reg
, TRI
);
337 LLVM_DEBUG(dbgs() << " " << printReg(SubregReg
, TRI
) << "->g"
338 << State
->GetGroup(SubregReg
) << tag
);
343 LLVM_DEBUG(if (!header
&& footer
) dbgs() << footer
);
346 void AggressiveAntiDepBreaker::PrescanInstruction(
347 MachineInstr
&MI
, unsigned Count
, std::set
<unsigned> &PassthruRegs
) {
348 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
349 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
350 RegRefs
= State
->GetRegRefs();
352 // Handle dead defs by simulating a last-use of the register just
353 // after the def. A dead def can occur because the def is truly
354 // dead, or because only a subregister is live at the def. If we
355 // don't do this the dead def will be incorrectly merged into the
357 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
358 MachineOperand
&MO
= MI
.getOperand(i
);
359 if (!MO
.isReg() || !MO
.isDef()) continue;
360 Register Reg
= MO
.getReg();
361 if (Reg
== 0) continue;
363 HandleLastUse(Reg
, Count
+ 1, "", "\tDead Def: ", "\n");
366 LLVM_DEBUG(dbgs() << "\tDef Groups:");
367 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
368 MachineOperand
&MO
= MI
.getOperand(i
);
369 if (!MO
.isReg() || !MO
.isDef()) continue;
370 Register Reg
= MO
.getReg();
371 if (Reg
== 0) continue;
373 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
) << "=g"
374 << State
->GetGroup(Reg
));
376 // If MI's defs have a special allocation requirement, don't allow
377 // any def registers to be changed. Also assume all registers
378 // defined in a call must not be changed (ABI). Inline assembly may
379 // reference either system calls or the register directly. Skip it until we
380 // can tell user specified registers from compiler-specified.
381 if (MI
.isCall() || MI
.hasExtraDefRegAllocReq() || TII
->isPredicated(MI
) ||
383 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs() << "->g0(alloc-req)");
384 State
->UnionGroups(Reg
, 0);
387 // Any aliased that are live at this point are completely or
388 // partially defined here, so group those aliases with Reg.
389 for (MCRegAliasIterator
AI(Reg
, TRI
, false); AI
.isValid(); ++AI
) {
390 unsigned AliasReg
= *AI
;
391 if (State
->IsLive(AliasReg
)) {
392 State
->UnionGroups(Reg
, AliasReg
);
393 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(Reg
) << "(via "
394 << printReg(AliasReg
, TRI
) << ")");
398 // Note register reference...
399 const TargetRegisterClass
*RC
= nullptr;
400 if (i
< MI
.getDesc().getNumOperands())
401 RC
= TII
->getRegClass(MI
.getDesc(), i
, TRI
, MF
);
402 AggressiveAntiDepState::RegisterReference RR
= { &MO
, RC
};
403 RegRefs
.insert(std::make_pair(Reg
, RR
));
406 LLVM_DEBUG(dbgs() << '\n');
408 // Scan the register defs for this instruction and update
410 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
411 MachineOperand
&MO
= MI
.getOperand(i
);
412 if (!MO
.isReg() || !MO
.isDef()) continue;
413 Register Reg
= MO
.getReg();
414 if (Reg
== 0) continue;
415 // Ignore KILLs and passthru registers for liveness...
416 if (MI
.isKill() || (PassthruRegs
.count(Reg
) != 0))
419 // Update def for Reg and aliases.
420 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
421 // We need to be careful here not to define already-live super registers.
422 // If the super register is already live, then this definition is not
423 // a definition of the whole super register (just a partial insertion
424 // into it). Earlier subregister definitions (which we've not yet visited
425 // because we're iterating bottom-up) need to be linked to the same group
426 // as this definition.
427 if (TRI
->isSuperRegister(Reg
, *AI
) && State
->IsLive(*AI
))
430 DefIndices
[*AI
] = Count
;
435 void AggressiveAntiDepBreaker::ScanInstruction(MachineInstr
&MI
,
437 LLVM_DEBUG(dbgs() << "\tUse Groups:");
438 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
439 RegRefs
= State
->GetRegRefs();
441 // If MI's uses have special allocation requirement, don't allow
442 // any use registers to be changed. Also assume all registers
443 // used in a call must not be changed (ABI).
444 // Inline Assembly register uses also cannot be safely changed.
445 // FIXME: The issue with predicated instruction is more complex. We are being
446 // conservatively here because the kill markers cannot be trusted after
448 // %r6 = LDR %sp, %reg0, 92, 14, %reg0; mem:LD4[FixedStack14]
450 // STR %r0, killed %r6, %reg0, 0, 0, %cpsr; mem:ST4[%395]
451 // %r6 = LDR %sp, %reg0, 100, 0, %cpsr; mem:LD4[FixedStack12]
452 // STR %r0, killed %r6, %reg0, 0, 14, %reg0; mem:ST4[%396](align=8)
454 // The first R6 kill is not really a kill since it's killed by a predicated
455 // instruction which may not be executed. The second R6 def may or may not
456 // re-define R6 so it's not safe to change it since the last R6 use cannot be
458 bool Special
= MI
.isCall() || MI
.hasExtraSrcRegAllocReq() ||
459 TII
->isPredicated(MI
) || MI
.isInlineAsm();
461 // Scan the register uses for this instruction and update
462 // live-ranges, groups and RegRefs.
463 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
464 MachineOperand
&MO
= MI
.getOperand(i
);
465 if (!MO
.isReg() || !MO
.isUse()) continue;
466 Register Reg
= MO
.getReg();
467 if (Reg
== 0) continue;
469 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
) << "=g"
470 << State
->GetGroup(Reg
));
472 // It wasn't previously live but now it is, this is a kill. Forget
473 // the previous live-range information and start a new live-range
475 HandleLastUse(Reg
, Count
, "(last-use)");
478 LLVM_DEBUG(if (State
->GetGroup(Reg
) != 0) dbgs() << "->g0(alloc-req)");
479 State
->UnionGroups(Reg
, 0);
482 // Note register reference...
483 const TargetRegisterClass
*RC
= nullptr;
484 if (i
< MI
.getDesc().getNumOperands())
485 RC
= TII
->getRegClass(MI
.getDesc(), i
, TRI
, MF
);
486 AggressiveAntiDepState::RegisterReference RR
= { &MO
, RC
};
487 RegRefs
.insert(std::make_pair(Reg
, RR
));
490 LLVM_DEBUG(dbgs() << '\n');
492 // Form a group of all defs and uses of a KILL instruction to ensure
493 // that all registers are renamed as a group.
495 LLVM_DEBUG(dbgs() << "\tKill Group:");
497 unsigned FirstReg
= 0;
498 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
499 MachineOperand
&MO
= MI
.getOperand(i
);
500 if (!MO
.isReg()) continue;
501 Register Reg
= MO
.getReg();
502 if (Reg
== 0) continue;
505 LLVM_DEBUG(dbgs() << "=" << printReg(Reg
, TRI
));
506 State
->UnionGroups(FirstReg
, Reg
);
508 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
));
513 LLVM_DEBUG(dbgs() << "->g" << State
->GetGroup(FirstReg
) << '\n');
517 BitVector
AggressiveAntiDepBreaker::GetRenameRegisters(unsigned Reg
) {
518 BitVector
BV(TRI
->getNumRegs(), false);
521 // Check all references that need rewriting for Reg. For each, use
522 // the corresponding register class to narrow the set of registers
523 // that are appropriate for renaming.
524 for (const auto &Q
: make_range(State
->GetRegRefs().equal_range(Reg
))) {
525 const TargetRegisterClass
*RC
= Q
.second
.RC
;
528 BitVector RCBV
= TRI
->getAllocatableSet(MF
, RC
);
536 LLVM_DEBUG(dbgs() << " " << TRI
->getRegClassName(RC
));
542 bool AggressiveAntiDepBreaker::FindSuitableFreeRegisters(
543 unsigned AntiDepGroupIndex
,
544 RenameOrderType
& RenameOrder
,
545 std::map
<unsigned, unsigned> &RenameMap
) {
546 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
547 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
548 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
549 RegRefs
= State
->GetRegRefs();
551 // Collect all referenced registers in the same group as
552 // AntiDepReg. These all need to be renamed together if we are to
553 // break the anti-dependence.
554 std::vector
<unsigned> Regs
;
555 State
->GetGroupRegs(AntiDepGroupIndex
, Regs
, &RegRefs
);
556 assert(!Regs
.empty() && "Empty register group!");
560 // Find the "superest" register in the group. At the same time,
561 // collect the BitVector of registers that can be used to rename
563 LLVM_DEBUG(dbgs() << "\tRename Candidates for Group g" << AntiDepGroupIndex
565 std::map
<unsigned, BitVector
> RenameRegisterMap
;
566 unsigned SuperReg
= 0;
567 for (unsigned i
= 0, e
= Regs
.size(); i
!= e
; ++i
) {
568 unsigned Reg
= Regs
[i
];
569 if ((SuperReg
== 0) || TRI
->isSuperRegister(SuperReg
, Reg
))
572 // If Reg has any references, then collect possible rename regs
573 if (RegRefs
.count(Reg
) > 0) {
574 LLVM_DEBUG(dbgs() << "\t\t" << printReg(Reg
, TRI
) << ":");
576 BitVector
&BV
= RenameRegisterMap
[Reg
];
578 BV
= GetRenameRegisters(Reg
);
582 for (unsigned r
: BV
.set_bits())
583 dbgs() << " " << printReg(r
, TRI
);
589 // All group registers should be a subreg of SuperReg.
590 for (unsigned i
= 0, e
= Regs
.size(); i
!= e
; ++i
) {
591 unsigned Reg
= Regs
[i
];
592 if (Reg
== SuperReg
) continue;
593 bool IsSub
= TRI
->isSubRegister(SuperReg
, Reg
);
594 // FIXME: remove this once PR18663 has been properly fixed. For now,
595 // return a conservative answer:
596 // assert(IsSub && "Expecting group subregister");
602 // If DebugDiv > 0 then only rename (renamecnt % DebugDiv) == DebugMod
604 static int renamecnt
= 0;
605 if (renamecnt
++ % DebugDiv
!= DebugMod
)
608 dbgs() << "*** Performing rename " << printReg(SuperReg
, TRI
)
609 << " for debug ***\n";
613 // Check each possible rename register for SuperReg in round-robin
614 // order. If that register is available, and the corresponding
615 // registers are available for the other group subregisters, then we
616 // can use those registers to rename.
618 // FIXME: Using getMinimalPhysRegClass is very conservative. We should
619 // check every use of the register and find the largest register class
620 // that can be used in all of them.
621 const TargetRegisterClass
*SuperRC
=
622 TRI
->getMinimalPhysRegClass(SuperReg
, MVT::Other
);
624 ArrayRef
<MCPhysReg
> Order
= RegClassInfo
.getOrder(SuperRC
);
626 LLVM_DEBUG(dbgs() << "\tEmpty Super Regclass!!\n");
630 LLVM_DEBUG(dbgs() << "\tFind Registers:");
632 RenameOrder
.insert(RenameOrderType::value_type(SuperRC
, Order
.size()));
634 unsigned OrigR
= RenameOrder
[SuperRC
];
635 unsigned EndR
= ((OrigR
== Order
.size()) ? 0 : OrigR
);
638 if (R
== 0) R
= Order
.size();
640 const unsigned NewSuperReg
= Order
[R
];
641 // Don't consider non-allocatable registers
642 if (!MRI
.isAllocatable(NewSuperReg
)) continue;
643 // Don't replace a register with itself.
644 if (NewSuperReg
== SuperReg
) continue;
646 LLVM_DEBUG(dbgs() << " [" << printReg(NewSuperReg
, TRI
) << ':');
649 // For each referenced group register (which must be a SuperReg or
650 // a subregister of SuperReg), find the corresponding subregister
651 // of NewSuperReg and make sure it is free to be renamed.
652 for (unsigned i
= 0, e
= Regs
.size(); i
!= e
; ++i
) {
653 unsigned Reg
= Regs
[i
];
655 if (Reg
== SuperReg
) {
656 NewReg
= NewSuperReg
;
658 unsigned NewSubRegIdx
= TRI
->getSubRegIndex(SuperReg
, Reg
);
659 if (NewSubRegIdx
!= 0)
660 NewReg
= TRI
->getSubReg(NewSuperReg
, NewSubRegIdx
);
663 LLVM_DEBUG(dbgs() << " " << printReg(NewReg
, TRI
));
665 // Check if Reg can be renamed to NewReg.
666 if (!RenameRegisterMap
[Reg
].test(NewReg
)) {
667 LLVM_DEBUG(dbgs() << "(no rename)");
671 // If NewReg is dead and NewReg's most recent def is not before
672 // Regs's kill, it's safe to replace Reg with NewReg. We
673 // must also check all aliases of NewReg, because we can't define a
674 // register when any sub or super is already live.
675 if (State
->IsLive(NewReg
) || (KillIndices
[Reg
] > DefIndices
[NewReg
])) {
676 LLVM_DEBUG(dbgs() << "(live)");
680 for (MCRegAliasIterator
AI(NewReg
, TRI
, false); AI
.isValid(); ++AI
) {
681 unsigned AliasReg
= *AI
;
682 if (State
->IsLive(AliasReg
) ||
683 (KillIndices
[Reg
] > DefIndices
[AliasReg
])) {
685 << "(alias " << printReg(AliasReg
, TRI
) << " live)");
694 // We cannot rename 'Reg' to 'NewReg' if one of the uses of 'Reg' also
695 // defines 'NewReg' via an early-clobber operand.
696 for (const auto &Q
: make_range(RegRefs
.equal_range(Reg
))) {
697 MachineInstr
*UseMI
= Q
.second
.Operand
->getParent();
698 int Idx
= UseMI
->findRegisterDefOperandIdx(NewReg
, false, true, TRI
);
702 if (UseMI
->getOperand(Idx
).isEarlyClobber()) {
703 LLVM_DEBUG(dbgs() << "(ec)");
708 // Also, we cannot rename 'Reg' to 'NewReg' if the instruction defining
709 // 'Reg' is an early-clobber define and that instruction also uses
711 for (const auto &Q
: make_range(RegRefs
.equal_range(Reg
))) {
712 if (!Q
.second
.Operand
->isDef() || !Q
.second
.Operand
->isEarlyClobber())
715 MachineInstr
*DefMI
= Q
.second
.Operand
->getParent();
716 if (DefMI
->readsRegister(NewReg
, TRI
)) {
717 LLVM_DEBUG(dbgs() << "(ec)");
722 // Record that 'Reg' can be renamed to 'NewReg'.
723 RenameMap
.insert(std::pair
<unsigned, unsigned>(Reg
, NewReg
));
726 // If we fall-out here, then every register in the group can be
727 // renamed, as recorded in RenameMap.
728 RenameOrder
.erase(SuperRC
);
729 RenameOrder
.insert(RenameOrderType::value_type(SuperRC
, R
));
730 LLVM_DEBUG(dbgs() << "]\n");
734 LLVM_DEBUG(dbgs() << ']');
737 LLVM_DEBUG(dbgs() << '\n');
739 // No registers are free and available!
743 /// BreakAntiDependencies - Identifiy anti-dependencies within the
744 /// ScheduleDAG and break them by renaming registers.
745 unsigned AggressiveAntiDepBreaker::BreakAntiDependencies(
746 const std::vector
<SUnit
> &SUnits
,
747 MachineBasicBlock::iterator Begin
,
748 MachineBasicBlock::iterator End
,
749 unsigned InsertPosIndex
,
750 DbgValueVector
&DbgValues
) {
751 std::vector
<unsigned> &KillIndices
= State
->GetKillIndices();
752 std::vector
<unsigned> &DefIndices
= State
->GetDefIndices();
753 std::multimap
<unsigned, AggressiveAntiDepState::RegisterReference
>&
754 RegRefs
= State
->GetRegRefs();
756 // The code below assumes that there is at least one instruction,
757 // so just duck out immediately if the block is empty.
758 if (SUnits
.empty()) return 0;
760 // For each regclass the next register to use for renaming.
761 RenameOrderType RenameOrder
;
763 // ...need a map from MI to SUnit.
764 std::map
<MachineInstr
*, const SUnit
*> MISUnitMap
;
765 for (unsigned i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
766 const SUnit
*SU
= &SUnits
[i
];
767 MISUnitMap
.insert(std::pair
<MachineInstr
*, const SUnit
*>(SU
->getInstr(),
771 // Track progress along the critical path through the SUnit graph as
772 // we walk the instructions. This is needed for regclasses that only
773 // break critical-path anti-dependencies.
774 const SUnit
*CriticalPathSU
= nullptr;
775 MachineInstr
*CriticalPathMI
= nullptr;
776 if (CriticalPathSet
.any()) {
777 for (unsigned i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
778 const SUnit
*SU
= &SUnits
[i
];
779 if (!CriticalPathSU
||
780 ((SU
->getDepth() + SU
->Latency
) >
781 (CriticalPathSU
->getDepth() + CriticalPathSU
->Latency
))) {
785 assert(CriticalPathSU
&& "Failed to find SUnit critical path");
786 CriticalPathMI
= CriticalPathSU
->getInstr();
790 LLVM_DEBUG(dbgs() << "\n===== Aggressive anti-dependency breaking\n");
791 LLVM_DEBUG(dbgs() << "Available regs:");
792 for (unsigned Reg
= 0; Reg
< TRI
->getNumRegs(); ++Reg
) {
793 if (!State
->IsLive(Reg
))
794 LLVM_DEBUG(dbgs() << " " << printReg(Reg
, TRI
));
796 LLVM_DEBUG(dbgs() << '\n');
799 BitVector
RegAliases(TRI
->getNumRegs());
801 // Attempt to break anti-dependence edges. Walk the instructions
802 // from the bottom up, tracking information about liveness as we go
803 // to help determine which registers are available.
805 unsigned Count
= InsertPosIndex
- 1;
806 for (MachineBasicBlock::iterator I
= End
, E
= Begin
;
808 MachineInstr
&MI
= *--I
;
810 if (MI
.isDebugInstr())
813 LLVM_DEBUG(dbgs() << "Anti: ");
814 LLVM_DEBUG(MI
.dump());
816 std::set
<unsigned> PassthruRegs
;
817 GetPassthruRegs(MI
, PassthruRegs
);
819 // Process the defs in MI...
820 PrescanInstruction(MI
, Count
, PassthruRegs
);
822 // The dependence edges that represent anti- and output-
823 // dependencies that are candidates for breaking.
824 std::vector
<const SDep
*> Edges
;
825 const SUnit
*PathSU
= MISUnitMap
[&MI
];
826 AntiDepEdges(PathSU
, Edges
);
828 // If MI is not on the critical path, then we don't rename
829 // registers in the CriticalPathSet.
830 BitVector
*ExcludeRegs
= nullptr;
831 if (&MI
== CriticalPathMI
) {
832 CriticalPathSU
= CriticalPathStep(CriticalPathSU
);
833 CriticalPathMI
= (CriticalPathSU
) ? CriticalPathSU
->getInstr() : nullptr;
834 } else if (CriticalPathSet
.any()) {
835 ExcludeRegs
= &CriticalPathSet
;
838 // Ignore KILL instructions (they form a group in ScanInstruction
839 // but don't cause any anti-dependence breaking themselves)
841 // Attempt to break each anti-dependency...
842 for (unsigned i
= 0, e
= Edges
.size(); i
!= e
; ++i
) {
843 const SDep
*Edge
= Edges
[i
];
844 SUnit
*NextSU
= Edge
->getSUnit();
846 if ((Edge
->getKind() != SDep::Anti
) &&
847 (Edge
->getKind() != SDep::Output
)) continue;
849 unsigned AntiDepReg
= Edge
->getReg();
850 LLVM_DEBUG(dbgs() << "\tAntidep reg: " << printReg(AntiDepReg
, TRI
));
851 assert(AntiDepReg
!= 0 && "Anti-dependence on reg0?");
853 if (!MRI
.isAllocatable(AntiDepReg
)) {
854 // Don't break anti-dependencies on non-allocatable registers.
855 LLVM_DEBUG(dbgs() << " (non-allocatable)\n");
857 } else if (ExcludeRegs
&& ExcludeRegs
->test(AntiDepReg
)) {
858 // Don't break anti-dependencies for critical path registers
859 // if not on the critical path
860 LLVM_DEBUG(dbgs() << " (not critical-path)\n");
862 } else if (PassthruRegs
.count(AntiDepReg
) != 0) {
863 // If the anti-dep register liveness "passes-thru", then
864 // don't try to change it. It will be changed along with
865 // the use if required to break an earlier antidep.
866 LLVM_DEBUG(dbgs() << " (passthru)\n");
869 // No anti-dep breaking for implicit deps
870 MachineOperand
*AntiDepOp
= MI
.findRegisterDefOperand(AntiDepReg
);
871 assert(AntiDepOp
&& "Can't find index for defined register operand");
872 if (!AntiDepOp
|| AntiDepOp
->isImplicit()) {
873 LLVM_DEBUG(dbgs() << " (implicit)\n");
877 // If the SUnit has other dependencies on the SUnit that
878 // it anti-depends on, don't bother breaking the
879 // anti-dependency since those edges would prevent such
880 // units from being scheduled past each other
883 // Also, if there are dependencies on other SUnits with the
884 // same register as the anti-dependency, don't attempt to
886 for (const SDep
&Pred
: PathSU
->Preds
) {
887 if (Pred
.getSUnit() == NextSU
? (Pred
.getKind() != SDep::Anti
||
888 Pred
.getReg() != AntiDepReg
)
889 : (Pred
.getKind() == SDep::Data
&&
890 Pred
.getReg() == AntiDepReg
)) {
895 for (const SDep
&Pred
: PathSU
->Preds
) {
896 if ((Pred
.getSUnit() == NextSU
) && (Pred
.getKind() != SDep::Anti
) &&
897 (Pred
.getKind() != SDep::Output
)) {
898 LLVM_DEBUG(dbgs() << " (real dependency)\n");
901 } else if ((Pred
.getSUnit() != NextSU
) &&
902 (Pred
.getKind() == SDep::Data
) &&
903 (Pred
.getReg() == AntiDepReg
)) {
904 LLVM_DEBUG(dbgs() << " (other dependency)\n");
910 if (AntiDepReg
== 0) continue;
912 // If the definition of the anti-dependency register does not start
913 // a new live range, bail out. This can happen if the anti-dep
914 // register is a sub-register of another register whose live range
915 // spans over PathSU. In such case, PathSU defines only a part of
916 // the larger register.
918 for (MCRegAliasIterator
AI(AntiDepReg
, TRI
, true); AI
.isValid(); ++AI
)
920 for (SDep S
: PathSU
->Succs
) {
921 SDep::Kind K
= S
.getKind();
922 if (K
!= SDep::Data
&& K
!= SDep::Output
&& K
!= SDep::Anti
)
924 unsigned R
= S
.getReg();
927 if (R
== AntiDepReg
|| TRI
->isSubRegister(AntiDepReg
, R
))
933 if (AntiDepReg
== 0) continue;
936 assert(AntiDepReg
!= 0);
937 if (AntiDepReg
== 0) continue;
939 // Determine AntiDepReg's register group.
940 const unsigned GroupIndex
= State
->GetGroup(AntiDepReg
);
941 if (GroupIndex
== 0) {
942 LLVM_DEBUG(dbgs() << " (zero group)\n");
946 LLVM_DEBUG(dbgs() << '\n');
948 // Look for a suitable register to use to break the anti-dependence.
949 std::map
<unsigned, unsigned> RenameMap
;
950 if (FindSuitableFreeRegisters(GroupIndex
, RenameOrder
, RenameMap
)) {
951 LLVM_DEBUG(dbgs() << "\tBreaking anti-dependence edge on "
952 << printReg(AntiDepReg
, TRI
) << ":");
954 // Handle each group register...
955 for (const auto &P
: RenameMap
) {
956 unsigned CurrReg
= P
.first
;
957 unsigned NewReg
= P
.second
;
959 LLVM_DEBUG(dbgs() << " " << printReg(CurrReg
, TRI
) << "->"
960 << printReg(NewReg
, TRI
) << "("
961 << RegRefs
.count(CurrReg
) << " refs)");
963 // Update the references to the old register CurrReg to
964 // refer to the new register NewReg.
965 for (const auto &Q
: make_range(RegRefs
.equal_range(CurrReg
))) {
966 Q
.second
.Operand
->setReg(NewReg
);
967 // If the SU for the instruction being updated has debug
968 // information related to the anti-dependency register, make
969 // sure to update that as well.
970 const SUnit
*SU
= MISUnitMap
[Q
.second
.Operand
->getParent()];
972 UpdateDbgValues(DbgValues
, Q
.second
.Operand
->getParent(),
976 // We just went back in time and modified history; the
977 // liveness information for CurrReg is now inconsistent. Set
978 // the state as if it were dead.
979 State
->UnionGroups(NewReg
, 0);
980 RegRefs
.erase(NewReg
);
981 DefIndices
[NewReg
] = DefIndices
[CurrReg
];
982 KillIndices
[NewReg
] = KillIndices
[CurrReg
];
984 State
->UnionGroups(CurrReg
, 0);
985 RegRefs
.erase(CurrReg
);
986 DefIndices
[CurrReg
] = KillIndices
[CurrReg
];
987 KillIndices
[CurrReg
] = ~0u;
988 assert(((KillIndices
[CurrReg
] == ~0u) !=
989 (DefIndices
[CurrReg
] == ~0u)) &&
990 "Kill and Def maps aren't consistent for AntiDepReg!");
994 LLVM_DEBUG(dbgs() << '\n');
999 ScanInstruction(MI
, Count
);
1005 AntiDepBreaker
*llvm::createAggressiveAntiDepBreaker(
1006 MachineFunction
&MFi
, const RegisterClassInfo
&RCI
,
1007 TargetSubtargetInfo::RegClassVector
&CriticalPathRCs
) {
1008 return new AggressiveAntiDepBreaker(MFi
, RCI
, CriticalPathRCs
);