1 //===- HexagonSubtarget.cpp - Hexagon Subtarget Information ---------------===//
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 file implements the Hexagon specific subclass of TargetSubtarget.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "HexagonSubtarget.h"
14 #include "Hexagon.h"
15 #include "HexagonInstrInfo.h"
16 #include "HexagonRegisterInfo.h"
17 #include "MCTargetDesc/HexagonMCTargetDesc.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineScheduler.h"
25 #include "llvm/CodeGen/ScheduleDAG.h"
26 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <map>
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "hexagon-subtarget"
37 
38 #define GET_SUBTARGETINFO_CTOR
39 #define GET_SUBTARGETINFO_TARGET_DESC
40 #include "HexagonGenSubtargetInfo.inc"
41 
42 static cl::opt<bool> EnableBSBSched("enable-bsb-sched",
43   cl::Hidden, cl::ZeroOrMore, cl::init(true));
44 
45 static cl::opt<bool> EnableTCLatencySched("enable-tc-latency-sched",
46   cl::Hidden, cl::ZeroOrMore, cl::init(false));
47 
48 static cl::opt<bool> EnableDotCurSched("enable-cur-sched",
49   cl::Hidden, cl::ZeroOrMore, cl::init(true),
50   cl::desc("Enable the scheduler to generate .cur"));
51 
52 static cl::opt<bool> DisableHexagonMISched("disable-hexagon-misched",
53   cl::Hidden, cl::ZeroOrMore, cl::init(false),
54   cl::desc("Disable Hexagon MI Scheduling"));
55 
56 static cl::opt<bool> EnableSubregLiveness("hexagon-subreg-liveness",
57   cl::Hidden, cl::ZeroOrMore, cl::init(true),
58   cl::desc("Enable subregister liveness tracking for Hexagon"));
59 
60 static cl::opt<bool> OverrideLongCalls("hexagon-long-calls",
61   cl::Hidden, cl::ZeroOrMore, cl::init(false),
62   cl::desc("If present, forces/disables the use of long calls"));
63 
64 static cl::opt<bool> EnablePredicatedCalls("hexagon-pred-calls",
65   cl::Hidden, cl::ZeroOrMore, cl::init(false),
66   cl::desc("Consider calls to be predicable"));
67 
68 static cl::opt<bool> SchedPredsCloser("sched-preds-closer",
69   cl::Hidden, cl::ZeroOrMore, cl::init(true));
70 
71 static cl::opt<bool> SchedRetvalOptimization("sched-retval-optimization",
72   cl::Hidden, cl::ZeroOrMore, cl::init(true));
73 
74 static cl::opt<bool> EnableCheckBankConflict("hexagon-check-bank-conflict",
75   cl::Hidden, cl::ZeroOrMore, cl::init(true),
76   cl::desc("Enable checking for cache bank conflicts"));
77 
78 HexagonSubtarget::HexagonSubtarget(const Triple &TT, StringRef CPU,
79                                    StringRef FS, const TargetMachine &TM)
80     : HexagonGenSubtargetInfo(TT, CPU, /*TuneCPU*/ CPU, FS),
81       OptLevel(TM.getOptLevel()),
82       CPUString(std::string(Hexagon_MC::selectHexagonCPU(CPU))),
83       TargetTriple(TT), InstrInfo(initializeSubtargetDependencies(CPU, FS)),
84       RegInfo(getHwMode()), TLInfo(TM, *this),
85       InstrItins(getInstrItineraryForCPU(CPUString)) {
86   Hexagon_MC::addArchSubtarget(this, FS);
87   // Beware of the default constructor of InstrItineraryData: it will
88   // reset all members to 0.
89   assert(InstrItins.Itineraries != nullptr && "InstrItins not initialized");
90 }
91 
92 HexagonSubtarget &
93 HexagonSubtarget::initializeSubtargetDependencies(StringRef CPU, StringRef FS) {
94   Optional<Hexagon::ArchEnum> ArchVer =
95       Hexagon::GetCpu(Hexagon::CpuTable, CPUString);
96   if (ArchVer)
97     HexagonArchVersion = *ArchVer;
98   else
99     llvm_unreachable("Unrecognized Hexagon processor version");
100 
101   UseHVX128BOps = false;
102   UseHVX64BOps = false;
103   UseAudioOps = false;
104   UseLongCalls = false;
105 
106   UseBSBScheduling = hasV60Ops() && EnableBSBSched;
107 
108   ParseSubtargetFeatures(CPUString, /*TuneCPU*/ CPUString, FS);
109 
110   if (OverrideLongCalls.getPosition())
111     UseLongCalls = OverrideLongCalls;
112 
113   if (isTinyCore()) {
114     // Tiny core has a single thread, so back-to-back scheduling is enabled by
115     // default.
116     if (!EnableBSBSched.getPosition())
117       UseBSBScheduling = false;
118   }
119 
120   FeatureBitset Features = getFeatureBits();
121   if (HexagonDisableDuplex)
122     setFeatureBits(Features.reset(Hexagon::FeatureDuplex));
123   setFeatureBits(Hexagon_MC::completeHVXFeatures(Features));
124 
125   return *this;
126 }
127 
128 bool HexagonSubtarget::isHVXElementType(MVT Ty, bool IncludeBool) const {
129   if (!useHVXOps())
130     return false;
131   if (Ty.isVector())
132     Ty = Ty.getVectorElementType();
133   if (IncludeBool && Ty == MVT::i1)
134     return true;
135   ArrayRef<MVT> ElemTypes = getHVXElementTypes();
136   return llvm::find(ElemTypes, Ty) != ElemTypes.end();
137 }
138 
139 bool HexagonSubtarget::isHVXVectorType(MVT VecTy, bool IncludeBool) const {
140   if (!VecTy.isVector() || !useHVXOps() || VecTy.isScalableVector())
141     return false;
142   MVT ElemTy = VecTy.getVectorElementType();
143   if (!IncludeBool && ElemTy == MVT::i1)
144     return false;
145 
146   unsigned HwLen = getVectorLength();
147   unsigned NumElems = VecTy.getVectorNumElements();
148   ArrayRef<MVT> ElemTypes = getHVXElementTypes();
149 
150   if (IncludeBool && ElemTy == MVT::i1) {
151     // Boolean HVX vector types are formed from regular HVX vector types
152     // by replacing the element type with i1.
153     for (MVT T : ElemTypes)
154       if (NumElems * T.getSizeInBits() == 8 * HwLen)
155         return true;
156     return false;
157   }
158 
159   unsigned VecWidth = VecTy.getSizeInBits();
160   if (VecWidth != 8 * HwLen && VecWidth != 16 * HwLen)
161     return false;
162   return llvm::find(ElemTypes, ElemTy) != ElemTypes.end();
163 }
164 
165 bool HexagonSubtarget::isTypeForHVX(Type *VecTy, bool IncludeBool) const {
166   if (!VecTy->isVectorTy() || isa<ScalableVectorType>(VecTy))
167     return false;
168   // Avoid types like <2 x i32*>.
169   if (!cast<VectorType>(VecTy)->getElementType()->isIntegerTy())
170     return false;
171   EVT Ty = EVT::getEVT(VecTy, /*HandleUnknown*/false);
172   if (!Ty.isSimple() || Ty.getSizeInBits() <= 64)
173     return false;
174   if (isHVXVectorType(Ty.getSimpleVT(), IncludeBool))
175     return true;
176   auto Action =
177       getTargetLowering()->getPreferredVectorAction(Ty.getSimpleVT());
178   return Action == TargetLoweringBase::TypeWidenVector;
179 }
180 
181 void HexagonSubtarget::UsrOverflowMutation::apply(ScheduleDAGInstrs *DAG) {
182   for (SUnit &SU : DAG->SUnits) {
183     if (!SU.isInstr())
184       continue;
185     SmallVector<SDep, 4> Erase;
186     for (auto &D : SU.Preds)
187       if (D.getKind() == SDep::Output && D.getReg() == Hexagon::USR_OVF)
188         Erase.push_back(D);
189     for (auto &E : Erase)
190       SU.removePred(E);
191   }
192 }
193 
194 void HexagonSubtarget::HVXMemLatencyMutation::apply(ScheduleDAGInstrs *DAG) {
195   for (SUnit &SU : DAG->SUnits) {
196     // Update the latency of chain edges between v60 vector load or store
197     // instructions to be 1. These instruction cannot be scheduled in the
198     // same packet.
199     MachineInstr &MI1 = *SU.getInstr();
200     auto *QII = static_cast<const HexagonInstrInfo*>(DAG->TII);
201     bool IsStoreMI1 = MI1.mayStore();
202     bool IsLoadMI1 = MI1.mayLoad();
203     if (!QII->isHVXVec(MI1) || !(IsStoreMI1 || IsLoadMI1))
204       continue;
205     for (SDep &SI : SU.Succs) {
206       if (SI.getKind() != SDep::Order || SI.getLatency() != 0)
207         continue;
208       MachineInstr &MI2 = *SI.getSUnit()->getInstr();
209       if (!QII->isHVXVec(MI2))
210         continue;
211       if ((IsStoreMI1 && MI2.mayStore()) || (IsLoadMI1 && MI2.mayLoad())) {
212         SI.setLatency(1);
213         SU.setHeightDirty();
214         // Change the dependence in the opposite direction too.
215         for (SDep &PI : SI.getSUnit()->Preds) {
216           if (PI.getSUnit() != &SU || PI.getKind() != SDep::Order)
217             continue;
218           PI.setLatency(1);
219           SI.getSUnit()->setDepthDirty();
220         }
221       }
222     }
223   }
224 }
225 
226 // Check if a call and subsequent A2_tfrpi instructions should maintain
227 // scheduling affinity. We are looking for the TFRI to be consumed in
228 // the next instruction. This should help reduce the instances of
229 // double register pairs being allocated and scheduled before a call
230 // when not used until after the call. This situation is exacerbated
231 // by the fact that we allocate the pair from the callee saves list,
232 // leading to excess spills and restores.
233 bool HexagonSubtarget::CallMutation::shouldTFRICallBind(
234       const HexagonInstrInfo &HII, const SUnit &Inst1,
235       const SUnit &Inst2) const {
236   if (Inst1.getInstr()->getOpcode() != Hexagon::A2_tfrpi)
237     return false;
238 
239   // TypeXTYPE are 64 bit operations.
240   unsigned Type = HII.getType(*Inst2.getInstr());
241   return Type == HexagonII::TypeS_2op || Type == HexagonII::TypeS_3op ||
242          Type == HexagonII::TypeALU64 || Type == HexagonII::TypeM;
243 }
244 
245 void HexagonSubtarget::CallMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
246   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
247   SUnit* LastSequentialCall = nullptr;
248   // Map from virtual register to physical register from the copy.
249   DenseMap<unsigned, unsigned> VRegHoldingReg;
250   // Map from the physical register to the instruction that uses virtual
251   // register. This is used to create the barrier edge.
252   DenseMap<unsigned, SUnit *> LastVRegUse;
253   auto &TRI = *DAG->MF.getSubtarget().getRegisterInfo();
254   auto &HII = *DAG->MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
255 
256   // Currently we only catch the situation when compare gets scheduled
257   // before preceding call.
258   for (unsigned su = 0, e = DAG->SUnits.size(); su != e; ++su) {
259     // Remember the call.
260     if (DAG->SUnits[su].getInstr()->isCall())
261       LastSequentialCall = &DAG->SUnits[su];
262     // Look for a compare that defines a predicate.
263     else if (DAG->SUnits[su].getInstr()->isCompare() && LastSequentialCall)
264       DAG->addEdge(&DAG->SUnits[su], SDep(LastSequentialCall, SDep::Barrier));
265     // Look for call and tfri* instructions.
266     else if (SchedPredsCloser && LastSequentialCall && su > 1 && su < e-1 &&
267              shouldTFRICallBind(HII, DAG->SUnits[su], DAG->SUnits[su+1]))
268       DAG->addEdge(&DAG->SUnits[su], SDep(&DAG->SUnits[su-1], SDep::Barrier));
269     // Prevent redundant register copies due to reads and writes of physical
270     // registers. The original motivation for this was the code generated
271     // between two calls, which are caused both the return value and the
272     // argument for the next call being in %r0.
273     // Example:
274     //   1: <call1>
275     //   2: %vreg = COPY %r0
276     //   3: <use of %vreg>
277     //   4: %r0 = ...
278     //   5: <call2>
279     // The scheduler would often swap 3 and 4, so an additional register is
280     // needed. This code inserts a Barrier dependence between 3 & 4 to prevent
281     // this.
282     // The code below checks for all the physical registers, not just R0/D0/V0.
283     else if (SchedRetvalOptimization) {
284       const MachineInstr *MI = DAG->SUnits[su].getInstr();
285       if (MI->isCopy() &&
286           Register::isPhysicalRegister(MI->getOperand(1).getReg())) {
287         // %vregX = COPY %r0
288         VRegHoldingReg[MI->getOperand(0).getReg()] = MI->getOperand(1).getReg();
289         LastVRegUse.erase(MI->getOperand(1).getReg());
290       } else {
291         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
292           const MachineOperand &MO = MI->getOperand(i);
293           if (!MO.isReg())
294             continue;
295           if (MO.isUse() && !MI->isCopy() &&
296               VRegHoldingReg.count(MO.getReg())) {
297             // <use of %vregX>
298             LastVRegUse[VRegHoldingReg[MO.getReg()]] = &DAG->SUnits[su];
299           } else if (MO.isDef() && Register::isPhysicalRegister(MO.getReg())) {
300             for (MCRegAliasIterator AI(MO.getReg(), &TRI, true); AI.isValid();
301                  ++AI) {
302               if (LastVRegUse.count(*AI) &&
303                   LastVRegUse[*AI] != &DAG->SUnits[su])
304                 // %r0 = ...
305                 DAG->addEdge(&DAG->SUnits[su], SDep(LastVRegUse[*AI], SDep::Barrier));
306               LastVRegUse.erase(*AI);
307             }
308           }
309         }
310       }
311     }
312   }
313 }
314 
315 void HexagonSubtarget::BankConflictMutation::apply(ScheduleDAGInstrs *DAG) {
316   if (!EnableCheckBankConflict)
317     return;
318 
319   const auto &HII = static_cast<const HexagonInstrInfo&>(*DAG->TII);
320 
321   // Create artificial edges between loads that could likely cause a bank
322   // conflict. Since such loads would normally not have any dependency
323   // between them, we cannot rely on existing edges.
324   for (unsigned i = 0, e = DAG->SUnits.size(); i != e; ++i) {
325     SUnit &S0 = DAG->SUnits[i];
326     MachineInstr &L0 = *S0.getInstr();
327     if (!L0.mayLoad() || L0.mayStore() ||
328         HII.getAddrMode(L0) != HexagonII::BaseImmOffset)
329       continue;
330     int64_t Offset0;
331     unsigned Size0;
332     MachineOperand *BaseOp0 = HII.getBaseAndOffset(L0, Offset0, Size0);
333     // Is the access size is longer than the L1 cache line, skip the check.
334     if (BaseOp0 == nullptr || !BaseOp0->isReg() || Size0 >= 32)
335       continue;
336     // Scan only up to 32 instructions ahead (to avoid n^2 complexity).
337     for (unsigned j = i+1, m = std::min(i+32, e); j != m; ++j) {
338       SUnit &S1 = DAG->SUnits[j];
339       MachineInstr &L1 = *S1.getInstr();
340       if (!L1.mayLoad() || L1.mayStore() ||
341           HII.getAddrMode(L1) != HexagonII::BaseImmOffset)
342         continue;
343       int64_t Offset1;
344       unsigned Size1;
345       MachineOperand *BaseOp1 = HII.getBaseAndOffset(L1, Offset1, Size1);
346       if (BaseOp1 == nullptr || !BaseOp1->isReg() || Size1 >= 32 ||
347           BaseOp0->getReg() != BaseOp1->getReg())
348         continue;
349       // Check bits 3 and 4 of the offset: if they differ, a bank conflict
350       // is unlikely.
351       if (((Offset0 ^ Offset1) & 0x18) != 0)
352         continue;
353       // Bits 3 and 4 are the same, add an artificial edge and set extra
354       // latency.
355       SDep A(&S0, SDep::Artificial);
356       A.setLatency(1);
357       S1.addPred(A, true);
358     }
359   }
360 }
361 
362 /// Enable use of alias analysis during code generation (during MI
363 /// scheduling, DAGCombine, etc.).
364 bool HexagonSubtarget::useAA() const {
365   if (OptLevel != CodeGenOpt::None)
366     return true;
367   return false;
368 }
369 
370 /// Perform target specific adjustments to the latency of a schedule
371 /// dependency.
372 void HexagonSubtarget::adjustSchedDependency(SUnit *Src, int SrcOpIdx,
373                                              SUnit *Dst, int DstOpIdx,
374                                              SDep &Dep) const {
375   if (!Src->isInstr() || !Dst->isInstr())
376     return;
377 
378   MachineInstr *SrcInst = Src->getInstr();
379   MachineInstr *DstInst = Dst->getInstr();
380   const HexagonInstrInfo *QII = getInstrInfo();
381 
382   // Instructions with .new operands have zero latency.
383   SmallSet<SUnit *, 4> ExclSrc;
384   SmallSet<SUnit *, 4> ExclDst;
385   if (QII->canExecuteInBundle(*SrcInst, *DstInst) &&
386       isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
387     Dep.setLatency(0);
388     return;
389   }
390 
391   if (!hasV60Ops())
392     return;
393 
394   // Set the latency for a copy to zero since we hope that is will get removed.
395   if (DstInst->isCopy())
396     Dep.setLatency(0);
397 
398   // If it's a REG_SEQUENCE/COPY, use its destination instruction to determine
399   // the correct latency.
400   if ((DstInst->isRegSequence() || DstInst->isCopy()) && Dst->NumSuccs == 1) {
401     Register DReg = DstInst->getOperand(0).getReg();
402     MachineInstr *DDst = Dst->Succs[0].getSUnit()->getInstr();
403     unsigned UseIdx = -1;
404     for (unsigned OpNum = 0; OpNum < DDst->getNumOperands(); OpNum++) {
405       const MachineOperand &MO = DDst->getOperand(OpNum);
406       if (MO.isReg() && MO.getReg() && MO.isUse() && MO.getReg() == DReg) {
407         UseIdx = OpNum;
408         break;
409       }
410     }
411     int DLatency = (InstrInfo.getOperandLatency(&InstrItins, *SrcInst,
412                                                 0, *DDst, UseIdx));
413     DLatency = std::max(DLatency, 0);
414     Dep.setLatency((unsigned)DLatency);
415   }
416 
417   // Try to schedule uses near definitions to generate .cur.
418   ExclSrc.clear();
419   ExclDst.clear();
420   if (EnableDotCurSched && QII->isToBeScheduledASAP(*SrcInst, *DstInst) &&
421       isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
422     Dep.setLatency(0);
423     return;
424   }
425 
426   updateLatency(*SrcInst, *DstInst, Dep);
427 }
428 
429 void HexagonSubtarget::getPostRAMutations(
430     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
431   Mutations.push_back(std::make_unique<UsrOverflowMutation>());
432   Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
433   Mutations.push_back(std::make_unique<BankConflictMutation>());
434 }
435 
436 void HexagonSubtarget::getSMSMutations(
437     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
438   Mutations.push_back(std::make_unique<UsrOverflowMutation>());
439   Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
440 }
441 
442 // Pin the vtable to this file.
443 void HexagonSubtarget::anchor() {}
444 
445 bool HexagonSubtarget::enableMachineScheduler() const {
446   if (DisableHexagonMISched.getNumOccurrences())
447     return !DisableHexagonMISched;
448   return true;
449 }
450 
451 bool HexagonSubtarget::usePredicatedCalls() const {
452   return EnablePredicatedCalls;
453 }
454 
455 void HexagonSubtarget::updateLatency(MachineInstr &SrcInst,
456       MachineInstr &DstInst, SDep &Dep) const {
457   if (Dep.isArtificial()) {
458     Dep.setLatency(1);
459     return;
460   }
461 
462   if (!hasV60Ops())
463     return;
464 
465   auto &QII = static_cast<const HexagonInstrInfo&>(*getInstrInfo());
466 
467   // BSB scheduling.
468   if (QII.isHVXVec(SrcInst) || useBSBScheduling())
469     Dep.setLatency((Dep.getLatency() + 1) >> 1);
470 }
471 
472 void HexagonSubtarget::restoreLatency(SUnit *Src, SUnit *Dst) const {
473   MachineInstr *SrcI = Src->getInstr();
474   for (auto &I : Src->Succs) {
475     if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
476       continue;
477     Register DepR = I.getReg();
478     int DefIdx = -1;
479     for (unsigned OpNum = 0; OpNum < SrcI->getNumOperands(); OpNum++) {
480       const MachineOperand &MO = SrcI->getOperand(OpNum);
481       bool IsSameOrSubReg = false;
482       if (MO.isReg()) {
483         Register MOReg = MO.getReg();
484         if (DepR.isVirtual()) {
485           IsSameOrSubReg = (MOReg == DepR);
486         } else {
487           IsSameOrSubReg = getRegisterInfo()->isSubRegisterEq(DepR, MOReg);
488         }
489         if (MO.isDef() && IsSameOrSubReg)
490           DefIdx = OpNum;
491       }
492     }
493     assert(DefIdx >= 0 && "Def Reg not found in Src MI");
494     MachineInstr *DstI = Dst->getInstr();
495     SDep T = I;
496     for (unsigned OpNum = 0; OpNum < DstI->getNumOperands(); OpNum++) {
497       const MachineOperand &MO = DstI->getOperand(OpNum);
498       if (MO.isReg() && MO.isUse() && MO.getReg() == DepR) {
499         int Latency = (InstrInfo.getOperandLatency(&InstrItins, *SrcI,
500                                                    DefIdx, *DstI, OpNum));
501 
502         // For some instructions (ex: COPY), we might end up with < 0 latency
503         // as they don't have any Itinerary class associated with them.
504         Latency = std::max(Latency, 0);
505 
506         I.setLatency(Latency);
507         updateLatency(*SrcI, *DstI, I);
508       }
509     }
510 
511     // Update the latency of opposite edge too.
512     T.setSUnit(Src);
513     auto F = std::find(Dst->Preds.begin(), Dst->Preds.end(), T);
514     assert(F != Dst->Preds.end());
515     F->setLatency(I.getLatency());
516   }
517 }
518 
519 /// Change the latency between the two SUnits.
520 void HexagonSubtarget::changeLatency(SUnit *Src, SUnit *Dst, unsigned Lat)
521       const {
522   for (auto &I : Src->Succs) {
523     if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
524       continue;
525     SDep T = I;
526     I.setLatency(Lat);
527 
528     // Update the latency of opposite edge too.
529     T.setSUnit(Src);
530     auto F = std::find(Dst->Preds.begin(), Dst->Preds.end(), T);
531     assert(F != Dst->Preds.end());
532     F->setLatency(Lat);
533   }
534 }
535 
536 /// If the SUnit has a zero latency edge, return the other SUnit.
537 static SUnit *getZeroLatency(SUnit *N, SmallVector<SDep, 4> &Deps) {
538   for (auto &I : Deps)
539     if (I.isAssignedRegDep() && I.getLatency() == 0 &&
540         !I.getSUnit()->getInstr()->isPseudo())
541       return I.getSUnit();
542   return nullptr;
543 }
544 
545 // Return true if these are the best two instructions to schedule
546 // together with a zero latency. Only one dependence should have a zero
547 // latency. If there are multiple choices, choose the best, and change
548 // the others, if needed.
549 bool HexagonSubtarget::isBestZeroLatency(SUnit *Src, SUnit *Dst,
550       const HexagonInstrInfo *TII, SmallSet<SUnit*, 4> &ExclSrc,
551       SmallSet<SUnit*, 4> &ExclDst) const {
552   MachineInstr &SrcInst = *Src->getInstr();
553   MachineInstr &DstInst = *Dst->getInstr();
554 
555   // Ignore Boundary SU nodes as these have null instructions.
556   if (Dst->isBoundaryNode())
557     return false;
558 
559   if (SrcInst.isPHI() || DstInst.isPHI())
560     return false;
561 
562   if (!TII->isToBeScheduledASAP(SrcInst, DstInst) &&
563       !TII->canExecuteInBundle(SrcInst, DstInst))
564     return false;
565 
566   // The architecture doesn't allow three dependent instructions in the same
567   // packet. So, if the destination has a zero latency successor, then it's
568   // not a candidate for a zero latency predecessor.
569   if (getZeroLatency(Dst, Dst->Succs) != nullptr)
570     return false;
571 
572   // Check if the Dst instruction is the best candidate first.
573   SUnit *Best = nullptr;
574   SUnit *DstBest = nullptr;
575   SUnit *SrcBest = getZeroLatency(Dst, Dst->Preds);
576   if (SrcBest == nullptr || Src->NodeNum >= SrcBest->NodeNum) {
577     // Check that Src doesn't have a better candidate.
578     DstBest = getZeroLatency(Src, Src->Succs);
579     if (DstBest == nullptr || Dst->NodeNum <= DstBest->NodeNum)
580       Best = Dst;
581   }
582   if (Best != Dst)
583     return false;
584 
585   // The caller frequently adds the same dependence twice. If so, then
586   // return true for this case too.
587   if ((Src == SrcBest && Dst == DstBest ) ||
588       (SrcBest == nullptr && Dst == DstBest) ||
589       (Src == SrcBest && Dst == nullptr))
590     return true;
591 
592   // Reassign the latency for the previous bests, which requires setting
593   // the dependence edge in both directions.
594   if (SrcBest != nullptr) {
595     if (!hasV60Ops())
596       changeLatency(SrcBest, Dst, 1);
597     else
598       restoreLatency(SrcBest, Dst);
599   }
600   if (DstBest != nullptr) {
601     if (!hasV60Ops())
602       changeLatency(Src, DstBest, 1);
603     else
604       restoreLatency(Src, DstBest);
605   }
606 
607   // Attempt to find another opprotunity for zero latency in a different
608   // dependence.
609   if (SrcBest && DstBest)
610     // If there is an edge from SrcBest to DstBst, then try to change that
611     // to 0 now.
612     changeLatency(SrcBest, DstBest, 0);
613   else if (DstBest) {
614     // Check if the previous best destination instruction has a new zero
615     // latency dependence opportunity.
616     ExclSrc.insert(Src);
617     for (auto &I : DstBest->Preds)
618       if (ExclSrc.count(I.getSUnit()) == 0 &&
619           isBestZeroLatency(I.getSUnit(), DstBest, TII, ExclSrc, ExclDst))
620         changeLatency(I.getSUnit(), DstBest, 0);
621   } else if (SrcBest) {
622     // Check if previous best source instruction has a new zero latency
623     // dependence opportunity.
624     ExclDst.insert(Dst);
625     for (auto &I : SrcBest->Succs)
626       if (ExclDst.count(I.getSUnit()) == 0 &&
627           isBestZeroLatency(SrcBest, I.getSUnit(), TII, ExclSrc, ExclDst))
628         changeLatency(SrcBest, I.getSUnit(), 0);
629   }
630 
631   return true;
632 }
633 
634 unsigned HexagonSubtarget::getL1CacheLineSize() const {
635   return 32;
636 }
637 
638 unsigned HexagonSubtarget::getL1PrefetchDistance() const {
639   return 32;
640 }
641 
642 bool HexagonSubtarget::enableSubRegLiveness() const {
643   return EnableSubregLiveness;
644 }
645