#include "HexagonSubtarget.h"
#include "Hexagon.h"
#include "HexagonInstrInfo.h"
#include "HexagonRegisterInfo.h"
#include "MCTargetDesc/HexagonMCTargetDesc.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineScheduler.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/CodeGen/ScheduleDAGInstrs.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <map>
using namespace llvm;
#define DEBUG_TYPE "hexagon-subtarget"
#define GET_SUBTARGETINFO_CTOR
#define GET_SUBTARGETINFO_TARGET_DESC
#include "HexagonGenSubtargetInfo.inc"
static cl::opt<bool> EnableBSBSched("enable-bsb-sched", cl::Hidden,
cl::init(true));
static cl::opt<bool> EnableTCLatencySched("enable-tc-latency-sched", cl::Hidden,
cl::init(false));
static cl::opt<bool>
EnableDotCurSched("enable-cur-sched", cl::Hidden, cl::init(true),
cl::desc("Enable the scheduler to generate .cur"));
static cl::opt<bool>
DisableHexagonMISched("disable-hexagon-misched", cl::Hidden,
cl::desc("Disable Hexagon MI Scheduling"));
static cl::opt<bool> EnableSubregLiveness(
"hexagon-subreg-liveness", cl::Hidden, cl::init(true),
cl::desc("Enable subregister liveness tracking for Hexagon"));
static cl::opt<bool> OverrideLongCalls(
"hexagon-long-calls", cl::Hidden,
cl::desc("If present, forces/disables the use of long calls"));
static cl::opt<bool>
EnablePredicatedCalls("hexagon-pred-calls", cl::Hidden,
cl::desc("Consider calls to be predicable"));
static cl::opt<bool> SchedPredsCloser("sched-preds-closer", cl::Hidden,
cl::init(true));
static cl::opt<bool> SchedRetvalOptimization("sched-retval-optimization",
cl::Hidden, cl::init(true));
static cl::opt<bool> EnableCheckBankConflict(
"hexagon-check-bank-conflict", cl::Hidden, cl::init(true),
cl::desc("Enable checking for cache bank conflicts"));
static cl::opt<bool> EnableV68FloatCodeGen(
"force-hvx-float", cl::Hidden,
cl::desc(
"Enable the code-generation for vector float instructions on v68."));
HexagonSubtarget::HexagonSubtarget(const Triple &TT, StringRef CPU,
StringRef FS, const TargetMachine &TM)
: HexagonGenSubtargetInfo(TT, CPU, CPU, FS),
OptLevel(TM.getOptLevel()),
CPUString(std::string(Hexagon_MC::selectHexagonCPU(CPU))),
TargetTriple(TT), InstrInfo(initializeSubtargetDependencies(CPU, FS)),
RegInfo(getHwMode()), TLInfo(TM, *this),
InstrItins(getInstrItineraryForCPU(CPUString)) {
Hexagon_MC::addArchSubtarget(this, FS);
assert(InstrItins.Itineraries != nullptr && "InstrItins not initialized");
}
HexagonSubtarget &
HexagonSubtarget::initializeSubtargetDependencies(StringRef CPU, StringRef FS) {
Optional<Hexagon::ArchEnum> ArchVer = Hexagon::getCpu(CPUString);
if (ArchVer)
HexagonArchVersion = *ArchVer;
else
llvm_unreachable("Unrecognized Hexagon processor version");
UseHVX128BOps = false;
UseHVX64BOps = false;
UseAudioOps = false;
UseLongCalls = false;
SubtargetFeatures Features(FS);
auto IsQFloatFS = [](StringRef F) {
return F == "+hvx-qfloat" || F == "-hvx-qfloat";
};
if (!llvm::count_if(Features.getFeatures(), IsQFloatFS)) {
auto getHvxVersion = [&Features](StringRef FS) -> StringRef {
for (StringRef F : llvm::reverse(Features.getFeatures())) {
if (F.startswith("+hvxv"))
return F;
}
for (StringRef F : llvm::reverse(Features.getFeatures())) {
if (F == "-hvx")
return StringRef();
if (F.startswith("+hvx") || F == "-hvx")
return F.take_front(4); }
return StringRef();
};
bool AddQFloat = false;
StringRef HvxVer = getHvxVersion(FS);
if (HvxVer.startswith("+hvxv")) {
int Ver = 0;
if (!HvxVer.drop_front(5).consumeInteger(10, Ver) && Ver >= 68)
AddQFloat = true;
} else if (HvxVer == "+hvx") {
if (hasV68Ops())
AddQFloat = true;
}
if (AddQFloat)
Features.AddFeature("+hvx-qfloat");
}
std::string FeatureString = Features.getString();
ParseSubtargetFeatures(CPUString, CPUString, FeatureString);
bool GreaterThanV68 = false;
if (useHVXV69Ops())
GreaterThanV68 = true;
if (!GreaterThanV68) {
if (EnableV68FloatCodeGen)
UseHVXFloatingPoint = true;
} else {
UseHVXFloatingPoint = true;
}
if (UseHVXQFloatOps && UseHVXIEEEFPOps && UseHVXFloatingPoint)
LLVM_DEBUG(
dbgs() << "Behavior is undefined for simultaneous qfloat and ieee hvx codegen...");
if (OverrideLongCalls.getPosition())
UseLongCalls = OverrideLongCalls;
UseBSBScheduling = hasV60Ops() && EnableBSBSched;
if (isTinyCore()) {
if (!EnableBSBSched.getPosition())
UseBSBScheduling = false;
}
FeatureBitset FeatureBits = getFeatureBits();
if (HexagonDisableDuplex)
setFeatureBits(FeatureBits.reset(Hexagon::FeatureDuplex));
setFeatureBits(Hexagon_MC::completeHVXFeatures(FeatureBits));
return *this;
}
bool HexagonSubtarget::isHVXElementType(MVT Ty, bool IncludeBool) const {
if (!useHVXOps())
return false;
if (Ty.isVector())
Ty = Ty.getVectorElementType();
if (IncludeBool && Ty == MVT::i1)
return true;
ArrayRef<MVT> ElemTypes = getHVXElementTypes();
return llvm::is_contained(ElemTypes, Ty);
}
bool HexagonSubtarget::isHVXVectorType(MVT VecTy, bool IncludeBool) const {
if (!VecTy.isVector() || !useHVXOps() || VecTy.isScalableVector())
return false;
MVT ElemTy = VecTy.getVectorElementType();
if (!IncludeBool && ElemTy == MVT::i1)
return false;
unsigned HwLen = getVectorLength();
unsigned NumElems = VecTy.getVectorNumElements();
ArrayRef<MVT> ElemTypes = getHVXElementTypes();
if (IncludeBool && ElemTy == MVT::i1) {
for (MVT T : ElemTypes)
if (NumElems * T.getSizeInBits() == 8 * HwLen)
return true;
return false;
}
unsigned VecWidth = VecTy.getSizeInBits();
if (VecWidth != 8 * HwLen && VecWidth != 16 * HwLen)
return false;
return llvm::is_contained(ElemTypes, ElemTy);
}
bool HexagonSubtarget::isTypeForHVX(Type *VecTy, bool IncludeBool) const {
if (!VecTy->isVectorTy() || isa<ScalableVectorType>(VecTy))
return false;
Type *ScalTy = VecTy->getScalarType();
if (!ScalTy->isIntegerTy() &&
!(ScalTy->isFloatingPointTy() && useHVXFloatingPoint()))
return false;
EVT Ty = EVT::getEVT(VecTy, false);
if (Ty.getSizeInBits() <= 64 || !Ty.getVectorElementType().isSimple())
return false;
auto isHvxTy = [this, IncludeBool](MVT SimpleTy) {
if (isHVXVectorType(SimpleTy, IncludeBool))
return true;
auto Action = getTargetLowering()->getPreferredVectorAction(SimpleTy);
return Action == TargetLoweringBase::TypeWidenVector;
};
MVT ElemTy = Ty.getVectorElementType().getSimpleVT();
unsigned VecLen = PowerOf2Ceil(Ty.getVectorNumElements());
while (ElemTy.getSizeInBits() * VecLen > 64) {
MVT SimpleTy = MVT::getVectorVT(ElemTy, VecLen);
if (SimpleTy.isValid() && isHvxTy(SimpleTy))
return true;
VecLen /= 2;
}
return false;
}
void HexagonSubtarget::UsrOverflowMutation::apply(ScheduleDAGInstrs *DAG) {
for (SUnit &SU : DAG->SUnits) {
if (!SU.isInstr())
continue;
SmallVector<SDep, 4> Erase;
for (auto &D : SU.Preds)
if (D.getKind() == SDep::Output && D.getReg() == Hexagon::USR_OVF)
Erase.push_back(D);
for (auto &E : Erase)
SU.removePred(E);
}
}
void HexagonSubtarget::HVXMemLatencyMutation::apply(ScheduleDAGInstrs *DAG) {
for (SUnit &SU : DAG->SUnits) {
MachineInstr &MI1 = *SU.getInstr();
auto *QII = static_cast<const HexagonInstrInfo*>(DAG->TII);
bool IsStoreMI1 = MI1.mayStore();
bool IsLoadMI1 = MI1.mayLoad();
if (!QII->isHVXVec(MI1) || !(IsStoreMI1 || IsLoadMI1))
continue;
for (SDep &SI : SU.Succs) {
if (SI.getKind() != SDep::Order || SI.getLatency() != 0)
continue;
MachineInstr &MI2 = *SI.getSUnit()->getInstr();
if (!QII->isHVXVec(MI2))
continue;
if ((IsStoreMI1 && MI2.mayStore()) || (IsLoadMI1 && MI2.mayLoad())) {
SI.setLatency(1);
SU.setHeightDirty();
for (SDep &PI : SI.getSUnit()->Preds) {
if (PI.getSUnit() != &SU || PI.getKind() != SDep::Order)
continue;
PI.setLatency(1);
SI.getSUnit()->setDepthDirty();
}
}
}
}
}
bool HexagonSubtarget::CallMutation::shouldTFRICallBind(
const HexagonInstrInfo &HII, const SUnit &Inst1,
const SUnit &Inst2) const {
if (Inst1.getInstr()->getOpcode() != Hexagon::A2_tfrpi)
return false;
unsigned Type = HII.getType(*Inst2.getInstr());
return Type == HexagonII::TypeS_2op || Type == HexagonII::TypeS_3op ||
Type == HexagonII::TypeALU64 || Type == HexagonII::TypeM;
}
void HexagonSubtarget::CallMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
SUnit* LastSequentialCall = nullptr;
DenseMap<unsigned, unsigned> VRegHoldingReg;
DenseMap<unsigned, SUnit *> LastVRegUse;
auto &TRI = *DAG->MF.getSubtarget().getRegisterInfo();
auto &HII = *DAG->MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
for (unsigned su = 0, e = DAG->SUnits.size(); su != e; ++su) {
if (DAG->SUnits[su].getInstr()->isCall())
LastSequentialCall = &DAG->SUnits[su];
else if (DAG->SUnits[su].getInstr()->isCompare() && LastSequentialCall)
DAG->addEdge(&DAG->SUnits[su], SDep(LastSequentialCall, SDep::Barrier));
else if (SchedPredsCloser && LastSequentialCall && su > 1 && su < e-1 &&
shouldTFRICallBind(HII, DAG->SUnits[su], DAG->SUnits[su+1]))
DAG->addEdge(&DAG->SUnits[su], SDep(&DAG->SUnits[su-1], SDep::Barrier));
else if (SchedRetvalOptimization) {
const MachineInstr *MI = DAG->SUnits[su].getInstr();
if (MI->isCopy() &&
Register::isPhysicalRegister(MI->getOperand(1).getReg())) {
VRegHoldingReg[MI->getOperand(0).getReg()] = MI->getOperand(1).getReg();
LastVRegUse.erase(MI->getOperand(1).getReg());
} else {
for (const MachineOperand &MO : MI->operands()) {
if (!MO.isReg())
continue;
if (MO.isUse() && !MI->isCopy() &&
VRegHoldingReg.count(MO.getReg())) {
LastVRegUse[VRegHoldingReg[MO.getReg()]] = &DAG->SUnits[su];
} else if (MO.isDef() && Register::isPhysicalRegister(MO.getReg())) {
for (MCRegAliasIterator AI(MO.getReg(), &TRI, true); AI.isValid();
++AI) {
if (LastVRegUse.count(*AI) &&
LastVRegUse[*AI] != &DAG->SUnits[su])
DAG->addEdge(&DAG->SUnits[su], SDep(LastVRegUse[*AI], SDep::Barrier));
LastVRegUse.erase(*AI);
}
}
}
}
}
}
}
void HexagonSubtarget::BankConflictMutation::apply(ScheduleDAGInstrs *DAG) {
if (!EnableCheckBankConflict)
return;
const auto &HII = static_cast<const HexagonInstrInfo&>(*DAG->TII);
for (unsigned i = 0, e = DAG->SUnits.size(); i != e; ++i) {
SUnit &S0 = DAG->SUnits[i];
MachineInstr &L0 = *S0.getInstr();
if (!L0.mayLoad() || L0.mayStore() ||
HII.getAddrMode(L0) != HexagonII::BaseImmOffset)
continue;
int64_t Offset0;
unsigned Size0;
MachineOperand *BaseOp0 = HII.getBaseAndOffset(L0, Offset0, Size0);
if (BaseOp0 == nullptr || !BaseOp0->isReg() || Size0 >= 32)
continue;
for (unsigned j = i+1, m = std::min(i+32, e); j != m; ++j) {
SUnit &S1 = DAG->SUnits[j];
MachineInstr &L1 = *S1.getInstr();
if (!L1.mayLoad() || L1.mayStore() ||
HII.getAddrMode(L1) != HexagonII::BaseImmOffset)
continue;
int64_t Offset1;
unsigned Size1;
MachineOperand *BaseOp1 = HII.getBaseAndOffset(L1, Offset1, Size1);
if (BaseOp1 == nullptr || !BaseOp1->isReg() || Size1 >= 32 ||
BaseOp0->getReg() != BaseOp1->getReg())
continue;
if (((Offset0 ^ Offset1) & 0x18) != 0)
continue;
SDep A(&S0, SDep::Artificial);
A.setLatency(1);
S1.addPred(A, true);
}
}
}
bool HexagonSubtarget::useAA() const {
if (OptLevel != CodeGenOpt::None)
return true;
return false;
}
void HexagonSubtarget::adjustSchedDependency(SUnit *Src, int SrcOpIdx,
SUnit *Dst, int DstOpIdx,
SDep &Dep) const {
if (!Src->isInstr() || !Dst->isInstr())
return;
MachineInstr *SrcInst = Src->getInstr();
MachineInstr *DstInst = Dst->getInstr();
const HexagonInstrInfo *QII = getInstrInfo();
SmallSet<SUnit *, 4> ExclSrc;
SmallSet<SUnit *, 4> ExclDst;
if (QII->canExecuteInBundle(*SrcInst, *DstInst) &&
isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
Dep.setLatency(0);
return;
}
if (DstInst->isCopy())
Dep.setLatency(0);
if ((DstInst->isRegSequence() || DstInst->isCopy())) {
Register DReg = DstInst->getOperand(0).getReg();
int DLatency = -1;
for (const auto &DDep : Dst->Succs) {
MachineInstr *DDst = DDep.getSUnit()->getInstr();
int UseIdx = -1;
for (unsigned OpNum = 0; OpNum < DDst->getNumOperands(); OpNum++) {
const MachineOperand &MO = DDst->getOperand(OpNum);
if (MO.isReg() && MO.getReg() && MO.isUse() && MO.getReg() == DReg) {
UseIdx = OpNum;
break;
}
}
if (UseIdx == -1)
continue;
int Latency = (InstrInfo.getOperandLatency(&InstrItins, *SrcInst, 0,
*DDst, UseIdx));
DLatency = (DLatency == -1) ? Latency : DLatency;
if (DLatency != Latency) {
DLatency = -1;
break;
}
}
DLatency = std::max(DLatency, 0);
Dep.setLatency((unsigned)DLatency);
}
ExclSrc.clear();
ExclDst.clear();
if (EnableDotCurSched && QII->isToBeScheduledASAP(*SrcInst, *DstInst) &&
isBestZeroLatency(Src, Dst, QII, ExclSrc, ExclDst)) {
Dep.setLatency(0);
return;
}
int Latency = Dep.getLatency();
bool IsArtificial = Dep.isArtificial();
Latency = updateLatency(*SrcInst, *DstInst, IsArtificial, Latency);
Dep.setLatency(Latency);
}
void HexagonSubtarget::getPostRAMutations(
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
Mutations.push_back(std::make_unique<UsrOverflowMutation>());
Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
Mutations.push_back(std::make_unique<BankConflictMutation>());
}
void HexagonSubtarget::getSMSMutations(
std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
Mutations.push_back(std::make_unique<UsrOverflowMutation>());
Mutations.push_back(std::make_unique<HVXMemLatencyMutation>());
}
void HexagonSubtarget::anchor() {}
bool HexagonSubtarget::enableMachineScheduler() const {
if (DisableHexagonMISched.getNumOccurrences())
return !DisableHexagonMISched;
return true;
}
bool HexagonSubtarget::usePredicatedCalls() const {
return EnablePredicatedCalls;
}
int HexagonSubtarget::updateLatency(MachineInstr &SrcInst,
MachineInstr &DstInst, bool IsArtificial,
int Latency) const {
if (IsArtificial)
return 1;
if (!hasV60Ops())
return Latency;
auto &QII = static_cast<const HexagonInstrInfo &>(*getInstrInfo());
if (QII.isHVXVec(SrcInst) || useBSBScheduling())
Latency = (Latency + 1) >> 1;
return Latency;
}
void HexagonSubtarget::restoreLatency(SUnit *Src, SUnit *Dst) const {
MachineInstr *SrcI = Src->getInstr();
for (auto &I : Src->Succs) {
if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
continue;
Register DepR = I.getReg();
int DefIdx = -1;
for (unsigned OpNum = 0; OpNum < SrcI->getNumOperands(); OpNum++) {
const MachineOperand &MO = SrcI->getOperand(OpNum);
bool IsSameOrSubReg = false;
if (MO.isReg()) {
Register MOReg = MO.getReg();
if (DepR.isVirtual()) {
IsSameOrSubReg = (MOReg == DepR);
} else {
IsSameOrSubReg = getRegisterInfo()->isSubRegisterEq(DepR, MOReg);
}
if (MO.isDef() && IsSameOrSubReg)
DefIdx = OpNum;
}
}
assert(DefIdx >= 0 && "Def Reg not found in Src MI");
MachineInstr *DstI = Dst->getInstr();
SDep T = I;
for (unsigned OpNum = 0; OpNum < DstI->getNumOperands(); OpNum++) {
const MachineOperand &MO = DstI->getOperand(OpNum);
if (MO.isReg() && MO.isUse() && MO.getReg() == DepR) {
int Latency = (InstrInfo.getOperandLatency(&InstrItins, *SrcI,
DefIdx, *DstI, OpNum));
Latency = std::max(Latency, 0);
bool IsArtificial = I.isArtificial();
Latency = updateLatency(*SrcI, *DstI, IsArtificial, Latency);
I.setLatency(Latency);
}
}
T.setSUnit(Src);
auto F = find(Dst->Preds, T);
assert(F != Dst->Preds.end());
F->setLatency(I.getLatency());
}
}
void HexagonSubtarget::changeLatency(SUnit *Src, SUnit *Dst, unsigned Lat)
const {
for (auto &I : Src->Succs) {
if (!I.isAssignedRegDep() || I.getSUnit() != Dst)
continue;
SDep T = I;
I.setLatency(Lat);
T.setSUnit(Src);
auto F = find(Dst->Preds, T);
assert(F != Dst->Preds.end());
F->setLatency(Lat);
}
}
static SUnit *getZeroLatency(SUnit *N, SmallVector<SDep, 4> &Deps) {
for (auto &I : Deps)
if (I.isAssignedRegDep() && I.getLatency() == 0 &&
!I.getSUnit()->getInstr()->isPseudo())
return I.getSUnit();
return nullptr;
}
bool HexagonSubtarget::isBestZeroLatency(SUnit *Src, SUnit *Dst,
const HexagonInstrInfo *TII, SmallSet<SUnit*, 4> &ExclSrc,
SmallSet<SUnit*, 4> &ExclDst) const {
MachineInstr &SrcInst = *Src->getInstr();
MachineInstr &DstInst = *Dst->getInstr();
if (Dst->isBoundaryNode())
return false;
if (SrcInst.isPHI() || DstInst.isPHI())
return false;
if (!TII->isToBeScheduledASAP(SrcInst, DstInst) &&
!TII->canExecuteInBundle(SrcInst, DstInst))
return false;
if (getZeroLatency(Dst, Dst->Succs) != nullptr)
return false;
SUnit *Best = nullptr;
SUnit *DstBest = nullptr;
SUnit *SrcBest = getZeroLatency(Dst, Dst->Preds);
if (SrcBest == nullptr || Src->NodeNum >= SrcBest->NodeNum) {
DstBest = getZeroLatency(Src, Src->Succs);
if (DstBest == nullptr || Dst->NodeNum <= DstBest->NodeNum)
Best = Dst;
}
if (Best != Dst)
return false;
if ((Src == SrcBest && Dst == DstBest ) ||
(SrcBest == nullptr && Dst == DstBest) ||
(Src == SrcBest && Dst == nullptr))
return true;
if (SrcBest != nullptr) {
if (!hasV60Ops())
changeLatency(SrcBest, Dst, 1);
else
restoreLatency(SrcBest, Dst);
}
if (DstBest != nullptr) {
if (!hasV60Ops())
changeLatency(Src, DstBest, 1);
else
restoreLatency(Src, DstBest);
}
if (SrcBest && DstBest)
changeLatency(SrcBest, DstBest, 0);
else if (DstBest) {
ExclSrc.insert(Src);
for (auto &I : DstBest->Preds)
if (ExclSrc.count(I.getSUnit()) == 0 &&
isBestZeroLatency(I.getSUnit(), DstBest, TII, ExclSrc, ExclDst))
changeLatency(I.getSUnit(), DstBest, 0);
} else if (SrcBest) {
ExclDst.insert(Dst);
for (auto &I : SrcBest->Succs)
if (ExclDst.count(I.getSUnit()) == 0 &&
isBestZeroLatency(SrcBest, I.getSUnit(), TII, ExclSrc, ExclDst))
changeLatency(SrcBest, I.getSUnit(), 0);
}
return true;
}
unsigned HexagonSubtarget::getL1CacheLineSize() const {
return 32;
}
unsigned HexagonSubtarget::getL1PrefetchDistance() const {
return 32;
}
bool HexagonSubtarget::enableSubRegLiveness() const {
return EnableSubregLiveness;
}