72#define DEBUG_TYPE "arm-low-overhead-loops"
73#define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
77 return PIdx != -1 &&
MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
81 return MI->findRegisterDefOperandIdx(ARM::VPR,
nullptr) != -1;
85 return MI.findRegisterUseOperandIdx(ARM::VPR,
nullptr) != -1;
100 if (
MI.isDebugInstr())
115 class PostOrderLoopTraversal {
117 MachineLoopInfo &MLI;
118 SmallPtrSet<MachineBasicBlock*, 4> Visited;
119 SmallVector<MachineBasicBlock*, 4> Order;
122 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
123 : ML(ML), MLI(MLI) { }
125 const SmallVectorImpl<MachineBasicBlock*> &getOrder()
const {
132 std::function<void(MachineBasicBlock *)> Search =
133 [
this, &Search](MachineBasicBlock *
MBB) ->
void {
134 if (!Visited.insert(
MBB).second)
138 if (!ML.contains(Succ))
142 Order.push_back(
MBB);
146 SmallVector<MachineBasicBlock*, 2> ExitBlocks;
147 ML.getExitBlocks(ExitBlocks);
151 Search(ML.getHeader());
154 std::function<void(MachineBasicBlock*)> GetPredecessor =
155 [
this, &GetPredecessor] (MachineBasicBlock *
MBB) ->
void {
156 Order.push_back(
MBB);
161 if (
auto *Preheader = ML.getLoopPreheader())
162 GetPredecessor(Preheader);
163 else if (
auto *Preheader = MLI.findLoopPreheader(&ML,
true,
true))
164 GetPredecessor(Preheader);
169 SmallVector<MachineInstr *, 4> Insts;
172 VPTBlock(MachineInstr *
MI) { Insts.push_back(
MI); }
176 bool hasUniformPredicate() {
return getDivergent() ==
nullptr; }
180 MachineInstr *getDivergent() {
181 SmallVectorImpl<MachineInstr *> &Insts = getInsts();
182 for (
unsigned i = 1; i < Insts.size(); ++i) {
183 MachineInstr *
Next = Insts[i];
190 void insert(MachineInstr *
MI) {
193 assert(Insts.size() <= 5 &&
"Too many instructions in VPT block!");
198 unsigned size()
const {
return Insts.size(); }
199 SmallVectorImpl<MachineInstr *> &getInsts() {
return Insts; }
208 friend struct LowOverheadLoop;
211 SetVector<MachineInstr *> CurrentPredicates;
212 std::map<MachineInstr *, SetVector<MachineInstr *>> PredicatedInsts;
215 assert((CurrentPredicates.size() ||
MI->getParent()->isLiveIn(ARM::VPR))
216 &&
"Can't begin VPT without predicate");
217 Blocks.emplace_back(
MI);
221 PredicatedInsts[
MI] = CurrentPredicates;
224 void addInst(MachineInstr *
MI) {
225 Blocks.back().insert(
MI);
226 PredicatedInsts[
MI] = CurrentPredicates;
229 void addPredicate(MachineInstr *
MI) {
231 CurrentPredicates.insert(
MI);
234 void resetPredicate(MachineInstr *
MI) {
236 CurrentPredicates.clear();
237 CurrentPredicates.insert(
MI);
242 bool isPredicatedOnVCTP(MachineInstr *
MI,
bool Exclusive =
false) {
243 SetVector<MachineInstr *> &Predicates = PredicatedInsts[
MI];
244 if (Exclusive && Predicates.
size() != 1)
253 bool isEntryPredicatedOnVCTP(VPTBlock &
Block,
bool Exclusive =
false) {
254 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
255 return isPredicatedOnVCTP(Insts.
front(), Exclusive);
261 bool hasImplicitlyValidVPT(VPTBlock &
Block, ReachingDefInfo &
RDI) {
262 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
263 MachineInstr *VPT = Insts.
front();
265 "Expected VPT block to begin with VPT/VPST");
275 return !MI->mayStore() && !MI->mayLoad() &&
276 !isHorizontalReduction(*MI) && !isVCTP(MI);
280 auto IsOperandPredicated = [&](MachineInstr *
MI,
unsigned Idx) {
282 return Op && PredicatedInsts.count(
Op) && isPredicatedOnVCTP(
Op);
285 auto IsOperandInvariant = [&](MachineInstr *
MI,
unsigned Idx) {
286 MachineOperand &MO =
MI->getOperand(Idx);
290 SmallPtrSet<MachineInstr *, 2> Defs;
295 for (
auto *Def : Defs)
303 return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
304 (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
305 (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
312 for (
auto &
Block : Blocks) {
313 if (isEntryPredicatedOnVCTP(
Block,
false) &&
315 return getVPTInstrPredicate(*MI) == ARMVCC::Else;
318 if (hasImplicitlyValidVPT(
Block,
RDI))
321 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
325 "Expected VPT block to start with a VPST or VPT!");
326 if (Insts.
size() == 2 && Insts.
front()->getOpcode() != ARM::MVE_VPST &&
330 for (
auto *
MI : Insts) {
340 if (!isPredicatedOnVCTP(
MI)) {
350 struct LowOverheadLoop {
353 MachineBasicBlock *Preheader =
nullptr;
354 MachineLoopInfo &MLI;
355 ReachingDefInfo &RDI;
356 const TargetRegisterInfo &TRI;
357 const ARMBaseInstrInfo &TII;
360 MachineBasicBlock *StartInsertBB =
nullptr;
361 MachineInstr *Start =
nullptr;
362 MachineInstr *Dec =
nullptr;
363 MachineInstr *End =
nullptr;
364 MachineOperand TPNumElements;
365 SmallVector<MachineInstr *, 4> VCTPs;
366 SmallPtrSet<MachineInstr *, 4> ToRemove;
367 SmallPtrSet<MachineInstr *, 4> BlockMasksToRecompute;
368 SmallPtrSet<MachineInstr *, 4> DoubleWidthResultInstrs;
369 SmallPtrSet<MachineInstr *, 4> VMOVCopies;
371 bool CannotTailPredicate =
false;
374 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, ReachingDefInfo &RDI,
375 const TargetRegisterInfo &TRI,
const ARMBaseInstrInfo &TII)
376 : ML(ML), MLI(MLI), RDI(RDI), TRI(TRI), TII(TII),
377 TPNumElements(MachineOperand::CreateImm(0)) {
379 if (
auto *
MBB = ML.getLoopPreheader())
381 else if (
auto *
MBB = MLI.findLoopPreheader(&ML,
true,
true))
388 bool ValidateMVEInst(MachineInstr *
MI);
390 void AnalyseMVEInst(MachineInstr *
MI) {
391 CannotTailPredicate = !ValidateMVEInst(
MI);
394 bool IsTailPredicationLegal()
const {
397 return !Revert && FoundAllComponents() && !VCTPs.empty() &&
398 !CannotTailPredicate && ML.getNumBlocks() == 1;
403 bool AddVCTP(MachineInstr *
MI);
408 bool ValidateTailPredicate();
412 bool ValidateLiveOuts();
416 void Validate(ARMBasicBlockUtils *BBUtils);
418 bool FoundAllComponents()
const {
419 return Start && Dec && End;
422 SmallVectorImpl<VPTBlock> &getVPTBlocks() {
return VPTstate.Blocks; }
426 MachineOperand &getLoopStartOperand() {
427 if (IsTailPredicationLegal())
428 return TPNumElements;
429 return Start->getOperand(1);
432 unsigned getStartOpcode()
const {
434 if (!IsTailPredicationLegal())
435 return IsDo ? ARM::t2DLS : ARM::t2WLS;
441 if (Start)
dbgs() <<
"ARM Loops: Found Loop Start: " << *Start;
442 if (Dec)
dbgs() <<
"ARM Loops: Found Loop Dec: " << *Dec;
443 if (End)
dbgs() <<
"ARM Loops: Found Loop End: " << *End;
444 if (!VCTPs.empty()) {
445 dbgs() <<
"ARM Loops: Found VCTP(s):\n";
446 for (
auto *
MI : VCTPs)
449 if (!FoundAllComponents())
450 dbgs() <<
"ARM Loops: Not a low-overhead loop.\n";
451 else if (!(Start && Dec && End))
452 dbgs() <<
"ARM Loops: Failed to find all loop components.\n";
458 MachineLoopInfo *MLI =
nullptr;
459 ReachingDefInfo *RDI =
nullptr;
460 const ARMBaseInstrInfo *TII =
nullptr;
461 const TargetRegisterInfo *TRI =
nullptr;
462 std::unique_ptr<ARMBasicBlockUtils> BBUtils =
nullptr;
467 ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
469 void getAnalysisUsage(AnalysisUsage &AU)
const override {
478 MachineFunctionProperties getRequiredProperties()
const override {
479 return MachineFunctionProperties().setNoVRegs().setTracksLiveness();
482 StringRef getPassName()
const override {
487 bool ProcessLoop(MachineLoop *
ML);
489 bool RevertNonLoops();
491 void RevertWhile(MachineInstr *
MI)
const;
492 void RevertDo(MachineInstr *
MI)
const;
498 void RevertLoopEndDec(MachineInstr *
MI)
const;
500 void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
502 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
504 void Expand(LowOverheadLoop &LoLoop);
506 void IterationCountDCE(LowOverheadLoop &LoLoop);
510char ARMLowOverheadLoops::ID = 0;
523 for (
auto *
Dead : Killed)
527 std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
528 for (
auto *
MBB : BasicBlocks) {
529 for (
auto &IT : *
MBB) {
530 if (IT.getOpcode() != ARM::t2IT)
541 for (
auto *
Dead : Killed) {
543 Dead->findRegisterUseOperand(ARM::ITSTATE,
nullptr)) {
546 auto &CurrentBlock = ITBlocks[IT];
547 CurrentBlock.erase(
Dead);
548 if (CurrentBlock.empty())
549 ModifiedITs.
erase(IT);
554 if (!ModifiedITs.
empty())
567 <<
" - can also remove:\n";
572 RDI.collectKilledOperands(
MI, Killed);
573 if (WontCorruptITs(Killed,
RDI)) {
583bool LowOverheadLoop::ValidateTailPredicate() {
584 if (!IsTailPredicationLegal()) {
586 dbgs() <<
"ARM Loops: Didn't find a VCTP instruction.\n";
587 dbgs() <<
"ARM Loops: Tail-predication is not valid.\n");
591 assert(!VCTPs.
empty() &&
"VCTP instruction expected but is not set");
592 assert(
ML.getBlocks().size() == 1 &&
593 "Shouldn't be processing a loop with more than one block");
595 if (!
TII.getSubtarget().getCLOpts().loloops_tailpred) {
596 LLVM_DEBUG(
dbgs() <<
"ARM Loops: tail-predication is disabled\n");
600 if (!VPTstate.isValid(
RDI)) {
605 if (!ValidateLiveOuts()) {
614 MachineInstr *VCTP = VCTPs.
back();
615 if (
Start->getOpcode() == ARM::t2DoLoopStartTP ||
616 Start->getOpcode() == ARM::t2WhileLoopStartTP) {
617 TPNumElements =
Start->getOperand(2);
618 StartInsertPt =
Start;
619 StartInsertBB =
Start->getParent();
628 LLVM_DEBUG(
dbgs() <<
"ARM Loops: VCTP operand is defined in the loop.\n");
636 if (StartInsertPt != StartInsertBB->
end() &&
641 ElemDef->removeFromParent();
642 StartInsertBB->
insert(StartInsertPt, ElemDef);
644 <<
"ARM Loops: Moved element count def: " << *ElemDef);
646 StartInsertPt->removeFromParent();
649 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Moved start past: " << *ElemDef);
654 MachineOperand Operand = ElemDef->getOperand(1);
659 TPNumElements = Operand;
660 NumElements = TPNumElements.
getReg();
663 <<
"ARM Loops: Unable to move element count to loop "
664 <<
"start instruction.\n");
674 auto CannotProvideElements = [
this](MachineBasicBlock *
MBB,
675 MCRegister NumElements) {
691 MachineBasicBlock *
MBB = Preheader;
692 while (
MBB &&
MBB != StartInsertBB) {
693 if (CannotProvideElements(
MBB, NumElements)) {
694 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unable to provide element count.\n");
711 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Instruction blocks [W|D]LSTP\n");
720 for (MachineInstr *
MI : DoubleWidthResultInstrs) {
722 if (InstrVecSize > VCTPVecSize) {
723 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Double width result larger than VCTP "
724 <<
"VecSize:\n" << *
MI);
733 auto IsValidSub = [](MachineInstr *
MI,
int ExpectedVecWidth) {
744 SmallPtrSet<MachineInstr*, 2> ElementChain;
745 SmallPtrSet<MachineInstr*, 2>
Ignore;
748 Ignore.insert_range(VCTPs);
750 if (TryRemove(Def,
RDI, ElementChain,
Ignore)) {
751 bool FoundSub =
false;
753 for (
auto *
MI : ElementChain) {
758 if (FoundSub || !IsValidSub(
MI, ExpectedVectorWidth)) {
759 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unexpected instruction in element"
765 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unexpected instruction in element"
770 ToRemove.insert_range(ElementChain);
777 if ((
Start->getOpcode() == ARM::t2DoLoopStartTP ||
778 Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
779 Preheader && !Preheader->
empty() &&
825 switch (
MI.getOpcode()) {
834 case ARM::MVE_VCLZs8:
835 case ARM::MVE_VCLZs16:
836 case ARM::MVE_VCLZs32:
850 InstSet &FalseLanesZero) {
862 Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
863 Def->getOperand(1).getImm() == 0;
867 for (
auto &MO :
MI.operands()) {
874 if (PIdx != -1 && MO.
getOperandNo() == PIdx + ARM::SUBOP_vpred_n_tp_reg)
885 for (
auto *Def : Defs) {
886 if (Def == &
MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
888 if (MO.
isUse() && isPredicated)
897bool LowOverheadLoop::ValidateLiveOuts() {
920 SetVector<MachineInstr *> FalseLanesUnknown;
923 MachineBasicBlock *Header =
ML.getHeader();
927 for (
auto &
MI : *Header) {
935 bool retainsOrReduces =
942 else if (
MI.getNumDefs() == 0)
944 else if (!isPredicated && retainsOrReduces) {
945 LLVM_DEBUG(
dbgs() <<
" Unpredicated instruction that retainsOrReduces: " <<
MI);
947 }
else if (!isPredicated &&
MI.getOpcode() != ARM::MQPRCopy)
952 dbgs() <<
" Predicated:\n";
955 dbgs() <<
" FalseLanesZero:\n";
956 for (
auto *
I : FalseLanesZero)
958 dbgs() <<
" FalseLanesUnknown:\n";
959 for (
auto *
I : FalseLanesUnknown)
963 auto HasPredicatedUsers = [
this](MachineInstr *
MI,
const MachineOperand &MO,
964 SmallPtrSetImpl<MachineInstr *> &
Predicated) {
965 SmallPtrSet<MachineInstr *, 2>
Uses;
967 for (
auto *Use :
Uses) {
980 SmallPtrSet<MachineInstr*, 2> NonPredicated;
981 for (
auto *
MI :
reverse(FalseLanesUnknown)) {
982 for (
auto &MO :
MI->operands()) {
987 <<
TRI.getRegAsmName(MO.getReg()) <<
" at " << *
MI);
997 SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
998 SmallVector<MachineBasicBlock *, 2> ExitBlocks;
999 ML.getExitBlocks(ExitBlocks);
1000 assert(
ML.getNumBlocks() == 1 &&
"Expected single block loop!");
1001 assert(ExitBlocks.
size() == 1 &&
"Expected a single exit block");
1002 MachineBasicBlock *ExitBB = ExitBlocks.
front();
1003 for (
const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->
liveins()) {
1006 if (RegMask.PhysReg == ARM::VPR) {
1012 if (QPRs->
contains(RegMask.PhysReg))
1025 while (!Worklist.empty()) {
1026 MachineInstr *
MI = Worklist.pop_back_val();
1027 if (
MI->getOpcode() == ARM::MQPRCopy) {
1030 MachineInstr *CopySrc =
1033 Worklist.push_back(CopySrc);
1042 if (InactiveIdx != -1) {
1044 MI,
MI->getOperand(InactiveIdx).getReg());
1047 <<
" Must check source of false lanes for: " << *
MI);
1048 Worklist.push_back(FalseSrc);
1057void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
1063 auto ValidateRanges = [](MachineInstr *
Start, MachineInstr *
End,
1064 ARMBasicBlockUtils *BBUtils, MachineLoop &
ML) {
1065 MachineBasicBlock *TgtBB =
End->getOpcode() == ARM::t2LoopEnd
1066 ?
End->getOperand(1).getMBB()
1067 :
End->getOperand(2).getMBB();
1070 if (TgtBB !=
ML.getHeader()) {
1071 LLVM_DEBUG(
dbgs() <<
"ARM Loops: LoopEnd is not targeting header.\n");
1077 if (BBUtils->getOffsetOf(
End) < BBUtils->getOffsetOf(
ML.getHeader()) ||
1078 !BBUtils->isBBInRange(
End,
ML.getHeader(), 4094)) {
1085 if (BBUtils->getOffsetOf(Start) > BBUtils->getOffsetOf(TargetBB) ||
1086 !BBUtils->isBBInRange(Start, TargetBB, 4094)) {
1087 LLVM_DEBUG(
dbgs() <<
"ARM Loops: WLS offset is out-of-range!\n");
1095 StartInsertBB =
Start->getParent();
1099 Revert = !ValidateRanges(Start,
End, BBUtils,
ML);
1100 CannotTailPredicate = !ValidateTailPredicate();
1103bool LowOverheadLoop::AddVCTP(MachineInstr *
MI) {
1105 if (VCTPs.
empty()) {
1112 MachineInstr *Prev = VCTPs.
back();
1115 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Found VCTP with a different reaching "
1116 "definition from the main VCTP");
1129 return FS->getFrameIndex();
1136 switch (
I->getOpcode()) {
1137 case ARM::MVE_VSTRWU32:
1138 case ARM::MVE_VLDRWU32: {
1139 return I->getOperand(1).getReg() == ARM::SP &&
1140 I->memoperands().size() == 1 &&
1141 GetFrameIndex(
I->memoperands().front()) >= 0;
1150 if (
MI->getOpcode() != ARM::MVE_VSTRWU32 || !IsStackOp(
MI))
1156 if (
MI->memoperands().size() == 0)
1158 int FI = GetFrameIndex(
MI->memoperands().front());
1160 auto &FrameInfo =
MI->getParent()->getParent()->getFrameInfo();
1161 if (FI == -1 || !FrameInfo.isSpillSlotObjectIndex(FI))
1165 ML->getExitBlocks(Frontier);
1168 while (Idx < Frontier.
size()) {
1170 bool LookAtSuccessors =
true;
1171 for (
auto &
I : *BB) {
1172 if (!IsStackOp(&
I) ||
I.memoperands().size() == 0)
1174 if (GetFrameIndex(
I.memoperands().front()) != FI)
1178 if (
I.getOpcode() == ARM::MVE_VSTRWU32) {
1179 LookAtSuccessors =
false;
1184 if (
I.getOpcode() == ARM::MVE_VLDRWU32)
1188 if (LookAtSuccessors) {
1201bool LowOverheadLoop::ValidateMVEInst(MachineInstr *
MI) {
1202 if (CannotTailPredicate)
1208 if (
MI->getOpcode() == ARM::MVE_VPSEL ||
1209 MI->getOpcode() == ARM::MVE_VPNOT) {
1227 const MCInstrDesc &MCID =
MI->getDesc();
1229 unsigned LastOpIdx =
MI->getNumOperands() - 1;
1231 const MachineOperand &MO =
MI->getOperand(LastOpIdx -
Op.index());
1236 VPTstate.addInst(
MI);
1238 }
else if (
MI->getOpcode() != ARM::MVE_VPST) {
1247 bool RequiresExplicitPredication =
1250 if (
MI->getOpcode() == ARM::MQPRCopy)
1253 DoubleWidthResultInstrs.insert(
MI);
1258 <<
"ARM Loops: Can't tail predicate: " << *
MI);
1273 VPTstate.resetPredicate(
MI);
1275 VPTstate.addPredicate(
MI);
1281 VPTstate.CreateVPTBlock(
MI);
1294 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1295 RDI = &getAnalysis<ReachingDefInfoWrapperPass>().getRDI();
1297 TII =
ST.getInstrInfo();
1298 TRI =
ST.getRegisterInfo();
1299 BBUtils = std::make_unique<ARMBasicBlockUtils>(*MF);
1300 BBUtils->computeAllBlockSizes();
1301 BBUtils->adjustBBOffsetsAfter(&MF->
front());
1304 for (
auto *
ML : *MLI) {
1305 if (
ML->isOutermost())
1312bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *
ML) {
1316 for (MachineLoop *L : *
ML)
1320 dbgs() <<
"ARM Loops: Processing loop containing:\n";
1321 if (
auto *Preheader =
ML->getLoopPreheader())
1323 else if (
auto *Preheader = MLI->findLoopPreheader(
ML,
true,
true))
1325 for (
auto *
MBB :
ML->getBlocks())
1331 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1332 [&SearchForStart](MachineBasicBlock *
MBB) -> MachineInstr* {
1333 for (
auto &
MI : *
MBB) {
1342 LowOverheadLoop LoLoop(*
ML, *MLI, *
RDI, *
TRI, *
TII);
1346 if (LoLoop.Preheader)
1347 LoLoop.Start = SearchForStart(LoLoop.Preheader);
1355 for (
auto &
MI : *
MBB) {
1356 if (
MI.isDebugValue())
1358 else if (
MI.getOpcode() == ARM::t2LoopDec)
1360 else if (
MI.getOpcode() == ARM::t2LoopEnd)
1362 else if (
MI.getOpcode() == ARM::t2LoopEndDec)
1363 LoLoop.End = LoLoop.Dec = &
MI;
1366 else if (
MI.getDesc().isCall()) {
1370 LoLoop.Revert =
true;
1375 LoLoop.AnalyseMVEInst(&
MI);
1381 if (!LoLoop.FoundAllComponents()) {
1382 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Didn't find loop start, update, end\n");
1386 assert(LoLoop.Start->getOpcode() != ARM::t2WhileLoopStart &&
1387 "Expected t2WhileLoopStart to be removed before regalloc!");
1392 if (LoLoop.Dec != LoLoop.End) {
1393 SmallPtrSet<MachineInstr *, 2>
Uses;
1395 if (
Uses.size() > 1 || !
Uses.count(LoLoop.End)) {
1397 LoLoop.Revert =
true;
1400 LoLoop.Validate(BBUtils.get());
1409void ARMLowOverheadLoops::RevertWhile(MachineInstr *
MI)
const {
1412 unsigned BrOpc = BBUtils->isBBInRange(
MI, DestBB, 254) ?
1413 ARM::tBcc : ARM::t2Bcc;
1418void ARMLowOverheadLoops::RevertDo(MachineInstr *
MI)
const {
1423bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *
MI)
const {
1426 SmallPtrSet<MachineInstr*, 1>
Ignore;
1428 if (
I->getOpcode() == ARM::t2LoopEnd) {
1443void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *
MI,
bool SkipCmp)
const {
1446 MachineBasicBlock *DestBB =
MI->getOperand(1).getMBB();
1447 unsigned BrOpc = BBUtils->isBBInRange(
MI, DestBB, 254) ?
1448 ARM::tBcc : ARM::t2Bcc;
1454void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *
MI)
const {
1456 assert(
MI->getOpcode() == ARM::t2LoopEndDec &&
"Expected a t2LoopEndDec!");
1459 MachineInstrBuilder MIB =
1462 MIB.
add(
MI->getOperand(1));
1469 MachineBasicBlock *DestBB =
MI->getOperand(2).getMBB();
1471 BBUtils->isBBInRange(
MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc;
1475 MIB.
add(
MI->getOperand(2));
1506void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1507 if (!LoLoop.IsTailPredicationLegal())
1510 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Trying DCE on loop iteration count.\n");
1514 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Couldn't find iteration count.\n");
1519 SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec,
1521 if (!TryRemove(Def, *
RDI, LoLoop.ToRemove, Killed))
1522 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unsafe to remove loop iteration count.\n");
1525MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1529 IterationCountDCE(LoLoop);
1532 MachineInstr *
Start = LoLoop.Start;
1533 MachineBasicBlock *
MBB = LoLoop.StartInsertBB;
1534 unsigned Opc = LoLoop.getStartOpcode();
1535 MachineOperand &
Count = LoLoop.getLoopStartOperand();
1538 MachineInstr* NewStart;
1539 if (
TII->getSubtarget().getCLOpts().omit_dls &&
Opc == ARM::t2DLS &&
1540 Count.isReg() &&
Count.getReg() == ARM::LR) {
1541 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Didn't insert start: DLS lr, lr");
1544 MachineInstrBuilder MIB =
1556 LoLoop.ToRemove.insert(Start);
1560void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1561 auto RemovePredicate = [](MachineInstr *
MI) {
1562 if (
MI->isDebugInstr())
1566 assert(PIdx >= 1 &&
"Trying to unpredicate a non-predicated instruction");
1568 "Expected Then predicate!");
1570 MI->getOperand(PIdx + 1).setReg(0);
1573 for (
auto &
Block : LoLoop.getVPTBlocks()) {
1574 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
1576 auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
1577 assert(TheVCMP &&
"Replacing a removed or non-existent VCMP");
1579 MachineInstrBuilder MIB =
1580 BuildMI(*At->getParent(), At, At->getDebugLoc(),
1589 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Combining with VCMP to VPT: " << *MIB);
1590 LoLoop.BlockMasksToRecompute.insert(MIB.
getInstr());
1591 LoLoop.ToRemove.insert(TheVCMP);
1595 if (LoLoop.VPTstate.isEntryPredicatedOnVCTP(
Block,
true)) {
1596 MachineInstr *VPST = Insts.
front();
1597 if (
Block.hasUniformPredicate()) {
1603 for (
unsigned i = 1; i < Insts.
size(); ++i)
1604 RemovePredicate(Insts[i]);
1613 MachineInstr *Divergent =
Block.getDivergent();
1616 while (DivergentNext !=
MBB->
end() && DivergentNext->isDebugInstr())
1619 bool DivergentNextIsPredicated =
1620 DivergentNext !=
MBB->
end() &&
1625 RemovePredicate(&*
I);
1629 MachineInstr *VCMP =
1632 if (DivergentNextIsPredicated) {
1639 MachineInstrBuilder MIB =
1644 LoLoop.BlockMasksToRecompute.insert(MIB.
getInstr());
1648 ReplaceVCMPWithVPT(VCMP, VCMP);
1653 LoLoop.ToRemove.insert(VPST);
1654 }
else if (
Block.containsVCTP()) {
1657 MachineInstr *VPST = Insts.
front();
1658 if (
Block.size() == 2) {
1660 "Found a VPST in an otherwise empty vpt block");
1661 LoLoop.ToRemove.insert(VPST);
1663 LoLoop.BlockMasksToRecompute.insert(VPST);
1664 }
else if (Insts.
front()->getOpcode() == ARM::MVE_VPST) {
1668 MachineInstr *VPST = Insts.
front();
1671 "The instruction after a VPST must be predicated");
1675 !LoLoop.ToRemove.contains(VprDef)) {
1676 MachineInstr *VCMP = VprDef;
1686 ReplaceVCMPWithVPT(VCMP, VPST);
1688 LoLoop.ToRemove.insert(VPST);
1694 LoLoop.ToRemove.insert_range(LoLoop.VCTPs);
1697void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1700 auto ExpandLoopEnd = [
this](LowOverheadLoop &LoLoop) {
1701 MachineInstr *
End = LoLoop.End;
1703 unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1704 ARM::MVE_LETP : ARM::t2LEUpdate;
1708 unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0;
1712 LoLoop.ToRemove.insert(LoLoop.Dec);
1713 LoLoop.ToRemove.insert(
End);
1722 auto RemoveDeadBranch = [](MachineInstr *
I) {
1723 MachineBasicBlock *BB =
I->getParent();
1725 if (
Terminator->isUnconditionalBranch() &&
I != Terminator) {
1726 MachineBasicBlock *Succ =
Terminator->getOperand(0).getMBB();
1728 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Removing branch: " << *Terminator);
1736 auto ExpandVMOVCopies = [
this](SmallPtrSet<MachineInstr *, 4> &VMOVCopies) {
1737 for (
auto *
MI : VMOVCopies) {
1739 assert(
MI->getOpcode() == ARM::MQPRCopy &&
"Only expected MQPRCOPY!");
1744 ARM::D0 + (Dst - ARM::Q0) * 2)
1745 .
addReg(ARM::D0 + (Src - ARM::Q0) * 2)
1750 ARM::D0 + (Dst - ARM::Q0) * 2 + 1)
1751 .
addReg(ARM::D0 + (Src - ARM::Q0) * 2 + 1)
1755 MI->eraseFromParent();
1759 if (LoLoop.Revert) {
1761 RevertWhile(LoLoop.Start);
1763 RevertDo(LoLoop.Start);
1764 if (LoLoop.Dec == LoLoop.End)
1765 RevertLoopEndDec(LoLoop.End);
1769 ExpandVMOVCopies(LoLoop.VMOVCopies);
1770 LoLoop.Start = ExpandLoopStart(LoLoop);
1772 RemoveDeadBranch(LoLoop.Start);
1773 LoLoop.End = ExpandLoopEnd(LoLoop);
1774 RemoveDeadBranch(LoLoop.End);
1775 if (LoLoop.IsTailPredicationLegal())
1776 ConvertVPTBlocks(LoLoop);
1777 for (
auto *
I : LoLoop.ToRemove) {
1779 I->eraseFromParent();
1781 for (
auto *
I : LoLoop.BlockMasksToRecompute) {
1782 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Recomputing VPT/VPST Block Mask: " << *
I);
1788 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1790 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1800bool ARMLowOverheadLoops::RevertNonLoops() {
1801 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Reverting any remaining pseudos...\n");
1804 for (
auto &
MBB : *MF) {
1805 SmallVector<MachineInstr*, 4> Starts;
1806 SmallVector<MachineInstr*, 4> Decs;
1807 SmallVector<MachineInstr*, 4> Ends;
1808 SmallVector<MachineInstr *, 4> EndDecs;
1809 SmallVector<MachineInstr *, 4> MQPRCopies;
1811 for (
auto &
I :
MBB) {
1814 else if (
I.getOpcode() == ARM::t2LoopDec)
1816 else if (
I.getOpcode() == ARM::t2LoopEnd)
1818 else if (
I.getOpcode() == ARM::t2LoopEndDec)
1820 else if (
I.getOpcode() == ARM::MQPRCopy)
1830 for (
auto *Start : Starts) {
1836 for (
auto *Dec : Decs)
1839 for (
auto *
End : Ends)
1841 for (
auto *
End : EndDecs)
1842 RevertLoopEndDec(
End);
1843 for (
auto *
MI : MQPRCopies) {
1845 assert(
MI->getOpcode() == ARM::MQPRCopy &&
"Only expected MQPRCOPY!");
1848 MI->getOperand(0).getReg())
1849 .
add(
MI->getOperand(1))
1850 .
add(
MI->getOperand(1));
1852 MI->eraseFromParent();
1859 return new ARMLowOverheadLoops();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isRegInClass(const MachineOperand &RegMO, const TargetRegisterClass &Class, const MachineRegisterInfo &MRI)
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
static int getVecSize(const AMDGPULibFunc &FInfo)
static bool isDomainMVE(MachineInstr *MI)
static bool isVectorPredicated(MachineInstr *MI)
static bool canGenerateNonZeros(const MachineInstr &MI)
static bool isHorizontalReduction(const MachineInstr &MI)
static bool producesDoubleWidthResult(const MachineInstr &MI)
static bool hasVPRUse(MachineInstr &MI)
static bool ValidateMVEStore(MachineInstr *MI, MachineLoop *ML)
static bool isVectorPredicate(MachineInstr *MI)
static bool retainsPreviousHalfElement(const MachineInstr &MI)
static bool shouldInspect(MachineInstr &MI)
static bool producesFalseLanesZero(MachineInstr &MI, const TargetRegisterClass *QPRs, const ReachingDefInfo &RDI, InstSet &FalseLanesZero)
ReachingDefInfo InstSet InstSet & Ignore
static int getVecSize(const MachineInstr &MI)
#define ARM_LOW_OVERHEAD_LOOPS_NAME
ReachingDefInfo InstSet & ToRemove
static const Function * getParent(const Value *V)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
if(!TBB||Cond.size()< 1) return false
static ARM::PredBlockMask CreateVPTBlock(MachineBasicBlock::instr_iterator &Iter, MachineBasicBlock::instr_iterator EndIter, SmallVectorImpl< MachineInstr * > &DeadInstructions)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file implements a set that has insertion order iteration characteristics.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
FunctionPass class - This class is used to implement most global optimizations.
Describe properties that are true of each instruction in the target description file.
ArrayRef< MCOperandInfo > operands() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
static constexpr MCRegister from(unsigned Val)
Check-convert the provided unsigned value to an MCRegister.
unsigned pred_size() const
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
MachineInstr & instr_back()
pred_iterator pred_begin()
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
LLVM_ABI void setIsDef(bool Val=true)
Change a def to a use, or a use to a def.
Special value supplied for machine level alias analysis.
This class provides the reaching def analysis.
LLVM_ABI MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
LLVM_ABI bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
LLVM_ABI bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
LLVM_ABI void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
LLVM_ABI bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
LLVM_ABI void reset()
Re-run the analysis.
LLVM_ABI void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
LLVM_ABI MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
LLVM_ABI bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
LLVM_ABI bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
LLVM_ABI void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
LLVM_ABI MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, Register Reg) const
Return the local MI that produces the live out value for Reg, or nullptr for a non-live out or non-lo...
LLVM_ABI bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
size_type size() const
Determine the number of elements in the SetVector.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
bool insert(const value_type &X)
Insert a new element into the SetVector.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A Use represents the edge between a Value definition and its users.
@ ValidForTailPredication
@ RetainsPreviousHalfElement
bool isPredicated(const MCInst &MI, const MCInstrInfo *MCII)
bool isVpred(OperandType op)
NodeAddr< DefNode * > Def
This is an optimization pass for GlobalISel generic memory operations.
static bool isDoLoopStart(const MachineInstr &MI)
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
int findVPTInactiveOperandIdx(const MachineInstr &MI)
int findFirstVPTPredOperandIdx(const MachineInstr &MI)
ARMVCC::VPTCodes getVPTInstrPredicate(const MachineInstr &MI, Register &PredReg)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static bool isVCTP(const MachineInstr *MI)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr from_range_t from_range
static bool isVPTOpcode(int Opc)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
static unsigned getTailPredVectorWidth(unsigned Opcode)
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
FunctionPass * createARMLowOverheadLoopsPass()
static bool isMovRegOpcode(int Opc)
static bool isSubImmOpcode(int Opc)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool isLoopStart(const MachineInstr &MI)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
void RevertWhileLoopStartLR(MachineInstr *MI, const TargetInstrInfo *TII, unsigned BrOpc=ARM::t2Bcc, bool UseCmp=false)
LLVM_ABI void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
static unsigned VCTPOpcodeToLSTP(unsigned Opcode, bool IsDoLoop)
void addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB, Register DestReg)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
void RevertLoopEnd(MachineInstr *MI, const TargetInstrInfo *TII, unsigned BrOpc=ARM::t2Bcc, bool SkipCmp=false)
void RevertLoopDec(MachineInstr *MI, const TargetInstrInfo *TII, bool SetFlags=false)
MachineBasicBlock * getWhileLoopStartTargetBB(const MachineInstr &MI)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
static bool isWhileLoopStart(const MachineInstr &MI)
static unsigned VCMPOpcodeToVPT(unsigned Opcode)
void RevertDoLoopStart(MachineInstr *MI, const TargetInstrInfo *TII)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
int getAddSubImmediate(MachineInstr &MI)
@ End
Run the machine verifier once, at the end of the pipeline.
void recomputeVPTBlockMask(MachineInstr &Instr)
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass