Home | History | Annotate | Line # | Download | only in Hexagon
      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::is_contained(ElemTypes, Ty);
    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::is_contained(ElemTypes, ElemTy);
    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   // The given type may be something like <17 x i32>, which is not MVT,
    172   // but can be represented as (non-simple) EVT.
    173   EVT Ty = EVT::getEVT(VecTy, /*HandleUnknown*/false);
    174   if (Ty.getSizeInBits() <= 64 || !Ty.getVectorElementType().isSimple())
    175     return false;
    176 
    177   auto isHvxTy = [this, IncludeBool](MVT SimpleTy) {
    178     if (isHVXVectorType(SimpleTy, IncludeBool))
    179       return true;
    180     auto Action = getTargetLowering()->getPreferredVectorAction(SimpleTy);
    181     return Action == TargetLoweringBase::TypeWidenVector;
    182   };
    183 
    184   // Round up EVT to have power-of-2 elements, and keep checking if it
    185   // qualifies for HVX, dividing it in half after each step.
    186   MVT ElemTy = Ty.getVectorElementType().getSimpleVT();
    187   unsigned VecLen = PowerOf2Ceil(Ty.getVectorNumElements());
    188   while (ElemTy.getSizeInBits() * VecLen > 64) {
    189     MVT SimpleTy = MVT::getVectorVT(ElemTy, VecLen);
    190     if (SimpleTy.isValid() && isHvxTy(SimpleTy))
    191       return true;
    192     VecLen /= 2;
    193   }
    194 
    195   return false;
    196 }
    197 
    198 void HexagonSubtarget::UsrOverflowMutation::apply(ScheduleDAGInstrs *DAG) {
    199   for (SUnit &SU : DAG->SUnits) {
    200     if (!SU.isInstr())
    201       continue;
    202     SmallVector<SDep, 4> Erase;
    203     for (auto &D : SU.Preds)
    204       if (D.getKind() == SDep::Output && D.getReg() == Hexagon::USR_OVF)
    205         Erase.push_back(D);
    206     for (auto &E : Erase)
    207       SU.removePred(E);
    208   }
    209 }
    210 
    211 void HexagonSubtarget::HVXMemLatencyMutation::apply(ScheduleDAGInstrs *DAG) {
    212   for (SUnit &SU : DAG->SUnits) {
    213     // Update the latency of chain edges between v60 vector load or store
    214     // instructions to be 1. These instruction cannot be scheduled in the
    215     // same packet.
    216     MachineInstr &MI1 = *SU.getInstr();
    217     auto *QII = static_cast<const HexagonInstrInfo*>(DAG->TII);
    218     bool IsStoreMI1 = MI1.mayStore();
    219     bool IsLoadMI1 = MI1.mayLoad();
    220     if (!QII->isHVXVec(MI1) || !(IsStoreMI1 || IsLoadMI1))
    221       continue;
    222     for (SDep &SI : SU.Succs) {
    223       if (SI.getKind() != SDep::Order || SI.getLatency() != 0)
    224         continue;
    225       MachineInstr &MI2 = *SI.getSUnit()->getInstr();
    226       if (!QII->isHVXVec(MI2))
    227         continue;
    228       if ((IsStoreMI1 && MI2.mayStore()) || (IsLoadMI1 && MI2.mayLoad())) {
    229         SI.setLatency(1);
    230         SU.setHeightDirty();
    231         // Change the dependence in the opposite direction too.
    232         for (SDep &PI : SI.getSUnit()->Preds) {
    233           if (PI.getSUnit() != &SU || PI.getKind() != SDep::Order)
    234             continue;
    235           PI.setLatency(1);
    236           SI.getSUnit()->setDepthDirty();
    237         }
    238       }
    239     }
    240   }
    241 }
    242 
    243 // Check if a call and subsequent A2_tfrpi instructions should maintain
    244 // scheduling affinity. We are looking for the TFRI to be consumed in
    245 // the next instruction. This should help reduce the instances of
    246 // double register pairs being allocated and scheduled before a call
    247 // when not used until after the call. This situation is exacerbated
    248 // by the fact that we allocate the pair from the callee saves list,
    249 // leading to excess spills and restores.
    250 bool HexagonSubtarget::CallMutation::shouldTFRICallBind(
    251       const HexagonInstrInfo &HII, const SUnit &Inst1,
    252       const SUnit &Inst2) const {
    253   if (Inst1.getInstr()->getOpcode() != Hexagon::A2_tfrpi)
    254     return false;
    255 
    256   // TypeXTYPE are 64 bit operations.
    257   unsigned Type = HII.getType(*Inst2.getInstr());
    258   return Type == HexagonII::TypeS_2op || Type == HexagonII::TypeS_3op ||
    259          Type == HexagonII::TypeALU64 || Type == HexagonII::TypeM;
    260 }
    261 
    262 void HexagonSubtarget::CallMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
    263   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
    264   SUnit* LastSequentialCall = nullptr;
    265   // Map from virtual register to physical register from the copy.
    266   DenseMap<unsigned, unsigned> VRegHoldingReg;
    267   // Map from the physical register to the instruction that uses virtual
    268   // register. This is used to create the barrier edge.
    269   DenseMap<unsigned, SUnit *> LastVRegUse;
    270   auto &TRI = *DAG->MF.getSubtarget().getRegisterInfo();
    271   auto &HII = *DAG->MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
    272 
    273   // Currently we only catch the situation when compare gets scheduled
    274   // before preceding call.
    275   for (unsigned su = 0, e = DAG->SUnits.size(); su != e; ++su) {
    276     // Remember the call.
    277     if (DAG->SUnits[su].getInstr()->isCall())
    278       LastSequentialCall = &DAG->SUnits[su];
    279     // Look for a compare that defines a predicate.
    280     else if (DAG->SUnits[su].getInstr()->isCompare() && LastSequentialCall)
    281       DAG->addEdge(&DAG->SUnits[su], SDep(LastSequentialCall, SDep::Barrier));
    282     // Look for call and tfri* instructions.
    283     else if (SchedPredsCloser && LastSequentialCall && su > 1 && su < e-1 &&
    284              shouldTFRICallBind(HII, DAG->SUnits[su], DAG->SUnits[su+1]))
    285       DAG->addEdge(&DAG->SUnits[su], SDep(&DAG->SUnits[su-1], SDep::Barrier));
    286     // Prevent redundant register copies due to reads and writes of physical
    287     // registers. The original motivation for this was the code generated
    288     // between two calls, which are caused both the return value and the
    289     // argument for the next call being in %r0.
    290     // Example:
    291     //   1: <call1>
    292     //   2: %vreg = COPY %r0
    293     //   3: <use of %vreg>
    294     //   4: %r0 = ...
    295     //   5: <call2>
    296     // The scheduler would often swap 3 and 4, so an additional register is
    297     // needed. This code inserts a Barrier dependence between 3 & 4 to prevent
    298     // this.
    299     // The code below checks for all the physical registers, not just R0/D0/V0.
    300     else if (SchedRetvalOptimization) {
    301       const MachineInstr *MI = DAG->SUnits[su].getInstr();
    302       if (MI->isCopy() &&
    303           Register::isPhysicalRegister(MI->getOperand(1).getReg())) {
    304         // %vregX = COPY %r0
    305         VRegHoldingReg[MI->getOperand(0).getReg()] = MI->getOperand(1).getReg();
    306         LastVRegUse.erase(MI->getOperand(1).getReg());
    307       } else {
    308         for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    309           const MachineOperand &MO = MI->getOperand(i);
    310           if (!MO.isReg())
    311             continue;
    312           if (MO.isUse() && !MI->isCopy() &&
    313               VRegHoldingReg.count(MO.getReg())) {
    314             // <use of %vregX>
    315             LastVRegUse[VRegHoldingReg[MO.getReg()]] = &DAG->SUnits[su];
    316           } else if (MO.isDef() && Register::isPhysicalRegister(MO.getReg())) {
    317             for (MCRegAliasIterator AI(MO.getReg(), &TRI, true); AI.isValid();
    318                  ++AI) {
    319               if (LastVRegUse.count(*AI) &&
    320                   LastVRegUse[*AI] != &DAG->SUnits[su])
    321                 // %r0 = ...
    322                 DAG->addEdge(&DAG->SUnits[su], SDep(LastVRegUse[*AI], SDep::Barrier));
    323               LastVRegUse.erase(*AI);
    324             }
    325           }
    326         }
    327       }
    328     }
    329   }
    330 }
    331 
    332 void HexagonSubtarget::BankConflictMutation::apply(ScheduleDAGInstrs *DAG) {
    333   if (!EnableCheckBankConflict)
    334     return;
    335 
    336   const auto &HII = static_cast<const HexagonInstrInfo&>(*DAG->TII);
    337 
    338   // Create artificial edges between loads that could likely cause a bank
    339   // conflict. Since such loads would normally not have any dependency
    340   // between them, we cannot rely on existing edges.
    341   for (unsigned i = 0, e = DAG->SUnits.size(); i != e; ++i) {
    342     SUnit &S0 = DAG->SUnits[i];
    343     MachineInstr &L0 = *S0.getInstr();
    344     if (!L0.mayLoad() || L0.mayStore() ||
    345         HII.getAddrMode(L0) != HexagonII::BaseImmOffset)
    346       continue;
    347     int64_t Offset0;
    348     unsigned Size0;
    349     MachineOperand *BaseOp0 = HII.getBaseAndOffset(L0, Offset0, Size0);
    350     // Is the access size is longer than the L1 cache line, skip the check.
    351     if (BaseOp0 == nullptr || !BaseOp0->isReg() || Size0 >= 32)
    352       continue;
    353     // Scan only up to 32 instructions ahead (to avoid n^2 complexity).
    354     for (unsigned j = i+1, m = std::min(i+32, e); j != m; ++j) {
    355       SUnit &S1 = DAG->SUnits[j];
    356       MachineInstr &L1 = *S1.getInstr();
    357       if (!L1.mayLoad() || L1.mayStore() ||
    358           HII.getAddrMode(L1) != HexagonII::BaseImmOffset)
    359         continue;
    360       int64_t Offset1;
    361       unsigned Size1;
    362       MachineOperand *BaseOp1 = HII.getBaseAndOffset(L1, Offset1, Size1);
    363       if (BaseOp1 == nullptr || !BaseOp1->isReg() || Size1 >= 32 ||
    364           BaseOp0->getReg() != BaseOp1->getReg())
    365         continue;
    366       // Check bits 3 and 4 of the offset: if they differ, a bank conflict
    367       // is unlikely.
    368       if (((Offset0 ^ Offset1) & 0x18) != 0)
    369         continue;
    370       // Bits 3 and 4 are the same, add an artificial edge and set extra
    371       // latency.
    372       SDep A(&S0, SDep::Artificial);
    373       A.setLatency(1);
    374       S1.addPred(A, true);
    375     }
    376   }
    377 }
    378 
    379 /// Enable use of alias analysis during code generation (during MI
    380 /// scheduling, DAGCombine, etc.).
    381 bool HexagonSubtarget::useAA() const {
    382   if (OptLevel != CodeGenOpt::None)
    383     return true;
    384   return false;
    385 }
    386 
    387 /// Perform target specific adjustments to the latency of a schedule
    388 /// dependency.
    389 void HexagonSubtarget::adjustSchedDependency(SUnit *Src, int SrcOpIdx,
    390                                              SUnit *Dst, int DstOpIdx,
    391                                              SDep &Dep) const {
    392   if (!Src->isInstr() || !Dst->isInstr())
    393     return;
    394 
    395   MachineInstr *SrcInst = Src->getInstr();
    396   MachineInstr *DstInst = Dst->getInstr();
    397   const HexagonInstrInfo *QII = getInstrInfo();
    398 
    399   // Instructions with .new operands have zero latency.
    400   SmallSet<SUnit *, 4> ExclSrc;
    401   SmallSet<SUnit *, 4> ExclDst;
    402   if (QII->canExecuteInBundle(*SrcInst, *DstInst) &&
    403       isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
    404     Dep.setLatency(0);
    405     return;
    406   }
    407 
    408   if (!hasV60Ops())
    409     return;
    410 
    411   // Set the latency for a copy to zero since we hope that is will get removed.
    412   if (DstInst->isCopy())
    413     Dep.setLatency(0);
    414 
    415   // If it's a REG_SEQUENCE/COPY, use its destination instruction to determine
    416   // the correct latency.
    417   if ((DstInst->isRegSequence() || DstInst->isCopy()) && Dst->NumSuccs == 1) {
    418     Register DReg = DstInst->getOperand(0).getReg();
    419     MachineInstr *DDst = Dst->Succs[0].getSUnit()->getInstr();
    420     unsigned UseIdx = -1;
    421     for (unsigned OpNum = 0; OpNum < DDst->getNumOperands(); OpNum++) {
    422       const MachineOperand &MO = DDst->getOperand(OpNum);
    423       if (MO.isReg() && MO.getReg() && MO.isUse() && MO.getReg() == DReg) {
    424         UseIdx = OpNum;
    425         break;
    426       }
    427     }
    428     int DLatency = (InstrInfo.getOperandLatency(&InstrItins, *SrcInst,
    429                                                 0, *DDst, UseIdx));
    430     DLatency = std::max(DLatency, 0);
    431     Dep.setLatency((unsigned)DLatency);
    432   }
    433 
    434   // Try to schedule uses near definitions to generate .cur.
    435   ExclSrc.clear();
    436   ExclDst.clear();
    437   if (EnableDotCurSched && QII->isToBeScheduledASAP(*SrcInst, *DstInst) &&
    438       isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
    439     Dep.setLatency(0);
    440     return;
    441   }
    442 
    443   updateLatency(*SrcInst, *DstInst, Dep);
    444 }
    445 
    446 void HexagonSubtarget::getPostRAMutations(
    447     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
    448   Mutations.push_back(std::make_unique<UsrOverflowMutation>());
    449   Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
    450   Mutations.push_back(std::make_unique<BankConflictMutation>());
    451 }
    452 
    453 void HexagonSubtarget::getSMSMutations(
    454     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
    455   Mutations.push_back(std::make_unique<UsrOverflowMutation>());
    456   Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
    457 }
    458 
    459 // Pin the vtable to this file.
    460 void HexagonSubtarget::anchor() {}
    461 
    462 bool HexagonSubtarget::enableMachineScheduler() const {
    463   if (DisableHexagonMISched.getNumOccurrences())
    464     return !DisableHexagonMISched;
    465   return true;
    466 }
    467 
    468 bool HexagonSubtarget::usePredicatedCalls() const {
    469   return EnablePredicatedCalls;
    470 }
    471 
    472 void HexagonSubtarget::updateLatency(MachineInstr &SrcInst,
    473       MachineInstr &DstInst, SDep &Dep) const {
    474   if (Dep.isArtificial()) {
    475     Dep.setLatency(1);
    476     return;
    477   }
    478 
    479   if (!hasV60Ops())
    480     return;
    481 
    482   auto &QII = static_cast<const HexagonInstrInfo&>(*getInstrInfo());
    483 
    484   // BSB scheduling.
    485   if (QII.isHVXVec(SrcInst) || useBSBScheduling())
    486     Dep.setLatency((Dep.getLatency() + 1) >> 1);
    487 }
    488 
    489 void HexagonSubtarget::restoreLatency(SUnit *Src, SUnit *Dst) const {
    490   MachineInstr *SrcI = Src->getInstr();
    491   for (auto &I : Src->Succs) {
    492     if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
    493       continue;
    494     Register DepR = I.getReg();
    495     int DefIdx = -1;
    496     for (unsigned OpNum = 0; OpNum < SrcI->getNumOperands(); OpNum++) {
    497       const MachineOperand &MO = SrcI->getOperand(OpNum);
    498       bool IsSameOrSubReg = false;
    499       if (MO.isReg()) {
    500         Register MOReg = MO.getReg();
    501         if (DepR.isVirtual()) {
    502           IsSameOrSubReg = (MOReg == DepR);
    503         } else {
    504           IsSameOrSubReg = getRegisterInfo()->isSubRegisterEq(DepR, MOReg);
    505         }
    506         if (MO.isDef() && IsSameOrSubReg)
    507           DefIdx = OpNum;
    508       }
    509     }
    510     assert(DefIdx >= 0 && "Def Reg not found in Src MI");
    511     MachineInstr *DstI = Dst->getInstr();
    512     SDep T = I;
    513     for (unsigned OpNum = 0; OpNum < DstI->getNumOperands(); OpNum++) {
    514       const MachineOperand &MO = DstI->getOperand(OpNum);
    515       if (MO.isReg() && MO.isUse() && MO.getReg() == DepR) {
    516         int Latency = (InstrInfo.getOperandLatency(&InstrItins, *SrcI,
    517                                                    DefIdx, *DstI, OpNum));
    518 
    519         // For some instructions (ex: COPY), we might end up with < 0 latency
    520         // as they don't have any Itinerary class associated with them.
    521         Latency = std::max(Latency, 0);
    522 
    523         I.setLatency(Latency);
    524         updateLatency(*SrcI, *DstI, I);
    525       }
    526     }
    527 
    528     // Update the latency of opposite edge too.
    529     T.setSUnit(Src);
    530     auto F = find(Dst->Preds, T);
    531     assert(F != Dst->Preds.end());
    532     F->setLatency(I.getLatency());
    533   }
    534 }
    535 
    536 /// Change the latency between the two SUnits.
    537 void HexagonSubtarget::changeLatency(SUnit *Src, SUnit *Dst, unsigned Lat)
    538       const {
    539   for (auto &I : Src->Succs) {
    540     if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
    541       continue;
    542     SDep T = I;
    543     I.setLatency(Lat);
    544 
    545     // Update the latency of opposite edge too.
    546     T.setSUnit(Src);
    547     auto F = find(Dst->Preds, T);
    548     assert(F != Dst->Preds.end());
    549     F->setLatency(Lat);
    550   }
    551 }
    552 
    553 /// If the SUnit has a zero latency edge, return the other SUnit.
    554 static SUnit *getZeroLatency(SUnit *N, SmallVector<SDep, 4> &Deps) {
    555   for (auto &I : Deps)
    556     if (I.isAssignedRegDep() && I.getLatency() == 0 &&
    557         !I.getSUnit()->getInstr()->isPseudo())
    558       return I.getSUnit();
    559   return nullptr;
    560 }
    561 
    562 // Return true if these are the best two instructions to schedule
    563 // together with a zero latency. Only one dependence should have a zero
    564 // latency. If there are multiple choices, choose the best, and change
    565 // the others, if needed.
    566 bool HexagonSubtarget::isBestZeroLatency(SUnit *Src, SUnit *Dst,
    567       const HexagonInstrInfo *TII, SmallSet<SUnit*, 4> &ExclSrc,
    568       SmallSet<SUnit*, 4> &ExclDst) const {
    569   MachineInstr &SrcInst = *Src->getInstr();
    570   MachineInstr &DstInst = *Dst->getInstr();
    571 
    572   // Ignore Boundary SU nodes as these have null instructions.
    573   if (Dst->isBoundaryNode())
    574     return false;
    575 
    576   if (SrcInst.isPHI() || DstInst.isPHI())
    577     return false;
    578 
    579   if (!TII->isToBeScheduledASAP(SrcInst, DstInst) &&
    580       !TII->canExecuteInBundle(SrcInst, DstInst))
    581     return false;
    582 
    583   // The architecture doesn't allow three dependent instructions in the same
    584   // packet. So, if the destination has a zero latency successor, then it's
    585   // not a candidate for a zero latency predecessor.
    586   if (getZeroLatency(Dst, Dst->Succs) != nullptr)
    587     return false;
    588 
    589   // Check if the Dst instruction is the best candidate first.
    590   SUnit *Best = nullptr;
    591   SUnit *DstBest = nullptr;
    592   SUnit *SrcBest = getZeroLatency(Dst, Dst->Preds);
    593   if (SrcBest == nullptr || Src->NodeNum >= SrcBest->NodeNum) {
    594     // Check that Src doesn't have a better candidate.
    595     DstBest = getZeroLatency(Src, Src->Succs);
    596     if (DstBest == nullptr || Dst->NodeNum <= DstBest->NodeNum)
    597       Best = Dst;
    598   }
    599   if (Best != Dst)
    600     return false;
    601 
    602   // The caller frequently adds the same dependence twice. If so, then
    603   // return true for this case too.
    604   if ((Src == SrcBest && Dst == DstBest ) ||
    605       (SrcBest == nullptr && Dst == DstBest) ||
    606       (Src == SrcBest && Dst == nullptr))
    607     return true;
    608 
    609   // Reassign the latency for the previous bests, which requires setting
    610   // the dependence edge in both directions.
    611   if (SrcBest != nullptr) {
    612     if (!hasV60Ops())
    613       changeLatency(SrcBest, Dst, 1);
    614     else
    615       restoreLatency(SrcBest, Dst);
    616   }
    617   if (DstBest != nullptr) {
    618     if (!hasV60Ops())
    619       changeLatency(Src, DstBest, 1);
    620     else
    621       restoreLatency(Src, DstBest);
    622   }
    623 
    624   // Attempt to find another opprotunity for zero latency in a different
    625   // dependence.
    626   if (SrcBest && DstBest)
    627     // If there is an edge from SrcBest to DstBst, then try to change that
    628     // to 0 now.
    629     changeLatency(SrcBest, DstBest, 0);
    630   else if (DstBest) {
    631     // Check if the previous best destination instruction has a new zero
    632     // latency dependence opportunity.
    633     ExclSrc.insert(Src);
    634     for (auto &I : DstBest->Preds)
    635       if (ExclSrc.count(I.getSUnit()) == 0 &&
    636           isBestZeroLatency(I.getSUnit(), DstBest, TII, ExclSrc, ExclDst))
    637         changeLatency(I.getSUnit(), DstBest, 0);
    638   } else if (SrcBest) {
    639     // Check if previous best source instruction has a new zero latency
    640     // dependence opportunity.
    641     ExclDst.insert(Dst);
    642     for (auto &I : SrcBest->Succs)
    643       if (ExclDst.count(I.getSUnit()) == 0 &&
    644           isBestZeroLatency(SrcBest, I.getSUnit(), TII, ExclSrc, ExclDst))
    645         changeLatency(SrcBest, I.getSUnit(), 0);
    646   }
    647 
    648   return true;
    649 }
    650 
    651 unsigned HexagonSubtarget::getL1CacheLineSize() const {
    652   return 32;
    653 }
    654 
    655 unsigned HexagonSubtarget::getL1PrefetchDistance() const {
    656   return 32;
    657 }
    658 
    659 bool HexagonSubtarget::enableSubRegLiveness() const {
    660   return EnableSubregLiveness;
    661 }
    662