[PowerPC] Correct commutable indices for VSX FMA instructions
[oota-llvm.git] / lib / Target / PowerPC / PPCInstrInfo.cpp
1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
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 file contains the PowerPC implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 #define GET_INSTRMAP_INFO
36 #define GET_INSTRINFO_CTOR_DTOR
37 #include "PPCGenInstrInfo.inc"
38
39 using namespace llvm;
40
41 static cl::
42 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
43             cl::desc("Disable analysis for CTR loops"));
44
45 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
46 cl::desc("Disable compare instruction optimization"), cl::Hidden);
47
48 // Pin the vtable to this file.
49 void PPCInstrInfo::anchor() {}
50
51 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
52   : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
53     TM(tm), RI(*TM.getSubtargetImpl()) {}
54
55 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
56 /// this target when scheduling the DAG.
57 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
58   const TargetMachine *TM,
59   const ScheduleDAG *DAG) const {
60   unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
61   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
62       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
63     const InstrItineraryData *II = TM->getInstrItineraryData();
64     return new ScoreboardHazardRecognizer(II, DAG);
65   }
66
67   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
68 }
69
70 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
71 /// to use for this target when scheduling the DAG.
72 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
73   const InstrItineraryData *II,
74   const ScheduleDAG *DAG) const {
75   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
76
77   if (Directive == PPC::DIR_PWR7)
78     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
79
80   // Most subtargets use a PPC970 recognizer.
81   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
82       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
83     assert(TM.getInstrInfo() && "No InstrInfo?");
84
85     return new PPCHazardRecognizer970(TM);
86   }
87
88   return new ScoreboardHazardRecognizer(II, DAG);
89 }
90
91
92 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
93                                     const MachineInstr *DefMI, unsigned DefIdx,
94                                     const MachineInstr *UseMI,
95                                     unsigned UseIdx) const {
96   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
97                                                    UseMI, UseIdx);
98
99   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
100   unsigned Reg = DefMO.getReg();
101
102   const TargetRegisterInfo *TRI = &getRegisterInfo();
103   bool IsRegCR;
104   if (TRI->isVirtualRegister(Reg)) {
105     const MachineRegisterInfo *MRI =
106       &DefMI->getParent()->getParent()->getRegInfo();
107     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
108               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
109   } else {
110     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
111               PPC::CRBITRCRegClass.contains(Reg);
112   }
113
114   if (UseMI->isBranch() && IsRegCR) {
115     if (Latency < 0)
116       Latency = getInstrLatency(ItinData, DefMI);
117
118     // On some cores, there is an additional delay between writing to a condition
119     // register, and using it from a branch.
120     unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
121     switch (Directive) {
122     default: break;
123     case PPC::DIR_7400:
124     case PPC::DIR_750:
125     case PPC::DIR_970:
126     case PPC::DIR_E5500:
127     case PPC::DIR_PWR4:
128     case PPC::DIR_PWR5:
129     case PPC::DIR_PWR5X:
130     case PPC::DIR_PWR6:
131     case PPC::DIR_PWR6X:
132     case PPC::DIR_PWR7:
133       Latency += 2;
134       break;
135     }
136   }
137
138   return Latency;
139 }
140
141 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
142 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
143                                          unsigned &SrcReg, unsigned &DstReg,
144                                          unsigned &SubIdx) const {
145   switch (MI.getOpcode()) {
146   default: return false;
147   case PPC::EXTSW:
148   case PPC::EXTSW_32_64:
149     SrcReg = MI.getOperand(1).getReg();
150     DstReg = MI.getOperand(0).getReg();
151     SubIdx = PPC::sub_32;
152     return true;
153   }
154 }
155
156 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
157                                            int &FrameIndex) const {
158   // Note: This list must be kept consistent with LoadRegFromStackSlot.
159   switch (MI->getOpcode()) {
160   default: break;
161   case PPC::LD:
162   case PPC::LWZ:
163   case PPC::LFS:
164   case PPC::LFD:
165   case PPC::RESTORE_CR:
166   case PPC::RESTORE_CRBIT:
167   case PPC::LVX:
168   case PPC::LXVD2X:
169   case PPC::RESTORE_VRSAVE:
170     // Check for the operands added by addFrameReference (the immediate is the
171     // offset which defaults to 0).
172     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
173         MI->getOperand(2).isFI()) {
174       FrameIndex = MI->getOperand(2).getIndex();
175       return MI->getOperand(0).getReg();
176     }
177     break;
178   }
179   return 0;
180 }
181
182 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
183                                           int &FrameIndex) const {
184   // Note: This list must be kept consistent with StoreRegToStackSlot.
185   switch (MI->getOpcode()) {
186   default: break;
187   case PPC::STD:
188   case PPC::STW:
189   case PPC::STFS:
190   case PPC::STFD:
191   case PPC::SPILL_CR:
192   case PPC::SPILL_CRBIT:
193   case PPC::STVX:
194   case PPC::STXVD2X:
195   case PPC::SPILL_VRSAVE:
196     // Check for the operands added by addFrameReference (the immediate is the
197     // offset which defaults to 0).
198     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
199         MI->getOperand(2).isFI()) {
200       FrameIndex = MI->getOperand(2).getIndex();
201       return MI->getOperand(0).getReg();
202     }
203     break;
204   }
205   return 0;
206 }
207
208 // commuteInstruction - We can commute rlwimi instructions, but only if the
209 // rotate amt is zero.  We also have to munge the immediates a bit.
210 MachineInstr *
211 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
212   MachineFunction &MF = *MI->getParent()->getParent();
213
214   // Normal instructions can be commuted the obvious way.
215   if (MI->getOpcode() != PPC::RLWIMI &&
216       MI->getOpcode() != PPC::RLWIMIo &&
217       MI->getOpcode() != PPC::RLWIMI8 &&
218       MI->getOpcode() != PPC::RLWIMI8o)
219     return TargetInstrInfo::commuteInstruction(MI, NewMI);
220
221   // Cannot commute if it has a non-zero rotate count.
222   if (MI->getOperand(3).getImm() != 0)
223     return 0;
224
225   // If we have a zero rotate count, we have:
226   //   M = mask(MB,ME)
227   //   Op0 = (Op1 & ~M) | (Op2 & M)
228   // Change this to:
229   //   M = mask((ME+1)&31, (MB-1)&31)
230   //   Op0 = (Op2 & ~M) | (Op1 & M)
231
232   // Swap op1/op2
233   unsigned Reg0 = MI->getOperand(0).getReg();
234   unsigned Reg1 = MI->getOperand(1).getReg();
235   unsigned Reg2 = MI->getOperand(2).getReg();
236   unsigned SubReg1 = MI->getOperand(1).getSubReg();
237   unsigned SubReg2 = MI->getOperand(2).getSubReg();
238   bool Reg1IsKill = MI->getOperand(1).isKill();
239   bool Reg2IsKill = MI->getOperand(2).isKill();
240   bool ChangeReg0 = false;
241   // If machine instrs are no longer in two-address forms, update
242   // destination register as well.
243   if (Reg0 == Reg1) {
244     // Must be two address instruction!
245     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
246            "Expecting a two-address instruction!");
247     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
248     Reg2IsKill = false;
249     ChangeReg0 = true;
250   }
251
252   // Masks.
253   unsigned MB = MI->getOperand(4).getImm();
254   unsigned ME = MI->getOperand(5).getImm();
255
256   if (NewMI) {
257     // Create a new instruction.
258     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
259     bool Reg0IsDead = MI->getOperand(0).isDead();
260     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
261       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
262       .addReg(Reg2, getKillRegState(Reg2IsKill))
263       .addReg(Reg1, getKillRegState(Reg1IsKill))
264       .addImm((ME+1) & 31)
265       .addImm((MB-1) & 31);
266   }
267
268   if (ChangeReg0) {
269     MI->getOperand(0).setReg(Reg2);
270     MI->getOperand(0).setSubReg(SubReg2);
271   }
272   MI->getOperand(2).setReg(Reg1);
273   MI->getOperand(1).setReg(Reg2);
274   MI->getOperand(2).setSubReg(SubReg1);
275   MI->getOperand(1).setSubReg(SubReg2);
276   MI->getOperand(2).setIsKill(Reg1IsKill);
277   MI->getOperand(1).setIsKill(Reg2IsKill);
278
279   // Swap the mask around.
280   MI->getOperand(4).setImm((ME+1) & 31);
281   MI->getOperand(5).setImm((MB-1) & 31);
282   return MI;
283 }
284
285 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
286                                          unsigned &SrcOpIdx2) const {
287   // For VSX A-Type FMA instructions, it is the first two operands that can be
288   // commuted, however, because the non-encoded tied input operand is listed
289   // first, the operands to swap are actually the second and third.
290
291   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
292   if (AltOpc == -1)
293     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
294
295   SrcOpIdx1 = 2;
296   SrcOpIdx2 = 3;
297   return true;
298 }
299
300 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
301                               MachineBasicBlock::iterator MI) const {
302   // This function is used for scheduling, and the nop wanted here is the type
303   // that terminates dispatch groups on the POWER cores.
304   unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
305   unsigned Opcode;
306   switch (Directive) {
307   default:            Opcode = PPC::NOP; break;
308   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
309   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
310   }
311
312   DebugLoc DL;
313   BuildMI(MBB, MI, DL, get(Opcode));
314 }
315
316 // Branch analysis.
317 // Note: If the condition register is set to CTR or CTR8 then this is a
318 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
319 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
320                                  MachineBasicBlock *&FBB,
321                                  SmallVectorImpl<MachineOperand> &Cond,
322                                  bool AllowModify) const {
323   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
324
325   // If the block has no terminators, it just falls into the block after it.
326   MachineBasicBlock::iterator I = MBB.end();
327   if (I == MBB.begin())
328     return false;
329   --I;
330   while (I->isDebugValue()) {
331     if (I == MBB.begin())
332       return false;
333     --I;
334   }
335   if (!isUnpredicatedTerminator(I))
336     return false;
337
338   // Get the last instruction in the block.
339   MachineInstr *LastInst = I;
340
341   // If there is only one terminator instruction, process it.
342   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
343     if (LastInst->getOpcode() == PPC::B) {
344       if (!LastInst->getOperand(0).isMBB())
345         return true;
346       TBB = LastInst->getOperand(0).getMBB();
347       return false;
348     } else if (LastInst->getOpcode() == PPC::BCC) {
349       if (!LastInst->getOperand(2).isMBB())
350         return true;
351       // Block ends with fall-through condbranch.
352       TBB = LastInst->getOperand(2).getMBB();
353       Cond.push_back(LastInst->getOperand(0));
354       Cond.push_back(LastInst->getOperand(1));
355       return false;
356     } else if (LastInst->getOpcode() == PPC::BC) {
357       if (!LastInst->getOperand(1).isMBB())
358         return true;
359       // Block ends with fall-through condbranch.
360       TBB = LastInst->getOperand(1).getMBB();
361       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
362       Cond.push_back(LastInst->getOperand(0));
363       return false;
364     } else if (LastInst->getOpcode() == PPC::BCn) {
365       if (!LastInst->getOperand(1).isMBB())
366         return true;
367       // Block ends with fall-through condbranch.
368       TBB = LastInst->getOperand(1).getMBB();
369       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
370       Cond.push_back(LastInst->getOperand(0));
371       return false;
372     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
373                LastInst->getOpcode() == PPC::BDNZ) {
374       if (!LastInst->getOperand(0).isMBB())
375         return true;
376       if (DisableCTRLoopAnal)
377         return true;
378       TBB = LastInst->getOperand(0).getMBB();
379       Cond.push_back(MachineOperand::CreateImm(1));
380       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
381                                                true));
382       return false;
383     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
384                LastInst->getOpcode() == PPC::BDZ) {
385       if (!LastInst->getOperand(0).isMBB())
386         return true;
387       if (DisableCTRLoopAnal)
388         return true;
389       TBB = LastInst->getOperand(0).getMBB();
390       Cond.push_back(MachineOperand::CreateImm(0));
391       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
392                                                true));
393       return false;
394     }
395
396     // Otherwise, don't know what this is.
397     return true;
398   }
399
400   // Get the instruction before it if it's a terminator.
401   MachineInstr *SecondLastInst = I;
402
403   // If there are three terminators, we don't know what sort of block this is.
404   if (SecondLastInst && I != MBB.begin() &&
405       isUnpredicatedTerminator(--I))
406     return true;
407
408   // If the block ends with PPC::B and PPC:BCC, handle it.
409   if (SecondLastInst->getOpcode() == PPC::BCC &&
410       LastInst->getOpcode() == PPC::B) {
411     if (!SecondLastInst->getOperand(2).isMBB() ||
412         !LastInst->getOperand(0).isMBB())
413       return true;
414     TBB =  SecondLastInst->getOperand(2).getMBB();
415     Cond.push_back(SecondLastInst->getOperand(0));
416     Cond.push_back(SecondLastInst->getOperand(1));
417     FBB = LastInst->getOperand(0).getMBB();
418     return false;
419   } else if (SecondLastInst->getOpcode() == PPC::BC &&
420       LastInst->getOpcode() == PPC::B) {
421     if (!SecondLastInst->getOperand(1).isMBB() ||
422         !LastInst->getOperand(0).isMBB())
423       return true;
424     TBB =  SecondLastInst->getOperand(1).getMBB();
425     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
426     Cond.push_back(SecondLastInst->getOperand(0));
427     FBB = LastInst->getOperand(0).getMBB();
428     return false;
429   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
430       LastInst->getOpcode() == PPC::B) {
431     if (!SecondLastInst->getOperand(1).isMBB() ||
432         !LastInst->getOperand(0).isMBB())
433       return true;
434     TBB =  SecondLastInst->getOperand(1).getMBB();
435     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
436     Cond.push_back(SecondLastInst->getOperand(0));
437     FBB = LastInst->getOperand(0).getMBB();
438     return false;
439   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
440               SecondLastInst->getOpcode() == PPC::BDNZ) &&
441       LastInst->getOpcode() == PPC::B) {
442     if (!SecondLastInst->getOperand(0).isMBB() ||
443         !LastInst->getOperand(0).isMBB())
444       return true;
445     if (DisableCTRLoopAnal)
446       return true;
447     TBB = SecondLastInst->getOperand(0).getMBB();
448     Cond.push_back(MachineOperand::CreateImm(1));
449     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
450                                              true));
451     FBB = LastInst->getOperand(0).getMBB();
452     return false;
453   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
454               SecondLastInst->getOpcode() == PPC::BDZ) &&
455       LastInst->getOpcode() == PPC::B) {
456     if (!SecondLastInst->getOperand(0).isMBB() ||
457         !LastInst->getOperand(0).isMBB())
458       return true;
459     if (DisableCTRLoopAnal)
460       return true;
461     TBB = SecondLastInst->getOperand(0).getMBB();
462     Cond.push_back(MachineOperand::CreateImm(0));
463     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
464                                              true));
465     FBB = LastInst->getOperand(0).getMBB();
466     return false;
467   }
468
469   // If the block ends with two PPC:Bs, handle it.  The second one is not
470   // executed, so remove it.
471   if (SecondLastInst->getOpcode() == PPC::B &&
472       LastInst->getOpcode() == PPC::B) {
473     if (!SecondLastInst->getOperand(0).isMBB())
474       return true;
475     TBB = SecondLastInst->getOperand(0).getMBB();
476     I = LastInst;
477     if (AllowModify)
478       I->eraseFromParent();
479     return false;
480   }
481
482   // Otherwise, can't handle this.
483   return true;
484 }
485
486 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
487   MachineBasicBlock::iterator I = MBB.end();
488   if (I == MBB.begin()) return 0;
489   --I;
490   while (I->isDebugValue()) {
491     if (I == MBB.begin())
492       return 0;
493     --I;
494   }
495   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
496       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
497       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
498       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
499     return 0;
500
501   // Remove the branch.
502   I->eraseFromParent();
503
504   I = MBB.end();
505
506   if (I == MBB.begin()) return 1;
507   --I;
508   if (I->getOpcode() != PPC::BCC &&
509       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
510       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
511       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
512     return 1;
513
514   // Remove the branch.
515   I->eraseFromParent();
516   return 2;
517 }
518
519 unsigned
520 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
521                            MachineBasicBlock *FBB,
522                            const SmallVectorImpl<MachineOperand> &Cond,
523                            DebugLoc DL) const {
524   // Shouldn't be a fall through.
525   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
526   assert((Cond.size() == 2 || Cond.size() == 0) &&
527          "PPC branch conditions have two components!");
528
529   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
530
531   // One-way branch.
532   if (FBB == 0) {
533     if (Cond.empty())   // Unconditional branch
534       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
535     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
536       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
537                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
538                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
539     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
540       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
541     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
542       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
543     else                // Conditional branch
544       BuildMI(&MBB, DL, get(PPC::BCC))
545         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
546     return 1;
547   }
548
549   // Two-way Conditional Branch.
550   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
551     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
552                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
553                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
554   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
555     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
556   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
557     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
558   else
559     BuildMI(&MBB, DL, get(PPC::BCC))
560       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
561   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
562   return 2;
563 }
564
565 // Select analysis.
566 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
567                 const SmallVectorImpl<MachineOperand> &Cond,
568                 unsigned TrueReg, unsigned FalseReg,
569                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
570   if (!TM.getSubtargetImpl()->hasISEL())
571     return false;
572
573   if (Cond.size() != 2)
574     return false;
575
576   // If this is really a bdnz-like condition, then it cannot be turned into a
577   // select.
578   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
579     return false;
580
581   // Check register classes.
582   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
583   const TargetRegisterClass *RC =
584     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
585   if (!RC)
586     return false;
587
588   // isel is for regular integer GPRs only.
589   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
590       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
591       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
592       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
593     return false;
594
595   // FIXME: These numbers are for the A2, how well they work for other cores is
596   // an open question. On the A2, the isel instruction has a 2-cycle latency
597   // but single-cycle throughput. These numbers are used in combination with
598   // the MispredictPenalty setting from the active SchedMachineModel.
599   CondCycles = 1;
600   TrueCycles = 1;
601   FalseCycles = 1;
602
603   return true;
604 }
605
606 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
607                                 MachineBasicBlock::iterator MI, DebugLoc dl,
608                                 unsigned DestReg,
609                                 const SmallVectorImpl<MachineOperand> &Cond,
610                                 unsigned TrueReg, unsigned FalseReg) const {
611   assert(Cond.size() == 2 &&
612          "PPC branch conditions have two components!");
613
614   assert(TM.getSubtargetImpl()->hasISEL() &&
615          "Cannot insert select on target without ISEL support");
616
617   // Get the register classes.
618   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
619   const TargetRegisterClass *RC =
620     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
621   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
622
623   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
624                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
625   assert((Is64Bit ||
626           PPC::GPRCRegClass.hasSubClassEq(RC) ||
627           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
628          "isel is for regular integer GPRs only");
629
630   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
631   unsigned SelectPred = Cond[0].getImm();
632
633   unsigned SubIdx;
634   bool SwapOps;
635   switch (SelectPred) {
636   default: llvm_unreachable("invalid predicate for isel");
637   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
638   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
639   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
640   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
641   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
642   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
643   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
644   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
645   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
646   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
647   }
648
649   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
650            SecondReg = SwapOps ? TrueReg  : FalseReg;
651
652   // The first input register of isel cannot be r0. If it is a member
653   // of a register class that can be r0, then copy it first (the
654   // register allocator should eliminate the copy).
655   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
656       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
657     const TargetRegisterClass *FirstRC =
658       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
659         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
660     unsigned OldFirstReg = FirstReg;
661     FirstReg = MRI.createVirtualRegister(FirstRC);
662     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
663       .addReg(OldFirstReg);
664   }
665
666   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
667     .addReg(FirstReg).addReg(SecondReg)
668     .addReg(Cond[1].getReg(), 0, SubIdx);
669 }
670
671 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
672                                MachineBasicBlock::iterator I, DebugLoc DL,
673                                unsigned DestReg, unsigned SrcReg,
674                                bool KillSrc) const {
675   // We can end up with self copies and similar things as a result of VSX copy
676   // legalization. Promote (or just ignore) them here.
677   const TargetRegisterInfo *TRI = &getRegisterInfo();
678   if (PPC::F8RCRegClass.contains(DestReg) &&
679       PPC::VSLRCRegClass.contains(SrcReg)) {
680     unsigned SuperReg =
681       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
682
683     if (SrcReg == SuperReg)
684       return;
685
686     DestReg = SuperReg;
687   } else if (PPC::VRRCRegClass.contains(DestReg) &&
688              PPC::VSHRCRegClass.contains(SrcReg)) {
689     unsigned SuperReg =
690       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
691
692     if (SrcReg == SuperReg)
693       return;
694
695     DestReg = SuperReg;
696   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
697              PPC::VSLRCRegClass.contains(DestReg)) {
698     unsigned SuperReg =
699       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
700
701     if (DestReg == SuperReg)
702       return;
703
704     SrcReg = SuperReg;
705   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
706              PPC::VSHRCRegClass.contains(DestReg)) {
707     unsigned SuperReg =
708       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
709
710     if (DestReg == SuperReg)
711       return;
712
713     SrcReg = SuperReg;
714   }
715
716   unsigned Opc;
717   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
718     Opc = PPC::OR;
719   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
720     Opc = PPC::OR8;
721   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
722     Opc = PPC::FMR;
723   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
724     Opc = PPC::MCRF;
725   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
726     Opc = PPC::VOR;
727   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
728     // There are two different ways this can be done:
729     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
730     //      issue in VSU pipeline 0.
731     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
732     //      can go to either pipeline.
733     // We'll always use xxlor here, because in practically all cases where
734     // copies are generated, they are close enough to some use that the
735     // lower-latency form is preferable.
736     Opc = PPC::XXLOR;
737   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
738     Opc = PPC::CROR;
739   else
740     llvm_unreachable("Impossible reg-to-reg copy");
741
742   const MCInstrDesc &MCID = get(Opc);
743   if (MCID.getNumOperands() == 3)
744     BuildMI(MBB, I, DL, MCID, DestReg)
745       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
746   else
747     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
748 }
749
750 // This function returns true if a CR spill is necessary and false otherwise.
751 bool
752 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
753                                   unsigned SrcReg, bool isKill,
754                                   int FrameIdx,
755                                   const TargetRegisterClass *RC,
756                                   SmallVectorImpl<MachineInstr*> &NewMIs,
757                                   bool &NonRI, bool &SpillsVRS) const{
758   // Note: If additional store instructions are added here,
759   // update isStoreToStackSlot.
760
761   DebugLoc DL;
762   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
763       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
764     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
765                                        .addReg(SrcReg,
766                                                getKillRegState(isKill)),
767                                        FrameIdx));
768   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
769              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
770     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
771                                        .addReg(SrcReg,
772                                                getKillRegState(isKill)),
773                                        FrameIdx));
774   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
775     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
776                                        .addReg(SrcReg,
777                                                getKillRegState(isKill)),
778                                        FrameIdx));
779   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
780     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
781                                        .addReg(SrcReg,
782                                                getKillRegState(isKill)),
783                                        FrameIdx));
784   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
785     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
786                                        .addReg(SrcReg,
787                                                getKillRegState(isKill)),
788                                        FrameIdx));
789     return true;
790   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
791     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
792                                        .addReg(SrcReg,
793                                                getKillRegState(isKill)),
794                                        FrameIdx));
795     return true;
796   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
797     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
798                                        .addReg(SrcReg,
799                                                getKillRegState(isKill)),
800                                        FrameIdx));
801     NonRI = true;
802   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
803     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
804                                        .addReg(SrcReg,
805                                                getKillRegState(isKill)),
806                                        FrameIdx));
807     NonRI = true;
808   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
809     assert(TM.getSubtargetImpl()->isDarwin() &&
810            "VRSAVE only needs spill/restore on Darwin");
811     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
812                                        .addReg(SrcReg,
813                                                getKillRegState(isKill)),
814                                        FrameIdx));
815     SpillsVRS = true;
816   } else {
817     llvm_unreachable("Unknown regclass!");
818   }
819
820   return false;
821 }
822
823 void
824 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
825                                   MachineBasicBlock::iterator MI,
826                                   unsigned SrcReg, bool isKill, int FrameIdx,
827                                   const TargetRegisterClass *RC,
828                                   const TargetRegisterInfo *TRI) const {
829   MachineFunction &MF = *MBB.getParent();
830   SmallVector<MachineInstr*, 4> NewMIs;
831
832   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
833   FuncInfo->setHasSpills();
834
835   bool NonRI = false, SpillsVRS = false;
836   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
837                           NonRI, SpillsVRS))
838     FuncInfo->setSpillsCR();
839
840   if (SpillsVRS)
841     FuncInfo->setSpillsVRSAVE();
842
843   if (NonRI)
844     FuncInfo->setHasNonRISpills();
845
846   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
847     MBB.insert(MI, NewMIs[i]);
848
849   const MachineFrameInfo &MFI = *MF.getFrameInfo();
850   MachineMemOperand *MMO =
851     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
852                             MachineMemOperand::MOStore,
853                             MFI.getObjectSize(FrameIdx),
854                             MFI.getObjectAlignment(FrameIdx));
855   NewMIs.back()->addMemOperand(MF, MMO);
856 }
857
858 bool
859 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
860                                    unsigned DestReg, int FrameIdx,
861                                    const TargetRegisterClass *RC,
862                                    SmallVectorImpl<MachineInstr*> &NewMIs,
863                                    bool &NonRI, bool &SpillsVRS) const{
864   // Note: If additional load instructions are added here,
865   // update isLoadFromStackSlot.
866
867   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
868       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
869     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
870                                                DestReg), FrameIdx));
871   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
872              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
873     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
874                                        FrameIdx));
875   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
876     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
877                                        FrameIdx));
878   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
879     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
880                                        FrameIdx));
881   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
882     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
883                                                get(PPC::RESTORE_CR), DestReg),
884                                        FrameIdx));
885     return true;
886   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
887     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
888                                                get(PPC::RESTORE_CRBIT), DestReg),
889                                        FrameIdx));
890     return true;
891   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
892     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
893                                        FrameIdx));
894     NonRI = true;
895   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
896     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
897                                        FrameIdx));
898     NonRI = true;
899   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
900     assert(TM.getSubtargetImpl()->isDarwin() &&
901            "VRSAVE only needs spill/restore on Darwin");
902     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
903                                                get(PPC::RESTORE_VRSAVE),
904                                                DestReg),
905                                        FrameIdx));
906     SpillsVRS = true;
907   } else {
908     llvm_unreachable("Unknown regclass!");
909   }
910
911   return false;
912 }
913
914 void
915 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
916                                    MachineBasicBlock::iterator MI,
917                                    unsigned DestReg, int FrameIdx,
918                                    const TargetRegisterClass *RC,
919                                    const TargetRegisterInfo *TRI) const {
920   MachineFunction &MF = *MBB.getParent();
921   SmallVector<MachineInstr*, 4> NewMIs;
922   DebugLoc DL;
923   if (MI != MBB.end()) DL = MI->getDebugLoc();
924
925   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
926   FuncInfo->setHasSpills();
927
928   bool NonRI = false, SpillsVRS = false;
929   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
930                            NonRI, SpillsVRS))
931     FuncInfo->setSpillsCR();
932
933   if (SpillsVRS)
934     FuncInfo->setSpillsVRSAVE();
935
936   if (NonRI)
937     FuncInfo->setHasNonRISpills();
938
939   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
940     MBB.insert(MI, NewMIs[i]);
941
942   const MachineFrameInfo &MFI = *MF.getFrameInfo();
943   MachineMemOperand *MMO =
944     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
945                             MachineMemOperand::MOLoad,
946                             MFI.getObjectSize(FrameIdx),
947                             MFI.getObjectAlignment(FrameIdx));
948   NewMIs.back()->addMemOperand(MF, MMO);
949 }
950
951 bool PPCInstrInfo::
952 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
953   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
954   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
955     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
956   else
957     // Leave the CR# the same, but invert the condition.
958     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
959   return false;
960 }
961
962 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
963                              unsigned Reg, MachineRegisterInfo *MRI) const {
964   // For some instructions, it is legal to fold ZERO into the RA register field.
965   // A zero immediate should always be loaded with a single li.
966   unsigned DefOpc = DefMI->getOpcode();
967   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
968     return false;
969   if (!DefMI->getOperand(1).isImm())
970     return false;
971   if (DefMI->getOperand(1).getImm() != 0)
972     return false;
973
974   // Note that we cannot here invert the arguments of an isel in order to fold
975   // a ZERO into what is presented as the second argument. All we have here
976   // is the condition bit, and that might come from a CR-logical bit operation.
977
978   const MCInstrDesc &UseMCID = UseMI->getDesc();
979
980   // Only fold into real machine instructions.
981   if (UseMCID.isPseudo())
982     return false;
983
984   unsigned UseIdx;
985   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
986     if (UseMI->getOperand(UseIdx).isReg() &&
987         UseMI->getOperand(UseIdx).getReg() == Reg)
988       break;
989
990   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
991   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
992
993   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
994
995   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
996   // register (which might also be specified as a pointer class kind).
997   if (UseInfo->isLookupPtrRegClass()) {
998     if (UseInfo->RegClass /* Kind */ != 1)
999       return false;
1000   } else {
1001     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1002         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1003       return false;
1004   }
1005
1006   // Make sure this is not tied to an output register (or otherwise
1007   // constrained). This is true for ST?UX registers, for example, which
1008   // are tied to their output registers.
1009   if (UseInfo->Constraints != 0)
1010     return false;
1011
1012   unsigned ZeroReg;
1013   if (UseInfo->isLookupPtrRegClass()) {
1014     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1015     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1016   } else {
1017     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1018               PPC::ZERO8 : PPC::ZERO;
1019   }
1020
1021   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1022   UseMI->getOperand(UseIdx).setReg(ZeroReg);
1023
1024   if (DeleteDef)
1025     DefMI->eraseFromParent();
1026
1027   return true;
1028 }
1029
1030 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1031   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1032        I != IE; ++I)
1033     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1034       return true;
1035   return false;
1036 }
1037
1038 // We should make sure that, if we're going to predicate both sides of a
1039 // condition (a diamond), that both sides don't define the counter register. We
1040 // can predicate counter-decrement-based branches, but while that predicates
1041 // the branching, it does not predicate the counter decrement. If we tried to
1042 // merge the triangle into one predicated block, we'd decrement the counter
1043 // twice.
1044 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1045                      unsigned NumT, unsigned ExtraT,
1046                      MachineBasicBlock &FMBB,
1047                      unsigned NumF, unsigned ExtraF,
1048                      const BranchProbability &Probability) const {
1049   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1050 }
1051
1052
1053 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1054   // The predicated branches are identified by their type, not really by the
1055   // explicit presence of a predicate. Furthermore, some of them can be
1056   // predicated more than once. Because if conversion won't try to predicate
1057   // any instruction which already claims to be predicated (by returning true
1058   // here), always return false. In doing so, we let isPredicable() be the
1059   // final word on whether not the instruction can be (further) predicated.
1060
1061   return false;
1062 }
1063
1064 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1065   if (!MI->isTerminator())
1066     return false;
1067
1068   // Conditional branch is a special case.
1069   if (MI->isBranch() && !MI->isBarrier())
1070     return true;
1071
1072   return !isPredicated(MI);
1073 }
1074
1075 bool PPCInstrInfo::PredicateInstruction(
1076                      MachineInstr *MI,
1077                      const SmallVectorImpl<MachineOperand> &Pred) const {
1078   unsigned OpC = MI->getOpcode();
1079   if (OpC == PPC::BLR) {
1080     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1081       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1082       MI->setDesc(get(Pred[0].getImm() ?
1083                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1084                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
1085     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1086       MI->setDesc(get(PPC::BCLR));
1087       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1088         .addReg(Pred[1].getReg());
1089     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1090       MI->setDesc(get(PPC::BCLRn));
1091       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1092         .addReg(Pred[1].getReg());
1093     } else {
1094       MI->setDesc(get(PPC::BCCLR));
1095       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1096         .addImm(Pred[0].getImm())
1097         .addReg(Pred[1].getReg());
1098     }
1099
1100     return true;
1101   } else if (OpC == PPC::B) {
1102     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1103       bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1104       MI->setDesc(get(Pred[0].getImm() ?
1105                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1106                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
1107     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1108       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1109       MI->RemoveOperand(0);
1110
1111       MI->setDesc(get(PPC::BC));
1112       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1113         .addReg(Pred[1].getReg())
1114         .addMBB(MBB);
1115     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1116       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1117       MI->RemoveOperand(0);
1118
1119       MI->setDesc(get(PPC::BCn));
1120       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1121         .addReg(Pred[1].getReg())
1122         .addMBB(MBB);
1123     } else {
1124       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1125       MI->RemoveOperand(0);
1126
1127       MI->setDesc(get(PPC::BCC));
1128       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1129         .addImm(Pred[0].getImm())
1130         .addReg(Pred[1].getReg())
1131         .addMBB(MBB);
1132     }
1133
1134     return true;
1135   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1136              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1137     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1138       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1139
1140     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1141     bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1142
1143     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1144       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1145                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
1146       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1147         .addReg(Pred[1].getReg());
1148       return true;
1149     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1150       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1151                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
1152       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1153         .addReg(Pred[1].getReg());
1154       return true;
1155     }
1156
1157     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1158                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
1159     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1160       .addImm(Pred[0].getImm())
1161       .addReg(Pred[1].getReg());
1162     return true;
1163   }
1164
1165   return false;
1166 }
1167
1168 bool PPCInstrInfo::SubsumesPredicate(
1169                      const SmallVectorImpl<MachineOperand> &Pred1,
1170                      const SmallVectorImpl<MachineOperand> &Pred2) const {
1171   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1172   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1173
1174   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1175     return false;
1176   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1177     return false;
1178
1179   // P1 can only subsume P2 if they test the same condition register.
1180   if (Pred1[1].getReg() != Pred2[1].getReg())
1181     return false;
1182
1183   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1184   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1185
1186   if (P1 == P2)
1187     return true;
1188
1189   // Does P1 subsume P2, e.g. GE subsumes GT.
1190   if (P1 == PPC::PRED_LE &&
1191       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1192     return true;
1193   if (P1 == PPC::PRED_GE &&
1194       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1195     return true;
1196
1197   return false;
1198 }
1199
1200 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1201                                     std::vector<MachineOperand> &Pred) const {
1202   // Note: At the present time, the contents of Pred from this function is
1203   // unused by IfConversion. This implementation follows ARM by pushing the
1204   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1205   // predicate, instructions defining CTR or CTR8 are also included as
1206   // predicate-defining instructions.
1207
1208   const TargetRegisterClass *RCs[] =
1209     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1210       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1211
1212   bool Found = false;
1213   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1214     const MachineOperand &MO = MI->getOperand(i);
1215     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1216       const TargetRegisterClass *RC = RCs[c];
1217       if (MO.isReg()) {
1218         if (MO.isDef() && RC->contains(MO.getReg())) {
1219           Pred.push_back(MO);
1220           Found = true;
1221         }
1222       } else if (MO.isRegMask()) {
1223         for (TargetRegisterClass::iterator I = RC->begin(),
1224              IE = RC->end(); I != IE; ++I)
1225           if (MO.clobbersPhysReg(*I)) {
1226             Pred.push_back(MO);
1227             Found = true;
1228           }
1229       }
1230     }
1231   }
1232
1233   return Found;
1234 }
1235
1236 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1237   unsigned OpC = MI->getOpcode();
1238   switch (OpC) {
1239   default:
1240     return false;
1241   case PPC::B:
1242   case PPC::BLR:
1243   case PPC::BCTR:
1244   case PPC::BCTR8:
1245   case PPC::BCTRL:
1246   case PPC::BCTRL8:
1247     return true;
1248   }
1249 }
1250
1251 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1252                                   unsigned &SrcReg, unsigned &SrcReg2,
1253                                   int &Mask, int &Value) const {
1254   unsigned Opc = MI->getOpcode();
1255
1256   switch (Opc) {
1257   default: return false;
1258   case PPC::CMPWI:
1259   case PPC::CMPLWI:
1260   case PPC::CMPDI:
1261   case PPC::CMPLDI:
1262     SrcReg = MI->getOperand(1).getReg();
1263     SrcReg2 = 0;
1264     Value = MI->getOperand(2).getImm();
1265     Mask = 0xFFFF;
1266     return true;
1267   case PPC::CMPW:
1268   case PPC::CMPLW:
1269   case PPC::CMPD:
1270   case PPC::CMPLD:
1271   case PPC::FCMPUS:
1272   case PPC::FCMPUD:
1273     SrcReg = MI->getOperand(1).getReg();
1274     SrcReg2 = MI->getOperand(2).getReg();
1275     return true;
1276   }
1277 }
1278
1279 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1280                                         unsigned SrcReg, unsigned SrcReg2,
1281                                         int Mask, int Value,
1282                                         const MachineRegisterInfo *MRI) const {
1283   if (DisableCmpOpt)
1284     return false;
1285
1286   int OpC = CmpInstr->getOpcode();
1287   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1288
1289   // FP record forms set CR1 based on the execption status bits, not a
1290   // comparison with zero.
1291   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1292     return false;
1293
1294   // The record forms set the condition register based on a signed comparison
1295   // with zero (so says the ISA manual). This is not as straightforward as it
1296   // seems, however, because this is always a 64-bit comparison on PPC64, even
1297   // for instructions that are 32-bit in nature (like slw for example).
1298   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1299   // for equality checks (as those don't depend on the sign). On PPC64,
1300   // we are restricted to equality for unsigned 64-bit comparisons and for
1301   // signed 32-bit comparisons the applicability is more restricted.
1302   bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1303   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1304   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1305   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1306
1307   // Get the unique definition of SrcReg.
1308   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1309   if (!MI) return false;
1310   int MIOpC = MI->getOpcode();
1311
1312   bool equalityOnly = false;
1313   bool noSub = false;
1314   if (isPPC64) {
1315     if (is32BitSignedCompare) {
1316       // We can perform this optimization only if MI is sign-extending.
1317       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1318           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1319           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1320           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1321           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1322         noSub = true;
1323       } else
1324         return false;
1325     } else if (is32BitUnsignedCompare) {
1326       // We can perform this optimization, equality only, if MI is
1327       // zero-extending.
1328       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1329           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1330           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1331         noSub = true;
1332         equalityOnly = true;
1333       } else
1334         return false;
1335     } else
1336       equalityOnly = is64BitUnsignedCompare;
1337   } else
1338     equalityOnly = is32BitUnsignedCompare;
1339
1340   if (equalityOnly) {
1341     // We need to check the uses of the condition register in order to reject
1342     // non-equality comparisons.
1343     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1344          IE = MRI->use_instr_end(); I != IE; ++I) {
1345       MachineInstr *UseMI = &*I;
1346       if (UseMI->getOpcode() == PPC::BCC) {
1347         unsigned Pred = UseMI->getOperand(0).getImm();
1348         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1349           return false;
1350       } else if (UseMI->getOpcode() == PPC::ISEL ||
1351                  UseMI->getOpcode() == PPC::ISEL8) {
1352         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1353         if (SubIdx != PPC::sub_eq)
1354           return false;
1355       } else
1356         return false;
1357     }
1358   }
1359
1360   MachineBasicBlock::iterator I = CmpInstr;
1361
1362   // Scan forward to find the first use of the compare.
1363   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1364        I != EL; ++I) {
1365     bool FoundUse = false;
1366     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1367          JE = MRI->use_instr_end(); J != JE; ++J)
1368       if (&*J == &*I) {
1369         FoundUse = true;
1370         break;
1371       }
1372
1373     if (FoundUse)
1374       break;
1375   }
1376
1377   // There are two possible candidates which can be changed to set CR[01].
1378   // One is MI, the other is a SUB instruction.
1379   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1380   MachineInstr *Sub = NULL;
1381   if (SrcReg2 != 0)
1382     // MI is not a candidate for CMPrr.
1383     MI = NULL;
1384   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1385   // same BB as the comparison. This is to allow the check below to avoid calls
1386   // (and other explicit clobbers); instead we should really check for these
1387   // more explicitly (in at least a few predecessors).
1388   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1389     // PPC does not have a record-form SUBri.
1390     return false;
1391   }
1392
1393   // Search for Sub.
1394   const TargetRegisterInfo *TRI = &getRegisterInfo();
1395   --I;
1396
1397   // Get ready to iterate backward from CmpInstr.
1398   MachineBasicBlock::iterator E = MI,
1399                               B = CmpInstr->getParent()->begin();
1400
1401   for (; I != E && !noSub; --I) {
1402     const MachineInstr &Instr = *I;
1403     unsigned IOpC = Instr.getOpcode();
1404
1405     if (&*I != CmpInstr && (
1406         Instr.modifiesRegister(PPC::CR0, TRI) ||
1407         Instr.readsRegister(PPC::CR0, TRI)))
1408       // This instruction modifies or uses the record condition register after
1409       // the one we want to change. While we could do this transformation, it
1410       // would likely not be profitable. This transformation removes one
1411       // instruction, and so even forcing RA to generate one move probably
1412       // makes it unprofitable.
1413       return false;
1414
1415     // Check whether CmpInstr can be made redundant by the current instruction.
1416     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1417          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1418         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1419         ((Instr.getOperand(1).getReg() == SrcReg &&
1420           Instr.getOperand(2).getReg() == SrcReg2) ||
1421         (Instr.getOperand(1).getReg() == SrcReg2 &&
1422          Instr.getOperand(2).getReg() == SrcReg))) {
1423       Sub = &*I;
1424       break;
1425     }
1426
1427     if (I == B)
1428       // The 'and' is below the comparison instruction.
1429       return false;
1430   }
1431
1432   // Return false if no candidates exist.
1433   if (!MI && !Sub)
1434     return false;
1435
1436   // The single candidate is called MI.
1437   if (!MI) MI = Sub;
1438
1439   int NewOpC = -1;
1440   MIOpC = MI->getOpcode();
1441   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1442     NewOpC = MIOpC;
1443   else {
1444     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1445     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1446       NewOpC = MIOpC;
1447   }
1448
1449   // FIXME: On the non-embedded POWER architectures, only some of the record
1450   // forms are fast, and we should use only the fast ones.
1451
1452   // The defining instruction has a record form (or is already a record
1453   // form). It is possible, however, that we'll need to reverse the condition
1454   // code of the users.
1455   if (NewOpC == -1)
1456     return false;
1457
1458   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1459   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1460
1461   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1462   // needs to be updated to be based on SUB.  Push the condition code
1463   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1464   // condition code of these operands will be modified.
1465   bool ShouldSwap = false;
1466   if (Sub) {
1467     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1468       Sub->getOperand(2).getReg() == SrcReg;
1469
1470     // The operands to subf are the opposite of sub, so only in the fixed-point
1471     // case, invert the order.
1472     ShouldSwap = !ShouldSwap;
1473   }
1474
1475   if (ShouldSwap)
1476     for (MachineRegisterInfo::use_instr_iterator
1477          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1478          I != IE; ++I) {
1479       MachineInstr *UseMI = &*I;
1480       if (UseMI->getOpcode() == PPC::BCC) {
1481         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1482         assert((!equalityOnly ||
1483                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1484                "Invalid predicate for equality-only optimization");
1485         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1486                                 PPC::getSwappedPredicate(Pred)));
1487       } else if (UseMI->getOpcode() == PPC::ISEL ||
1488                  UseMI->getOpcode() == PPC::ISEL8) {
1489         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1490         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1491                "Invalid CR bit for equality-only optimization");
1492
1493         if (NewSubReg == PPC::sub_lt)
1494           NewSubReg = PPC::sub_gt;
1495         else if (NewSubReg == PPC::sub_gt)
1496           NewSubReg = PPC::sub_lt;
1497
1498         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1499                                                  NewSubReg));
1500       } else // We need to abort on a user we don't understand.
1501         return false;
1502     }
1503
1504   // Create a new virtual register to hold the value of the CR set by the
1505   // record-form instruction. If the instruction was not previously in
1506   // record form, then set the kill flag on the CR.
1507   CmpInstr->eraseFromParent();
1508
1509   MachineBasicBlock::iterator MII = MI;
1510   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1511           get(TargetOpcode::COPY), CRReg)
1512     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1513
1514   if (MIOpC != NewOpC) {
1515     // We need to be careful here: we're replacing one instruction with
1516     // another, and we need to make sure that we get all of the right
1517     // implicit uses and defs. On the other hand, the caller may be holding
1518     // an iterator to this instruction, and so we can't delete it (this is
1519     // specifically the case if this is the instruction directly after the
1520     // compare).
1521
1522     const MCInstrDesc &NewDesc = get(NewOpC);
1523     MI->setDesc(NewDesc);
1524
1525     if (NewDesc.ImplicitDefs)
1526       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1527            *ImpDefs; ++ImpDefs)
1528         if (!MI->definesRegister(*ImpDefs))
1529           MI->addOperand(*MI->getParent()->getParent(),
1530                          MachineOperand::CreateReg(*ImpDefs, true, true));
1531     if (NewDesc.ImplicitUses)
1532       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1533            *ImpUses; ++ImpUses)
1534         if (!MI->readsRegister(*ImpUses))
1535           MI->addOperand(*MI->getParent()->getParent(),
1536                          MachineOperand::CreateReg(*ImpUses, false, true));
1537   }
1538
1539   // Modify the condition code of operands in OperandsToUpdate.
1540   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1541   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1542   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1543     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1544
1545   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1546     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1547
1548   return true;
1549 }
1550
1551 /// GetInstSize - Return the number of bytes of code the specified
1552 /// instruction may be.  This returns the maximum number of bytes.
1553 ///
1554 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1555   unsigned Opcode = MI->getOpcode();
1556
1557   if (Opcode == PPC::INLINEASM) {
1558     const MachineFunction *MF = MI->getParent()->getParent();
1559     const char *AsmStr = MI->getOperand(0).getSymbolName();
1560     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1561   } else {
1562     const MCInstrDesc &Desc = get(Opcode);
1563     return Desc.getSize();
1564   }
1565 }
1566
1567
1568 #undef DEBUG_TYPE
1569 #define DEBUG_TYPE "ppc-vsx-copy"
1570
1571 namespace llvm {
1572   void initializePPCVSXCopyPass(PassRegistry&);
1573 }
1574
1575 namespace {
1576   // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1577   // (Altivec and scalar floating-point registers), we need to transform the
1578   // copies into subregister copies with other restrictions.
1579   struct PPCVSXCopy : public MachineFunctionPass {
1580     static char ID;
1581     PPCVSXCopy() : MachineFunctionPass(ID) {
1582       initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1583     }
1584
1585     const PPCTargetMachine *TM;
1586     const PPCInstrInfo *TII;
1587
1588     bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1589                       MachineRegisterInfo &MRI) {
1590       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1591         return RC->hasSubClassEq(MRI.getRegClass(Reg));
1592       } else if (RC->contains(Reg)) {
1593         return true;
1594       }
1595
1596       return false;
1597     }
1598
1599     bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1600       return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1601     }
1602
1603     bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1604       return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1605     }
1606
1607     bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1608       return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1609     }
1610
1611 protected:
1612     bool processBlock(MachineBasicBlock &MBB) {
1613       bool Changed = false;
1614
1615       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1616       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1617            I != IE; ++I) {
1618         MachineInstr *MI = I;
1619         if (!MI->isFullCopy())
1620           continue;
1621
1622         MachineOperand &DstMO = MI->getOperand(0);
1623         MachineOperand &SrcMO = MI->getOperand(1);
1624
1625         if ( IsVSReg(DstMO.getReg(), MRI) &&
1626             !IsVSReg(SrcMO.getReg(), MRI)) {
1627           // This is a copy *to* a VSX register from a non-VSX register.
1628           Changed = true;
1629
1630           const TargetRegisterClass *SrcRC =
1631             IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1632                                            &PPC::VSLRCRegClass;
1633           assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1634                   IsVRReg(SrcMO.getReg(), MRI)) &&
1635                  "Unknown source for a VSX copy");
1636
1637           unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1638           BuildMI(MBB, MI, MI->getDebugLoc(),
1639                   TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1640             .addImm(1) // add 1, not 0, because there is no implicit clearing
1641                        // of the high bits.
1642             .addOperand(SrcMO)
1643             .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1644                                                    PPC::sub_64);
1645
1646           // The source of the original copy is now the new virtual register.
1647           SrcMO.setReg(NewVReg);
1648         } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1649                     IsVSReg(SrcMO.getReg(), MRI)) {
1650           // This is a copy *from* a VSX register to a non-VSX register.
1651           Changed = true;
1652
1653           const TargetRegisterClass *DstRC =
1654             IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1655                                            &PPC::VSLRCRegClass;
1656           assert((IsF8Reg(DstMO.getReg(), MRI) ||
1657                   IsVRReg(DstMO.getReg(), MRI)) &&
1658                  "Unknown destination for a VSX copy");
1659
1660           // Copy the VSX value into a new VSX register of the correct subclass.
1661           unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1662           BuildMI(MBB, MI, MI->getDebugLoc(),
1663                   TII->get(TargetOpcode::COPY), NewVReg)
1664             .addOperand(SrcMO);
1665
1666           // Transform the original copy into a subregister extraction copy.
1667           SrcMO.setReg(NewVReg);
1668           SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1669                                                          PPC::sub_64);
1670         }
1671       }
1672
1673       return Changed;
1674     }
1675
1676 public:
1677     virtual bool runOnMachineFunction(MachineFunction &MF) {
1678       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1679       TII = TM->getInstrInfo();
1680
1681       bool Changed = false;
1682
1683       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1684         MachineBasicBlock &B = *I++;
1685         if (processBlock(B))
1686           Changed = true;
1687       }
1688
1689       return Changed;
1690     }
1691
1692     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1693       MachineFunctionPass::getAnalysisUsage(AU);
1694     }
1695   };
1696 }
1697
1698 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
1699                 "PowerPC VSX Copy Legalization", false, false)
1700
1701 char PPCVSXCopy::ID = 0;
1702 FunctionPass*
1703 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
1704
1705 #undef DEBUG_TYPE
1706 #define DEBUG_TYPE "ppc-early-ret"
1707 STATISTIC(NumBCLR, "Number of early conditional returns");
1708 STATISTIC(NumBLR,  "Number of early returns");
1709
1710 namespace llvm {
1711   void initializePPCEarlyReturnPass(PassRegistry&);
1712 }
1713
1714 namespace {
1715   // PPCEarlyReturn pass - For simple functions without epilogue code, move
1716   // returns up, and create conditional returns, to avoid unnecessary
1717   // branch-to-blr sequences.
1718   struct PPCEarlyReturn : public MachineFunctionPass {
1719     static char ID;
1720     PPCEarlyReturn() : MachineFunctionPass(ID) {
1721       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1722     }
1723
1724     const PPCTargetMachine *TM;
1725     const PPCInstrInfo *TII;
1726
1727 protected:
1728     bool processBlock(MachineBasicBlock &ReturnMBB) {
1729       bool Changed = false;
1730
1731       MachineBasicBlock::iterator I = ReturnMBB.begin();
1732       I = ReturnMBB.SkipPHIsAndLabels(I);
1733
1734       // The block must be essentially empty except for the blr.
1735       if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1736           I != ReturnMBB.getLastNonDebugInstr())
1737         return Changed;
1738
1739       SmallVector<MachineBasicBlock*, 8> PredToRemove;
1740       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1741            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1742         bool OtherReference = false, BlockChanged = false;
1743         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1744           if (J->getOpcode() == PPC::B) {
1745             if (J->getOperand(0).getMBB() == &ReturnMBB) {
1746               // This is an unconditional branch to the return. Replace the
1747               // branch with a blr.
1748               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1749               MachineBasicBlock::iterator K = J--;
1750               K->eraseFromParent();
1751               BlockChanged = true;
1752               ++NumBLR;
1753               continue;
1754             }
1755           } else if (J->getOpcode() == PPC::BCC) {
1756             if (J->getOperand(2).getMBB() == &ReturnMBB) {
1757               // This is a conditional branch to the return. Replace the branch
1758               // with a bclr.
1759               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
1760                 .addImm(J->getOperand(0).getImm())
1761                 .addReg(J->getOperand(1).getReg());
1762               MachineBasicBlock::iterator K = J--;
1763               K->eraseFromParent();
1764               BlockChanged = true;
1765               ++NumBCLR;
1766               continue;
1767             }
1768           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
1769             if (J->getOperand(1).getMBB() == &ReturnMBB) {
1770               // This is a conditional branch to the return. Replace the branch
1771               // with a bclr.
1772               BuildMI(**PI, J, J->getDebugLoc(),
1773                       TII->get(J->getOpcode() == PPC::BC ?
1774                                PPC::BCLR : PPC::BCLRn))
1775                 .addReg(J->getOperand(0).getReg());
1776               MachineBasicBlock::iterator K = J--;
1777               K->eraseFromParent();
1778               BlockChanged = true;
1779               ++NumBCLR;
1780               continue;
1781             }
1782           } else if (J->isBranch()) {
1783             if (J->isIndirectBranch()) {
1784               if (ReturnMBB.hasAddressTaken())
1785                 OtherReference = true;
1786             } else
1787               for (unsigned i = 0; i < J->getNumOperands(); ++i)
1788                 if (J->getOperand(i).isMBB() &&
1789                     J->getOperand(i).getMBB() == &ReturnMBB)
1790                   OtherReference = true;
1791           } else if (!J->isTerminator() && !J->isDebugValue())
1792             break;
1793
1794           if (J == (*PI)->begin())
1795             break;
1796
1797           --J;
1798         }
1799
1800         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1801           OtherReference = true;
1802
1803         // Predecessors are stored in a vector and can't be removed here.
1804         if (!OtherReference && BlockChanged) {
1805           PredToRemove.push_back(*PI);
1806         }
1807
1808         if (BlockChanged)
1809           Changed = true;
1810       }
1811
1812       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1813         PredToRemove[i]->removeSuccessor(&ReturnMBB);
1814
1815       if (Changed && !ReturnMBB.hasAddressTaken()) {
1816         // We now might be able to merge this blr-only block into its
1817         // by-layout predecessor.
1818         if (ReturnMBB.pred_size() == 1 &&
1819             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1820           // Move the blr into the preceding block.
1821           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1822           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1823           PrevMBB.removeSuccessor(&ReturnMBB);
1824         }
1825
1826         if (ReturnMBB.pred_empty())
1827           ReturnMBB.eraseFromParent();
1828       }
1829
1830       return Changed;
1831     }
1832
1833 public:
1834     virtual bool runOnMachineFunction(MachineFunction &MF) {
1835       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1836       TII = TM->getInstrInfo();
1837
1838       bool Changed = false;
1839
1840       // If the function does not have at least two blocks, then there is
1841       // nothing to do.
1842       if (MF.size() < 2)
1843         return Changed;
1844
1845       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1846         MachineBasicBlock &B = *I++;
1847         if (processBlock(B))
1848           Changed = true;
1849       }
1850
1851       return Changed;
1852     }
1853
1854     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1855       MachineFunctionPass::getAnalysisUsage(AU);
1856     }
1857   };
1858 }
1859
1860 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1861                 "PowerPC Early-Return Creation", false, false)
1862
1863 char PPCEarlyReturn::ID = 0;
1864 FunctionPass*
1865 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }