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 //===----------------------------------------------------------------------===//
24 #include "llvm/PassSupport.h"
26 #include "HexagonInstrInfo.h"
27 #include "HexagonMachineFunctionInfo.h"
28 #include "HexagonRegisterInfo.h"
29 #include "HexagonSubtarget.h"
30 #include "HexagonTargetMachine.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
50 #define DEBUG_TYPE "hexagon-nvj"
52 STATISTIC(NumNVJGenerated, "Number of New Value Jump Instructions created");
55 DbgNVJCount("nvj-count", cl::init(-1), cl::Hidden, cl::desc(
56 "Maximum number of predicated jumps to be converted to New Value Jump"));
58 static cl::opt<bool> DisableNewValueJumps("disable-nvjump", cl::Hidden,
59 cl::ZeroOrMore, cl::init(false),
60 cl::desc("Disable New Value Jumps"));
63 void initializeHexagonNewValueJumpPass(PassRegistry&);
68 struct HexagonNewValueJump : public MachineFunctionPass {
69 const HexagonInstrInfo *QII;
70 const HexagonRegisterInfo *QRI;
75 HexagonNewValueJump() : MachineFunctionPass(ID) {
76 initializeHexagonNewValueJumpPass(*PassRegistry::getPassRegistry());
79 void getAnalysisUsage(AnalysisUsage &AU) const override {
80 AU.addRequired<MachineBranchProbabilityInfo>();
81 MachineFunctionPass::getAnalysisUsage(AU);
84 const char *getPassName() const override {
85 return "Hexagon NewValueJump";
88 bool runOnMachineFunction(MachineFunction &Fn) override;
91 /// \brief A handle to the branch probability pass.
92 const MachineBranchProbabilityInfo *MBPI;
96 } // end of anonymous namespace
98 char HexagonNewValueJump::ID = 0;
100 INITIALIZE_PASS_BEGIN(HexagonNewValueJump, "hexagon-nvj",
101 "Hexagon NewValueJump", false, false)
102 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
103 INITIALIZE_PASS_END(HexagonNewValueJump, "hexagon-nvj",
104 "Hexagon NewValueJump", false, false)
107 // We have identified this II could be feeder to NVJ,
108 // verify that it can be.
109 static bool canBeFeederToNewValueJump(const HexagonInstrInfo *QII,
110 const TargetRegisterInfo *TRI,
111 MachineBasicBlock::iterator II,
112 MachineBasicBlock::iterator end,
113 MachineBasicBlock::iterator skip,
114 MachineFunction &MF) {
116 // Predicated instruction can not be feeder to NVJ.
117 if (QII->isPredicated(II))
120 // Bail out if feederReg is a paired register (double regs in
121 // our case). One would think that we can check to see if a given
122 // register cmpReg1 or cmpReg2 is a sub register of feederReg
123 // using -- if (QRI->isSubRegister(feederReg, cmpReg1) logic
124 // before the callsite of this function
125 // But we can not as it comes in the following fashion.
126 // %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
127 // %R0<def> = KILL %R0, %D0<imp-use,kill>
128 // %P0<def> = CMPEQri %R0<kill>, 0
129 // Hence, we need to check if it's a KILL instruction.
130 if (II->getOpcode() == TargetOpcode::KILL)
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.
180 if (MII->getOpcode() == Hexagon::J2_call)
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> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
190 // %R0<def> = KILL %R0, %D0<imp-use,kill>
191 // %P0<def> = CMPEQri %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();
227 if (!(isUInt<5>(v) ||
228 ((MI->getOpcode() == Hexagon::C2_cmpeqi ||
229 MI->getOpcode() == Hexagon::C2_cmpgti) &&
234 unsigned cmpReg1, cmpOp2 = 0; // cmpOp2 assignment silences compiler warning.
235 cmpReg1 = MI->getOperand(1).getReg();
238 cmpOp2 = MI->getOperand(2).getReg();
240 // Make sure that that second register is not from COPY
241 // At machine code level, we don't need this, but if we decide
242 // to move new value jump prior to RA, we would be needing this.
243 MachineRegisterInfo &MRI = MF.getRegInfo();
244 if (secondReg && !TargetRegisterInfo::isPhysicalRegister(cmpOp2)) {
245 MachineInstr *def = MRI.getVRegDef(cmpOp2);
246 if (def->getOpcode() == TargetOpcode::COPY)
251 // Walk the instructions after the compare (predicate def) to the jump,
252 // and satisfy the following conditions.
254 for (MachineBasicBlock::iterator localII = II; localII != end;
258 // If "common" checks fail, bail out.
259 if (!commonChecksToProhibitNewValueJump(optLocation, localII))
263 // If there is a def or use of predicate (result of compare), bail out.
264 if (localII->modifiesRegister(pReg, TRI) ||
265 localII->readsRegister(pReg, TRI))
269 // If there is a def of any of the use of the compare (operands of compare),
272 // p0 = cmp.eq(r2, r0)
274 // if (p0.new) jump:t .LBB28_3
275 if (localII->modifiesRegister(cmpReg1, TRI) ||
276 (secondReg && localII->modifiesRegister(cmpOp2, TRI)))
282 // Given a compare operator, return a matching New Value Jump
283 // compare operator. Make sure that MI here is included in
284 // HexagonInstrInfo.cpp::isNewValueJumpCandidate
285 static unsigned getNewValueJumpOpcode(MachineInstr *MI, int reg,
286 bool secondRegNewified,
287 MachineBasicBlock *jmpTarget,
288 const MachineBranchProbabilityInfo
291 MachineBasicBlock *Src = MI->getParent();
292 const BranchProbability Prediction =
293 MBPI->getEdgeProbability(Src, jmpTarget);
295 if (Prediction >= BranchProbability(1,2))
298 switch (MI->getOpcode()) {
299 case Hexagon::C2_cmpeq:
300 return taken ? Hexagon::J4_cmpeq_t_jumpnv_t
301 : Hexagon::J4_cmpeq_t_jumpnv_nt;
303 case Hexagon::C2_cmpeqi: {
305 return taken ? Hexagon::J4_cmpeqi_t_jumpnv_t
306 : Hexagon::J4_cmpeqi_t_jumpnv_nt;
308 return taken ? Hexagon::J4_cmpeqn1_t_jumpnv_t
309 : Hexagon::J4_cmpeqn1_t_jumpnv_nt;
312 case Hexagon::C2_cmpgt: {
313 if (secondRegNewified)
314 return taken ? Hexagon::J4_cmplt_t_jumpnv_t
315 : Hexagon::J4_cmplt_t_jumpnv_nt;
317 return taken ? Hexagon::J4_cmpgt_t_jumpnv_t
318 : Hexagon::J4_cmpgt_t_jumpnv_nt;
321 case Hexagon::C2_cmpgti: {
323 return taken ? Hexagon::J4_cmpgti_t_jumpnv_t
324 : Hexagon::J4_cmpgti_t_jumpnv_nt;
326 return taken ? Hexagon::J4_cmpgtn1_t_jumpnv_t
327 : Hexagon::J4_cmpgtn1_t_jumpnv_nt;
330 case Hexagon::C2_cmpgtu: {
331 if (secondRegNewified)
332 return taken ? Hexagon::J4_cmpltu_t_jumpnv_t
333 : Hexagon::J4_cmpltu_t_jumpnv_nt;
335 return taken ? Hexagon::J4_cmpgtu_t_jumpnv_t
336 : Hexagon::J4_cmpgtu_t_jumpnv_nt;
339 case Hexagon::C2_cmpgtui:
340 return taken ? Hexagon::J4_cmpgtui_t_jumpnv_t
341 : Hexagon::J4_cmpgtui_t_jumpnv_nt;
344 llvm_unreachable("Could not find matching New Value Jump instruction.");
346 // return *some value* to avoid compiler warning
350 bool HexagonNewValueJump::runOnMachineFunction(MachineFunction &MF) {
352 DEBUG(dbgs() << "********** Hexagon New Value Jump **********\n"
353 << "********** Function: "
354 << MF.getName() << "\n");
356 // If we move NewValueJump before register allocation we'll need live variable
357 // analysis here too.
359 QII = static_cast<const HexagonInstrInfo *>(MF.getSubtarget().getInstrInfo());
360 QRI = static_cast<const HexagonRegisterInfo *>(
361 MF.getSubtarget().getRegisterInfo());
362 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
364 if (DisableNewValueJumps) {
368 int nvjCount = DbgNVJCount;
369 int nvjGenerated = 0;
371 // Loop through all the bb's of the function
372 for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
373 MBBb != MBBe; ++MBBb) {
374 MachineBasicBlock* MBB = MBBb;
376 DEBUG(dbgs() << "** dumping bb ** "
377 << MBB->getNumber() << "\n");
379 DEBUG(dbgs() << "\n" << "********** dumping instr bottom up **********\n");
380 bool foundJump = false;
381 bool foundCompare = false;
382 bool invertPredicate = false;
383 unsigned predReg = 0; // predicate reg of the jump.
384 unsigned cmpReg1 = 0;
386 bool MO1IsKill = false;
387 bool MO2IsKill = false;
388 MachineBasicBlock::iterator jmpPos;
389 MachineBasicBlock::iterator cmpPos;
390 MachineInstr *cmpInstr = nullptr, *jmpInstr = nullptr;
391 MachineBasicBlock *jmpTarget = nullptr;
392 bool afterRA = false;
393 bool isSecondOpReg = false;
394 bool isSecondOpNewified = false;
395 // Traverse the basic block - bottom up
396 for (MachineBasicBlock::iterator MII = MBB->end(), E = MBB->begin();
398 MachineInstr *MI = --MII;
399 if (MI->isDebugValue()) {
403 if ((nvjCount == 0) || (nvjCount > -1 && nvjCount <= nvjGenerated))
406 DEBUG(dbgs() << "Instr: "; MI->dump(); dbgs() << "\n");
409 (MI->getOpcode() == Hexagon::J2_jumpt ||
410 MI->getOpcode() == Hexagon::J2_jumpf ||
411 MI->getOpcode() == Hexagon::J2_jumptnewpt ||
412 MI->getOpcode() == Hexagon::J2_jumptnew ||
413 MI->getOpcode() == Hexagon::J2_jumpfnewpt ||
414 MI->getOpcode() == Hexagon::J2_jumpfnew)) {
415 // This is where you would insert your compare and
416 // instr that feeds compare
419 predReg = MI->getOperand(0).getReg();
420 afterRA = TargetRegisterInfo::isPhysicalRegister(predReg);
422 // If ifconverter had not messed up with the kill flags of the
423 // operands, the following check on the kill flag would suffice.
424 // if(!jmpInstr->getOperand(0).isKill()) break;
426 // This predicate register is live out out of BB
427 // this would only work if we can actually use Live
428 // variable analysis on phy regs - but LLVM does not
429 // provide LV analysis on phys regs.
430 //if(LVs.isLiveOut(predReg, *MBB)) break;
432 // Get all the successors of this block - which will always
433 // be 2. Check if the predicate register is live in in those
434 // successor. If yes, we can not delete the predicate -
435 // I am doing this only because LLVM does not provide LiveOut
437 bool predLive = false;
438 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
439 SIE = MBB->succ_end(); SI != SIE; ++SI) {
440 MachineBasicBlock* succMBB = *SI;
441 if (succMBB->isLiveIn(predReg)) {
448 jmpTarget = MI->getOperand(1).getMBB();
450 if (MI->getOpcode() == Hexagon::J2_jumpf ||
451 MI->getOpcode() == Hexagon::J2_jumpfnewpt ||
452 MI->getOpcode() == Hexagon::J2_jumpfnew) {
453 invertPredicate = true;
458 // No new value jump if there is a barrier. A barrier has to be in its
459 // own packet. A barrier has zero operands. We conservatively bail out
460 // here if we see any instruction with zero operands.
461 if (foundJump && MI->getNumOperands() == 0)
466 MI->getOperand(0).isReg() &&
467 MI->getOperand(0).getReg() == predReg) {
469 // Not all compares can be new value compare. Arch Spec: 7.6.1.1
470 if (QII->isNewValueJumpCandidate(MI)) {
472 assert((MI->getDesc().isCompare()) &&
473 "Only compare instruction can be collapsed into New Value Jump");
474 isSecondOpReg = MI->getOperand(2).isReg();
476 if (!canCompareBeNewValueJump(QII, QRI, MII, predReg, isSecondOpReg,
477 afterRA, jmpPos, MF))
484 // We need cmpReg1 and cmpOp2(imm or reg) while building
485 // new value jump instruction.
486 cmpReg1 = MI->getOperand(1).getReg();
487 if (MI->getOperand(1).isKill())
491 cmpOp2 = MI->getOperand(2).getReg();
492 if (MI->getOperand(2).isKill())
495 cmpOp2 = MI->getOperand(2).getImm();
500 if (foundCompare && foundJump) {
502 // If "common" checks fail, bail out on this BB.
503 if (!commonChecksToProhibitNewValueJump(afterRA, MII))
506 bool foundFeeder = false;
507 MachineBasicBlock::iterator feederPos = MII;
508 if (MI->getOperand(0).isReg() &&
509 MI->getOperand(0).isDef() &&
510 (MI->getOperand(0).getReg() == cmpReg1 ||
512 MI->getOperand(0).getReg() == (unsigned) cmpOp2))) {
514 unsigned feederReg = MI->getOperand(0).getReg();
516 // First try to see if we can get the feeder from the first operand
517 // of the compare. If we can not, and if secondOpReg is true
518 // (second operand of the compare is also register), try that one.
519 // TODO: Try to come up with some heuristic to figure out which
520 // feeder would benefit.
522 if (feederReg == cmpReg1) {
523 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF)) {
534 feederReg == (unsigned) cmpOp2)
535 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF))
539 // In case of CMPLT, or CMPLTU, or EQ with the second register
540 // to newify, swap the operands.
541 if (cmpInstr->getOpcode() == Hexagon::C2_cmpeq &&
542 feederReg == (unsigned) cmpOp2) {
543 unsigned tmp = cmpReg1;
544 bool tmpIsKill = MO1IsKill;
546 MO1IsKill = MO2IsKill;
548 MO2IsKill = tmpIsKill;
551 // Now we have swapped the operands, all we need to check is,
552 // if the second operand (after swap) is the feeder.
553 // And if it is, make a note.
554 if (feederReg == (unsigned)cmpOp2)
555 isSecondOpNewified = true;
558 // Now that we are moving feeder close the jump,
559 // make sure we are respecting the kill values of
560 // the operands of the feeder.
562 bool updatedIsKill = false;
563 for (unsigned i = 0; i < MI->getNumOperands(); i++) {
564 MachineOperand &MO = MI->getOperand(i);
565 if (MO.isReg() && MO.isUse()) {
566 unsigned feederReg = MO.getReg();
567 for (MachineBasicBlock::iterator localII = feederPos,
568 end = jmpPos; localII != end; localII++) {
569 MachineInstr *localMI = localII;
570 for (unsigned j = 0; j < localMI->getNumOperands(); j++) {
571 MachineOperand &localMO = localMI->getOperand(j);
572 if (localMO.isReg() && localMO.isUse() &&
573 localMO.isKill() && feederReg == localMO.getReg()) {
574 // We found that there is kill of a use register
575 // Set up a kill flag on the register
576 localMO.setIsKill(false);
578 updatedIsKill = true;
582 if (updatedIsKill) break;
585 if (updatedIsKill) break;
588 MBB->splice(jmpPos, MI->getParent(), MI);
589 MBB->splice(jmpPos, MI->getParent(), cmpInstr);
590 DebugLoc dl = MI->getDebugLoc();
593 assert((QII->isNewValueJumpCandidate(cmpInstr)) &&
594 "This compare is not a New Value Jump candidate.");
595 unsigned opc = getNewValueJumpOpcode(cmpInstr, cmpOp2,
599 opc = QII->getInvertedPredicatedOpcode(opc);
602 NewMI = BuildMI(*MBB, jmpPos, dl,
604 .addReg(cmpReg1, getKillRegState(MO1IsKill))
605 .addReg(cmpOp2, getKillRegState(MO2IsKill))
608 else if ((cmpInstr->getOpcode() == Hexagon::C2_cmpeqi ||
609 cmpInstr->getOpcode() == Hexagon::C2_cmpgti) &&
611 // Corresponding new-value compare jump instructions don't have the
612 // operand for -1 immediate value.
613 NewMI = BuildMI(*MBB, jmpPos, dl,
615 .addReg(cmpReg1, getKillRegState(MO1IsKill))
619 NewMI = BuildMI(*MBB, jmpPos, dl,
621 .addReg(cmpReg1, getKillRegState(MO1IsKill))
625 assert(NewMI && "New Value Jump Instruction Not created!");
627 if (cmpInstr->getOperand(0).isReg() &&
628 cmpInstr->getOperand(0).isKill())
629 cmpInstr->getOperand(0).setIsKill(false);
630 if (cmpInstr->getOperand(1).isReg() &&
631 cmpInstr->getOperand(1).isKill())
632 cmpInstr->getOperand(1).setIsKill(false);
633 cmpInstr->eraseFromParent();
634 jmpInstr->eraseFromParent();
647 FunctionPass *llvm::createHexagonNewValueJump() {
648 return new HexagonNewValueJump();