1 //===- HexagonPacketizer.cpp - VLIW packetizer ----------------------------===//
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 implements a simple VLIW packetizer using DFA. The packetizer works on
10 // machine basic blocks. For each instruction I in BB, the packetizer consults
11 // the DFA to see if machine resources are available to execute I. If so, the
12 // packetizer checks if I depends on any instruction J in the current packet.
13 // If no dependency is found, I is added to current packet and machine resource
14 // is marked as taken. If any dependency is found, a target API call is made to
15 // prune the dependence.
17 //===----------------------------------------------------------------------===//
19 #include "HexagonVLIWPacketizer.h"
21 #include "HexagonInstrInfo.h"
22 #include "HexagonRegisterInfo.h"
23 #include "HexagonSubtarget.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
31 #include "llvm/CodeGen/MachineDominators.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBundle.h"
37 #include "llvm/CodeGen/MachineLoopInfo.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/ScheduleDAG.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/MC/MCInstrDesc.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
55 #define DEBUG_TYPE "packets"
57 static cl::opt
<bool> DisablePacketizer("disable-packetizer", cl::Hidden
,
58 cl::ZeroOrMore
, cl::init(false),
59 cl::desc("Disable Hexagon packetizer pass"));
61 static cl::opt
<bool> Slot1Store("slot1-store-slot0-load", cl::Hidden
,
62 cl::ZeroOrMore
, cl::init(true),
63 cl::desc("Allow slot1 store and slot0 load"));
65 static cl::opt
<bool> PacketizeVolatiles("hexagon-packetize-volatiles",
66 cl::ZeroOrMore
, cl::Hidden
, cl::init(true),
67 cl::desc("Allow non-solo packetization of volatile memory references"));
69 static cl::opt
<bool> EnableGenAllInsnClass("enable-gen-insn", cl::init(false),
70 cl::Hidden
, cl::ZeroOrMore
, cl::desc("Generate all instruction with TC"));
72 static cl::opt
<bool> DisableVecDblNVStores("disable-vecdbl-nv-stores",
73 cl::init(false), cl::Hidden
, cl::ZeroOrMore
,
74 cl::desc("Disable vector double new-value-stores"));
76 extern cl::opt
<bool> ScheduleInlineAsm
;
80 FunctionPass
*createHexagonPacketizer(bool Minimal
);
81 void initializeHexagonPacketizerPass(PassRegistry
&);
83 } // end namespace llvm
87 class HexagonPacketizer
: public MachineFunctionPass
{
91 HexagonPacketizer(bool Min
= false)
92 : MachineFunctionPass(ID
), Minimal(Min
) {}
94 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
96 AU
.addRequired
<AAResultsWrapperPass
>();
97 AU
.addRequired
<MachineBranchProbabilityInfo
>();
98 AU
.addRequired
<MachineDominatorTree
>();
99 AU
.addRequired
<MachineLoopInfo
>();
100 AU
.addPreserved
<MachineDominatorTree
>();
101 AU
.addPreserved
<MachineLoopInfo
>();
102 MachineFunctionPass::getAnalysisUsage(AU
);
105 StringRef
getPassName() const override
{ return "Hexagon Packetizer"; }
106 bool runOnMachineFunction(MachineFunction
&Fn
) override
;
108 MachineFunctionProperties
getRequiredProperties() const override
{
109 return MachineFunctionProperties().set(
110 MachineFunctionProperties::Property::NoVRegs
);
114 const HexagonInstrInfo
*HII
;
115 const HexagonRegisterInfo
*HRI
;
119 } // end anonymous namespace
121 char HexagonPacketizer::ID
= 0;
123 INITIALIZE_PASS_BEGIN(HexagonPacketizer
, "hexagon-packetizer",
124 "Hexagon Packetizer", false, false)
125 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
126 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
127 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
128 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
129 INITIALIZE_PASS_END(HexagonPacketizer
, "hexagon-packetizer",
130 "Hexagon Packetizer", false, false)
132 HexagonPacketizerList::HexagonPacketizerList(MachineFunction
&MF
,
133 MachineLoopInfo
&MLI
, AAResults
*AA
,
134 const MachineBranchProbabilityInfo
*MBPI
, bool Minimal
)
135 : VLIWPacketizerList(MF
, MLI
, AA
), MBPI(MBPI
), MLI(&MLI
),
137 HII
= MF
.getSubtarget
<HexagonSubtarget
>().getInstrInfo();
138 HRI
= MF
.getSubtarget
<HexagonSubtarget
>().getRegisterInfo();
140 addMutation(std::make_unique
<HexagonSubtarget::UsrOverflowMutation
>());
141 addMutation(std::make_unique
<HexagonSubtarget::HVXMemLatencyMutation
>());
142 addMutation(std::make_unique
<HexagonSubtarget::BankConflictMutation
>());
145 // Check if FirstI modifies a register that SecondI reads.
146 static bool hasWriteToReadDep(const MachineInstr
&FirstI
,
147 const MachineInstr
&SecondI
,
148 const TargetRegisterInfo
*TRI
) {
149 for (auto &MO
: FirstI
.operands()) {
150 if (!MO
.isReg() || !MO
.isDef())
152 Register R
= MO
.getReg();
153 if (SecondI
.readsRegister(R
, TRI
))
160 static MachineBasicBlock::iterator
moveInstrOut(MachineInstr
&MI
,
161 MachineBasicBlock::iterator BundleIt
, bool Before
) {
162 MachineBasicBlock::instr_iterator InsertPt
;
164 InsertPt
= BundleIt
.getInstrIterator();
166 InsertPt
= std::next(BundleIt
).getInstrIterator();
168 MachineBasicBlock
&B
= *MI
.getParent();
169 // The instruction should at least be bundled with the preceding instruction
170 // (there will always be one, i.e. BUNDLE, if nothing else).
171 assert(MI
.isBundledWithPred());
172 if (MI
.isBundledWithSucc()) {
173 MI
.clearFlag(MachineInstr::BundledSucc
);
174 MI
.clearFlag(MachineInstr::BundledPred
);
176 // If it's not bundled with the successor (i.e. it is the last one
177 // in the bundle), then we can simply unbundle it from the predecessor,
178 // which will take care of updating the predecessor's flag.
179 MI
.unbundleFromPred();
181 B
.splice(InsertPt
, &B
, MI
.getIterator());
183 // Get the size of the bundle without asserting.
184 MachineBasicBlock::const_instr_iterator I
= BundleIt
.getInstrIterator();
185 MachineBasicBlock::const_instr_iterator E
= B
.instr_end();
187 for (++I
; I
!= E
&& I
->isBundledWithPred(); ++I
)
190 // If there are still two or more instructions, then there is nothing
195 // Otherwise, extract the single instruction out and delete the bundle.
196 MachineBasicBlock::iterator NextIt
= std::next(BundleIt
);
197 MachineInstr
&SingleI
= *BundleIt
->getNextNode();
198 SingleI
.unbundleFromPred();
199 assert(!SingleI
.isBundledWithSucc());
200 BundleIt
->eraseFromParent();
204 bool HexagonPacketizer::runOnMachineFunction(MachineFunction
&MF
) {
205 auto &HST
= MF
.getSubtarget
<HexagonSubtarget
>();
206 HII
= HST
.getInstrInfo();
207 HRI
= HST
.getRegisterInfo();
208 auto &MLI
= getAnalysis
<MachineLoopInfo
>();
209 auto *AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
210 auto *MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
212 if (EnableGenAllInsnClass
)
213 HII
->genAllInsnTimingClasses(MF
);
215 // Instantiate the packetizer.
216 bool MinOnly
= Minimal
|| DisablePacketizer
|| !HST
.usePackets() ||
217 skipFunction(MF
.getFunction());
218 HexagonPacketizerList
Packetizer(MF
, MLI
, AA
, MBPI
, MinOnly
);
220 // DFA state table should not be empty.
221 assert(Packetizer
.getResourceTracker() && "Empty DFA table!");
223 // Loop over all basic blocks and remove KILL pseudo-instructions
224 // These instructions confuse the dependence analysis. Consider:
226 // R0 = KILL R0, D0 (Insn 1)
228 // Here, Insn 1 will result in the dependence graph not emitting an output
229 // dependence between Insn 0 and Insn 2. This can lead to incorrect
231 for (MachineBasicBlock
&MB
: MF
) {
233 auto MI
= MB
.begin();
235 auto NextI
= std::next(MI
);
244 // Loop over all of the basic blocks.
245 for (auto &MB
: MF
) {
246 auto Begin
= MB
.begin(), End
= MB
.end();
247 while (Begin
!= End
) {
248 // Find the first non-boundary starting from the end of the last
249 // scheduling region.
250 MachineBasicBlock::iterator RB
= Begin
;
251 while (RB
!= End
&& HII
->isSchedulingBoundary(*RB
, &MB
, MF
))
253 // Find the first boundary starting from the beginning of the new
255 MachineBasicBlock::iterator RE
= RB
;
256 while (RE
!= End
&& !HII
->isSchedulingBoundary(*RE
, &MB
, MF
))
258 // Add the scheduling boundary if it's not block end.
261 // If RB == End, then RE == End.
263 Packetizer
.PacketizeMIs(&MB
, RB
, RE
);
269 Packetizer
.unpacketizeSoloInstrs(MF
);
273 // Reserve resources for a constant extender. Trigger an assertion if the
274 // reservation fails.
275 void HexagonPacketizerList::reserveResourcesForConstExt() {
276 if (!tryAllocateResourcesForConstExt(true))
277 llvm_unreachable("Resources not available");
280 bool HexagonPacketizerList::canReserveResourcesForConstExt() {
281 return tryAllocateResourcesForConstExt(false);
284 // Allocate resources (i.e. 4 bytes) for constant extender. If succeeded,
285 // return true, otherwise, return false.
286 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(bool Reserve
) {
287 auto *ExtMI
= MF
.CreateMachineInstr(HII
->get(Hexagon::A4_ext
), DebugLoc());
288 bool Avail
= ResourceTracker
->canReserveResources(*ExtMI
);
289 if (Reserve
&& Avail
)
290 ResourceTracker
->reserveResources(*ExtMI
);
291 MF
.DeleteMachineInstr(ExtMI
);
295 bool HexagonPacketizerList::isCallDependent(const MachineInstr
&MI
,
296 SDep::Kind DepType
, unsigned DepReg
) {
297 // Check for LR dependence.
298 if (DepReg
== HRI
->getRARegister())
301 if (HII
->isDeallocRet(MI
))
302 if (DepReg
== HRI
->getFrameRegister() || DepReg
== HRI
->getStackRegister())
305 // Call-like instructions can be packetized with preceding instructions
306 // that define registers implicitly used or modified by the call. Explicit
307 // uses are still prohibited, as in the case of indirect calls:
310 if (DepType
== SDep::Data
) {
311 for (const MachineOperand MO
: MI
.operands())
312 if (MO
.isReg() && MO
.getReg() == DepReg
&& !MO
.isImplicit())
319 static bool isRegDependence(const SDep::Kind DepType
) {
320 return DepType
== SDep::Data
|| DepType
== SDep::Anti
||
321 DepType
== SDep::Output
;
324 static bool isDirectJump(const MachineInstr
&MI
) {
325 return MI
.getOpcode() == Hexagon::J2_jump
;
328 static bool isSchedBarrier(const MachineInstr
&MI
) {
329 switch (MI
.getOpcode()) {
330 case Hexagon::Y2_barrier
:
336 static bool isControlFlow(const MachineInstr
&MI
) {
337 return MI
.getDesc().isTerminator() || MI
.getDesc().isCall();
340 /// Returns true if the instruction modifies a callee-saved register.
341 static bool doesModifyCalleeSavedReg(const MachineInstr
&MI
,
342 const TargetRegisterInfo
*TRI
) {
343 const MachineFunction
&MF
= *MI
.getParent()->getParent();
344 for (auto *CSR
= TRI
->getCalleeSavedRegs(&MF
); CSR
&& *CSR
; ++CSR
)
345 if (MI
.modifiesRegister(*CSR
, TRI
))
350 // Returns true if an instruction can be promoted to .new predicate or
352 bool HexagonPacketizerList::isNewifiable(const MachineInstr
&MI
,
353 const TargetRegisterClass
*NewRC
) {
354 // Vector stores can be predicated, and can be new-value stores, but
355 // they cannot be predicated on a .new predicate value.
356 if (NewRC
== &Hexagon::PredRegsRegClass
) {
357 if (HII
->isHVXVec(MI
) && MI
.mayStore())
359 return HII
->isPredicated(MI
) && HII
->getDotNewPredOp(MI
, nullptr) > 0;
361 // If the class is not PredRegs, it could only apply to new-value stores.
362 return HII
->mayBeNewStore(MI
);
365 // Promote an instructiont to its .cur form.
366 // At this time, we have already made a call to canPromoteToDotCur and made
367 // sure that it can *indeed* be promoted.
368 bool HexagonPacketizerList::promoteToDotCur(MachineInstr
&MI
,
369 SDep::Kind DepType
, MachineBasicBlock::iterator
&MII
,
370 const TargetRegisterClass
* RC
) {
371 assert(DepType
== SDep::Data
);
372 int CurOpcode
= HII
->getDotCurOp(MI
);
373 MI
.setDesc(HII
->get(CurOpcode
));
377 void HexagonPacketizerList::cleanUpDotCur() {
378 MachineInstr
*MI
= nullptr;
379 for (auto BI
: CurrentPacketMIs
) {
380 LLVM_DEBUG(dbgs() << "Cleanup packet has "; BI
->dump(););
381 if (HII
->isDotCurInst(*BI
)) {
386 for (auto &MO
: BI
->operands())
387 if (MO
.isReg() && MO
.getReg() == MI
->getOperand(0).getReg())
393 // We did not find a use of the CUR, so de-cur it.
394 MI
->setDesc(HII
->get(HII
->getNonDotCurOp(*MI
)));
395 LLVM_DEBUG(dbgs() << "Demoted CUR "; MI
->dump(););
398 // Check to see if an instruction can be dot cur.
399 bool HexagonPacketizerList::canPromoteToDotCur(const MachineInstr
&MI
,
400 const SUnit
*PacketSU
, unsigned DepReg
, MachineBasicBlock::iterator
&MII
,
401 const TargetRegisterClass
*RC
) {
402 if (!HII
->isHVXVec(MI
))
404 if (!HII
->isHVXVec(*MII
))
407 // Already a dot new instruction.
408 if (HII
->isDotCurInst(MI
) && !HII
->mayBeCurLoad(MI
))
411 if (!HII
->mayBeCurLoad(MI
))
414 // The "cur value" cannot come from inline asm.
415 if (PacketSU
->getInstr()->isInlineAsm())
418 // Make sure candidate instruction uses cur.
419 LLVM_DEBUG(dbgs() << "Can we DOT Cur Vector MI\n"; MI
.dump();
420 dbgs() << "in packet\n";);
421 MachineInstr
&MJ
= *MII
;
423 dbgs() << "Checking CUR against ";
426 Register DestReg
= MI
.getOperand(0).getReg();
427 bool FoundMatch
= false;
428 for (auto &MO
: MJ
.operands())
429 if (MO
.isReg() && MO
.getReg() == DestReg
)
434 // Check for existing uses of a vector register within the packet which
435 // would be affected by converting a vector load into .cur formt.
436 for (auto BI
: CurrentPacketMIs
) {
437 LLVM_DEBUG(dbgs() << "packet has "; BI
->dump(););
438 if (BI
->readsRegister(DepReg
, MF
.getSubtarget().getRegisterInfo()))
442 LLVM_DEBUG(dbgs() << "Can Dot CUR MI\n"; MI
.dump(););
443 // We can convert the opcode into a .cur.
447 // Promote an instruction to its .new form. At this time, we have already
448 // made a call to canPromoteToDotNew and made sure that it can *indeed* be
450 bool HexagonPacketizerList::promoteToDotNew(MachineInstr
&MI
,
451 SDep::Kind DepType
, MachineBasicBlock::iterator
&MII
,
452 const TargetRegisterClass
* RC
) {
453 assert(DepType
== SDep::Data
);
455 if (RC
== &Hexagon::PredRegsRegClass
)
456 NewOpcode
= HII
->getDotNewPredOp(MI
, MBPI
);
458 NewOpcode
= HII
->getDotNewOp(MI
);
459 MI
.setDesc(HII
->get(NewOpcode
));
463 bool HexagonPacketizerList::demoteToDotOld(MachineInstr
&MI
) {
464 int NewOpcode
= HII
->getDotOldOp(MI
);
465 MI
.setDesc(HII
->get(NewOpcode
));
469 bool HexagonPacketizerList::useCallersSP(MachineInstr
&MI
) {
470 unsigned Opc
= MI
.getOpcode();
472 case Hexagon::S2_storerd_io
:
473 case Hexagon::S2_storeri_io
:
474 case Hexagon::S2_storerh_io
:
475 case Hexagon::S2_storerb_io
:
478 llvm_unreachable("Unexpected instruction");
480 unsigned FrameSize
= MF
.getFrameInfo().getStackSize();
481 MachineOperand
&Off
= MI
.getOperand(1);
482 int64_t NewOff
= Off
.getImm() - (FrameSize
+ HEXAGON_LRFP_SIZE
);
483 if (HII
->isValidOffset(Opc
, NewOff
, HRI
)) {
490 void HexagonPacketizerList::useCalleesSP(MachineInstr
&MI
) {
491 unsigned Opc
= MI
.getOpcode();
493 case Hexagon::S2_storerd_io
:
494 case Hexagon::S2_storeri_io
:
495 case Hexagon::S2_storerh_io
:
496 case Hexagon::S2_storerb_io
:
499 llvm_unreachable("Unexpected instruction");
501 unsigned FrameSize
= MF
.getFrameInfo().getStackSize();
502 MachineOperand
&Off
= MI
.getOperand(1);
503 Off
.setImm(Off
.getImm() + FrameSize
+ HEXAGON_LRFP_SIZE
);
506 /// Return true if we can update the offset in MI so that MI and MJ
507 /// can be packetized together.
508 bool HexagonPacketizerList::updateOffset(SUnit
*SUI
, SUnit
*SUJ
) {
509 assert(SUI
->getInstr() && SUJ
->getInstr());
510 MachineInstr
&MI
= *SUI
->getInstr();
511 MachineInstr
&MJ
= *SUJ
->getInstr();
514 if (!HII
->getBaseAndOffsetPosition(MI
, BPI
, OPI
))
517 if (!HII
->getBaseAndOffsetPosition(MJ
, BPJ
, OPJ
))
519 Register Reg
= MI
.getOperand(BPI
).getReg();
520 if (Reg
!= MJ
.getOperand(BPJ
).getReg())
522 // Make sure that the dependences do not restrict adding MI to the packet.
523 // That is, ignore anti dependences, and make sure the only data dependence
524 // involves the specific register.
525 for (const auto &PI
: SUI
->Preds
)
526 if (PI
.getKind() != SDep::Anti
&&
527 (PI
.getKind() != SDep::Data
|| PI
.getReg() != Reg
))
530 if (!HII
->getIncrementValue(MJ
, Incr
))
533 int64_t Offset
= MI
.getOperand(OPI
).getImm();
534 if (!HII
->isValidOffset(MI
.getOpcode(), Offset
+Incr
, HRI
))
537 MI
.getOperand(OPI
).setImm(Offset
+ Incr
);
538 ChangedOffset
= Offset
;
542 /// Undo the changed offset. This is needed if the instruction cannot be
543 /// added to the current packet due to a different instruction.
544 void HexagonPacketizerList::undoChangedOffset(MachineInstr
&MI
) {
546 if (!HII
->getBaseAndOffsetPosition(MI
, BP
, OP
))
547 llvm_unreachable("Unable to find base and offset operands.");
548 MI
.getOperand(OP
).setImm(ChangedOffset
);
557 /// Returns true if an instruction is predicated on p0 and false if it's
558 /// predicated on !p0.
559 static PredicateKind
getPredicateSense(const MachineInstr
&MI
,
560 const HexagonInstrInfo
*HII
) {
561 if (!HII
->isPredicated(MI
))
563 if (HII
->isPredicatedTrue(MI
))
568 static const MachineOperand
&getPostIncrementOperand(const MachineInstr
&MI
,
569 const HexagonInstrInfo
*HII
) {
570 assert(HII
->isPostIncrement(MI
) && "Not a post increment operation.");
572 // Post Increment means duplicates. Use dense map to find duplicates in the
573 // list. Caution: Densemap initializes with the minimum of 64 buckets,
574 // whereas there are at most 5 operands in the post increment.
575 DenseSet
<unsigned> DefRegsSet
;
576 for (auto &MO
: MI
.operands())
577 if (MO
.isReg() && MO
.isDef())
578 DefRegsSet
.insert(MO
.getReg());
580 for (auto &MO
: MI
.operands())
581 if (MO
.isReg() && MO
.isUse() && DefRegsSet
.count(MO
.getReg()))
585 const MachineOperand
&Op1
= MI
.getOperand(1);
586 // The 2nd operand is always the post increment operand in load.
587 assert(Op1
.isReg() && "Post increment operand has be to a register.");
590 if (MI
.getDesc().mayStore()) {
591 const MachineOperand
&Op0
= MI
.getOperand(0);
592 // The 1st operand is always the post increment operand in store.
593 assert(Op0
.isReg() && "Post increment operand has be to a register.");
597 // we should never come here.
598 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
601 // Get the value being stored.
602 static const MachineOperand
& getStoreValueOperand(const MachineInstr
&MI
) {
603 // value being stored is always the last operand.
604 return MI
.getOperand(MI
.getNumOperands()-1);
607 static bool isLoadAbsSet(const MachineInstr
&MI
) {
608 unsigned Opc
= MI
.getOpcode();
610 case Hexagon::L4_loadrd_ap
:
611 case Hexagon::L4_loadrb_ap
:
612 case Hexagon::L4_loadrh_ap
:
613 case Hexagon::L4_loadrub_ap
:
614 case Hexagon::L4_loadruh_ap
:
615 case Hexagon::L4_loadri_ap
:
621 static const MachineOperand
&getAbsSetOperand(const MachineInstr
&MI
) {
622 assert(isLoadAbsSet(MI
));
623 return MI
.getOperand(1);
626 // Can be new value store?
627 // Following restrictions are to be respected in convert a store into
628 // a new value store.
629 // 1. If an instruction uses auto-increment, its address register cannot
630 // be a new-value register. Arch Spec 5.4.2.1
631 // 2. If an instruction uses absolute-set addressing mode, its address
632 // register cannot be a new-value register. Arch Spec 5.4.2.1.
633 // 3. If an instruction produces a 64-bit result, its registers cannot be used
634 // as new-value registers. Arch Spec 5.4.2.2.
635 // 4. If the instruction that sets the new-value register is conditional, then
636 // the instruction that uses the new-value register must also be conditional,
637 // and both must always have their predicates evaluate identically.
638 // Arch Spec 5.4.2.3.
639 // 5. There is an implied restriction that a packet cannot have another store,
640 // if there is a new value store in the packet. Corollary: if there is
641 // already a store in a packet, there can not be a new value store.
642 // Arch Spec: 3.4.4.2
643 bool HexagonPacketizerList::canPromoteToNewValueStore(const MachineInstr
&MI
,
644 const MachineInstr
&PacketMI
, unsigned DepReg
) {
645 // Make sure we are looking at the store, that can be promoted.
646 if (!HII
->mayBeNewStore(MI
))
649 // Make sure there is dependency and can be new value'd.
650 const MachineOperand
&Val
= getStoreValueOperand(MI
);
651 if (Val
.isReg() && Val
.getReg() != DepReg
)
654 const MCInstrDesc
& MCID
= PacketMI
.getDesc();
656 // First operand is always the result.
657 const TargetRegisterClass
*PacketRC
= HII
->getRegClass(MCID
, 0, HRI
, MF
);
658 // Double regs can not feed into new value store: PRM section: 5.4.2.2.
659 if (PacketRC
== &Hexagon::DoubleRegsRegClass
)
662 // New-value stores are of class NV (slot 0), dual stores require class ST
663 // in slot 0 (PRM 5.5).
664 for (auto I
: CurrentPacketMIs
) {
665 SUnit
*PacketSU
= MIToSUnit
.find(I
)->second
;
666 if (PacketSU
->getInstr()->mayStore())
670 // Make sure it's NOT the post increment register that we are going to
672 if (HII
->isPostIncrement(MI
) &&
673 getPostIncrementOperand(MI
, HII
).getReg() == DepReg
) {
677 if (HII
->isPostIncrement(PacketMI
) && PacketMI
.mayLoad() &&
678 getPostIncrementOperand(PacketMI
, HII
).getReg() == DepReg
) {
679 // If source is post_inc, or absolute-set addressing, it can not feed
680 // into new value store
682 // memw(r30 + #-1404) = r2.new -> can not be new value store
683 // arch spec section: 5.4.2.1.
687 if (isLoadAbsSet(PacketMI
) && getAbsSetOperand(PacketMI
).getReg() == DepReg
)
690 // If the source that feeds the store is predicated, new value store must
691 // also be predicated.
692 if (HII
->isPredicated(PacketMI
)) {
693 if (!HII
->isPredicated(MI
))
696 // Check to make sure that they both will have their predicates
697 // evaluate identically.
698 unsigned predRegNumSrc
= 0;
699 unsigned predRegNumDst
= 0;
700 const TargetRegisterClass
* predRegClass
= nullptr;
702 // Get predicate register used in the source instruction.
703 for (auto &MO
: PacketMI
.operands()) {
706 predRegNumSrc
= MO
.getReg();
707 predRegClass
= HRI
->getMinimalPhysRegClass(predRegNumSrc
);
708 if (predRegClass
== &Hexagon::PredRegsRegClass
)
711 assert((predRegClass
== &Hexagon::PredRegsRegClass
) &&
712 "predicate register not found in a predicated PacketMI instruction");
714 // Get predicate register used in new-value store instruction.
715 for (auto &MO
: MI
.operands()) {
718 predRegNumDst
= MO
.getReg();
719 predRegClass
= HRI
->getMinimalPhysRegClass(predRegNumDst
);
720 if (predRegClass
== &Hexagon::PredRegsRegClass
)
723 assert((predRegClass
== &Hexagon::PredRegsRegClass
) &&
724 "predicate register not found in a predicated MI instruction");
726 // New-value register producer and user (store) need to satisfy these
728 // 1) Both instructions should be predicated on the same register.
729 // 2) If producer of the new-value register is .new predicated then store
730 // should also be .new predicated and if producer is not .new predicated
731 // then store should not be .new predicated.
732 // 3) Both new-value register producer and user should have same predicate
733 // sense, i.e, either both should be negated or both should be non-negated.
734 if (predRegNumDst
!= predRegNumSrc
||
735 HII
->isDotNewInst(PacketMI
) != HII
->isDotNewInst(MI
) ||
736 getPredicateSense(MI
, HII
) != getPredicateSense(PacketMI
, HII
))
740 // Make sure that other than the new-value register no other store instruction
741 // register has been modified in the same packet. Predicate registers can be
742 // modified by they should not be modified between the producer and the store
743 // instruction as it will make them both conditional on different values.
744 // We already know this to be true for all the instructions before and
745 // including PacketMI. Howerver, we need to perform the check for the
746 // remaining instructions in the packet.
748 unsigned StartCheck
= 0;
750 for (auto I
: CurrentPacketMIs
) {
751 SUnit
*TempSU
= MIToSUnit
.find(I
)->second
;
752 MachineInstr
&TempMI
= *TempSU
->getInstr();
754 // Following condition is true for all the instructions until PacketMI is
755 // reached (StartCheck is set to 0 before the for loop).
756 // StartCheck flag is 1 for all the instructions after PacketMI.
757 if (&TempMI
!= &PacketMI
&& !StartCheck
) // Start processing only after
758 continue; // encountering PacketMI.
761 if (&TempMI
== &PacketMI
) // We don't want to check PacketMI for dependence.
764 for (auto &MO
: MI
.operands())
765 if (MO
.isReg() && TempSU
->getInstr()->modifiesRegister(MO
.getReg(), HRI
))
769 // Make sure that for non-POST_INC stores:
770 // 1. The only use of reg is DepReg and no other registers.
771 // This handles base+index registers.
772 // The following store can not be dot new.
773 // Eg. r0 = add(r0, #3)
774 // memw(r1+r0<<#2) = r0
775 if (!HII
->isPostIncrement(MI
)) {
776 for (unsigned opNum
= 0; opNum
< MI
.getNumOperands()-1; opNum
++) {
777 const MachineOperand
&MO
= MI
.getOperand(opNum
);
778 if (MO
.isReg() && MO
.getReg() == DepReg
)
783 // If data definition is because of implicit definition of the register,
784 // do not newify the store. Eg.
785 // %r9 = ZXTH %r12, implicit %d6, implicit-def %r12
786 // S2_storerh_io %r8, 2, killed %r12; mem:ST2[%scevgep343]
787 for (auto &MO
: PacketMI
.operands()) {
788 if (MO
.isRegMask() && MO
.clobbersPhysReg(DepReg
))
790 if (!MO
.isReg() || !MO
.isDef() || !MO
.isImplicit())
792 Register R
= MO
.getReg();
793 if (R
== DepReg
|| HRI
->isSuperRegister(DepReg
, R
))
797 // Handle imp-use of super reg case. There is a target independent side
798 // change that should prevent this situation but I am handling it for
799 // just-in-case. For example, we cannot newify R2 in the following case:
801 // S2_storeri_io killed %r0, 0, killed %r2, implicit killed %d1;
802 for (auto &MO
: MI
.operands()) {
803 if (MO
.isReg() && MO
.isUse() && MO
.isImplicit() && MO
.getReg() == DepReg
)
807 // Can be dot new store.
811 // Can this MI to promoted to either new value store or new value jump.
812 bool HexagonPacketizerList::canPromoteToNewValue(const MachineInstr
&MI
,
813 const SUnit
*PacketSU
, unsigned DepReg
,
814 MachineBasicBlock::iterator
&MII
) {
815 if (!HII
->mayBeNewStore(MI
))
818 // Check to see the store can be new value'ed.
819 MachineInstr
&PacketMI
= *PacketSU
->getInstr();
820 if (canPromoteToNewValueStore(MI
, PacketMI
, DepReg
))
823 // Check to see the compare/jump can be new value'ed.
824 // This is done as a pass on its own. Don't need to check it here.
828 static bool isImplicitDependency(const MachineInstr
&I
, bool CheckDef
,
830 for (auto &MO
: I
.operands()) {
831 if (CheckDef
&& MO
.isRegMask() && MO
.clobbersPhysReg(DepReg
))
833 if (!MO
.isReg() || MO
.getReg() != DepReg
|| !MO
.isImplicit())
835 if (CheckDef
== MO
.isDef())
841 // Check to see if an instruction can be dot new.
842 bool HexagonPacketizerList::canPromoteToDotNew(const MachineInstr
&MI
,
843 const SUnit
*PacketSU
, unsigned DepReg
, MachineBasicBlock::iterator
&MII
,
844 const TargetRegisterClass
* RC
) {
845 // Already a dot new instruction.
846 if (HII
->isDotNewInst(MI
) && !HII
->mayBeNewStore(MI
))
849 if (!isNewifiable(MI
, RC
))
852 const MachineInstr
&PI
= *PacketSU
->getInstr();
854 // The "new value" cannot come from inline asm.
855 if (PI
.isInlineAsm())
858 // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no
860 if (PI
.isImplicitDef())
863 // If dependency is trough an implicitly defined register, we should not
865 if (isImplicitDependency(PI
, true, DepReg
) ||
866 isImplicitDependency(MI
, false, DepReg
))
869 const MCInstrDesc
& MCID
= PI
.getDesc();
870 const TargetRegisterClass
*VecRC
= HII
->getRegClass(MCID
, 0, HRI
, MF
);
871 if (DisableVecDblNVStores
&& VecRC
== &Hexagon::HvxWRRegClass
)
875 if (RC
== &Hexagon::PredRegsRegClass
)
876 return HII
->predCanBeUsedAsDotNew(PI
, DepReg
);
878 if (RC
!= &Hexagon::PredRegsRegClass
&& !HII
->mayBeNewStore(MI
))
881 // Create a dot new machine instruction to see if resources can be
882 // allocated. If not, bail out now.
883 int NewOpcode
= HII
->getDotNewOp(MI
);
884 const MCInstrDesc
&D
= HII
->get(NewOpcode
);
885 MachineInstr
*NewMI
= MF
.CreateMachineInstr(D
, DebugLoc());
886 bool ResourcesAvailable
= ResourceTracker
->canReserveResources(*NewMI
);
887 MF
.DeleteMachineInstr(NewMI
);
888 if (!ResourcesAvailable
)
891 // New Value Store only. New Value Jump generated as a separate pass.
892 if (!canPromoteToNewValue(MI
, PacketSU
, DepReg
, MII
))
898 // Go through the packet instructions and search for an anti dependency between
899 // them and DepReg from MI. Consider this case:
901 // a) %r1 = TFRI_cdNotPt %p3, 2
904 // b) %p0 = C2_or killed %p3, killed %p0
905 // c) %p3 = C2_tfrrp %r23
906 // d) %r1 = C2_cmovenewit %p3, 4
908 // The P3 from a) and d) will be complements after
909 // a)'s P3 is converted to .new form
910 // Anti-dep between c) and b) is irrelevant for this case
911 bool HexagonPacketizerList::restrictingDepExistInPacket(MachineInstr
&MI
,
913 SUnit
*PacketSUDep
= MIToSUnit
.find(&MI
)->second
;
915 for (auto I
: CurrentPacketMIs
) {
916 // We only care for dependencies to predicated instructions
917 if (!HII
->isPredicated(*I
))
920 // Scheduling Unit for current insn in the packet
921 SUnit
*PacketSU
= MIToSUnit
.find(I
)->second
;
923 // Look at dependencies between current members of the packet and
924 // predicate defining instruction MI. Make sure that dependency is
925 // on the exact register we care about.
926 if (PacketSU
->isSucc(PacketSUDep
)) {
927 for (unsigned i
= 0; i
< PacketSU
->Succs
.size(); ++i
) {
928 auto &Dep
= PacketSU
->Succs
[i
];
929 if (Dep
.getSUnit() == PacketSUDep
&& Dep
.getKind() == SDep::Anti
&&
930 Dep
.getReg() == DepReg
)
939 /// Gets the predicate register of a predicated instruction.
940 static unsigned getPredicatedRegister(MachineInstr
&MI
,
941 const HexagonInstrInfo
*QII
) {
942 /// We use the following rule: The first predicate register that is a use is
943 /// the predicate register of a predicated instruction.
944 assert(QII
->isPredicated(MI
) && "Must be predicated instruction");
946 for (auto &Op
: MI
.operands()) {
947 if (Op
.isReg() && Op
.getReg() && Op
.isUse() &&
948 Hexagon::PredRegsRegClass
.contains(Op
.getReg()))
952 llvm_unreachable("Unknown instruction operand layout");
956 // Given two predicated instructions, this function detects whether
957 // the predicates are complements.
958 bool HexagonPacketizerList::arePredicatesComplements(MachineInstr
&MI1
,
960 // If we don't know the predicate sense of the instructions bail out early, we
962 if (getPredicateSense(MI1
, HII
) == PK_Unknown
||
963 getPredicateSense(MI2
, HII
) == PK_Unknown
)
966 // Scheduling unit for candidate.
967 SUnit
*SU
= MIToSUnit
[&MI1
];
969 // One corner case deals with the following scenario:
971 // a) %r24 = A2_tfrt %p0, %r25
974 // b) %r25 = A2_tfrf %p0, %r24
975 // c) %p0 = C2_cmpeqi %r26, 1
978 // On general check a) and b) are complements, but presence of c) will
979 // convert a) to .new form, and then it is not a complement.
980 // We attempt to detect it by analyzing existing dependencies in the packet.
982 // Analyze relationships between all existing members of the packet.
983 // Look for Anti dependecy on the same predicate reg as used in the
985 for (auto I
: CurrentPacketMIs
) {
986 // Scheduling Unit for current insn in the packet.
987 SUnit
*PacketSU
= MIToSUnit
.find(I
)->second
;
989 // If this instruction in the packet is succeeded by the candidate...
990 if (PacketSU
->isSucc(SU
)) {
991 for (unsigned i
= 0; i
< PacketSU
->Succs
.size(); ++i
) {
992 auto Dep
= PacketSU
->Succs
[i
];
993 // The corner case exist when there is true data dependency between
994 // candidate and one of current packet members, this dep is on
995 // predicate reg, and there already exist anti dep on the same pred in
997 if (Dep
.getSUnit() == SU
&& Dep
.getKind() == SDep::Data
&&
998 Hexagon::PredRegsRegClass
.contains(Dep
.getReg())) {
999 // Here I know that I is predicate setting instruction with true
1000 // data dep to candidate on the register we care about - c) in the
1001 // above example. Now I need to see if there is an anti dependency
1002 // from c) to any other instruction in the same packet on the pred
1004 if (restrictingDepExistInPacket(*I
, Dep
.getReg()))
1011 // If the above case does not apply, check regular complement condition.
1012 // Check that the predicate register is the same and that the predicate
1013 // sense is different We also need to differentiate .old vs. .new: !p0
1014 // is not complementary to p0.new.
1015 unsigned PReg1
= getPredicatedRegister(MI1
, HII
);
1016 unsigned PReg2
= getPredicatedRegister(MI2
, HII
);
1017 return PReg1
== PReg2
&&
1018 Hexagon::PredRegsRegClass
.contains(PReg1
) &&
1019 Hexagon::PredRegsRegClass
.contains(PReg2
) &&
1020 getPredicateSense(MI1
, HII
) != getPredicateSense(MI2
, HII
) &&
1021 HII
->isDotNewInst(MI1
) == HII
->isDotNewInst(MI2
);
1024 // Initialize packetizer flags.
1025 void HexagonPacketizerList::initPacketizerState() {
1027 PromotedToDotNew
= false;
1028 GlueToNewValueJump
= false;
1029 GlueAllocframeStore
= false;
1030 FoundSequentialDependence
= false;
1031 ChangedOffset
= INT64_MAX
;
1034 // Ignore bundling of pseudo instructions.
1035 bool HexagonPacketizerList::ignorePseudoInstruction(const MachineInstr
&MI
,
1036 const MachineBasicBlock
*) {
1037 if (MI
.isDebugInstr())
1040 if (MI
.isCFIInstruction())
1043 // We must print out inline assembly.
1044 if (MI
.isInlineAsm())
1047 if (MI
.isImplicitDef())
1050 // We check if MI has any functional units mapped to it. If it doesn't,
1051 // we ignore the instruction.
1052 const MCInstrDesc
& TID
= MI
.getDesc();
1053 auto *IS
= ResourceTracker
->getInstrItins()->beginStage(TID
.getSchedClass());
1054 unsigned FuncUnits
= IS
->getUnits();
1058 bool HexagonPacketizerList::isSoloInstruction(const MachineInstr
&MI
) {
1059 // Ensure any bundles created by gather packetize remain seperate.
1063 if (MI
.isEHLabel() || MI
.isCFIInstruction())
1066 // Consider inline asm to not be a solo instruction by default.
1067 // Inline asm will be put in a packet temporarily, but then it will be
1068 // removed, and placed outside of the packet (before or after, depending
1069 // on dependencies). This is to reduce the impact of inline asm as a
1070 // "packet splitting" instruction.
1071 if (MI
.isInlineAsm() && !ScheduleInlineAsm
)
1074 if (isSchedBarrier(MI
))
1077 if (HII
->isSolo(MI
))
1080 if (MI
.getOpcode() == Hexagon::A2_nop
)
1086 // Quick check if instructions MI and MJ cannot coexist in the same packet.
1087 // Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm",
1088 // but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm".
1089 // For full test call this function twice:
1090 // cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI)
1091 // Doing the test only one way saves the amount of code in this function,
1092 // since every test would need to be repeated with the MI and MJ reversed.
1093 static bool cannotCoexistAsymm(const MachineInstr
&MI
, const MachineInstr
&MJ
,
1094 const HexagonInstrInfo
&HII
) {
1095 const MachineFunction
*MF
= MI
.getParent()->getParent();
1096 if (MF
->getSubtarget
<HexagonSubtarget
>().hasV60OpsOnly() &&
1097 HII
.isHVXMemWithAIndirect(MI
, MJ
))
1100 // An inline asm cannot be together with a branch, because we may not be
1101 // able to remove the asm out after packetizing (i.e. if the asm must be
1102 // moved past the bundle). Similarly, two asms cannot be together to avoid
1103 // complications when determining their relative order outside of a bundle.
1104 if (MI
.isInlineAsm())
1105 return MJ
.isInlineAsm() || MJ
.isBranch() || MJ
.isBarrier() ||
1106 MJ
.isCall() || MJ
.isTerminator();
1108 // New-value stores cannot coexist with any other stores.
1109 if (HII
.isNewValueStore(MI
) && MJ
.mayStore())
1112 switch (MI
.getOpcode()) {
1113 case Hexagon::S2_storew_locked
:
1114 case Hexagon::S4_stored_locked
:
1115 case Hexagon::L2_loadw_locked
:
1116 case Hexagon::L4_loadd_locked
:
1117 case Hexagon::Y2_dccleana
:
1118 case Hexagon::Y2_dccleaninva
:
1119 case Hexagon::Y2_dcinva
:
1120 case Hexagon::Y2_dczeroa
:
1121 case Hexagon::Y4_l2fetch
:
1122 case Hexagon::Y5_l2fetch
: {
1123 // These instructions can only be grouped with ALU32 or non-floating-point
1124 // XTYPE instructions. Since there is no convenient way of identifying fp
1125 // XTYPE instructions, only allow grouping with ALU32 for now.
1126 unsigned TJ
= HII
.getType(MJ
);
1127 if (TJ
!= HexagonII::TypeALU32_2op
&&
1128 TJ
!= HexagonII::TypeALU32_3op
&&
1129 TJ
!= HexagonII::TypeALU32_ADDI
)
1137 // "False" really means that the quick check failed to determine if
1138 // I and J cannot coexist.
1142 // Full, symmetric check.
1143 bool HexagonPacketizerList::cannotCoexist(const MachineInstr
&MI
,
1144 const MachineInstr
&MJ
) {
1145 return cannotCoexistAsymm(MI
, MJ
, *HII
) || cannotCoexistAsymm(MJ
, MI
, *HII
);
1148 void HexagonPacketizerList::unpacketizeSoloInstrs(MachineFunction
&MF
) {
1149 for (auto &B
: MF
) {
1150 MachineBasicBlock::iterator BundleIt
;
1151 MachineBasicBlock::instr_iterator NextI
;
1152 for (auto I
= B
.instr_begin(), E
= B
.instr_end(); I
!= E
; I
= NextI
) {
1153 NextI
= std::next(I
);
1154 MachineInstr
&MI
= *I
;
1157 if (!MI
.isInsideBundle())
1160 // Decide on where to insert the instruction that we are pulling out.
1161 // Debug instructions always go before the bundle, but the placement of
1162 // INLINE_ASM depends on potential dependencies. By default, try to
1163 // put it before the bundle, but if the asm writes to a register that
1164 // other instructions in the bundle read, then we need to place it
1165 // after the bundle (to preserve the bundle semantics).
1166 bool InsertBeforeBundle
;
1167 if (MI
.isInlineAsm())
1168 InsertBeforeBundle
= !hasWriteToReadDep(MI
, *BundleIt
, HRI
);
1169 else if (MI
.isDebugValue())
1170 InsertBeforeBundle
= true;
1174 BundleIt
= moveInstrOut(MI
, BundleIt
, InsertBeforeBundle
);
1179 // Check if a given instruction is of class "system".
1180 static bool isSystemInstr(const MachineInstr
&MI
) {
1181 unsigned Opc
= MI
.getOpcode();
1183 case Hexagon::Y2_barrier
:
1184 case Hexagon::Y2_dcfetchbo
:
1185 case Hexagon::Y4_l2fetch
:
1186 case Hexagon::Y5_l2fetch
:
1192 bool HexagonPacketizerList::hasDeadDependence(const MachineInstr
&I
,
1193 const MachineInstr
&J
) {
1194 // The dependence graph may not include edges between dead definitions,
1195 // so without extra checks, we could end up packetizing two instruction
1196 // defining the same (dead) register.
1197 if (I
.isCall() || J
.isCall())
1199 if (HII
->isPredicated(I
) || HII
->isPredicated(J
))
1202 BitVector
DeadDefs(Hexagon::NUM_TARGET_REGS
);
1203 for (auto &MO
: I
.operands()) {
1204 if (!MO
.isReg() || !MO
.isDef() || !MO
.isDead())
1206 DeadDefs
[MO
.getReg()] = true;
1209 for (auto &MO
: J
.operands()) {
1210 if (!MO
.isReg() || !MO
.isDef() || !MO
.isDead())
1212 Register R
= MO
.getReg();
1213 if (R
!= Hexagon::USR_OVF
&& DeadDefs
[R
])
1219 bool HexagonPacketizerList::hasControlDependence(const MachineInstr
&I
,
1220 const MachineInstr
&J
) {
1221 // A save callee-save register function call can only be in a packet
1222 // with instructions that don't write to the callee-save registers.
1223 if ((HII
->isSaveCalleeSavedRegsCall(I
) &&
1224 doesModifyCalleeSavedReg(J
, HRI
)) ||
1225 (HII
->isSaveCalleeSavedRegsCall(J
) &&
1226 doesModifyCalleeSavedReg(I
, HRI
)))
1229 // Two control flow instructions cannot go in the same packet.
1230 if (isControlFlow(I
) && isControlFlow(J
))
1233 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1234 // contain a speculative indirect jump,
1235 // a new-value compare jump or a dealloc_return.
1236 auto isBadForLoopN
= [this] (const MachineInstr
&MI
) -> bool {
1237 if (MI
.isCall() || HII
->isDeallocRet(MI
) || HII
->isNewValueJump(MI
))
1239 if (HII
->isPredicated(MI
) && HII
->isPredicatedNew(MI
) && HII
->isJumpR(MI
))
1244 if (HII
->isLoopN(I
) && isBadForLoopN(J
))
1246 if (HII
->isLoopN(J
) && isBadForLoopN(I
))
1249 // dealloc_return cannot appear in the same packet as a conditional or
1250 // unconditional jump.
1251 return HII
->isDeallocRet(I
) &&
1252 (J
.isBranch() || J
.isCall() || J
.isBarrier());
1255 bool HexagonPacketizerList::hasRegMaskDependence(const MachineInstr
&I
,
1256 const MachineInstr
&J
) {
1257 // Adding I to a packet that has J.
1259 // Regmasks are not reflected in the scheduling dependency graph, so
1260 // we need to check them manually. This code assumes that regmasks only
1261 // occur on calls, and the problematic case is when we add an instruction
1262 // defining a register R to a packet that has a call that clobbers R via
1263 // a regmask. Those cannot be packetized together, because the call will
1264 // be executed last. That's also a reson why it is ok to add a call
1265 // clobbering R to a packet that defines R.
1267 // Look for regmasks in J.
1268 for (const MachineOperand
&OpJ
: J
.operands()) {
1269 if (!OpJ
.isRegMask())
1271 assert((J
.isCall() || HII
->isTailCall(J
)) && "Regmask on a non-call");
1272 for (const MachineOperand
&OpI
: I
.operands()) {
1274 if (OpJ
.clobbersPhysReg(OpI
.getReg()))
1276 } else if (OpI
.isRegMask()) {
1277 // Both are regmasks. Assume that they intersect.
1285 bool HexagonPacketizerList::hasDualStoreDependence(const MachineInstr
&I
,
1286 const MachineInstr
&J
) {
1287 bool SysI
= isSystemInstr(I
), SysJ
= isSystemInstr(J
);
1288 bool StoreI
= I
.mayStore(), StoreJ
= J
.mayStore();
1289 if ((SysI
&& StoreJ
) || (SysJ
&& StoreI
))
1292 if (StoreI
&& StoreJ
) {
1293 if (HII
->isNewValueInst(J
) || HII
->isMemOp(J
) || HII
->isMemOp(I
))
1296 // A memop cannot be in the same packet with another memop or a store.
1297 // Two stores can be together, but here I and J cannot both be stores.
1298 bool MopStI
= HII
->isMemOp(I
) || StoreI
;
1299 bool MopStJ
= HII
->isMemOp(J
) || StoreJ
;
1300 if (MopStI
&& MopStJ
)
1304 return (StoreJ
&& HII
->isDeallocRet(I
)) || (StoreI
&& HII
->isDeallocRet(J
));
1307 // SUI is the current instruction that is out side of the current packet.
1308 // SUJ is the current instruction inside the current packet against which that
1309 // SUI will be packetized.
1310 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit
*SUI
, SUnit
*SUJ
) {
1311 assert(SUI
->getInstr() && SUJ
->getInstr());
1312 MachineInstr
&I
= *SUI
->getInstr();
1313 MachineInstr
&J
= *SUJ
->getInstr();
1315 // Clear IgnoreDepMIs when Packet starts.
1316 if (CurrentPacketMIs
.size() == 1)
1317 IgnoreDepMIs
.clear();
1319 MachineBasicBlock::iterator II
= I
.getIterator();
1321 // Solo instructions cannot go in the packet.
1322 assert(!isSoloInstruction(I
) && "Unexpected solo instr!");
1324 if (cannotCoexist(I
, J
))
1327 Dependence
= hasDeadDependence(I
, J
) || hasControlDependence(I
, J
);
1331 // Regmasks are not accounted for in the scheduling graph, so we need
1332 // to explicitly check for dependencies caused by them. They should only
1333 // appear on calls, so it's not too pessimistic to reject all regmask
1335 Dependence
= hasRegMaskDependence(I
, J
);
1339 // Dual-store does not allow second store, if the first store is not
1340 // in SLOT0. New value store, new value jump, dealloc_return and memop
1341 // always take SLOT0. Arch spec 3.4.4.2.
1342 Dependence
= hasDualStoreDependence(I
, J
);
1346 // If an instruction feeds new value jump, glue it.
1347 MachineBasicBlock::iterator NextMII
= I
.getIterator();
1349 if (NextMII
!= I
.getParent()->end() && HII
->isNewValueJump(*NextMII
)) {
1350 MachineInstr
&NextMI
= *NextMII
;
1352 bool secondRegMatch
= false;
1353 const MachineOperand
&NOp0
= NextMI
.getOperand(0);
1354 const MachineOperand
&NOp1
= NextMI
.getOperand(1);
1356 if (NOp1
.isReg() && I
.getOperand(0).getReg() == NOp1
.getReg())
1357 secondRegMatch
= true;
1359 for (MachineInstr
*PI
: CurrentPacketMIs
) {
1360 // NVJ can not be part of the dual jump - Arch Spec: section 7.8.
1366 // 1. Packet does not have a store in it.
1367 // 2. If the first operand of the nvj is newified, and the second
1368 // operand is also a reg, it (second reg) is not defined in
1370 // 3. If the second operand of the nvj is newified, (which means
1371 // first operand is also a reg), first reg is not defined in
1373 if (PI
->getOpcode() == Hexagon::S2_allocframe
|| PI
->mayStore() ||
1374 HII
->isLoopN(*PI
)) {
1379 const MachineOperand
&OpR
= secondRegMatch
? NOp0
: NOp1
;
1380 if (OpR
.isReg() && PI
->modifiesRegister(OpR
.getReg(), HRI
)) {
1386 GlueToNewValueJump
= true;
1391 // There no dependency between a prolog instruction and its successor.
1392 if (!SUJ
->isSucc(SUI
))
1395 for (unsigned i
= 0; i
< SUJ
->Succs
.size(); ++i
) {
1396 if (FoundSequentialDependence
)
1399 if (SUJ
->Succs
[i
].getSUnit() != SUI
)
1402 SDep::Kind DepType
= SUJ
->Succs
[i
].getKind();
1403 // For direct calls:
1404 // Ignore register dependences for call instructions for packetization
1405 // purposes except for those due to r31 and predicate registers.
1407 // For indirect calls:
1408 // Same as direct calls + check for true dependences to the register
1409 // used in the indirect call.
1411 // We completely ignore Order dependences for call instructions.
1414 // Ignore register dependences for return instructions like jumpr,
1415 // dealloc return unless we have dependencies on the explicit uses
1416 // of the registers used by jumpr (like r31) or dealloc return
1417 // (like r29 or r30).
1418 unsigned DepReg
= 0;
1419 const TargetRegisterClass
*RC
= nullptr;
1420 if (DepType
== SDep::Data
) {
1421 DepReg
= SUJ
->Succs
[i
].getReg();
1422 RC
= HRI
->getMinimalPhysRegClass(DepReg
);
1425 if (I
.isCall() || HII
->isJumpR(I
) || I
.isReturn() || HII
->isTailCall(I
)) {
1426 if (!isRegDependence(DepType
))
1428 if (!isCallDependent(I
, DepType
, SUJ
->Succs
[i
].getReg()))
1432 if (DepType
== SDep::Data
) {
1433 if (canPromoteToDotCur(J
, SUJ
, DepReg
, II
, RC
))
1434 if (promoteToDotCur(J
, DepType
, II
, RC
))
1438 // Data dpendence ok if we have load.cur.
1439 if (DepType
== SDep::Data
&& HII
->isDotCurInst(J
)) {
1440 if (HII
->isHVXVec(I
))
1444 // For instructions that can be promoted to dot-new, try to promote.
1445 if (DepType
== SDep::Data
) {
1446 if (canPromoteToDotNew(I
, SUJ
, DepReg
, II
, RC
)) {
1447 if (promoteToDotNew(I
, DepType
, II
, RC
)) {
1448 PromotedToDotNew
= true;
1449 if (cannotCoexist(I
, J
))
1450 FoundSequentialDependence
= true;
1454 if (HII
->isNewValueJump(I
))
1458 // For predicated instructions, if the predicates are complements then
1459 // there can be no dependence.
1460 if (HII
->isPredicated(I
) && HII
->isPredicated(J
) &&
1461 arePredicatesComplements(I
, J
)) {
1462 // Not always safe to do this translation.
1463 // DAG Builder attempts to reduce dependence edges using transitive
1464 // nature of dependencies. Here is an example:
1466 // r0 = tfr_pt ... (1)
1467 // r0 = tfr_pf ... (2)
1468 // r0 = tfr_pt ... (3)
1470 // There will be an output dependence between (1)->(2) and (2)->(3).
1471 // However, there is no dependence edge between (1)->(3). This results
1472 // in all 3 instructions going in the same packet. We ignore dependce
1473 // only once to avoid this situation.
1474 auto Itr
= find(IgnoreDepMIs
, &J
);
1475 if (Itr
!= IgnoreDepMIs
.end()) {
1479 IgnoreDepMIs
.push_back(&I
);
1483 // Ignore Order dependences between unconditional direct branches
1484 // and non-control-flow instructions.
1485 if (isDirectJump(I
) && !J
.isBranch() && !J
.isCall() &&
1486 DepType
== SDep::Order
)
1489 // Ignore all dependences for jumps except for true and output
1491 if (I
.isConditionalBranch() && DepType
!= SDep::Data
&&
1492 DepType
!= SDep::Output
)
1495 if (DepType
== SDep::Output
) {
1496 FoundSequentialDependence
= true;
1500 // For Order dependences:
1501 // 1. Volatile loads/stores can be packetized together, unless other
1502 // rules prevent is.
1503 // 2. Store followed by a load is not allowed.
1504 // 3. Store followed by a store is valid.
1505 // 4. Load followed by any memory operation is allowed.
1506 if (DepType
== SDep::Order
) {
1507 if (!PacketizeVolatiles
) {
1508 bool OrdRefs
= I
.hasOrderedMemoryRef() || J
.hasOrderedMemoryRef();
1510 FoundSequentialDependence
= true;
1514 // J is first, I is second.
1515 bool LoadJ
= J
.mayLoad(), StoreJ
= J
.mayStore();
1516 bool LoadI
= I
.mayLoad(), StoreI
= I
.mayStore();
1517 bool NVStoreJ
= HII
->isNewValueStore(J
);
1518 bool NVStoreI
= HII
->isNewValueStore(I
);
1519 bool IsVecJ
= HII
->isHVXVec(J
);
1520 bool IsVecI
= HII
->isHVXVec(I
);
1522 if (Slot1Store
&& MF
.getSubtarget
<HexagonSubtarget
>().hasV65Ops() &&
1523 ((LoadJ
&& StoreI
&& !NVStoreI
) ||
1524 (StoreJ
&& LoadI
&& !NVStoreJ
)) &&
1525 (J
.getOpcode() != Hexagon::S2_allocframe
&&
1526 I
.getOpcode() != Hexagon::S2_allocframe
) &&
1527 (J
.getOpcode() != Hexagon::L2_deallocframe
&&
1528 I
.getOpcode() != Hexagon::L2_deallocframe
) &&
1529 (!HII
->isMemOp(J
) && !HII
->isMemOp(I
)) && (!IsVecJ
&& !IsVecI
))
1530 setmemShufDisabled(true);
1532 if (StoreJ
&& LoadI
&& alias(J
, I
)) {
1533 FoundSequentialDependence
= true;
1538 if (!LoadJ
|| (!LoadI
&& !StoreI
)) {
1539 // If J is neither load nor store, assume a dependency.
1540 // If J is a load, but I is neither, also assume a dependency.
1541 FoundSequentialDependence
= true;
1544 // Store followed by store: not OK on V2.
1545 // Store followed by load: not OK on all.
1546 // Load followed by store: OK on all.
1547 // Load followed by load: OK on all.
1551 // Special case for ALLOCFRAME: even though there is dependency
1552 // between ALLOCFRAME and subsequent store, allow it to be packetized
1553 // in a same packet. This implies that the store is using the caller's
1554 // SP. Hence, offset needs to be updated accordingly.
1555 if (DepType
== SDep::Data
&& J
.getOpcode() == Hexagon::S2_allocframe
) {
1556 unsigned Opc
= I
.getOpcode();
1558 case Hexagon::S2_storerd_io
:
1559 case Hexagon::S2_storeri_io
:
1560 case Hexagon::S2_storerh_io
:
1561 case Hexagon::S2_storerb_io
:
1562 if (I
.getOperand(0).getReg() == HRI
->getStackRegister()) {
1563 // Since this store is to be glued with allocframe in the same
1564 // packet, it will use SP of the previous stack frame, i.e.
1565 // caller's SP. Therefore, we need to recalculate offset
1566 // according to this change.
1567 GlueAllocframeStore
= useCallersSP(I
);
1568 if (GlueAllocframeStore
)
1577 // There are certain anti-dependencies that cannot be ignored.
1579 // J2_call ... implicit-def %r0 ; SUJ
1581 // Those cannot be packetized together, since the call will observe
1582 // the effect of the assignment to R0.
1583 if ((DepType
== SDep::Anti
|| DepType
== SDep::Output
) && J
.isCall()) {
1584 // Check if I defines any volatile register. We should also check
1585 // registers that the call may read, but these happen to be a
1586 // subset of the volatile register set.
1587 for (const MachineOperand
&Op
: I
.operands()) {
1588 if (Op
.isReg() && Op
.isDef()) {
1589 Register R
= Op
.getReg();
1590 if (!J
.readsRegister(R
, HRI
) && !J
.modifiesRegister(R
, HRI
))
1592 } else if (!Op
.isRegMask()) {
1593 // If I has a regmask assume dependency.
1596 FoundSequentialDependence
= true;
1601 // Skip over remaining anti-dependences. Two instructions that are
1602 // anti-dependent can share a packet, since in most such cases all
1603 // operands are read before any modifications take place.
1604 // The exceptions are branch and call instructions, since they are
1605 // executed after all other instructions have completed (at least
1607 if (DepType
!= SDep::Anti
) {
1608 FoundSequentialDependence
= true;
1613 if (FoundSequentialDependence
) {
1621 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit
*SUI
, SUnit
*SUJ
) {
1622 assert(SUI
->getInstr() && SUJ
->getInstr());
1623 MachineInstr
&I
= *SUI
->getInstr();
1624 MachineInstr
&J
= *SUJ
->getInstr();
1626 bool Coexist
= !cannotCoexist(I
, J
);
1628 if (Coexist
&& !Dependence
)
1631 // Check if the instruction was promoted to a dot-new. If so, demote it
1632 // back into a dot-old.
1633 if (PromotedToDotNew
)
1637 // Check if the instruction (must be a store) was glued with an allocframe
1638 // instruction. If so, restore its offset to its original value, i.e. use
1639 // current SP instead of caller's SP.
1640 if (GlueAllocframeStore
) {
1642 GlueAllocframeStore
= false;
1645 if (ChangedOffset
!= INT64_MAX
)
1646 undoChangedOffset(I
);
1648 if (GlueToNewValueJump
) {
1649 // Putting I and J together would prevent the new-value jump from being
1650 // packetized with the producer. In that case I and J must be separated.
1651 GlueToNewValueJump
= false;
1658 if (ChangedOffset
== INT64_MAX
&& updateOffset(SUI
, SUJ
)) {
1659 FoundSequentialDependence
= false;
1668 bool HexagonPacketizerList::foundLSInPacket() {
1669 bool FoundLoad
= false;
1670 bool FoundStore
= false;
1672 for (auto MJ
: CurrentPacketMIs
) {
1673 unsigned Opc
= MJ
->getOpcode();
1674 if (Opc
== Hexagon::S2_allocframe
|| Opc
== Hexagon::L2_deallocframe
)
1676 if (HII
->isMemOp(*MJ
))
1680 if (MJ
->mayStore() && !HII
->isNewValueStore(*MJ
))
1683 return FoundLoad
&& FoundStore
;
1687 MachineBasicBlock::iterator
1688 HexagonPacketizerList::addToPacket(MachineInstr
&MI
) {
1689 MachineBasicBlock::iterator MII
= MI
.getIterator();
1690 MachineBasicBlock
*MBB
= MI
.getParent();
1692 if (CurrentPacketMIs
.empty())
1693 PacketStalls
= false;
1694 PacketStalls
|= producesStall(MI
);
1696 if (MI
.isImplicitDef()) {
1697 // Add to the packet to allow subsequent instructions to be checked
1699 CurrentPacketMIs
.push_back(&MI
);
1702 assert(ResourceTracker
->canReserveResources(MI
));
1704 bool ExtMI
= HII
->isExtended(MI
) || HII
->isConstExtended(MI
);
1707 if (GlueToNewValueJump
) {
1708 MachineInstr
&NvjMI
= *++MII
;
1709 // We need to put both instructions in the same packet: MI and NvjMI.
1710 // Either of them can require a constant extender. Try to add both to
1711 // the current packet, and if that fails, end the packet and start a
1713 ResourceTracker
->reserveResources(MI
);
1715 Good
= tryAllocateResourcesForConstExt(true);
1717 bool ExtNvjMI
= HII
->isExtended(NvjMI
) || HII
->isConstExtended(NvjMI
);
1719 if (ResourceTracker
->canReserveResources(NvjMI
))
1720 ResourceTracker
->reserveResources(NvjMI
);
1724 if (Good
&& ExtNvjMI
)
1725 Good
= tryAllocateResourcesForConstExt(true);
1729 assert(ResourceTracker
->canReserveResources(MI
));
1730 ResourceTracker
->reserveResources(MI
);
1732 assert(canReserveResourcesForConstExt());
1733 tryAllocateResourcesForConstExt(true);
1735 assert(ResourceTracker
->canReserveResources(NvjMI
));
1736 ResourceTracker
->reserveResources(NvjMI
);
1738 assert(canReserveResourcesForConstExt());
1739 reserveResourcesForConstExt();
1742 CurrentPacketMIs
.push_back(&MI
);
1743 CurrentPacketMIs
.push_back(&NvjMI
);
1747 ResourceTracker
->reserveResources(MI
);
1748 if (ExtMI
&& !tryAllocateResourcesForConstExt(true)) {
1750 if (PromotedToDotNew
)
1752 if (GlueAllocframeStore
) {
1754 GlueAllocframeStore
= false;
1756 ResourceTracker
->reserveResources(MI
);
1757 reserveResourcesForConstExt();
1760 CurrentPacketMIs
.push_back(&MI
);
1764 void HexagonPacketizerList::endPacket(MachineBasicBlock
*MBB
,
1765 MachineBasicBlock::iterator EndMI
) {
1766 // Replace VLIWPacketizerList::endPacket(MBB, EndMI).
1768 if (!CurrentPacketMIs
.empty()) {
1769 dbgs() << "Finalizing packet:\n";
1771 for (MachineInstr
*MI
: CurrentPacketMIs
) {
1772 unsigned R
= ResourceTracker
->getUsedResources(Idx
++);
1773 dbgs() << " * [res:0x" << utohexstr(R
) << "] " << *MI
;
1778 bool memShufDisabled
= getmemShufDisabled();
1779 if (memShufDisabled
&& !foundLSInPacket()) {
1780 setmemShufDisabled(false);
1781 LLVM_DEBUG(dbgs() << " Not added to NoShufPacket\n");
1783 memShufDisabled
= getmemShufDisabled();
1785 OldPacketMIs
.clear();
1786 for (MachineInstr
*MI
: CurrentPacketMIs
) {
1787 MachineBasicBlock::instr_iterator NextMI
= std::next(MI
->getIterator());
1788 for (auto &I
: make_range(HII
->expandVGatherPseudo(*MI
), NextMI
))
1789 OldPacketMIs
.push_back(&I
);
1791 CurrentPacketMIs
.clear();
1793 if (OldPacketMIs
.size() > 1) {
1794 MachineBasicBlock::instr_iterator
FirstMI(OldPacketMIs
.front());
1795 MachineBasicBlock::instr_iterator
LastMI(EndMI
.getInstrIterator());
1796 finalizeBundle(*MBB
, FirstMI
, LastMI
);
1797 auto BundleMII
= std::prev(FirstMI
);
1798 if (memShufDisabled
)
1799 HII
->setBundleNoShuf(BundleMII
);
1801 setmemShufDisabled(false);
1804 ResourceTracker
->clearResources();
1805 LLVM_DEBUG(dbgs() << "End packet\n");
1808 bool HexagonPacketizerList::shouldAddToPacket(const MachineInstr
&MI
) {
1811 return !producesStall(MI
);
1814 // V60 forward scheduling.
1815 bool HexagonPacketizerList::producesStall(const MachineInstr
&I
) {
1816 // If the packet already stalls, then ignore the stall from a subsequent
1817 // instruction in the same packet.
1821 // Check whether the previous packet is in a different loop. If this is the
1822 // case, there is little point in trying to avoid a stall because that would
1823 // favor the rare case (loop entry) over the common case (loop iteration).
1825 // TODO: We should really be able to check all the incoming edges if this is
1826 // the first packet in a basic block, so we can avoid stalls from the loop
1828 if (!OldPacketMIs
.empty()) {
1829 auto *OldBB
= OldPacketMIs
.front()->getParent();
1830 auto *ThisBB
= I
.getParent();
1831 if (MLI
->getLoopFor(OldBB
) != MLI
->getLoopFor(ThisBB
))
1835 SUnit
*SUI
= MIToSUnit
[const_cast<MachineInstr
*>(&I
)];
1837 // If the latency is 0 and there is a data dependence between this
1838 // instruction and any instruction in the current packet, we disregard any
1839 // potential stalls due to the instructions in the previous packet. Most of
1840 // the instruction pairs that can go together in the same packet have 0
1841 // latency between them. The exceptions are
1842 // 1. NewValueJumps as they're generated much later and the latencies can't
1843 // be changed at that point.
1844 // 2. .cur instructions, if its consumer has a 0 latency successor (such as
1845 // .new). In this case, the latency between .cur and the consumer stays
1846 // non-zero even though we can have both .cur and .new in the same packet.
1847 // Changing the latency to 0 is not an option as it causes software pipeliner
1848 // to not pipeline in some cases.
1852 // I1: v6.cur = vmem(r0++#1)
1853 // I2: v7 = valign(v6,v4,r2)
1854 // I3: vmem(r5++#1) = v7.new
1856 // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2.
1858 for (auto J
: CurrentPacketMIs
) {
1859 SUnit
*SUJ
= MIToSUnit
[J
];
1860 for (auto &Pred
: SUI
->Preds
)
1861 if (Pred
.getSUnit() == SUJ
)
1862 if ((Pred
.getLatency() == 0 && Pred
.isAssignedRegDep()) ||
1863 HII
->isNewValueJump(I
) || HII
->isToBeScheduledASAP(*J
, I
))
1867 // Check if the latency is greater than one between this instruction and any
1868 // instruction in the previous packet.
1869 for (auto J
: OldPacketMIs
) {
1870 SUnit
*SUJ
= MIToSUnit
[J
];
1871 for (auto &Pred
: SUI
->Preds
)
1872 if (Pred
.getSUnit() == SUJ
&& Pred
.getLatency() > 1)
1879 //===----------------------------------------------------------------------===//
1880 // Public Constructor Functions
1881 //===----------------------------------------------------------------------===//
1883 FunctionPass
*llvm::createHexagonPacketizer(bool Minimal
) {
1884 return new HexagonPacketizer(Minimal
);