]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/Hexagon/HexagonVLIWPacketizer.cpp
MFV r323794: 8605 zfs channel programs: zfs.exists undocumented and non-working
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / Hexagon / HexagonVLIWPacketizer.cpp
1 //===----- HexagonPacketizer.cpp - vliw packetizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a simple VLIW packetizer using DFA. The packetizer works on
11 // machine basic blocks. For each instruction I in BB, the packetizer consults
12 // the DFA to see if machine resources are available to execute I. If so, the
13 // packetizer checks if I depends on any instruction J in the current packet.
14 // If no dependency is found, I is added to current packet and machine resource
15 // is marked as taken. If any dependency is found, a target API call is made to
16 // prune the dependence.
17 //
18 //===----------------------------------------------------------------------===//
19 #include "HexagonVLIWPacketizer.h"
20 #include "HexagonRegisterInfo.h"
21 #include "HexagonSubtarget.h"
22 #include "HexagonTargetMachine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31
32 using namespace llvm;
33
34 #define DEBUG_TYPE "packets"
35
36 static cl::opt<bool> DisablePacketizer("disable-packetizer", cl::Hidden,
37   cl::ZeroOrMore, cl::init(false),
38   cl::desc("Disable Hexagon packetizer pass"));
39
40 static cl::opt<bool> PacketizeVolatiles("hexagon-packetize-volatiles",
41   cl::ZeroOrMore, cl::Hidden, cl::init(true),
42   cl::desc("Allow non-solo packetization of volatile memory references"));
43
44 static cl::opt<bool> EnableGenAllInsnClass("enable-gen-insn", cl::init(false),
45   cl::Hidden, cl::ZeroOrMore, cl::desc("Generate all instruction with TC"));
46
47 static cl::opt<bool> DisableVecDblNVStores("disable-vecdbl-nv-stores",
48   cl::init(false), cl::Hidden, cl::ZeroOrMore,
49   cl::desc("Disable vector double new-value-stores"));
50
51 extern cl::opt<bool> ScheduleInlineAsm;
52
53 namespace llvm {
54   FunctionPass *createHexagonPacketizer();
55   void initializeHexagonPacketizerPass(PassRegistry&);
56 }
57
58
59 namespace {
60   class HexagonPacketizer : public MachineFunctionPass {
61   public:
62     static char ID;
63     HexagonPacketizer() : MachineFunctionPass(ID) {}
64
65     void getAnalysisUsage(AnalysisUsage &AU) const override {
66       AU.setPreservesCFG();
67       AU.addRequired<AAResultsWrapperPass>();
68       AU.addRequired<MachineBranchProbabilityInfo>();
69       AU.addRequired<MachineDominatorTree>();
70       AU.addRequired<MachineLoopInfo>();
71       AU.addPreserved<MachineDominatorTree>();
72       AU.addPreserved<MachineLoopInfo>();
73       MachineFunctionPass::getAnalysisUsage(AU);
74     }
75     StringRef getPassName() const override { return "Hexagon Packetizer"; }
76     bool runOnMachineFunction(MachineFunction &Fn) override;
77     MachineFunctionProperties getRequiredProperties() const override {
78       return MachineFunctionProperties().set(
79           MachineFunctionProperties::Property::NoVRegs);
80     }
81
82   private:
83     const HexagonInstrInfo *HII;
84     const HexagonRegisterInfo *HRI;
85   };
86
87   char HexagonPacketizer::ID = 0;
88 }
89
90 INITIALIZE_PASS_BEGIN(HexagonPacketizer, "hexagon-packetizer",
91                       "Hexagon Packetizer", false, false)
92 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
93 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
94 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
95 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
96 INITIALIZE_PASS_END(HexagonPacketizer, "hexagon-packetizer",
97                     "Hexagon Packetizer", false, false)
98
99 HexagonPacketizerList::HexagonPacketizerList(MachineFunction &MF,
100       MachineLoopInfo &MLI, AliasAnalysis *AA,
101       const MachineBranchProbabilityInfo *MBPI)
102     : VLIWPacketizerList(MF, MLI, AA), MBPI(MBPI), MLI(&MLI) {
103   HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
104   HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
105
106   addMutation(make_unique<HexagonSubtarget::HexagonDAGMutation>());
107 }
108
109 // Check if FirstI modifies a register that SecondI reads.
110 static bool hasWriteToReadDep(const MachineInstr &FirstI,
111                               const MachineInstr &SecondI,
112                               const TargetRegisterInfo *TRI) {
113   for (auto &MO : FirstI.operands()) {
114     if (!MO.isReg() || !MO.isDef())
115       continue;
116     unsigned R = MO.getReg();
117     if (SecondI.readsRegister(R, TRI))
118       return true;
119   }
120   return false;
121 }
122
123
124 static MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI,
125       MachineBasicBlock::iterator BundleIt, bool Before) {
126   MachineBasicBlock::instr_iterator InsertPt;
127   if (Before)
128     InsertPt = BundleIt.getInstrIterator();
129   else
130     InsertPt = std::next(BundleIt).getInstrIterator();
131
132   MachineBasicBlock &B = *MI.getParent();
133   // The instruction should at least be bundled with the preceding instruction
134   // (there will always be one, i.e. BUNDLE, if nothing else).
135   assert(MI.isBundledWithPred());
136   if (MI.isBundledWithSucc()) {
137     MI.clearFlag(MachineInstr::BundledSucc);
138     MI.clearFlag(MachineInstr::BundledPred);
139   } else {
140     // If it's not bundled with the successor (i.e. it is the last one
141     // in the bundle), then we can simply unbundle it from the predecessor,
142     // which will take care of updating the predecessor's flag.
143     MI.unbundleFromPred();
144   }
145   B.splice(InsertPt, &B, MI.getIterator());
146
147   // Get the size of the bundle without asserting.
148   MachineBasicBlock::const_instr_iterator I = BundleIt.getInstrIterator();
149   MachineBasicBlock::const_instr_iterator E = B.instr_end();
150   unsigned Size = 0;
151   for (++I; I != E && I->isBundledWithPred(); ++I)
152     ++Size;
153
154   // If there are still two or more instructions, then there is nothing
155   // else to be done.
156   if (Size > 1)
157     return BundleIt;
158
159   // Otherwise, extract the single instruction out and delete the bundle.
160   MachineBasicBlock::iterator NextIt = std::next(BundleIt);
161   MachineInstr &SingleI = *BundleIt->getNextNode();
162   SingleI.unbundleFromPred();
163   assert(!SingleI.isBundledWithSucc());
164   BundleIt->eraseFromParent();
165   return NextIt;
166 }
167
168
169 bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) {
170   if (DisablePacketizer || skipFunction(*MF.getFunction()))
171     return false;
172
173   HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
174   HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
175   auto &MLI = getAnalysis<MachineLoopInfo>();
176   auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
177   auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
178
179   if (EnableGenAllInsnClass)
180     HII->genAllInsnTimingClasses(MF);
181
182   // Instantiate the packetizer.
183   HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI);
184
185   // DFA state table should not be empty.
186   assert(Packetizer.getResourceTracker() && "Empty DFA table!");
187
188   //
189   // Loop over all basic blocks and remove KILL pseudo-instructions
190   // These instructions confuse the dependence analysis. Consider:
191   // D0 = ...   (Insn 0)
192   // R0 = KILL R0, D0 (Insn 1)
193   // R0 = ... (Insn 2)
194   // Here, Insn 1 will result in the dependence graph not emitting an output
195   // dependence between Insn 0 and Insn 2. This can lead to incorrect
196   // packetization
197   //
198   for (auto &MB : MF) {
199     auto End = MB.end();
200     auto MI = MB.begin();
201     while (MI != End) {
202       auto NextI = std::next(MI);
203       if (MI->isKill()) {
204         MB.erase(MI);
205         End = MB.end();
206       }
207       MI = NextI;
208     }
209   }
210
211   // Loop over all of the basic blocks.
212   for (auto &MB : MF) {
213     auto Begin = MB.begin(), End = MB.end();
214     while (Begin != End) {
215       // Find the first non-boundary starting from the end of the last
216       // scheduling region.
217       MachineBasicBlock::iterator RB = Begin;
218       while (RB != End && HII->isSchedulingBoundary(*RB, &MB, MF))
219         ++RB;
220       // Find the first boundary starting from the beginning of the new
221       // region.
222       MachineBasicBlock::iterator RE = RB;
223       while (RE != End && !HII->isSchedulingBoundary(*RE, &MB, MF))
224         ++RE;
225       // Add the scheduling boundary if it's not block end.
226       if (RE != End)
227         ++RE;
228       // If RB == End, then RE == End.
229       if (RB != End)
230         Packetizer.PacketizeMIs(&MB, RB, RE);
231
232       Begin = RE;
233     }
234   }
235
236   Packetizer.unpacketizeSoloInstrs(MF);
237   return true;
238 }
239
240
241 // Reserve resources for a constant extender. Trigger an assertion if the
242 // reservation fails.
243 void HexagonPacketizerList::reserveResourcesForConstExt() {
244   if (!tryAllocateResourcesForConstExt(true))
245     llvm_unreachable("Resources not available");
246 }
247
248 bool HexagonPacketizerList::canReserveResourcesForConstExt() {
249   return tryAllocateResourcesForConstExt(false);
250 }
251
252 // Allocate resources (i.e. 4 bytes) for constant extender. If succeeded,
253 // return true, otherwise, return false.
254 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(bool Reserve) {
255   auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc());
256   bool Avail = ResourceTracker->canReserveResources(*ExtMI);
257   if (Reserve && Avail)
258     ResourceTracker->reserveResources(*ExtMI);
259   MF.DeleteMachineInstr(ExtMI);
260   return Avail;
261 }
262
263
264 bool HexagonPacketizerList::isCallDependent(const MachineInstr &MI,
265       SDep::Kind DepType, unsigned DepReg) {
266   // Check for LR dependence.
267   if (DepReg == HRI->getRARegister())
268     return true;
269
270   if (HII->isDeallocRet(MI))
271     if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister())
272       return true;
273
274   // Call-like instructions can be packetized with preceding instructions
275   // that define registers implicitly used or modified by the call. Explicit
276   // uses are still prohibited, as in the case of indirect calls:
277   //   r0 = ...
278   //   J2_jumpr r0
279   if (DepType == SDep::Data) {
280     for (const MachineOperand MO : MI.operands())
281       if (MO.isReg() && MO.getReg() == DepReg && !MO.isImplicit())
282         return true;
283   }
284
285   return false;
286 }
287
288 static bool isRegDependence(const SDep::Kind DepType) {
289   return DepType == SDep::Data || DepType == SDep::Anti ||
290          DepType == SDep::Output;
291 }
292
293 static bool isDirectJump(const MachineInstr &MI) {
294   return MI.getOpcode() == Hexagon::J2_jump;
295 }
296
297 static bool isSchedBarrier(const MachineInstr &MI) {
298   switch (MI.getOpcode()) {
299   case Hexagon::Y2_barrier:
300     return true;
301   }
302   return false;
303 }
304
305 static bool isControlFlow(const MachineInstr &MI) {
306   return MI.getDesc().isTerminator() || MI.getDesc().isCall();
307 }
308
309
310 /// Returns true if the instruction modifies a callee-saved register.
311 static bool doesModifyCalleeSavedReg(const MachineInstr &MI,
312                                      const TargetRegisterInfo *TRI) {
313   const MachineFunction &MF = *MI.getParent()->getParent();
314   for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
315     if (MI.modifiesRegister(*CSR, TRI))
316       return true;
317   return false;
318 }
319
320 // Returns true if an instruction can be promoted to .new predicate or
321 // new-value store.
322 bool HexagonPacketizerList::isNewifiable(const MachineInstr &MI,
323       const TargetRegisterClass *NewRC) {
324   // Vector stores can be predicated, and can be new-value stores, but
325   // they cannot be predicated on a .new predicate value.
326   if (NewRC == &Hexagon::PredRegsRegClass) {
327     if (HII->isHVXVec(MI) && MI.mayStore())
328       return false;
329     return HII->isPredicated(MI) && HII->getDotNewPredOp(MI, nullptr) > 0;
330   }
331   // If the class is not PredRegs, it could only apply to new-value stores.
332   return HII->mayBeNewStore(MI);
333 }
334
335 // Promote an instructiont to its .cur form.
336 // At this time, we have already made a call to canPromoteToDotCur and made
337 // sure that it can *indeed* be promoted.
338 bool HexagonPacketizerList::promoteToDotCur(MachineInstr &MI,
339       SDep::Kind DepType, MachineBasicBlock::iterator &MII,
340       const TargetRegisterClass* RC) {
341   assert(DepType == SDep::Data);
342   int CurOpcode = HII->getDotCurOp(MI);
343   MI.setDesc(HII->get(CurOpcode));
344   return true;
345 }
346
347 void HexagonPacketizerList::cleanUpDotCur() {
348   MachineInstr *MI = nullptr;
349   for (auto BI : CurrentPacketMIs) {
350     DEBUG(dbgs() << "Cleanup packet has "; BI->dump(););
351     if (HII->isDotCurInst(*BI)) {
352       MI = BI;
353       continue;
354     }
355     if (MI) {
356       for (auto &MO : BI->operands())
357         if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg())
358           return;
359     }
360   }
361   if (!MI)
362     return;
363   // We did not find a use of the CUR, so de-cur it.
364   MI->setDesc(HII->get(HII->getNonDotCurOp(*MI)));
365   DEBUG(dbgs() << "Demoted CUR "; MI->dump(););
366 }
367
368 // Check to see if an instruction can be dot cur.
369 bool HexagonPacketizerList::canPromoteToDotCur(const MachineInstr &MI,
370       const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
371       const TargetRegisterClass *RC) {
372   if (!HII->isHVXVec(MI))
373     return false;
374   if (!HII->isHVXVec(*MII))
375     return false;
376
377   // Already a dot new instruction.
378   if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI))
379     return false;
380
381   if (!HII->mayBeCurLoad(MI))
382     return false;
383
384   // The "cur value" cannot come from inline asm.
385   if (PacketSU->getInstr()->isInlineAsm())
386     return false;
387
388   // Make sure candidate instruction uses cur.
389   DEBUG(dbgs() << "Can we DOT Cur Vector MI\n";
390         MI.dump();
391         dbgs() << "in packet\n";);
392   MachineInstr &MJ = *MII;
393   DEBUG({
394     dbgs() << "Checking CUR against ";
395     MJ.dump();
396   });
397   unsigned DestReg = MI.getOperand(0).getReg();
398   bool FoundMatch = false;
399   for (auto &MO : MJ.operands())
400     if (MO.isReg() && MO.getReg() == DestReg)
401       FoundMatch = true;
402   if (!FoundMatch)
403     return false;
404
405   // Check for existing uses of a vector register within the packet which
406   // would be affected by converting a vector load into .cur formt.
407   for (auto BI : CurrentPacketMIs) {
408     DEBUG(dbgs() << "packet has "; BI->dump(););
409     if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo()))
410       return false;
411   }
412
413   DEBUG(dbgs() << "Can Dot CUR MI\n"; MI.dump(););
414   // We can convert the opcode into a .cur.
415   return true;
416 }
417
418 // Promote an instruction to its .new form. At this time, we have already
419 // made a call to canPromoteToDotNew and made sure that it can *indeed* be
420 // promoted.
421 bool HexagonPacketizerList::promoteToDotNew(MachineInstr &MI,
422       SDep::Kind DepType, MachineBasicBlock::iterator &MII,
423       const TargetRegisterClass* RC) {
424   assert (DepType == SDep::Data);
425   int NewOpcode;
426   if (RC == &Hexagon::PredRegsRegClass)
427     NewOpcode = HII->getDotNewPredOp(MI, MBPI);
428   else
429     NewOpcode = HII->getDotNewOp(MI);
430   MI.setDesc(HII->get(NewOpcode));
431   return true;
432 }
433
434 bool HexagonPacketizerList::demoteToDotOld(MachineInstr &MI) {
435   int NewOpcode = HII->getDotOldOp(MI);
436   MI.setDesc(HII->get(NewOpcode));
437   return true;
438 }
439
440 bool HexagonPacketizerList::useCallersSP(MachineInstr &MI) {
441   unsigned Opc = MI.getOpcode();
442   switch (Opc) {
443     case Hexagon::S2_storerd_io:
444     case Hexagon::S2_storeri_io:
445     case Hexagon::S2_storerh_io:
446     case Hexagon::S2_storerb_io:
447       break;
448     default:
449       llvm_unreachable("Unexpected instruction");
450   }
451   unsigned FrameSize = MF.getFrameInfo().getStackSize();
452   MachineOperand &Off = MI.getOperand(1);
453   int64_t NewOff = Off.getImm() - (FrameSize + HEXAGON_LRFP_SIZE);
454   if (HII->isValidOffset(Opc, NewOff)) {
455     Off.setImm(NewOff);
456     return true;
457   }
458   return false;
459 }
460
461 void HexagonPacketizerList::useCalleesSP(MachineInstr &MI) {
462   unsigned Opc = MI.getOpcode();
463   switch (Opc) {
464     case Hexagon::S2_storerd_io:
465     case Hexagon::S2_storeri_io:
466     case Hexagon::S2_storerh_io:
467     case Hexagon::S2_storerb_io:
468       break;
469     default:
470       llvm_unreachable("Unexpected instruction");
471   }
472   unsigned FrameSize = MF.getFrameInfo().getStackSize();
473   MachineOperand &Off = MI.getOperand(1);
474   Off.setImm(Off.getImm() + FrameSize + HEXAGON_LRFP_SIZE);
475 }
476
477 enum PredicateKind {
478   PK_False,
479   PK_True,
480   PK_Unknown
481 };
482
483 /// Returns true if an instruction is predicated on p0 and false if it's
484 /// predicated on !p0.
485 static PredicateKind getPredicateSense(const MachineInstr &MI,
486                                        const HexagonInstrInfo *HII) {
487   if (!HII->isPredicated(MI))
488     return PK_Unknown;
489   if (HII->isPredicatedTrue(MI))
490     return PK_True;
491   return PK_False;
492 }
493
494 static const MachineOperand &getPostIncrementOperand(const MachineInstr &MI,
495       const HexagonInstrInfo *HII) {
496   assert(HII->isPostIncrement(MI) && "Not a post increment operation.");
497 #ifndef NDEBUG
498   // Post Increment means duplicates. Use dense map to find duplicates in the
499   // list. Caution: Densemap initializes with the minimum of 64 buckets,
500   // whereas there are at most 5 operands in the post increment.
501   DenseSet<unsigned> DefRegsSet;
502   for (auto &MO : MI.operands())
503     if (MO.isReg() && MO.isDef())
504       DefRegsSet.insert(MO.getReg());
505
506   for (auto &MO : MI.operands())
507     if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg()))
508       return MO;
509 #else
510   if (MI.mayLoad()) {
511     const MachineOperand &Op1 = MI.getOperand(1);
512     // The 2nd operand is always the post increment operand in load.
513     assert(Op1.isReg() && "Post increment operand has be to a register.");
514     return Op1;
515   }
516   if (MI.getDesc().mayStore()) {
517     const MachineOperand &Op0 = MI.getOperand(0);
518     // The 1st operand is always the post increment operand in store.
519     assert(Op0.isReg() && "Post increment operand has be to a register.");
520     return Op0;
521   }
522 #endif
523   // we should never come here.
524   llvm_unreachable("mayLoad or mayStore not set for Post Increment operation");
525 }
526
527 // Get the value being stored.
528 static const MachineOperand& getStoreValueOperand(const MachineInstr &MI) {
529   // value being stored is always the last operand.
530   return MI.getOperand(MI.getNumOperands()-1);
531 }
532
533 static bool isLoadAbsSet(const MachineInstr &MI) {
534   unsigned Opc = MI.getOpcode();
535   switch (Opc) {
536     case Hexagon::L4_loadrd_ap:
537     case Hexagon::L4_loadrb_ap:
538     case Hexagon::L4_loadrh_ap:
539     case Hexagon::L4_loadrub_ap:
540     case Hexagon::L4_loadruh_ap:
541     case Hexagon::L4_loadri_ap:
542       return true;
543   }
544   return false;
545 }
546
547 static const MachineOperand &getAbsSetOperand(const MachineInstr &MI) {
548   assert(isLoadAbsSet(MI));
549   return MI.getOperand(1);
550 }
551
552
553 // Can be new value store?
554 // Following restrictions are to be respected in convert a store into
555 // a new value store.
556 // 1. If an instruction uses auto-increment, its address register cannot
557 //    be a new-value register. Arch Spec 5.4.2.1
558 // 2. If an instruction uses absolute-set addressing mode, its address
559 //    register cannot be a new-value register. Arch Spec 5.4.2.1.
560 // 3. If an instruction produces a 64-bit result, its registers cannot be used
561 //    as new-value registers. Arch Spec 5.4.2.2.
562 // 4. If the instruction that sets the new-value register is conditional, then
563 //    the instruction that uses the new-value register must also be conditional,
564 //    and both must always have their predicates evaluate identically.
565 //    Arch Spec 5.4.2.3.
566 // 5. There is an implied restriction that a packet cannot have another store,
567 //    if there is a new value store in the packet. Corollary: if there is
568 //    already a store in a packet, there can not be a new value store.
569 //    Arch Spec: 3.4.4.2
570 bool HexagonPacketizerList::canPromoteToNewValueStore(const MachineInstr &MI,
571       const MachineInstr &PacketMI, unsigned DepReg) {
572   // Make sure we are looking at the store, that can be promoted.
573   if (!HII->mayBeNewStore(MI))
574     return false;
575
576   // Make sure there is dependency and can be new value'd.
577   const MachineOperand &Val = getStoreValueOperand(MI);
578   if (Val.isReg() && Val.getReg() != DepReg)
579     return false;
580
581   const MCInstrDesc& MCID = PacketMI.getDesc();
582
583   // First operand is always the result.
584   const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0, HRI, MF);
585   // Double regs can not feed into new value store: PRM section: 5.4.2.2.
586   if (PacketRC == &Hexagon::DoubleRegsRegClass)
587     return false;
588
589   // New-value stores are of class NV (slot 0), dual stores require class ST
590   // in slot 0 (PRM 5.5).
591   for (auto I : CurrentPacketMIs) {
592     SUnit *PacketSU = MIToSUnit.find(I)->second;
593     if (PacketSU->getInstr()->mayStore())
594       return false;
595   }
596
597   // Make sure it's NOT the post increment register that we are going to
598   // new value.
599   if (HII->isPostIncrement(MI) &&
600       getPostIncrementOperand(MI, HII).getReg() == DepReg) {
601     return false;
602   }
603
604   if (HII->isPostIncrement(PacketMI) && PacketMI.mayLoad() &&
605       getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) {
606     // If source is post_inc, or absolute-set addressing, it can not feed
607     // into new value store
608     //   r3 = memw(r2++#4)
609     //   memw(r30 + #-1404) = r2.new -> can not be new value store
610     // arch spec section: 5.4.2.1.
611     return false;
612   }
613
614   if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg)
615     return false;
616
617   // If the source that feeds the store is predicated, new value store must
618   // also be predicated.
619   if (HII->isPredicated(PacketMI)) {
620     if (!HII->isPredicated(MI))
621       return false;
622
623     // Check to make sure that they both will have their predicates
624     // evaluate identically.
625     unsigned predRegNumSrc = 0;
626     unsigned predRegNumDst = 0;
627     const TargetRegisterClass* predRegClass = nullptr;
628
629     // Get predicate register used in the source instruction.
630     for (auto &MO : PacketMI.operands()) {
631       if (!MO.isReg())
632         continue;
633       predRegNumSrc = MO.getReg();
634       predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc);
635       if (predRegClass == &Hexagon::PredRegsRegClass)
636         break;
637     }
638     assert((predRegClass == &Hexagon::PredRegsRegClass) &&
639         "predicate register not found in a predicated PacketMI instruction");
640
641     // Get predicate register used in new-value store instruction.
642     for (auto &MO : MI.operands()) {
643       if (!MO.isReg())
644         continue;
645       predRegNumDst = MO.getReg();
646       predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst);
647       if (predRegClass == &Hexagon::PredRegsRegClass)
648         break;
649     }
650     assert((predRegClass == &Hexagon::PredRegsRegClass) &&
651            "predicate register not found in a predicated MI instruction");
652
653     // New-value register producer and user (store) need to satisfy these
654     // constraints:
655     // 1) Both instructions should be predicated on the same register.
656     // 2) If producer of the new-value register is .new predicated then store
657     // should also be .new predicated and if producer is not .new predicated
658     // then store should not be .new predicated.
659     // 3) Both new-value register producer and user should have same predicate
660     // sense, i.e, either both should be negated or both should be non-negated.
661     if (predRegNumDst != predRegNumSrc ||
662         HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) ||
663         getPredicateSense(MI, HII) != getPredicateSense(PacketMI, HII))
664       return false;
665   }
666
667   // Make sure that other than the new-value register no other store instruction
668   // register has been modified in the same packet. Predicate registers can be
669   // modified by they should not be modified between the producer and the store
670   // instruction as it will make them both conditional on different values.
671   // We already know this to be true for all the instructions before and
672   // including PacketMI. Howerver, we need to perform the check for the
673   // remaining instructions in the packet.
674
675   unsigned StartCheck = 0;
676
677   for (auto I : CurrentPacketMIs) {
678     SUnit *TempSU = MIToSUnit.find(I)->second;
679     MachineInstr &TempMI = *TempSU->getInstr();
680
681     // Following condition is true for all the instructions until PacketMI is
682     // reached (StartCheck is set to 0 before the for loop).
683     // StartCheck flag is 1 for all the instructions after PacketMI.
684     if (&TempMI != &PacketMI && !StartCheck) // Start processing only after
685       continue;                              // encountering PacketMI.
686
687     StartCheck = 1;
688     if (&TempMI == &PacketMI) // We don't want to check PacketMI for dependence.
689       continue;
690
691     for (auto &MO : MI.operands())
692       if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI))
693         return false;
694   }
695
696   // Make sure that for non-POST_INC stores:
697   // 1. The only use of reg is DepReg and no other registers.
698   //    This handles V4 base+index registers.
699   //    The following store can not be dot new.
700   //    Eg.   r0 = add(r0, #3)
701   //          memw(r1+r0<<#2) = r0
702   if (!HII->isPostIncrement(MI)) {
703     for (unsigned opNum = 0; opNum < MI.getNumOperands()-1; opNum++) {
704       const MachineOperand &MO = MI.getOperand(opNum);
705       if (MO.isReg() && MO.getReg() == DepReg)
706         return false;
707     }
708   }
709
710   // If data definition is because of implicit definition of the register,
711   // do not newify the store. Eg.
712   // %R9<def> = ZXTH %R12, %D6<imp-use>, %R12<imp-def>
713   // S2_storerh_io %R8, 2, %R12<kill>; mem:ST2[%scevgep343]
714   for (auto &MO : PacketMI.operands()) {
715     if (MO.isRegMask() && MO.clobbersPhysReg(DepReg))
716       return false;
717     if (!MO.isReg() || !MO.isDef() || !MO.isImplicit())
718       continue;
719     unsigned R = MO.getReg();
720     if (R == DepReg || HRI->isSuperRegister(DepReg, R))
721       return false;
722   }
723
724   // Handle imp-use of super reg case. There is a target independent side
725   // change that should prevent this situation but I am handling it for
726   // just-in-case. For example, we cannot newify R2 in the following case:
727   // %R3<def> = A2_tfrsi 0;
728   // S2_storeri_io %R0<kill>, 0, %R2<kill>, %D1<imp-use,kill>;
729   for (auto &MO : MI.operands()) {
730     if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg)
731       return false;
732   }
733
734   // Can be dot new store.
735   return true;
736 }
737
738 // Can this MI to promoted to either new value store or new value jump.
739 bool HexagonPacketizerList::canPromoteToNewValue(const MachineInstr &MI,
740       const SUnit *PacketSU, unsigned DepReg,
741       MachineBasicBlock::iterator &MII) {
742   if (!HII->mayBeNewStore(MI))
743     return false;
744
745   // Check to see the store can be new value'ed.
746   MachineInstr &PacketMI = *PacketSU->getInstr();
747   if (canPromoteToNewValueStore(MI, PacketMI, DepReg))
748     return true;
749
750   // Check to see the compare/jump can be new value'ed.
751   // This is done as a pass on its own. Don't need to check it here.
752   return false;
753 }
754
755 static bool isImplicitDependency(const MachineInstr &I, bool CheckDef,
756       unsigned DepReg) {
757   for (auto &MO : I.operands()) {
758     if (CheckDef && MO.isRegMask() && MO.clobbersPhysReg(DepReg))
759       return true;
760     if (!MO.isReg() || MO.getReg() != DepReg || !MO.isImplicit())
761       continue;
762     if (CheckDef == MO.isDef())
763       return true;
764   }
765   return false;
766 }
767
768 // Check to see if an instruction can be dot new
769 // There are three kinds.
770 // 1. dot new on predicate - V2/V3/V4
771 // 2. dot new on stores NV/ST - V4
772 // 3. dot new on jump NV/J - V4 -- This is generated in a pass.
773 bool HexagonPacketizerList::canPromoteToDotNew(const MachineInstr &MI,
774       const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII,
775       const TargetRegisterClass* RC) {
776   // Already a dot new instruction.
777   if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI))
778     return false;
779
780   if (!isNewifiable(MI, RC))
781     return false;
782
783   const MachineInstr &PI = *PacketSU->getInstr();
784
785   // The "new value" cannot come from inline asm.
786   if (PI.isInlineAsm())
787     return false;
788
789   // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no
790   // sense.
791   if (PI.isImplicitDef())
792     return false;
793
794   // If dependency is trough an implicitly defined register, we should not
795   // newify the use.
796   if (isImplicitDependency(PI, true, DepReg) ||
797       isImplicitDependency(MI, false, DepReg))
798     return false;
799
800   const MCInstrDesc& MCID = PI.getDesc();
801   const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0, HRI, MF);
802   if (DisableVecDblNVStores && VecRC == &Hexagon::VecDblRegsRegClass)
803     return false;
804
805   // predicate .new
806   if (RC == &Hexagon::PredRegsRegClass)
807     return HII->predCanBeUsedAsDotNew(PI, DepReg);
808
809   if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI))
810     return false;
811
812   // Create a dot new machine instruction to see if resources can be
813   // allocated. If not, bail out now.
814   int NewOpcode = HII->getDotNewOp(MI);
815   const MCInstrDesc &D = HII->get(NewOpcode);
816   MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc());
817   bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI);
818   MF.DeleteMachineInstr(NewMI);
819   if (!ResourcesAvailable)
820     return false;
821
822   // New Value Store only. New Value Jump generated as a separate pass.
823   if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII))
824     return false;
825
826   return true;
827 }
828
829 // Go through the packet instructions and search for an anti dependency between
830 // them and DepReg from MI. Consider this case:
831 // Trying to add
832 // a) %R1<def> = TFRI_cdNotPt %P3, 2
833 // to this packet:
834 // {
835 //   b) %P0<def> = C2_or %P3<kill>, %P0<kill>
836 //   c) %P3<def> = C2_tfrrp %R23
837 //   d) %R1<def> = C2_cmovenewit %P3, 4
838 //  }
839 // The P3 from a) and d) will be complements after
840 // a)'s P3 is converted to .new form
841 // Anti-dep between c) and b) is irrelevant for this case
842 bool HexagonPacketizerList::restrictingDepExistInPacket(MachineInstr &MI,
843                                                         unsigned DepReg) {
844   SUnit *PacketSUDep = MIToSUnit.find(&MI)->second;
845
846   for (auto I : CurrentPacketMIs) {
847     // We only care for dependencies to predicated instructions
848     if (!HII->isPredicated(*I))
849       continue;
850
851     // Scheduling Unit for current insn in the packet
852     SUnit *PacketSU = MIToSUnit.find(I)->second;
853
854     // Look at dependencies between current members of the packet and
855     // predicate defining instruction MI. Make sure that dependency is
856     // on the exact register we care about.
857     if (PacketSU->isSucc(PacketSUDep)) {
858       for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
859         auto &Dep = PacketSU->Succs[i];
860         if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti &&
861             Dep.getReg() == DepReg)
862           return true;
863       }
864     }
865   }
866
867   return false;
868 }
869
870
871 /// Gets the predicate register of a predicated instruction.
872 static unsigned getPredicatedRegister(MachineInstr &MI,
873                                       const HexagonInstrInfo *QII) {
874   /// We use the following rule: The first predicate register that is a use is
875   /// the predicate register of a predicated instruction.
876   assert(QII->isPredicated(MI) && "Must be predicated instruction");
877
878   for (auto &Op : MI.operands()) {
879     if (Op.isReg() && Op.getReg() && Op.isUse() &&
880         Hexagon::PredRegsRegClass.contains(Op.getReg()))
881       return Op.getReg();
882   }
883
884   llvm_unreachable("Unknown instruction operand layout");
885   return 0;
886 }
887
888 // Given two predicated instructions, this function detects whether
889 // the predicates are complements.
890 bool HexagonPacketizerList::arePredicatesComplements(MachineInstr &MI1,
891                                                      MachineInstr &MI2) {
892   // If we don't know the predicate sense of the instructions bail out early, we
893   // need it later.
894   if (getPredicateSense(MI1, HII) == PK_Unknown ||
895       getPredicateSense(MI2, HII) == PK_Unknown)
896     return false;
897
898   // Scheduling unit for candidate.
899   SUnit *SU = MIToSUnit[&MI1];
900
901   // One corner case deals with the following scenario:
902   // Trying to add
903   // a) %R24<def> = A2_tfrt %P0, %R25
904   // to this packet:
905   // {
906   //   b) %R25<def> = A2_tfrf %P0, %R24
907   //   c) %P0<def> = C2_cmpeqi %R26, 1
908   // }
909   //
910   // On general check a) and b) are complements, but presence of c) will
911   // convert a) to .new form, and then it is not a complement.
912   // We attempt to detect it by analyzing existing dependencies in the packet.
913
914   // Analyze relationships between all existing members of the packet.
915   // Look for Anti dependecy on the same predicate reg as used in the
916   // candidate.
917   for (auto I : CurrentPacketMIs) {
918     // Scheduling Unit for current insn in the packet.
919     SUnit *PacketSU = MIToSUnit.find(I)->second;
920
921     // If this instruction in the packet is succeeded by the candidate...
922     if (PacketSU->isSucc(SU)) {
923       for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) {
924         auto Dep = PacketSU->Succs[i];
925         // The corner case exist when there is true data dependency between
926         // candidate and one of current packet members, this dep is on
927         // predicate reg, and there already exist anti dep on the same pred in
928         // the packet.
929         if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data &&
930             Hexagon::PredRegsRegClass.contains(Dep.getReg())) {
931           // Here I know that I is predicate setting instruction with true
932           // data dep to candidate on the register we care about - c) in the
933           // above example. Now I need to see if there is an anti dependency
934           // from c) to any other instruction in the same packet on the pred
935           // reg of interest.
936           if (restrictingDepExistInPacket(*I, Dep.getReg()))
937             return false;
938         }
939       }
940     }
941   }
942
943   // If the above case does not apply, check regular complement condition.
944   // Check that the predicate register is the same and that the predicate
945   // sense is different We also need to differentiate .old vs. .new: !p0
946   // is not complementary to p0.new.
947   unsigned PReg1 = getPredicatedRegister(MI1, HII);
948   unsigned PReg2 = getPredicatedRegister(MI2, HII);
949   return PReg1 == PReg2 &&
950          Hexagon::PredRegsRegClass.contains(PReg1) &&
951          Hexagon::PredRegsRegClass.contains(PReg2) &&
952          getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) &&
953          HII->isDotNewInst(MI1) == HII->isDotNewInst(MI2);
954 }
955
956 // Initialize packetizer flags.
957 void HexagonPacketizerList::initPacketizerState() {
958   Dependence = false;
959   PromotedToDotNew = false;
960   GlueToNewValueJump = false;
961   GlueAllocframeStore = false;
962   FoundSequentialDependence = false;
963 }
964
965 // Ignore bundling of pseudo instructions.
966 bool HexagonPacketizerList::ignorePseudoInstruction(const MachineInstr &MI,
967                                                     const MachineBasicBlock *) {
968   if (MI.isDebugValue())
969     return true;
970
971   if (MI.isCFIInstruction())
972     return false;
973
974   // We must print out inline assembly.
975   if (MI.isInlineAsm())
976     return false;
977
978   if (MI.isImplicitDef())
979     return false;
980
981   // We check if MI has any functional units mapped to it. If it doesn't,
982   // we ignore the instruction.
983   const MCInstrDesc& TID = MI.getDesc();
984   auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass());
985   unsigned FuncUnits = IS->getUnits();
986   return !FuncUnits;
987 }
988
989 bool HexagonPacketizerList::isSoloInstruction(const MachineInstr &MI) {
990   if (MI.isEHLabel() || MI.isCFIInstruction())
991     return true;
992
993   // Consider inline asm to not be a solo instruction by default.
994   // Inline asm will be put in a packet temporarily, but then it will be
995   // removed, and placed outside of the packet (before or after, depending
996   // on dependencies).  This is to reduce the impact of inline asm as a
997   // "packet splitting" instruction.
998   if (MI.isInlineAsm() && !ScheduleInlineAsm)
999     return true;
1000
1001   // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints:
1002   // trap, pause, barrier, icinva, isync, and syncht are solo instructions.
1003   // They must not be grouped with other instructions in a packet.
1004   if (isSchedBarrier(MI))
1005     return true;
1006
1007   if (HII->isSolo(MI))
1008     return true;
1009
1010   if (MI.getOpcode() == Hexagon::A2_nop)
1011     return true;
1012
1013   return false;
1014 }
1015
1016
1017 // Quick check if instructions MI and MJ cannot coexist in the same packet.
1018 // Limit the tests to be "one-way", e.g.  "if MI->isBranch and MJ->isInlineAsm",
1019 // but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm".
1020 // For full test call this function twice:
1021 //   cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI)
1022 // Doing the test only one way saves the amount of code in this function,
1023 // since every test would need to be repeated with the MI and MJ reversed.
1024 static bool cannotCoexistAsymm(const MachineInstr &MI, const MachineInstr &MJ,
1025       const HexagonInstrInfo &HII) {
1026   const MachineFunction *MF = MI.getParent()->getParent();
1027   if (MF->getSubtarget<HexagonSubtarget>().hasV60TOpsOnly() &&
1028       HII.isHVXMemWithAIndirect(MI, MJ))
1029     return true;
1030
1031   // An inline asm cannot be together with a branch, because we may not be
1032   // able to remove the asm out after packetizing (i.e. if the asm must be
1033   // moved past the bundle).  Similarly, two asms cannot be together to avoid
1034   // complications when determining their relative order outside of a bundle.
1035   if (MI.isInlineAsm())
1036     return MJ.isInlineAsm() || MJ.isBranch() || MJ.isBarrier() ||
1037            MJ.isCall() || MJ.isTerminator();
1038
1039   switch (MI.getOpcode()) {
1040   case (Hexagon::S2_storew_locked):
1041   case (Hexagon::S4_stored_locked):
1042   case (Hexagon::L2_loadw_locked):
1043   case (Hexagon::L4_loadd_locked):
1044   case (Hexagon::Y4_l2fetch): {
1045     // These instructions can only be grouped with ALU32 or non-floating-point
1046     // XTYPE instructions.  Since there is no convenient way of identifying fp
1047     // XTYPE instructions, only allow grouping with ALU32 for now.
1048     unsigned TJ = HII.getType(MJ);
1049     if (TJ != HexagonII::TypeALU32_2op &&
1050         TJ != HexagonII::TypeALU32_3op &&
1051         TJ != HexagonII::TypeALU32_ADDI)
1052       return true;
1053     break;
1054   }
1055   default:
1056     break;
1057   }
1058
1059   // "False" really means that the quick check failed to determine if
1060   // I and J cannot coexist.
1061   return false;
1062 }
1063
1064
1065 // Full, symmetric check.
1066 bool HexagonPacketizerList::cannotCoexist(const MachineInstr &MI,
1067       const MachineInstr &MJ) {
1068   return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII);
1069 }
1070
1071 void HexagonPacketizerList::unpacketizeSoloInstrs(MachineFunction &MF) {
1072   for (auto &B : MF) {
1073     MachineBasicBlock::iterator BundleIt;
1074     MachineBasicBlock::instr_iterator NextI;
1075     for (auto I = B.instr_begin(), E = B.instr_end(); I != E; I = NextI) {
1076       NextI = std::next(I);
1077       MachineInstr &MI = *I;
1078       if (MI.isBundle())
1079         BundleIt = I;
1080       if (!MI.isInsideBundle())
1081         continue;
1082
1083       // Decide on where to insert the instruction that we are pulling out.
1084       // Debug instructions always go before the bundle, but the placement of
1085       // INLINE_ASM depends on potential dependencies.  By default, try to
1086       // put it before the bundle, but if the asm writes to a register that
1087       // other instructions in the bundle read, then we need to place it
1088       // after the bundle (to preserve the bundle semantics).
1089       bool InsertBeforeBundle;
1090       if (MI.isInlineAsm())
1091         InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI);
1092       else if (MI.isDebugValue())
1093         InsertBeforeBundle = true;
1094       else
1095         continue;
1096
1097       BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle);
1098     }
1099   }
1100 }
1101
1102 // Check if a given instruction is of class "system".
1103 static bool isSystemInstr(const MachineInstr &MI) {
1104   unsigned Opc = MI.getOpcode();
1105   switch (Opc) {
1106     case Hexagon::Y2_barrier:
1107     case Hexagon::Y2_dcfetchbo:
1108       return true;
1109   }
1110   return false;
1111 }
1112
1113 bool HexagonPacketizerList::hasDeadDependence(const MachineInstr &I,
1114                                               const MachineInstr &J) {
1115   // The dependence graph may not include edges between dead definitions,
1116   // so without extra checks, we could end up packetizing two instruction
1117   // defining the same (dead) register.
1118   if (I.isCall() || J.isCall())
1119     return false;
1120   if (HII->isPredicated(I) || HII->isPredicated(J))
1121     return false;
1122
1123   BitVector DeadDefs(Hexagon::NUM_TARGET_REGS);
1124   for (auto &MO : I.operands()) {
1125     if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1126       continue;
1127     DeadDefs[MO.getReg()] = true;
1128   }
1129
1130   for (auto &MO : J.operands()) {
1131     if (!MO.isReg() || !MO.isDef() || !MO.isDead())
1132       continue;
1133     unsigned R = MO.getReg();
1134     if (R != Hexagon::USR_OVF && DeadDefs[R])
1135       return true;
1136   }
1137   return false;
1138 }
1139
1140 bool HexagonPacketizerList::hasControlDependence(const MachineInstr &I,
1141                                                  const MachineInstr &J) {
1142   // A save callee-save register function call can only be in a packet
1143   // with instructions that don't write to the callee-save registers.
1144   if ((HII->isSaveCalleeSavedRegsCall(I) &&
1145        doesModifyCalleeSavedReg(J, HRI)) ||
1146       (HII->isSaveCalleeSavedRegsCall(J) &&
1147        doesModifyCalleeSavedReg(I, HRI)))
1148     return true;
1149
1150   // Two control flow instructions cannot go in the same packet.
1151   if (isControlFlow(I) && isControlFlow(J))
1152     return true;
1153
1154   // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot
1155   // contain a speculative indirect jump,
1156   // a new-value compare jump or a dealloc_return.
1157   auto isBadForLoopN = [this] (const MachineInstr &MI) -> bool {
1158     if (MI.isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI))
1159       return true;
1160     if (HII->isPredicated(MI) && HII->isPredicatedNew(MI) && HII->isJumpR(MI))
1161       return true;
1162     return false;
1163   };
1164
1165   if (HII->isLoopN(I) && isBadForLoopN(J))
1166     return true;
1167   if (HII->isLoopN(J) && isBadForLoopN(I))
1168     return true;
1169
1170   // dealloc_return cannot appear in the same packet as a conditional or
1171   // unconditional jump.
1172   return HII->isDeallocRet(I) &&
1173          (J.isBranch() || J.isCall() || J.isBarrier());
1174 }
1175
1176 bool HexagonPacketizerList::hasRegMaskDependence(const MachineInstr &I,
1177                                                  const MachineInstr &J) {
1178   // Adding I to a packet that has J.
1179
1180   // Regmasks are not reflected in the scheduling dependency graph, so
1181   // we need to check them manually. This code assumes that regmasks only
1182   // occur on calls, and the problematic case is when we add an instruction
1183   // defining a register R to a packet that has a call that clobbers R via
1184   // a regmask. Those cannot be packetized together, because the call will
1185   // be executed last. That's also a reson why it is ok to add a call
1186   // clobbering R to a packet that defines R.
1187
1188   // Look for regmasks in J.
1189   for (const MachineOperand &OpJ : J.operands()) {
1190     if (!OpJ.isRegMask())
1191       continue;
1192     assert((J.isCall() || HII->isTailCall(J)) && "Regmask on a non-call");
1193     for (const MachineOperand &OpI : I.operands()) {
1194       if (OpI.isReg()) {
1195         if (OpJ.clobbersPhysReg(OpI.getReg()))
1196           return true;
1197       } else if (OpI.isRegMask()) {
1198         // Both are regmasks. Assume that they intersect.
1199         return true;
1200       }
1201     }
1202   }
1203   return false;
1204 }
1205
1206 bool HexagonPacketizerList::hasV4SpecificDependence(const MachineInstr &I,
1207                                                     const MachineInstr &J) {
1208   bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J);
1209   bool StoreI = I.mayStore(), StoreJ = J.mayStore();
1210   if ((SysI && StoreJ) || (SysJ && StoreI))
1211     return true;
1212
1213   if (StoreI && StoreJ) {
1214     if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I))
1215       return true;
1216   } else {
1217     // A memop cannot be in the same packet with another memop or a store.
1218     // Two stores can be together, but here I and J cannot both be stores.
1219     bool MopStI = HII->isMemOp(I) || StoreI;
1220     bool MopStJ = HII->isMemOp(J) || StoreJ;
1221     if (MopStI && MopStJ)
1222       return true;
1223   }
1224
1225   return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J));
1226 }
1227
1228 // SUI is the current instruction that is out side of the current packet.
1229 // SUJ is the current instruction inside the current packet against which that
1230 // SUI will be packetized.
1231 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {
1232   assert(SUI->getInstr() && SUJ->getInstr());
1233   MachineInstr &I = *SUI->getInstr();
1234   MachineInstr &J = *SUJ->getInstr();
1235
1236   // Clear IgnoreDepMIs when Packet starts.
1237   if (CurrentPacketMIs.size() == 1)
1238     IgnoreDepMIs.clear();
1239
1240   MachineBasicBlock::iterator II = I.getIterator();
1241
1242   // Solo instructions cannot go in the packet.
1243   assert(!isSoloInstruction(I) && "Unexpected solo instr!");
1244
1245   if (cannotCoexist(I, J))
1246     return false;
1247
1248   Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J);
1249   if (Dependence)
1250     return false;
1251
1252   // Regmasks are not accounted for in the scheduling graph, so we need
1253   // to explicitly check for dependencies caused by them. They should only
1254   // appear on calls, so it's not too pessimistic to reject all regmask
1255   // dependencies.
1256   Dependence = hasRegMaskDependence(I, J);
1257   if (Dependence)
1258     return false;
1259
1260   // V4 allows dual stores. It does not allow second store, if the first
1261   // store is not in SLOT0. New value store, new value jump, dealloc_return
1262   // and memop always take SLOT0. Arch spec 3.4.4.2.
1263   Dependence = hasV4SpecificDependence(I, J);
1264   if (Dependence)
1265     return false;
1266
1267   // If an instruction feeds new value jump, glue it.
1268   MachineBasicBlock::iterator NextMII = I.getIterator();
1269   ++NextMII;
1270   if (NextMII != I.getParent()->end() && HII->isNewValueJump(*NextMII)) {
1271     MachineInstr &NextMI = *NextMII;
1272
1273     bool secondRegMatch = false;
1274     const MachineOperand &NOp0 = NextMI.getOperand(0);
1275     const MachineOperand &NOp1 = NextMI.getOperand(1);
1276
1277     if (NOp1.isReg() && I.getOperand(0).getReg() == NOp1.getReg())
1278       secondRegMatch = true;
1279
1280     for (auto T : CurrentPacketMIs) {
1281       SUnit *PacketSU = MIToSUnit.find(T)->second;
1282       MachineInstr &PI = *PacketSU->getInstr();
1283       // NVJ can not be part of the dual jump - Arch Spec: section 7.8.
1284       if (PI.isCall()) {
1285         Dependence = true;
1286         break;
1287       }
1288       // Validate:
1289       // 1. Packet does not have a store in it.
1290       // 2. If the first operand of the nvj is newified, and the second
1291       //    operand is also a reg, it (second reg) is not defined in
1292       //    the same packet.
1293       // 3. If the second operand of the nvj is newified, (which means
1294       //    first operand is also a reg), first reg is not defined in
1295       //    the same packet.
1296       if (PI.getOpcode() == Hexagon::S2_allocframe || PI.mayStore() ||
1297           HII->isLoopN(PI)) {
1298         Dependence = true;
1299         break;
1300       }
1301       // Check #2/#3.
1302       const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1;
1303       if (OpR.isReg() && PI.modifiesRegister(OpR.getReg(), HRI)) {
1304         Dependence = true;
1305         break;
1306       }
1307     }
1308
1309     if (Dependence)
1310       return false;
1311     GlueToNewValueJump = true;
1312   }
1313
1314   // There no dependency between a prolog instruction and its successor.
1315   if (!SUJ->isSucc(SUI))
1316     return true;
1317
1318   for (unsigned i = 0; i < SUJ->Succs.size(); ++i) {
1319     if (FoundSequentialDependence)
1320       break;
1321
1322     if (SUJ->Succs[i].getSUnit() != SUI)
1323       continue;
1324
1325     SDep::Kind DepType = SUJ->Succs[i].getKind();
1326     // For direct calls:
1327     // Ignore register dependences for call instructions for packetization
1328     // purposes except for those due to r31 and predicate registers.
1329     //
1330     // For indirect calls:
1331     // Same as direct calls + check for true dependences to the register
1332     // used in the indirect call.
1333     //
1334     // We completely ignore Order dependences for call instructions.
1335     //
1336     // For returns:
1337     // Ignore register dependences for return instructions like jumpr,
1338     // dealloc return unless we have dependencies on the explicit uses
1339     // of the registers used by jumpr (like r31) or dealloc return
1340     // (like r29 or r30).
1341     unsigned DepReg = 0;
1342     const TargetRegisterClass *RC = nullptr;
1343     if (DepType == SDep::Data) {
1344       DepReg = SUJ->Succs[i].getReg();
1345       RC = HRI->getMinimalPhysRegClass(DepReg);
1346     }
1347
1348     if (I.isCall() || HII->isJumpR(I) || I.isReturn() || HII->isTailCall(I)) {
1349       if (!isRegDependence(DepType))
1350         continue;
1351       if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg()))
1352         continue;
1353     }
1354
1355     if (DepType == SDep::Data) {
1356       if (canPromoteToDotCur(J, SUJ, DepReg, II, RC))
1357         if (promoteToDotCur(J, DepType, II, RC))
1358           continue;
1359     }
1360
1361     // Data dpendence ok if we have load.cur.
1362     if (DepType == SDep::Data && HII->isDotCurInst(J)) {
1363       if (HII->isHVXVec(I))
1364         continue;
1365     }
1366
1367     // For instructions that can be promoted to dot-new, try to promote.
1368     if (DepType == SDep::Data) {
1369       if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) {
1370         if (promoteToDotNew(I, DepType, II, RC)) {
1371           PromotedToDotNew = true;
1372           if (cannotCoexist(I, J))
1373             FoundSequentialDependence = true;
1374           continue;
1375         }
1376       }
1377       if (HII->isNewValueJump(I))
1378         continue;
1379     }
1380
1381     // For predicated instructions, if the predicates are complements then
1382     // there can be no dependence.
1383     if (HII->isPredicated(I) && HII->isPredicated(J) &&
1384         arePredicatesComplements(I, J)) {
1385       // Not always safe to do this translation.
1386       // DAG Builder attempts to reduce dependence edges using transitive
1387       // nature of dependencies. Here is an example:
1388       //
1389       // r0 = tfr_pt ... (1)
1390       // r0 = tfr_pf ... (2)
1391       // r0 = tfr_pt ... (3)
1392       //
1393       // There will be an output dependence between (1)->(2) and (2)->(3).
1394       // However, there is no dependence edge between (1)->(3). This results
1395       // in all 3 instructions going in the same packet. We ignore dependce
1396       // only once to avoid this situation.
1397       auto Itr = find(IgnoreDepMIs, &J);
1398       if (Itr != IgnoreDepMIs.end()) {
1399         Dependence = true;
1400         return false;
1401       }
1402       IgnoreDepMIs.push_back(&I);
1403       continue;
1404     }
1405
1406     // Ignore Order dependences between unconditional direct branches
1407     // and non-control-flow instructions.
1408     if (isDirectJump(I) && !J.isBranch() && !J.isCall() &&
1409         DepType == SDep::Order)
1410       continue;
1411
1412     // Ignore all dependences for jumps except for true and output
1413     // dependences.
1414     if (I.isConditionalBranch() && DepType != SDep::Data &&
1415         DepType != SDep::Output)
1416       continue;
1417
1418     if (DepType == SDep::Output) {
1419       FoundSequentialDependence = true;
1420       break;
1421     }
1422
1423     // For Order dependences:
1424     // 1. On V4 or later, volatile loads/stores can be packetized together,
1425     //    unless other rules prevent is.
1426     // 2. Store followed by a load is not allowed.
1427     // 3. Store followed by a store is only valid on V4 or later.
1428     // 4. Load followed by any memory operation is allowed.
1429     if (DepType == SDep::Order) {
1430       if (!PacketizeVolatiles) {
1431         bool OrdRefs = I.hasOrderedMemoryRef() || J.hasOrderedMemoryRef();
1432         if (OrdRefs) {
1433           FoundSequentialDependence = true;
1434           break;
1435         }
1436       }
1437       // J is first, I is second.
1438       bool LoadJ = J.mayLoad(), StoreJ = J.mayStore();
1439       bool LoadI = I.mayLoad(), StoreI = I.mayStore();
1440       if (StoreJ) {
1441         // Two stores are only allowed on V4+. Load following store is never
1442         // allowed.
1443         if (LoadI) {
1444           FoundSequentialDependence = true;
1445           break;
1446         }
1447       } else if (!LoadJ || (!LoadI && !StoreI)) {
1448         // If J is neither load nor store, assume a dependency.
1449         // If J is a load, but I is neither, also assume a dependency.
1450         FoundSequentialDependence = true;
1451         break;
1452       }
1453       // Store followed by store: not OK on V2.
1454       // Store followed by load: not OK on all.
1455       // Load followed by store: OK on all.
1456       // Load followed by load: OK on all.
1457       continue;
1458     }
1459
1460     // For V4, special case ALLOCFRAME. Even though there is dependency
1461     // between ALLOCFRAME and subsequent store, allow it to be packetized
1462     // in a same packet. This implies that the store is using the caller's
1463     // SP. Hence, offset needs to be updated accordingly.
1464     if (DepType == SDep::Data && J.getOpcode() == Hexagon::S2_allocframe) {
1465       unsigned Opc = I.getOpcode();
1466       switch (Opc) {
1467         case Hexagon::S2_storerd_io:
1468         case Hexagon::S2_storeri_io:
1469         case Hexagon::S2_storerh_io:
1470         case Hexagon::S2_storerb_io:
1471           if (I.getOperand(0).getReg() == HRI->getStackRegister()) {
1472             // Since this store is to be glued with allocframe in the same
1473             // packet, it will use SP of the previous stack frame, i.e.
1474             // caller's SP. Therefore, we need to recalculate offset
1475             // according to this change.
1476             GlueAllocframeStore = useCallersSP(I);
1477             if (GlueAllocframeStore)
1478               continue;
1479           }
1480         default:
1481           break;
1482       }
1483     }
1484
1485     // There are certain anti-dependencies that cannot be ignored.
1486     // Specifically:
1487     //   J2_call ... %R0<imp-def>   ; SUJ
1488     //   R0 = ...                   ; SUI
1489     // Those cannot be packetized together, since the call will observe
1490     // the effect of the assignment to R0.
1491     if ((DepType == SDep::Anti || DepType == SDep::Output) && J.isCall()) {
1492       // Check if I defines any volatile register. We should also check
1493       // registers that the call may read, but these happen to be a
1494       // subset of the volatile register set.
1495       for (const MachineOperand &Op : I.operands()) {
1496         if (Op.isReg() && Op.isDef()) {
1497           unsigned R = Op.getReg();
1498           if (!J.readsRegister(R, HRI) && !J.modifiesRegister(R, HRI))
1499             continue;
1500         } else if (!Op.isRegMask()) {
1501           // If I has a regmask assume dependency.
1502           continue;
1503         }
1504         FoundSequentialDependence = true;
1505         break;
1506       }
1507     }
1508
1509     // Skip over remaining anti-dependences. Two instructions that are
1510     // anti-dependent can share a packet, since in most such cases all
1511     // operands are read before any modifications take place.
1512     // The exceptions are branch and call instructions, since they are
1513     // executed after all other instructions have completed (at least
1514     // conceptually).
1515     if (DepType != SDep::Anti) {
1516       FoundSequentialDependence = true;
1517       break;
1518     }
1519   }
1520
1521   if (FoundSequentialDependence) {
1522     Dependence = true;
1523     return false;
1524   }
1525
1526   return true;
1527 }
1528
1529 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {
1530   assert(SUI->getInstr() && SUJ->getInstr());
1531   MachineInstr &I = *SUI->getInstr();
1532   MachineInstr &J = *SUJ->getInstr();
1533
1534   bool Coexist = !cannotCoexist(I, J);
1535
1536   if (Coexist && !Dependence)
1537     return true;
1538
1539   // Check if the instruction was promoted to a dot-new. If so, demote it
1540   // back into a dot-old.
1541   if (PromotedToDotNew)
1542     demoteToDotOld(I);
1543
1544   cleanUpDotCur();
1545   // Check if the instruction (must be a store) was glued with an allocframe
1546   // instruction. If so, restore its offset to its original value, i.e. use
1547   // current SP instead of caller's SP.
1548   if (GlueAllocframeStore) {
1549     useCalleesSP(I);
1550     GlueAllocframeStore = false;
1551   }
1552   return false;
1553 }
1554
1555 MachineBasicBlock::iterator
1556 HexagonPacketizerList::addToPacket(MachineInstr &MI) {
1557   MachineBasicBlock::iterator MII = MI.getIterator();
1558   MachineBasicBlock *MBB = MI.getParent();
1559
1560   if (CurrentPacketMIs.size() == 0)
1561     PacketStalls = false;
1562   PacketStalls |= producesStall(MI);
1563
1564   if (MI.isImplicitDef())
1565     return MII;
1566   assert(ResourceTracker->canReserveResources(MI));
1567
1568   bool ExtMI = HII->isExtended(MI) || HII->isConstExtended(MI);
1569   bool Good = true;
1570
1571   if (GlueToNewValueJump) {
1572     MachineInstr &NvjMI = *++MII;
1573     // We need to put both instructions in the same packet: MI and NvjMI.
1574     // Either of them can require a constant extender. Try to add both to
1575     // the current packet, and if that fails, end the packet and start a
1576     // new one.
1577     ResourceTracker->reserveResources(MI);
1578     if (ExtMI)
1579       Good = tryAllocateResourcesForConstExt(true);
1580
1581     bool ExtNvjMI = HII->isExtended(NvjMI) || HII->isConstExtended(NvjMI);
1582     if (Good) {
1583       if (ResourceTracker->canReserveResources(NvjMI))
1584         ResourceTracker->reserveResources(NvjMI);
1585       else
1586         Good = false;
1587     }
1588     if (Good && ExtNvjMI)
1589       Good = tryAllocateResourcesForConstExt(true);
1590
1591     if (!Good) {
1592       endPacket(MBB, MI);
1593       assert(ResourceTracker->canReserveResources(MI));
1594       ResourceTracker->reserveResources(MI);
1595       if (ExtMI) {
1596         assert(canReserveResourcesForConstExt());
1597         tryAllocateResourcesForConstExt(true);
1598       }
1599       assert(ResourceTracker->canReserveResources(NvjMI));
1600       ResourceTracker->reserveResources(NvjMI);
1601       if (ExtNvjMI) {
1602         assert(canReserveResourcesForConstExt());
1603         reserveResourcesForConstExt();
1604       }
1605     }
1606     CurrentPacketMIs.push_back(&MI);
1607     CurrentPacketMIs.push_back(&NvjMI);
1608     return MII;
1609   }
1610
1611   ResourceTracker->reserveResources(MI);
1612   if (ExtMI && !tryAllocateResourcesForConstExt(true)) {
1613     endPacket(MBB, MI);
1614     if (PromotedToDotNew)
1615       demoteToDotOld(MI);
1616     if (GlueAllocframeStore) {
1617       useCalleesSP(MI);
1618       GlueAllocframeStore = false;
1619     }
1620     ResourceTracker->reserveResources(MI);
1621     reserveResourcesForConstExt();
1622   }
1623
1624   CurrentPacketMIs.push_back(&MI);
1625   return MII;
1626 }
1627
1628 void HexagonPacketizerList::endPacket(MachineBasicBlock *MBB,
1629                                       MachineBasicBlock::iterator MI) {
1630   OldPacketMIs = CurrentPacketMIs;
1631   VLIWPacketizerList::endPacket(MBB, MI);
1632 }
1633
1634 bool HexagonPacketizerList::shouldAddToPacket(const MachineInstr &MI) {
1635   return !producesStall(MI);
1636 }
1637
1638
1639 // V60 forward scheduling.
1640 bool HexagonPacketizerList::producesStall(const MachineInstr &I) {
1641   // If the packet already stalls, then ignore the stall from a subsequent
1642   // instruction in the same packet.
1643   if (PacketStalls)
1644     return false;
1645
1646   // Check whether the previous packet is in a different loop. If this is the
1647   // case, there is little point in trying to avoid a stall because that would
1648   // favor the rare case (loop entry) over the common case (loop iteration).
1649   //
1650   // TODO: We should really be able to check all the incoming edges if this is
1651   // the first packet in a basic block, so we can avoid stalls from the loop
1652   // backedge.
1653   if (!OldPacketMIs.empty()) {
1654     auto *OldBB = OldPacketMIs.front()->getParent();
1655     auto *ThisBB = I.getParent();
1656     if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB))
1657       return false;
1658   }
1659
1660   SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)];
1661
1662   // Check if the latency is 0 between this instruction and any instruction
1663   // in the current packet. If so, we disregard any potential stalls due to
1664   // the instructions in the previous packet. Most of the instruction pairs
1665   // that can go together in the same packet have 0 latency between them.
1666   // Only exceptions are newValueJumps as they're generated much later and
1667   // the latencies can't be changed at that point. Another is .cur
1668   // instructions if its consumer has a 0 latency successor (such as .new).
1669   // In this case, the latency between .cur and the consumer stays non-zero
1670   // even though we can have  both .cur and .new in the same packet. Changing
1671   // the latency to 0 is not an option as it causes software pipeliner to
1672   // not pipeline in some cases.
1673
1674   // For Example:
1675   // {
1676   //   I1:  v6.cur = vmem(r0++#1)
1677   //   I2:  v7 = valign(v6,v4,r2)
1678   //   I3:  vmem(r5++#1) = v7.new
1679   // }
1680   // Here I2 and I3 has 0 cycle latency, but I1 and I2 has 2.
1681
1682   for (auto J : CurrentPacketMIs) {
1683     SUnit *SUJ = MIToSUnit[J];
1684     for (auto &Pred : SUI->Preds)
1685       if (Pred.getSUnit() == SUJ &&
1686           (Pred.getLatency() == 0 || HII->isNewValueJump(I) ||
1687            HII->isToBeScheduledASAP(*J, I)))
1688         return false;
1689   }
1690
1691   // Check if the latency is greater than one between this instruction and any
1692   // instruction in the previous packet.
1693   for (auto J : OldPacketMIs) {
1694     SUnit *SUJ = MIToSUnit[J];
1695     for (auto &Pred : SUI->Preds)
1696       if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
1697         return true;
1698   }
1699
1700   // Check if the latency is greater than one between this instruction and any
1701   // instruction in the previous packet.
1702   for (auto J : OldPacketMIs) {
1703     SUnit *SUJ = MIToSUnit[J];
1704     for (auto &Pred : SUI->Preds)
1705       if (Pred.getSUnit() == SUJ && Pred.getLatency() > 1)
1706         return true;
1707   }
1708
1709   return false;
1710 }
1711
1712 //===----------------------------------------------------------------------===//
1713 //                         Public Constructor Functions
1714 //===----------------------------------------------------------------------===//
1715
1716 FunctionPass *llvm::createHexagonPacketizer() {
1717   return new HexagonPacketizer();
1718 }