72#define DEBUG_TYPE "arm-low-overhead-loops"
73#define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
77 cl::desc(
"Disable tail-predication in the ARM LowOverheadLoop pass"),
82 cl::desc(
"Disable omitting 'dls lr, lr' instructions"),
87 return PIdx != -1 &&
MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
91 return MI->findRegisterDefOperandIdx(ARM::VPR,
nullptr) != -1;
95 return MI.findRegisterUseOperandIdx(ARM::VPR,
nullptr) != -1;
110 if (
MI.isDebugInstr())
125 class PostOrderLoopTraversal {
127 MachineLoopInfo &MLI;
128 SmallPtrSet<MachineBasicBlock*, 4> Visited;
129 SmallVector<MachineBasicBlock*, 4> Order;
132 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
133 : ML(ML), MLI(MLI) { }
135 const SmallVectorImpl<MachineBasicBlock*> &getOrder()
const {
142 std::function<void(MachineBasicBlock *)> Search =
143 [
this, &Search](MachineBasicBlock *
MBB) ->
void {
144 if (!Visited.insert(
MBB).second)
148 if (!ML.contains(Succ))
152 Order.push_back(
MBB);
157 ML.getExitBlocks(ExitBlocks);
161 Search(ML.getHeader());
164 std::function<void(MachineBasicBlock*)> GetPredecessor =
165 [
this, &GetPredecessor] (MachineBasicBlock *
MBB) ->
void {
166 Order.push_back(
MBB);
171 if (
auto *Preheader = ML.getLoopPreheader())
172 GetPredecessor(Preheader);
173 else if (
auto *Preheader = MLI.findLoopPreheader(&ML,
true,
true))
174 GetPredecessor(Preheader);
179 SmallVector<MachineInstr *, 4> Insts;
182 VPTBlock(MachineInstr *
MI) { Insts.push_back(
MI); }
186 bool hasUniformPredicate() {
return getDivergent() ==
nullptr; }
190 MachineInstr *getDivergent() {
191 SmallVectorImpl<MachineInstr *> &Insts = getInsts();
192 for (
unsigned i = 1; i < Insts.size(); ++i) {
193 MachineInstr *
Next = Insts[i];
200 void insert(MachineInstr *
MI) {
203 assert(Insts.size() <= 5 &&
"Too many instructions in VPT block!");
208 unsigned size()
const {
return Insts.size(); }
209 SmallVectorImpl<MachineInstr *> &getInsts() {
return Insts; }
218 friend struct LowOverheadLoop;
221 SetVector<MachineInstr *> CurrentPredicates;
222 std::map<MachineInstr *, SetVector<MachineInstr *>> PredicatedInsts;
225 assert((CurrentPredicates.size() ||
MI->getParent()->isLiveIn(ARM::VPR))
226 &&
"Can't begin VPT without predicate");
227 Blocks.emplace_back(
MI);
231 PredicatedInsts[
MI] = CurrentPredicates;
234 void addInst(MachineInstr *
MI) {
235 Blocks.back().insert(
MI);
236 PredicatedInsts[
MI] = CurrentPredicates;
239 void addPredicate(MachineInstr *
MI) {
241 CurrentPredicates.insert(
MI);
244 void resetPredicate(MachineInstr *
MI) {
246 CurrentPredicates.clear();
247 CurrentPredicates.insert(
MI);
252 bool isPredicatedOnVCTP(MachineInstr *
MI,
bool Exclusive =
false) {
253 SetVector<MachineInstr *> &Predicates = PredicatedInsts[
MI];
254 if (Exclusive && Predicates.
size() != 1)
263 bool isEntryPredicatedOnVCTP(VPTBlock &
Block,
bool Exclusive =
false) {
264 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
265 return isPredicatedOnVCTP(Insts.
front(), Exclusive);
271 bool hasImplicitlyValidVPT(VPTBlock &
Block, ReachingDefInfo &
RDI) {
272 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
273 MachineInstr *VPT = Insts.
front();
275 "Expected VPT block to begin with VPT/VPST");
285 return !MI->mayStore() && !MI->mayLoad() &&
286 !isHorizontalReduction(*MI) && !isVCTP(MI);
290 auto IsOperandPredicated = [&](MachineInstr *
MI,
unsigned Idx) {
292 return Op && PredicatedInsts.count(
Op) && isPredicatedOnVCTP(
Op);
295 auto IsOperandInvariant = [&](MachineInstr *
MI,
unsigned Idx) {
296 MachineOperand &MO =
MI->getOperand(Idx);
300 SmallPtrSet<MachineInstr *, 2> Defs;
305 for (
auto *Def : Defs)
313 return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
314 (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
315 (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
322 for (
auto &
Block : Blocks) {
323 if (isEntryPredicatedOnVCTP(
Block,
false) &&
325 return getVPTInstrPredicate(*MI) == ARMVCC::Else;
328 if (hasImplicitlyValidVPT(
Block,
RDI))
331 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
335 "Expected VPT block to start with a VPST or VPT!");
336 if (Insts.
size() == 2 && Insts.
front()->getOpcode() != ARM::MVE_VPST &&
340 for (
auto *
MI : Insts) {
350 if (!isPredicatedOnVCTP(
MI)) {
360 struct LowOverheadLoop {
363 MachineBasicBlock *Preheader =
nullptr;
364 MachineLoopInfo &MLI;
365 ReachingDefInfo &RDI;
366 const TargetRegisterInfo &TRI;
367 const ARMBaseInstrInfo &TII;
370 MachineBasicBlock *StartInsertBB =
nullptr;
371 MachineInstr *Start =
nullptr;
372 MachineInstr *Dec =
nullptr;
373 MachineInstr *End =
nullptr;
374 MachineOperand TPNumElements;
375 SmallVector<MachineInstr *, 4> VCTPs;
376 SmallPtrSet<MachineInstr *, 4> ToRemove;
377 SmallPtrSet<MachineInstr *, 4> BlockMasksToRecompute;
378 SmallPtrSet<MachineInstr *, 4> DoubleWidthResultInstrs;
379 SmallPtrSet<MachineInstr *, 4> VMOVCopies;
381 bool CannotTailPredicate =
false;
384 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, ReachingDefInfo &RDI,
385 const TargetRegisterInfo &TRI,
const ARMBaseInstrInfo &TII)
386 : ML(ML), MLI(MLI), RDI(RDI), TRI(TRI), TII(TII),
387 TPNumElements(MachineOperand::CreateImm(0)) {
389 if (
auto *
MBB = ML.getLoopPreheader())
391 else if (
auto *
MBB = MLI.findLoopPreheader(&ML,
true,
true))
398 bool ValidateMVEInst(MachineInstr *
MI);
400 void AnalyseMVEInst(MachineInstr *
MI) {
401 CannotTailPredicate = !ValidateMVEInst(
MI);
404 bool IsTailPredicationLegal()
const {
407 return !Revert && FoundAllComponents() && !VCTPs.empty() &&
408 !CannotTailPredicate && ML.getNumBlocks() == 1;
413 bool AddVCTP(MachineInstr *
MI);
418 bool ValidateTailPredicate();
422 bool ValidateLiveOuts();
426 void Validate(ARMBasicBlockUtils *BBUtils);
428 bool FoundAllComponents()
const {
429 return Start && Dec && End;
432 SmallVectorImpl<VPTBlock> &getVPTBlocks() {
return VPTstate.Blocks; }
436 MachineOperand &getLoopStartOperand() {
437 if (IsTailPredicationLegal())
438 return TPNumElements;
439 return Start->getOperand(1);
442 unsigned getStartOpcode()
const {
444 if (!IsTailPredicationLegal())
445 return IsDo ? ARM::t2DLS : ARM::t2WLS;
451 if (Start)
dbgs() <<
"ARM Loops: Found Loop Start: " << *Start;
452 if (Dec)
dbgs() <<
"ARM Loops: Found Loop Dec: " << *Dec;
453 if (End)
dbgs() <<
"ARM Loops: Found Loop End: " << *End;
454 if (!VCTPs.empty()) {
455 dbgs() <<
"ARM Loops: Found VCTP(s):\n";
456 for (
auto *
MI : VCTPs)
459 if (!FoundAllComponents())
460 dbgs() <<
"ARM Loops: Not a low-overhead loop.\n";
461 else if (!(Start && Dec && End))
462 dbgs() <<
"ARM Loops: Failed to find all loop components.\n";
468 MachineLoopInfo *MLI =
nullptr;
469 ReachingDefInfo *RDI =
nullptr;
470 const ARMBaseInstrInfo *TII =
nullptr;
471 const TargetRegisterInfo *TRI =
nullptr;
472 std::unique_ptr<ARMBasicBlockUtils> BBUtils =
nullptr;
477 ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
479 void getAnalysisUsage(AnalysisUsage &AU)
const override {
488 MachineFunctionProperties getRequiredProperties()
const override {
489 return MachineFunctionProperties().setNoVRegs().setTracksLiveness();
492 StringRef getPassName()
const override {
497 bool ProcessLoop(MachineLoop *
ML);
499 bool RevertNonLoops();
501 void RevertWhile(MachineInstr *
MI)
const;
502 void RevertDo(MachineInstr *
MI)
const;
508 void RevertLoopEndDec(MachineInstr *
MI)
const;
510 void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
512 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
514 void Expand(LowOverheadLoop &LoLoop);
516 void IterationCountDCE(LowOverheadLoop &LoLoop);
520char ARMLowOverheadLoops::ID = 0;
533 for (
auto *
Dead : Killed)
537 std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
538 for (
auto *
MBB : BasicBlocks) {
539 for (
auto &
IT : *
MBB) {
540 if (
IT.getOpcode() != ARM::t2IT)
551 for (
auto *
Dead : Killed) {
553 Dead->findRegisterUseOperand(ARM::ITSTATE,
nullptr)) {
556 auto &CurrentBlock = ITBlocks[
IT];
557 CurrentBlock.erase(
Dead);
558 if (CurrentBlock.empty())
564 if (!ModifiedITs.
empty())
577 <<
" - can also remove:\n";
582 RDI.collectKilledOperands(
MI, Killed);
583 if (WontCorruptITs(Killed,
RDI)) {
593bool LowOverheadLoop::ValidateTailPredicate() {
594 if (!IsTailPredicationLegal()) {
596 dbgs() <<
"ARM Loops: Didn't find a VCTP instruction.\n";
597 dbgs() <<
"ARM Loops: Tail-predication is not valid.\n");
601 assert(!VCTPs.
empty() &&
"VCTP instruction expected but is not set");
602 assert(
ML.getBlocks().size() == 1 &&
603 "Shouldn't be processing a loop with more than one block");
606 LLVM_DEBUG(
dbgs() <<
"ARM Loops: tail-predication is disabled\n");
610 if (!VPTstate.isValid(
RDI)) {
615 if (!ValidateLiveOuts()) {
624 MachineInstr *VCTP = VCTPs.
back();
625 if (
Start->getOpcode() == ARM::t2DoLoopStartTP ||
626 Start->getOpcode() == ARM::t2WhileLoopStartTP) {
627 TPNumElements =
Start->getOperand(2);
628 StartInsertPt =
Start;
629 StartInsertBB =
Start->getParent();
638 LLVM_DEBUG(
dbgs() <<
"ARM Loops: VCTP operand is defined in the loop.\n");
646 if (StartInsertPt != StartInsertBB->
end() &&
651 ElemDef->removeFromParent();
652 StartInsertBB->
insert(StartInsertPt, ElemDef);
654 <<
"ARM Loops: Moved element count def: " << *ElemDef);
656 StartInsertPt->removeFromParent();
659 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Moved start past: " << *ElemDef);
664 MachineOperand Operand = ElemDef->getOperand(1);
669 TPNumElements = Operand;
670 NumElements = TPNumElements.
getReg();
673 <<
"ARM Loops: Unable to move element count to loop "
674 <<
"start instruction.\n");
684 auto CannotProvideElements = [
this](MachineBasicBlock *
MBB,
685 MCRegister NumElements) {
701 MachineBasicBlock *
MBB = Preheader;
702 while (
MBB &&
MBB != StartInsertBB) {
703 if (CannotProvideElements(
MBB, NumElements)) {
704 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unable to provide element count.\n");
721 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Instruction blocks [W|D]LSTP\n");
730 for (MachineInstr *
MI : DoubleWidthResultInstrs) {
732 if (InstrVecSize > VCTPVecSize) {
733 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Double width result larger than VCTP "
734 <<
"VecSize:\n" << *
MI);
743 auto IsValidSub = [](MachineInstr *
MI,
int ExpectedVecWidth) {
754 SmallPtrSet<MachineInstr*, 2> ElementChain;
755 SmallPtrSet<MachineInstr*, 2>
Ignore;
758 Ignore.insert_range(VCTPs);
760 if (TryRemove(Def,
RDI, ElementChain,
Ignore)) {
761 bool FoundSub =
false;
763 for (
auto *
MI : ElementChain) {
768 if (FoundSub || !IsValidSub(
MI, ExpectedVectorWidth)) {
769 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unexpected instruction in element"
775 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unexpected instruction in element"
780 ToRemove.insert_range(ElementChain);
787 if ((
Start->getOpcode() == ARM::t2DoLoopStartTP ||
788 Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
789 Preheader && !Preheader->
empty() &&
835 switch (
MI.getOpcode()) {
844 case ARM::MVE_VCLZs8:
845 case ARM::MVE_VCLZs16:
846 case ARM::MVE_VCLZs32:
860 InstSet &FalseLanesZero) {
872 Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
873 Def->getOperand(1).getImm() == 0;
877 for (
auto &MO :
MI.operands()) {
884 if (PIdx != -1 && MO.
getOperandNo() == PIdx + ARM::SUBOP_vpred_n_tp_reg)
895 for (
auto *Def : Defs) {
896 if (Def == &
MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
898 if (MO.
isUse() && isPredicated)
907bool LowOverheadLoop::ValidateLiveOuts() {
930 SetVector<MachineInstr *> FalseLanesUnknown;
933 MachineBasicBlock *Header =
ML.getHeader();
937 for (
auto &
MI : *Header) {
945 bool retainsOrReduces =
952 else if (
MI.getNumDefs() == 0)
954 else if (!isPredicated && retainsOrReduces) {
955 LLVM_DEBUG(
dbgs() <<
" Unpredicated instruction that retainsOrReduces: " <<
MI);
957 }
else if (!isPredicated &&
MI.getOpcode() != ARM::MQPRCopy)
962 dbgs() <<
" Predicated:\n";
965 dbgs() <<
" FalseLanesZero:\n";
966 for (
auto *
I : FalseLanesZero)
968 dbgs() <<
" FalseLanesUnknown:\n";
969 for (
auto *
I : FalseLanesUnknown)
973 auto HasPredicatedUsers = [
this](MachineInstr *
MI,
const MachineOperand &MO,
974 SmallPtrSetImpl<MachineInstr *> &
Predicated) {
975 SmallPtrSet<MachineInstr *, 2>
Uses;
977 for (
auto *Use :
Uses) {
990 SmallPtrSet<MachineInstr*, 2> NonPredicated;
991 for (
auto *
MI :
reverse(FalseLanesUnknown)) {
992 for (
auto &MO :
MI->operands()) {
997 <<
TRI.getRegAsmName(MO.getReg()) <<
" at " << *
MI);
1007 SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
1009 ML.getExitBlocks(ExitBlocks);
1010 assert(
ML.getNumBlocks() == 1 &&
"Expected single block loop!");
1011 assert(ExitBlocks.
size() == 1 &&
"Expected a single exit block");
1012 MachineBasicBlock *ExitBB = ExitBlocks.
front();
1013 for (
const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->
liveins()) {
1016 if (RegMask.PhysReg == ARM::VPR) {
1022 if (QPRs->
contains(RegMask.PhysReg))
1035 while (!Worklist.empty()) {
1036 MachineInstr *
MI = Worklist.pop_back_val();
1037 if (
MI->getOpcode() == ARM::MQPRCopy) {
1040 MachineInstr *CopySrc =
1043 Worklist.push_back(CopySrc);
1052 if (InactiveIdx != -1) {
1054 MI,
MI->getOperand(InactiveIdx).getReg());
1057 <<
" Must check source of false lanes for: " << *
MI);
1058 Worklist.push_back(FalseSrc);
1067void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
1073 auto ValidateRanges = [](MachineInstr *
Start, MachineInstr *
End,
1074 ARMBasicBlockUtils *BBUtils, MachineLoop &
ML) {
1075 MachineBasicBlock *TgtBB =
End->getOpcode() == ARM::t2LoopEnd
1076 ?
End->getOperand(1).getMBB()
1077 :
End->getOperand(2).getMBB();
1080 if (TgtBB !=
ML.getHeader()) {
1081 LLVM_DEBUG(
dbgs() <<
"ARM Loops: LoopEnd is not targeting header.\n");
1087 if (BBUtils->getOffsetOf(
End) < BBUtils->getOffsetOf(
ML.getHeader()) ||
1088 !BBUtils->isBBInRange(
End,
ML.getHeader(), 4094)) {
1095 if (BBUtils->getOffsetOf(Start) > BBUtils->getOffsetOf(TargetBB) ||
1096 !BBUtils->isBBInRange(Start, TargetBB, 4094)) {
1097 LLVM_DEBUG(
dbgs() <<
"ARM Loops: WLS offset is out-of-range!\n");
1105 StartInsertBB =
Start->getParent();
1109 Revert = !ValidateRanges(Start,
End, BBUtils,
ML);
1110 CannotTailPredicate = !ValidateTailPredicate();
1113bool LowOverheadLoop::AddVCTP(MachineInstr *
MI) {
1115 if (VCTPs.
empty()) {
1122 MachineInstr *Prev = VCTPs.
back();
1125 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Found VCTP with a different reaching "
1126 "definition from the main VCTP");
1139 return FS->getFrameIndex();
1146 switch (
I->getOpcode()) {
1147 case ARM::MVE_VSTRWU32:
1148 case ARM::MVE_VLDRWU32: {
1149 return I->getOperand(1).getReg() == ARM::SP &&
1150 I->memoperands().size() == 1 &&
1151 GetFrameIndex(
I->memoperands().front()) >= 0;
1160 if (
MI->getOpcode() != ARM::MVE_VSTRWU32 || !IsStackOp(
MI))
1166 if (
MI->memoperands().size() == 0)
1168 int FI = GetFrameIndex(
MI->memoperands().front());
1170 auto &FrameInfo =
MI->getParent()->getParent()->getFrameInfo();
1171 if (FI == -1 || !FrameInfo.isSpillSlotObjectIndex(FI))
1175 ML->getExitBlocks(Frontier);
1178 while (Idx < Frontier.
size()) {
1180 bool LookAtSuccessors =
true;
1181 for (
auto &
I : *BB) {
1182 if (!IsStackOp(&
I) ||
I.memoperands().size() == 0)
1184 if (GetFrameIndex(
I.memoperands().front()) != FI)
1188 if (
I.getOpcode() == ARM::MVE_VSTRWU32) {
1189 LookAtSuccessors =
false;
1194 if (
I.getOpcode() == ARM::MVE_VLDRWU32)
1198 if (LookAtSuccessors) {
1211bool LowOverheadLoop::ValidateMVEInst(MachineInstr *
MI) {
1212 if (CannotTailPredicate)
1218 if (
MI->getOpcode() == ARM::MVE_VPSEL ||
1219 MI->getOpcode() == ARM::MVE_VPNOT) {
1237 const MCInstrDesc &MCID =
MI->getDesc();
1239 unsigned LastOpIdx =
MI->getNumOperands() - 1;
1241 const MachineOperand &MO =
MI->getOperand(LastOpIdx -
Op.index());
1246 VPTstate.addInst(
MI);
1248 }
else if (
MI->getOpcode() != ARM::MVE_VPST) {
1257 bool RequiresExplicitPredication =
1260 if (
MI->getOpcode() == ARM::MQPRCopy)
1263 DoubleWidthResultInstrs.insert(
MI);
1268 <<
"ARM Loops: Can't tail predicate: " << *
MI);
1283 VPTstate.resetPredicate(
MI);
1285 VPTstate.addPredicate(
MI);
1291 VPTstate.CreateVPTBlock(
MI);
1304 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1305 RDI = &getAnalysis<ReachingDefInfoWrapperPass>().getRDI();
1307 TII =
ST.getInstrInfo();
1308 TRI =
ST.getRegisterInfo();
1309 BBUtils = std::make_unique<ARMBasicBlockUtils>(*MF);
1310 BBUtils->computeAllBlockSizes();
1311 BBUtils->adjustBBOffsetsAfter(&MF->
front());
1314 for (
auto *
ML : *MLI) {
1315 if (
ML->isOutermost())
1322bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *
ML) {
1326 for (MachineLoop *L : *
ML)
1330 dbgs() <<
"ARM Loops: Processing loop containing:\n";
1331 if (
auto *Preheader =
ML->getLoopPreheader())
1333 else if (
auto *Preheader = MLI->findLoopPreheader(
ML,
true,
true))
1335 for (
auto *
MBB :
ML->getBlocks())
1341 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
1342 [&SearchForStart](MachineBasicBlock *
MBB) -> MachineInstr* {
1343 for (
auto &
MI : *
MBB) {
1352 LowOverheadLoop LoLoop(*
ML, *MLI, *
RDI, *
TRI, *
TII);
1356 if (LoLoop.Preheader)
1357 LoLoop.Start = SearchForStart(LoLoop.Preheader);
1365 for (
auto &
MI : *
MBB) {
1366 if (
MI.isDebugValue())
1368 else if (
MI.getOpcode() == ARM::t2LoopDec)
1370 else if (
MI.getOpcode() == ARM::t2LoopEnd)
1372 else if (
MI.getOpcode() == ARM::t2LoopEndDec)
1373 LoLoop.End = LoLoop.Dec = &
MI;
1376 else if (
MI.getDesc().isCall()) {
1380 LoLoop.Revert =
true;
1385 LoLoop.AnalyseMVEInst(&
MI);
1391 if (!LoLoop.FoundAllComponents()) {
1392 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Didn't find loop start, update, end\n");
1396 assert(LoLoop.Start->getOpcode() != ARM::t2WhileLoopStart &&
1397 "Expected t2WhileLoopStart to be removed before regalloc!");
1402 if (LoLoop.Dec != LoLoop.End) {
1403 SmallPtrSet<MachineInstr *, 2>
Uses;
1405 if (
Uses.size() > 1 || !
Uses.count(LoLoop.End)) {
1407 LoLoop.Revert =
true;
1410 LoLoop.Validate(BBUtils.get());
1419void ARMLowOverheadLoops::RevertWhile(MachineInstr *
MI)
const {
1422 unsigned BrOpc = BBUtils->isBBInRange(
MI, DestBB, 254) ?
1423 ARM::tBcc : ARM::t2Bcc;
1428void ARMLowOverheadLoops::RevertDo(MachineInstr *
MI)
const {
1433bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *
MI)
const {
1436 SmallPtrSet<MachineInstr*, 1>
Ignore;
1438 if (
I->getOpcode() == ARM::t2LoopEnd) {
1453void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *
MI,
bool SkipCmp)
const {
1456 MachineBasicBlock *DestBB =
MI->getOperand(1).getMBB();
1457 unsigned BrOpc = BBUtils->isBBInRange(
MI, DestBB, 254) ?
1458 ARM::tBcc : ARM::t2Bcc;
1464void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *
MI)
const {
1466 assert(
MI->getOpcode() == ARM::t2LoopEndDec &&
"Expected a t2LoopEndDec!");
1469 MachineInstrBuilder MIB =
1472 MIB.
add(
MI->getOperand(1));
1479 MachineBasicBlock *DestBB =
MI->getOperand(2).getMBB();
1481 BBUtils->isBBInRange(
MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc;
1485 MIB.
add(
MI->getOperand(2));
1516void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
1517 if (!LoLoop.IsTailPredicationLegal())
1520 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Trying DCE on loop iteration count.\n");
1524 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Couldn't find iteration count.\n");
1529 SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec,
1531 if (!TryRemove(Def, *
RDI, LoLoop.ToRemove, Killed))
1532 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Unsafe to remove loop iteration count.\n");
1535MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
1539 IterationCountDCE(LoLoop);
1542 MachineInstr *
Start = LoLoop.Start;
1543 MachineBasicBlock *
MBB = LoLoop.StartInsertBB;
1544 unsigned Opc = LoLoop.getStartOpcode();
1545 MachineOperand &
Count = LoLoop.getLoopStartOperand();
1548 MachineInstr* NewStart;
1550 Count.getReg() == ARM::LR) {
1551 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Didn't insert start: DLS lr, lr");
1554 MachineInstrBuilder MIB =
1566 LoLoop.ToRemove.insert(Start);
1570void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
1571 auto RemovePredicate = [](MachineInstr *
MI) {
1572 if (
MI->isDebugInstr())
1576 assert(PIdx >= 1 &&
"Trying to unpredicate a non-predicated instruction");
1578 "Expected Then predicate!");
1580 MI->getOperand(PIdx + 1).setReg(0);
1583 for (
auto &
Block : LoLoop.getVPTBlocks()) {
1584 SmallVectorImpl<MachineInstr *> &Insts =
Block.getInsts();
1586 auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
1587 assert(TheVCMP &&
"Replacing a removed or non-existent VCMP");
1589 MachineInstrBuilder MIB =
1590 BuildMI(*At->getParent(), At, At->getDebugLoc(),
1599 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Combining with VCMP to VPT: " << *MIB);
1600 LoLoop.BlockMasksToRecompute.insert(MIB.
getInstr());
1601 LoLoop.ToRemove.insert(TheVCMP);
1605 if (LoLoop.VPTstate.isEntryPredicatedOnVCTP(
Block,
true)) {
1606 MachineInstr *VPST = Insts.
front();
1607 if (
Block.hasUniformPredicate()) {
1613 for (
unsigned i = 1; i < Insts.
size(); ++i)
1614 RemovePredicate(Insts[i]);
1623 MachineInstr *Divergent =
Block.getDivergent();
1626 while (DivergentNext !=
MBB->
end() && DivergentNext->isDebugInstr())
1629 bool DivergentNextIsPredicated =
1630 DivergentNext !=
MBB->
end() &&
1635 RemovePredicate(&*
I);
1639 MachineInstr *VCMP =
1642 if (DivergentNextIsPredicated) {
1649 MachineInstrBuilder MIB =
1654 LoLoop.BlockMasksToRecompute.insert(MIB.
getInstr());
1658 ReplaceVCMPWithVPT(VCMP, VCMP);
1663 LoLoop.ToRemove.insert(VPST);
1664 }
else if (
Block.containsVCTP()) {
1667 MachineInstr *VPST = Insts.
front();
1668 if (
Block.size() == 2) {
1670 "Found a VPST in an otherwise empty vpt block");
1671 LoLoop.ToRemove.insert(VPST);
1673 LoLoop.BlockMasksToRecompute.insert(VPST);
1674 }
else if (Insts.
front()->getOpcode() == ARM::MVE_VPST) {
1678 MachineInstr *VPST = Insts.
front();
1681 "The instruction after a VPST must be predicated");
1685 !LoLoop.ToRemove.contains(VprDef)) {
1686 MachineInstr *VCMP = VprDef;
1696 ReplaceVCMPWithVPT(VCMP, VPST);
1698 LoLoop.ToRemove.insert(VPST);
1704 LoLoop.ToRemove.insert_range(LoLoop.VCTPs);
1707void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
1710 auto ExpandLoopEnd = [
this](LowOverheadLoop &LoLoop) {
1711 MachineInstr *
End = LoLoop.End;
1713 unsigned Opc = LoLoop.IsTailPredicationLegal() ?
1714 ARM::MVE_LETP : ARM::t2LEUpdate;
1718 unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0;
1722 LoLoop.ToRemove.insert(LoLoop.Dec);
1723 LoLoop.ToRemove.insert(
End);
1732 auto RemoveDeadBranch = [](MachineInstr *
I) {
1733 MachineBasicBlock *BB =
I->getParent();
1735 if (
Terminator->isUnconditionalBranch() &&
I != Terminator) {
1736 MachineBasicBlock *Succ =
Terminator->getOperand(0).getMBB();
1738 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Removing branch: " << *Terminator);
1746 auto ExpandVMOVCopies = [
this](SmallPtrSet<MachineInstr *, 4> &VMOVCopies) {
1747 for (
auto *
MI : VMOVCopies) {
1749 assert(
MI->getOpcode() == ARM::MQPRCopy &&
"Only expected MQPRCOPY!");
1754 ARM::D0 + (Dst - ARM::Q0) * 2)
1755 .
addReg(ARM::D0 + (Src - ARM::Q0) * 2)
1760 ARM::D0 + (Dst - ARM::Q0) * 2 + 1)
1761 .
addReg(ARM::D0 + (Src - ARM::Q0) * 2 + 1)
1765 MI->eraseFromParent();
1769 if (LoLoop.Revert) {
1771 RevertWhile(LoLoop.Start);
1773 RevertDo(LoLoop.Start);
1774 if (LoLoop.Dec == LoLoop.End)
1775 RevertLoopEndDec(LoLoop.End);
1779 ExpandVMOVCopies(LoLoop.VMOVCopies);
1780 LoLoop.Start = ExpandLoopStart(LoLoop);
1782 RemoveDeadBranch(LoLoop.Start);
1783 LoLoop.End = ExpandLoopEnd(LoLoop);
1784 RemoveDeadBranch(LoLoop.End);
1785 if (LoLoop.IsTailPredicationLegal())
1786 ConvertVPTBlocks(LoLoop);
1787 for (
auto *
I : LoLoop.ToRemove) {
1789 I->eraseFromParent();
1791 for (
auto *
I : LoLoop.BlockMasksToRecompute) {
1792 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Recomputing VPT/VPST Block Mask: " << *
I);
1798 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
1800 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
1810bool ARMLowOverheadLoops::RevertNonLoops() {
1811 LLVM_DEBUG(
dbgs() <<
"ARM Loops: Reverting any remaining pseudos...\n");
1814 for (
auto &
MBB : *MF) {
1815 SmallVector<MachineInstr*, 4> Starts;
1816 SmallVector<MachineInstr*, 4> Decs;
1817 SmallVector<MachineInstr*, 4> Ends;
1818 SmallVector<MachineInstr *, 4> EndDecs;
1819 SmallVector<MachineInstr *, 4> MQPRCopies;
1821 for (
auto &
I :
MBB) {
1824 else if (
I.getOpcode() == ARM::t2LoopDec)
1826 else if (
I.getOpcode() == ARM::t2LoopEnd)
1828 else if (
I.getOpcode() == ARM::t2LoopEndDec)
1830 else if (
I.getOpcode() == ARM::MQPRCopy)
1840 for (
auto *Start : Starts) {
1846 for (
auto *Dec : Decs)
1849 for (
auto *
End : Ends)
1851 for (
auto *
End : EndDecs)
1852 RevertLoopEndDec(
End);
1853 for (
auto *
MI : MQPRCopies) {
1855 assert(
MI->getOpcode() == ARM::MQPRCopy &&
"Only expected MQPRCOPY!");
1858 MI->getOperand(0).getReg())
1859 .
add(
MI->getOperand(1))
1860 .
add(
MI->getOperand(1));
1862 MI->eraseFromParent();
1869 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)
static cl::opt< bool > DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden, cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"), cl::init(false))
ReachingDefInfo InstSet InstSet & Ignore
if(!RDI.isSafeToRemove(MI, Uses, Ignore)) return false
static int getVecSize(const MachineInstr &MI)
#define ARM_LOW_OVERHEAD_LOOPS_NAME
static cl::opt< bool > DisableOmitDLS("arm-disable-omit-dls", cl::Hidden, cl::desc("Disable omitting 'dls lr, lr' instructions"), cl::init(false))
ReachingDefInfo InstSet & ToRemove
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
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.
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 MCRegister from(unsigned Val)
Check the provided unsigned value is a valid 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)
initializer< Ty > init(const Ty &Val)
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)
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