LLVM 24.0.0git
HexagonVLIWPacketizer.cpp
Go to the documentation of this file.
1//===- HexagonPacketizer.cpp - VLIW packetizer ----------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
16//
17//===----------------------------------------------------------------------===//
18
20#include "Hexagon.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"
42#include "llvm/IR/DebugLoc.h"
44#include "llvm/MC/MCInstrDesc.h"
45#include "llvm/Pass.h"
47#include "llvm/Support/Debug.h"
50#include <cassert>
51#include <cstdint>
52#include <iterator>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "packets"
57
59 cl::desc("Disable Hexagon packetizer pass"));
60
62 "single-float-packet", cl::Hidden,
63 cl::desc("Allow only one single floating point instruction in a packet"));
64
66 "single-complex-packet", cl::Hidden,
67 cl::desc("Allow only one complex instruction in a packet"));
68
69static cl::opt<bool> Slot1Store("slot1-store-slot0-load", cl::Hidden,
70 cl::init(true),
71 cl::desc("Allow slot1 store and slot0 load"));
72
74 "hexagon-packetize-volatiles", cl::Hidden, cl::init(true),
75 cl::desc("Allow non-solo packetization of volatile memory references"));
76
77static cl::opt<bool>
79 cl::desc("Generate all instruction with TC"));
80
81static cl::opt<bool>
82 DisableVecDblNVStores("disable-vecdbl-nv-stores", cl::Hidden,
83 cl::desc("Disable vector double new-value-stores"));
84
86
87namespace {
88
89 class HexagonPacketizer : public MachineFunctionPass {
90 public:
91 static char ID;
92
93 HexagonPacketizer(bool Min = false)
94 : MachineFunctionPass(ID), Minimal(Min) {}
95
96 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.setPreservesCFG();
98 AU.addRequired<AAResultsWrapperPass>();
99 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
100 AU.addRequired<MachineLoopInfoWrapperPass>();
102 }
103
104 StringRef getPassName() const override { return "Hexagon Packetizer"; }
105 bool runOnMachineFunction(MachineFunction &Fn) override;
106
107 MachineFunctionProperties getRequiredProperties() const override {
108 return MachineFunctionProperties().setNoVRegs();
109 }
110
111 private:
112 const HexagonInstrInfo *HII = nullptr;
113 const bool Minimal = false;
114 };
115
116} // end anonymous namespace
117
118char HexagonPacketizer::ID = 0;
119
120INITIALIZE_PASS_BEGIN(HexagonPacketizer, "hexagon-packetizer",
121 "Hexagon Packetizer", false, false)
126INITIALIZE_PASS_END(HexagonPacketizer, "hexagon-packetizer",
127 "Hexagon Packetizer", false, false)
128
133 Minimal(Minimal) {
134 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
135 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
136
137 addMutation(std::make_unique<HexagonSubtarget::UsrOverflowMutation>());
138 addMutation(std::make_unique<HexagonSubtarget::HVXMemLatencyMutation>());
139 addMutation(std::make_unique<HexagonSubtarget::HMXActivateWeightMutation>());
140 addMutation(std::make_unique<HexagonSubtarget::BankConflictMutation>());
141 addMutation(std::make_unique<HexagonSubtarget::HLXPseudoMutation>());
142}
143
144// Check if FirstI modifies a register that SecondI reads.
145static bool hasWriteToReadDep(const MachineInstr &FirstI,
146 const MachineInstr &SecondI,
147 const TargetRegisterInfo *TRI) {
148 for (auto &MO : FirstI.operands()) {
149 if (!MO.isReg() || !MO.isDef())
150 continue;
151 Register R = MO.getReg();
152 if (SecondI.readsRegister(R, TRI))
153 return true;
154 }
155 return false;
156}
157
158
160 MachineBasicBlock::iterator BundleIt, bool Before) {
162 if (Before)
163 InsertPt = BundleIt.getInstrIterator();
164 else
165 InsertPt = std::next(BundleIt).getInstrIterator();
166
167 MachineBasicBlock &B = *MI.getParent();
168 // The instruction should at least be bundled with the preceding instruction
169 // (there will always be one, i.e. BUNDLE, if nothing else).
170 assert(MI.isBundledWithPred());
171 if (MI.isBundledWithSucc()) {
172 MI.clearFlag(MachineInstr::BundledSucc);
173 MI.clearFlag(MachineInstr::BundledPred);
174 } else {
175 // If it's not bundled with the successor (i.e. it is the last one
176 // in the bundle), then we can simply unbundle it from the predecessor,
177 // which will take care of updating the predecessor's flag.
178 MI.unbundleFromPred();
179 }
180 B.splice(InsertPt, &B, MI.getIterator());
181
182 // Get the size of the bundle without asserting.
185 unsigned Size = 0;
186 for (++I; I != E && I->isBundledWithPred(); ++I)
187 ++Size;
188
189 // If there are still two or more instructions, then there is nothing
190 // else to be done.
191 if (Size > 1)
192 return BundleIt;
193
194 // Otherwise, extract the single instruction out and delete the bundle.
195 MachineBasicBlock::iterator NextIt = std::next(BundleIt);
196 MachineInstr &SingleI = *BundleIt->getNextNode();
197 SingleI.unbundleFromPred();
198 assert(!SingleI.isBundledWithSucc());
199 BundleIt->eraseFromParent();
200 return NextIt;
201}
202
203bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) {
204 // FIXME: This pass causes verification failures.
205 MF.getProperties().setFailsVerification();
206
207 auto &HST = MF.getSubtarget<HexagonSubtarget>();
208 HII = HST.getInstrInfo();
209 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
210 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
211 auto *MBPI =
212 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
213
215 HII->genAllInsnTimingClasses(MF);
216
217 // Instantiate the packetizer.
218 bool MinOnly = Minimal || DisablePacketizer || !HST.usePackets() ||
219 skipFunction(MF.getFunction());
220 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI, MinOnly);
221
222 // DFA state table should not be empty.
223 assert(Packetizer.getResourceTracker() && "Empty DFA table!");
224
225 // Loop over all basic blocks and remove KILL pseudo-instructions
226 // These instructions confuse the dependence analysis. Consider:
227 // D0 = ... (Insn 0)
228 // R0 = KILL R0, D0 (Insn 1)
229 // R0 = ... (Insn 2)
230 // Here, Insn 1 will result in the dependence graph not emitting an output
231 // dependence between Insn 0 and Insn 2. This can lead to incorrect
232 // packetization
233 for (MachineBasicBlock &MB : MF) {
234 for (MachineInstr &MI : llvm::make_early_inc_range(MB))
235 if (MI.isKill())
236 MB.erase(&MI);
237 }
238
239 // TinyCore with Duplexes: Translate to big-instructions.
240 if (HST.isTinyCoreWithDuplex())
241 HII->translateInstrsForDup(MF, true);
242
243 // Loop over all of the basic blocks.
244 for (auto &MB : MF) {
245 auto Begin = MB.begin(), End = MB.end();
246 while (Begin != End) {
247 // Find the first non-boundary starting from the end of the last
248 // scheduling region.
250 while (RB != End && HII->isSchedulingBoundary(*RB, &MB, MF))
251 ++RB;
252 // Find the first boundary starting from the beginning of the new
253 // region.
255 while (RE != End && !HII->isSchedulingBoundary(*RE, &MB, MF))
256 ++RE;
257 // Add the scheduling boundary if it's not block end.
258 if (RE != End)
259 ++RE;
260 // If RB == End, then RE == End.
261 if (RB != End)
262 Packetizer.PacketizeMIs(&MB, RB, RE);
263
264 Begin = RE;
265 }
266 }
267
268 // TinyCore with Duplexes: Translate to tiny-instructions.
269 if (HST.isTinyCoreWithDuplex())
270 HII->translateInstrsForDup(MF, false);
271
272 Packetizer.unpacketizeSoloInstrs(MF);
273 return true;
274}
275
276// Reserve resources for a constant extender. Trigger an assertion if the
277// reservation fails.
282
286
287// Allocate resources (i.e. 4 bytes) for constant extender. If succeeded,
288// return true, otherwise, return false.
290 auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc());
291 bool Avail = ResourceTracker->canReserveResources(*ExtMI);
292 if (Reserve && Avail)
293 ResourceTracker->reserveResources(*ExtMI);
294 MF.deleteMachineInstr(ExtMI);
295 return Avail;
296}
297
299 SDep::Kind DepType, unsigned DepReg) {
300 // Check for LR dependence.
301 if (DepReg == HRI->getRARegister())
302 return true;
303
304 if (HII->isDeallocRet(MI))
305 if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister())
306 return true;
307
308 // Call-like instructions can be packetized with preceding instructions
309 // that define registers implicitly used or modified by the call. Explicit
310 // uses are still prohibited, as in the case of indirect calls:
311 // r0 = ...
312 // J2_jumpr r0
313 if (DepType == SDep::Data) {
314 for (const MachineOperand &MO : MI.operands())
315 if (MO.isReg() && MO.getReg() == DepReg && !MO.isImplicit())
316 return true;
317 }
318
319 return false;
320}
321
322static bool isRegDependence(const SDep::Kind DepType) {
323 return DepType == SDep::Data || DepType == SDep::Anti ||
324 DepType == SDep::Output;
325}
326
327static bool isDirectJump(const MachineInstr &MI) {
328 return MI.getOpcode() == Hexagon::J2_jump;
329}
330
331static bool isSchedBarrier(const MachineInstr &MI) {
332 switch (MI.getOpcode()) {
333 case Hexagon::Y2_barrier:
334 return true;
335 }
336 return false;
337}
338
339static bool isControlFlow(const MachineInstr &MI) {
340 return MI.getDesc().isTerminator() || MI.getDesc().isCall();
341}
342
343/// Returns true if the instruction modifies a callee-saved register.
345 const TargetRegisterInfo *TRI) {
346 const MachineFunction &MF = *MI.getParent()->getParent();
347 for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
348 if (MI.modifiesRegister(*CSR, TRI))
349 return true;
350 return false;
351}
352
353// Returns true if an instruction can be promoted to .new predicate or
354// new-value store.
356 const TargetRegisterClass *NewRC) {
357 // Vector stores can be predicated, and can be new-value stores, but
358 // they cannot be predicated on a .new predicate value.
359 if (NewRC == &Hexagon::PredRegsRegClass) {
360 if (HII->isHVXVec(MI) && MI.mayStore())
361 return false;
362 return HII->isPredicated(MI) && HII->getDotNewPredOp(MI, nullptr) > 0;
363 }
364 // If the class is not PredRegs, it could only apply to new-value stores.
365 return HII->mayBeNewStore(MI);
366}
367
368// Promote an instructiont to its .cur form.
369// At this time, we have already made a call to canPromoteToDotCur and made
370// sure that it can *indeed* be promoted.
373 const TargetRegisterClass* RC) {
374 assert(DepType == SDep::Data);
375 int CurOpcode = HII->getDotCurOp(MI);
376 MI.setDesc(HII->get(CurOpcode));
377 return true;
378}
379
381 MachineInstr *MI = nullptr;
382 for (auto *BI : CurrentPacketMIs) {
383 LLVM_DEBUG(dbgs() << "Cleanup packet has "; BI->dump(););
384 if (HII->isDotCurInst(*BI)) {
385 MI = BI;
386 continue;
387 }
388 if (MI) {
389 for (auto &MO : BI->operands())
390 if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg())
391 return;
392 }
393 }
394 if (!MI)
395 return;
396 // We did not find a use of the CUR, so de-cur it.
397 MI->setDesc(HII->get(HII->getNonDotCurOp(*MI)));
398 LLVM_DEBUG(dbgs() << "Demoted CUR "; MI->dump(););
399}
400
401// Check to see if an instruction can be dot cur.
403 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
404 const TargetRegisterClass *RC) {
405 if (!HII->isHVXVec(MI))
406 return false;
407 if (!HII->isHVXVec(*MII))
408 return false;
409
410 // Already a dot new instruction.
411 if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI))
412 return false;
413
414 if (!HII->mayBeCurLoad(MI))
415 return false;
416
417 // The "cur value" cannot come from inline asm.
418 if (PacketSU->getInstr()->isInlineAsm())
419 return false;
420
421 // Make sure candidate instruction uses cur.
422 LLVM_DEBUG(dbgs() << "Can we DOT Cur Vector MI\n"; MI.dump();
423 dbgs() << "in packet\n";);
424 MachineInstr &MJ = *MII;
425 LLVM_DEBUG({
426 dbgs() << "Checking CUR against ";
427 MJ.dump();
428 });
429 Register DestReg = MI.getOperand(0).getReg();
430 bool FoundMatch = false;
431 for (auto &MO : MJ.operands())
432 if (MO.isReg() && MO.getReg() == DestReg)
433 FoundMatch = true;
434 if (!FoundMatch)
435 return false;
436
437 // Check for existing uses of a vector register within the packet which
438 // would be affected by converting a vector load into .cur format.
439 for (auto *BI : CurrentPacketMIs) {
440 LLVM_DEBUG(dbgs() << "packet has "; BI->dump(););
441 if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo()))
442 return false;
443 }
444
445 LLVM_DEBUG(dbgs() << "Can Dot CUR MI\n"; MI.dump(););
446 // We can convert the opcode into a .cur.
447 return true;
448}
449
450// Promote an instruction to its .new form. At this time, we have already
451// made a call to canPromoteToDotNew and made sure that it can *indeed* be
452// promoted.
455 const TargetRegisterClass* RC) {
456 assert(DepType == SDep::Data);
457 int NewOpcode;
458 if (RC == &Hexagon::PredRegsRegClass)
459 NewOpcode = HII->getDotNewPredOp(MI, MBPI);
460 else
461 NewOpcode = HII->getDotNewOp(MI);
462 MI.setDesc(HII->get(NewOpcode));
463 return true;
464}
465
467 int NewOpcode = HII->getDotOldOp(MI);
468 MI.setDesc(HII->get(NewOpcode));
469 return true;
470}
471
473 unsigned Opc = MI.getOpcode();
474 switch (Opc) {
475 case Hexagon::S2_storerd_io:
476 case Hexagon::S2_storeri_io:
477 case Hexagon::S2_storerh_io:
478 case Hexagon::S2_storerb_io:
479 break;
480 default:
481 llvm_unreachable("Unexpected instruction");
482 }
483 unsigned FrameSize = MF.getFrameInfo().getStackSize();
484 MachineOperand &Off = MI.getOperand(1);
485 int64_t NewOff = Off.getImm() - (FrameSize + HEXAGON_LRFP_SIZE);
486 if (HII->isValidOffset(Opc, NewOff)) {
487 Off.setImm(NewOff);
488 return true;
489 }
490 return false;
491}
492
494 unsigned Opc = MI.getOpcode();
495 switch (Opc) {
496 case Hexagon::S2_storerd_io:
497 case Hexagon::S2_storeri_io:
498 case Hexagon::S2_storerh_io:
499 case Hexagon::S2_storerb_io:
500 break;
501 default:
502 llvm_unreachable("Unexpected instruction");
503 }
504 unsigned FrameSize = MF.getFrameInfo().getStackSize();
505 MachineOperand &Off = MI.getOperand(1);
506 Off.setImm(Off.getImm() + FrameSize + HEXAGON_LRFP_SIZE);
507}
508
509/// Return true if we can update the offset in MI so that MI and MJ
510/// can be packetized together.
512 assert(SUI->getInstr() && SUJ->getInstr());
513 MachineInstr &MI = *SUI->getInstr();
514 MachineInstr &MJ = *SUJ->getInstr();
515
516 unsigned BPI, OPI;
517 if (!HII->getBaseAndOffsetPosition(MI, BPI, OPI))
518 return false;
519 unsigned BPJ, OPJ;
520 if (!HII->getBaseAndOffsetPosition(MJ, BPJ, OPJ))
521 return false;
522 Register Reg = MI.getOperand(BPI).getReg();
523 if (Reg != MJ.getOperand(BPJ).getReg())
524 return false;
525 // Make sure that the dependences do not restrict adding MI to the packet.
526 // That is, ignore anti dependences, and make sure the only data dependence
527 // involves the specific register.
528 for (const auto &PI : SUI->Preds)
529 if (PI.getKind() != SDep::Anti &&
530 (PI.getKind() != SDep::Data || PI.getReg() != Reg))
531 return false;
532 int Incr;
533 if (!HII->getIncrementValue(MJ, Incr))
534 return false;
535
536 int64_t Offset = MI.getOperand(OPI).getImm();
537 if (!HII->isValidOffset(MI.getOpcode(), Offset + Incr))
538 return false;
539
540 MI.getOperand(OPI).setImm(Offset + Incr);
541 ChangedOffset = Offset;
542 return true;
543}
544
545/// Undo the changed offset. This is needed if the instruction cannot be
546/// added to the current packet due to a different instruction.
548 unsigned BP, OP;
549 if (!HII->getBaseAndOffsetPosition(MI, BP, OP))
550 llvm_unreachable("Unable to find base and offset operands.");
551 MI.getOperand(OP).setImm(ChangedOffset);
552}
553
559
560/// Returns true if an instruction is predicated on p0 and false if it's
561/// predicated on !p0.
563 const HexagonInstrInfo *HII) {
564 if (!HII->isPredicated(MI))
565 return PK_Unknown;
566 if (HII->isPredicatedTrue(MI))
567 return PK_True;
568 return PK_False;
569}
570
572 const HexagonInstrInfo *HII) {
573 assert(HII->isPostIncrement(MI) && "Not a post increment operation.");
574#ifndef NDEBUG
575 // Post Increment means duplicates. Use dense map to find duplicates in the
576 // list. Caution: Densemap initializes with the minimum of 64 buckets,
577 // whereas there are at most 5 operands in the post increment.
578 DenseSet<unsigned> DefRegsSet;
579 for (auto &MO : MI.operands())
580 if (MO.isReg() && MO.isDef())
581 DefRegsSet.insert(MO.getReg());
582
583 for (auto &MO : MI.operands())
584 if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg()))
585 return MO;
586#else
587 if (MI.mayLoad()) {
588 const MachineOperand &Op1 = MI.getOperand(1);
589 // The 2nd operand is always the post increment operand in load.
590 assert(Op1.isReg() && "Post increment operand has be to a register.");
591 return Op1;
592 }
593 if (MI.getDesc().mayStore()) {
594 const MachineOperand &Op0 = MI.getOperand(0);
595 // The 1st operand is always the post increment operand in store.
596 assert(Op0.isReg() && "Post increment operand has be to a register.");
597 return Op0;
598 }
599#endif
600 // we should never come here.
601 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
602}
603
604// Get the value being stored.
606 // value being stored is always the last operand.
607 return MI.getOperand(MI.getNumOperands()-1);
608}
609
610static bool isLoadAbsSet(const MachineInstr &MI) {
611 unsigned Opc = MI.getOpcode();
612 switch (Opc) {
613 case Hexagon::L4_loadrd_ap:
614 case Hexagon::L4_loadrb_ap:
615 case Hexagon::L4_loadrh_ap:
616 case Hexagon::L4_loadrub_ap:
617 case Hexagon::L4_loadruh_ap:
618 case Hexagon::L4_loadri_ap:
619 return true;
620 }
621 return false;
622}
623
626 return MI.getOperand(1);
627}
628
629// Can be new value store?
630// Following restrictions are to be respected in convert a store into
631// a new value store.
632// 1. If an instruction uses auto-increment, its address register cannot
633// be a new-value register. Arch Spec 5.4.2.1
634// 2. If an instruction uses absolute-set addressing mode, its address
635// register cannot be a new-value register. Arch Spec 5.4.2.1.
636// 3. If an instruction produces a 64-bit result, its registers cannot be used
637// as new-value registers. Arch Spec 5.4.2.2.
638// 4. If the instruction that sets the new-value register is conditional, then
639// the instruction that uses the new-value register must also be conditional,
640// and both must always have their predicates evaluate identically.
641// Arch Spec 5.4.2.3.
642// 5. There is an implied restriction that a packet cannot have another store,
643// if there is a new value store in the packet. Corollary: if there is
644// already a store in a packet, there can not be a new value store.
645// Arch Spec: 3.4.4.2
647 const MachineInstr &PacketMI, unsigned DepReg) {
648 // Make sure we are looking at the store, that can be promoted.
649 if (!HII->mayBeNewStore(MI))
650 return false;
651
652 // Make sure there is dependency and can be new value'd.
654 if (Val.isReg() && Val.getReg() != DepReg)
655 return false;
656
657 const MCInstrDesc& MCID = PacketMI.getDesc();
658
659 // First operand is always the result.
660 const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0);
661 // Double regs can not feed into new value store: PRM section: 5.4.2.2.
662 if (PacketRC == &Hexagon::DoubleRegsRegClass)
663 return false;
664
665 // New-value stores are of class NV (slot 0), dual stores require class ST
666 // in slot 0 (PRM 5.5).
667 for (auto *I : CurrentPacketMIs) {
668 SUnit *PacketSU = MIToSUnit.find(I)->second;
669 if (PacketSU->getInstr()->mayStore())
670 return false;
671 }
672
673 // Make sure it's NOT the post increment register that we are going to
674 // new value.
675 if (HII->isPostIncrement(MI) &&
676 getPostIncrementOperand(MI, HII).getReg() == DepReg) {
677 return false;
678 }
679
680 if (HII->isPostIncrement(PacketMI) && PacketMI.mayLoad() &&
681 getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) {
682 // If source is post_inc, or absolute-set addressing, it can not feed
683 // into new value store
684 // r3 = memw(r2++#4)
685 // memw(r30 + #-1404) = r2.new -> can not be new value store
686 // arch spec section: 5.4.2.1.
687 return false;
688 }
689
690 if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg)
691 return false;
692
693 // If the source that feeds the store is predicated, new value store must
694 // also be predicated.
695 if (HII->isPredicated(PacketMI)) {
696 if (!HII->isPredicated(MI))
697 return false;
698
699 // Check to make sure that they both will have their predicates
700 // evaluate identically.
701 unsigned predRegNumSrc = 0;
702 unsigned predRegNumDst = 0;
703 const TargetRegisterClass* predRegClass = nullptr;
704
705 // Get predicate register used in the source instruction.
706 for (auto &MO : PacketMI.operands()) {
707 if (!MO.isReg())
708 continue;
709 predRegNumSrc = MO.getReg();
710 predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc);
711 if (predRegClass == &Hexagon::PredRegsRegClass)
712 break;
713 }
714 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
715 "predicate register not found in a predicated PacketMI instruction");
716
717 // Get predicate register used in new-value store instruction.
718 for (auto &MO : MI.operands()) {
719 if (!MO.isReg())
720 continue;
721 predRegNumDst = MO.getReg();
722 predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst);
723 if (predRegClass == &Hexagon::PredRegsRegClass)
724 break;
725 }
726 assert((predRegClass == &Hexagon::PredRegsRegClass) &&
727 "predicate register not found in a predicated MI instruction");
728
729 // New-value register producer and user (store) need to satisfy these
730 // constraints:
731 // 1) Both instructions should be predicated on the same register.
732 // 2) If producer of the new-value register is .new predicated then store
733 // should also be .new predicated and if producer is not .new predicated
734 // then store should not be .new predicated.
735 // 3) Both new-value register producer and user should have same predicate
736 // sense, i.e, either both should be negated or both should be non-negated.
737 if (predRegNumDst != predRegNumSrc ||
738 HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) ||
739 getPredicateSense(MI, HII) != getPredicateSense(PacketMI, HII))
740 return false;
741 }
742
743 // Make sure that other than the new-value register no other store instruction
744 // register has been modified in the same packet. Predicate registers can be
745 // modified by they should not be modified between the producer and the store
746 // instruction as it will make them both conditional on different values.
747 // We already know this to be true for all the instructions before and
748 // including PacketMI. However, we need to perform the check for the
749 // remaining instructions in the packet.
750
751 unsigned StartCheck = 0;
752
753 for (auto *I : CurrentPacketMIs) {
754 SUnit *TempSU = MIToSUnit.find(I)->second;
755 MachineInstr &TempMI = *TempSU->getInstr();
756
757 // Following condition is true for all the instructions until PacketMI is
758 // reached (StartCheck is set to 0 before the for loop).
759 // StartCheck flag is 1 for all the instructions after PacketMI.
760 if (&TempMI != &PacketMI && !StartCheck) // Start processing only after
761 continue; // encountering PacketMI.
762
763 StartCheck = 1;
764 if (&TempMI == &PacketMI) // We don't want to check PacketMI for dependence.
765 continue;
766
767 for (auto &MO : MI.operands())
768 if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI))
769 return false;
770 }
771
772 // Make sure that for non-POST_INC stores:
773 // 1. The only use of reg is DepReg and no other registers.
774 // This handles base+index registers.
775 // The following store can not be dot new.
776 // Eg. r0 = add(r0, #3)
777 // memw(r1+r0<<#2) = r0
778 if (!HII->isPostIncrement(MI)) {
779 for (unsigned opNum = 0; opNum < MI.getNumOperands()-1; opNum++) {
780 const MachineOperand &MO = MI.getOperand(opNum);
781 if (MO.isReg() && MO.getReg() == DepReg)
782 return false;
783 }
784 }
785
786 // If data definition is because of implicit definition of the register,
787 // do not newify the store. Eg.
788 // %r9 = ZXTH %r12, implicit %d6, implicit-def %r12
789 // S2_storerh_io %r8, 2, killed %r12; mem:ST2[%scevgep343]
790 for (auto &MO : PacketMI.operands()) {
791 if (MO.isRegMask() && MO.clobbersPhysReg(DepReg))
792 return false;
793 if (!MO.isReg() || !MO.isDef() || !MO.isImplicit())
794 continue;
795 Register R = MO.getReg();
796 if (R == DepReg || HRI->isSuperRegister(DepReg, R))
797 return false;
798 }
799
800 // Handle imp-use of super reg case. There is a target independent side
801 // change that should prevent this situation but I am handling it for
802 // just-in-case. For example, we cannot newify R2 in the following case:
803 // %r3 = A2_tfrsi 0;
804 // S2_storeri_io killed %r0, 0, killed %r2, implicit killed %d1;
805 for (auto &MO : MI.operands()) {
806 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg)
807 return false;
808 }
809
810 // Can be dot new store.
811 return true;
812}
813
814// Can this MI to promoted to either new value store or new value jump.
816 const SUnit *PacketSU, unsigned DepReg,
818 if (!HII->mayBeNewStore(MI))
819 return false;
820
821 // Check to see the store can be new value'ed.
822 MachineInstr &PacketMI = *PacketSU->getInstr();
823 if (canPromoteToNewValueStore(MI, PacketMI, DepReg))
824 return true;
825
826 // Check to see the compare/jump can be new value'ed.
827 // This is done as a pass on its own. Don't need to check it here.
828 return false;
829}
830
831static bool isImplicitDependency(const MachineInstr &I, bool CheckDef,
832 unsigned DepReg) {
833 for (auto &MO : I.operands()) {
834 if (CheckDef && MO.isRegMask() && MO.clobbersPhysReg(DepReg))
835 return true;
836 if (!MO.isReg() || MO.getReg() != DepReg || !MO.isImplicit())
837 continue;
838 if (CheckDef == MO.isDef())
839 return true;
840 }
841 return false;
842}
843
844// Check to see if an instruction can be dot new.
846 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
847 const TargetRegisterClass* RC) {
848 // Already a dot new instruction.
849 if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI))
850 return false;
851
852 if (!isNewifiable(MI, RC))
853 return false;
854
855 const MachineInstr &PI = *PacketSU->getInstr();
856
857 // The "new value" cannot come from inline asm.
858 if (PI.isInlineAsm())
859 return false;
860
861 // IMPLICIT_DEFs and FREEZEs won't materialize as real instructions, so .new
862 // makes no sense.
863 if (PI.isImplicitDef() || PI.getOpcode() == TargetOpcode::FREEZE)
864 return false;
865
866 // If dependency is through an implicitly defined register, we should not
867 // newify the use.
868 if (isImplicitDependency(PI, true, DepReg) ||
869 isImplicitDependency(MI, false, DepReg))
870 return false;
871
872 const MCInstrDesc& MCID = PI.getDesc();
873 const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0);
874 if (DisableVecDblNVStores && VecRC == &Hexagon::HvxWRRegClass)
875 return false;
876
877 // predicate .new
878 if (RC == &Hexagon::PredRegsRegClass)
879 return HII->predCanBeUsedAsDotNew(PI, DepReg);
880
881 if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI))
882 return false;
883
884 // Create a dot new machine instruction to see if resources can be
885 // allocated. If not, bail out now.
886 int NewOpcode = (RC != &Hexagon::PredRegsRegClass) ? HII->getDotNewOp(MI) :
887 HII->getDotNewPredOp(MI, MBPI);
888 const MCInstrDesc &D = HII->get(NewOpcode);
889 MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc());
890 bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI);
891 MF.deleteMachineInstr(NewMI);
892 if (!ResourcesAvailable)
893 return false;
894
895 // New Value Store only. New Value Jump generated as a separate pass.
896 if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII))
897 return false;
898
899 return true;
900}
901
902// Go through the packet instructions and search for an anti dependency between
903// them and DepReg from MI. Consider this case:
904// Trying to add
905// a) %r1 = TFRI_cdNotPt %p3, 2
906// to this packet:
907// {
908// b) %p0 = C2_or killed %p3, killed %p0
909// c) %p3 = C2_tfrrp %r23
910// d) %r1 = C2_cmovenewit %p3, 4
911// }
912// The P3 from a) and d) will be complements after
913// a)'s P3 is converted to .new form
914// Anti-dep between c) and b) is irrelevant for this case
916 unsigned DepReg) {
917 SUnit *PacketSUDep = MIToSUnit.find(&MI)->second;
918
919 for (auto *I : CurrentPacketMIs) {
920 // We only care for dependencies to predicated instructions
921 if (!HII->isPredicated(*I))
922 continue;
923
924 // Scheduling Unit for current insn in the packet
925 SUnit *PacketSU = MIToSUnit.find(I)->second;
926
927 // Look at dependencies between current members of the packet and
928 // predicate defining instruction MI. Make sure that dependency is
929 // on the exact register we care about.
930 if (PacketSU->isSucc(PacketSUDep)) {
931 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
932 auto &Dep = PacketSU->Succs[i];
933 if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti &&
934 Dep.getReg() == DepReg)
935 return true;
936 }
937 }
938 }
939
940 return false;
941}
942
943/// Gets the predicate register of a predicated instruction.
945 const HexagonInstrInfo *QII) {
946 /// We use the following rule: The first predicate register that is a use is
947 /// the predicate register of a predicated instruction.
948 assert(QII->isPredicated(MI) && "Must be predicated instruction");
949
950 for (auto &Op : MI.operands()) {
951 if (Op.isReg() && Op.getReg() && Op.isUse() &&
952 Hexagon::PredRegsRegClass.contains(Op.getReg()))
953 return Op.getReg();
954 }
955
956 llvm_unreachable("Unknown instruction operand layout");
957 return 0;
958}
959
960// Given two predicated instructions, this function detects whether
961// the predicates are complements.
963 MachineInstr &MI2) {
964 // If we don't know the predicate sense of the instructions bail out early, we
965 // need it later.
966 if (getPredicateSense(MI1, HII) == PK_Unknown ||
967 getPredicateSense(MI2, HII) == PK_Unknown)
968 return false;
969
970 // Scheduling unit for candidate.
971 SUnit *SU = MIToSUnit[&MI1];
972
973 // One corner case deals with the following scenario:
974 // Trying to add
975 // a) %r24 = A2_tfrt %p0, %r25
976 // to this packet:
977 // {
978 // b) %r25 = A2_tfrf %p0, %r24
979 // c) %p0 = C2_cmpeqi %r26, 1
980 // }
981 //
982 // On general check a) and b) are complements, but presence of c) will
983 // convert a) to .new form, and then it is not a complement.
984 // We attempt to detect it by analyzing existing dependencies in the packet.
985
986 // Analyze relationships between all existing members of the packet.
987 // Look for Anti dependency on the same predicate reg as used in the
988 // candidate.
989 for (auto *I : CurrentPacketMIs) {
990 // Scheduling Unit for current insn in the packet.
991 SUnit *PacketSU = MIToSUnit.find(I)->second;
992
993 // If this instruction in the packet is succeeded by the candidate...
994 if (PacketSU->isSucc(SU)) {
995 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
996 auto Dep = PacketSU->Succs[i];
997 // The corner case exist when there is true data dependency between
998 // candidate and one of current packet members, this dep is on
999 // predicate reg, and there already exist anti dep on the same pred in
1000 // the packet.
1001 if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data &&
1002 Hexagon::PredRegsRegClass.contains(Dep.getReg())) {
1003 // Here I know that I is predicate setting instruction with true
1004 // data dep to candidate on the register we care about - c) in the
1005 // above example. Now I need to see if there is an anti dependency
1006 // from c) to any other instruction in the same packet on the pred
1007 // reg of interest.
1008 if (restrictingDepExistInPacket(*I, Dep.getReg()))
1009 return false;
1010 }
1011 }
1012 }
1013 }
1014
1015 // If the above case does not apply, check regular complement condition.
1016 // Check that the predicate register is the same and that the predicate
1017 // sense is different We also need to differentiate .old vs. .new: !p0
1018 // is not complementary to p0.new.
1019 unsigned PReg1 = getPredicatedRegister(MI1, HII);
1020 unsigned PReg2 = getPredicatedRegister(MI2, HII);
1021 return PReg1 == PReg2 &&
1022 Hexagon::PredRegsRegClass.contains(PReg1) &&
1023 Hexagon::PredRegsRegClass.contains(PReg2) &&
1024 getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) &&
1025 HII->isDotNewInst(MI1) == HII->isDotNewInst(MI2);
1026}
1027
1028// Initialize packetizer flags.
1030 Dependence = false;
1031 PromotedToDotNew = false;
1032 GlueToNewValueJump = false;
1033 GlueAllocframeStore = false;
1034 FoundSequentialDependence = false;
1035 ChangedOffset = INT64_MAX;
1036}
1037
1038// Ignore bundling of pseudo instructions.
1040 const MachineBasicBlock *) {
1041 if (MI.isDebugInstr())
1042 return true;
1043
1044 if (MI.isCFIInstruction())
1045 return false;
1046
1047 // We must print out inline assembly.
1048 if (MI.isInlineAsm())
1049 return false;
1050
1051 if (MI.isImplicitDef() || MI.getOpcode() == TargetOpcode::FREEZE)
1052 return false;
1053
1054 // We check if MI has any functional units mapped to it. If it doesn't,
1055 // we ignore the instruction.
1056 const MCInstrDesc& TID = MI.getDesc();
1057 auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass());
1058 return !IS->getUnits();
1059}
1060
1062 // Ensure any bundles created by gather packetize remain separate.
1063 if (MI.isBundle())
1064 return true;
1065
1066 if (MI.isEHLabel() || MI.isCFIInstruction())
1067 return true;
1068
1069 // Consider inline asm to not be a solo instruction by default.
1070 // Inline asm will be put in a packet temporarily, but then it will be
1071 // removed, and placed outside of the packet (before or after, depending
1072 // on dependencies). This is to reduce the impact of inline asm as a
1073 // "packet splitting" instruction.
1074 if (MI.isInlineAsm() && !ScheduleInlineAsm)
1075 return true;
1076
1077 if (isSchedBarrier(MI))
1078 return true;
1079
1080 if (HII->isSolo(MI))
1081 return true;
1082
1083 if (MI.getOpcode() == Hexagon::PATCHABLE_FUNCTION_ENTER ||
1084 MI.getOpcode() == Hexagon::PATCHABLE_FUNCTION_EXIT ||
1085 MI.getOpcode() == Hexagon::PATCHABLE_TAIL_CALL ||
1086 MI.getOpcode() == Hexagon::PATCHABLE_EVENT_CALL ||
1087 MI.getOpcode() == Hexagon::PATCHABLE_TYPED_EVENT_CALL)
1088 return true;
1089
1090 if (MI.getOpcode() == Hexagon::A2_nop)
1091 return true;
1092
1093 return false;
1094}
1095
1096// Quick check if instructions MI and MJ cannot coexist in the same packet.
1097// Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm",
1098// but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm".
1099// For full test call this function twice:
1100// cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI)
1101// Doing the test only one way saves the amount of code in this function,
1102// since every test would need to be repeated with the MI and MJ reversed.
1103static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ,
1104 const HexagonInstrInfo &HII) {
1105 if (OneFloatPerPacket && HII.isFloat(MI) && HII.isFloat(MJ))
1106 return true;
1107 if (OneComplexPerPacket && HII.isComplex(MI) && HII.isComplex(MJ))
1108 return true;
1109
1110 const MachineFunction *MF = MI.getParent()->getParent();
1112 HII.isHVXMemWithAIndirect(MI, MJ))
1113 return true;
1114
1115 // Don't allow a store and an instruction that must be in slot0 and
1116 // doesn't allow a slot1 instruction.
1117 if (MI.mayStore() && HII.isRestrictNoSlot1Store(MJ) && HII.isPureSlot0(MJ))
1118 return true;
1119
1120 // An inline asm cannot be together with a branch, because we may not be
1121 // able to remove the asm out after packetizing (i.e. if the asm must be
1122 // moved past the bundle). Similarly, two asms cannot be together to avoid
1123 // complications when determining their relative order outside of a bundle.
1124 if (MI.isInlineAsm())
1125 return MJ.isInlineAsm() || MJ.isBranch() || MJ.isBarrier() ||
1126 MJ.isCall() || MJ.isTerminator();
1127
1128 // New-value stores cannot coexist with any other stores.
1129 if (HII.isNewValueStore(MI) && MJ.mayStore())
1130 return true;
1131
1132 const auto &MID = MI.getDesc();
1133 const auto &MJD = MJ.getDesc();
1134 bool isHVXVS3SRC = HexagonII::getTSFlag(MID, HexagonII::isHVXVS3SRCPos);
1135 if (isHVXVS3SRC) {
1136 bool HVXALU2SRC = HexagonII::getTSFlag(MJD, HexagonII::isHVXALU2SRCPos);
1137 if (HVXALU2SRC) // Checking for a Non Unary HVX ALU Operation.
1138 return true;
1139 const uint64_t V = HII.getType(MJ);
1140 // HVX permute instruction cannot be paired with 3 source shift.
1141 if (V == HexagonII::TypeCVI_VP)
1142 return true;
1143 // v79 onwards, a packet can have two HVX shift instructions.
1144 // But an HVX shift instruction cannot be paired with 3 source shift.
1145 if (V == HexagonII::TypeCVI_VS)
1146 return true;
1147 }
1148
1149 // An HLX instruction with a 64-bit scalar source cannot be paired with
1150 // another HLX instruction using a scalar or immediate source. Loads and
1151 // stores are exempt because they do not use the shared scalar resource.
1152 if (HII.isHLXVec(MI) && HII.isHLXVec(MJ) && !MJ.mayLoad() && !MJ.mayStore()) {
1153 auto getScalarUses = [](const MachineInstr &MI) {
1154 unsigned Uses = 0;
1155 for (const MachineOperand &MO : MI.explicit_uses()) {
1156 if (MO.isImm())
1157 Uses |= 1;
1158 else if (MO.isReg() && Hexagon::IntRegsRegClass.contains(MO.getReg()))
1159 Uses |= 2;
1160 else if (MO.isReg() &&
1161 Hexagon::DoubleRegsRegClass.contains(MO.getReg()))
1162 Uses |= 4;
1163 }
1164 return Uses;
1165 };
1166
1167 if ((getScalarUses(MI) & 4) && getScalarUses(MJ))
1168 return true;
1169 }
1170
1171 switch (MI.getOpcode()) {
1172 case Hexagon::S2_storew_locked:
1173 case Hexagon::S4_stored_locked:
1174 case Hexagon::L2_loadw_locked:
1175 case Hexagon::L4_loadd_locked:
1176 case Hexagon::Y2_dccleana:
1177 case Hexagon::Y2_dccleaninva:
1178 case Hexagon::Y2_dcinva:
1179 case Hexagon::Y2_dczeroa:
1180 case Hexagon::Y4_l2fetch:
1181 case Hexagon::Y5_l2fetch: {
1182 // These instructions can only be grouped with ALU32 or non-floating-point
1183 // XTYPE instructions. Since there is no convenient way of identifying fp
1184 // XTYPE instructions, only allow grouping with ALU32 for now.
1185 unsigned TJ = HII.getType(MJ);
1186 if (TJ != HexagonII::TypeALU32_2op &&
1189 return true;
1190 break;
1191 }
1192 case Hexagon::LX_S16b_pseudo: {
1193 // The store pseudo expands to a copy of the stored register followed by a
1194 // new-value store. Do not packetize it with an instruction defining that
1195 // register, otherwise the packet would have two definitions of it.
1196 Register StReg = MI.getOperand(1).getReg();
1197 const HexagonRegisterInfo &HRI = HII.getRegisterInfo();
1198 if (any_of(MJ.all_defs(), [&](const MachineOperand &Def) {
1199 return HRI.isSuperRegisterEq(StReg, Def.getReg());
1200 }))
1201 return true;
1202 break;
1203 }
1204 default:
1205 break;
1206 }
1207
1208 // "False" really means that the quick check failed to determine if
1209 // I and J cannot coexist.
1210 return false;
1211}
1212
1213// Full, symmetric check.
1215 const MachineInstr &MJ) {
1216 return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII);
1217}
1218
1220 for (auto &B : MF) {
1222 for (MachineInstr &MI : llvm::make_early_inc_range(B.instrs())) {
1223 if (MI.isBundle())
1224 BundleIt = MI.getIterator();
1225 if (!MI.isInsideBundle())
1226 continue;
1227
1228 // Decide on where to insert the instruction that we are pulling out.
1229 // Debug instructions always go before the bundle, but the placement of
1230 // INLINE_ASM depends on potential dependencies. By default, try to
1231 // put it before the bundle, but if the asm writes to a register that
1232 // other instructions in the bundle read, then we need to place it
1233 // after the bundle (to preserve the bundle semantics).
1234 bool InsertBeforeBundle;
1235 if (MI.isInlineAsm())
1236 InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI);
1237 else if (MI.isDebugInstr())
1238 InsertBeforeBundle = true;
1239 else
1240 continue;
1241
1242 BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle);
1243 }
1244 }
1245}
1246
1247// Check if a given instruction is of class "system".
1248static bool isSystemInstr(const MachineInstr &MI) {
1249 unsigned Opc = MI.getOpcode();
1250 switch (Opc) {
1251 case Hexagon::Y2_barrier:
1252 case Hexagon::Y2_dcfetchbo:
1253 case Hexagon::Y4_l2fetch:
1254 case Hexagon::Y5_l2fetch:
1255 return true;
1256 }
1257 return false;
1258}
1259
1261 const MachineInstr &J) {
1262 // The dependence graph may not include edges between dead definitions,
1263 // so without extra checks, we could end up packetizing two instruction
1264 // defining the same (dead) register.
1265 if (I.isCall() || J.isCall())
1266 return false;
1267 if (HII->isPredicated(I) || HII->isPredicated(J))
1268 return false;
1269
1270 BitVector DeadDefs(Hexagon::NUM_TARGET_REGS);
1271 for (auto &MO : I.operands()) {
1272 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1273 continue;
1274 DeadDefs[MO.getReg()] = true;
1275 }
1276
1277 for (auto &MO : J.operands()) {
1278 if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1279 continue;
1280 Register R = MO.getReg();
1281 if (R != Hexagon::USR_OVF && DeadDefs[R])
1282 return true;
1283 }
1284 return false;
1285}
1286
1288 const MachineInstr &J) {
1289 // A save callee-save register function call can only be in a packet
1290 // with instructions that don't write to the callee-save registers.
1291 if ((HII->isSaveCalleeSavedRegsCall(I) &&
1292 doesModifyCalleeSavedReg(J, HRI)) ||
1293 (HII->isSaveCalleeSavedRegsCall(J) &&
1295 return true;
1296
1297 // Two control flow instructions cannot go in the same packet.
1298 if (isControlFlow(I) && isControlFlow(J))
1299 return true;
1300
1301 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1302 // contain a speculative indirect jump,
1303 // a new-value compare jump or a dealloc_return.
1304 auto isBadForLoopN = [this] (const MachineInstr &MI) -> bool {
1305 if (MI.isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI))
1306 return true;
1307 if (HII->isPredicated(MI) && HII->isPredicatedNew(MI) && HII->isJumpR(MI))
1308 return true;
1309 return false;
1310 };
1311
1312 if (HII->isLoopN(I) && isBadForLoopN(J))
1313 return true;
1314 if (HII->isLoopN(J) && isBadForLoopN(I))
1315 return true;
1316
1317 // dealloc_return cannot appear in the same packet as a conditional or
1318 // unconditional jump.
1319 return HII->isDeallocRet(I) &&
1320 (J.isBranch() || J.isCall() || J.isBarrier());
1321}
1322
1324 const MachineInstr &J) {
1325 // Adding I to a packet that has J.
1326
1327 // Regmasks are not reflected in the scheduling dependency graph, so
1328 // we need to check them manually. This code assumes that regmasks only
1329 // occur on calls, and the problematic case is when we add an instruction
1330 // defining a register R to a packet that has a call that clobbers R via
1331 // a regmask. Those cannot be packetized together, because the call will
1332 // be executed last. That's also a reason why it is ok to add a call
1333 // clobbering R to a packet that defines R.
1334
1335 // Look for regmasks in J.
1336 for (const MachineOperand &OpJ : J.operands()) {
1337 if (!OpJ.isRegMask())
1338 continue;
1339 assert((J.isCall() || HII->isTailCall(J)) && "Regmask on a non-call");
1340 for (const MachineOperand &OpI : I.operands()) {
1341 if (OpI.isReg()) {
1342 if (OpJ.clobbersPhysReg(OpI.getReg()))
1343 return true;
1344 } else if (OpI.isRegMask()) {
1345 // Both are regmasks. Assume that they intersect.
1346 return true;
1347 }
1348 }
1349 }
1350 return false;
1351}
1352
1354 const MachineInstr &J) {
1355 bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J);
1356 bool StoreI = I.mayStore(), StoreJ = J.mayStore();
1357 if ((SysI && StoreJ) || (SysJ && StoreI))
1358 return true;
1359
1360 if (StoreI && StoreJ) {
1361 if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I))
1362 return true;
1363 } else {
1364 // A memop cannot be in the same packet with another memop or a store.
1365 // Two stores can be together, but here I and J cannot both be stores.
1366 bool MopStI = HII->isMemOp(I) || StoreI;
1367 bool MopStJ = HII->isMemOp(J) || StoreJ;
1368 if (MopStI && MopStJ)
1369 return true;
1370 }
1371
1372 return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J));
1373}
1374
1375// SUI is the current instruction that is outside of the current packet.
1376// SUJ is the current instruction inside the current packet against which that
1377// SUI will be packetized.
1379 assert(SUI->getInstr() && SUJ->getInstr());
1380 MachineInstr &I = *SUI->getInstr();
1381 MachineInstr &J = *SUJ->getInstr();
1382
1383 // Clear IgnoreDepMIs when Packet starts.
1384 if (CurrentPacketMIs.size() == 1)
1385 IgnoreDepMIs.clear();
1386
1387 MachineBasicBlock::iterator II = I.getIterator();
1388
1389 // Solo instructions cannot go in the packet.
1390 assert(!isSoloInstruction(I) && "Unexpected solo instr!");
1391
1392 if (cannotCoexist(I, J))
1393 return false;
1394
1395 Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J);
1396 if (Dependence)
1397 return false;
1398
1399 // Regmasks are not accounted for in the scheduling graph, so we need
1400 // to explicitly check for dependencies caused by them. They should only
1401 // appear on calls, so it's not too pessimistic to reject all regmask
1402 // dependencies.
1403 Dependence = hasRegMaskDependence(I, J);
1404 if (Dependence)
1405 return false;
1406
1407 // Dual-store does not allow second store, if the first store is not
1408 // in SLOT0. New value store, new value jump, dealloc_return and memop
1409 // always take SLOT0. Arch spec 3.4.4.2.
1410 Dependence = hasDualStoreDependence(I, J);
1411 if (Dependence)
1412 return false;
1413
1414 // If an instruction feeds new value jump, glue it.
1415 MachineBasicBlock::iterator NextMII = I.getIterator();
1416 ++NextMII;
1417 if (NextMII != I.getParent()->end() && HII->isNewValueJump(*NextMII)) {
1418 MachineInstr &NextMI = *NextMII;
1419
1420 bool secondRegMatch = false;
1421 const MachineOperand &NOp0 = NextMI.getOperand(0);
1422 const MachineOperand &NOp1 = NextMI.getOperand(1);
1423
1424 if (NOp1.isReg() && I.getOperand(0).getReg() == NOp1.getReg())
1425 secondRegMatch = true;
1426
1427 for (MachineInstr *PI : CurrentPacketMIs) {
1428 // NVJ can not be part of the dual jump - Arch Spec: section 7.8.
1429 if (PI->isCall()) {
1430 Dependence = true;
1431 break;
1432 }
1433 // Validate:
1434 // 1. Packet does not have a store in it.
1435 // 2. If the first operand of the nvj is newified, and the second
1436 // operand is also a reg, it (second reg) is not defined in
1437 // the same packet.
1438 // 3. If the second operand of the nvj is newified, (which means
1439 // first operand is also a reg), first reg is not defined in
1440 // the same packet.
1441 if (PI->getOpcode() == Hexagon::S2_allocframe || PI->mayStore() ||
1442 HII->isLoopN(*PI)) {
1443 Dependence = true;
1444 break;
1445 }
1446 // Check #2/#3.
1447 const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1;
1448 if (OpR.isReg() && PI->modifiesRegister(OpR.getReg(), HRI)) {
1449 Dependence = true;
1450 break;
1451 }
1452 }
1453
1454 GlueToNewValueJump = true;
1455 if (Dependence)
1456 return false;
1457 }
1458
1459 // There no dependency between a prolog instruction and its successor.
1460 if (!SUJ->isSucc(SUI))
1461 return true;
1462
1463 for (unsigned i = 0; i < SUJ->Succs.size(); ++i) {
1464 if (FoundSequentialDependence)
1465 break;
1466
1467 if (SUJ->Succs[i].getSUnit() != SUI)
1468 continue;
1469
1470 SDep::Kind DepType = SUJ->Succs[i].getKind();
1471 // For direct calls:
1472 // Ignore register dependences for call instructions for packetization
1473 // purposes except for those due to r31 and predicate registers.
1474 //
1475 // For indirect calls:
1476 // Same as direct calls + check for true dependences to the register
1477 // used in the indirect call.
1478 //
1479 // We completely ignore Order dependences for call instructions.
1480 //
1481 // For returns:
1482 // Ignore register dependences for return instructions like jumpr,
1483 // dealloc return unless we have dependencies on the explicit uses
1484 // of the registers used by jumpr (like r31) or dealloc return
1485 // (like r29 or r30).
1486 unsigned DepReg = 0;
1487 const TargetRegisterClass *RC = nullptr;
1488 if (DepType == SDep::Data) {
1489 DepReg = SUJ->Succs[i].getReg();
1490 RC = HRI->getMinimalPhysRegClass(DepReg);
1491 }
1492
1493 if (I.isCall() || HII->isJumpR(I) || I.isReturn() || HII->isTailCall(I)) {
1494 if (!isRegDependence(DepType))
1495 continue;
1496 if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg()))
1497 continue;
1498 }
1499
1500 if (DepType == SDep::Data) {
1501 if (canPromoteToDotCur(J, SUJ, DepReg, II, RC))
1502 if (promoteToDotCur(J, DepType, II, RC))
1503 continue;
1504 }
1505
1506 // Data dependence ok if we have load.cur.
1507 if (DepType == SDep::Data && HII->isDotCurInst(J)) {
1508 if (HII->isHVXVec(I))
1509 continue;
1510 }
1511
1512 // For instructions that can be promoted to dot-new, try to promote.
1513 if (DepType == SDep::Data) {
1514 if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) {
1515 if (promoteToDotNew(I, DepType, II, RC)) {
1516 PromotedToDotNew = true;
1517 if (cannotCoexist(I, J))
1518 FoundSequentialDependence = true;
1519 continue;
1520 }
1521 }
1522 if (HII->isNewValueJump(I))
1523 continue;
1524 }
1525
1526 // For predicated instructions, if the predicates are complements then
1527 // there can be no dependence.
1528 if (HII->isPredicated(I) && HII->isPredicated(J) &&
1530 // Not always safe to do this translation.
1531 // DAG Builder attempts to reduce dependence edges using transitive
1532 // nature of dependencies. Here is an example:
1533 //
1534 // r0 = tfr_pt ... (1)
1535 // r0 = tfr_pf ... (2)
1536 // r0 = tfr_pt ... (3)
1537 //
1538 // There will be an output dependence between (1)->(2) and (2)->(3).
1539 // However, there is no dependence edge between (1)->(3). This results
1540 // in all 3 instructions going in the same packet. We ignore dependce
1541 // only once to avoid this situation.
1542 auto Itr = find(IgnoreDepMIs, &J);
1543 if (Itr != IgnoreDepMIs.end()) {
1544 Dependence = true;
1545 return false;
1546 }
1547 IgnoreDepMIs.push_back(&I);
1548 continue;
1549 }
1550
1551 // Ignore Order dependences between unconditional direct branches
1552 // and non-control-flow instructions.
1553 if (isDirectJump(I) && !J.isBranch() && !J.isCall() &&
1554 DepType == SDep::Order)
1555 continue;
1556
1557 // Ignore all dependences for jumps except for true and output
1558 // dependences.
1559 if (I.isConditionalBranch() && DepType != SDep::Data &&
1560 DepType != SDep::Output)
1561 continue;
1562
1563 if (DepType == SDep::Output) {
1564 FoundSequentialDependence = true;
1565 break;
1566 }
1567
1568 // For Order dependences:
1569 // 1. Volatile loads/stores can be packetized together, unless other
1570 // rules prevent is.
1571 // 2. Store followed by a load is not allowed.
1572 // 3. Store followed by a store is valid.
1573 // 4. Load followed by any memory operation is allowed.
1574 if (DepType == SDep::Order) {
1575 if (!PacketizeVolatiles) {
1576 bool OrdRefs = I.hasOrderedMemoryRef() || J.hasOrderedMemoryRef();
1577 if (OrdRefs) {
1578 FoundSequentialDependence = true;
1579 break;
1580 }
1581 }
1582 // J is first, I is second.
1583 bool LoadJ = J.mayLoad(), StoreJ = J.mayStore();
1584 bool LoadI = I.mayLoad(), StoreI = I.mayStore();
1585
1586 // BankConflictMutation adds an artificial edge between loads that
1587 // likely map to the same bank. Other passes add artificial edges too,
1588 // so re-check the condition before keeping the loads apart.
1589 if (SUJ->Succs[i].isArtificial() &&
1591 FoundSequentialDependence = true;
1592 break;
1593 }
1594
1595 bool NVStoreJ = HII->isNewValueStore(J);
1596 bool NVStoreI = HII->isNewValueStore(I);
1597 bool IsVecJ = HII->isHVXVec(J) || HII->isHLXVec(J);
1598 bool IsVecI = HII->isHVXVec(I) || HII->isHLXVec(I);
1599
1600 // Don't reorder the loads if there is an order dependence. This would
1601 // occur if the first instruction must go in slot0.
1602 if (LoadJ && LoadI && HII->isPureSlot0(J)) {
1603 FoundSequentialDependence = true;
1604 break;
1605 }
1606
1607 if (Slot1Store && MF.getSubtarget<HexagonSubtarget>().hasV65Ops() &&
1608 ((LoadJ && StoreI && !NVStoreI) ||
1609 (StoreJ && LoadI && !NVStoreJ)) &&
1610 (J.getOpcode() != Hexagon::S2_allocframe &&
1611 I.getOpcode() != Hexagon::S2_allocframe) &&
1612 (J.getOpcode() != Hexagon::L2_deallocframe &&
1613 I.getOpcode() != Hexagon::L2_deallocframe) &&
1614 (!HII->isMemOp(J) && !HII->isMemOp(I)) && (!IsVecJ && !IsVecI))
1615 setmemShufDisabled(true);
1616 else
1617 if (StoreJ && LoadI && alias(J, I)) {
1618 FoundSequentialDependence = true;
1619 break;
1620 }
1621
1622 if (!StoreJ)
1623 if (!LoadJ || (!LoadI && !StoreI)) {
1624 // If J is neither load nor store, assume a dependency.
1625 // If J is a load, but I is neither, also assume a dependency.
1626 FoundSequentialDependence = true;
1627 break;
1628 }
1629 // Store followed by store: not OK on V2.
1630 // Store followed by load: not OK on all.
1631 // Load followed by store: OK on all.
1632 // Load followed by load: OK on all.
1633 continue;
1634 }
1635
1636 // Special case for ALLOCFRAME: even though there is dependency
1637 // between ALLOCFRAME and subsequent store, allow it to be packetized
1638 // in a same packet. This implies that the store is using the caller's
1639 // SP. Hence, offset needs to be updated accordingly.
1640 if (DepType == SDep::Data && J.getOpcode() == Hexagon::S2_allocframe) {
1641 unsigned Opc = I.getOpcode();
1642 switch (Opc) {
1643 case Hexagon::S2_storerd_io:
1644 case Hexagon::S2_storeri_io:
1645 case Hexagon::S2_storerh_io:
1646 case Hexagon::S2_storerb_io:
1647 if (I.getOperand(0).getReg() == HRI->getStackRegister()) {
1648 // Since this store is to be glued with allocframe in the same
1649 // packet, it will use SP of the previous stack frame, i.e.
1650 // caller's SP. Therefore, we need to recalculate offset
1651 // according to this change.
1652 GlueAllocframeStore = useCallersSP(I);
1653 if (GlueAllocframeStore)
1654 continue;
1655 }
1656 break;
1657 default:
1658 break;
1659 }
1660 }
1661
1662 // There are certain anti-dependencies that cannot be ignored.
1663 // Specifically:
1664 // J2_call ... implicit-def %r0 ; SUJ
1665 // R0 = ... ; SUI
1666 // Those cannot be packetized together, since the call will observe
1667 // the effect of the assignment to R0.
1668 if ((DepType == SDep::Anti || DepType == SDep::Output) && J.isCall()) {
1669 // Check if I defines any volatile register. We should also check
1670 // registers that the call may read, but these happen to be a
1671 // subset of the volatile register set.
1672 for (const MachineOperand &Op : I.operands()) {
1673 if (Op.isReg() && Op.isDef()) {
1674 Register R = Op.getReg();
1675 if (!J.readsRegister(R, HRI) && !J.modifiesRegister(R, HRI))
1676 continue;
1677 } else if (!Op.isRegMask()) {
1678 // If I has a regmask assume dependency.
1679 continue;
1680 }
1681 FoundSequentialDependence = true;
1682 break;
1683 }
1684 }
1685
1686 // Skip over remaining anti-dependences. Two instructions that are
1687 // anti-dependent can share a packet, since in most such cases all
1688 // operands are read before any modifications take place.
1689 // The exceptions are branch and call instructions, since they are
1690 // executed after all other instructions have completed (at least
1691 // conceptually).
1692 // Another exception is the HLX load pseudo, which expands to a temporary
1693 // load and a copy of the loaded value. An instruction it is anti-dependent
1694 // on would read the new value if both were in the same packet.
1695 if (DepType != SDep::Anti || I.getOpcode() == Hexagon::LX_L16b_pseudo) {
1696 FoundSequentialDependence = true;
1697 break;
1698 }
1699 }
1700
1701 if (FoundSequentialDependence) {
1702 Dependence = true;
1703 return false;
1704 }
1705
1706 return true;
1707}
1708
1710 assert(SUI->getInstr() && SUJ->getInstr());
1711 MachineInstr &I = *SUI->getInstr();
1712 MachineInstr &J = *SUJ->getInstr();
1713
1714 bool Coexist = !cannotCoexist(I, J);
1715
1716 if (Coexist && !Dependence)
1717 return true;
1718
1719 // Check if the instruction was promoted to a dot-new. If so, demote it
1720 // back into a dot-old.
1721 if (PromotedToDotNew)
1723
1724 cleanUpDotCur();
1725 // Check if the instruction (must be a store) was glued with an allocframe
1726 // instruction. If so, restore its offset to its original value, i.e. use
1727 // current SP instead of caller's SP.
1728 if (GlueAllocframeStore) {
1729 useCalleesSP(I);
1730 GlueAllocframeStore = false;
1731 }
1732
1733 if (ChangedOffset != INT64_MAX)
1735
1736 if (GlueToNewValueJump) {
1737 // Putting I and J together would prevent the new-value jump from being
1738 // packetized with the producer. In that case I and J must be separated.
1739 GlueToNewValueJump = false;
1740 return false;
1741 }
1742
1743 if (!Coexist)
1744 return false;
1745
1746 if (ChangedOffset == INT64_MAX && updateOffset(SUI, SUJ)) {
1747 FoundSequentialDependence = false;
1748 Dependence = false;
1749 return true;
1750 }
1751
1752 return false;
1753}
1754
1755
1757 bool FoundLoad = false;
1758 bool FoundStore = false;
1759
1760 for (auto *MJ : CurrentPacketMIs) {
1761 unsigned Opc = MJ->getOpcode();
1762 if (Opc == Hexagon::S2_allocframe || Opc == Hexagon::L2_deallocframe)
1763 continue;
1764 if (HII->isMemOp(*MJ))
1765 continue;
1766 if (MJ->mayLoad())
1767 FoundLoad = true;
1768 if (MJ->mayStore() && !HII->isNewValueStore(*MJ))
1769 FoundStore = true;
1770 }
1771 return FoundLoad && FoundStore;
1772}
1773
1774
1777 MachineBasicBlock::iterator MII = MI.getIterator();
1778 MachineBasicBlock *MBB = MI.getParent();
1779
1780 if (CurrentPacketMIs.empty()) {
1781 PacketStalls = false;
1782 PacketStallCycles = 0;
1783 }
1784 PacketStalls |= producesStall(MI);
1785 PacketStallCycles = std::max(PacketStallCycles, calcStall(MI));
1786
1787 if (MI.isImplicitDef() || MI.getOpcode() == TargetOpcode::FREEZE) {
1788 // Add to the packet to allow subsequent instructions to be checked
1789 // properly.
1790 CurrentPacketMIs.push_back(&MI);
1791 return MII;
1792 }
1793 assert(ResourceTracker->canReserveResources(MI));
1794
1795 MachineBasicBlock::iterator nextMII = MII;
1796 if (std::next(MII) != MI.getParent()->end()) {
1797 MachineInstr &nextMI = *++nextMII;
1798 if (HII->isActivateWeightPair(MI, nextMI)) {
1799 for (auto J : CurrentPacketMIs) {
1800 MachineInstr &JMI = *J;
1801 if (HII->isDependent(JMI, MI) || HII->isDependent(JMI, nextMI)) {
1802 endPacket(MBB, MI);
1803 break;
1804 }
1805 }
1806 ResourceTracker->reserveResources(MI);
1807 if (ResourceTracker->canReserveResources(nextMI))
1808 ResourceTracker->reserveResources(nextMI);
1809 else {
1810 endPacket(MBB, MI);
1811 assert(ResourceTracker->canReserveResources(MI));
1812 ResourceTracker->reserveResources(MI);
1813 assert(ResourceTracker->canReserveResources(nextMI));
1814 ResourceTracker->reserveResources(nextMI);
1815 }
1816 CurrentPacketMIs.push_back(&MI);
1817 CurrentPacketMIs.push_back(&nextMI);
1818 return nextMII;
1819 }
1820 }
1821
1822 bool ExtMI = HII->isExtended(MI) || HII->isConstExtended(MI);
1823 bool Good = true;
1824
1825 if (GlueToNewValueJump) {
1826 MachineInstr &NvjMI = *++MII;
1827 // We need to put both instructions in the same packet: MI and NvjMI.
1828 // Either of them can require a constant extender. Try to add both to
1829 // the current packet, and if that fails, end the packet and start a
1830 // new one.
1831 ResourceTracker->reserveResources(MI);
1832 if (ExtMI)
1834
1835 bool ExtNvjMI = HII->isExtended(NvjMI) || HII->isConstExtended(NvjMI);
1836 if (Good) {
1837 if (ResourceTracker->canReserveResources(NvjMI))
1838 ResourceTracker->reserveResources(NvjMI);
1839 else
1840 Good = false;
1841 }
1842 if (Good && ExtNvjMI)
1844
1845 if (!Good) {
1846 endPacket(MBB, MI);
1847 assert(ResourceTracker->canReserveResources(MI));
1848 ResourceTracker->reserveResources(MI);
1849 if (ExtMI) {
1852 }
1853 assert(ResourceTracker->canReserveResources(NvjMI));
1854 ResourceTracker->reserveResources(NvjMI);
1855 if (ExtNvjMI) {
1858 }
1859 }
1860 CurrentPacketMIs.push_back(&MI);
1861 CurrentPacketMIs.push_back(&NvjMI);
1862 return MII;
1863 }
1864
1865 ResourceTracker->reserveResources(MI);
1866 if (ExtMI && !tryAllocateResourcesForConstExt(true)) {
1867 endPacket(MBB, MI);
1868 if (PromotedToDotNew)
1870 if (GlueAllocframeStore) {
1872 GlueAllocframeStore = false;
1873 }
1874 ResourceTracker->reserveResources(MI);
1876 }
1877
1878 CurrentPacketMIs.push_back(&MI);
1879 return MII;
1880}
1881
1884 // Replace VLIWPacketizerList::endPacket(MBB, EndMI).
1885 LLVM_DEBUG({
1886 if (!CurrentPacketMIs.empty()) {
1887 dbgs() << "Finalizing packet:\n";
1888 unsigned Idx = 0;
1890 unsigned R = ResourceTracker->getUsedResources(Idx++);
1891 dbgs() << " * [res:0x" << utohexstr(R) << "] " << *MI;
1892 }
1893 }
1894 });
1895
1896 bool memShufDisabled = getmemShufDisabled();
1897 if (memShufDisabled && !foundLSInPacket()) {
1898 setmemShufDisabled(false);
1899 LLVM_DEBUG(dbgs() << " Not added to NoShufPacket\n");
1900 }
1901 memShufDisabled = getmemShufDisabled();
1902
1903 OldPacketMIs.clear();
1905 MachineBasicBlock::instr_iterator NextMI = std::next(MI->getIterator());
1906 for (auto &I : make_range(HII->expandVGatherPseudo(*MI), NextMI))
1907 OldPacketMIs.push_back(&I);
1908 }
1909 CurrentPacketMIs.clear();
1910
1911 if (OldPacketMIs.size() > 1) {
1912 MachineBasicBlock::instr_iterator FirstMI(OldPacketMIs.front());
1914 finalizeBundle(*MBB, FirstMI, LastMI);
1915 auto BundleMII = std::prev(FirstMI);
1916 if (memShufDisabled)
1917 HII->setBundleNoShuf(BundleMII);
1918
1919 setmemShufDisabled(false);
1920 }
1921
1922 PacketHasDuplex = false;
1923 PacketHasSLOT0OnlyInsn = false;
1924 ResourceTracker->clearResources();
1925 LLVM_DEBUG(dbgs() << "End packet\n");
1926}
1927
1929 if (Minimal)
1930 return false;
1931
1932 if (producesStall(MI))
1933 return false;
1934
1935 // If TinyCore with Duplexes is enabled, check if this MI can form a Duplex
1936 // with any other instruction in the existing packet.
1937 auto &HST = MI.getParent()->getParent()->getSubtarget<HexagonSubtarget>();
1938 // Constraint 1: Only one duplex allowed per packet.
1939 // Constraint 2: Consider duplex checks only if there is at least one
1940 // instruction in a packet.
1941 // Constraint 3: If one of the existing instructions in the packet has a
1942 // SLOT0 only instruction that can not be duplexed, do not attempt to form
1943 // duplexes. (TODO: This will invalidate the L4_return* instructions to form a
1944 // duplex)
1945 if (HST.isTinyCoreWithDuplex() && CurrentPacketMIs.size() > 0 &&
1946 !PacketHasDuplex) {
1947 // Check for SLOT0 only non-duplexable instruction in packet.
1948 for (auto &MJ : CurrentPacketMIs)
1949 PacketHasSLOT0OnlyInsn |= HII->isPureSlot0(*MJ);
1950 // Get the Big Core Opcode (dup_*).
1951 int Opcode = HII->getDuplexOpcode(MI, false);
1952 if (Opcode >= 0) {
1953 // We now have an instruction that can be duplexed.
1954 for (auto &MJ : CurrentPacketMIs) {
1955 if (HII->isDuplexPair(MI, *MJ) && !PacketHasSLOT0OnlyInsn) {
1956 PacketHasDuplex = true;
1957 return true;
1958 }
1959 }
1960 // If it can not be duplexed, check if there is a valid transition in DFA
1961 // with the original opcode.
1962 MachineInstr &MIRef = const_cast<MachineInstr &>(MI);
1963 MIRef.setDesc(HII->get(Opcode));
1964 return ResourceTracker->canReserveResources(MIRef);
1965 }
1966 }
1967
1968 // An HLX load/store pseudo expands to two instructions in its packet. With
1969 // one more instruction in the packet, there is no room left for a
1970 // constant-extended instruction and its extender within the four-word
1971 // packet limit.
1972 if (HST.useHLXOps() && CurrentPacketMIs.size() > 1) {
1973 auto IsHLXLdStPseudo = [this](const MachineInstr &I) {
1974 return HII->isTmpLoadPseudo(I) || HII->isNewStorePseudo(I);
1975 };
1976 bool HasConstExt = HII->isConstExtended(MI);
1977 bool HasPseudo = IsHLXLdStPseudo(MI);
1978 for (const MachineInstr *MJ : CurrentPacketMIs) {
1979 HasConstExt |= HII->isConstExtended(*MJ);
1980 HasPseudo |= IsHLXLdStPseudo(*MJ);
1981 }
1982 if (HasConstExt && HasPseudo)
1983 return false;
1984 }
1985
1986 return true;
1987}
1988
1989// V60 forward scheduling.
1991 // Check whether the previous packet is in a different loop. If this is the
1992 // case, there is little point in trying to avoid a stall because that would
1993 // favor the rare case (loop entry) over the common case (loop iteration).
1994 //
1995 // TODO: We should really be able to check all the incoming edges if this is
1996 // the first packet in a basic block, so we can avoid stalls from the loop
1997 // backedge.
1998 if (!OldPacketMIs.empty()) {
1999 auto *OldBB = OldPacketMIs.front()->getParent();
2000 auto *ThisBB = I.getParent();
2001 if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB))
2002 return 0;
2003 }
2004
2005 SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)];
2006 if (!SUI)
2007 return 0;
2008
2009 // If the latency is 0 and there is a data dependence between this
2010 // instruction and any instruction in the current packet, we disregard any
2011 // potential stalls due to the instructions in the previous packet. Most of
2012 // the instruction pairs that can go together in the same packet have 0
2013 // latency between them. The exceptions are
2014 // 1. NewValueJumps as they're generated much later and the latencies can't
2015 // be changed at that point.
2016 // 2. .cur instructions, if its consumer has a 0 latency successor (such as
2017 // .new). In this case, the latency between .cur and the consumer stays
2018 // non-zero even though we can have both .cur and .new in the same packet.
2019 // Changing the latency to 0 is not an option as it causes software pipeliner
2020 // to not pipeline in some cases.
2021
2022 // For Example:
2023 // {
2024 // I1: v6.cur = vmem(r0++#1)
2025 // I2: v7 = valign(v6,v4,r2)
2026 // I3: vmem(r5++#1) = v7.new
2027 // }
2028 // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2.
2029
2030 for (auto *J : CurrentPacketMIs) {
2031 SUnit *SUJ = MIToSUnit[J];
2032 for (auto &Pred : SUI->Preds)
2033 if (Pred.getSUnit() == SUJ)
2034 if ((Pred.getLatency() == 0 && Pred.isAssignedRegDep()) ||
2035 HII->isNewValueJump(I) || HII->isToBeScheduledASAP(*J, I))
2036 return 0;
2037 }
2038
2039 // Check if the latency is greater than one between this instruction and any
2040 // instruction in the previous packet.
2041 for (auto *J : OldPacketMIs) {
2042 SUnit *SUJ = MIToSUnit[J];
2043 for (auto &Pred : SUI->Preds)
2044 if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
2045 return Pred.getLatency();
2046 }
2047
2048 return 0;
2049}
2050
2052 unsigned int Latency = calcStall(I);
2053 if (Latency == 0)
2054 return false;
2055 // Ignore stall unless it stalls more than previous instruction in packet
2056 if (PacketStalls)
2057 return Latency > PacketStallCycles;
2058 return true;
2059}
2060
2061//===----------------------------------------------------------------------===//
2062// Public Constructor Functions
2063//===----------------------------------------------------------------------===//
2064
2066 return new HexagonPacketizer(Minimal);
2067}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
cl::opt< bool > OneComplexPerPacket
cl::opt< bool > OneFloatPerPacket
cl::opt< bool > ScheduleInlineAsm("hexagon-sched-inline-asm", cl::Hidden, cl::init(false), cl::desc("Do not consider inline-asm a scheduling/" "packetization boundary."))
#define HEXAGON_LRFP_SIZE
cl::opt< bool > DisablePacketizer
static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ, const HexagonInstrInfo &HII)
static bool isDirectJump(const MachineInstr &MI)
static MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI, MachineBasicBlock::iterator BundleIt, bool Before)
static bool isRegDependence(const SDep::Kind DepType)
cl::opt< bool > OneComplexPerPacket("single-complex-packet", cl::Hidden, cl::desc("Allow only one complex instruction in a packet"))
static const MachineOperand & getStoreValueOperand(const MachineInstr &MI)
static cl::opt< bool > EnableGenAllInsnClass("enable-gen-insn", cl::Hidden, cl::desc("Generate all instruction with TC"))
static bool isControlFlow(const MachineInstr &MI)
static cl::opt< bool > DisableVecDblNVStores("disable-vecdbl-nv-stores", cl::Hidden, cl::desc("Disable vector double new-value-stores"))
static PredicateKind getPredicateSense(const MachineInstr &MI, const HexagonInstrInfo *HII)
Returns true if an instruction is predicated on p0 and false if it's predicated on !...
static unsigned getPredicatedRegister(MachineInstr &MI, const HexagonInstrInfo *QII)
Gets the predicate register of a predicated instruction.
cl::opt< bool > DisablePacketizer("disable-packetizer", cl::Hidden, cl::desc("Disable Hexagon packetizer pass"))
static cl::opt< bool > Slot1Store("slot1-store-slot0-load", cl::Hidden, cl::init(true), cl::desc("Allow slot1 store and slot0 load"))
static cl::opt< bool > PacketizeVolatiles("hexagon-packetize-volatiles", cl::Hidden, cl::init(true), cl::desc("Allow non-solo packetization of volatile memory references"))
static bool hasWriteToReadDep(const MachineInstr &FirstI, const MachineInstr &SecondI, const TargetRegisterInfo *TRI)
static bool doesModifyCalleeSavedReg(const MachineInstr &MI, const TargetRegisterInfo *TRI)
Returns true if the instruction modifies a callee-saved register.
static bool isLoadAbsSet(const MachineInstr &MI)
static const MachineOperand & getAbsSetOperand(const MachineInstr &MI)
static const MachineOperand & getPostIncrementOperand(const MachineInstr &MI, const HexagonInstrInfo *HII)
cl::opt< bool > OneFloatPerPacket("single-float-packet", cl::Hidden, cl::desc("Allow only one single floating point instruction in a packet"))
static bool isImplicitDependency(const MachineInstr &I, bool CheckDef, unsigned DepReg)
static bool isSchedBarrier(const MachineInstr &MI)
static bool isSystemInstr(const MachineInstr &MI)
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Packetizer
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
A debug info location.
Definition DebugLoc.h:127
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool isHLXVec(const MachineInstr &MI) const
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool isHVXMemWithAIndirect(const MachineInstr &I, const MachineInstr &J) const
bool isRestrictNoSlot1Store(const MachineInstr &MI) const
bool isPureSlot0(const MachineInstr &MI) const
const HexagonRegisterInfo & getRegisterInfo() const
bool isComplex(const MachineInstr &MI) const
bool isPostIncrement(const MachineInstr &MI) const override
Return true for post-incremented instructions.
bool isFloat(const MachineInstr &MI) const
uint64_t getType(const MachineInstr &MI) const
bool isPredicatedTrue(const MachineInstr &MI) const
bool isNewValueStore(const MachineInstr &MI) const
bool arePredicatesComplements(MachineInstr &MI1, MachineInstr &MI2)
bool updateOffset(SUnit *SUI, SUnit *SUJ)
Return true if we can update the offset in MI so that MI and MJ can be packetized together.
void endPacket(MachineBasicBlock *MBB, MachineBasicBlock::iterator MI) override
HexagonPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA, const MachineBranchProbabilityInfo *MBPI, bool Minimal)
bool isCallDependent(const MachineInstr &MI, SDep::Kind DepType, unsigned DepReg)
bool promoteToDotCur(MachineInstr &MI, SDep::Kind DepType, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool promoteToDotNew(MachineInstr &MI, SDep::Kind DepType, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override
bool canPromoteToDotCur(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool demoteToDotOld(MachineInstr &MI)
bool cannotCoexist(const MachineInstr &MI, const MachineInstr &MJ)
bool isSoloInstruction(const MachineInstr &MI) override
bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override
bool hasControlDependence(const MachineInstr &I, const MachineInstr &J)
bool restrictingDepExistInPacket(MachineInstr &, unsigned)
bool producesStall(const MachineInstr &MI)
void undoChangedOffset(MachineInstr &MI)
Undo the changed offset.
bool hasDualStoreDependence(const MachineInstr &I, const MachineInstr &J)
unsigned int calcStall(const MachineInstr &MI)
bool canPromoteToDotNew(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, const TargetRegisterClass *RC)
bool canPromoteToNewValue(const MachineInstr &MI, const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII)
bool ignorePseudoInstruction(const MachineInstr &MI, const MachineBasicBlock *MBB) override
void unpacketizeSoloInstrs(MachineFunction &MF)
const MachineBranchProbabilityInfo * MBPI
A handle to the branch probability pass.
bool shouldAddToPacket(const MachineInstr &MI) override
bool canPromoteToNewValueStore(const MachineInstr &MI, const MachineInstr &PacketMI, unsigned DepReg)
bool tryAllocateResourcesForConstExt(bool Reserve)
MachineBasicBlock::iterator addToPacket(MachineInstr &MI) override
bool hasDeadDependence(const MachineInstr &I, const MachineInstr &J)
bool isNewifiable(const MachineInstr &MI, const TargetRegisterClass *NewRC)
bool hasRegMaskDependence(const MachineInstr &I, const MachineInstr &J)
const HexagonInstrInfo * getInstrInfo() const override
const HexagonRegisterInfo * getRegisterInfo() const override
static bool mayHaveBankConflict(const MachineInstr &MI0, const MachineInstr &MI1, const HexagonInstrInfo &HII, bool IgnoreSameLine=true)
Describe properties that are true of each instruction in the target description file.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
Instructions::iterator instr_iterator
Instructions::const_iterator const_instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isImplicitDef() const
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool isInlineAsm() const
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register.
LLVM_ABI void unbundleFromPred()
Break bundle above this instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Kind
These are the different kinds of scheduling dependencies.
Definition ScheduleDAG.h:57
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:60
@ Order
Any other ordering dependency.
Definition ScheduleDAG.h:61
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
Scheduling unit. This is a node in the scheduling DAG.
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
SmallVector< SDep, 4 > Succs
All sunit successors.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
VLIWPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI, AAResults *AA)
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
bool alias(const MachineInstr &MI1, const MachineInstr &MI2, bool UseTBAA=true) const
std::vector< MachineInstr * > CurrentPacketMIs
std::map< MachineInstr *, SUnit * > MIToSUnit
DFAPacketizer * ResourceTracker
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool getTSFlag(const MCInstrDesc &MID, HexagonTSFlagsVal Pos)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void finalizeBundle(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
finalizeBundle - Finalize a machine instruction bundle which includes a sequence of instructions star...
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
FunctionPass * createHexagonPacketizer(bool Minimal)
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
DWARFExpression::Operation Op
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58