LLVM 24.0.0git
HexagonHardwareLoops.cpp
Go to the documentation of this file.
1//===- HexagonHardwareLoops.cpp - Identify and generate hardware loops ----===//
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//
9// This pass identifies loops where we can generate the Hexagon hardware
10// loop instruction. The hardware loop can perform loop branches with a
11// zero-cycle overhead.
12//
13// The pattern that defines the induction variable can changed depending on
14// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
15// normalizes induction variables, and the Loop Strength Reduction pass
16// run by 'llc' may also make changes to the induction variable.
17// The pattern detected by this phase is due to running Strength Reduction.
18//
19// Criteria for hardware loops:
20// - Countable loops (w/ ind. var for a trip count)
21// - Assumes loops are normalized by IndVarSimplify
22// - Try inner-most loops first
23// - No function calls in loops.
24//
25//===----------------------------------------------------------------------===//
26
27#include "Hexagon.h"
28#include "HexagonInstrInfo.h"
29#include "HexagonSubtarget.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
47#include "llvm/IR/DebugLoc.h"
49#include "llvm/Pass.h"
50#include "llvm/Support/Debug.h"
54#include <cassert>
55#include <cstdint>
56#include <cstdlib>
57#include <iterator>
58#include <map>
59#include <set>
60#include <string>
61#include <utility>
62#include <vector>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "hwloops"
67
68STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
69
70namespace {
71
72 class CountValue;
73
74 struct HexagonHardwareLoops : public MachineFunctionPass {
75 MachineLoopInfo *MLI;
78 const HexagonInstrInfo *TII;
81 const HexagonOptions *CLOpts = nullptr;
82#ifndef NDEBUG
83 static int Counter;
84#endif
85
86 public:
87 static char ID;
88
89 HexagonHardwareLoops() : MachineFunctionPass(ID) {}
90
91 bool runOnMachineFunction(MachineFunction &MF) override;
92
93 StringRef getPassName() const override { return "Hexagon Hardware Loops"; }
94
95 void getAnalysisUsage(AnalysisUsage &AU) const override {
96 AU.addRequired<MachineDominatorTreeWrapperPass>();
97 AU.addRequired<MachineLoopInfoWrapperPass>();
98 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
100 }
101
102 private:
103 using LoopFeederMap = std::map<Register, MachineInstr *>;
104
105 /// Kinds of comparisons in the compare instructions.
106 struct Comparison {
107 enum Kind {
108 EQ = 0x01,
109 NE = 0x02,
110 L = 0x04,
111 G = 0x08,
112 U = 0x40,
113 LTs = L,
114 LEs = L | EQ,
115 GTs = G,
116 GEs = G | EQ,
117 LTu = L | U,
118 LEu = L | EQ | U,
119 GTu = G | U,
120 GEu = G | EQ | U
121 };
122
123 static Kind getSwappedComparison(Kind Cmp) {
124 assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
125 if ((Cmp & L) || (Cmp & G))
126 return (Kind)(Cmp ^ (L|G));
127 return Cmp;
128 }
129
130 static Kind getNegatedComparison(Kind Cmp) {
131 if ((Cmp & L) || (Cmp & G))
132 return (Kind)((Cmp ^ (L | G)) ^ EQ);
133 if ((Cmp & NE) || (Cmp & EQ))
134 return (Kind)(Cmp ^ (EQ | NE));
135 return (Kind)0;
136 }
137
138 static bool isSigned(Kind Cmp) {
139 return (Cmp & (L | G) && !(Cmp & U));
140 }
141
142 static bool isUnsigned(Kind Cmp) {
143 return (Cmp & U);
144 }
145 };
146
147 /// Find the register that contains the loop controlling
148 /// induction variable.
149 /// If successful, it will return true and set the \p Reg, \p IVBump
150 /// and \p IVOp arguments. Otherwise it will return false.
151 /// The returned induction register is the register R that follows the
152 /// following induction pattern:
153 /// loop:
154 /// R = phi ..., [ R.next, LatchBlock ]
155 /// R.next = R + #bump
156 /// if (R.next < #N) goto loop
157 /// IVBump is the immediate value added to R, and IVOp is the instruction
158 /// "R.next = R + #bump".
159 bool findInductionRegister(MachineLoop *L, Register &Reg,
160 int64_t &IVBump, MachineInstr *&IVOp) const;
161
162 /// Return the comparison kind for the specified opcode.
163 Comparison::Kind getComparisonKind(unsigned CondOpc,
164 MachineOperand *InitialValue,
165 const MachineOperand *Endvalue,
166 int64_t IVBump) const;
167
168 /// Analyze the statements in a loop to determine if the loop
169 /// has a computable trip count and, if so, return a value that represents
170 /// the trip count expression.
171 CountValue *getLoopTripCount(MachineLoop *L,
172 SmallVectorImpl<MachineInstr *> &OldInsts);
173
174 /// Return the expression that represents the number of times
175 /// a loop iterates. The function takes the operands that represent the
176 /// loop start value, loop end value, and induction value. Based upon
177 /// these operands, the function attempts to compute the trip count.
178 /// If the trip count is not directly available (as an immediate value,
179 /// or a register), the function will attempt to insert computation of it
180 /// to the loop's preheader.
181 CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
182 const MachineOperand *End, Register IVReg,
183 int64_t IVBump, Comparison::Kind Cmp) const;
184
185 /// Return true if the instruction is not valid within a hardware
186 /// loop.
187 bool isInvalidLoopOperation(const MachineInstr *MI,
188 bool IsInnerHWLoop) const;
189
190 /// Return true if the loop contains an instruction that inhibits
191 /// using the hardware loop.
192 bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
193
194 /// Given a loop, check if we can convert it to a hardware loop.
195 /// If so, then perform the conversion and return true.
196 bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
197
198 /// Return true if the instruction is now dead.
199 bool isDead(const MachineInstr *MI,
200 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
201
202 /// Remove the instruction if it is now dead.
203 void removeIfDead(MachineInstr *MI);
204
205 /// Make sure that the "bump" instruction executes before the
206 /// compare. We need that for the IV fixup, so that the compare
207 /// instruction would not use a bumped value that has not yet been
208 /// defined. If the instructions are out of order, try to reorder them.
209 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
210
211 /// Return true if MO and MI pair is visited only once. If visited
212 /// more than once, this indicates there is recursion. In such a case,
213 /// return false.
214 bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
215 const MachineOperand *MO,
216 LoopFeederMap &LoopFeederPhi) const;
217
218 /// Return true if the Phi may generate a value that may underflow,
219 /// or may wrap.
220 bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
221 MachineBasicBlock *MBB, MachineLoop *L,
222 LoopFeederMap &LoopFeederPhi) const;
223
224 /// Return true if the induction variable may underflow an unsigned
225 /// value in the first iteration.
226 bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
227 const MachineOperand *EndVal,
228 MachineBasicBlock *MBB, MachineLoop *L,
229 LoopFeederMap &LoopFeederPhi) const;
230
231 /// Check if the given operand has a compile-time known constant
232 /// value. Return true if yes, and false otherwise. When returning true, set
233 /// Val to the corresponding constant value.
234 bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
235
236 /// Check if the operand has a compile-time known constant value.
237 bool isImmediate(const MachineOperand &MO) const {
238 int64_t V;
239 return checkForImmediate(MO, V);
240 }
241
242 /// Return the immediate for the specified operand.
243 int64_t getImmediate(const MachineOperand &MO) const {
244 int64_t V;
245 if (!checkForImmediate(MO, V))
246 llvm_unreachable("Invalid operand");
247 return V;
248 }
249
250 /// Reset the given machine operand to now refer to a new immediate
251 /// value. Assumes that the operand was already referencing an immediate
252 /// value, either directly, or via a register.
253 void setImmediate(MachineOperand &MO, int64_t Val);
254
255 /// If DI is a post-increment instruction whose base register is defined
256 /// by Phi and whose incremented address is PhiOpReg (the register feeding
257 /// Phi from the latch), extract the induction register and immediate bump
258 /// into IndReg and IVBump and return true. Returns false otherwise.
259 bool tryExtractPostIncInduction(MachineInstr *DI, MachineInstr *Phi,
260 Register PhiOpReg, Register &IndReg,
261 int64_t &IVBump) const;
262
263 /// Fix the data flow of the induction variable.
264 /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
265 /// |
266 /// +-> back to phi
267 /// where "bump" is the increment of the induction variable:
268 /// iv = iv + #const.
269 /// Due to some prior code transformations, the actual flow may look
270 /// like this:
271 /// phi -+-> bump ---> back to phi
272 /// |
273 /// +-> comparison-in-latch (against upper_bound-bump),
274 /// i.e. the comparison that controls the loop execution may be using
275 /// the value of the induction variable from before the increment.
276 ///
277 /// Return true if the loop's flow is the desired one (i.e. it's
278 /// either been fixed, or no fixing was necessary).
279 /// Otherwise, return false. This can happen if the induction variable
280 /// couldn't be identified, or if the value in the latch's comparison
281 /// cannot be adjusted to reflect the post-bump value.
282 bool fixupInductionVariable(MachineLoop *L);
283
284 /// Given a loop, if it does not have a preheader, create one.
285 /// Return the block that is the preheader.
286 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
287 };
288
289 char HexagonHardwareLoops::ID = 0;
290#ifndef NDEBUG
291 int HexagonHardwareLoops::Counter = 0;
292#endif
293
294 /// Abstraction for a trip count of a loop. A smaller version
295 /// of the MachineOperand class without the concerns of changing the
296 /// operand representation.
297 class CountValue {
298 public:
299 enum CountValueType {
300 CV_Register,
301 CV_Immediate
302 };
303
304 private:
305 CountValueType Kind;
306 union Values {
307 Values() : R{Register(), 0} {}
308 Values(const Values&) = default;
309 struct {
311 unsigned Sub;
312 } R;
313 unsigned ImmVal;
314 } Contents;
315
316 public:
317 explicit CountValue(CountValueType t, Register v, unsigned u = 0) {
318 Kind = t;
319 if (Kind == CV_Register) {
320 Contents.R.Reg = v;
321 Contents.R.Sub = u;
322 } else {
323 Contents.ImmVal = v;
324 }
325 }
326
327 bool isReg() const { return Kind == CV_Register; }
328 bool isImm() const { return Kind == CV_Immediate; }
329
330 Register getReg() const {
331 assert(isReg() && "Wrong CountValue accessor");
332 return Contents.R.Reg;
333 }
334
335 unsigned getSubReg() const {
336 assert(isReg() && "Wrong CountValue accessor");
337 return Contents.R.Sub;
338 }
339
340 unsigned getImm() const {
341 assert(isImm() && "Wrong CountValue accessor");
342 return Contents.ImmVal;
343 }
344
345 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
346 if (isReg()) { OS << printReg(Contents.R.Reg, TRI, Contents.R.Sub); }
347 if (isImm()) { OS << Contents.ImmVal; }
348 }
349 };
350
351} // end anonymous namespace
352
353INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
354 "Hexagon Hardware Loops", false, false)
357INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
358 "Hexagon Hardware Loops", false, false)
359
361 return new HexagonHardwareLoops();
362}
363
364bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
365 LLVM_DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
366 if (skipFunction(MF.getFunction()))
367 return false;
368
369 bool Changed = false;
370
371 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
372 MRI = &MF.getRegInfo();
373 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
375 TII = HST.getInstrInfo();
376 TRI = HST.getRegisterInfo();
377 CLOpts = &HST.getCLOpts();
378
379 MORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
380
381 for (auto &L : *MLI)
382 if (L->isOutermost()) {
383 bool L0Used = false;
384 bool L1Used = false;
385 Changed |= convertToHardwareLoop(L, L0Used, L1Used);
386 }
387
388 return Changed;
389}
390
391bool HexagonHardwareLoops::tryExtractPostIncInduction(MachineInstr *DI,
392 MachineInstr *Phi,
393 Register PhiOpReg,
394 Register &IndReg,
395 int64_t &IVBump) const {
396 if (!TII->isPostIncWithImmOffset(*DI))
397 return false;
398
399 unsigned BasePos, OffsetPos;
400 if (!TII->getBaseAndOffsetPosition(*DI, BasePos, OffsetPos))
401 return false;
402
403 if (BasePos >= DI->getNumOperands() || OffsetPos >= DI->getNumOperands())
404 return false;
405
406 // A post-increment load also defines the loaded value, which is unrelated
407 // to the base. Only the incremented address, tied to the base operand, is
408 // "base + offset", so require that it is what feeds the PHI.
409 const MachineOperand &BaseOp = DI->getOperand(BasePos);
410 if (!BaseOp.isReg() || !BaseOp.isTied())
411 return false;
412 if (DI->getOperand(DI->findTiedOperandIdx(BasePos)).getReg() != PhiOpReg)
413 return false;
414
415 IndReg = BaseOp.getReg();
416 IVBump = DI->getOperand(OffsetPos).getImm();
417 return MRI->getVRegDef(IndReg) == Phi;
418}
419
420bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
421 Register &Reg,
422 int64_t &IVBump,
423 MachineInstr *&IVOp
424 ) const {
425 MachineBasicBlock *Header = L->getHeader();
426 MachineBasicBlock *Preheader =
427 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
428 MachineBasicBlock *Latch = L->getLoopLatch();
429 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
430 if (!Header || !Preheader || !Latch || !ExitingBlock)
431 return false;
432
433 // This pair represents an induction register together with an immediate
434 // value that will be added to it in each loop iteration.
435 using RegisterBump = std::pair<Register, int64_t>;
436
437 // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
438 // from an induction operation
439 // R.next = R + bump
440 // where bump is an immediate value.
441 using InductionMap = std::map<Register, RegisterBump>;
442
443 InductionMap IndMap;
444
445 using instr_iterator = MachineBasicBlock::instr_iterator;
446
447 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
448 I != E && I->isPHI(); ++I) {
449 MachineInstr *Phi = &*I;
450
451 // Have a PHI instruction. Get the operand that corresponds to the
452 // latch block, and see if is a result of an addition of form "reg+imm",
453 // where the "reg" is defined by the PHI node we are looking at.
454 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
455 if (Phi->getOperand(i+1).getMBB() != Latch)
456 continue;
457
458 Register PhiOpReg = Phi->getOperand(i).getReg();
459 MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
460
461 if (DI->getDesc().isAdd()) {
462 // If the register operand to the add is the PHI we're looking at, this
463 // meets the induction pattern.
464 Register IndReg = DI->getOperand(1).getReg();
465 MachineOperand &Opnd2 = DI->getOperand(2);
466 int64_t V;
467 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
468 Register UpdReg = DI->getOperand(0).getReg();
469 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
470 }
471 } else {
472 Register IndReg;
473 int64_t V;
474 if (tryExtractPostIncInduction(DI, Phi, PhiOpReg, IndReg, V))
475 IndMap.insert(std::make_pair(PhiOpReg, std::make_pair(IndReg, V)));
476 }
477 } // for (i)
478 } // for (instr)
479
481 MachineBasicBlock *TB = nullptr, *FB = nullptr;
482 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
483 if (NotAnalyzed)
484 return false;
485
486 Register PredR;
487 unsigned PredPos;
488 RegState PredRegFlags;
489 if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
490 return false;
491
492 MachineInstr *PredI = MRI->getVRegDef(PredR);
493 if (!PredI->isCompare())
494 return false;
495
496 Register CmpReg1, CmpReg2;
497 int64_t CmpImm = 0, CmpMask = 0;
498 bool CmpAnalyzed =
499 TII->analyzeCompare(*PredI, CmpReg1, CmpReg2, CmpMask, CmpImm);
500 // Fail if the compare was not analyzed, or it's not comparing a register
501 // with an immediate value. Not checking the mask here, since we handle
502 // the individual compare opcodes (including A4_cmpb*) later on.
503 if (!CmpAnalyzed)
504 return false;
505
506 // Exactly one of the input registers to the comparison should be among
507 // the induction registers.
508 InductionMap::iterator IndMapEnd = IndMap.end();
509 InductionMap::iterator F = IndMapEnd;
510 if (CmpReg1 != 0) {
511 InductionMap::iterator F1 = IndMap.find(CmpReg1);
512 if (F1 != IndMapEnd)
513 F = F1;
514 }
515 if (CmpReg2 != 0) {
516 InductionMap::iterator F2 = IndMap.find(CmpReg2);
517 if (F2 != IndMapEnd) {
518 if (F != IndMapEnd)
519 return false;
520 F = F2;
521 }
522 }
523 if (F == IndMapEnd)
524 return false;
525
526 Reg = F->second.first;
527 IVBump = F->second.second;
528 IVOp = MRI->getVRegDef(F->first);
529 return true;
530}
531
532// Return the comparison kind for the specified opcode.
533HexagonHardwareLoops::Comparison::Kind
534HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
535 MachineOperand *InitialValue,
536 const MachineOperand *EndValue,
537 int64_t IVBump) const {
538 Comparison::Kind Cmp = (Comparison::Kind)0;
539 switch (CondOpc) {
540 case Hexagon::C2_cmpeq:
541 case Hexagon::C2_cmpeqi:
542 case Hexagon::C2_cmpeqp:
543 Cmp = Comparison::EQ;
544 break;
545 case Hexagon::C4_cmpneq:
546 case Hexagon::C4_cmpneqi:
547 Cmp = Comparison::NE;
548 break;
549 case Hexagon::C2_cmplt:
550 Cmp = Comparison::LTs;
551 break;
552 case Hexagon::C2_cmpltu:
553 Cmp = Comparison::LTu;
554 break;
555 case Hexagon::C4_cmplte:
556 case Hexagon::C4_cmpltei:
557 Cmp = Comparison::LEs;
558 break;
559 case Hexagon::C4_cmplteu:
560 case Hexagon::C4_cmplteui:
561 Cmp = Comparison::LEu;
562 break;
563 case Hexagon::C2_cmpgt:
564 case Hexagon::C2_cmpgti:
565 case Hexagon::C2_cmpgtp:
566 Cmp = Comparison::GTs;
567 break;
568 case Hexagon::C2_cmpgtu:
569 case Hexagon::C2_cmpgtui:
570 case Hexagon::C2_cmpgtup:
571 Cmp = Comparison::GTu;
572 break;
573 case Hexagon::C2_cmpgei:
574 Cmp = Comparison::GEs;
575 break;
576 case Hexagon::C2_cmpgeui:
577 Cmp = Comparison::GEs;
578 break;
579 default:
580 return (Comparison::Kind)0;
581 }
582 return Cmp;
583}
584
585/// Analyze the statements in a loop to determine if the loop has
586/// a computable trip count and, if so, return a value that represents
587/// the trip count expression.
588///
589/// This function iterates over the phi nodes in the loop to check for
590/// induction variable patterns that are used in the calculation for
591/// the number of time the loop is executed.
592CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
593 SmallVectorImpl<MachineInstr *> &OldInsts) {
594 MachineBasicBlock *TopMBB = L->getTopBlock();
596 assert(PI != TopMBB->pred_end() &&
597 "Loop must have more than one incoming edge!");
598 MachineBasicBlock *Backedge = *PI++;
599 if (PI == TopMBB->pred_end()) // dead loop?
600 return nullptr;
601 MachineBasicBlock *Incoming = *PI++;
602 if (PI != TopMBB->pred_end()) // multiple backedges?
603 return nullptr;
604
605 // Make sure there is one incoming and one backedge and determine which
606 // is which.
607 if (L->contains(Incoming)) {
608 if (L->contains(Backedge))
609 return nullptr;
610 std::swap(Incoming, Backedge);
611 } else if (!L->contains(Backedge))
612 return nullptr;
613
614 // Look for the cmp instruction to determine if we can get a useful trip
615 // count. The trip count can be either a register or an immediate. The
616 // location of the value depends upon the type (reg or imm).
617 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
618 if (!ExitingBlock)
619 return nullptr;
620
621 Register IVReg = 0;
622 int64_t IVBump = 0;
623 MachineInstr *IVOp;
624 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
625 if (!FoundIV)
626 return nullptr;
627
628 MachineBasicBlock *Preheader =
629 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
630
631 MachineOperand *InitialValue = nullptr;
632 MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
633 MachineBasicBlock *Latch = L->getLoopLatch();
634 for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
635 MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
636 if (MBB == Preheader)
637 InitialValue = &IV_Phi->getOperand(i);
638 else if (MBB == Latch)
639 IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
640 }
641 if (!InitialValue)
642 return nullptr;
643
645 MachineBasicBlock *TB = nullptr, *FB = nullptr;
646 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
647 if (NotAnalyzed)
648 return nullptr;
649
650 MachineBasicBlock *Header = L->getHeader();
651 // TB must be non-null. If FB is also non-null, one of them must be
652 // the header. Otherwise, branch to TB could be exiting the loop, and
653 // the fall through can go to the header.
654 assert (TB && "Exit block without a branch?");
655 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
656 MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
658 bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
659 if (NotAnalyzed)
660 return nullptr;
661 if (TB == Latch)
662 TB = (LTB == Header) ? LTB : LFB;
663 else
664 FB = (LTB == Header) ? LTB: LFB;
665 }
666 assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
667 if (!TB || (FB && TB != Header && FB != Header))
668 return nullptr;
669
670 // Branches of form "if (!P) ..." cause HexagonInstrInfo::analyzeBranch
671 // to put imm(0), followed by P in the vector Cond.
672 // If TB is not the header, it means that the "not-taken" path must lead
673 // to the header.
674 bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
675 Register PredReg;
676 unsigned PredPos;
677 RegState PredRegFlags;
678 if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
679 return nullptr;
680 MachineInstr *CondI = MRI->getVRegDef(PredReg);
681 unsigned CondOpc = CondI->getOpcode();
682
683 Register CmpReg1, CmpReg2;
684 int64_t Mask = 0, ImmValue = 0;
685 bool AnalyzedCmp =
686 TII->analyzeCompare(*CondI, CmpReg1, CmpReg2, Mask, ImmValue);
687 if (!AnalyzedCmp)
688 return nullptr;
689
690 // The comparison operator type determines how we compute the loop
691 // trip count.
692 OldInsts.push_back(CondI);
693 OldInsts.push_back(IVOp);
694
695 // Sadly, the following code gets information based on the position
696 // of the operands in the compare instruction. This has to be done
697 // this way, because the comparisons check for a specific relationship
698 // between the operands (e.g. is-less-than), rather than to find out
699 // what relationship the operands are in (as on PPC).
700 Comparison::Kind Cmp;
701 bool isSwapped = false;
702 const MachineOperand &Op1 = CondI->getOperand(1);
703 const MachineOperand &Op2 = CondI->getOperand(2);
704 const MachineOperand *EndValue = nullptr;
705
706 if (Op1.isReg()) {
707 if (Op2.isImm() || Op1.getReg() == IVReg)
708 EndValue = &Op2;
709 else {
710 EndValue = &Op1;
711 isSwapped = true;
712 }
713 }
714
715 if (!EndValue)
716 return nullptr;
717
718 Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
719 if (!Cmp)
720 return nullptr;
721 if (Negated)
722 Cmp = Comparison::getNegatedComparison(Cmp);
723 if (isSwapped)
724 Cmp = Comparison::getSwappedComparison(Cmp);
725
726 if (InitialValue->isReg()) {
727 Register R = InitialValue->getReg();
728 MachineBasicBlock *DefBB = MRI->getDefBlock(R);
729 if (!MDT->properlyDominates(DefBB, Header)) {
730 int64_t V;
731 if (!checkForImmediate(*InitialValue, V))
732 return nullptr;
733 }
734 OldInsts.push_back(MRI->getVRegDef(R));
735 }
736 if (EndValue->isReg()) {
737 Register R = EndValue->getReg();
738 MachineBasicBlock *DefBB = MRI->getDefBlock(R);
739 if (!MDT->properlyDominates(DefBB, Header)) {
740 int64_t V;
741 if (!checkForImmediate(*EndValue, V))
742 return nullptr;
743 }
744 OldInsts.push_back(MRI->getVRegDef(R));
745 }
746
747 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
748}
749
750/// Helper function that returns the expression that represents the
751/// number of times a loop iterates. The function takes the operands that
752/// represent the loop start value, loop end value, and induction value.
753/// Based upon these operands, the function attempts to compute the trip count.
754CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
755 const MachineOperand *Start,
756 const MachineOperand *End,
757 Register IVReg,
758 int64_t IVBump,
759 Comparison::Kind Cmp) const {
760 LLVM_DEBUG(llvm::dbgs() << "Loop: " << *Loop << "\n");
761 LLVM_DEBUG(llvm::dbgs() << "Initial Value: " << *Start << "\n");
762 LLVM_DEBUG(llvm::dbgs() << "End Value: " << *End << "\n");
763 LLVM_DEBUG(llvm::dbgs() << "Inc/Dec Value: " << IVBump << "\n");
764 LLVM_DEBUG(llvm::dbgs() << "Comparison: " << Cmp << "\n");
765 // Cannot handle comparison EQ, i.e. while (A == B).
766 if (Cmp == Comparison::EQ)
767 return nullptr;
768
769 // Check if either the start or end values are an assignment of an immediate.
770 // If so, use the immediate value rather than the register.
771 if (Start->isReg()) {
772 const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
773 if (StartValInstr && (StartValInstr->getOpcode() == Hexagon::A2_tfrsi ||
774 StartValInstr->getOpcode() == Hexagon::A2_tfrpi))
775 Start = &StartValInstr->getOperand(1);
776 }
777 if (End->isReg()) {
778 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
779 if (EndValInstr && (EndValInstr->getOpcode() == Hexagon::A2_tfrsi ||
780 EndValInstr->getOpcode() == Hexagon::A2_tfrpi))
781 End = &EndValInstr->getOperand(1);
782 }
783
784 if (!Start->isReg() && !Start->isImm())
785 return nullptr;
786 if (!End->isReg() && !End->isImm())
787 return nullptr;
788
789 bool CmpLess = Cmp & Comparison::L;
790 bool CmpGreater = Cmp & Comparison::G;
791 bool CmpHasEqual = Cmp & Comparison::EQ;
792
793 // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
794 if (CmpLess && IVBump < 0)
795 // Loop going while iv is "less" with the iv value going down. Must wrap.
796 return nullptr;
797
798 if (CmpGreater && IVBump > 0)
799 // Loop going while iv is "greater" with the iv value going up. Must wrap.
800 return nullptr;
801
802 // Phis that may feed into the loop.
803 LoopFeederMap LoopFeederPhi;
804
805 // Check if the initial value may be zero and can be decremented in the first
806 // iteration. If the value is zero, the endloop instruction will not decrement
807 // the loop counter, so we shouldn't generate a hardware loop in this case.
808 if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
809 LoopFeederPhi))
810 return nullptr;
811
812 if (Start->isImm() && End->isImm()) {
813 // Both, start and end are immediates.
814 int64_t StartV = Start->getImm();
815 int64_t EndV = End->getImm();
816 int64_t Dist = EndV - StartV;
817 if (Dist == 0)
818 return nullptr;
819
820 bool Exact = (Dist % IVBump) == 0;
821
822 if (Cmp == Comparison::NE) {
823 if (!Exact)
824 return nullptr;
825 if ((Dist < 0) ^ (IVBump < 0))
826 return nullptr;
827 }
828
829 // For comparisons that include the final value (i.e. include equality
830 // with the final value), we need to increase the distance by 1.
831 if (CmpHasEqual)
832 Dist = Dist > 0 ? Dist+1 : Dist-1;
833
834 // For the loop to iterate, CmpLess should imply Dist > 0. Similarly,
835 // CmpGreater should imply Dist < 0. These conditions could actually
836 // fail, for example, in unreachable code (which may still appear to be
837 // reachable in the CFG).
838 if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
839 return nullptr;
840
841 // "Normalized" distance, i.e. with the bump set to +-1.
842 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump - 1)) / IVBump
843 : (-Dist + (-IVBump - 1)) / (-IVBump);
844 assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
845
846 uint64_t Count = Dist1;
847
848 if (Count > 0xFFFFFFFFULL)
849 return nullptr;
850
851 return new CountValue(CountValue::CV_Immediate, Count);
852 }
853
854 // A general case: Start and End are some values, but the actual
855 // iteration count may not be available. If it is not, insert
856 // a computation of it into the preheader.
857
858 // If the induction variable bump is not a power of 2, quit.
859 // Otherwise we'd need a general integer division.
860 if (!isPowerOf2_64(std::abs(IVBump)))
861 return nullptr;
862
863 MachineBasicBlock *PH =
864 MLI->findLoopPreheader(Loop, CLOpts->hwloop_spec_preheader);
865 assert (PH && "Should have a preheader by now");
867 DebugLoc DL;
868 if (InsertPos != PH->end())
869 DL = InsertPos->getDebugLoc();
870
871 // If Start is an immediate and End is a register, the trip count
872 // will be "reg - imm". Hexagon's "subtract immediate" instruction
873 // is actually "reg + -imm".
874
875 // If the loop IV is going downwards, i.e. if the bump is negative,
876 // then the iteration count (computed as End-Start) will need to be
877 // negated. To avoid the negation, just swap Start and End.
878 if (IVBump < 0) {
879 std::swap(Start, End);
880 IVBump = -IVBump;
881 std::swap(CmpLess, CmpGreater);
882 }
883 // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
884 // Signedness, and "including equality" are preserved.
885
886 bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
887 bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
888
889 int64_t StartV = 0, EndV = 0;
890 if (Start->isImm())
891 StartV = Start->getImm();
892 if (End->isImm())
893 EndV = End->getImm();
894
895 int64_t AdjV = 0;
896 // To compute the iteration count, we would need this computation:
897 // Count = (End - Start + (IVBump-1)) / IVBump
898 // or, when CmpHasEqual:
899 // Count = (End - Start + (IVBump-1)+1) / IVBump
900 // The "IVBump-1" part is the adjustment (AdjV). We can avoid
901 // generating an instruction specifically to add it if we can adjust
902 // the immediate values for Start or End.
903
904 if (CmpHasEqual) {
905 // Need to add 1 to the total iteration count.
906 if (Start->isImm())
907 StartV--;
908 else if (End->isImm())
909 EndV++;
910 else
911 AdjV += 1;
912 }
913
914 if (Cmp != Comparison::NE) {
915 if (Start->isImm())
916 StartV -= (IVBump-1);
917 else if (End->isImm())
918 EndV += (IVBump-1);
919 else
920 AdjV += (IVBump-1);
921 }
922
923 Register R = 0;
924 unsigned SR = 0;
925 if (Start->isReg()) {
926 R = Start->getReg();
927 SR = Start->getSubReg();
928 } else {
929 R = End->getReg();
930 SR = End->getSubReg();
931 }
932 const TargetRegisterClass *RC = MRI->getRegClass(R);
933 // Hardware loops cannot handle 64-bit registers. If it's a double
934 // register, it has to have a subregister.
935 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
936 return nullptr;
937 const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
938
939 // Compute DistR (register with the distance between Start and End).
940 Register DistR;
941 unsigned DistSR;
942
943 // Avoid special case, where the start value is an imm(0).
944 if (Start->isImm() && StartV == 0) {
945 DistR = End->getReg();
946 DistSR = End->getSubReg();
947 } else {
948 const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
949 (RegToImm ? TII->get(Hexagon::A2_subri) :
950 TII->get(Hexagon::A2_addi));
951 if (RegToReg || RegToImm) {
952 Register SubR = MRI->createVirtualRegister(IntRC);
953 MachineInstrBuilder SubIB =
954 BuildMI(*PH, InsertPos, DL, SubD, SubR);
955
956 if (RegToReg)
957 SubIB.addReg(End->getReg(), {}, End->getSubReg())
958 .addReg(Start->getReg(), {}, Start->getSubReg());
959 else
960 SubIB.addImm(EndV).addReg(Start->getReg(), {}, Start->getSubReg());
961 DistR = SubR;
962 } else {
963 // If the loop has been unrolled, we should use the original loop count
964 // instead of recalculating the value. This will avoid additional
965 // 'Add' instruction.
966 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
967 if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
968 EndValInstr->getOperand(1).getSubReg() == 0 &&
969 EndValInstr->getOperand(2).getImm() == StartV) {
970 DistR = EndValInstr->getOperand(1).getReg();
971 } else {
972 Register SubR = MRI->createVirtualRegister(IntRC);
973 MachineInstrBuilder SubIB =
974 BuildMI(*PH, InsertPos, DL, SubD, SubR);
975 SubIB.addReg(End->getReg(), {}, End->getSubReg()).addImm(-StartV);
976 DistR = SubR;
977 }
978 }
979 DistSR = 0;
980 }
981
982 // From DistR, compute AdjR (register with the adjusted distance).
983 Register AdjR;
984 unsigned AdjSR;
985
986 if (AdjV == 0) {
987 AdjR = DistR;
988 AdjSR = DistSR;
989 } else {
990 // Generate CountR = ADD DistR, AdjVal
991 Register AddR = MRI->createVirtualRegister(IntRC);
992 MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
993 BuildMI(*PH, InsertPos, DL, AddD, AddR)
994 .addReg(DistR, {}, DistSR)
995 .addImm(AdjV);
996
997 AdjR = AddR;
998 AdjSR = 0;
999 }
1000
1001 // From AdjR, compute CountR (register with the final count).
1002 Register CountR;
1003 unsigned CountSR;
1004
1005 if (IVBump == 1) {
1006 CountR = AdjR;
1007 CountSR = AdjSR;
1008 } else {
1009 // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
1010 unsigned Shift = Log2_32(IVBump);
1011
1012 // Generate NormR = LSR DistR, Shift.
1013 Register LsrR = MRI->createVirtualRegister(IntRC);
1014 const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
1015 BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
1016 .addReg(AdjR, {}, AdjSR)
1017 .addImm(Shift);
1018
1019 CountR = LsrR;
1020 CountSR = 0;
1021 }
1022
1023 const TargetRegisterClass *PredRC = &Hexagon::PredRegsRegClass;
1024 Register MuxR = CountR;
1025 unsigned MuxSR = CountSR;
1026 // For the loop count to be valid unsigned number, CmpLess should imply
1027 // Dist >= 0. Similarly, CmpGreater should imply Dist < 0. We can skip the
1028 // check if the initial distance is zero and the comparison is LTu || LTEu.
1029 if (!(Start->isImm() && StartV == 0 && Comparison::isUnsigned(Cmp) &&
1030 CmpLess) &&
1031 (CmpLess || CmpGreater)) {
1032 // Generate:
1033 // DistCheck = CMP_GT DistR, 0 --> CmpLess
1034 // DistCheck = CMP_GT DistR, -1 --> CmpGreater
1035 Register DistCheckR = MRI->createVirtualRegister(PredRC);
1036 unsigned DistCheckOpc = (CmpLess && Comparison::isUnsigned(Cmp))
1037 ? Hexagon::C2_cmpgtui
1038 : Hexagon::C2_cmpgti;
1039 const MCInstrDesc &DistCheckD = TII->get(DistCheckOpc);
1040 BuildMI(*PH, InsertPos, DL, DistCheckD, DistCheckR)
1041 .addReg(DistR, {}, DistSR)
1042 .addImm((CmpLess) ? 0 : -1);
1043
1044 // Generate:
1045 // MUXR = MUX DistCheck, CountR, 1 --> CmpLess
1046 // MUXR = MUX DistCheck, 1, CountR --> CmpGreater
1047 MuxR = MRI->createVirtualRegister(IntRC);
1048 if (CmpLess) {
1049 const MCInstrDesc &MuxD = TII->get(Hexagon::C2_muxir);
1050 BuildMI(*PH, InsertPos, DL, MuxD, MuxR)
1051 .addReg(DistCheckR)
1052 .addReg(CountR, {}, CountSR)
1053 .addImm(1);
1054 } else {
1055 const MCInstrDesc &MuxD = TII->get(Hexagon::C2_muxri);
1056 BuildMI(*PH, InsertPos, DL, MuxD, MuxR)
1057 .addReg(DistCheckR)
1058 .addImm(1)
1059 .addReg(CountR, {}, CountSR);
1060 }
1061 MuxSR = 0;
1062 }
1063
1064 return new CountValue(CountValue::CV_Register, MuxR, MuxSR);
1065}
1066
1067/// Return true if the operation is invalid within hardware loop.
1068bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
1069 bool IsInnerHWLoop) const {
1070 // Call is not allowed because the callee may use a hardware loop except for
1071 // the case when the call never returns.
1072 if (MI->getDesc().isCall())
1073 return !TII->doesNotReturn(*MI);
1074
1075 // Check if the instruction defines a hardware loop register.
1076 using namespace Hexagon;
1077
1078 static const Register Regs01[] = { LC0, SA0, LC1, SA1 };
1079 static const Register Regs1[] = { LC1, SA1 };
1080 auto CheckRegs = IsInnerHWLoop ? ArrayRef(Regs01) : ArrayRef(Regs1);
1081 for (Register R : CheckRegs)
1082 if (MI->modifiesRegister(R, TRI))
1083 return true;
1084
1085 return false;
1086}
1087
1088/// Return true if the loop contains an instruction that inhibits
1089/// the use of the hardware loop instruction.
1090bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
1091 bool IsInnerHWLoop) const {
1092 LLVM_DEBUG(dbgs() << "\nhw_loop head, "
1093 << printMBBReference(**L->block_begin()));
1094 for (MachineBasicBlock *MBB : L->getBlocks()) {
1095 for (const MachineInstr &MI : *MBB) {
1096 if (isInvalidLoopOperation(&MI, IsInnerHWLoop)) {
1097 LLVM_DEBUG(dbgs() << "\nCannot convert to hw_loop due to:";
1098 MI.dump(););
1099 return true;
1100 }
1101 }
1102 }
1103 return false;
1104}
1105
1106/// Returns true if the instruction is dead. This was essentially
1107/// copied from DeadMachineInstructionElim::isDead, but with special cases
1108/// for inline asm, physical registers and instructions with side effects
1109/// removed.
1110bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
1111 SmallVectorImpl<MachineInstr *> &DeadPhis) const {
1112 // Examine each operand.
1113 for (const MachineOperand &MO : MI->operands()) {
1114 if (!MO.isReg() || !MO.isDef())
1115 continue;
1116
1117 Register Reg = MO.getReg();
1118 if (MRI->use_nodbg_empty(Reg))
1119 continue;
1120
1121 using use_nodbg_iterator = MachineRegisterInfo::use_nodbg_iterator;
1122
1123 // This instruction has users, but if the only user is the phi node for the
1124 // parent block, and the only use of that phi node is this instruction, then
1125 // this instruction is dead: both it (and the phi node) can be removed.
1126 use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
1127 use_nodbg_iterator End = MRI->use_nodbg_end();
1128 if (std::next(I) != End || !I->getParent()->isPHI())
1129 return false;
1130
1131 MachineInstr *OnePhi = I->getParent();
1132 for (const MachineOperand &OPO : OnePhi->operands()) {
1133 if (!OPO.isReg() || !OPO.isDef())
1134 continue;
1135
1136 Register OPReg = OPO.getReg();
1137 use_nodbg_iterator nextJ;
1138 for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
1139 J != End; J = nextJ) {
1140 nextJ = std::next(J);
1141 MachineOperand &Use = *J;
1142 MachineInstr *UseMI = Use.getParent();
1143
1144 // If the phi node has a user that is not MI, bail.
1145 if (MI != UseMI)
1146 return false;
1147 }
1148 }
1149 DeadPhis.push_back(OnePhi);
1150 }
1151
1152 // If there are no defs with uses, the instruction is dead.
1153 return true;
1154}
1155
1156void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1157 // This procedure was essentially copied from DeadMachineInstructionElim.
1158
1160 if (isDead(MI, DeadPhis)) {
1161 LLVM_DEBUG(dbgs() << "HW looping will remove: " << *MI);
1162
1163 // It is possible that some DBG_VALUE instructions refer to this
1164 // instruction. Examine each def operand for such references;
1165 // if found, mark the DBG_VALUE as undef (but don't delete it).
1166 for (const MachineOperand &MO : MI->operands()) {
1167 if (!MO.isReg() || !MO.isDef())
1168 continue;
1169 Register Reg = MO.getReg();
1170 // We use make_early_inc_range here because setReg below invalidates the
1171 // iterator.
1172 for (MachineOperand &MO :
1174 MachineInstr *UseMI = MO.getParent();
1175 if (UseMI == MI)
1176 continue;
1177 if (MO.isDebug())
1178 MO.setReg(0U);
1179 }
1180 }
1181
1182 MI->eraseFromParent();
1183 for (unsigned i = 0; i < DeadPhis.size(); ++i)
1184 DeadPhis[i]->eraseFromParent();
1185 }
1186}
1187
1188/// Check if the loop is a candidate for converting to a hardware
1189/// loop. If so, then perform the transformation.
1190///
1191/// This function works on innermost loops first. A loop can be converted
1192/// if it is a counting loop; either a register value or an immediate.
1193///
1194/// The code makes several assumptions about the representation of the loop
1195/// in llvm.
1196bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1197 bool &RecL0used,
1198 bool &RecL1used) {
1199 // This is just to confirm basic correctness.
1200 assert(L->getHeader() && "Loop without a header?");
1201
1202 bool Changed = false;
1203 bool L0Used = false;
1204 bool L1Used = false;
1205
1206 // Process nested loops first.
1207 for (MachineLoop *I : *L) {
1208 Changed |= convertToHardwareLoop(I, RecL0used, RecL1used);
1209 L0Used |= RecL0used;
1210 L1Used |= RecL1used;
1211 }
1212
1213 // If a nested loop has been converted, then we can't convert this loop.
1214 if (Changed && L0Used && L1Used)
1215 return Changed;
1216
1217 unsigned LOOP_i;
1218 unsigned LOOP_r;
1219 unsigned ENDLOOP;
1220
1221 // Flag used to track loopN instruction:
1222 // 1 - Hardware loop is being generated for the inner most loop.
1223 // 0 - Hardware loop is being generated for the outer loop.
1224 unsigned IsInnerHWLoop = 1;
1225
1226 if (L0Used) {
1227 LOOP_i = Hexagon::J2_loop1i;
1228 LOOP_r = Hexagon::J2_loop1r;
1229 ENDLOOP = Hexagon::ENDLOOP1;
1230 IsInnerHWLoop = 0;
1231 } else {
1232 LOOP_i = Hexagon::J2_loop0i;
1233 LOOP_r = Hexagon::J2_loop0r;
1234 ENDLOOP = Hexagon::ENDLOOP0;
1235 }
1236
1237#ifndef NDEBUG
1238 // Stop trying after reaching the limit (if any).
1239 int Limit = CLOpts->max_hwloop;
1240 if (Limit >= 0) {
1241 if (Counter >= CLOpts->max_hwloop)
1242 return false;
1243 Counter++;
1244 }
1245#endif
1246
1247 // Does the loop contain any invalid instructions?
1248 if (containsInvalidInstruction(L, IsInnerHWLoop)) {
1249 MORE->emit([&]() {
1250 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "InvalidInstruction",
1251 L->getStartLoc(), L->getHeader())
1252 << "loop contains an instruction that prevents hardware loop "
1253 "generation (e.g. a call or hardware loop register definition)";
1254 });
1255 return false;
1256 }
1257
1258 MachineBasicBlock *LastMBB = L->findLoopControlBlock();
1259 // Check actual CFG successors: analyzeBranch omits implicit fallthroughs.
1260 // Only reject multi-exit loops whose selected exit reaches an unreachable
1261 // sink, preserving valid multi-exit loops.
1262 SmallVector<MachineBasicBlock *, 2> ExitingBlocks;
1263 L->getExitingBlocks(ExitingBlocks);
1264 bool HasUnreachableExit = false;
1265 if (LastMBB && ExitingBlocks.size() > 1) {
1266 for (MachineBasicBlock *Succ : LastMBB->successors()) {
1267 if (!L->contains(Succ) && !Succ->empty() && Succ->succ_empty() &&
1268 !Succ->isReturnBlock()) {
1269 HasUnreachableExit = true;
1270 break;
1271 }
1272 }
1273 }
1274 if (!LastMBB || HasUnreachableExit) {
1275 MORE->emit([&]() {
1276 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "MultipleExits",
1277 L->getStartLoc(), L->getHeader())
1278 << "loop has multiple exits and cannot be converted to a "
1279 "hardware loop";
1280 });
1281 return false;
1282 }
1283
1285 if (LastI == LastMBB->end())
1286 return false;
1287
1288 // Is the induction variable bump feeding the latch condition?
1289 if (!fixupInductionVariable(L)) {
1290 MORE->emit([&]() {
1291 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "InductionVariable",
1292 L->getStartLoc(), L->getHeader())
1293 << "could not identify or fix up the induction variable";
1294 });
1295 return false;
1296 }
1297
1298 // Ensure the loop has a preheader: the loop instruction will be
1299 // placed there.
1300 MachineBasicBlock *Preheader =
1301 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader);
1302 if (!Preheader) {
1303 Preheader = createPreheaderForLoop(L);
1304 if (!Preheader)
1305 return false;
1306 }
1307
1308 MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1309
1310 SmallVector<MachineInstr*, 2> OldInsts;
1311 // Are we able to determine the trip count for the loop?
1312 CountValue *TripCount = getLoopTripCount(L, OldInsts);
1313 if (!TripCount) {
1314 MORE->emit([&]() {
1315 return MachineOptimizationRemarkMissed(DEBUG_TYPE, "TripCount",
1316 L->getStartLoc(), L->getHeader())
1317 << "trip count of the loop could not be computed";
1318 });
1319 return false;
1320 }
1321
1322 // Is the trip count available in the preheader?
1323 if (TripCount->isReg()) {
1324 // There will be a use of the register inserted into the preheader,
1325 // so make sure that the register is actually defined at that point.
1326 MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1327 MachineBasicBlock *BBDef = TCDef->getParent();
1328 if (!MDT->dominates(BBDef, Preheader)) {
1329 MORE->emit([&]() {
1330 return MachineOptimizationRemarkMissed(DEBUG_TYPE,
1331 "TripCountNotDominating",
1332 L->getStartLoc(), L->getHeader())
1333 << "trip count register is not available in the loop preheader";
1334 });
1335 return false;
1336 }
1337 }
1338
1339 // Determine the loop start.
1340 MachineBasicBlock *TopBlock = L->getTopBlock();
1341 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1342 MachineBasicBlock *LoopStart = nullptr;
1343 if (ExitingBlock != L->getLoopLatch()) {
1344 MachineBasicBlock *TB = nullptr, *FB = nullptr;
1346
1347 if (TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false))
1348 return false;
1349
1350 if (L->contains(TB))
1351 LoopStart = TB;
1352 else if (L->contains(FB))
1353 LoopStart = FB;
1354 else
1355 return false;
1356 }
1357 else
1358 LoopStart = TopBlock;
1359
1360 // Convert the loop to a hardware loop.
1361 LLVM_DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
1362 DebugLoc DL;
1363 if (InsertPos != Preheader->end())
1364 DL = InsertPos->getDebugLoc();
1365
1366 if (TripCount->isReg()) {
1367 // Create a copy of the loop count register.
1368 Register CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1369 BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1370 .addReg(TripCount->getReg(), {}, TripCount->getSubReg());
1371 // Add the Loop instruction to the beginning of the loop.
1372 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
1373 .addReg(CountReg);
1374 } else {
1375 assert(TripCount->isImm() && "Expecting immediate value for trip count");
1376 // Add the Loop immediate instruction to the beginning of the loop,
1377 // if the immediate fits in the instructions. Otherwise, we need to
1378 // create a new virtual register.
1379 int64_t CountImm = TripCount->getImm();
1380 if (!TII->isValidOffset(LOOP_i, CountImm)) {
1381 Register CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1382 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
1383 .addImm(CountImm);
1384 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
1385 .addMBB(LoopStart).addReg(CountReg);
1386 } else
1387 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
1388 .addMBB(LoopStart).addImm(CountImm);
1389 }
1390
1391 // Make sure the loop start always has a reference in the CFG.
1392 LoopStart->setMachineBlockAddressTaken();
1393
1394 // Replace the loop branch with an endloop instruction.
1395 DebugLoc LastIDL = LastI->getDebugLoc();
1396 BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
1397
1398 // The loop ends with either:
1399 // - a conditional branch followed by an unconditional branch, or
1400 // - a conditional branch to the loop start.
1401 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1402 LastI->getOpcode() == Hexagon::J2_jumpf) {
1403 // Delete one and change/add an uncond. branch to out of the loop.
1404 MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1405 LastI = LastMBB->erase(LastI);
1406 if (!L->contains(BranchTarget)) {
1407 if (LastI != LastMBB->end())
1408 LastI = LastMBB->erase(LastI);
1410 TII->insertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
1411 }
1412 } else {
1413 // Conditional branch to loop start; just delete it.
1414 LastMBB->erase(LastI);
1415 }
1416 delete TripCount;
1417
1418 // The induction operation and the comparison may now be
1419 // unneeded. If these are unneeded, then remove them.
1420 for (unsigned i = 0; i < OldInsts.size(); ++i)
1421 removeIfDead(OldInsts[i]);
1422
1423 ++NumHWLoops;
1424
1425 MORE->emit([&]() {
1426 return MachineOptimizationRemark(DEBUG_TYPE, "HardwareLoop",
1427 L->getStartLoc(), L->getHeader())
1428 << "converted loop to hardware loop";
1429 });
1430
1431 // Set RecL1used and RecL0used only after hardware loop has been
1432 // successfully generated. Doing it earlier can cause wrong loop instruction
1433 // to be used.
1434 if (L0Used) // Loop0 was already used. So, the correct loop must be loop1.
1435 RecL1used = true;
1436 else
1437 RecL0used = true;
1438
1439 return true;
1440}
1441
1442bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1443 MachineInstr *CmpI) {
1444 assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1445
1446 MachineBasicBlock *BB = BumpI->getParent();
1447 if (CmpI->getParent() != BB)
1448 return false;
1449
1450 using instr_iterator = MachineBasicBlock::instr_iterator;
1451
1452 // Check if things are in order to begin with.
1453 for (instr_iterator I(BumpI), E = BB->instr_end(); I != E; ++I)
1454 if (&*I == CmpI)
1455 return true;
1456
1457 // Out of order.
1458 Register PredR = CmpI->getOperand(0).getReg();
1459 bool FoundBump = false;
1460 instr_iterator CmpIt = CmpI->getIterator(), NextIt = std::next(CmpIt);
1461 for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1462 MachineInstr *In = &*I;
1463 for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1464 MachineOperand &MO = In->getOperand(i);
1465 if (MO.isReg() && MO.isUse()) {
1466 if (MO.getReg() == PredR) // Found an intervening use of PredR.
1467 return false;
1468 }
1469 }
1470
1471 if (In == BumpI) {
1472 BB->splice(++BumpI->getIterator(), BB, CmpI->getIterator());
1473 FoundBump = true;
1474 break;
1475 }
1476 }
1477 assert (FoundBump && "Cannot determine instruction order");
1478 return FoundBump;
1479}
1480
1481/// This function is required to break recursion. Visiting phis in a loop may
1482/// result in recursion during compilation. We break the recursion by making
1483/// sure that we visit a MachineOperand and its definition in a
1484/// MachineInstruction only once. If we attempt to visit more than once, then
1485/// there is recursion, and will return false.
1486bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1487 MachineInstr *MI,
1488 const MachineOperand *MO,
1489 LoopFeederMap &LoopFeederPhi) const {
1490 if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1491 LLVM_DEBUG(dbgs() << "\nhw_loop head, "
1492 << printMBBReference(**L->block_begin()));
1493 // Ignore all BBs that form Loop.
1494 if (llvm::is_contained(L->getBlocks(), A))
1495 return false;
1496 MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1497 LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1498 return true;
1499 } else
1500 // Already visited node.
1501 return false;
1502}
1503
1504/// Return true if a Phi may generate a value that can underflow.
1505/// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1506bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1507 MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1508 MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1509 assert(Phi->isPHI() && "Expecting a Phi.");
1510 // Walk through each Phi, and its used operands. Make sure that
1511 // if there is recursion in Phi, we won't generate hardware loops.
1512 for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1513 if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1514 if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1515 Phi->getParent(), L, LoopFeederPhi))
1516 return true;
1517 return false;
1518}
1519
1520/// Return true if the induction variable can underflow in the first iteration.
1521/// An example, is an initial unsigned value that is 0 and is decrement in the
1522/// first itertion of a do-while loop. In this case, we cannot generate a
1523/// hardware loop because the endloop instruction does not decrement the loop
1524/// counter if it is <= 1. We only need to perform this analysis if the
1525/// initial value is a register.
1526///
1527/// This function assumes the initial value may underflow unless proven
1528/// otherwise. If the type is signed, then we don't care because signed
1529/// underflow is undefined. We attempt to prove the initial value is not
1530/// zero by performing a crude analysis of the loop counter. This function
1531/// checks if the initial value is used in any comparison prior to the loop
1532/// and, if so, assumes the comparison is a range check. This is inexact,
1533/// but will catch the simple cases.
1534bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1535 const MachineOperand *InitVal, const MachineOperand *EndVal,
1536 MachineBasicBlock *MBB, MachineLoop *L,
1537 LoopFeederMap &LoopFeederPhi) const {
1538 // Only check register values since they are unknown.
1539 if (!InitVal->isReg())
1540 return false;
1541
1542 if (!EndVal->isImm())
1543 return false;
1544
1545 // A register value that is assigned an immediate is a known value, and it
1546 // won't underflow in the first iteration.
1547 int64_t Imm;
1548 if (checkForImmediate(*InitVal, Imm))
1549 return (EndVal->getImm() == Imm);
1550
1551 Register Reg = InitVal->getReg();
1552
1553 // We don't know the value of a physical register.
1554 if (!Reg.isVirtual())
1555 return true;
1556
1557 MachineInstr *Def = MRI->getVRegDef(Reg);
1558 if (!Def)
1559 return true;
1560
1561 // If the initial value is a Phi or copy and the operands may not underflow,
1562 // then the definition cannot be underflow either.
1563 if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1564 L, LoopFeederPhi))
1565 return false;
1566 if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1567 EndVal, Def->getParent(),
1568 L, LoopFeederPhi))
1569 return false;
1570
1571 // Iterate over the uses of the initial value. If the initial value is used
1572 // in a compare, then we assume this is a range check that ensures the loop
1573 // doesn't underflow. This is not an exact test and should be improved.
1575 E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1576 MachineInstr *MI = &*I;
1577 Register CmpReg1, CmpReg2;
1578 int64_t CmpMask = 0, CmpValue = 0;
1579
1580 if (!TII->analyzeCompare(*MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
1581 continue;
1582
1583 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1585 if (TII->analyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
1586 continue;
1587
1588 Comparison::Kind Cmp =
1589 getComparisonKind(MI->getOpcode(), nullptr, nullptr, 0);
1590 if (Cmp == 0)
1591 continue;
1592 if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1593 Cmp = Comparison::getNegatedComparison(Cmp);
1594 if (CmpReg2 != 0 && CmpReg2 == Reg)
1595 Cmp = Comparison::getSwappedComparison(Cmp);
1596
1597 // Signed underflow is undefined.
1598 if (Comparison::isSigned(Cmp))
1599 return false;
1600
1601 // Check if there is a comparison of the initial value. If the initial value
1602 // is greater than or not equal to another value, then assume this is a
1603 // range check.
1604 if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1605 return false;
1606 }
1607
1608 // OK - this is a hack that needs to be improved. We really need to analyze
1609 // the instructions performed on the initial value. This works on the simplest
1610 // cases only.
1611 if (!Def->isCopy() && !Def->isPHI())
1612 return false;
1613
1614 return true;
1615}
1616
1617bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1618 int64_t &Val) const {
1619 if (MO.isImm()) {
1620 Val = MO.getImm();
1621 return true;
1622 }
1623 if (!MO.isReg())
1624 return false;
1625
1626 // MO is a register. Check whether it is defined as an immediate value,
1627 // and if so, get the value of it in TV. That value will then need to be
1628 // processed to handle potential subregisters in MO.
1629 int64_t TV;
1630
1631 Register R = MO.getReg();
1632 if (!R.isVirtual())
1633 return false;
1634 MachineInstr *DI = MRI->getVRegDef(R);
1635 unsigned DOpc = DI->getOpcode();
1636 switch (DOpc) {
1637 case TargetOpcode::COPY:
1638 case Hexagon::A2_tfrsi:
1639 case Hexagon::A2_tfrpi:
1640 case Hexagon::CONST32:
1641 case Hexagon::CONST64:
1642 // Call recursively to avoid an extra check whether operand(1) is
1643 // indeed an immediate (it could be a global address, for example),
1644 // plus we can handle COPY at the same time.
1645 if (!checkForImmediate(DI->getOperand(1), TV))
1646 return false;
1647 break;
1648 case Hexagon::A2_combineii:
1649 case Hexagon::A4_combineir:
1650 case Hexagon::A4_combineii:
1651 case Hexagon::A4_combineri:
1652 case Hexagon::A2_combinew: {
1653 const MachineOperand &S1 = DI->getOperand(1);
1654 const MachineOperand &S2 = DI->getOperand(2);
1655 int64_t V1, V2;
1656 if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1657 return false;
1658 TV = V2 | (static_cast<uint64_t>(V1) << 32);
1659 break;
1660 }
1661 case TargetOpcode::REG_SEQUENCE: {
1662 const MachineOperand &S1 = DI->getOperand(1);
1663 const MachineOperand &S3 = DI->getOperand(3);
1664 int64_t V1, V3;
1665 if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1666 return false;
1667 unsigned Sub2 = DI->getOperand(2).getImm();
1668 unsigned Sub4 = DI->getOperand(4).getImm();
1669 if (Sub2 == Hexagon::isub_lo && Sub4 == Hexagon::isub_hi)
1670 TV = V1 | (V3 << 32);
1671 else if (Sub2 == Hexagon::isub_hi && Sub4 == Hexagon::isub_lo)
1672 TV = V3 | (V1 << 32);
1673 else
1674 llvm_unreachable("Unexpected form of REG_SEQUENCE");
1675 break;
1676 }
1677
1678 default:
1679 return false;
1680 }
1681
1682 // By now, we should have successfully obtained the immediate value defining
1683 // the register referenced in MO. Handle a potential use of a subregister.
1684 switch (MO.getSubReg()) {
1685 case Hexagon::isub_lo:
1686 Val = TV & 0xFFFFFFFFULL;
1687 break;
1688 case Hexagon::isub_hi:
1689 Val = (TV >> 32) & 0xFFFFFFFFULL;
1690 break;
1691 default:
1692 Val = TV;
1693 break;
1694 }
1695 return true;
1696}
1697
1698void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1699 if (MO.isImm()) {
1700 MO.setImm(Val);
1701 return;
1702 }
1703
1704 assert(MO.isReg());
1705 Register R = MO.getReg();
1706 MachineInstr *DI = MRI->getVRegDef(R);
1707
1708 const TargetRegisterClass *RC = MRI->getRegClass(R);
1710 MachineBasicBlock &B = *DI->getParent();
1711 DebugLoc DL = DI->getDebugLoc();
1712 BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
1713 MO.setReg(NewR);
1714}
1715
1716bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1717 MachineBasicBlock *Header = L->getHeader();
1718 MachineBasicBlock *Latch = L->getLoopLatch();
1719 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1720
1721 if (!(Header && Latch && ExitingBlock))
1722 return false;
1723
1724 // These data structures follow the same concept as the corresponding
1725 // ones in findInductionRegister (where some comments are).
1726 using RegisterBump = std::pair<Register, int64_t>;
1727 using RegisterInduction = std::pair<Register, RegisterBump>;
1728 using RegisterInductionSet = std::set<RegisterInduction>;
1729
1730 // Register candidates for induction variables, with their associated bumps.
1731 RegisterInductionSet IndRegs;
1732
1733 // Look for induction patterns:
1734 // %1 = PHI ..., [ latch, %2 ]
1735 // %2 = ADD %1, imm
1736 using instr_iterator = MachineBasicBlock::instr_iterator;
1737
1738 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1739 I != E && I->isPHI(); ++I) {
1740 MachineInstr *Phi = &*I;
1741
1742 // Have a PHI instruction.
1743 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1744 if (Phi->getOperand(i+1).getMBB() != Latch)
1745 continue;
1746
1747 Register PhiReg = Phi->getOperand(i).getReg();
1748 MachineInstr *DI = MRI->getVRegDef(PhiReg);
1749
1750 if (DI->getDesc().isAdd()) {
1751 // If the register operand to the add/sub is the PHI we are looking
1752 // at, this meets the induction pattern.
1753 Register IndReg = DI->getOperand(1).getReg();
1754 MachineOperand &Opnd2 = DI->getOperand(2);
1755 int64_t V;
1756 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
1757 Register UpdReg = DI->getOperand(0).getReg();
1758 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
1759 }
1760 } else {
1761 Register IndReg;
1762 int64_t V;
1763 if (tryExtractPostIncInduction(DI, Phi, PhiReg, IndReg, V))
1764 IndRegs.insert(std::make_pair(PhiReg, std::make_pair(IndReg, V)));
1765 }
1766 } // for (i)
1767 } // for (instr)
1768
1769 if (IndRegs.empty())
1770 return false;
1771
1772 MachineBasicBlock *TB = nullptr, *FB = nullptr;
1774 // analyzeBranch returns true if it fails to analyze branch.
1775 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
1776 if (NotAnalyzed || Cond.empty())
1777 return false;
1778
1779 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1780 MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
1782 bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
1783 if (NotAnalyzed)
1784 return false;
1785
1786 // Since latch is not the exiting block, the latch branch should be an
1787 // unconditional branch to the loop header.
1788 if (TB == Latch)
1789 TB = (LTB == Header) ? LTB : LFB;
1790 else
1791 FB = (LTB == Header) ? LTB : LFB;
1792 }
1793 if (TB != Header) {
1794 if (FB != Header) {
1795 // The latch/exit block does not go back to the header.
1796 return false;
1797 }
1798 // FB is the header (i.e., uncond. jump to branch header)
1799 // In this case, the LoopBody -> TB should not be a back edge otherwise
1800 // it could result in an infinite loop after conversion to hw_loop.
1801 // This case can happen when the Latch has two jumps like this:
1802 // Jmp_c OuterLoopHeader <-- TB
1803 // Jmp InnerLoopHeader <-- FB
1804 if (MDT->dominates(TB, FB))
1805 return false;
1806 }
1807
1808 // Expecting a predicate register as a condition. It won't be a hardware
1809 // predicate register at this point yet, just a vreg.
1810 // HexagonInstrInfo::analyzeBranch for negated branches inserts imm(0)
1811 // into Cond, followed by the predicate register. For non-negated branches
1812 // it's just the register.
1813 unsigned CSz = Cond.size();
1814 if (CSz != 1 && CSz != 2)
1815 return false;
1816
1817 if (!Cond[CSz-1].isReg())
1818 return false;
1819
1820 Register P = Cond[CSz - 1].getReg();
1821 MachineInstr *PredDef = MRI->getVRegDef(P);
1822
1823 if (!PredDef->isCompare())
1824 return false;
1825
1826 SmallSet<Register,2> CmpRegs;
1827 MachineOperand *CmpImmOp = nullptr;
1828
1829 // Go over all operands to the compare and look for immediate and register
1830 // operands. Assume that if the compare has a single register use and a
1831 // single immediate operand, then the register is being compared with the
1832 // immediate value.
1833 for (MachineOperand &MO : PredDef->operands()) {
1834 if (MO.isReg()) {
1835 // Skip all implicit references. In one case there was:
1836 // %140 = FCMPUGT32_rr %138, %139, implicit %usr
1837 if (MO.isImplicit())
1838 continue;
1839 if (MO.isUse()) {
1840 if (!isImmediate(MO)) {
1841 CmpRegs.insert(MO.getReg());
1842 continue;
1843 }
1844 // Consider the register to be the "immediate" operand.
1845 if (CmpImmOp)
1846 return false;
1847 CmpImmOp = &MO;
1848 }
1849 } else if (MO.isImm()) {
1850 if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
1851 return false;
1852 CmpImmOp = &MO;
1853 }
1854 }
1855
1856 if (CmpRegs.empty())
1857 return false;
1858
1859 // Check if the compared register follows the order we want. Fix if needed.
1860 for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1861 I != E; ++I) {
1862 // This is a success. If the register used in the comparison is one that
1863 // we have identified as a bumped (updated) induction register, there is
1864 // nothing to do.
1865 if (CmpRegs.count(I->first))
1866 return true;
1867
1868 // Otherwise, if the register being compared comes out of a PHI node,
1869 // and has been recognized as following the induction pattern, and is
1870 // compared against an immediate, we can fix it.
1871 const RegisterBump &RB = I->second;
1872 if (CmpRegs.count(RB.first)) {
1873 if (!CmpImmOp) {
1874 // If both operands to the compare instruction are registers, see if
1875 // it can be changed to use induction register as one of the operands.
1876 MachineInstr *IndI = nullptr;
1877 MachineInstr *nonIndI = nullptr;
1878 MachineOperand *IndMO = nullptr;
1879 MachineOperand *nonIndMO = nullptr;
1880
1881 for (unsigned i = 1, n = PredDef->getNumOperands(); i < n; ++i) {
1882 MachineOperand &MO = PredDef->getOperand(i);
1883 if (MO.isReg() && MO.getReg() == RB.first) {
1884 LLVM_DEBUG(dbgs() << "\n DefMI(" << i
1885 << ") = " << *(MRI->getVRegDef(I->first)));
1886 if (IndI)
1887 return false;
1888
1889 IndI = MRI->getVRegDef(I->first);
1890 IndMO = &MO;
1891 } else if (MO.isReg()) {
1892 LLVM_DEBUG(dbgs() << "\n DefMI(" << i
1893 << ") = " << *(MRI->getVRegDef(MO.getReg())));
1894 if (nonIndI)
1895 return false;
1896
1897 nonIndI = MRI->getVRegDef(MO.getReg());
1898 nonIndMO = &MO;
1899 }
1900 }
1901 if (IndI && nonIndI &&
1902 nonIndI->getOpcode() == Hexagon::A2_addi &&
1903 nonIndI->getOperand(2).isImm() &&
1904 nonIndI->getOperand(2).getImm() == - RB.second) {
1905 bool Order = orderBumpCompare(IndI, PredDef);
1906 if (Order) {
1907 IndMO->setReg(I->first);
1908 nonIndMO->setReg(nonIndI->getOperand(1).getReg());
1909 return true;
1910 }
1911 }
1912 return false;
1913 }
1914
1915 // It is not valid to do this transformation on an unsigned comparison
1916 // because it may underflow.
1917 Comparison::Kind Cmp =
1918 getComparisonKind(PredDef->getOpcode(), nullptr, nullptr, 0);
1919 if (!Cmp || Comparison::isUnsigned(Cmp))
1920 return false;
1921
1922 // If the register is being compared against an immediate, try changing
1923 // the compare instruction to use induction register and adjust the
1924 // immediate operand.
1925 int64_t CmpImm = getImmediate(*CmpImmOp);
1926 int64_t V = RB.second;
1927 // Handle Overflow (64-bit).
1928 if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1929 ((V < 0) && (CmpImm < INT64_MIN - V)))
1930 return false;
1931 CmpImm += V;
1932 // Most comparisons of register against an immediate value allow
1933 // the immediate to be constant-extended. There are some exceptions
1934 // though. Make sure the new combination will work.
1935 if (CmpImmOp->isImm() && !TII->isExtendable(*PredDef) &&
1936 !TII->isValidOffset(PredDef->getOpcode(), CmpImm, false))
1937 return false;
1938
1939 // Make sure that the compare happens after the bump. Otherwise,
1940 // after the fixup, the compare would use a yet-undefined register.
1941 MachineInstr *BumpI = MRI->getVRegDef(I->first);
1942 bool Order = orderBumpCompare(BumpI, PredDef);
1943 if (!Order)
1944 return false;
1945
1946 // Finally, fix the compare instruction.
1947 setImmediate(*CmpImmOp, CmpImm);
1948 for (MachineOperand &MO : PredDef->operands()) {
1949 if (MO.isReg() && MO.getReg() == RB.first) {
1950 MO.setReg(I->first);
1951 return true;
1952 }
1953 }
1954 }
1955 }
1956
1957 return false;
1958}
1959
1960/// createPreheaderForLoop - Create a preheader for a given loop.
1961MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1962 MachineLoop *L) {
1963 if (MachineBasicBlock *TmpPH =
1964 MLI->findLoopPreheader(L, CLOpts->hwloop_spec_preheader))
1965 return TmpPH;
1966 if (!CLOpts->hwloop_preheader)
1967 return nullptr;
1968
1969 MachineBasicBlock *Header = L->getHeader();
1970 MachineBasicBlock *Latch = L->getLoopLatch();
1971 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1972 MachineFunction *MF = Header->getParent();
1973 DebugLoc DL;
1974
1975#ifndef NDEBUG
1976 if (!CLOpts->hwloop_phfn.empty() && CLOpts->hwloop_phfn != MF->getName())
1977 return nullptr;
1978#endif
1979
1980 if (!Latch || !ExitingBlock || Header->hasAddressTaken())
1981 return nullptr;
1982
1983 using instr_iterator = MachineBasicBlock::instr_iterator;
1984
1985 // Verify that all existing predecessors have analyzable branches
1986 // (or no branches at all).
1987 using MBBVector = std::vector<MachineBasicBlock *>;
1988
1989 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1991 MachineBasicBlock *TB = nullptr, *FB = nullptr;
1992
1993 if (TII->analyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
1994 return nullptr;
1995
1996 for (MachineBasicBlock *PB : Preds) {
1997 bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp1, false);
1998 if (NotAnalyzed)
1999 return nullptr;
2000 }
2001
2002 MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
2003 MF->insert(Header->getIterator(), NewPH);
2004
2005 if (Header->pred_size() > 2) {
2006 // Ensure that the header has only two predecessors: the preheader and
2007 // the loop latch. Any additional predecessors of the header should
2008 // join at the newly created preheader. Inspect all PHI nodes from the
2009 // header and create appropriate corresponding PHI nodes in the preheader.
2010
2011 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
2012 I != E && I->isPHI(); ++I) {
2013 MachineInstr *PN = &*I;
2014
2015 const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
2016 MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
2017 NewPH->insert(NewPH->end(), NewPN);
2018
2019 Register PR = PN->getOperand(0).getReg();
2020 const TargetRegisterClass *RC = MRI->getRegClass(PR);
2021 Register NewPR = MRI->createVirtualRegister(RC);
2022 NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
2023
2024 // Copy all non-latch operands of a header's PHI node to the newly
2025 // created PHI node in the preheader.
2026 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
2027 Register PredR = PN->getOperand(i).getReg();
2028 unsigned PredRSub = PN->getOperand(i).getSubReg();
2029 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
2030 if (PredB == Latch)
2031 continue;
2032
2033 MachineOperand MO = MachineOperand::CreateReg(PredR, false);
2034 MO.setSubReg(PredRSub);
2035 NewPN->addOperand(MO);
2037 }
2038
2039 // Remove copied operands from the old PHI node and add the value
2040 // coming from the preheader's PHI.
2041 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
2042 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
2043 if (PredB != Latch) {
2044 PN->removeOperand(i+1);
2045 PN->removeOperand(i);
2046 }
2047 }
2048 PN->addOperand(MachineOperand::CreateReg(NewPR, false));
2050 }
2051 } else {
2052 assert(Header->pred_size() == 2);
2053
2054 // The header has only two predecessors, but the non-latch predecessor
2055 // is not a preheader (e.g. it has other successors, etc.)
2056 // In such a case we don't need any extra PHI nodes in the new preheader,
2057 // all we need is to adjust existing PHIs in the header to now refer to
2058 // the new preheader.
2059 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
2060 I != E && I->isPHI(); ++I) {
2061 MachineInstr *PN = &*I;
2062 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
2063 MachineOperand &MO = PN->getOperand(i+1);
2064 if (MO.getMBB() != Latch)
2065 MO.setMBB(NewPH);
2066 }
2067 }
2068 }
2069
2070 // "Reroute" the CFG edges to link in the new preheader.
2071 // If any of the predecessors falls through to the header, insert a branch
2072 // to the new preheader in that place.
2075
2076 TB = FB = nullptr;
2077
2078 for (MachineBasicBlock *PB : Preds) {
2079 if (PB != Latch) {
2080 Tmp2.clear();
2081 bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp2, false);
2082 (void)NotAnalyzed; // suppress compiler warning
2083 assert (!NotAnalyzed && "Should be analyzable!");
2084 if (TB != Header && (Tmp2.empty() || FB != Header))
2085 TII->insertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
2086 PB->ReplaceUsesOfBlockWith(Header, NewPH);
2087 }
2088 }
2089
2090 // It can happen that the latch block will fall through into the header.
2091 // Insert an unconditional branch to the header.
2092 TB = FB = nullptr;
2093 bool LatchNotAnalyzed = TII->analyzeBranch(*Latch, TB, FB, Tmp2, false);
2094 (void)LatchNotAnalyzed; // suppress compiler warning
2095 assert (!LatchNotAnalyzed && "Should be analyzable!");
2096 if (!TB && !FB)
2097 TII->insertBranch(*Latch, Header, nullptr, EmptyCond, DL);
2098
2099 // Finally, the branch from the preheader to the header.
2100 TII->insertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
2101 NewPH->addSuccessor(Header);
2102
2103 MachineLoop *ParentLoop = L->getParentLoop();
2104 if (ParentLoop)
2105 ParentLoop->addBasicBlockToLoop(NewPH, *MLI);
2106
2107 // Update the dominator information with the new preheader.
2108 if (MDT) {
2109 if (MachineDomTreeNode *HN = MDT->getNode(Header)) {
2110 if (MachineDomTreeNode *DHN = HN->getIDom()) {
2111 MDT->addNewBlock(NewPH, DHN->getBlock());
2112 MDT->changeImmediateDominator(Header, NewPH);
2113 }
2114 }
2115 }
2116
2117 return NewPH;
2118}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
constexpr LLT S1
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isSigned(unsigned Opcode)
#define DEBUG_TYPE
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
#define P(N)
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineBasicBlock *, 4 > MBBVector
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &CmpMask, int64_t &CmpValue) const override
analyzeCompare - For a comparison instruction, return the source registers in SrcReg and SrcReg2,...
AnalysisUsage & addRequired()
DomTreeNodeBase * getIDom() const
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const HexagonInstrInfo * getInstrInfo() const override
const HexagonRegisterInfo * getRegisterInfo() const override
const HexagonOptions & getCLOpts() const
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool isAdd() const
Return true if the instruction is an add instruction.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
Instructions::iterator instr_iterator
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
mop_range operands()
LLVM_ABI void insert(mop_iterator InsertBefore, ArrayRef< MachineOperand > Ops)
Inserts Ops BEFORE It. Can untie/retie tied operands.
LLVM_ABI unsigned findTiedOperandIdx(unsigned OpIdx) const
Given the index of a tied register operand, find the operand it is tied to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setMBB(MachineBasicBlock *MBB)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
defusechain_instr_iterator< true, false, true, true > use_instr_nodbg_iterator
use_instr_nodbg_iterator/use_instr_nodbg_begin/use_instr_nodbg_end - Walk all uses of the specified r...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
static use_nodbg_iterator use_nodbg_end()
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
defusechain_iterator< true, false, true, true, false > use_nodbg_iterator
use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the specified register,...
iterator_range< use_iterator > use_operands(Register Reg) const
static use_instr_nodbg_iterator use_instr_nodbg_end()
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
self_iterator getIterator()
Definition ilist_node.h:123
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ TB
TB - TwoByte - Set if this instruction has a two byte opcode, which starts with a 0x0F byte before th...
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
unsigned getLoopTripCount(const Loop *L, ScalarEvolution &SE, unsigned LoopAwareTripCount)
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
RegState
Flags to represent properties of register accesses.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createHexagonHardwareLoops()
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define MORE()
Definition regcomp.c:247