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