723edbc1dd54d929dc2755b007a5a48676f34735
[oota-llvm.git] / lib / Target / Hexagon / HexagonNewValueJump.cpp
1 //===----- HexagonNewValueJump.cpp - Hexagon Backend New Value Jump -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
15 // in future.
16
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
20 // intstructions.
21 //
22 //
23 //===----------------------------------------------------------------------===//
24 #define DEBUG_TYPE "hexagon-nvj"
25 #include "Hexagon.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/PassSupport.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include <map>
48 using namespace llvm;
49
50 STATISTIC(NumNVJGenerated, "Number of New Value Jump Instructions created");
51
52 static cl::opt<int>
53 DbgNVJCount("nvj-count", cl::init(-1), cl::Hidden, cl::desc(
54   "Maximum number of predicated jumps to be converted to New Value Jump"));
55
56 static cl::opt<bool> DisableNewValueJumps("disable-nvjump", cl::Hidden,
57     cl::ZeroOrMore, cl::init(false),
58     cl::desc("Disable New Value Jumps"));
59
60 namespace {
61   struct HexagonNewValueJump : public MachineFunctionPass {
62     const HexagonInstrInfo    *QII;
63     const HexagonRegisterInfo *QRI;
64
65   public:
66     static char ID;
67
68     HexagonNewValueJump() : MachineFunctionPass(ID) { }
69
70     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71       MachineFunctionPass::getAnalysisUsage(AU);
72     }
73
74     const char *getPassName() const {
75       return "Hexagon NewValueJump";
76     }
77
78     virtual bool runOnMachineFunction(MachineFunction &Fn);
79
80   private:
81
82   };
83
84 } // end of anonymous namespace
85
86 char HexagonNewValueJump::ID = 0;
87
88 // We have identified this II could be feeder to NVJ,
89 // verify that it can be.
90 static bool canBeFeederToNewValueJump(const HexagonInstrInfo *QII,
91                                       const TargetRegisterInfo *TRI,
92                                       MachineBasicBlock::iterator II,
93                                       MachineBasicBlock::iterator end,
94                                       MachineBasicBlock::iterator skip,
95                                       MachineFunction &MF) {
96
97   // Predicated instruction can not be feeder to NVJ.
98   if (QII->isPredicated(II))
99     return false;
100
101   // Bail out if feederReg is a paired register (double regs in
102   // our case). One would think that we can check to see if a given
103   // register cmpReg1 or cmpReg2 is a sub register of feederReg
104   // using -- if (QRI->isSubRegister(feederReg, cmpReg1) logic
105   // before the callsite of this function
106   // But we can not as it comes in the following fashion.
107   //    %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
108   //    %R0<def> = KILL %R0, %D0<imp-use,kill>
109   //    %P0<def> = CMPEQri %R0<kill>, 0
110   // Hence, we need to check if it's a KILL instruction.
111   if (II->getOpcode() == TargetOpcode::KILL)
112     return false;
113
114
115   // Make sure there there is no 'def' or 'use' of any of the uses of
116   // feeder insn between it's definition, this MI and jump, jmpInst
117   // skipping compare, cmpInst.
118   // Here's the example.
119   //    r21=memub(r22+r24<<#0)
120   //    p0 = cmp.eq(r21, #0)
121   //    r4=memub(r3+r21<<#0)
122   //    if (p0.new) jump:t .LBB29_45
123   // Without this check, it will be converted into
124   //    r4=memub(r3+r21<<#0)
125   //    r21=memub(r22+r24<<#0)
126   //    p0 = cmp.eq(r21, #0)
127   //    if (p0.new) jump:t .LBB29_45
128   // and result WAR hazards if converted to New Value Jump.
129
130   for (unsigned i = 0; i < II->getNumOperands(); ++i) {
131     if (II->getOperand(i).isReg() &&
132         (II->getOperand(i).isUse() || II->getOperand(i).isDef())) {
133       MachineBasicBlock::iterator localII = II;
134       ++localII;
135       unsigned Reg = II->getOperand(i).getReg();
136       for (MachineBasicBlock::iterator localBegin = localII;
137                         localBegin != end; ++localBegin) {
138         if (localBegin == skip ) continue;
139         // Check for Subregisters too.
140         if (localBegin->modifiesRegister(Reg, TRI) ||
141             localBegin->readsRegister(Reg, TRI))
142           return false;
143       }
144     }
145   }
146   return true;
147 }
148
149 // These are the common checks that need to performed
150 // to determine if
151 // 1. compare instruction can be moved before jump.
152 // 2. feeder to the compare instruction can be moved before jump.
153 static bool commonChecksToProhibitNewValueJump(bool afterRA,
154                           MachineBasicBlock::iterator MII) {
155
156   // If store in path, bail out.
157   if (MII->getDesc().mayStore())
158     return false;
159
160   // if call in path, bail out.
161   if (MII->getOpcode() == Hexagon::CALLv3)
162     return false;
163
164   // if NVJ is running prior to RA, do the following checks.
165   if (!afterRA) {
166     // The following Target Opcode instructions are spurious
167     // to new value jump. If they are in the path, bail out.
168     // KILL sets kill flag on the opcode. It also sets up a
169     // single register, out of pair.
170     //    %D0<def> = Hexagon_S2_lsr_r_p %D0<kill>, %R2<kill>
171     //    %R0<def> = KILL %R0, %D0<imp-use,kill>
172     //    %P0<def> = CMPEQri %R0<kill>, 0
173     // PHI can be anything after RA.
174     // COPY can remateriaze things in between feeder, compare and nvj.
175     if (MII->getOpcode() == TargetOpcode::KILL ||
176         MII->getOpcode() == TargetOpcode::PHI  ||
177         MII->getOpcode() == TargetOpcode::COPY)
178       return false;
179
180     // The following pseudo Hexagon instructions sets "use" and "def"
181     // of registers by individual passes in the backend. At this time,
182     // we don't know the scope of usage and definitions of these
183     // instructions.
184     if (MII->getOpcode() == Hexagon::TFR_condset_rr ||
185         MII->getOpcode() == Hexagon::TFR_condset_ii ||
186         MII->getOpcode() == Hexagon::TFR_condset_ri ||
187         MII->getOpcode() == Hexagon::TFR_condset_ir ||
188         MII->getOpcode() == Hexagon::LDriw_pred     ||
189         MII->getOpcode() == Hexagon::STriw_pred)
190       return false;
191   }
192
193   return true;
194 }
195
196 static bool canCompareBeNewValueJump(const HexagonInstrInfo *QII,
197                                      const TargetRegisterInfo *TRI,
198                                      MachineBasicBlock::iterator II,
199                                      unsigned pReg,
200                                      bool secondReg,
201                                      bool optLocation,
202                                      MachineBasicBlock::iterator end,
203                                      MachineFunction &MF) {
204
205   MachineInstr *MI = II;
206
207   // If the second operand of the compare is an imm, make sure it's in the
208   // range specified by the arch.
209   if (!secondReg) {
210     int64_t v = MI->getOperand(2).getImm();
211
212     if (!(isUInt<5>(v) ||
213          ((MI->getOpcode() == Hexagon::CMPEQri ||
214            MI->getOpcode() == Hexagon::CMPGTri) &&
215           (v == -1))))
216       return false;
217   }
218
219   unsigned cmpReg1, cmpOp2;
220   cmpReg1 = MI->getOperand(1).getReg();
221
222   if (secondReg) {
223     cmpOp2 = MI->getOperand(2).getReg();
224
225     // Make sure that that second register is not from COPY
226     // At machine code level, we don't need this, but if we decide
227     // to move new value jump prior to RA, we would be needing this.
228     MachineRegisterInfo &MRI = MF.getRegInfo();
229     if (secondReg && !TargetRegisterInfo::isPhysicalRegister(cmpOp2)) {
230       MachineInstr *def = MRI.getVRegDef(cmpOp2);
231       if (def->getOpcode() == TargetOpcode::COPY)
232         return false;
233     }
234   }
235
236   // Walk the instructions after the compare (predicate def) to the jump,
237   // and satisfy the following conditions.
238   ++II ;
239   for (MachineBasicBlock::iterator localII = II; localII != end;
240        ++localII) {
241
242     // Check 1.
243     // If "common" checks fail, bail out.
244     if (!commonChecksToProhibitNewValueJump(optLocation, localII))
245       return false;
246
247     // Check 2.
248     // If there is a def or use of predicate (result of compare), bail out.
249     if (localII->modifiesRegister(pReg, TRI) ||
250         localII->readsRegister(pReg, TRI))
251       return false;
252
253     // Check 3.
254     // If there is a def of any of the use of the compare (operands of compare),
255     // bail out.
256     // Eg.
257     //    p0 = cmp.eq(r2, r0)
258     //    r2 = r4
259     //    if (p0.new) jump:t .LBB28_3
260     if (localII->modifiesRegister(cmpReg1, TRI) ||
261         (secondReg && localII->modifiesRegister(cmpOp2, TRI)))
262       return false;
263   }
264   return true;
265 }
266
267 // Given a compare operator, return a matching New Value Jump
268 // compare operator. Make sure that MI here is included in
269 // HexagonInstrInfo.cpp::isNewValueJumpCandidate
270 static unsigned getNewValueJumpOpcode(const MachineInstr *MI, int reg,
271                                       bool secondRegNewified) {
272   switch (MI->getOpcode()) {
273     case Hexagon::CMPEQrr:
274       return Hexagon::JMP_EQrrPt_nv_V4;
275
276     case Hexagon::CMPEQri: {
277       if (reg >= 0)
278         return Hexagon::JMP_EQriPt_nv_V4;
279       else
280         return Hexagon::JMP_EQriPtneg_nv_V4;
281     }
282
283     case Hexagon::CMPGTrr: {
284       if (secondRegNewified)
285         return Hexagon::JMP_GTrrdnPt_nv_V4;
286       else
287         return Hexagon::JMP_GTrrPt_nv_V4;
288     }
289
290     case Hexagon::CMPGTri: {
291       if (reg >= 0)
292         return Hexagon::JMP_GTriPt_nv_V4;
293       else
294         return Hexagon::JMP_GTriPtneg_nv_V4;
295     }
296
297     case Hexagon::CMPGTUrr: {
298       if (secondRegNewified)
299         return Hexagon::JMP_GTUrrdnPt_nv_V4;
300       else
301         return Hexagon::JMP_GTUrrPt_nv_V4;
302     }
303
304     case Hexagon::CMPGTUri:
305       return Hexagon::JMP_GTUriPt_nv_V4;
306
307     default:
308        llvm_unreachable("Could not find matching New Value Jump instruction.");
309   }
310   // return *some value* to avoid compiler warning
311   return 0;
312 }
313
314 bool HexagonNewValueJump::runOnMachineFunction(MachineFunction &MF) {
315
316   DEBUG(dbgs() << "********** Hexagon New Value Jump **********\n"
317                << "********** Function: "
318                << MF.getName() << "\n");
319
320 #if 0
321   // for now disable this, if we move NewValueJump before register
322   // allocation we need this information.
323   LiveVariables &LVs = getAnalysis<LiveVariables>();
324 #endif
325
326   QII = static_cast<const HexagonInstrInfo *>(MF.getTarget().getInstrInfo());
327   QRI =
328     static_cast<const HexagonRegisterInfo *>(MF.getTarget().getRegisterInfo());
329
330   if (!QRI->Subtarget.hasV4TOps() ||
331       DisableNewValueJumps) {
332     return false;
333   }
334
335   int nvjCount = DbgNVJCount;
336   int nvjGenerated = 0;
337
338   // Loop through all the bb's of the function
339   for (MachineFunction::iterator MBBb = MF.begin(), MBBe = MF.end();
340         MBBb != MBBe; ++MBBb) {
341     MachineBasicBlock* MBB = MBBb;
342
343     DEBUG(dbgs() << "** dumping bb ** "
344                  << MBB->getNumber() << "\n");
345     DEBUG(MBB->dump());
346     DEBUG(dbgs() << "\n" << "********** dumping instr bottom up **********\n");
347     bool foundJump    = false;
348     bool foundCompare = false;
349     bool invertPredicate = false;
350     unsigned predReg = 0; // predicate reg of the jump.
351     unsigned cmpReg1 = 0;
352     int cmpOp2 = 0;
353     bool MO1IsKill = false;
354     bool MO2IsKill = false;
355     MachineBasicBlock::iterator jmpPos;
356     MachineBasicBlock::iterator cmpPos;
357     MachineInstr *cmpInstr = NULL, *jmpInstr = NULL;
358     MachineBasicBlock *jmpTarget = NULL;
359     bool afterRA = false;
360     bool isSecondOpReg = false;
361     bool isSecondOpNewified = false;
362     // Traverse the basic block - bottom up
363     for (MachineBasicBlock::iterator MII = MBB->end(), E = MBB->begin();
364              MII != E;) {
365       MachineInstr *MI = --MII;
366       if (MI->isDebugValue()) {
367         continue;
368       }
369
370       if ((nvjCount == 0) || (nvjCount > -1 && nvjCount <= nvjGenerated))
371         break;
372
373       DEBUG(dbgs() << "Instr: "; MI->dump(); dbgs() << "\n");
374
375       if (!foundJump &&
376          (MI->getOpcode() == Hexagon::JMP_t ||
377           MI->getOpcode() == Hexagon::JMP_f ||
378           MI->getOpcode() == Hexagon::JMP_tnew_t ||
379           MI->getOpcode() == Hexagon::JMP_tnew_nt ||
380           MI->getOpcode() == Hexagon::JMP_fnew_t ||
381           MI->getOpcode() == Hexagon::JMP_fnew_nt)) {
382         // This is where you would insert your compare and
383         // instr that feeds compare
384         jmpPos = MII;
385         jmpInstr = MI;
386         predReg = MI->getOperand(0).getReg();
387         afterRA = TargetRegisterInfo::isPhysicalRegister(predReg);
388
389         // If ifconverter had not messed up with the kill flags of the
390         // operands, the following check on the kill flag would suffice.
391         // if(!jmpInstr->getOperand(0).isKill()) break;
392
393         // This predicate register is live out out of BB
394         // this would only work if we can actually use Live
395         // variable analysis on phy regs - but LLVM does not
396         // provide LV analysis on phys regs.
397         //if(LVs.isLiveOut(predReg, *MBB)) break;
398
399         // Get all the successors of this block - which will always
400         // be 2. Check if the predicate register is live in in those
401         // successor. If yes, we can not delete the predicate -
402         // I am doing this only because LLVM does not provide LiveOut
403         // at the BB level.
404         bool predLive = false;
405         for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
406                             SIE = MBB->succ_end(); SI != SIE; ++SI) {
407           MachineBasicBlock* succMBB = *SI;
408          if (succMBB->isLiveIn(predReg)) {
409             predLive = true;
410           }
411         }
412         if (predLive)
413           break;
414
415         jmpTarget = MI->getOperand(1).getMBB();
416         foundJump = true;
417         if (MI->getOpcode() == Hexagon::JMP_f ||
418             MI->getOpcode() == Hexagon::JMP_fnew_t ||
419             MI->getOpcode() == Hexagon::JMP_fnew_nt) {
420           invertPredicate = true;
421         }
422         continue;
423       }
424
425       // No new value jump if there is a barrier. A barrier has to be in its
426       // own packet. A barrier has zero operands. We conservatively bail out
427       // here if we see any instruction with zero operands.
428       if (foundJump && MI->getNumOperands() == 0)
429         break;
430
431       if (foundJump &&
432          !foundCompare &&
433           MI->getOperand(0).isReg() &&
434           MI->getOperand(0).getReg() == predReg) {
435
436         // Not all compares can be new value compare. Arch Spec: 7.6.1.1
437         if (QII->isNewValueJumpCandidate(MI)) {
438
439           assert((MI->getDesc().isCompare()) &&
440               "Only compare instruction can be collapsed into New Value Jump");
441           isSecondOpReg = MI->getOperand(2).isReg();
442
443           if (!canCompareBeNewValueJump(QII, QRI, MII, predReg, isSecondOpReg,
444                                         afterRA, jmpPos, MF))
445             break;
446
447           cmpInstr = MI;
448           cmpPos = MII;
449           foundCompare = true;
450
451           // We need cmpReg1 and cmpOp2(imm or reg) while building
452           // new value jump instruction.
453           cmpReg1 = MI->getOperand(1).getReg();
454           if (MI->getOperand(1).isKill())
455             MO1IsKill = true;
456
457           if (isSecondOpReg) {
458             cmpOp2 = MI->getOperand(2).getReg();
459             if (MI->getOperand(2).isKill())
460               MO2IsKill = true;
461           } else
462             cmpOp2 = MI->getOperand(2).getImm();
463           continue;
464         }
465       }
466
467       if (foundCompare && foundJump) {
468
469         // If "common" checks fail, bail out on this BB.
470         if (!commonChecksToProhibitNewValueJump(afterRA, MII))
471           break;
472
473         bool foundFeeder = false;
474         MachineBasicBlock::iterator feederPos = MII;
475         if (MI->getOperand(0).isReg() &&
476             MI->getOperand(0).isDef() &&
477            (MI->getOperand(0).getReg() == cmpReg1 ||
478             (isSecondOpReg &&
479              MI->getOperand(0).getReg() == (unsigned) cmpOp2))) {
480
481           unsigned feederReg = MI->getOperand(0).getReg();
482
483           // First try to see if we can get the feeder from the first operand
484           // of the compare. If we can not, and if secondOpReg is true
485           // (second operand of the compare is also register), try that one.
486           // TODO: Try to come up with some heuristic to figure out which
487           // feeder would benefit.
488
489           if (feederReg == cmpReg1) {
490             if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF)) {
491               if (!isSecondOpReg)
492                 break;
493               else
494                 continue;
495             } else
496               foundFeeder = true;
497           }
498
499           if (!foundFeeder &&
500                isSecondOpReg &&
501                feederReg == (unsigned) cmpOp2)
502             if (!canBeFeederToNewValueJump(QII, QRI, MII, jmpPos, cmpPos, MF))
503               break;
504
505           if (isSecondOpReg) {
506             // In case of CMPLT, or CMPLTU, or EQ with the second register
507             // to newify, swap the operands.
508             if (cmpInstr->getOpcode() == Hexagon::CMPEQrr &&
509                                      feederReg == (unsigned) cmpOp2) {
510               unsigned tmp = cmpReg1;
511               bool tmpIsKill = MO1IsKill;
512               cmpReg1 = cmpOp2;
513               MO1IsKill = MO2IsKill;
514               cmpOp2 = tmp;
515               MO2IsKill = tmpIsKill;
516             }
517
518             // Now we have swapped the operands, all we need to check is,
519             // if the second operand (after swap) is the feeder.
520             // And if it is, make a note.
521             if (feederReg == (unsigned)cmpOp2)
522               isSecondOpNewified = true;
523           }
524
525           // Now that we are moving feeder close the jump,
526           // make sure we are respecting the kill values of
527           // the operands of the feeder.
528
529           bool updatedIsKill = false;
530           for (unsigned i = 0; i < MI->getNumOperands(); i++) {
531             MachineOperand &MO = MI->getOperand(i);
532             if (MO.isReg() && MO.isUse()) {
533               unsigned feederReg = MO.getReg();
534               for (MachineBasicBlock::iterator localII = feederPos,
535                    end = jmpPos; localII != end; localII++) {
536                 MachineInstr *localMI = localII;
537                 for (unsigned j = 0; j < localMI->getNumOperands(); j++) {
538                   MachineOperand &localMO = localMI->getOperand(j);
539                   if (localMO.isReg() && localMO.isUse() &&
540                       localMO.isKill() && feederReg == localMO.getReg()) {
541                     // We found that there is kill of a use register
542                     // Set up a kill flag on the register
543                     localMO.setIsKill(false);
544                     MO.setIsKill();
545                     updatedIsKill = true;
546                     break;
547                   }
548                 }
549                 if (updatedIsKill) break;
550               }
551             }
552             if (updatedIsKill) break;
553           }
554
555           MBB->splice(jmpPos, MI->getParent(), MI);
556           MBB->splice(jmpPos, MI->getParent(), cmpInstr);
557           DebugLoc dl = MI->getDebugLoc();
558           MachineInstr *NewMI;
559
560            assert((QII->isNewValueJumpCandidate(cmpInstr)) &&
561                       "This compare is not a New Value Jump candidate.");
562           unsigned opc = getNewValueJumpOpcode(cmpInstr, cmpOp2,
563                                                isSecondOpNewified);
564           if (invertPredicate)
565             opc = QII->getInvertedPredicatedOpcode(opc);
566
567           if (isSecondOpReg)
568             NewMI = BuildMI(*MBB, jmpPos, dl,
569                                   QII->get(opc))
570                                     .addReg(cmpReg1, getKillRegState(MO1IsKill))
571                                     .addReg(cmpOp2, getKillRegState(MO2IsKill))
572                                     .addMBB(jmpTarget);
573
574           else if ((cmpInstr->getOpcode() == Hexagon::CMPEQri ||
575                     cmpInstr->getOpcode() == Hexagon::CMPGTri) &&
576                     cmpOp2 == -1 )
577             // Corresponding new-value compare jump instructions don't have the
578             // operand for -1 immediate value.
579             NewMI = BuildMI(*MBB, jmpPos, dl,
580                                   QII->get(opc))
581                                     .addReg(cmpReg1, getKillRegState(MO1IsKill))
582                                     .addMBB(jmpTarget);
583
584           else
585             NewMI = BuildMI(*MBB, jmpPos, dl,
586                                   QII->get(opc))
587                                     .addReg(cmpReg1, getKillRegState(MO1IsKill))
588                                     .addImm(cmpOp2)
589                                     .addMBB(jmpTarget);
590
591           assert(NewMI && "New Value Jump Instruction Not created!");
592           if (cmpInstr->getOperand(0).isReg() &&
593               cmpInstr->getOperand(0).isKill())
594             cmpInstr->getOperand(0).setIsKill(false);
595           if (cmpInstr->getOperand(1).isReg() &&
596               cmpInstr->getOperand(1).isKill())
597             cmpInstr->getOperand(1).setIsKill(false);
598           cmpInstr->eraseFromParent();
599           jmpInstr->eraseFromParent();
600           ++nvjGenerated;
601           ++NumNVJGenerated;
602           break;
603         }
604       }
605     }
606   }
607
608   return true;
609
610 }
611
612 FunctionPass *llvm::createHexagonNewValueJump() {
613   return new HexagonNewValueJump();
614 }