1 //===----- HexagonNewValueJump.cpp - Hexagon Backend New Value Jump -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements NewValueJump pass in Hexagon.
11 // Ideally, we should merge this as a Peephole pass prior to register
12 // allocation, but because we have a spill in between the feeder and new value
13 // jump instructions, we are forced to write after register allocation.
14 // Having said that, we should re-attempt to pull this earlier at some point
17 // The basic approach looks for sequence of predicated jump, compare instruciton
18 // that genereates the predicate and, the feeder to the predicate. Once it finds
19 // all, it collapses compare and jump instruction into a new valu jump
23 //===----------------------------------------------------------------------===//
25 #include "HexagonInstrInfo.h"
26 #include "HexagonMachineFunctionInfo.h"
27 #include "HexagonRegisterInfo.h"
28 #include "HexagonSubtarget.h"
29 #include "HexagonTargetMachine.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/LiveVariables.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
37 #include "llvm/PassSupport.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
46 #define DEBUG_TYPE "hexagon-nvj"
48 STATISTIC(NumNVJGenerated, "Number of New Value Jump Instructions created");
51 DbgNVJCount("nvj-count", cl::init(-1), cl::Hidden, cl::desc(
52 "Maximum number of predicated jumps to be converted to New Value Jump"));
54 static cl::opt<bool> DisableNewValueJumps("disable-nvjump", cl::Hidden,
55 cl::ZeroOrMore, cl::init(false),
56 cl::desc("Disable New Value Jumps"));
59 FunctionPass *createHexagonNewValueJump();
60 void initializeHexagonNewValueJumpPass(PassRegistry&);
65 struct HexagonNewValueJump : public MachineFunctionPass {
66 const HexagonInstrInfo *QII;
67 const HexagonRegisterInfo *QRI;
72 HexagonNewValueJump() : MachineFunctionPass(ID) {}
74 void getAnalysisUsage(AnalysisUsage &AU) const override {
75 AU.addRequired<MachineBranchProbabilityInfo>();
76 MachineFunctionPass::getAnalysisUsage(AU);
79 StringRef getPassName() const override { return "Hexagon NewValueJump"; }
81 bool runOnMachineFunction(MachineFunction &Fn) override;
82 MachineFunctionProperties getRequiredProperties() const override {
83 return MachineFunctionProperties().set(
84 MachineFunctionProperties::Property::NoVRegs);
88 /// \brief A handle to the branch probability pass.
89 const MachineBranchProbabilityInfo *MBPI;
91 bool isNewValueJumpCandidate(const MachineInstr &MI) const;
94 } // end of anonymous namespace
96 char HexagonNewValueJump::ID = 0;
98 INITIALIZE_PASS_BEGIN(HexagonNewValueJump, "hexagon-nvj",
99 "Hexagon NewValueJump", false, false)
100 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
101 INITIALIZE_PASS_END(HexagonNewValueJump, "hexagon-nvj",
102 "Hexagon NewValueJump", false, false)
105 // We have identified this II could be feeder to NVJ,
106 // verify that it can be.
107 static bool canBeFeederToNewValueJump(const HexagonInstrInfo *QII,
108 const TargetRegisterInfo *TRI,
109 MachineBasicBlock::iterator II,
110 MachineBasicBlock::iterator end,
111 MachineBasicBlock::iterator skip,
112 MachineFunction &MF) {
114 // Predicated instruction can not be feeder to NVJ.
115 if (QII->isPredicated(*II))
118 // Bail out if feederReg is a paired register (double regs in
119 // our case). One would think that we can check to see if a given
120 // register cmpReg1 or cmpReg2 is a sub register of feederReg
121 // using -- if (QRI->isSubRegister(feederReg, cmpReg1) logic
122 // before the callsite of this function
123 // But we can not as it comes in the following fashion.
124 // %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
125 // %R0<def> = KILL %R0, %D0<imp-use,kill>
126 // %P0<def> = CMPEQri %R0<kill>, 0
127 // Hence, we need to check if it's a KILL instruction.
128 if (II->getOpcode() == TargetOpcode::KILL)
131 if (II->isImplicitDef())
134 // Make sure there there is no 'def' or 'use' of any of the uses of
135 // feeder insn between it's definition, this MI and jump, jmpInst
136 // skipping compare, cmpInst.
137 // Here's the example.
138 // r21=memub(r22+r24<<#0)
139 // p0 = cmp.eq(r21, #0)
140 // r4=memub(r3+r21<<#0)
141 // if (p0.new) jump:t .LBB29_45
142 // Without this check, it will be converted into
143 // r4=memub(r3+r21<<#0)
144 // r21=memub(r22+r24<<#0)
145 // p0 = cmp.eq(r21, #0)
146 // if (p0.new) jump:t .LBB29_45
147 // and result WAR hazards if converted to New Value Jump.
149 for (unsigned i = 0; i < II->getNumOperands(); ++i) {
150 if (II->getOperand(i).isReg() &&
151 (II->getOperand(i).isUse() || II->getOperand(i).isDef())) {
152 MachineBasicBlock::iterator localII = II;
154 unsigned Reg = II->getOperand(i).getReg();
155 for (MachineBasicBlock::iterator localBegin = localII;
156 localBegin != end; ++localBegin) {
157 if (localBegin == skip ) continue;
158 // Check for Subregisters too.
159 if (localBegin->modifiesRegister(Reg, TRI) ||
160 localBegin->readsRegister(Reg, TRI))
168 // These are the common checks that need to performed
170 // 1. compare instruction can be moved before jump.
171 // 2. feeder to the compare instruction can be moved before jump.
172 static bool commonChecksToProhibitNewValueJump(bool afterRA,
173 MachineBasicBlock::iterator MII) {
175 // If store in path, bail out.
176 if (MII->getDesc().mayStore())
179 // if call in path, bail out.
183 // if NVJ is running prior to RA, do the following checks.
185 // The following Target Opcode instructions are spurious
186 // to new value jump. If they are in the path, bail out.
187 // KILL sets kill flag on the opcode. It also sets up a
188 // single register, out of pair.
189 // %D0<def> = S2_lsr_r_p %D0<kill>, %R2<kill>
190 // %R0<def> = KILL %R0, %D0<imp-use,kill>
191 // %P0<def> = C2_cmpeqi %R0<kill>, 0
192 // PHI can be anything after RA.
193 // COPY can remateriaze things in between feeder, compare and nvj.
194 if (MII->getOpcode() == TargetOpcode::KILL ||
195 MII->getOpcode() == TargetOpcode::PHI ||
196 MII->getOpcode() == TargetOpcode::COPY)
199 // The following pseudo Hexagon instructions sets "use" and "def"
200 // of registers by individual passes in the backend. At this time,
201 // we don't know the scope of usage and definitions of these
203 if (MII->getOpcode() == Hexagon::LDriw_pred ||
204 MII->getOpcode() == Hexagon::STriw_pred)
211 static bool canCompareBeNewValueJump(const HexagonInstrInfo *QII,
212 const TargetRegisterInfo *TRI,
213 MachineBasicBlock::iterator II,
217 MachineBasicBlock::iterator end,
218 MachineFunction &MF) {
220 MachineInstr &MI = *II;
222 // If the second operand of the compare is an imm, make sure it's in the
223 // range specified by the arch.
225 int64_t v = MI.getOperand(2).getImm();
228 switch (MI.getOpcode()) {
229 case Hexagon::C2_cmpeqi:
230 case Hexagon::C2_cmpgti:
231 Valid = (isUInt<5>(v) || v == -1);
233 case Hexagon::C2_cmpgtui:
234 Valid = isUInt<5>(v);
236 case Hexagon::S2_tstbit_i:
237 case Hexagon::S4_ntstbit_i:
246 unsigned cmpReg1, cmpOp2 = 0; // cmpOp2 assignment silences compiler warning.
247 cmpReg1 = MI.getOperand(1).getReg();
250 cmpOp2 = MI.getOperand(2).getReg();
252 // If the same register appears as both operands, we cannot generate a new
253 // value compare. Only one operand may use the .new suffix.
254 if (cmpReg1 == cmpOp2)
257 // Make sure that that second register is not from COPY
258 // At machine code level, we don't need this, but if we decide
259 // to move new value jump prior to RA, we would be needing this.
260 MachineRegisterInfo &MRI = MF.getRegInfo();
261 if (secondReg && !TargetRegisterInfo::isPhysicalRegister(cmpOp2)) {
262 MachineInstr *def = MRI.getVRegDef(cmpOp2);
263 if (def->getOpcode() == TargetOpcode::COPY)
268 // Walk the instructions after the compare (predicate def) to the jump,
269 // and satisfy the following conditions.
271 for (MachineBasicBlock::iterator localII = II; localII != end;
273 if (localII->isDebugValue())
277 // If "common" checks fail, bail out.
278 if (!commonChecksToProhibitNewValueJump(optLocation, localII))
282 // If there is a def or use of predicate (result of compare), bail out.
283 if (localII->modifiesRegister(pReg, TRI) ||
284 localII->readsRegister(pReg, TRI))
288 // If there is a def of any of the use of the compare (operands of compare),
291 // p0 = cmp.eq(r2, r0)
293 // if (p0.new) jump:t .LBB28_3
294 if (localII->modifiesRegister(cmpReg1, TRI) ||
295 (secondReg && localII->modifiesRegister(cmpOp2, TRI)))
302 // Given a compare operator, return a matching New Value Jump compare operator.
303 // Make sure that MI here is included in isNewValueJumpCandidate.
304 static unsigned getNewValueJumpOpcode(MachineInstr *MI, int reg,
305 bool secondRegNewified,
306 MachineBasicBlock *jmpTarget,
307 const MachineBranchProbabilityInfo
310 MachineBasicBlock *Src = MI->getParent();
311 const BranchProbability Prediction =
312 MBPI->getEdgeProbability(Src, jmpTarget);
314 if (Prediction >= BranchProbability(1,2))
317 switch (MI->getOpcode()) {
318 case Hexagon::C2_cmpeq:
319 return taken ? Hexagon::J4_cmpeq_t_jumpnv_t
320 : Hexagon::J4_cmpeq_t_jumpnv_nt;
322 case Hexagon::C2_cmpeqi: {
324 return taken ? Hexagon::J4_cmpeqi_t_jumpnv_t
325 : Hexagon::J4_cmpeqi_t_jumpnv_nt;
327 return taken ? Hexagon::J4_cmpeqn1_t_jumpnv_t
328 : Hexagon::J4_cmpeqn1_t_jumpnv_nt;
331 case Hexagon::C2_cmpgt: {
332 if (secondRegNewified)
333 return taken ? Hexagon::J4_cmplt_t_jumpnv_t
334 : Hexagon::J4_cmplt_t_jumpnv_nt;
336 return taken ? Hexagon::J4_cmpgt_t_jumpnv_t
337 : Hexagon::J4_cmpgt_t_jumpnv_nt;
340 case Hexagon::C2_cmpgti: {
342 return taken ? Hexagon::J4_cmpgti_t_jumpnv_t
343 : Hexagon::J4_cmpgti_t_jumpnv_nt;
345 return taken ? Hexagon::J4_cmpgtn1_t_jumpnv_t
346 : Hexagon::J4_cmpgtn1_t_jumpnv_nt;
349 case Hexagon::C2_cmpgtu: {
350 if (secondRegNewified)
351 return taken ? Hexagon::J4_cmpltu_t_jumpnv_t
352 : Hexagon::J4_cmpltu_t_jumpnv_nt;
354 return taken ? Hexagon::J4_cmpgtu_t_jumpnv_t
355 : Hexagon::J4_cmpgtu_t_jumpnv_nt;
358 case Hexagon::C2_cmpgtui:
359 return taken ? Hexagon::J4_cmpgtui_t_jumpnv_t
360 : Hexagon::J4_cmpgtui_t_jumpnv_nt;
362 case Hexagon::C4_cmpneq:
363 return taken ? Hexagon::J4_cmpeq_f_jumpnv_t
364 : Hexagon::J4_cmpeq_f_jumpnv_nt;
366 case Hexagon::C4_cmplte:
367 if (secondRegNewified)
368 return taken ? Hexagon::J4_cmplt_f_jumpnv_t
369 : Hexagon::J4_cmplt_f_jumpnv_nt;
370 return taken ? Hexagon::J4_cmpgt_f_jumpnv_t
371 : Hexagon::J4_cmpgt_f_jumpnv_nt;
373 case Hexagon::C4_cmplteu:
374 if (secondRegNewified)
375 return taken ? Hexagon::J4_cmpltu_f_jumpnv_t
376 : Hexagon::J4_cmpltu_f_jumpnv_nt;
377 return taken ? Hexagon::J4_cmpgtu_f_jumpnv_t
378 : Hexagon::J4_cmpgtu_f_jumpnv_nt;
381 llvm_unreachable("Could not find matching New Value Jump instruction.");
383 // return *some value* to avoid compiler warning
387 bool HexagonNewValueJump::isNewValueJumpCandidate(
388 const MachineInstr &MI) const {
389 switch (MI.getOpcode()) {
390 case Hexagon::C2_cmpeq:
391 case Hexagon::C2_cmpeqi:
392 case Hexagon::C2_cmpgt:
393 case Hexagon::C2_cmpgti:
394 case Hexagon::C2_cmpgtu:
395 case Hexagon::C2_cmpgtui:
396 case Hexagon::C4_cmpneq:
397 case Hexagon::C4_cmplte:
398 case Hexagon::C4_cmplteu:
407 bool HexagonNewValueJump::runOnMachineFunction(MachineFunction &MF) {
409 DEBUG(dbgs() << "********** Hexagon New Value Jump **********\n"
410 << "********** Function: "
411 << MF.getName() << "\n");
413 if (skipFunction(*MF.getFunction()))
416 // If we move NewValueJump before register allocation we'll need live variable
417 // analysis here too.
419 QII = static_cast<const HexagonInstrInfo *>(MF.getSubtarget().getInstrInfo());
420 QRI = static_cast<const HexagonRegisterInfo *>(
421 MF.getSubtarget().getRegisterInfo());
422 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
424 if (DisableNewValueJumps) {
428 int nvjCount = DbgNVJCount;
429 int nvjGenerated = 0;
431 // Loop through all the bb's of the function
432 for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
433 MBBb != MBBe; ++MBBb) {
434 MachineBasicBlock *MBB = &*MBBb;
436 DEBUG(dbgs() << "** dumping bb ** "
437 << MBB->getNumber() << "\n");
439 DEBUG(dbgs() << "\n" << "********** dumping instr bottom up **********\n");
440 bool foundJump = false;
441 bool foundCompare = false;
442 bool invertPredicate = false;
443 unsigned predReg = 0; // predicate reg of the jump.
444 unsigned cmpReg1 = 0;
446 MachineBasicBlock::iterator jmpPos;
447 MachineBasicBlock::iterator cmpPos;
448 MachineInstr *cmpInstr = nullptr, *jmpInstr = nullptr;
449 MachineBasicBlock *jmpTarget = nullptr;
450 bool afterRA = false;
451 bool isSecondOpReg = false;
452 bool isSecondOpNewified = false;
453 // Traverse the basic block - bottom up
454 for (MachineBasicBlock::iterator MII = MBB->end(), E = MBB->begin();
456 MachineInstr &MI = *--MII;
457 if (MI.isDebugValue()) {
461 if ((nvjCount == 0) || (nvjCount > -1 && nvjCount <= nvjGenerated))
464 DEBUG(dbgs() << "Instr: "; MI.dump(); dbgs() << "\n");
466 if (!foundJump && (MI.getOpcode() == Hexagon::J2_jumpt ||
467 MI.getOpcode() == Hexagon::J2_jumptpt ||
468 MI.getOpcode() == Hexagon::J2_jumpf ||
469 MI.getOpcode() == Hexagon::J2_jumpfpt ||
470 MI.getOpcode() == Hexagon::J2_jumptnewpt ||
471 MI.getOpcode() == Hexagon::J2_jumptnew ||
472 MI.getOpcode() == Hexagon::J2_jumpfnewpt ||
473 MI.getOpcode() == Hexagon::J2_jumpfnew)) {
474 // This is where you would insert your compare and
475 // instr that feeds compare
478 predReg = MI.getOperand(0).getReg();
479 afterRA = TargetRegisterInfo::isPhysicalRegister(predReg);
481 // If ifconverter had not messed up with the kill flags of the
482 // operands, the following check on the kill flag would suffice.
483 // if(!jmpInstr->getOperand(0).isKill()) break;
485 // This predicate register is live out out of BB
486 // this would only work if we can actually use Live
487 // variable analysis on phy regs - but LLVM does not
488 // provide LV analysis on phys regs.
489 //if(LVs.isLiveOut(predReg, *MBB)) break;
491 // Get all the successors of this block - which will always
492 // be 2. Check if the predicate register is live-in in those
493 // successor. If yes, we can not delete the predicate -
494 // I am doing this only because LLVM does not provide LiveOut
496 bool predLive = false;
497 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
498 SIE = MBB->succ_end(); SI != SIE; ++SI) {
499 MachineBasicBlock* succMBB = *SI;
500 if (succMBB->isLiveIn(predReg)) {
507 if (!MI.getOperand(1).isMBB())
509 jmpTarget = MI.getOperand(1).getMBB();
511 if (MI.getOpcode() == Hexagon::J2_jumpf ||
512 MI.getOpcode() == Hexagon::J2_jumpfnewpt ||
513 MI.getOpcode() == Hexagon::J2_jumpfnew) {
514 invertPredicate = true;
519 // No new value jump if there is a barrier. A barrier has to be in its
520 // own packet. A barrier has zero operands. We conservatively bail out
521 // here if we see any instruction with zero operands.
522 if (foundJump && MI.getNumOperands() == 0)
525 if (foundJump && !foundCompare && MI.getOperand(0).isReg() &&
526 MI.getOperand(0).getReg() == predReg) {
528 // Not all compares can be new value compare. Arch Spec: 7.6.1.1
529 if (isNewValueJumpCandidate(MI)) {
532 (MI.getDesc().isCompare()) &&
533 "Only compare instruction can be collapsed into New Value Jump");
534 isSecondOpReg = MI.getOperand(2).isReg();
536 if (!canCompareBeNewValueJump(QII, QRI, MII, predReg, isSecondOpReg,
537 afterRA, jmpPos, MF))
544 // We need cmpReg1 and cmpOp2(imm or reg) while building
545 // new value jump instruction.
546 cmpReg1 = MI.getOperand(1).getReg();
549 cmpOp2 = MI.getOperand(2).getReg();
551 cmpOp2 = MI.getOperand(2).getImm();
556 if (foundCompare && foundJump) {
558 // If "common" checks fail, bail out on this BB.
559 if (!commonChecksToProhibitNewValueJump(afterRA, MII))
562 bool foundFeeder = false;
563 MachineBasicBlock::iterator feederPos = MII;
564 if (MI.getOperand(0).isReg() && MI.getOperand(0).isDef() &&
565 (MI.getOperand(0).getReg() == cmpReg1 ||
567 MI.getOperand(0).getReg() == (unsigned)cmpOp2))) {
569 unsigned feederReg = MI.getOperand(0).getReg();
571 // First try to see if we can get the feeder from the first operand
572 // of the compare. If we can not, and if secondOpReg is true
573 // (second operand of the compare is also register), try that one.
574 // TODO: Try to come up with some heuristic to figure out which
575 // feeder would benefit.
577 if (feederReg == cmpReg1) {
578 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF)) {
589 feederReg == (unsigned) cmpOp2)
590 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF))
594 // In case of CMPLT, or CMPLTU, or EQ with the second register
595 // to newify, swap the operands.
596 unsigned COp = cmpInstr->getOpcode();
597 if ((COp == Hexagon::C2_cmpeq || COp == Hexagon::C4_cmpneq) &&
598 (feederReg == (unsigned) cmpOp2)) {
599 unsigned tmp = cmpReg1;
604 // Now we have swapped the operands, all we need to check is,
605 // if the second operand (after swap) is the feeder.
606 // And if it is, make a note.
607 if (feederReg == (unsigned)cmpOp2)
608 isSecondOpNewified = true;
611 // Now that we are moving feeder close the jump,
612 // make sure we are respecting the kill values of
613 // the operands of the feeder.
615 auto TransferKills = [jmpPos,cmpPos] (MachineInstr &MI) {
616 for (MachineOperand &MO : MI.operands()) {
617 if (!MO.isReg() || !MO.isUse())
619 unsigned UseR = MO.getReg();
620 for (auto I = std::next(MI.getIterator()); I != jmpPos; ++I) {
623 for (MachineOperand &Op : I->operands()) {
624 if (!Op.isReg() || !Op.isUse() || !Op.isKill())
626 if (Op.getReg() != UseR)
628 // We found that there is kill of a use register
629 // Set up a kill flag on the register
638 TransferKills(*feederPos);
639 TransferKills(*cmpPos);
640 bool MO1IsKill = cmpPos->killsRegister(cmpReg1, QRI);
641 bool MO2IsKill = isSecondOpReg && cmpPos->killsRegister(cmpOp2, QRI);
643 MBB->splice(jmpPos, MI.getParent(), MI);
644 MBB->splice(jmpPos, MI.getParent(), cmpInstr);
645 DebugLoc dl = MI.getDebugLoc();
648 assert((isNewValueJumpCandidate(*cmpInstr)) &&
649 "This compare is not a New Value Jump candidate.");
650 unsigned opc = getNewValueJumpOpcode(cmpInstr, cmpOp2,
654 opc = QII->getInvertedPredicatedOpcode(opc);
657 NewMI = BuildMI(*MBB, jmpPos, dl,
659 .addReg(cmpReg1, getKillRegState(MO1IsKill))
660 .addReg(cmpOp2, getKillRegState(MO2IsKill))
664 NewMI = BuildMI(*MBB, jmpPos, dl,
666 .addReg(cmpReg1, getKillRegState(MO1IsKill))
670 assert(NewMI && "New Value Jump Instruction Not created!");
672 if (cmpInstr->getOperand(0).isReg() &&
673 cmpInstr->getOperand(0).isKill())
674 cmpInstr->getOperand(0).setIsKill(false);
675 if (cmpInstr->getOperand(1).isReg() &&
676 cmpInstr->getOperand(1).isKill())
677 cmpInstr->getOperand(1).setIsKill(false);
678 cmpInstr->eraseFromParent();
679 jmpInstr->eraseFromParent();
692 FunctionPass *llvm::createHexagonNewValueJump() {
693 return new HexagonNewValueJump();