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 FunctionPass *createHexagonNewValueJump();
64 void initializeHexagonNewValueJumpPass(PassRegistry&);
69 struct HexagonNewValueJump : public MachineFunctionPass {
70 const HexagonInstrInfo *QII;
71 const HexagonRegisterInfo *QRI;
76 HexagonNewValueJump() : MachineFunctionPass(ID) {
77 initializeHexagonNewValueJumpPass(*PassRegistry::getPassRegistry());
80 void getAnalysisUsage(AnalysisUsage &AU) const override {
81 AU.addRequired<MachineBranchProbabilityInfo>();
82 MachineFunctionPass::getAnalysisUsage(AU);
85 const char *getPassName() const override {
86 return "Hexagon NewValueJump";
89 bool runOnMachineFunction(MachineFunction &Fn) override;
92 /// \brief A handle to the branch probability pass.
93 const MachineBranchProbabilityInfo *MBPI;
97 } // end of anonymous namespace
99 char HexagonNewValueJump::ID = 0;
101 INITIALIZE_PASS_BEGIN(HexagonNewValueJump, "hexagon-nvj",
102 "Hexagon NewValueJump", false, false)
103 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
104 INITIALIZE_PASS_END(HexagonNewValueJump, "hexagon-nvj",
105 "Hexagon NewValueJump", false, false)
108 // We have identified this II could be feeder to NVJ,
109 // verify that it can be.
110 static bool canBeFeederToNewValueJump(const HexagonInstrInfo *QII,
111 const TargetRegisterInfo *TRI,
112 MachineBasicBlock::iterator II,
113 MachineBasicBlock::iterator end,
114 MachineBasicBlock::iterator skip,
115 MachineFunction &MF) {
117 // Predicated instruction can not be feeder to NVJ.
118 if (QII->isPredicated(II))
121 // Bail out if feederReg is a paired register (double regs in
122 // our case). One would think that we can check to see if a given
123 // register cmpReg1 or cmpReg2 is a sub register of feederReg
124 // using -- if (QRI->isSubRegister(feederReg, cmpReg1) logic
125 // before the callsite of this function
126 // But we can not as it comes in the following fashion.
127 // %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
128 // %R0<def> = KILL %R0, %D0<imp-use,kill>
129 // %P0<def> = CMPEQri %R0<kill>, 0
130 // Hence, we need to check if it's a KILL instruction.
131 if (II->getOpcode() == TargetOpcode::KILL)
135 // Make sure there there is no 'def' or 'use' of any of the uses of
136 // feeder insn between it's definition, this MI and jump, jmpInst
137 // skipping compare, cmpInst.
138 // Here's the example.
139 // r21=memub(r22+r24<<#0)
140 // p0 = cmp.eq(r21, #0)
141 // r4=memub(r3+r21<<#0)
142 // if (p0.new) jump:t .LBB29_45
143 // Without this check, it will be converted into
144 // r4=memub(r3+r21<<#0)
145 // r21=memub(r22+r24<<#0)
146 // p0 = cmp.eq(r21, #0)
147 // if (p0.new) jump:t .LBB29_45
148 // and result WAR hazards if converted to New Value Jump.
150 for (unsigned i = 0; i < II->getNumOperands(); ++i) {
151 if (II->getOperand(i).isReg() &&
152 (II->getOperand(i).isUse() || II->getOperand(i).isDef())) {
153 MachineBasicBlock::iterator localII = II;
155 unsigned Reg = II->getOperand(i).getReg();
156 for (MachineBasicBlock::iterator localBegin = localII;
157 localBegin != end; ++localBegin) {
158 if (localBegin == skip ) continue;
159 // Check for Subregisters too.
160 if (localBegin->modifiesRegister(Reg, TRI) ||
161 localBegin->readsRegister(Reg, TRI))
169 // These are the common checks that need to performed
171 // 1. compare instruction can be moved before jump.
172 // 2. feeder to the compare instruction can be moved before jump.
173 static bool commonChecksToProhibitNewValueJump(bool afterRA,
174 MachineBasicBlock::iterator MII) {
176 // If store in path, bail out.
177 if (MII->getDesc().mayStore())
180 // if call in path, bail out.
181 if (MII->getOpcode() == Hexagon::J2_call)
184 // if NVJ is running prior to RA, do the following checks.
186 // The following Target Opcode instructions are spurious
187 // to new value jump. If they are in the path, bail out.
188 // KILL sets kill flag on the opcode. It also sets up a
189 // single register, out of pair.
190 // %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
191 // %R0<def> = KILL %R0, %D0<imp-use,kill>
192 // %P0<def> = CMPEQri %R0<kill>, 0
193 // PHI can be anything after RA.
194 // COPY can remateriaze things in between feeder, compare and nvj.
195 if (MII->getOpcode() == TargetOpcode::KILL ||
196 MII->getOpcode() == TargetOpcode::PHI ||
197 MII->getOpcode() == TargetOpcode::COPY)
200 // The following pseudo Hexagon instructions sets "use" and "def"
201 // of registers by individual passes in the backend. At this time,
202 // we don't know the scope of usage and definitions of these
204 if (MII->getOpcode() == Hexagon::LDriw_pred ||
205 MII->getOpcode() == Hexagon::STriw_pred)
212 static bool canCompareBeNewValueJump(const HexagonInstrInfo *QII,
213 const TargetRegisterInfo *TRI,
214 MachineBasicBlock::iterator II,
218 MachineBasicBlock::iterator end,
219 MachineFunction &MF) {
221 MachineInstr *MI = II;
223 // If the second operand of the compare is an imm, make sure it's in the
224 // range specified by the arch.
226 int64_t v = MI->getOperand(2).getImm();
228 if (!(isUInt<5>(v) ||
229 ((MI->getOpcode() == Hexagon::C2_cmpeqi ||
230 MI->getOpcode() == Hexagon::C2_cmpgti) &&
235 unsigned cmpReg1, cmpOp2 = 0; // cmpOp2 assignment silences compiler warning.
236 cmpReg1 = MI->getOperand(1).getReg();
239 cmpOp2 = MI->getOperand(2).getReg();
241 // Make sure that that second register is not from COPY
242 // At machine code level, we don't need this, but if we decide
243 // to move new value jump prior to RA, we would be needing this.
244 MachineRegisterInfo &MRI = MF.getRegInfo();
245 if (secondReg && !TargetRegisterInfo::isPhysicalRegister(cmpOp2)) {
246 MachineInstr *def = MRI.getVRegDef(cmpOp2);
247 if (def->getOpcode() == TargetOpcode::COPY)
252 // Walk the instructions after the compare (predicate def) to the jump,
253 // and satisfy the following conditions.
255 for (MachineBasicBlock::iterator localII = II; localII != end;
259 // If "common" checks fail, bail out.
260 if (!commonChecksToProhibitNewValueJump(optLocation, localII))
264 // If there is a def or use of predicate (result of compare), bail out.
265 if (localII->modifiesRegister(pReg, TRI) ||
266 localII->readsRegister(pReg, TRI))
270 // If there is a def of any of the use of the compare (operands of compare),
273 // p0 = cmp.eq(r2, r0)
275 // if (p0.new) jump:t .LBB28_3
276 if (localII->modifiesRegister(cmpReg1, TRI) ||
277 (secondReg && localII->modifiesRegister(cmpOp2, TRI)))
283 // Given a compare operator, return a matching New Value Jump
284 // compare operator. Make sure that MI here is included in
285 // HexagonInstrInfo.cpp::isNewValueJumpCandidate
286 static unsigned getNewValueJumpOpcode(MachineInstr *MI, int reg,
287 bool secondRegNewified,
288 MachineBasicBlock *jmpTarget,
289 const MachineBranchProbabilityInfo
292 MachineBasicBlock *Src = MI->getParent();
293 const BranchProbability Prediction =
294 MBPI->getEdgeProbability(Src, jmpTarget);
296 if (Prediction >= BranchProbability(1,2))
299 switch (MI->getOpcode()) {
300 case Hexagon::C2_cmpeq:
301 return taken ? Hexagon::J4_cmpeq_t_jumpnv_t
302 : Hexagon::J4_cmpeq_t_jumpnv_nt;
304 case Hexagon::C2_cmpeqi: {
306 return taken ? Hexagon::J4_cmpeqi_t_jumpnv_t
307 : Hexagon::J4_cmpeqi_t_jumpnv_nt;
309 return taken ? Hexagon::J4_cmpeqn1_t_jumpnv_t
310 : Hexagon::J4_cmpeqn1_t_jumpnv_nt;
313 case Hexagon::C2_cmpgt: {
314 if (secondRegNewified)
315 return taken ? Hexagon::J4_cmplt_t_jumpnv_t
316 : Hexagon::J4_cmplt_t_jumpnv_nt;
318 return taken ? Hexagon::J4_cmpgt_t_jumpnv_t
319 : Hexagon::J4_cmpgt_t_jumpnv_nt;
322 case Hexagon::C2_cmpgti: {
324 return taken ? Hexagon::J4_cmpgti_t_jumpnv_t
325 : Hexagon::J4_cmpgti_t_jumpnv_nt;
327 return taken ? Hexagon::J4_cmpgtn1_t_jumpnv_t
328 : Hexagon::J4_cmpgtn1_t_jumpnv_nt;
331 case Hexagon::C2_cmpgtu: {
332 if (secondRegNewified)
333 return taken ? Hexagon::J4_cmpltu_t_jumpnv_t
334 : Hexagon::J4_cmpltu_t_jumpnv_nt;
336 return taken ? Hexagon::J4_cmpgtu_t_jumpnv_t
337 : Hexagon::J4_cmpgtu_t_jumpnv_nt;
340 case Hexagon::C2_cmpgtui:
341 return taken ? Hexagon::J4_cmpgtui_t_jumpnv_t
342 : Hexagon::J4_cmpgtui_t_jumpnv_nt;
345 llvm_unreachable("Could not find matching New Value Jump instruction.");
347 // return *some value* to avoid compiler warning
351 bool HexagonNewValueJump::runOnMachineFunction(MachineFunction &MF) {
353 DEBUG(dbgs() << "********** Hexagon New Value Jump **********\n"
354 << "********** Function: "
355 << MF.getName() << "\n");
357 // If we move NewValueJump before register allocation we'll need live variable
358 // analysis here too.
360 QII = static_cast<const HexagonInstrInfo *>(MF.getSubtarget().getInstrInfo());
361 QRI = static_cast<const HexagonRegisterInfo *>(
362 MF.getSubtarget().getRegisterInfo());
363 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
365 if (DisableNewValueJumps) {
369 int nvjCount = DbgNVJCount;
370 int nvjGenerated = 0;
372 // Loop through all the bb's of the function
373 for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
374 MBBb != MBBe; ++MBBb) {
375 MachineBasicBlock* MBB = MBBb;
377 DEBUG(dbgs() << "** dumping bb ** "
378 << MBB->getNumber() << "\n");
380 DEBUG(dbgs() << "\n" << "********** dumping instr bottom up **********\n");
381 bool foundJump = false;
382 bool foundCompare = false;
383 bool invertPredicate = false;
384 unsigned predReg = 0; // predicate reg of the jump.
385 unsigned cmpReg1 = 0;
387 bool MO1IsKill = false;
388 bool MO2IsKill = false;
389 MachineBasicBlock::iterator jmpPos;
390 MachineBasicBlock::iterator cmpPos;
391 MachineInstr *cmpInstr = nullptr, *jmpInstr = nullptr;
392 MachineBasicBlock *jmpTarget = nullptr;
393 bool afterRA = false;
394 bool isSecondOpReg = false;
395 bool isSecondOpNewified = false;
396 // Traverse the basic block - bottom up
397 for (MachineBasicBlock::iterator MII = MBB->end(), E = MBB->begin();
399 MachineInstr *MI = --MII;
400 if (MI->isDebugValue()) {
404 if ((nvjCount == 0) || (nvjCount > -1 && nvjCount <= nvjGenerated))
407 DEBUG(dbgs() << "Instr: "; MI->dump(); dbgs() << "\n");
410 (MI->getOpcode() == Hexagon::J2_jumpt ||
411 MI->getOpcode() == Hexagon::J2_jumpf ||
412 MI->getOpcode() == Hexagon::J2_jumptnewpt ||
413 MI->getOpcode() == Hexagon::J2_jumptnew ||
414 MI->getOpcode() == Hexagon::J2_jumpfnewpt ||
415 MI->getOpcode() == Hexagon::J2_jumpfnew)) {
416 // This is where you would insert your compare and
417 // instr that feeds compare
420 predReg = MI->getOperand(0).getReg();
421 afterRA = TargetRegisterInfo::isPhysicalRegister(predReg);
423 // If ifconverter had not messed up with the kill flags of the
424 // operands, the following check on the kill flag would suffice.
425 // if(!jmpInstr->getOperand(0).isKill()) break;
427 // This predicate register is live out out of BB
428 // this would only work if we can actually use Live
429 // variable analysis on phy regs - but LLVM does not
430 // provide LV analysis on phys regs.
431 //if(LVs.isLiveOut(predReg, *MBB)) break;
433 // Get all the successors of this block - which will always
434 // be 2. Check if the predicate register is live in in those
435 // successor. If yes, we can not delete the predicate -
436 // I am doing this only because LLVM does not provide LiveOut
438 bool predLive = false;
439 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
440 SIE = MBB->succ_end(); SI != SIE; ++SI) {
441 MachineBasicBlock* succMBB = *SI;
442 if (succMBB->isLiveIn(predReg)) {
449 jmpTarget = MI->getOperand(1).getMBB();
451 if (MI->getOpcode() == Hexagon::J2_jumpf ||
452 MI->getOpcode() == Hexagon::J2_jumpfnewpt ||
453 MI->getOpcode() == Hexagon::J2_jumpfnew) {
454 invertPredicate = true;
459 // No new value jump if there is a barrier. A barrier has to be in its
460 // own packet. A barrier has zero operands. We conservatively bail out
461 // here if we see any instruction with zero operands.
462 if (foundJump && MI->getNumOperands() == 0)
467 MI->getOperand(0).isReg() &&
468 MI->getOperand(0).getReg() == predReg) {
470 // Not all compares can be new value compare. Arch Spec: 7.6.1.1
471 if (QII->isNewValueJumpCandidate(MI)) {
473 assert((MI->getDesc().isCompare()) &&
474 "Only compare instruction can be collapsed into New Value Jump");
475 isSecondOpReg = MI->getOperand(2).isReg();
477 if (!canCompareBeNewValueJump(QII, QRI, MII, predReg, isSecondOpReg,
478 afterRA, jmpPos, MF))
485 // We need cmpReg1 and cmpOp2(imm or reg) while building
486 // new value jump instruction.
487 cmpReg1 = MI->getOperand(1).getReg();
488 if (MI->getOperand(1).isKill())
492 cmpOp2 = MI->getOperand(2).getReg();
493 if (MI->getOperand(2).isKill())
496 cmpOp2 = MI->getOperand(2).getImm();
501 if (foundCompare && foundJump) {
503 // If "common" checks fail, bail out on this BB.
504 if (!commonChecksToProhibitNewValueJump(afterRA, MII))
507 bool foundFeeder = false;
508 MachineBasicBlock::iterator feederPos = MII;
509 if (MI->getOperand(0).isReg() &&
510 MI->getOperand(0).isDef() &&
511 (MI->getOperand(0).getReg() == cmpReg1 ||
513 MI->getOperand(0).getReg() == (unsigned) cmpOp2))) {
515 unsigned feederReg = MI->getOperand(0).getReg();
517 // First try to see if we can get the feeder from the first operand
518 // of the compare. If we can not, and if secondOpReg is true
519 // (second operand of the compare is also register), try that one.
520 // TODO: Try to come up with some heuristic to figure out which
521 // feeder would benefit.
523 if (feederReg == cmpReg1) {
524 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF)) {
535 feederReg == (unsigned) cmpOp2)
536 if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF))
540 // In case of CMPLT, or CMPLTU, or EQ with the second register
541 // to newify, swap the operands.
542 if (cmpInstr->getOpcode() == Hexagon::C2_cmpeq &&
543 feederReg == (unsigned) cmpOp2) {
544 unsigned tmp = cmpReg1;
545 bool tmpIsKill = MO1IsKill;
547 MO1IsKill = MO2IsKill;
549 MO2IsKill = tmpIsKill;
552 // Now we have swapped the operands, all we need to check is,
553 // if the second operand (after swap) is the feeder.
554 // And if it is, make a note.
555 if (feederReg == (unsigned)cmpOp2)
556 isSecondOpNewified = true;
559 // Now that we are moving feeder close the jump,
560 // make sure we are respecting the kill values of
561 // the operands of the feeder.
563 bool updatedIsKill = false;
564 for (unsigned i = 0; i < MI->getNumOperands(); i++) {
565 MachineOperand &MO = MI->getOperand(i);
566 if (MO.isReg() && MO.isUse()) {
567 unsigned feederReg = MO.getReg();
568 for (MachineBasicBlock::iterator localII = feederPos,
569 end = jmpPos; localII != end; localII++) {
570 MachineInstr *localMI = localII;
571 for (unsigned j = 0; j < localMI->getNumOperands(); j++) {
572 MachineOperand &localMO = localMI->getOperand(j);
573 if (localMO.isReg() && localMO.isUse() &&
574 localMO.isKill() && feederReg == localMO.getReg()) {
575 // We found that there is kill of a use register
576 // Set up a kill flag on the register
577 localMO.setIsKill(false);
579 updatedIsKill = true;
583 if (updatedIsKill) break;
586 if (updatedIsKill) break;
589 MBB->splice(jmpPos, MI->getParent(), MI);
590 MBB->splice(jmpPos, MI->getParent(), cmpInstr);
591 DebugLoc dl = MI->getDebugLoc();
594 assert((QII->isNewValueJumpCandidate(cmpInstr)) &&
595 "This compare is not a New Value Jump candidate.");
596 unsigned opc = getNewValueJumpOpcode(cmpInstr, cmpOp2,
600 opc = QII->getInvertedPredicatedOpcode(opc);
603 NewMI = BuildMI(*MBB, jmpPos, dl,
605 .addReg(cmpReg1, getKillRegState(MO1IsKill))
606 .addReg(cmpOp2, getKillRegState(MO2IsKill))
609 else if ((cmpInstr->getOpcode() == Hexagon::C2_cmpeqi ||
610 cmpInstr->getOpcode() == Hexagon::C2_cmpgti) &&
612 // Corresponding new-value compare jump instructions don't have the
613 // operand for -1 immediate value.
614 NewMI = BuildMI(*MBB, jmpPos, dl,
616 .addReg(cmpReg1, getKillRegState(MO1IsKill))
620 NewMI = BuildMI(*MBB, jmpPos, dl,
622 .addReg(cmpReg1, getKillRegState(MO1IsKill))
626 assert(NewMI && "New Value Jump Instruction Not created!");
628 if (cmpInstr->getOperand(0).isReg() &&
629 cmpInstr->getOperand(0).isKill())
630 cmpInstr->getOperand(0).setIsKill(false);
631 if (cmpInstr->getOperand(1).isReg() &&
632 cmpInstr->getOperand(1).isKill())
633 cmpInstr->getOperand(1).setIsKill(false);
634 cmpInstr->eraseFromParent();
635 jmpInstr->eraseFromParent();
648 FunctionPass *llvm::createHexagonNewValueJump() {
649 return new HexagonNewValueJump();