1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// Finalize v8.1-m low-overhead loops by converting the associated pseudo
10 /// instructions into machine operations.
11 /// The expectation is that the loop contains three pseudo instructions:
12 /// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop
13 /// form should be in the preheader, whereas the while form should be in the
14 /// preheaders only predecessor.
15 /// - t2LoopDec - placed within in the loop body.
16 /// - t2LoopEnd - the loop latch terminator.
17 ///
18 /// In addition to this, we also look for the presence of the VCTP instruction,
19 /// which determines whether we can generated the tail-predicated low-overhead
20 /// loop form.
21 ///
22 /// Assumptions and Dependencies:
23 /// Low-overhead loops are constructed and executed using a setup instruction:
24 /// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP.
25 /// WLS(TP) and LE(TP) are branching instructions with a (large) limited range
26 /// but fixed polarity: WLS can only branch forwards and LE can only branch
27 /// backwards. These restrictions mean that this pass is dependent upon block
28 /// layout and block sizes, which is why it's the last pass to run. The same is
29 /// true for ConstantIslands, but this pass does not increase the size of the
30 /// basic blocks, nor does it change the CFG. Instructions are mainly removed
31 /// during the transform and pseudo instructions are replaced by real ones. In
32 /// some cases, when we have to revert to a 'normal' loop, we have to introduce
33 /// multiple instructions for a single pseudo (see RevertWhile and
34 /// RevertLoopEnd). To handle this situation, t2WhileLoopStart and t2LoopEnd
35 /// are defined to be as large as this maximum sequence of replacement
36 /// instructions.
37 ///
38 //===----------------------------------------------------------------------===//
39
40 #include "ARM.h"
41 #include "ARMBaseInstrInfo.h"
42 #include "ARMBaseRegisterInfo.h"
43 #include "ARMBasicBlockInfo.h"
44 #include "ARMSubtarget.h"
45 #include "Thumb2InstrInfo.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SmallSet.h"
48 #include "llvm/CodeGen/MachineFunctionPass.h"
49 #include "llvm/CodeGen/MachineLoopInfo.h"
50 #include "llvm/CodeGen/MachineLoopUtils.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/Passes.h"
53 #include "llvm/CodeGen/ReachingDefAnalysis.h"
54 #include "llvm/MC/MCInstrDesc.h"
55
56 using namespace llvm;
57
58 #define DEBUG_TYPE "arm-low-overhead-loops"
59 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
60
61 namespace {
62
63 struct PredicatedMI {
64 MachineInstr *MI = nullptr;
65 SetVector<MachineInstr*> Predicates;
66
67 public:
PredicatedMI__anonace2ebed0111::PredicatedMI68 PredicatedMI(MachineInstr *I, SetVector<MachineInstr*> &Preds) :
69 MI(I) {
70 Predicates.insert(Preds.begin(), Preds.end());
71 }
72 };
73
74 // Represent a VPT block, a list of instructions that begins with a VPST and
75 // has a maximum of four proceeding instructions. All instructions within the
76 // block are predicated upon the vpr and we allow instructions to define the
77 // vpr within in the block too.
78 class VPTBlock {
79 std::unique_ptr<PredicatedMI> VPST;
80 PredicatedMI *Divergent = nullptr;
81 SmallVector<PredicatedMI, 4> Insts;
82
83 public:
VPTBlock(MachineInstr * MI,SetVector<MachineInstr * > & Preds)84 VPTBlock(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
85 VPST = std::make_unique<PredicatedMI>(MI, Preds);
86 }
87
addInst(MachineInstr * MI,SetVector<MachineInstr * > & Preds)88 void addInst(MachineInstr *MI, SetVector<MachineInstr*> &Preds) {
89 LLVM_DEBUG(dbgs() << "ARM Loops: Adding predicated MI: " << *MI);
90 if (!Divergent && !set_difference(Preds, VPST->Predicates).empty()) {
91 Divergent = &Insts.back();
92 LLVM_DEBUG(dbgs() << " - has divergent predicate: " << *Divergent->MI);
93 }
94 Insts.emplace_back(MI, Preds);
95 assert(Insts.size() <= 4 && "Too many instructions in VPT block!");
96 }
97
98 // Have we found an instruction within the block which defines the vpr? If
99 // so, not all the instructions in the block will have the same predicate.
HasNonUniformPredicate() const100 bool HasNonUniformPredicate() const {
101 return Divergent != nullptr;
102 }
103
104 // Is the given instruction part of the predicate set controlling the entry
105 // to the block.
IsPredicatedOn(MachineInstr * MI) const106 bool IsPredicatedOn(MachineInstr *MI) const {
107 return VPST->Predicates.count(MI);
108 }
109
110 // Is the given instruction the only predicate which controls the entry to
111 // the block.
IsOnlyPredicatedOn(MachineInstr * MI) const112 bool IsOnlyPredicatedOn(MachineInstr *MI) const {
113 return IsPredicatedOn(MI) && VPST->Predicates.size() == 1;
114 }
115
size() const116 unsigned size() const { return Insts.size(); }
getInsts()117 SmallVectorImpl<PredicatedMI> &getInsts() { return Insts; }
getVPST() const118 MachineInstr *getVPST() const { return VPST->MI; }
getDivergent() const119 PredicatedMI *getDivergent() const { return Divergent; }
120 };
121
122 struct LowOverheadLoop {
123
124 MachineLoop *ML = nullptr;
125 MachineFunction *MF = nullptr;
126 MachineInstr *InsertPt = nullptr;
127 MachineInstr *Start = nullptr;
128 MachineInstr *Dec = nullptr;
129 MachineInstr *End = nullptr;
130 MachineInstr *VCTP = nullptr;
131 VPTBlock *CurrentBlock = nullptr;
132 SetVector<MachineInstr*> CurrentPredicate;
133 SmallVector<VPTBlock, 4> VPTBlocks;
134 bool Revert = false;
135 bool CannotTailPredicate = false;
136
LowOverheadLoop__anonace2ebed0111::LowOverheadLoop137 LowOverheadLoop(MachineLoop *ML) : ML(ML) {
138 MF = ML->getHeader()->getParent();
139 }
140
141 // If this is an MVE instruction, check that we know how to use tail
142 // predication with it. Record VPT blocks and return whether the
143 // instruction is valid for tail predication.
144 bool ValidateMVEInst(MachineInstr *MI);
145
AnalyseMVEInst__anonace2ebed0111::LowOverheadLoop146 void AnalyseMVEInst(MachineInstr *MI) {
147 CannotTailPredicate = !ValidateMVEInst(MI);
148 }
149
IsTailPredicationLegal__anonace2ebed0111::LowOverheadLoop150 bool IsTailPredicationLegal() const {
151 // For now, let's keep things really simple and only support a single
152 // block for tail predication.
153 return !Revert && FoundAllComponents() && VCTP &&
154 !CannotTailPredicate && ML->getNumBlocks() == 1;
155 }
156
157 bool ValidateTailPredicate(MachineInstr *StartInsertPt,
158 ReachingDefAnalysis *RDA,
159 MachineLoopInfo *MLI);
160
161 // Is it safe to define LR with DLS/WLS?
162 // LR can be defined if it is the operand to start, because it's the same
163 // value, or if it's going to be equivalent to the operand to Start.
164 MachineInstr *IsSafeToDefineLR(ReachingDefAnalysis *RDA);
165
166 // Check the branch targets are within range and we satisfy our
167 // restrictions.
168 void CheckLegality(ARMBasicBlockUtils *BBUtils, ReachingDefAnalysis *RDA,
169 MachineLoopInfo *MLI);
170
FoundAllComponents__anonace2ebed0111::LowOverheadLoop171 bool FoundAllComponents() const {
172 return Start && Dec && End;
173 }
174
getVPTBlocks__anonace2ebed0111::LowOverheadLoop175 SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; }
176
177 // Return the loop iteration count, or the number of elements if we're tail
178 // predicating.
getCount__anonace2ebed0111::LowOverheadLoop179 MachineOperand &getCount() {
180 return IsTailPredicationLegal() ?
181 VCTP->getOperand(1) : Start->getOperand(0);
182 }
183
getStartOpcode__anonace2ebed0111::LowOverheadLoop184 unsigned getStartOpcode() const {
185 bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
186 if (!IsTailPredicationLegal())
187 return IsDo ? ARM::t2DLS : ARM::t2WLS;
188
189 return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo);
190 }
191
dump__anonace2ebed0111::LowOverheadLoop192 void dump() const {
193 if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
194 if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
195 if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
196 if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP;
197 if (!FoundAllComponents())
198 dbgs() << "ARM Loops: Not a low-overhead loop.\n";
199 else if (!(Start && Dec && End))
200 dbgs() << "ARM Loops: Failed to find all loop components.\n";
201 }
202 };
203
204 class ARMLowOverheadLoops : public MachineFunctionPass {
205 MachineFunction *MF = nullptr;
206 MachineLoopInfo *MLI = nullptr;
207 ReachingDefAnalysis *RDA = nullptr;
208 const ARMBaseInstrInfo *TII = nullptr;
209 MachineRegisterInfo *MRI = nullptr;
210 const TargetRegisterInfo *TRI = nullptr;
211 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
212
213 public:
214 static char ID;
215
ARMLowOverheadLoops()216 ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
217
getAnalysisUsage(AnalysisUsage & AU) const218 void getAnalysisUsage(AnalysisUsage &AU) const override {
219 AU.setPreservesCFG();
220 AU.addRequired<MachineLoopInfo>();
221 AU.addRequired<ReachingDefAnalysis>();
222 MachineFunctionPass::getAnalysisUsage(AU);
223 }
224
225 bool runOnMachineFunction(MachineFunction &MF) override;
226
getRequiredProperties() const227 MachineFunctionProperties getRequiredProperties() const override {
228 return MachineFunctionProperties().set(
229 MachineFunctionProperties::Property::NoVRegs).set(
230 MachineFunctionProperties::Property::TracksLiveness);
231 }
232
getPassName() const233 StringRef getPassName() const override {
234 return ARM_LOW_OVERHEAD_LOOPS_NAME;
235 }
236
237 private:
238 bool ProcessLoop(MachineLoop *ML);
239
240 bool RevertNonLoops();
241
242 void RevertWhile(MachineInstr *MI) const;
243
244 bool RevertLoopDec(MachineInstr *MI, bool AllowFlags = false) const;
245
246 void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
247
248 void RemoveLoopUpdate(LowOverheadLoop &LoLoop);
249
250 void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
251
252 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
253
254 void Expand(LowOverheadLoop &LoLoop);
255
256 };
257 }
258
259 char ARMLowOverheadLoops::ID = 0;
260
INITIALIZE_PASS(ARMLowOverheadLoops,DEBUG_TYPE,ARM_LOW_OVERHEAD_LOOPS_NAME,false,false)261 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
262 false, false)
263
264 MachineInstr *LowOverheadLoop::IsSafeToDefineLR(ReachingDefAnalysis *RDA) {
265 // We can define LR because LR already contains the same value.
266 if (Start->getOperand(0).getReg() == ARM::LR)
267 return Start;
268
269 unsigned CountReg = Start->getOperand(0).getReg();
270 auto IsMoveLR = [&CountReg](MachineInstr *MI) {
271 return MI->getOpcode() == ARM::tMOVr &&
272 MI->getOperand(0).getReg() == ARM::LR &&
273 MI->getOperand(1).getReg() == CountReg &&
274 MI->getOperand(2).getImm() == ARMCC::AL;
275 };
276
277 MachineBasicBlock *MBB = Start->getParent();
278
279 // Find an insertion point:
280 // - Is there a (mov lr, Count) before Start? If so, and nothing else writes
281 // to Count before Start, we can insert at that mov.
282 if (auto *LRDef = RDA->getReachingMIDef(Start, ARM::LR))
283 if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
284 return LRDef;
285
286 // - Is there a (mov lr, Count) after Start? If so, and nothing else writes
287 // to Count after Start, we can insert at that mov.
288 if (auto *LRDef = RDA->getLocalLiveOutMIDef(MBB, ARM::LR))
289 if (IsMoveLR(LRDef) && RDA->hasSameReachingDef(Start, LRDef, CountReg))
290 return LRDef;
291
292 // We've found no suitable LR def and Start doesn't use LR directly. Can we
293 // just define LR anyway?
294 if (!RDA->isRegUsedAfter(Start, ARM::LR))
295 return Start;
296
297 return nullptr;
298 }
299
300 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
301 // not define a register that is used by any instructions, after and including,
302 // 'To'. These instructions also must not redefine any of Froms operands.
303 template<typename Iterator>
IsSafeToMove(MachineInstr * From,MachineInstr * To,ReachingDefAnalysis * RDA)304 static bool IsSafeToMove(MachineInstr *From, MachineInstr *To, ReachingDefAnalysis *RDA) {
305 SmallSet<int, 2> Defs;
306 // First check that From would compute the same value if moved.
307 for (auto &MO : From->operands()) {
308 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
309 continue;
310 if (MO.isDef())
311 Defs.insert(MO.getReg());
312 else if (!RDA->hasSameReachingDef(From, To, MO.getReg()))
313 return false;
314 }
315
316 // Now walk checking that the rest of the instructions will compute the same
317 // value.
318 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
319 for (auto &MO : I->operands())
320 if (MO.isReg() && MO.getReg() && MO.isUse() && Defs.count(MO.getReg()))
321 return false;
322 }
323 return true;
324 }
325
ValidateTailPredicate(MachineInstr * StartInsertPt,ReachingDefAnalysis * RDA,MachineLoopInfo * MLI)326 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt,
327 ReachingDefAnalysis *RDA, MachineLoopInfo *MLI) {
328 assert(VCTP && "VCTP instruction expected but is not set");
329 // All predication within the loop should be based on vctp. If the block
330 // isn't predicated on entry, check whether the vctp is within the block
331 // and that all other instructions are then predicated on it.
332 for (auto &Block : VPTBlocks) {
333 if (Block.IsPredicatedOn(VCTP))
334 continue;
335 if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) {
336 LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: "
337 << *Block.getDivergent()->MI);
338 return false;
339 }
340 SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
341 for (auto &PredMI : Insts) {
342 if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI))
343 continue;
344 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI
345 << " - which is predicated on:\n";
346 for (auto *MI : PredMI.Predicates)
347 dbgs() << " - " << *MI;
348 );
349 return false;
350 }
351 }
352
353 // For tail predication, we need to provide the number of elements, instead
354 // of the iteration count, to the loop start instruction. The number of
355 // elements is provided to the vctp instruction, so we need to check that
356 // we can use this register at InsertPt.
357 Register NumElements = VCTP->getOperand(1).getReg();
358
359 // If the register is defined within loop, then we can't perform TP.
360 // TODO: Check whether this is just a mov of a register that would be
361 // available.
362 if (RDA->getReachingDef(VCTP, NumElements) >= 0) {
363 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
364 return false;
365 }
366
367 // The element count register maybe defined after InsertPt, in which case we
368 // need to try to move either InsertPt or the def so that the [w|d]lstp can
369 // use the value.
370 MachineBasicBlock *InsertBB = InsertPt->getParent();
371 if (!RDA->isReachingDefLiveOut(InsertPt, NumElements)) {
372 if (auto *ElemDef = RDA->getLocalLiveOutMIDef(InsertBB, NumElements)) {
373 if (IsSafeToMove<MachineBasicBlock::reverse_iterator>(ElemDef, InsertPt, RDA)) {
374 ElemDef->removeFromParent();
375 InsertBB->insert(MachineBasicBlock::iterator(InsertPt), ElemDef);
376 LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: "
377 << *ElemDef);
378 } else if (IsSafeToMove<MachineBasicBlock::iterator>(InsertPt, ElemDef, RDA)) {
379 InsertPt->removeFromParent();
380 InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef), InsertPt);
381 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
382 } else {
383 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop "
384 << "start instruction.\n");
385 return false;
386 }
387 }
388 }
389
390 // Especially in the case of while loops, InsertBB may not be the
391 // preheader, so we need to check that the register isn't redefined
392 // before entering the loop.
393 auto CannotProvideElements = [&RDA](MachineBasicBlock *MBB,
394 Register NumElements) {
395 // NumElements is redefined in this block.
396 if (RDA->getReachingDef(&MBB->back(), NumElements) >= 0)
397 return true;
398
399 // Don't continue searching up through multiple predecessors.
400 if (MBB->pred_size() > 1)
401 return true;
402
403 return false;
404 };
405
406 // First, find the block that looks like the preheader.
407 MachineBasicBlock *MBB = MLI->findLoopPreheader(ML, true);
408 if (!MBB) {
409 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n");
410 return false;
411 }
412
413 // Then search backwards for a def, until we get to InsertBB.
414 while (MBB != InsertBB) {
415 if (CannotProvideElements(MBB, NumElements)) {
416 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
417 return false;
418 }
419 MBB = *MBB->pred_begin();
420 }
421
422 LLVM_DEBUG(dbgs() << "ARM Loops: Will use tail predication.\n");
423 return true;
424 }
425
CheckLegality(ARMBasicBlockUtils * BBUtils,ReachingDefAnalysis * RDA,MachineLoopInfo * MLI)426 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils,
427 ReachingDefAnalysis *RDA,
428 MachineLoopInfo *MLI) {
429 if (Revert)
430 return;
431
432 if (!End->getOperand(1).isMBB())
433 report_fatal_error("Expected LoopEnd to target basic block");
434
435 // TODO Maybe there's cases where the target doesn't have to be the header,
436 // but for now be safe and revert.
437 if (End->getOperand(1).getMBB() != ML->getHeader()) {
438 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n");
439 Revert = true;
440 return;
441 }
442
443 // The WLS and LE instructions have 12-bits for the label offset. WLS
444 // requires a positive offset, while LE uses negative.
445 if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML->getHeader()) ||
446 !BBUtils->isBBInRange(End, ML->getHeader(), 4094)) {
447 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
448 Revert = true;
449 return;
450 }
451
452 if (Start->getOpcode() == ARM::t2WhileLoopStart &&
453 (BBUtils->getOffsetOf(Start) >
454 BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) ||
455 !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) {
456 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
457 Revert = true;
458 return;
459 }
460
461 InsertPt = Revert ? nullptr : IsSafeToDefineLR(RDA);
462 if (!InsertPt) {
463 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n");
464 Revert = true;
465 return;
466 } else
467 LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt);
468
469 if (!IsTailPredicationLegal()) {
470 LLVM_DEBUG(if (!VCTP)
471 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
472 dbgs() << "ARM Loops: Tail-predication is not valid.\n");
473 return;
474 }
475
476 assert(ML->getBlocks().size() == 1 &&
477 "Shouldn't be processing a loop with more than one block");
478 CannotTailPredicate = !ValidateTailPredicate(InsertPt, RDA, MLI);
479 LLVM_DEBUG(if (CannotTailPredicate)
480 dbgs() << "ARM Loops: Couldn't validate tail predicate.\n");
481 }
482
ValidateMVEInst(MachineInstr * MI)483 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) {
484 if (CannotTailPredicate)
485 return false;
486
487 // Only support a single vctp.
488 if (isVCTP(MI) && VCTP)
489 return false;
490
491 // Start a new vpt block when we discover a vpt.
492 if (MI->getOpcode() == ARM::MVE_VPST) {
493 VPTBlocks.emplace_back(MI, CurrentPredicate);
494 CurrentBlock = &VPTBlocks.back();
495 return true;
496 } else if (isVCTP(MI))
497 VCTP = MI;
498 else if (MI->getOpcode() == ARM::MVE_VPSEL ||
499 MI->getOpcode() == ARM::MVE_VPNOT)
500 return false;
501
502 // TODO: Allow VPSEL and VPNOT, we currently cannot because:
503 // 1) It will use the VPR as a predicate operand, but doesn't have to be
504 // instead a VPT block, which means we can assert while building up
505 // the VPT block because we don't find another VPST to being a new
506 // one.
507 // 2) VPSEL still requires a VPR operand even after tail predicating,
508 // which means we can't remove it unless there is another
509 // instruction, such as vcmp, that can provide the VPR def.
510
511 bool IsUse = false;
512 bool IsDef = false;
513 const MCInstrDesc &MCID = MI->getDesc();
514 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
515 const MachineOperand &MO = MI->getOperand(i);
516 if (!MO.isReg() || MO.getReg() != ARM::VPR)
517 continue;
518
519 if (MO.isDef()) {
520 CurrentPredicate.insert(MI);
521 IsDef = true;
522 } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) {
523 CurrentBlock->addInst(MI, CurrentPredicate);
524 IsUse = true;
525 } else {
526 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
527 return false;
528 }
529 }
530
531 // If we find a vpr def that is not already predicated on the vctp, we've
532 // got disjoint predicates that may not be equivalent when we do the
533 // conversion.
534 if (IsDef && !IsUse && VCTP && !isVCTP(MI)) {
535 LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI);
536 return false;
537 }
538
539 uint64_t Flags = MCID.TSFlags;
540 if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE)
541 return true;
542
543 // If we find an instruction that has been marked as not valid for tail
544 // predication, only allow the instruction if it's contained within a valid
545 // VPT block.
546 if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) {
547 LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI);
548 return false;
549 }
550
551 return true;
552 }
553
runOnMachineFunction(MachineFunction & mf)554 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
555 const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
556 if (!ST.hasLOB())
557 return false;
558
559 MF = &mf;
560 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
561
562 MLI = &getAnalysis<MachineLoopInfo>();
563 RDA = &getAnalysis<ReachingDefAnalysis>();
564 MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
565 MRI = &MF->getRegInfo();
566 TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
567 TRI = ST.getRegisterInfo();
568 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
569 BBUtils->computeAllBlockSizes();
570 BBUtils->adjustBBOffsetsAfter(&MF->front());
571
572 bool Changed = false;
573 for (auto ML : *MLI) {
574 if (!ML->getParentLoop())
575 Changed |= ProcessLoop(ML);
576 }
577 Changed |= RevertNonLoops();
578 return Changed;
579 }
580
ProcessLoop(MachineLoop * ML)581 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
582 // Process inner loops first.
583 for (auto I = ML->begin(), E = ML->end(); I != E; ++I)
584 ProcessLoop(*I);
585
586 LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n";
587 if (auto *Preheader = ML->getLoopPreheader())
588 dbgs() << " - " << Preheader->getName() << "\n";
589 else if (auto *Preheader = MLI->findLoopPreheader(ML))
590 dbgs() << " - " << Preheader->getName() << "\n";
591 for (auto *MBB : ML->getBlocks())
592 dbgs() << " - " << MBB->getName() << "\n";
593 );
594
595 // Search the given block for a loop start instruction. If one isn't found,
596 // and there's only one predecessor block, search that one too.
597 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
598 [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
599 for (auto &MI : *MBB) {
600 if (isLoopStart(MI))
601 return &MI;
602 }
603 if (MBB->pred_size() == 1)
604 return SearchForStart(*MBB->pred_begin());
605 return nullptr;
606 };
607
608 LowOverheadLoop LoLoop(ML);
609 // Search the preheader for the start intrinsic.
610 // FIXME: I don't see why we shouldn't be supporting multiple predecessors
611 // with potentially multiple set.loop.iterations, so we need to enable this.
612 if (auto *Preheader = ML->getLoopPreheader())
613 LoLoop.Start = SearchForStart(Preheader);
614 else if (auto *Preheader = MLI->findLoopPreheader(ML, true))
615 LoLoop.Start = SearchForStart(Preheader);
616 else
617 return false;
618
619 // Find the low-overhead loop components and decide whether or not to fall
620 // back to a normal loop. Also look for a vctp instructions and decide
621 // whether we can convert that predicate using tail predication.
622 for (auto *MBB : reverse(ML->getBlocks())) {
623 for (auto &MI : *MBB) {
624 if (MI.getOpcode() == ARM::t2LoopDec)
625 LoLoop.Dec = &MI;
626 else if (MI.getOpcode() == ARM::t2LoopEnd)
627 LoLoop.End = &MI;
628 else if (isLoopStart(MI))
629 LoLoop.Start = &MI;
630 else if (MI.getDesc().isCall()) {
631 // TODO: Though the call will require LE to execute again, does this
632 // mean we should revert? Always executing LE hopefully should be
633 // faster than performing a sub,cmp,br or even subs,br.
634 LoLoop.Revert = true;
635 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
636 } else {
637 // Record VPR defs and build up their corresponding vpt blocks.
638 // Check we know how to tail predicate any mve instructions.
639 LoLoop.AnalyseMVEInst(&MI);
640 }
641
642 // We need to ensure that LR is not used or defined inbetween LoopDec and
643 // LoopEnd.
644 if (!LoLoop.Dec || LoLoop.End || LoLoop.Revert)
645 continue;
646
647 // If we find that LR has been written or read between LoopDec and
648 // LoopEnd, expect that the decremented value is being used else where.
649 // Because this value isn't actually going to be produced until the
650 // latch, by LE, we would need to generate a real sub. The value is also
651 // likely to be copied/reloaded for use of LoopEnd - in which in case
652 // we'd need to perform an add because it gets subtracted again by LE!
653 // The other option is to then generate the other form of LE which doesn't
654 // perform the sub.
655 for (auto &MO : MI.operands()) {
656 if (MI.getOpcode() != ARM::t2LoopDec && MO.isReg() &&
657 MO.getReg() == ARM::LR) {
658 LLVM_DEBUG(dbgs() << "ARM Loops: Found LR Use/Def: " << MI);
659 LoLoop.Revert = true;
660 break;
661 }
662 }
663 }
664 }
665
666 LLVM_DEBUG(LoLoop.dump());
667 if (!LoLoop.FoundAllComponents()) {
668 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
669 return false;
670 }
671
672 LoLoop.CheckLegality(BBUtils.get(), RDA, MLI);
673 Expand(LoLoop);
674 return true;
675 }
676
677 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
678 // beq that branches to the exit branch.
679 // TODO: We could also try to generate a cbz if the value in LR is also in
680 // another low register.
RevertWhile(MachineInstr * MI) const681 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
682 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
683 MachineBasicBlock *MBB = MI->getParent();
684 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
685 TII->get(ARM::t2CMPri));
686 MIB.add(MI->getOperand(0));
687 MIB.addImm(0);
688 MIB.addImm(ARMCC::AL);
689 MIB.addReg(ARM::NoRegister);
690
691 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
692 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
693 ARM::tBcc : ARM::t2Bcc;
694
695 MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
696 MIB.add(MI->getOperand(1)); // branch target
697 MIB.addImm(ARMCC::EQ); // condition code
698 MIB.addReg(ARM::CPSR);
699 MI->eraseFromParent();
700 }
701
RevertLoopDec(MachineInstr * MI,bool SetFlags) const702 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI,
703 bool SetFlags) const {
704 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
705 MachineBasicBlock *MBB = MI->getParent();
706
707 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
708 if (SetFlags &&
709 (RDA->isRegUsedAfter(MI, ARM::CPSR) ||
710 !RDA->hasSameReachingDef(MI, &MBB->back(), ARM::CPSR)))
711 SetFlags = false;
712
713 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
714 TII->get(ARM::t2SUBri));
715 MIB.addDef(ARM::LR);
716 MIB.add(MI->getOperand(1));
717 MIB.add(MI->getOperand(2));
718 MIB.addImm(ARMCC::AL);
719 MIB.addReg(0);
720
721 if (SetFlags) {
722 MIB.addReg(ARM::CPSR);
723 MIB->getOperand(5).setIsDef(true);
724 } else
725 MIB.addReg(0);
726
727 MI->eraseFromParent();
728 return SetFlags;
729 }
730
731 // Generate a subs, or sub and cmp, and a branch instead of an LE.
RevertLoopEnd(MachineInstr * MI,bool SkipCmp) const732 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
733 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
734
735 MachineBasicBlock *MBB = MI->getParent();
736 // Create cmp
737 if (!SkipCmp) {
738 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(),
739 TII->get(ARM::t2CMPri));
740 MIB.addReg(ARM::LR);
741 MIB.addImm(0);
742 MIB.addImm(ARMCC::AL);
743 MIB.addReg(ARM::NoRegister);
744 }
745
746 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
747 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
748 ARM::tBcc : ARM::t2Bcc;
749
750 // Create bne
751 MachineInstrBuilder MIB =
752 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
753 MIB.add(MI->getOperand(1)); // branch target
754 MIB.addImm(ARMCC::NE); // condition code
755 MIB.addReg(ARM::CPSR);
756 MI->eraseFromParent();
757 }
758
ExpandLoopStart(LowOverheadLoop & LoLoop)759 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
760 MachineInstr *InsertPt = LoLoop.InsertPt;
761 MachineInstr *Start = LoLoop.Start;
762 MachineBasicBlock *MBB = InsertPt->getParent();
763 bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart;
764 unsigned Opc = LoLoop.getStartOpcode();
765 MachineOperand &Count = LoLoop.getCount();
766
767 MachineInstrBuilder MIB =
768 BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc));
769
770 MIB.addDef(ARM::LR);
771 MIB.add(Count);
772 if (!IsDo)
773 MIB.add(Start->getOperand(1));
774
775 // When using tail-predication, try to delete the dead code that was used to
776 // calculate the number of loop iterations.
777 if (LoLoop.IsTailPredicationLegal()) {
778 SmallVector<MachineInstr*, 4> Killed;
779 SmallVector<MachineInstr*, 4> Dead;
780 if (auto *Def = RDA->getReachingMIDef(Start,
781 Start->getOperand(0).getReg())) {
782 Killed.push_back(Def);
783
784 while (!Killed.empty()) {
785 MachineInstr *Def = Killed.back();
786 Killed.pop_back();
787 Dead.push_back(Def);
788 for (auto &MO : Def->operands()) {
789 if (!MO.isReg() || !MO.isKill())
790 continue;
791
792 MachineInstr *Kill = RDA->getReachingMIDef(Def, MO.getReg());
793 if (Kill && RDA->getNumUses(Kill, MO.getReg()) == 1)
794 Killed.push_back(Kill);
795 }
796 }
797 for (auto *MI : Dead)
798 MI->eraseFromParent();
799 }
800 }
801
802 // If we're inserting at a mov lr, then remove it as it's redundant.
803 if (InsertPt != Start)
804 InsertPt->eraseFromParent();
805 Start->eraseFromParent();
806 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
807 return &*MIB;
808 }
809
810 // Goal is to optimise and clean-up these loops:
811 //
812 // vector.body:
813 // renamable $vpr = MVE_VCTP32 renamable $r3, 0, $noreg
814 // renamable $r3, dead $cpsr = tSUBi8 killed renamable $r3(tied-def 0), 4
815 // ..
816 // $lr = MVE_DLSTP_32 renamable $r3
817 //
818 // The SUB is the old update of the loop iteration count expression, which
819 // is no longer needed. This sub is removed when the element count, which is in
820 // r3 in this example, is defined by an instruction in the loop, and it has
821 // no uses.
822 //
RemoveLoopUpdate(LowOverheadLoop & LoLoop)823 void ARMLowOverheadLoops::RemoveLoopUpdate(LowOverheadLoop &LoLoop) {
824 Register ElemCount = LoLoop.VCTP->getOperand(1).getReg();
825 MachineInstr *LastInstrInBlock = &LoLoop.VCTP->getParent()->back();
826
827 LLVM_DEBUG(dbgs() << "ARM Loops: Trying to remove loop update stmt\n");
828
829 if (LoLoop.ML->getNumBlocks() != 1) {
830 LLVM_DEBUG(dbgs() << "ARM Loops: Single block loop expected\n");
831 return;
832 }
833
834 LLVM_DEBUG(dbgs() << "ARM Loops: Analyzing elemcount in operand: ";
835 LoLoop.VCTP->getOperand(1).dump());
836
837 // Find the definition we are interested in removing, if there is one.
838 MachineInstr *Def = RDA->getReachingMIDef(LastInstrInBlock, ElemCount);
839 if (!Def) {
840 LLVM_DEBUG(dbgs() << "ARM Loops: Can't find a def, nothing to do.\n");
841 return;
842 }
843
844 // Bail if we define CPSR and it is not dead
845 if (!Def->registerDefIsDead(ARM::CPSR, TRI)) {
846 LLVM_DEBUG(dbgs() << "ARM Loops: CPSR is not dead\n");
847 return;
848 }
849
850 // Bail if elemcount is used in exit blocks, i.e. if it is live-in.
851 if (isRegLiveInExitBlocks(LoLoop.ML, ElemCount)) {
852 LLVM_DEBUG(dbgs() << "ARM Loops: Elemcount is live-out, can't remove stmt\n");
853 return;
854 }
855
856 // Bail if there are uses after this Def in the block.
857 SmallVector<MachineInstr*, 4> Uses;
858 RDA->getReachingLocalUses(Def, ElemCount, Uses);
859 if (Uses.size()) {
860 LLVM_DEBUG(dbgs() << "ARM Loops: Local uses in block, can't remove stmt\n");
861 return;
862 }
863
864 Uses.clear();
865 RDA->getAllInstWithUseBefore(Def, ElemCount, Uses);
866
867 // Remove Def if there are no uses, or if the only use is the VCTP
868 // instruction.
869 if (!Uses.size() || (Uses.size() == 1 && Uses[0] == LoLoop.VCTP)) {
870 LLVM_DEBUG(dbgs() << "ARM Loops: Removing loop update instruction: ";
871 Def->dump());
872 Def->eraseFromParent();
873 return;
874 }
875
876 LLVM_DEBUG(dbgs() << "ARM Loops: Can't remove loop update, it's used by:\n";
877 for (auto U : Uses) U->dump());
878 }
879
ConvertVPTBlocks(LowOverheadLoop & LoLoop)880 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
881 auto RemovePredicate = [](MachineInstr *MI) {
882 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
883 if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) {
884 assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
885 "Expected Then predicate!");
886 MI->getOperand(PIdx).setImm(ARMVCC::None);
887 MI->getOperand(PIdx+1).setReg(0);
888 } else
889 llvm_unreachable("trying to unpredicate a non-predicated instruction");
890 };
891
892 // There are a few scenarios which we have to fix up:
893 // 1) A VPT block with is only predicated by the vctp and has no internal vpr
894 // defs.
895 // 2) A VPT block which is only predicated by the vctp but has an internal
896 // vpr def.
897 // 3) A VPT block which is predicated upon the vctp as well as another vpr
898 // def.
899 // 4) A VPT block which is not predicated upon a vctp, but contains it and
900 // all instructions within the block are predicated upon in.
901
902 for (auto &Block : LoLoop.getVPTBlocks()) {
903 SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts();
904 if (Block.HasNonUniformPredicate()) {
905 PredicatedMI *Divergent = Block.getDivergent();
906 if (isVCTP(Divergent->MI)) {
907 // The vctp will be removed, so the size of the vpt block needs to be
908 // modified.
909 uint64_t Size = getARMVPTBlockMask(Block.size() - 1);
910 Block.getVPST()->getOperand(0).setImm(Size);
911 LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n");
912 } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
913 // The VPT block has a non-uniform predicate but it's entry is guarded
914 // only by a vctp, which means we:
915 // - Need to remove the original vpst.
916 // - Then need to unpredicate any following instructions, until
917 // we come across the divergent vpr def.
918 // - Insert a new vpst to predicate the instruction(s) that following
919 // the divergent vpr def.
920 // TODO: We could be producing more VPT blocks than necessary and could
921 // fold the newly created one into a proceeding one.
922 for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()),
923 E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I)
924 RemovePredicate(&*I);
925
926 unsigned Size = 0;
927 auto E = MachineBasicBlock::reverse_iterator(Divergent->MI);
928 auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI);
929 MachineInstr *InsertAt = nullptr;
930 while (I != E) {
931 InsertAt = &*I;
932 ++Size;
933 ++I;
934 }
935 MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt,
936 InsertAt->getDebugLoc(),
937 TII->get(ARM::MVE_VPST));
938 MIB.addImm(getARMVPTBlockMask(Size));
939 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
940 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
941 Block.getVPST()->eraseFromParent();
942 }
943 } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) {
944 // A vpt block which is only predicated upon vctp and has no internal vpr
945 // defs:
946 // - Remove vpst.
947 // - Unpredicate the remaining instructions.
948 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST());
949 Block.getVPST()->eraseFromParent();
950 for (auto &PredMI : Insts)
951 RemovePredicate(PredMI.MI);
952 }
953 }
954
955 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP);
956 LoLoop.VCTP->eraseFromParent();
957 }
958
Expand(LowOverheadLoop & LoLoop)959 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
960
961 // Combine the LoopDec and LoopEnd instructions into LE(TP).
962 auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
963 MachineInstr *End = LoLoop.End;
964 MachineBasicBlock *MBB = End->getParent();
965 unsigned Opc = LoLoop.IsTailPredicationLegal() ?
966 ARM::MVE_LETP : ARM::t2LEUpdate;
967 MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
968 TII->get(Opc));
969 MIB.addDef(ARM::LR);
970 MIB.add(End->getOperand(0));
971 MIB.add(End->getOperand(1));
972 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
973
974 LoLoop.End->eraseFromParent();
975 LoLoop.Dec->eraseFromParent();
976 return &*MIB;
977 };
978
979 // TODO: We should be able to automatically remove these branches before we
980 // get here - probably by teaching analyzeBranch about the pseudo
981 // instructions.
982 // If there is an unconditional branch, after I, that just branches to the
983 // next block, remove it.
984 auto RemoveDeadBranch = [](MachineInstr *I) {
985 MachineBasicBlock *BB = I->getParent();
986 MachineInstr *Terminator = &BB->instr_back();
987 if (Terminator->isUnconditionalBranch() && I != Terminator) {
988 MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
989 if (BB->isLayoutSuccessor(Succ)) {
990 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
991 Terminator->eraseFromParent();
992 }
993 }
994 };
995
996 if (LoLoop.Revert) {
997 if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart)
998 RevertWhile(LoLoop.Start);
999 else
1000 LoLoop.Start->eraseFromParent();
1001 bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec, true);
1002 RevertLoopEnd(LoLoop.End, FlagsAlreadySet);
1003 } else {
1004 LoLoop.Start = ExpandLoopStart(LoLoop);
1005 RemoveDeadBranch(LoLoop.Start);
1006 LoLoop.End = ExpandLoopEnd(LoLoop);
1007 RemoveDeadBranch(LoLoop.End);
1008 if (LoLoop.IsTailPredicationLegal()) {
1009 RemoveLoopUpdate(LoLoop);
1010 ConvertVPTBlocks(LoLoop);
1011 }
1012 }
1013 }
1014
RevertNonLoops()1015 bool ARMLowOverheadLoops::RevertNonLoops() {
1016 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
1017 bool Changed = false;
1018
1019 for (auto &MBB : *MF) {
1020 SmallVector<MachineInstr*, 4> Starts;
1021 SmallVector<MachineInstr*, 4> Decs;
1022 SmallVector<MachineInstr*, 4> Ends;
1023
1024 for (auto &I : MBB) {
1025 if (isLoopStart(I))
1026 Starts.push_back(&I);
1027 else if (I.getOpcode() == ARM::t2LoopDec)
1028 Decs.push_back(&I);
1029 else if (I.getOpcode() == ARM::t2LoopEnd)
1030 Ends.push_back(&I);
1031 }
1032
1033 if (Starts.empty() && Decs.empty() && Ends.empty())
1034 continue;
1035
1036 Changed = true;
1037
1038 for (auto *Start : Starts) {
1039 if (Start->getOpcode() == ARM::t2WhileLoopStart)
1040 RevertWhile(Start);
1041 else
1042 Start->eraseFromParent();
1043 }
1044 for (auto *Dec : Decs)
1045 RevertLoopDec(Dec);
1046
1047 for (auto *End : Ends)
1048 RevertLoopEnd(End);
1049 }
1050 return Changed;
1051 }
1052
createARMLowOverheadLoopsPass()1053 FunctionPass *llvm::createARMLowOverheadLoopsPass() {
1054 return new ARMLowOverheadLoops();
1055 }
1056