ARMLowOverheadLoops.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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, t2WhileLoopStartLR and t2LoopEnd
  35. /// are defined to be as large as this maximum sequence of replacement
  36. /// instructions.
  37. ///
  38. /// A note on VPR.P0 (the lane mask):
  39. /// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a
  40. /// "VPT Active" context (which includes low-overhead loops and vpt blocks).
  41. /// They will simply "and" the result of their calculation with the current
  42. /// value of VPR.P0. You can think of it like this:
  43. /// \verbatim
  44. /// if VPT active: ; Between a DLSTP/LETP, or for predicated instrs
  45. /// VPR.P0 &= Value
  46. /// else
  47. /// VPR.P0 = Value
  48. /// \endverbatim
  49. /// When we're inside the low-overhead loop (between DLSTP and LETP), we always
  50. /// fall in the "VPT active" case, so we can consider that all VPR writes by
  51. /// one of those instruction is actually a "and".
  52. //===----------------------------------------------------------------------===//
  53. #include "ARM.h"
  54. #include "ARMBaseInstrInfo.h"
  55. #include "ARMBaseRegisterInfo.h"
  56. #include "ARMBasicBlockInfo.h"
  57. #include "ARMSubtarget.h"
  58. #include "MVETailPredUtils.h"
  59. #include "Thumb2InstrInfo.h"
  60. #include "llvm/ADT/SetOperations.h"
  61. #include "llvm/ADT/SmallSet.h"
  62. #include "llvm/CodeGen/LivePhysRegs.h"
  63. #include "llvm/CodeGen/MachineFunctionPass.h"
  64. #include "llvm/CodeGen/MachineLoopInfo.h"
  65. #include "llvm/CodeGen/MachineLoopUtils.h"
  66. #include "llvm/CodeGen/MachineRegisterInfo.h"
  67. #include "llvm/CodeGen/Passes.h"
  68. #include "llvm/CodeGen/ReachingDefAnalysis.h"
  69. #include "llvm/MC/MCInstrDesc.h"
  70. using namespace llvm;
  71. #define DEBUG_TYPE "arm-low-overhead-loops"
  72. #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass"
  73. static cl::opt<bool>
  74. DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden,
  75. cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"),
  76. cl::init(false));
  77. static bool isVectorPredicated(MachineInstr *MI) {
  78. int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
  79. return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR;
  80. }
  81. static bool isVectorPredicate(MachineInstr *MI) {
  82. return MI->findRegisterDefOperandIdx(ARM::VPR) != -1;
  83. }
  84. static bool hasVPRUse(MachineInstr &MI) {
  85. return MI.findRegisterUseOperandIdx(ARM::VPR) != -1;
  86. }
  87. static bool isDomainMVE(MachineInstr *MI) {
  88. uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
  89. return Domain == ARMII::DomainMVE;
  90. }
  91. static int getVecSize(const MachineInstr &MI) {
  92. const MCInstrDesc &MCID = MI.getDesc();
  93. uint64_t Flags = MCID.TSFlags;
  94. return (Flags & ARMII::VecSize) >> ARMII::VecSizeShift;
  95. }
  96. static bool shouldInspect(MachineInstr &MI) {
  97. if (MI.isDebugInstr())
  98. return false;
  99. return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI);
  100. }
  101. namespace {
  102. using InstSet = SmallPtrSetImpl<MachineInstr *>;
  103. class PostOrderLoopTraversal {
  104. MachineLoop &ML;
  105. MachineLoopInfo &MLI;
  106. SmallPtrSet<MachineBasicBlock*, 4> Visited;
  107. SmallVector<MachineBasicBlock*, 4> Order;
  108. public:
  109. PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI)
  110. : ML(ML), MLI(MLI) { }
  111. const SmallVectorImpl<MachineBasicBlock*> &getOrder() const {
  112. return Order;
  113. }
  114. // Visit all the blocks within the loop, as well as exit blocks and any
  115. // blocks properly dominating the header.
  116. void ProcessLoop() {
  117. std::function<void(MachineBasicBlock*)> Search = [this, &Search]
  118. (MachineBasicBlock *MBB) -> void {
  119. if (Visited.count(MBB))
  120. return;
  121. Visited.insert(MBB);
  122. for (auto *Succ : MBB->successors()) {
  123. if (!ML.contains(Succ))
  124. continue;
  125. Search(Succ);
  126. }
  127. Order.push_back(MBB);
  128. };
  129. // Insert exit blocks.
  130. SmallVector<MachineBasicBlock*, 2> ExitBlocks;
  131. ML.getExitBlocks(ExitBlocks);
  132. append_range(Order, ExitBlocks);
  133. // Then add the loop body.
  134. Search(ML.getHeader());
  135. // Then try the preheader and its predecessors.
  136. std::function<void(MachineBasicBlock*)> GetPredecessor =
  137. [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void {
  138. Order.push_back(MBB);
  139. if (MBB->pred_size() == 1)
  140. GetPredecessor(*MBB->pred_begin());
  141. };
  142. if (auto *Preheader = ML.getLoopPreheader())
  143. GetPredecessor(Preheader);
  144. else if (auto *Preheader = MLI.findLoopPreheader(&ML, true, true))
  145. GetPredecessor(Preheader);
  146. }
  147. };
  148. struct PredicatedMI {
  149. MachineInstr *MI = nullptr;
  150. SetVector<MachineInstr*> Predicates;
  151. public:
  152. PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) {
  153. assert(I && "Instruction must not be null!");
  154. Predicates.insert(Preds.begin(), Preds.end());
  155. }
  156. };
  157. // Represent the current state of the VPR and hold all instances which
  158. // represent a VPT block, which is a list of instructions that begins with a
  159. // VPT/VPST and has a maximum of four proceeding instructions. All
  160. // instructions within the block are predicated upon the vpr and we allow
  161. // instructions to define the vpr within in the block too.
  162. class VPTState {
  163. friend struct LowOverheadLoop;
  164. SmallVector<MachineInstr *, 4> Insts;
  165. static SmallVector<VPTState, 4> Blocks;
  166. static SetVector<MachineInstr *> CurrentPredicates;
  167. static std::map<MachineInstr *,
  168. std::unique_ptr<PredicatedMI>> PredicatedInsts;
  169. static void CreateVPTBlock(MachineInstr *MI) {
  170. assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR))
  171. && "Can't begin VPT without predicate");
  172. Blocks.emplace_back(MI);
  173. // The execution of MI is predicated upon the current set of instructions
  174. // that are AND'ed together to form the VPR predicate value. In the case
  175. // that MI is a VPT, CurrentPredicates will also just be MI.
  176. PredicatedInsts.emplace(
  177. MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
  178. }
  179. static void reset() {
  180. Blocks.clear();
  181. PredicatedInsts.clear();
  182. CurrentPredicates.clear();
  183. }
  184. static void addInst(MachineInstr *MI) {
  185. Blocks.back().insert(MI);
  186. PredicatedInsts.emplace(
  187. MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates));
  188. }
  189. static void addPredicate(MachineInstr *MI) {
  190. LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI);
  191. CurrentPredicates.insert(MI);
  192. }
  193. static void resetPredicate(MachineInstr *MI) {
  194. LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI);
  195. CurrentPredicates.clear();
  196. CurrentPredicates.insert(MI);
  197. }
  198. public:
  199. // Have we found an instruction within the block which defines the vpr? If
  200. // so, not all the instructions in the block will have the same predicate.
  201. static bool hasUniformPredicate(VPTState &Block) {
  202. return getDivergent(Block) == nullptr;
  203. }
  204. // If it exists, return the first internal instruction which modifies the
  205. // VPR.
  206. static MachineInstr *getDivergent(VPTState &Block) {
  207. SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
  208. for (unsigned i = 1; i < Insts.size(); ++i) {
  209. MachineInstr *Next = Insts[i];
  210. if (isVectorPredicate(Next))
  211. return Next; // Found an instruction altering the vpr.
  212. }
  213. return nullptr;
  214. }
  215. // Return whether the given instruction is predicated upon a VCTP.
  216. static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) {
  217. SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates;
  218. if (Exclusive && Predicates.size() != 1)
  219. return false;
  220. return llvm::any_of(Predicates, isVCTP);
  221. }
  222. // Is the VPST, controlling the block entry, predicated upon a VCTP.
  223. static bool isEntryPredicatedOnVCTP(VPTState &Block,
  224. bool Exclusive = false) {
  225. SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
  226. return isPredicatedOnVCTP(Insts.front(), Exclusive);
  227. }
  228. // If this block begins with a VPT, we can check whether it's using
  229. // at least one predicated input(s), as well as possible loop invariant
  230. // which would result in it being implicitly predicated.
  231. static bool hasImplicitlyValidVPT(VPTState &Block,
  232. ReachingDefAnalysis &RDA) {
  233. SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
  234. MachineInstr *VPT = Insts.front();
  235. assert(isVPTOpcode(VPT->getOpcode()) &&
  236. "Expected VPT block to begin with VPT/VPST");
  237. if (VPT->getOpcode() == ARM::MVE_VPST)
  238. return false;
  239. auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) {
  240. MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx));
  241. return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op);
  242. };
  243. auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) {
  244. MachineOperand &MO = MI->getOperand(Idx);
  245. if (!MO.isReg() || !MO.getReg())
  246. return true;
  247. SmallPtrSet<MachineInstr *, 2> Defs;
  248. RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs);
  249. if (Defs.empty())
  250. return true;
  251. for (auto *Def : Defs)
  252. if (Def->getParent() == VPT->getParent())
  253. return false;
  254. return true;
  255. };
  256. // Check that at least one of the operands is directly predicated on a
  257. // vctp and allow an invariant value too.
  258. return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) &&
  259. (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) &&
  260. (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2));
  261. }
  262. static bool isValid(ReachingDefAnalysis &RDA) {
  263. // All predication within the loop should be based on vctp. If the block
  264. // isn't predicated on entry, check whether the vctp is within the block
  265. // and that all other instructions are then predicated on it.
  266. for (auto &Block : Blocks) {
  267. if (isEntryPredicatedOnVCTP(Block, false) ||
  268. hasImplicitlyValidVPT(Block, RDA))
  269. continue;
  270. SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
  271. // We don't know how to convert a block with just a VPT;VCTP into
  272. // anything valid once we remove the VCTP. For now just bail out.
  273. assert(isVPTOpcode(Insts.front()->getOpcode()) &&
  274. "Expected VPT block to start with a VPST or VPT!");
  275. if (Insts.size() == 2 && Insts.front()->getOpcode() != ARM::MVE_VPST &&
  276. isVCTP(Insts.back()))
  277. return false;
  278. for (auto *MI : Insts) {
  279. // Check that any internal VCTPs are 'Then' predicated.
  280. if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then)
  281. return false;
  282. // Skip other instructions that build up the predicate.
  283. if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI))
  284. continue;
  285. // Check that any other instructions are predicated upon a vctp.
  286. // TODO: We could infer when VPTs are implicitly predicated on the
  287. // vctp (when the operands are predicated).
  288. if (!isPredicatedOnVCTP(MI)) {
  289. LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI);
  290. return false;
  291. }
  292. }
  293. }
  294. return true;
  295. }
  296. VPTState(MachineInstr *MI) { Insts.push_back(MI); }
  297. void insert(MachineInstr *MI) {
  298. Insts.push_back(MI);
  299. // VPT/VPST + 4 predicated instructions.
  300. assert(Insts.size() <= 5 && "Too many instructions in VPT block!");
  301. }
  302. bool containsVCTP() const {
  303. return llvm::any_of(Insts, isVCTP);
  304. }
  305. unsigned size() const { return Insts.size(); }
  306. SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; }
  307. };
  308. struct LowOverheadLoop {
  309. MachineLoop &ML;
  310. MachineBasicBlock *Preheader = nullptr;
  311. MachineLoopInfo &MLI;
  312. ReachingDefAnalysis &RDA;
  313. const TargetRegisterInfo &TRI;
  314. const ARMBaseInstrInfo &TII;
  315. MachineFunction *MF = nullptr;
  316. MachineBasicBlock::iterator StartInsertPt;
  317. MachineBasicBlock *StartInsertBB = nullptr;
  318. MachineInstr *Start = nullptr;
  319. MachineInstr *Dec = nullptr;
  320. MachineInstr *End = nullptr;
  321. MachineOperand TPNumElements;
  322. SmallVector<MachineInstr *, 4> VCTPs;
  323. SmallPtrSet<MachineInstr *, 4> ToRemove;
  324. SmallPtrSet<MachineInstr *, 4> BlockMasksToRecompute;
  325. SmallPtrSet<MachineInstr *, 4> DoubleWidthResultInstrs;
  326. SmallPtrSet<MachineInstr *, 4> VMOVCopies;
  327. bool Revert = false;
  328. bool CannotTailPredicate = false;
  329. LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI,
  330. ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI,
  331. const ARMBaseInstrInfo &TII)
  332. : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII),
  333. TPNumElements(MachineOperand::CreateImm(0)) {
  334. MF = ML.getHeader()->getParent();
  335. if (auto *MBB = ML.getLoopPreheader())
  336. Preheader = MBB;
  337. else if (auto *MBB = MLI.findLoopPreheader(&ML, true, true))
  338. Preheader = MBB;
  339. VPTState::reset();
  340. }
  341. // If this is an MVE instruction, check that we know how to use tail
  342. // predication with it. Record VPT blocks and return whether the
  343. // instruction is valid for tail predication.
  344. bool ValidateMVEInst(MachineInstr *MI);
  345. void AnalyseMVEInst(MachineInstr *MI) {
  346. CannotTailPredicate = !ValidateMVEInst(MI);
  347. }
  348. bool IsTailPredicationLegal() const {
  349. // For now, let's keep things really simple and only support a single
  350. // block for tail predication.
  351. return !Revert && FoundAllComponents() && !VCTPs.empty() &&
  352. !CannotTailPredicate && ML.getNumBlocks() == 1;
  353. }
  354. // Given that MI is a VCTP, check that is equivalent to any other VCTPs
  355. // found.
  356. bool AddVCTP(MachineInstr *MI);
  357. // Check that the predication in the loop will be equivalent once we
  358. // perform the conversion. Also ensure that we can provide the number
  359. // of elements to the loop start instruction.
  360. bool ValidateTailPredicate();
  361. // Check that any values available outside of the loop will be the same
  362. // after tail predication conversion.
  363. bool ValidateLiveOuts();
  364. // Is it safe to define LR with DLS/WLS?
  365. // LR can be defined if it is the operand to start, because it's the same
  366. // value, or if it's going to be equivalent to the operand to Start.
  367. MachineInstr *isSafeToDefineLR();
  368. // Check the branch targets are within range and we satisfy our
  369. // restrictions.
  370. void Validate(ARMBasicBlockUtils *BBUtils);
  371. bool FoundAllComponents() const {
  372. return Start && Dec && End;
  373. }
  374. SmallVectorImpl<VPTState> &getVPTBlocks() {
  375. return VPTState::Blocks;
  376. }
  377. // Return the operand for the loop start instruction. This will be the loop
  378. // iteration count, or the number of elements if we're tail predicating.
  379. MachineOperand &getLoopStartOperand() {
  380. if (IsTailPredicationLegal())
  381. return TPNumElements;
  382. return Start->getOperand(1);
  383. }
  384. unsigned getStartOpcode() const {
  385. bool IsDo = isDoLoopStart(*Start);
  386. if (!IsTailPredicationLegal())
  387. return IsDo ? ARM::t2DLS : ARM::t2WLS;
  388. return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo);
  389. }
  390. void dump() const {
  391. if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start;
  392. if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec;
  393. if (End) dbgs() << "ARM Loops: Found Loop End: " << *End;
  394. if (!VCTPs.empty()) {
  395. dbgs() << "ARM Loops: Found VCTP(s):\n";
  396. for (auto *MI : VCTPs)
  397. dbgs() << " - " << *MI;
  398. }
  399. if (!FoundAllComponents())
  400. dbgs() << "ARM Loops: Not a low-overhead loop.\n";
  401. else if (!(Start && Dec && End))
  402. dbgs() << "ARM Loops: Failed to find all loop components.\n";
  403. }
  404. };
  405. class ARMLowOverheadLoops : public MachineFunctionPass {
  406. MachineFunction *MF = nullptr;
  407. MachineLoopInfo *MLI = nullptr;
  408. ReachingDefAnalysis *RDA = nullptr;
  409. const ARMBaseInstrInfo *TII = nullptr;
  410. MachineRegisterInfo *MRI = nullptr;
  411. const TargetRegisterInfo *TRI = nullptr;
  412. std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;
  413. public:
  414. static char ID;
  415. ARMLowOverheadLoops() : MachineFunctionPass(ID) { }
  416. void getAnalysisUsage(AnalysisUsage &AU) const override {
  417. AU.setPreservesCFG();
  418. AU.addRequired<MachineLoopInfo>();
  419. AU.addRequired<ReachingDefAnalysis>();
  420. MachineFunctionPass::getAnalysisUsage(AU);
  421. }
  422. bool runOnMachineFunction(MachineFunction &MF) override;
  423. MachineFunctionProperties getRequiredProperties() const override {
  424. return MachineFunctionProperties().set(
  425. MachineFunctionProperties::Property::NoVRegs).set(
  426. MachineFunctionProperties::Property::TracksLiveness);
  427. }
  428. StringRef getPassName() const override {
  429. return ARM_LOW_OVERHEAD_LOOPS_NAME;
  430. }
  431. private:
  432. bool ProcessLoop(MachineLoop *ML);
  433. bool RevertNonLoops();
  434. void RevertWhile(MachineInstr *MI) const;
  435. void RevertDo(MachineInstr *MI) const;
  436. bool RevertLoopDec(MachineInstr *MI) const;
  437. void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const;
  438. void RevertLoopEndDec(MachineInstr *MI) const;
  439. void ConvertVPTBlocks(LowOverheadLoop &LoLoop);
  440. MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop);
  441. void Expand(LowOverheadLoop &LoLoop);
  442. void IterationCountDCE(LowOverheadLoop &LoLoop);
  443. };
  444. }
  445. char ARMLowOverheadLoops::ID = 0;
  446. SmallVector<VPTState, 4> VPTState::Blocks;
  447. SetVector<MachineInstr *> VPTState::CurrentPredicates;
  448. std::map<MachineInstr *,
  449. std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts;
  450. INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME,
  451. false, false)
  452. static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA,
  453. InstSet &ToRemove, InstSet &Ignore) {
  454. // Check that we can remove all of Killed without having to modify any IT
  455. // blocks.
  456. auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) {
  457. // Collect the dead code and the MBBs in which they reside.
  458. SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks;
  459. for (auto *Dead : Killed)
  460. BasicBlocks.insert(Dead->getParent());
  461. // Collect IT blocks in all affected basic blocks.
  462. std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks;
  463. for (auto *MBB : BasicBlocks) {
  464. for (auto &IT : *MBB) {
  465. if (IT.getOpcode() != ARM::t2IT)
  466. continue;
  467. RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE),
  468. ITBlocks[&IT]);
  469. }
  470. }
  471. // If we're removing all of the instructions within an IT block, then
  472. // also remove the IT instruction.
  473. SmallPtrSet<MachineInstr *, 2> ModifiedITs;
  474. SmallPtrSet<MachineInstr *, 2> RemoveITs;
  475. for (auto *Dead : Killed) {
  476. if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) {
  477. MachineInstr *IT = RDA.getMIOperand(Dead, *MO);
  478. RemoveITs.insert(IT);
  479. auto &CurrentBlock = ITBlocks[IT];
  480. CurrentBlock.erase(Dead);
  481. if (CurrentBlock.empty())
  482. ModifiedITs.erase(IT);
  483. else
  484. ModifiedITs.insert(IT);
  485. }
  486. }
  487. if (!ModifiedITs.empty())
  488. return false;
  489. Killed.insert(RemoveITs.begin(), RemoveITs.end());
  490. return true;
  491. };
  492. SmallPtrSet<MachineInstr *, 2> Uses;
  493. if (!RDA.isSafeToRemove(MI, Uses, Ignore))
  494. return false;
  495. if (WontCorruptITs(Uses, RDA)) {
  496. ToRemove.insert(Uses.begin(), Uses.end());
  497. LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI
  498. << " - can also remove:\n";
  499. for (auto *Use : Uses)
  500. dbgs() << " - " << *Use);
  501. SmallPtrSet<MachineInstr*, 4> Killed;
  502. RDA.collectKilledOperands(MI, Killed);
  503. if (WontCorruptITs(Killed, RDA)) {
  504. ToRemove.insert(Killed.begin(), Killed.end());
  505. LLVM_DEBUG(for (auto *Dead : Killed)
  506. dbgs() << " - " << *Dead);
  507. }
  508. return true;
  509. }
  510. return false;
  511. }
  512. bool LowOverheadLoop::ValidateTailPredicate() {
  513. if (!IsTailPredicationLegal()) {
  514. LLVM_DEBUG(if (VCTPs.empty())
  515. dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n";
  516. dbgs() << "ARM Loops: Tail-predication is not valid.\n");
  517. return false;
  518. }
  519. assert(!VCTPs.empty() && "VCTP instruction expected but is not set");
  520. assert(ML.getBlocks().size() == 1 &&
  521. "Shouldn't be processing a loop with more than one block");
  522. if (DisableTailPredication) {
  523. LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n");
  524. return false;
  525. }
  526. if (!VPTState::isValid(RDA)) {
  527. LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n");
  528. return false;
  529. }
  530. if (!ValidateLiveOuts()) {
  531. LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n");
  532. return false;
  533. }
  534. // For tail predication, we need to provide the number of elements, instead
  535. // of the iteration count, to the loop start instruction. The number of
  536. // elements is provided to the vctp instruction, so we need to check that
  537. // we can use this register at InsertPt.
  538. MachineInstr *VCTP = VCTPs.back();
  539. if (Start->getOpcode() == ARM::t2DoLoopStartTP ||
  540. Start->getOpcode() == ARM::t2WhileLoopStartTP) {
  541. TPNumElements = Start->getOperand(2);
  542. StartInsertPt = Start;
  543. StartInsertBB = Start->getParent();
  544. } else {
  545. TPNumElements = VCTP->getOperand(1);
  546. MCRegister NumElements = TPNumElements.getReg().asMCReg();
  547. // If the register is defined within loop, then we can't perform TP.
  548. // TODO: Check whether this is just a mov of a register that would be
  549. // available.
  550. if (RDA.hasLocalDefBefore(VCTP, NumElements)) {
  551. LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n");
  552. return false;
  553. }
  554. // The element count register maybe defined after InsertPt, in which case we
  555. // need to try to move either InsertPt or the def so that the [w|d]lstp can
  556. // use the value.
  557. if (StartInsertPt != StartInsertBB->end() &&
  558. !RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) {
  559. if (auto *ElemDef =
  560. RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) {
  561. if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) {
  562. ElemDef->removeFromParent();
  563. StartInsertBB->insert(StartInsertPt, ElemDef);
  564. LLVM_DEBUG(dbgs()
  565. << "ARM Loops: Moved element count def: " << *ElemDef);
  566. } else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) {
  567. StartInsertPt->removeFromParent();
  568. StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef),
  569. &*StartInsertPt);
  570. LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef);
  571. } else {
  572. // If we fail to move an instruction and the element count is provided
  573. // by a mov, use the mov operand if it will have the same value at the
  574. // insertion point
  575. MachineOperand Operand = ElemDef->getOperand(1);
  576. if (isMovRegOpcode(ElemDef->getOpcode()) &&
  577. RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) ==
  578. RDA.getUniqueReachingMIDef(&*StartInsertPt,
  579. Operand.getReg().asMCReg())) {
  580. TPNumElements = Operand;
  581. NumElements = TPNumElements.getReg();
  582. } else {
  583. LLVM_DEBUG(dbgs()
  584. << "ARM Loops: Unable to move element count to loop "
  585. << "start instruction.\n");
  586. return false;
  587. }
  588. }
  589. }
  590. }
  591. // Especially in the case of while loops, InsertBB may not be the
  592. // preheader, so we need to check that the register isn't redefined
  593. // before entering the loop.
  594. auto CannotProvideElements = [this](MachineBasicBlock *MBB,
  595. MCRegister NumElements) {
  596. if (MBB->empty())
  597. return false;
  598. // NumElements is redefined in this block.
  599. if (RDA.hasLocalDefBefore(&MBB->back(), NumElements))
  600. return true;
  601. // Don't continue searching up through multiple predecessors.
  602. if (MBB->pred_size() > 1)
  603. return true;
  604. return false;
  605. };
  606. // Search backwards for a def, until we get to InsertBB.
  607. MachineBasicBlock *MBB = Preheader;
  608. while (MBB && MBB != StartInsertBB) {
  609. if (CannotProvideElements(MBB, NumElements)) {
  610. LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n");
  611. return false;
  612. }
  613. MBB = *MBB->pred_begin();
  614. }
  615. }
  616. // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect
  617. // world the [w|d]lstp instruction would be last instruction in the preheader
  618. // and so it would only affect instructions within the loop body. But due to
  619. // scheduling, and/or the logic in this pass (above), the insertion point can
  620. // be moved earlier. So if the Loop Start isn't the last instruction in the
  621. // preheader, and if the initial element count is smaller than the vector
  622. // width, the Loop Start instruction will immediately generate one or more
  623. // false lane mask which can, incorrectly, affect the proceeding MVE
  624. // instructions in the preheader.
  625. if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) {
  626. LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n");
  627. return false;
  628. }
  629. // For any DoubleWidthResultInstrs we found whilst scanning instructions, they
  630. // need to compute an output size that is smaller than the VCTP mask operates
  631. // on. The VecSize of the DoubleWidthResult is the larger vector size - the
  632. // size it extends into, so any VCTP VecSize <= is valid.
  633. unsigned VCTPVecSize = getVecSize(*VCTP);
  634. for (MachineInstr *MI : DoubleWidthResultInstrs) {
  635. unsigned InstrVecSize = getVecSize(*MI);
  636. if (InstrVecSize > VCTPVecSize) {
  637. LLVM_DEBUG(dbgs() << "ARM Loops: Double width result larger than VCTP "
  638. << "VecSize:\n" << *MI);
  639. return false;
  640. }
  641. }
  642. // Check that the value change of the element count is what we expect and
  643. // that the predication will be equivalent. For this we need:
  644. // NumElements = NumElements - VectorWidth. The sub will be a sub immediate
  645. // and we can also allow register copies within the chain too.
  646. auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) {
  647. return -getAddSubImmediate(*MI) == ExpectedVecWidth;
  648. };
  649. MachineBasicBlock *MBB = VCTP->getParent();
  650. // Remove modifications to the element count since they have no purpose in a
  651. // tail predicated loop. Explicitly refer to the vctp operand no matter which
  652. // register NumElements has been assigned to, since that is what the
  653. // modifications will be using
  654. if (auto *Def = RDA.getUniqueReachingMIDef(
  655. &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) {
  656. SmallPtrSet<MachineInstr*, 2> ElementChain;
  657. SmallPtrSet<MachineInstr*, 2> Ignore;
  658. unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode());
  659. Ignore.insert(VCTPs.begin(), VCTPs.end());
  660. if (TryRemove(Def, RDA, ElementChain, Ignore)) {
  661. bool FoundSub = false;
  662. for (auto *MI : ElementChain) {
  663. if (isMovRegOpcode(MI->getOpcode()))
  664. continue;
  665. if (isSubImmOpcode(MI->getOpcode())) {
  666. if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) {
  667. LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
  668. " count: " << *MI);
  669. return false;
  670. }
  671. FoundSub = true;
  672. } else {
  673. LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element"
  674. " count: " << *MI);
  675. return false;
  676. }
  677. }
  678. ToRemove.insert(ElementChain.begin(), ElementChain.end());
  679. }
  680. }
  681. // If we converted the LoopStart to a t2DoLoopStartTP/t2WhileLoopStartTP, we
  682. // can also remove any extra instructions in the preheader, which often
  683. // includes a now unused MOV.
  684. if ((Start->getOpcode() == ARM::t2DoLoopStartTP ||
  685. Start->getOpcode() == ARM::t2WhileLoopStartTP) &&
  686. Preheader && !Preheader->empty() &&
  687. !RDA.hasLocalDefBefore(VCTP, VCTP->getOperand(1).getReg())) {
  688. if (auto *Def = RDA.getUniqueReachingMIDef(
  689. &Preheader->back(), VCTP->getOperand(1).getReg().asMCReg())) {
  690. SmallPtrSet<MachineInstr*, 2> Ignore;
  691. Ignore.insert(VCTPs.begin(), VCTPs.end());
  692. TryRemove(Def, RDA, ToRemove, Ignore);
  693. }
  694. }
  695. return true;
  696. }
  697. static bool isRegInClass(const MachineOperand &MO,
  698. const TargetRegisterClass *Class) {
  699. return MO.isReg() && MO.getReg() && Class->contains(MO.getReg());
  700. }
  701. // MVE 'narrowing' operate on half a lane, reading from half and writing
  702. // to half, which are referred to has the top and bottom half. The other
  703. // half retains its previous value.
  704. static bool retainsPreviousHalfElement(const MachineInstr &MI) {
  705. const MCInstrDesc &MCID = MI.getDesc();
  706. uint64_t Flags = MCID.TSFlags;
  707. return (Flags & ARMII::RetainsPreviousHalfElement) != 0;
  708. }
  709. // Some MVE instructions read from the top/bottom halves of their operand(s)
  710. // and generate a vector result with result elements that are double the
  711. // width of the input.
  712. static bool producesDoubleWidthResult(const MachineInstr &MI) {
  713. const MCInstrDesc &MCID = MI.getDesc();
  714. uint64_t Flags = MCID.TSFlags;
  715. return (Flags & ARMII::DoubleWidthResult) != 0;
  716. }
  717. static bool isHorizontalReduction(const MachineInstr &MI) {
  718. const MCInstrDesc &MCID = MI.getDesc();
  719. uint64_t Flags = MCID.TSFlags;
  720. return (Flags & ARMII::HorizontalReduction) != 0;
  721. }
  722. // Can this instruction generate a non-zero result when given only zeroed
  723. // operands? This allows us to know that, given operands with false bytes
  724. // zeroed by masked loads, that the result will also contain zeros in those
  725. // bytes.
  726. static bool canGenerateNonZeros(const MachineInstr &MI) {
  727. // Check for instructions which can write into a larger element size,
  728. // possibly writing into a previous zero'd lane.
  729. if (producesDoubleWidthResult(MI))
  730. return true;
  731. switch (MI.getOpcode()) {
  732. default:
  733. break;
  734. // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow
  735. // fp16 -> fp32 vector conversions.
  736. // Instructions that perform a NOT will generate 1s from 0s.
  737. case ARM::MVE_VMVN:
  738. case ARM::MVE_VORN:
  739. // Count leading zeros will do just that!
  740. case ARM::MVE_VCLZs8:
  741. case ARM::MVE_VCLZs16:
  742. case ARM::MVE_VCLZs32:
  743. return true;
  744. }
  745. return false;
  746. }
  747. // Look at its register uses to see if it only can only receive zeros
  748. // into its false lanes which would then produce zeros. Also check that
  749. // the output register is also defined by an FalseLanesZero instruction
  750. // so that if tail-predication happens, the lanes that aren't updated will
  751. // still be zeros.
  752. static bool producesFalseLanesZero(MachineInstr &MI,
  753. const TargetRegisterClass *QPRs,
  754. const ReachingDefAnalysis &RDA,
  755. InstSet &FalseLanesZero) {
  756. if (canGenerateNonZeros(MI))
  757. return false;
  758. bool isPredicated = isVectorPredicated(&MI);
  759. // Predicated loads will write zeros to the falsely predicated bytes of the
  760. // destination register.
  761. if (MI.mayLoad())
  762. return isPredicated;
  763. auto IsZeroInit = [](MachineInstr *Def) {
  764. return !isVectorPredicated(Def) &&
  765. Def->getOpcode() == ARM::MVE_VMOVimmi32 &&
  766. Def->getOperand(1).getImm() == 0;
  767. };
  768. bool AllowScalars = isHorizontalReduction(MI);
  769. for (auto &MO : MI.operands()) {
  770. if (!MO.isReg() || !MO.getReg())
  771. continue;
  772. if (!isRegInClass(MO, QPRs) && AllowScalars)
  773. continue;
  774. // Skip the lr predicate reg
  775. int PIdx = llvm::findFirstVPTPredOperandIdx(MI);
  776. if (PIdx != -1 && (int)MI.getOperandNo(&MO) == PIdx + 2)
  777. continue;
  778. // Check that this instruction will produce zeros in its false lanes:
  779. // - If it only consumes false lanes zero or constant 0 (vmov #0)
  780. // - If it's predicated, it only matters that it's def register already has
  781. // false lane zeros, so we can ignore the uses.
  782. SmallPtrSet<MachineInstr *, 2> Defs;
  783. RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs);
  784. for (auto *Def : Defs) {
  785. if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def))
  786. continue;
  787. if (MO.isUse() && isPredicated)
  788. continue;
  789. return false;
  790. }
  791. }
  792. LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI);
  793. return true;
  794. }
  795. bool LowOverheadLoop::ValidateLiveOuts() {
  796. // We want to find out if the tail-predicated version of this loop will
  797. // produce the same values as the loop in its original form. For this to
  798. // be true, the newly inserted implicit predication must not change the
  799. // the (observable) results.
  800. // We're doing this because many instructions in the loop will not be
  801. // predicated and so the conversion from VPT predication to tail-predication
  802. // can result in different values being produced; due to the tail-predication
  803. // preventing many instructions from updating their falsely predicated
  804. // lanes. This analysis assumes that all the instructions perform lane-wise
  805. // operations and don't perform any exchanges.
  806. // A masked load, whether through VPT or tail predication, will write zeros
  807. // to any of the falsely predicated bytes. So, from the loads, we know that
  808. // the false lanes are zeroed and here we're trying to track that those false
  809. // lanes remain zero, or where they change, the differences are masked away
  810. // by their user(s).
  811. // All MVE stores have to be predicated, so we know that any predicate load
  812. // operands, or stored results are equivalent already. Other explicitly
  813. // predicated instructions will perform the same operation in the original
  814. // loop and the tail-predicated form too. Because of this, we can insert
  815. // loads, stores and other predicated instructions into our Predicated
  816. // set and build from there.
  817. const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID);
  818. SetVector<MachineInstr *> FalseLanesUnknown;
  819. SmallPtrSet<MachineInstr *, 4> FalseLanesZero;
  820. SmallPtrSet<MachineInstr *, 4> Predicated;
  821. MachineBasicBlock *Header = ML.getHeader();
  822. LLVM_DEBUG(dbgs() << "ARM Loops: Validating Live outs\n");
  823. for (auto &MI : *Header) {
  824. if (!shouldInspect(MI))
  825. continue;
  826. if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode()))
  827. continue;
  828. bool isPredicated = isVectorPredicated(&MI);
  829. bool retainsOrReduces =
  830. retainsPreviousHalfElement(MI) || isHorizontalReduction(MI);
  831. if (isPredicated)
  832. Predicated.insert(&MI);
  833. if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero))
  834. FalseLanesZero.insert(&MI);
  835. else if (MI.getNumDefs() == 0)
  836. continue;
  837. else if (!isPredicated && retainsOrReduces) {
  838. LLVM_DEBUG(dbgs() << " Unpredicated instruction that retainsOrReduces: " << MI);
  839. return false;
  840. } else if (!isPredicated && MI.getOpcode() != ARM::MQPRCopy)
  841. FalseLanesUnknown.insert(&MI);
  842. }
  843. LLVM_DEBUG({
  844. dbgs() << " Predicated:\n";
  845. for (auto *I : Predicated)
  846. dbgs() << " " << *I;
  847. dbgs() << " FalseLanesZero:\n";
  848. for (auto *I : FalseLanesZero)
  849. dbgs() << " " << *I;
  850. dbgs() << " FalseLanesUnknown:\n";
  851. for (auto *I : FalseLanesUnknown)
  852. dbgs() << " " << *I;
  853. });
  854. auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO,
  855. SmallPtrSetImpl<MachineInstr *> &Predicated) {
  856. SmallPtrSet<MachineInstr *, 2> Uses;
  857. RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses);
  858. for (auto *Use : Uses) {
  859. if (Use != MI && !Predicated.count(Use))
  860. return false;
  861. }
  862. return true;
  863. };
  864. // Visit the unknowns in reverse so that we can start at the values being
  865. // stored and then we can work towards the leaves, hopefully adding more
  866. // instructions to Predicated. Successfully terminating the loop means that
  867. // all the unknown values have to found to be masked by predicated user(s).
  868. // For any unpredicated values, we store them in NonPredicated so that we
  869. // can later check whether these form a reduction.
  870. SmallPtrSet<MachineInstr*, 2> NonPredicated;
  871. for (auto *MI : reverse(FalseLanesUnknown)) {
  872. for (auto &MO : MI->operands()) {
  873. if (!isRegInClass(MO, QPRs) || !MO.isDef())
  874. continue;
  875. if (!HasPredicatedUsers(MI, MO, Predicated)) {
  876. LLVM_DEBUG(dbgs() << " Found an unknown def of : "
  877. << TRI.getRegAsmName(MO.getReg()) << " at " << *MI);
  878. NonPredicated.insert(MI);
  879. break;
  880. }
  881. }
  882. // Any unknown false lanes have been masked away by the user(s).
  883. if (!NonPredicated.contains(MI))
  884. Predicated.insert(MI);
  885. }
  886. SmallPtrSet<MachineInstr *, 2> LiveOutMIs;
  887. SmallVector<MachineBasicBlock *, 2> ExitBlocks;
  888. ML.getExitBlocks(ExitBlocks);
  889. assert(ML.getNumBlocks() == 1 && "Expected single block loop!");
  890. assert(ExitBlocks.size() == 1 && "Expected a single exit block");
  891. MachineBasicBlock *ExitBB = ExitBlocks.front();
  892. for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) {
  893. // TODO: Instead of blocking predication, we could move the vctp to the exit
  894. // block and calculate it's operand there in or the preheader.
  895. if (RegMask.PhysReg == ARM::VPR) {
  896. LLVM_DEBUG(dbgs() << " VPR is live in to the exit block.");
  897. return false;
  898. }
  899. // Check Q-regs that are live in the exit blocks. We don't collect scalars
  900. // because they won't be affected by lane predication.
  901. if (QPRs->contains(RegMask.PhysReg))
  902. if (auto *MI = RDA.getLocalLiveOutMIDef(Header, RegMask.PhysReg))
  903. LiveOutMIs.insert(MI);
  904. }
  905. // We've already validated that any VPT predication within the loop will be
  906. // equivalent when we perform the predication transformation; so we know that
  907. // any VPT predicated instruction is predicated upon VCTP. Any live-out
  908. // instruction needs to be predicated, so check this here. The instructions
  909. // in NonPredicated have been found to be a reduction that we can ensure its
  910. // legality. Any MQPRCopy found will need to validate its input as if it was
  911. // live out.
  912. SmallVector<MachineInstr *> Worklist(LiveOutMIs.begin(), LiveOutMIs.end());
  913. while (!Worklist.empty()) {
  914. MachineInstr *MI = Worklist.pop_back_val();
  915. if (MI->getOpcode() == ARM::MQPRCopy) {
  916. VMOVCopies.insert(MI);
  917. MachineInstr *CopySrc =
  918. RDA.getUniqueReachingMIDef(MI, MI->getOperand(1).getReg());
  919. if (CopySrc)
  920. Worklist.push_back(CopySrc);
  921. } else if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) {
  922. LLVM_DEBUG(dbgs() << " Unable to handle live out: " << *MI);
  923. VMOVCopies.clear();
  924. return false;
  925. }
  926. }
  927. return true;
  928. }
  929. void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) {
  930. if (Revert)
  931. return;
  932. // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP]
  933. // can only jump back.
  934. auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End,
  935. ARMBasicBlockUtils *BBUtils, MachineLoop &ML) {
  936. MachineBasicBlock *TgtBB = End->getOpcode() == ARM::t2LoopEnd
  937. ? End->getOperand(1).getMBB()
  938. : End->getOperand(2).getMBB();
  939. // TODO Maybe there's cases where the target doesn't have to be the header,
  940. // but for now be safe and revert.
  941. if (TgtBB != ML.getHeader()) {
  942. LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n");
  943. return false;
  944. }
  945. // The WLS and LE instructions have 12-bits for the label offset. WLS
  946. // requires a positive offset, while LE uses negative.
  947. if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) ||
  948. !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) {
  949. LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n");
  950. return false;
  951. }
  952. if (isWhileLoopStart(*Start)) {
  953. MachineBasicBlock *TargetBB = getWhileLoopStartTargetBB(*Start);
  954. if (BBUtils->getOffsetOf(Start) > BBUtils->getOffsetOf(TargetBB) ||
  955. !BBUtils->isBBInRange(Start, TargetBB, 4094)) {
  956. LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n");
  957. return false;
  958. }
  959. }
  960. return true;
  961. };
  962. StartInsertPt = MachineBasicBlock::iterator(Start);
  963. StartInsertBB = Start->getParent();
  964. LLVM_DEBUG(dbgs() << "ARM Loops: Will insert LoopStart at "
  965. << *StartInsertPt);
  966. Revert = !ValidateRanges(Start, End, BBUtils, ML);
  967. CannotTailPredicate = !ValidateTailPredicate();
  968. }
  969. bool LowOverheadLoop::AddVCTP(MachineInstr *MI) {
  970. LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI);
  971. if (VCTPs.empty()) {
  972. VCTPs.push_back(MI);
  973. return true;
  974. }
  975. // If we find another VCTP, check whether it uses the same value as the main VCTP.
  976. // If it does, store it in the VCTPs set, else refuse it.
  977. MachineInstr *Prev = VCTPs.back();
  978. if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) ||
  979. !RDA.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) {
  980. LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching "
  981. "definition from the main VCTP");
  982. return false;
  983. }
  984. VCTPs.push_back(MI);
  985. return true;
  986. }
  987. static bool ValidateMVEStore(MachineInstr *MI, MachineLoop *ML) {
  988. auto GetFrameIndex = [](MachineMemOperand *Operand) {
  989. const PseudoSourceValue *PseudoValue = Operand->getPseudoValue();
  990. if (PseudoValue && PseudoValue->kind() == PseudoSourceValue::FixedStack) {
  991. if (const auto *FS = dyn_cast<FixedStackPseudoSourceValue>(PseudoValue)) {
  992. return FS->getFrameIndex();
  993. }
  994. }
  995. return -1;
  996. };
  997. auto IsStackOp = [GetFrameIndex](MachineInstr *I) {
  998. switch (I->getOpcode()) {
  999. case ARM::MVE_VSTRWU32:
  1000. case ARM::MVE_VLDRWU32: {
  1001. return I->getOperand(1).getReg() == ARM::SP &&
  1002. I->memoperands().size() == 1 &&
  1003. GetFrameIndex(I->memoperands().front()) >= 0;
  1004. }
  1005. default:
  1006. return false;
  1007. }
  1008. };
  1009. // An unpredicated vector register spill is allowed if all of the uses of the
  1010. // stack slot are within the loop
  1011. if (MI->getOpcode() != ARM::MVE_VSTRWU32 || !IsStackOp(MI))
  1012. return false;
  1013. // Search all blocks after the loop for accesses to the same stack slot.
  1014. // ReachingDefAnalysis doesn't work for sp as it relies on registers being
  1015. // live-out (which sp never is) to know what blocks to look in
  1016. if (MI->memoperands().size() == 0)
  1017. return false;
  1018. int FI = GetFrameIndex(MI->memoperands().front());
  1019. auto &FrameInfo = MI->getParent()->getParent()->getFrameInfo();
  1020. if (FI == -1 || !FrameInfo.isSpillSlotObjectIndex(FI))
  1021. return false;
  1022. SmallVector<MachineBasicBlock *> Frontier;
  1023. ML->getExitBlocks(Frontier);
  1024. SmallPtrSet<MachineBasicBlock *, 4> Visited{MI->getParent()};
  1025. unsigned Idx = 0;
  1026. while (Idx < Frontier.size()) {
  1027. MachineBasicBlock *BB = Frontier[Idx];
  1028. bool LookAtSuccessors = true;
  1029. for (auto &I : *BB) {
  1030. if (!IsStackOp(&I) || I.memoperands().size() == 0)
  1031. continue;
  1032. if (GetFrameIndex(I.memoperands().front()) != FI)
  1033. continue;
  1034. // If this block has a store to the stack slot before any loads then we
  1035. // can ignore the block
  1036. if (I.getOpcode() == ARM::MVE_VSTRWU32) {
  1037. LookAtSuccessors = false;
  1038. break;
  1039. }
  1040. // If the store and the load are using the same stack slot then the
  1041. // store isn't valid for tail predication
  1042. if (I.getOpcode() == ARM::MVE_VLDRWU32)
  1043. return false;
  1044. }
  1045. if (LookAtSuccessors) {
  1046. for (auto Succ : BB->successors()) {
  1047. if (!Visited.contains(Succ) && !is_contained(Frontier, Succ))
  1048. Frontier.push_back(Succ);
  1049. }
  1050. }
  1051. Visited.insert(BB);
  1052. Idx++;
  1053. }
  1054. return true;
  1055. }
  1056. bool LowOverheadLoop::ValidateMVEInst(MachineInstr *MI) {
  1057. if (CannotTailPredicate)
  1058. return false;
  1059. if (!shouldInspect(*MI))
  1060. return true;
  1061. if (MI->getOpcode() == ARM::MVE_VPSEL ||
  1062. MI->getOpcode() == ARM::MVE_VPNOT) {
  1063. // TODO: Allow VPSEL and VPNOT, we currently cannot because:
  1064. // 1) It will use the VPR as a predicate operand, but doesn't have to be
  1065. // instead a VPT block, which means we can assert while building up
  1066. // the VPT block because we don't find another VPT or VPST to being a new
  1067. // one.
  1068. // 2) VPSEL still requires a VPR operand even after tail predicating,
  1069. // which means we can't remove it unless there is another
  1070. // instruction, such as vcmp, that can provide the VPR def.
  1071. return false;
  1072. }
  1073. // Record all VCTPs and check that they're equivalent to one another.
  1074. if (isVCTP(MI) && !AddVCTP(MI))
  1075. return false;
  1076. // Inspect uses first so that any instructions that alter the VPR don't
  1077. // alter the predicate upon themselves.
  1078. const MCInstrDesc &MCID = MI->getDesc();
  1079. bool IsUse = false;
  1080. unsigned LastOpIdx = MI->getNumOperands() - 1;
  1081. for (auto &Op : enumerate(reverse(MCID.operands()))) {
  1082. const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index());
  1083. if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR)
  1084. continue;
  1085. if (ARM::isVpred(Op.value().OperandType)) {
  1086. VPTState::addInst(MI);
  1087. IsUse = true;
  1088. } else if (MI->getOpcode() != ARM::MVE_VPST) {
  1089. LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI);
  1090. return false;
  1091. }
  1092. }
  1093. // If we find an instruction that has been marked as not valid for tail
  1094. // predication, only allow the instruction if it's contained within a valid
  1095. // VPT block.
  1096. bool RequiresExplicitPredication =
  1097. (MCID.TSFlags & ARMII::ValidForTailPredication) == 0;
  1098. if (isDomainMVE(MI) && RequiresExplicitPredication) {
  1099. if (MI->getOpcode() == ARM::MQPRCopy)
  1100. return true;
  1101. if (!IsUse && producesDoubleWidthResult(*MI)) {
  1102. DoubleWidthResultInstrs.insert(MI);
  1103. return true;
  1104. }
  1105. LLVM_DEBUG(if (!IsUse) dbgs()
  1106. << "ARM Loops: Can't tail predicate: " << *MI);
  1107. return IsUse;
  1108. }
  1109. // If the instruction is already explicitly predicated, then the conversion
  1110. // will be fine, but ensure that all store operations are predicated.
  1111. if (MI->mayStore() && !ValidateMVEStore(MI, &ML))
  1112. return IsUse;
  1113. // If this instruction defines the VPR, update the predicate for the
  1114. // proceeding instructions.
  1115. if (isVectorPredicate(MI)) {
  1116. // Clear the existing predicate when we're not in VPT Active state,
  1117. // otherwise we add to it.
  1118. if (!isVectorPredicated(MI))
  1119. VPTState::resetPredicate(MI);
  1120. else
  1121. VPTState::addPredicate(MI);
  1122. }
  1123. // Finally once the predicate has been modified, we can start a new VPT
  1124. // block if necessary.
  1125. if (isVPTOpcode(MI->getOpcode()))
  1126. VPTState::CreateVPTBlock(MI);
  1127. return true;
  1128. }
  1129. bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) {
  1130. const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget());
  1131. if (!ST.hasLOB())
  1132. return false;
  1133. MF = &mf;
  1134. LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n");
  1135. MLI = &getAnalysis<MachineLoopInfo>();
  1136. RDA = &getAnalysis<ReachingDefAnalysis>();
  1137. MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
  1138. MRI = &MF->getRegInfo();
  1139. TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo());
  1140. TRI = ST.getRegisterInfo();
  1141. BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF));
  1142. BBUtils->computeAllBlockSizes();
  1143. BBUtils->adjustBBOffsetsAfter(&MF->front());
  1144. bool Changed = false;
  1145. for (auto ML : *MLI) {
  1146. if (ML->isOutermost())
  1147. Changed |= ProcessLoop(ML);
  1148. }
  1149. Changed |= RevertNonLoops();
  1150. return Changed;
  1151. }
  1152. bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) {
  1153. bool Changed = false;
  1154. // Process inner loops first.
  1155. for (MachineLoop *L : *ML)
  1156. Changed |= ProcessLoop(L);
  1157. LLVM_DEBUG({
  1158. dbgs() << "ARM Loops: Processing loop containing:\n";
  1159. if (auto *Preheader = ML->getLoopPreheader())
  1160. dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
  1161. else if (auto *Preheader = MLI->findLoopPreheader(ML, true, true))
  1162. dbgs() << " - Preheader: " << printMBBReference(*Preheader) << "\n";
  1163. for (auto *MBB : ML->getBlocks())
  1164. dbgs() << " - Block: " << printMBBReference(*MBB) << "\n";
  1165. });
  1166. // Search the given block for a loop start instruction. If one isn't found,
  1167. // and there's only one predecessor block, search that one too.
  1168. std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart =
  1169. [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* {
  1170. for (auto &MI : *MBB) {
  1171. if (isLoopStart(MI))
  1172. return &MI;
  1173. }
  1174. if (MBB->pred_size() == 1)
  1175. return SearchForStart(*MBB->pred_begin());
  1176. return nullptr;
  1177. };
  1178. LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII);
  1179. // Search the preheader for the start intrinsic.
  1180. // FIXME: I don't see why we shouldn't be supporting multiple predecessors
  1181. // with potentially multiple set.loop.iterations, so we need to enable this.
  1182. if (LoLoop.Preheader)
  1183. LoLoop.Start = SearchForStart(LoLoop.Preheader);
  1184. else
  1185. return Changed;
  1186. // Find the low-overhead loop components and decide whether or not to fall
  1187. // back to a normal loop. Also look for a vctp instructions and decide
  1188. // whether we can convert that predicate using tail predication.
  1189. for (auto *MBB : reverse(ML->getBlocks())) {
  1190. for (auto &MI : *MBB) {
  1191. if (MI.isDebugValue())
  1192. continue;
  1193. else if (MI.getOpcode() == ARM::t2LoopDec)
  1194. LoLoop.Dec = &MI;
  1195. else if (MI.getOpcode() == ARM::t2LoopEnd)
  1196. LoLoop.End = &MI;
  1197. else if (MI.getOpcode() == ARM::t2LoopEndDec)
  1198. LoLoop.End = LoLoop.Dec = &MI;
  1199. else if (isLoopStart(MI))
  1200. LoLoop.Start = &MI;
  1201. else if (MI.getDesc().isCall()) {
  1202. // TODO: Though the call will require LE to execute again, does this
  1203. // mean we should revert? Always executing LE hopefully should be
  1204. // faster than performing a sub,cmp,br or even subs,br.
  1205. LoLoop.Revert = true;
  1206. LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n");
  1207. } else {
  1208. // Record VPR defs and build up their corresponding vpt blocks.
  1209. // Check we know how to tail predicate any mve instructions.
  1210. LoLoop.AnalyseMVEInst(&MI);
  1211. }
  1212. }
  1213. }
  1214. LLVM_DEBUG(LoLoop.dump());
  1215. if (!LoLoop.FoundAllComponents()) {
  1216. LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n");
  1217. return Changed;
  1218. }
  1219. assert(LoLoop.Start->getOpcode() != ARM::t2WhileLoopStart &&
  1220. "Expected t2WhileLoopStart to be removed before regalloc!");
  1221. // Check that the only instruction using LoopDec is LoopEnd. This can only
  1222. // happen when the Dec and End are separate, not a single t2LoopEndDec.
  1223. // TODO: Check for copy chains that really have no effect.
  1224. if (LoLoop.Dec != LoLoop.End) {
  1225. SmallPtrSet<MachineInstr *, 2> Uses;
  1226. RDA->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses);
  1227. if (Uses.size() > 1 || !Uses.count(LoLoop.End)) {
  1228. LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n");
  1229. LoLoop.Revert = true;
  1230. }
  1231. }
  1232. LoLoop.Validate(BBUtils.get());
  1233. Expand(LoLoop);
  1234. return true;
  1235. }
  1236. // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a
  1237. // beq that branches to the exit branch.
  1238. // TODO: We could also try to generate a cbz if the value in LR is also in
  1239. // another low register.
  1240. void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const {
  1241. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI);
  1242. MachineBasicBlock *DestBB = getWhileLoopStartTargetBB(*MI);
  1243. unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
  1244. ARM::tBcc : ARM::t2Bcc;
  1245. RevertWhileLoopStartLR(MI, TII, BrOpc);
  1246. }
  1247. void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const {
  1248. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI);
  1249. RevertDoLoopStart(MI, TII);
  1250. }
  1251. bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const {
  1252. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI);
  1253. MachineBasicBlock *MBB = MI->getParent();
  1254. SmallPtrSet<MachineInstr*, 1> Ignore;
  1255. for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) {
  1256. if (I->getOpcode() == ARM::t2LoopEnd) {
  1257. Ignore.insert(&*I);
  1258. break;
  1259. }
  1260. }
  1261. // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS.
  1262. bool SetFlags =
  1263. RDA->isSafeToDefRegAt(MI, MCRegister::from(ARM::CPSR), Ignore);
  1264. llvm::RevertLoopDec(MI, TII, SetFlags);
  1265. return SetFlags;
  1266. }
  1267. // Generate a subs, or sub and cmp, and a branch instead of an LE.
  1268. void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const {
  1269. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI);
  1270. MachineBasicBlock *DestBB = MI->getOperand(1).getMBB();
  1271. unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ?
  1272. ARM::tBcc : ARM::t2Bcc;
  1273. llvm::RevertLoopEnd(MI, TII, BrOpc, SkipCmp);
  1274. }
  1275. // Generate a subs, or sub and cmp, and a branch instead of an LE.
  1276. void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *MI) const {
  1277. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to subs, br: " << *MI);
  1278. assert(MI->getOpcode() == ARM::t2LoopEndDec && "Expected a t2LoopEndDec!");
  1279. MachineBasicBlock *MBB = MI->getParent();
  1280. MachineInstrBuilder MIB =
  1281. BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::t2SUBri));
  1282. MIB.addDef(ARM::LR);
  1283. MIB.add(MI->getOperand(1));
  1284. MIB.addImm(1);
  1285. MIB.addImm(ARMCC::AL);
  1286. MIB.addReg(ARM::NoRegister);
  1287. MIB.addReg(ARM::CPSR);
  1288. MIB->getOperand(5).setIsDef(true);
  1289. MachineBasicBlock *DestBB = MI->getOperand(2).getMBB();
  1290. unsigned BrOpc =
  1291. BBUtils->isBBInRange(MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc;
  1292. // Create bne
  1293. MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc));
  1294. MIB.add(MI->getOperand(2)); // branch target
  1295. MIB.addImm(ARMCC::NE); // condition code
  1296. MIB.addReg(ARM::CPSR);
  1297. MI->eraseFromParent();
  1298. }
  1299. // Perform dead code elimation on the loop iteration count setup expression.
  1300. // If we are tail-predicating, the number of elements to be processed is the
  1301. // operand of the VCTP instruction in the vector body, see getCount(), which is
  1302. // register $r3 in this example:
  1303. //
  1304. // $lr = big-itercount-expression
  1305. // ..
  1306. // $lr = t2DoLoopStart renamable $lr
  1307. // vector.body:
  1308. // ..
  1309. // $vpr = MVE_VCTP32 renamable $r3
  1310. // renamable $lr = t2LoopDec killed renamable $lr, 1
  1311. // t2LoopEnd renamable $lr, %vector.body
  1312. // tB %end
  1313. //
  1314. // What we would like achieve here is to replace the do-loop start pseudo
  1315. // instruction t2DoLoopStart with:
  1316. //
  1317. // $lr = MVE_DLSTP_32 killed renamable $r3
  1318. //
  1319. // Thus, $r3 which defines the number of elements, is written to $lr,
  1320. // and then we want to delete the whole chain that used to define $lr,
  1321. // see the comment below how this chain could look like.
  1322. //
  1323. void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) {
  1324. if (!LoLoop.IsTailPredicationLegal())
  1325. return;
  1326. LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n");
  1327. MachineInstr *Def = RDA->getMIOperand(LoLoop.Start, 1);
  1328. if (!Def) {
  1329. LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n");
  1330. return;
  1331. }
  1332. // Collect and remove the users of iteration count.
  1333. SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec,
  1334. LoLoop.End };
  1335. if (!TryRemove(Def, *RDA, LoLoop.ToRemove, Killed))
  1336. LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n");
  1337. }
  1338. MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) {
  1339. LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n");
  1340. // When using tail-predication, try to delete the dead code that was used to
  1341. // calculate the number of loop iterations.
  1342. IterationCountDCE(LoLoop);
  1343. MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt;
  1344. MachineInstr *Start = LoLoop.Start;
  1345. MachineBasicBlock *MBB = LoLoop.StartInsertBB;
  1346. unsigned Opc = LoLoop.getStartOpcode();
  1347. MachineOperand &Count = LoLoop.getLoopStartOperand();
  1348. // A DLS lr, lr we needn't emit
  1349. MachineInstr* NewStart;
  1350. if (Opc == ARM::t2DLS && Count.isReg() && Count.getReg() == ARM::LR) {
  1351. LLVM_DEBUG(dbgs() << "ARM Loops: Didn't insert start: DLS lr, lr");
  1352. NewStart = nullptr;
  1353. } else {
  1354. MachineInstrBuilder MIB =
  1355. BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc));
  1356. MIB.addDef(ARM::LR);
  1357. MIB.add(Count);
  1358. if (isWhileLoopStart(*Start))
  1359. MIB.addMBB(getWhileLoopStartTargetBB(*Start));
  1360. LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB);
  1361. NewStart = &*MIB;
  1362. }
  1363. LoLoop.ToRemove.insert(Start);
  1364. return NewStart;
  1365. }
  1366. void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) {
  1367. auto RemovePredicate = [](MachineInstr *MI) {
  1368. if (MI->isDebugInstr())
  1369. return;
  1370. LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI);
  1371. int PIdx = llvm::findFirstVPTPredOperandIdx(*MI);
  1372. assert(PIdx >= 1 && "Trying to unpredicate a non-predicated instruction");
  1373. assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then &&
  1374. "Expected Then predicate!");
  1375. MI->getOperand(PIdx).setImm(ARMVCC::None);
  1376. MI->getOperand(PIdx + 1).setReg(0);
  1377. };
  1378. for (auto &Block : LoLoop.getVPTBlocks()) {
  1379. SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts();
  1380. auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) {
  1381. assert(TheVCMP && "Replacing a removed or non-existent VCMP");
  1382. // Replace the VCMP with a VPT
  1383. MachineInstrBuilder MIB =
  1384. BuildMI(*At->getParent(), At, At->getDebugLoc(),
  1385. TII->get(VCMPOpcodeToVPT(TheVCMP->getOpcode())));
  1386. MIB.addImm(ARMVCC::Then);
  1387. // Register one
  1388. MIB.add(TheVCMP->getOperand(1));
  1389. // Register two
  1390. MIB.add(TheVCMP->getOperand(2));
  1391. // The comparison code, e.g. ge, eq, lt
  1392. MIB.add(TheVCMP->getOperand(3));
  1393. LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB);
  1394. LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
  1395. LoLoop.ToRemove.insert(TheVCMP);
  1396. TheVCMP = nullptr;
  1397. };
  1398. if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/ true)) {
  1399. MachineInstr *VPST = Insts.front();
  1400. if (VPTState::hasUniformPredicate(Block)) {
  1401. // A vpt block starting with VPST, is only predicated upon vctp and has no
  1402. // internal vpr defs:
  1403. // - Remove vpst.
  1404. // - Unpredicate the remaining instructions.
  1405. LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
  1406. for (unsigned i = 1; i < Insts.size(); ++i)
  1407. RemovePredicate(Insts[i]);
  1408. } else {
  1409. // The VPT block has a non-uniform predicate but it uses a vpst and its
  1410. // entry is guarded only by a vctp, which means we:
  1411. // - Need to remove the original vpst.
  1412. // - Then need to unpredicate any following instructions, until
  1413. // we come across the divergent vpr def.
  1414. // - Insert a new vpst to predicate the instruction(s) that following
  1415. // the divergent vpr def.
  1416. MachineInstr *Divergent = VPTState::getDivergent(Block);
  1417. MachineBasicBlock *MBB = Divergent->getParent();
  1418. auto DivergentNext = ++MachineBasicBlock::iterator(Divergent);
  1419. while (DivergentNext != MBB->end() && DivergentNext->isDebugInstr())
  1420. ++DivergentNext;
  1421. bool DivergentNextIsPredicated =
  1422. DivergentNext != MBB->end() &&
  1423. getVPTInstrPredicate(*DivergentNext) != ARMVCC::None;
  1424. for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext;
  1425. I != E; ++I)
  1426. RemovePredicate(&*I);
  1427. // Check if the instruction defining vpr is a vcmp so it can be combined
  1428. // with the VPST This should be the divergent instruction
  1429. MachineInstr *VCMP =
  1430. VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr;
  1431. if (DivergentNextIsPredicated) {
  1432. // Insert a VPST at the divergent only if the next instruction
  1433. // would actually use it. A VCMP following a VPST can be
  1434. // merged into a VPT so do that instead if the VCMP exists.
  1435. if (!VCMP) {
  1436. // Create a VPST (with a null mask for now, we'll recompute it
  1437. // later)
  1438. MachineInstrBuilder MIB =
  1439. BuildMI(*Divergent->getParent(), Divergent,
  1440. Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST));
  1441. MIB.addImm(0);
  1442. LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB);
  1443. LoLoop.BlockMasksToRecompute.insert(MIB.getInstr());
  1444. } else {
  1445. // No RDA checks are necessary here since the VPST would have been
  1446. // directly after the VCMP
  1447. ReplaceVCMPWithVPT(VCMP, VCMP);
  1448. }
  1449. }
  1450. }
  1451. LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
  1452. LoLoop.ToRemove.insert(VPST);
  1453. } else if (Block.containsVCTP()) {
  1454. // The vctp will be removed, so either the entire block will be dead or
  1455. // the block mask of the vp(s)t will need to be recomputed.
  1456. MachineInstr *VPST = Insts.front();
  1457. if (Block.size() == 2) {
  1458. assert(VPST->getOpcode() == ARM::MVE_VPST &&
  1459. "Found a VPST in an otherwise empty vpt block");
  1460. LoLoop.ToRemove.insert(VPST);
  1461. } else
  1462. LoLoop.BlockMasksToRecompute.insert(VPST);
  1463. } else if (Insts.front()->getOpcode() == ARM::MVE_VPST) {
  1464. // If this block starts with a VPST then attempt to merge it with the
  1465. // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT
  1466. // block that no longer exists
  1467. MachineInstr *VPST = Insts.front();
  1468. auto Next = ++MachineBasicBlock::iterator(VPST);
  1469. assert(getVPTInstrPredicate(*Next) != ARMVCC::None &&
  1470. "The instruction after a VPST must be predicated");
  1471. (void)Next;
  1472. MachineInstr *VprDef = RDA->getUniqueReachingMIDef(VPST, ARM::VPR);
  1473. if (VprDef && VCMPOpcodeToVPT(VprDef->getOpcode()) &&
  1474. !LoLoop.ToRemove.contains(VprDef)) {
  1475. MachineInstr *VCMP = VprDef;
  1476. // The VCMP and VPST can only be merged if the VCMP's operands will have
  1477. // the same values at the VPST.
  1478. // If any of the instructions between the VCMP and VPST are predicated
  1479. // then a different code path is expected to have merged the VCMP and
  1480. // VPST already.
  1481. if (std::none_of(++MachineBasicBlock::iterator(VCMP),
  1482. MachineBasicBlock::iterator(VPST), hasVPRUse) &&
  1483. RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(1).getReg()) &&
  1484. RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(2).getReg())) {
  1485. ReplaceVCMPWithVPT(VCMP, VPST);
  1486. LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST);
  1487. LoLoop.ToRemove.insert(VPST);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end());
  1493. }
  1494. void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) {
  1495. // Combine the LoopDec and LoopEnd instructions into LE(TP).
  1496. auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) {
  1497. MachineInstr *End = LoLoop.End;
  1498. MachineBasicBlock *MBB = End->getParent();
  1499. unsigned Opc = LoLoop.IsTailPredicationLegal() ?
  1500. ARM::MVE_LETP : ARM::t2LEUpdate;
  1501. MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(),
  1502. TII->get(Opc));
  1503. MIB.addDef(ARM::LR);
  1504. unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0;
  1505. MIB.add(End->getOperand(Off + 0));
  1506. MIB.add(End->getOperand(Off + 1));
  1507. LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB);
  1508. LoLoop.ToRemove.insert(LoLoop.Dec);
  1509. LoLoop.ToRemove.insert(End);
  1510. return &*MIB;
  1511. };
  1512. // TODO: We should be able to automatically remove these branches before we
  1513. // get here - probably by teaching analyzeBranch about the pseudo
  1514. // instructions.
  1515. // If there is an unconditional branch, after I, that just branches to the
  1516. // next block, remove it.
  1517. auto RemoveDeadBranch = [](MachineInstr *I) {
  1518. MachineBasicBlock *BB = I->getParent();
  1519. MachineInstr *Terminator = &BB->instr_back();
  1520. if (Terminator->isUnconditionalBranch() && I != Terminator) {
  1521. MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB();
  1522. if (BB->isLayoutSuccessor(Succ)) {
  1523. LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator);
  1524. Terminator->eraseFromParent();
  1525. }
  1526. }
  1527. };
  1528. // And VMOVCopies need to become 2xVMOVD for tail predication to be valid.
  1529. // Anything other MQPRCopy can be converted to MVE_VORR later on.
  1530. auto ExpandVMOVCopies = [this](SmallPtrSet<MachineInstr *, 4> &VMOVCopies) {
  1531. for (auto *MI : VMOVCopies) {
  1532. LLVM_DEBUG(dbgs() << "Converting copy to VMOVD: " << *MI);
  1533. assert(MI->getOpcode() == ARM::MQPRCopy && "Only expected MQPRCOPY!");
  1534. MachineBasicBlock *MBB = MI->getParent();
  1535. Register Dst = MI->getOperand(0).getReg();
  1536. Register Src = MI->getOperand(1).getReg();
  1537. auto MIB1 = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::VMOVD),
  1538. ARM::D0 + (Dst - ARM::Q0) * 2)
  1539. .addReg(ARM::D0 + (Src - ARM::Q0) * 2)
  1540. .add(predOps(ARMCC::AL));
  1541. (void)MIB1;
  1542. LLVM_DEBUG(dbgs() << " into " << *MIB1);
  1543. auto MIB2 = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::VMOVD),
  1544. ARM::D0 + (Dst - ARM::Q0) * 2 + 1)
  1545. .addReg(ARM::D0 + (Src - ARM::Q0) * 2 + 1)
  1546. .add(predOps(ARMCC::AL));
  1547. LLVM_DEBUG(dbgs() << " and " << *MIB2);
  1548. (void)MIB2;
  1549. MI->eraseFromParent();
  1550. }
  1551. };
  1552. if (LoLoop.Revert) {
  1553. if (isWhileLoopStart(*LoLoop.Start))
  1554. RevertWhile(LoLoop.Start);
  1555. else
  1556. RevertDo(LoLoop.Start);
  1557. if (LoLoop.Dec == LoLoop.End)
  1558. RevertLoopEndDec(LoLoop.End);
  1559. else
  1560. RevertLoopEnd(LoLoop.End, RevertLoopDec(LoLoop.Dec));
  1561. } else {
  1562. ExpandVMOVCopies(LoLoop.VMOVCopies);
  1563. LoLoop.Start = ExpandLoopStart(LoLoop);
  1564. if (LoLoop.Start)
  1565. RemoveDeadBranch(LoLoop.Start);
  1566. LoLoop.End = ExpandLoopEnd(LoLoop);
  1567. RemoveDeadBranch(LoLoop.End);
  1568. if (LoLoop.IsTailPredicationLegal())
  1569. ConvertVPTBlocks(LoLoop);
  1570. for (auto *I : LoLoop.ToRemove) {
  1571. LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I);
  1572. I->eraseFromParent();
  1573. }
  1574. for (auto *I : LoLoop.BlockMasksToRecompute) {
  1575. LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I);
  1576. recomputeVPTBlockMask(*I);
  1577. LLVM_DEBUG(dbgs() << " ... done: " << *I);
  1578. }
  1579. }
  1580. PostOrderLoopTraversal DFS(LoLoop.ML, *MLI);
  1581. DFS.ProcessLoop();
  1582. const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder();
  1583. for (auto *MBB : PostOrder) {
  1584. recomputeLiveIns(*MBB);
  1585. // FIXME: For some reason, the live-in print order is non-deterministic for
  1586. // our tests and I can't out why... So just sort them.
  1587. MBB->sortUniqueLiveIns();
  1588. }
  1589. for (auto *MBB : reverse(PostOrder))
  1590. recomputeLivenessFlags(*MBB);
  1591. // We've moved, removed and inserted new instructions, so update RDA.
  1592. RDA->reset();
  1593. }
  1594. bool ARMLowOverheadLoops::RevertNonLoops() {
  1595. LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n");
  1596. bool Changed = false;
  1597. for (auto &MBB : *MF) {
  1598. SmallVector<MachineInstr*, 4> Starts;
  1599. SmallVector<MachineInstr*, 4> Decs;
  1600. SmallVector<MachineInstr*, 4> Ends;
  1601. SmallVector<MachineInstr *, 4> EndDecs;
  1602. SmallVector<MachineInstr *, 4> MQPRCopies;
  1603. for (auto &I : MBB) {
  1604. if (isLoopStart(I))
  1605. Starts.push_back(&I);
  1606. else if (I.getOpcode() == ARM::t2LoopDec)
  1607. Decs.push_back(&I);
  1608. else if (I.getOpcode() == ARM::t2LoopEnd)
  1609. Ends.push_back(&I);
  1610. else if (I.getOpcode() == ARM::t2LoopEndDec)
  1611. EndDecs.push_back(&I);
  1612. else if (I.getOpcode() == ARM::MQPRCopy)
  1613. MQPRCopies.push_back(&I);
  1614. }
  1615. if (Starts.empty() && Decs.empty() && Ends.empty() && EndDecs.empty() &&
  1616. MQPRCopies.empty())
  1617. continue;
  1618. Changed = true;
  1619. for (auto *Start : Starts) {
  1620. if (isWhileLoopStart(*Start))
  1621. RevertWhile(Start);
  1622. else
  1623. RevertDo(Start);
  1624. }
  1625. for (auto *Dec : Decs)
  1626. RevertLoopDec(Dec);
  1627. for (auto *End : Ends)
  1628. RevertLoopEnd(End);
  1629. for (auto *End : EndDecs)
  1630. RevertLoopEndDec(End);
  1631. for (auto *MI : MQPRCopies) {
  1632. LLVM_DEBUG(dbgs() << "Converting copy to VORR: " << *MI);
  1633. assert(MI->getOpcode() == ARM::MQPRCopy && "Only expected MQPRCOPY!");
  1634. MachineBasicBlock *MBB = MI->getParent();
  1635. auto MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::MVE_VORR),
  1636. MI->getOperand(0).getReg())
  1637. .add(MI->getOperand(1))
  1638. .add(MI->getOperand(1));
  1639. addUnpredicatedMveVpredROp(MIB, MI->getOperand(0).getReg());
  1640. MI->eraseFromParent();
  1641. }
  1642. }
  1643. return Changed;
  1644. }
  1645. FunctionPass *llvm::createARMLowOverheadLoopsPass() {
  1646. return new ARMLowOverheadLoops();
  1647. }