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/MC/MCInst.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "ppc-instr-info"
44 
45 #define GET_INSTRMAP_INFO
46 #define GET_INSTRINFO_CTOR_DTOR
47 #include "PPCGenInstrInfo.inc"
48 
49 STATISTIC(NumStoreSPILLVSRRCAsVec,
50           "Number of spillvsrrc spilled to stack as vec");
51 STATISTIC(NumStoreSPILLVSRRCAsGpr,
52           "Number of spillvsrrc spilled to stack as gpr");
53 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
54 
55 static cl::
56 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
57             cl::desc("Disable analysis for CTR loops"));
58 
59 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
60 cl::desc("Disable compare instruction optimization"), cl::Hidden);
61 
62 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
63 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
64 cl::Hidden);
65 
66 static cl::opt<bool>
67 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
68   cl::desc("Use the old (incorrect) instruction latency calculation"));
69 
70 // Pin the vtable to this file.
71 void PPCInstrInfo::anchor() {}
72 
73 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
74     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
75                       /* CatchRetOpcode */ -1,
76                       STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
77       Subtarget(STI), RI(STI.getTargetMachine()) {}
78 
79 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
80 /// this target when scheduling the DAG.
81 ScheduleHazardRecognizer *
82 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
83                                            const ScheduleDAG *DAG) const {
84   unsigned Directive =
85       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
86   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
87       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
88     const InstrItineraryData *II =
89         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
90     return new ScoreboardHazardRecognizer(II, DAG);
91   }
92 
93   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
94 }
95 
96 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
97 /// to use for this target when scheduling the DAG.
98 ScheduleHazardRecognizer *
99 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
100                                                  const ScheduleDAG *DAG) const {
101   unsigned Directive =
102       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
103 
104   // FIXME: Leaving this as-is until we have POWER9 scheduling info
105   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
106     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
107 
108   // Most subtargets use a PPC970 recognizer.
109   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
110       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
111     assert(DAG->TII && "No InstrInfo?");
112 
113     return new PPCHazardRecognizer970(*DAG);
114   }
115 
116   return new ScoreboardHazardRecognizer(II, DAG);
117 }
118 
119 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
120                                        const MachineInstr &MI,
121                                        unsigned *PredCost) const {
122   if (!ItinData || UseOldLatencyCalc)
123     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
124 
125   // The default implementation of getInstrLatency calls getStageLatency, but
126   // getStageLatency does not do the right thing for us. While we have
127   // itinerary, most cores are fully pipelined, and so the itineraries only
128   // express the first part of the pipeline, not every stage. Instead, we need
129   // to use the listed output operand cycle number (using operand 0 here, which
130   // is an output).
131 
132   unsigned Latency = 1;
133   unsigned DefClass = MI.getDesc().getSchedClass();
134   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
135     const MachineOperand &MO = MI.getOperand(i);
136     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
137       continue;
138 
139     int Cycle = ItinData->getOperandCycle(DefClass, i);
140     if (Cycle < 0)
141       continue;
142 
143     Latency = std::max(Latency, (unsigned) Cycle);
144   }
145 
146   return Latency;
147 }
148 
149 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
150                                     const MachineInstr &DefMI, unsigned DefIdx,
151                                     const MachineInstr &UseMI,
152                                     unsigned UseIdx) const {
153   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
154                                                    UseMI, UseIdx);
155 
156   if (!DefMI.getParent())
157     return Latency;
158 
159   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
160   unsigned Reg = DefMO.getReg();
161 
162   bool IsRegCR;
163   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
164     const MachineRegisterInfo *MRI =
165         &DefMI.getParent()->getParent()->getRegInfo();
166     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
167               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
168   } else {
169     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
170               PPC::CRBITRCRegClass.contains(Reg);
171   }
172 
173   if (UseMI.isBranch() && IsRegCR) {
174     if (Latency < 0)
175       Latency = getInstrLatency(ItinData, DefMI);
176 
177     // On some cores, there is an additional delay between writing to a condition
178     // register, and using it from a branch.
179     unsigned Directive = Subtarget.getDarwinDirective();
180     switch (Directive) {
181     default: break;
182     case PPC::DIR_7400:
183     case PPC::DIR_750:
184     case PPC::DIR_970:
185     case PPC::DIR_E5500:
186     case PPC::DIR_PWR4:
187     case PPC::DIR_PWR5:
188     case PPC::DIR_PWR5X:
189     case PPC::DIR_PWR6:
190     case PPC::DIR_PWR6X:
191     case PPC::DIR_PWR7:
192     case PPC::DIR_PWR8:
193     // FIXME: Is this needed for POWER9?
194       Latency += 2;
195       break;
196     }
197   }
198 
199   return Latency;
200 }
201 
202 // This function does not list all associative and commutative operations, but
203 // only those worth feeding through the machine combiner in an attempt to
204 // reduce the critical path. Mostly, this means floating-point operations,
205 // because they have high latencies (compared to other operations, such and
206 // and/or, which are also associative and commutative, but have low latencies).
207 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
208   switch (Inst.getOpcode()) {
209   // FP Add:
210   case PPC::FADD:
211   case PPC::FADDS:
212   // FP Multiply:
213   case PPC::FMUL:
214   case PPC::FMULS:
215   // Altivec Add:
216   case PPC::VADDFP:
217   // VSX Add:
218   case PPC::XSADDDP:
219   case PPC::XVADDDP:
220   case PPC::XVADDSP:
221   case PPC::XSADDSP:
222   // VSX Multiply:
223   case PPC::XSMULDP:
224   case PPC::XVMULDP:
225   case PPC::XVMULSP:
226   case PPC::XSMULSP:
227   // QPX Add:
228   case PPC::QVFADD:
229   case PPC::QVFADDS:
230   case PPC::QVFADDSs:
231   // QPX Multiply:
232   case PPC::QVFMUL:
233   case PPC::QVFMULS:
234   case PPC::QVFMULSs:
235     return true;
236   default:
237     return false;
238   }
239 }
240 
241 bool PPCInstrInfo::getMachineCombinerPatterns(
242     MachineInstr &Root,
243     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
244   // Using the machine combiner in this way is potentially expensive, so
245   // restrict to when aggressive optimizations are desired.
246   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
247     return false;
248 
249   // FP reassociation is only legal when we don't need strict IEEE semantics.
250   if (!Root.getParent()->getParent()->getTarget().Options.UnsafeFPMath)
251     return false;
252 
253   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
254 }
255 
256 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
257 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
258                                          unsigned &SrcReg, unsigned &DstReg,
259                                          unsigned &SubIdx) const {
260   switch (MI.getOpcode()) {
261   default: return false;
262   case PPC::EXTSW:
263   case PPC::EXTSW_32_64:
264     SrcReg = MI.getOperand(1).getReg();
265     DstReg = MI.getOperand(0).getReg();
266     SubIdx = PPC::sub_32;
267     return true;
268   }
269 }
270 
271 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
272                                            int &FrameIndex) const {
273   // Note: This list must be kept consistent with LoadRegFromStackSlot.
274   switch (MI.getOpcode()) {
275   default: break;
276   case PPC::LD:
277   case PPC::LWZ:
278   case PPC::LFS:
279   case PPC::LFD:
280   case PPC::RESTORE_CR:
281   case PPC::RESTORE_CRBIT:
282   case PPC::LVX:
283   case PPC::LXVD2X:
284   case PPC::LXVX:
285   case PPC::QVLFDX:
286   case PPC::QVLFSXs:
287   case PPC::QVLFDXb:
288   case PPC::RESTORE_VRSAVE:
289   case PPC::SPILLTOVSR_LD:
290     // Check for the operands added by addFrameReference (the immediate is the
291     // offset which defaults to 0).
292     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
293         MI.getOperand(2).isFI()) {
294       FrameIndex = MI.getOperand(2).getIndex();
295       return MI.getOperand(0).getReg();
296     }
297     break;
298   }
299   return 0;
300 }
301 
302 // For opcodes with the ReMaterializable flag set, this function is called to
303 // verify the instruction is really rematable.
304 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
305                                                      AliasAnalysis *AA) const {
306   switch (MI.getOpcode()) {
307   default:
308     // This function should only be called for opcodes with the ReMaterializable
309     // flag set.
310     llvm_unreachable("Unknown rematerializable operation!");
311     break;
312   case PPC::LI:
313   case PPC::LI8:
314   case PPC::LIS:
315   case PPC::LIS8:
316   case PPC::QVGPCI:
317   case PPC::ADDIStocHA:
318   case PPC::ADDItocL:
319   case PPC::LOAD_STACK_GUARD:
320     return true;
321   }
322   return false;
323 }
324 
325 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
326                                           int &FrameIndex) const {
327   // Note: This list must be kept consistent with StoreRegToStackSlot.
328   switch (MI.getOpcode()) {
329   default: break;
330   case PPC::STD:
331   case PPC::STW:
332   case PPC::STFS:
333   case PPC::STFD:
334   case PPC::SPILL_CR:
335   case PPC::SPILL_CRBIT:
336   case PPC::STVX:
337   case PPC::STXVD2X:
338   case PPC::STXVX:
339   case PPC::QVSTFDX:
340   case PPC::QVSTFSXs:
341   case PPC::QVSTFDXb:
342   case PPC::SPILL_VRSAVE:
343   case PPC::SPILLTOVSR_ST:
344     // Check for the operands added by addFrameReference (the immediate is the
345     // offset which defaults to 0).
346     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
347         MI.getOperand(2).isFI()) {
348       FrameIndex = MI.getOperand(2).getIndex();
349       return MI.getOperand(0).getReg();
350     }
351     break;
352   }
353   return 0;
354 }
355 
356 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
357                                                    unsigned OpIdx1,
358                                                    unsigned OpIdx2) const {
359   MachineFunction &MF = *MI.getParent()->getParent();
360 
361   // Normal instructions can be commuted the obvious way.
362   if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMIo)
363     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
364   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
365   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
366   // changing the relative order of the mask operands might change what happens
367   // to the high-bits of the mask (and, thus, the result).
368 
369   // Cannot commute if it has a non-zero rotate count.
370   if (MI.getOperand(3).getImm() != 0)
371     return nullptr;
372 
373   // If we have a zero rotate count, we have:
374   //   M = mask(MB,ME)
375   //   Op0 = (Op1 & ~M) | (Op2 & M)
376   // Change this to:
377   //   M = mask((ME+1)&31, (MB-1)&31)
378   //   Op0 = (Op2 & ~M) | (Op1 & M)
379 
380   // Swap op1/op2
381   assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
382          "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMIo.");
383   unsigned Reg0 = MI.getOperand(0).getReg();
384   unsigned Reg1 = MI.getOperand(1).getReg();
385   unsigned Reg2 = MI.getOperand(2).getReg();
386   unsigned SubReg1 = MI.getOperand(1).getSubReg();
387   unsigned SubReg2 = MI.getOperand(2).getSubReg();
388   bool Reg1IsKill = MI.getOperand(1).isKill();
389   bool Reg2IsKill = MI.getOperand(2).isKill();
390   bool ChangeReg0 = false;
391   // If machine instrs are no longer in two-address forms, update
392   // destination register as well.
393   if (Reg0 == Reg1) {
394     // Must be two address instruction!
395     assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
396            "Expecting a two-address instruction!");
397     assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
398     Reg2IsKill = false;
399     ChangeReg0 = true;
400   }
401 
402   // Masks.
403   unsigned MB = MI.getOperand(4).getImm();
404   unsigned ME = MI.getOperand(5).getImm();
405 
406   // We can't commute a trivial mask (there is no way to represent an all-zero
407   // mask).
408   if (MB == 0 && ME == 31)
409     return nullptr;
410 
411   if (NewMI) {
412     // Create a new instruction.
413     unsigned Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
414     bool Reg0IsDead = MI.getOperand(0).isDead();
415     return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
416         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
417         .addReg(Reg2, getKillRegState(Reg2IsKill))
418         .addReg(Reg1, getKillRegState(Reg1IsKill))
419         .addImm((ME + 1) & 31)
420         .addImm((MB - 1) & 31);
421   }
422 
423   if (ChangeReg0) {
424     MI.getOperand(0).setReg(Reg2);
425     MI.getOperand(0).setSubReg(SubReg2);
426   }
427   MI.getOperand(2).setReg(Reg1);
428   MI.getOperand(1).setReg(Reg2);
429   MI.getOperand(2).setSubReg(SubReg1);
430   MI.getOperand(1).setSubReg(SubReg2);
431   MI.getOperand(2).setIsKill(Reg1IsKill);
432   MI.getOperand(1).setIsKill(Reg2IsKill);
433 
434   // Swap the mask around.
435   MI.getOperand(4).setImm((ME + 1) & 31);
436   MI.getOperand(5).setImm((MB - 1) & 31);
437   return &MI;
438 }
439 
440 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1,
441                                          unsigned &SrcOpIdx2) const {
442   // For VSX A-Type FMA instructions, it is the first two operands that can be
443   // commuted, however, because the non-encoded tied input operand is listed
444   // first, the operands to swap are actually the second and third.
445 
446   int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
447   if (AltOpc == -1)
448     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
449 
450   // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
451   // and SrcOpIdx2.
452   return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
453 }
454 
455 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
456                               MachineBasicBlock::iterator MI) const {
457   // This function is used for scheduling, and the nop wanted here is the type
458   // that terminates dispatch groups on the POWER cores.
459   unsigned Directive = Subtarget.getDarwinDirective();
460   unsigned Opcode;
461   switch (Directive) {
462   default:            Opcode = PPC::NOP; break;
463   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
464   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
465   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
466   // FIXME: Update when POWER9 scheduling model is ready.
467   case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
468   }
469 
470   DebugLoc DL;
471   BuildMI(MBB, MI, DL, get(Opcode));
472 }
473 
474 /// Return the noop instruction to use for a noop.
475 void PPCInstrInfo::getNoop(MCInst &NopInst) const {
476   NopInst.setOpcode(PPC::NOP);
477 }
478 
479 // Branch analysis.
480 // Note: If the condition register is set to CTR or CTR8 then this is a
481 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
482 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
483                                  MachineBasicBlock *&TBB,
484                                  MachineBasicBlock *&FBB,
485                                  SmallVectorImpl<MachineOperand> &Cond,
486                                  bool AllowModify) const {
487   bool isPPC64 = Subtarget.isPPC64();
488 
489   // If the block has no terminators, it just falls into the block after it.
490   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
491   if (I == MBB.end())
492     return false;
493 
494   if (!isUnpredicatedTerminator(*I))
495     return false;
496 
497   // Get the last instruction in the block.
498   MachineInstr &LastInst = *I;
499 
500   // If there is only one terminator instruction, process it.
501   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
502     if (LastInst.getOpcode() == PPC::B) {
503       if (!LastInst.getOperand(0).isMBB())
504         return true;
505       TBB = LastInst.getOperand(0).getMBB();
506       return false;
507     } else if (LastInst.getOpcode() == PPC::BCC) {
508       if (!LastInst.getOperand(2).isMBB())
509         return true;
510       // Block ends with fall-through condbranch.
511       TBB = LastInst.getOperand(2).getMBB();
512       Cond.push_back(LastInst.getOperand(0));
513       Cond.push_back(LastInst.getOperand(1));
514       return false;
515     } else if (LastInst.getOpcode() == PPC::BC) {
516       if (!LastInst.getOperand(1).isMBB())
517         return true;
518       // Block ends with fall-through condbranch.
519       TBB = LastInst.getOperand(1).getMBB();
520       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
521       Cond.push_back(LastInst.getOperand(0));
522       return false;
523     } else if (LastInst.getOpcode() == PPC::BCn) {
524       if (!LastInst.getOperand(1).isMBB())
525         return true;
526       // Block ends with fall-through condbranch.
527       TBB = LastInst.getOperand(1).getMBB();
528       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
529       Cond.push_back(LastInst.getOperand(0));
530       return false;
531     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
532                LastInst.getOpcode() == PPC::BDNZ) {
533       if (!LastInst.getOperand(0).isMBB())
534         return true;
535       if (DisableCTRLoopAnal)
536         return true;
537       TBB = LastInst.getOperand(0).getMBB();
538       Cond.push_back(MachineOperand::CreateImm(1));
539       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
540                                                true));
541       return false;
542     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
543                LastInst.getOpcode() == PPC::BDZ) {
544       if (!LastInst.getOperand(0).isMBB())
545         return true;
546       if (DisableCTRLoopAnal)
547         return true;
548       TBB = LastInst.getOperand(0).getMBB();
549       Cond.push_back(MachineOperand::CreateImm(0));
550       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
551                                                true));
552       return false;
553     }
554 
555     // Otherwise, don't know what this is.
556     return true;
557   }
558 
559   // Get the instruction before it if it's a terminator.
560   MachineInstr &SecondLastInst = *I;
561 
562   // If there are three terminators, we don't know what sort of block this is.
563   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
564     return true;
565 
566   // If the block ends with PPC::B and PPC:BCC, handle it.
567   if (SecondLastInst.getOpcode() == PPC::BCC &&
568       LastInst.getOpcode() == PPC::B) {
569     if (!SecondLastInst.getOperand(2).isMBB() ||
570         !LastInst.getOperand(0).isMBB())
571       return true;
572     TBB = SecondLastInst.getOperand(2).getMBB();
573     Cond.push_back(SecondLastInst.getOperand(0));
574     Cond.push_back(SecondLastInst.getOperand(1));
575     FBB = LastInst.getOperand(0).getMBB();
576     return false;
577   } else if (SecondLastInst.getOpcode() == PPC::BC &&
578              LastInst.getOpcode() == PPC::B) {
579     if (!SecondLastInst.getOperand(1).isMBB() ||
580         !LastInst.getOperand(0).isMBB())
581       return true;
582     TBB = SecondLastInst.getOperand(1).getMBB();
583     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
584     Cond.push_back(SecondLastInst.getOperand(0));
585     FBB = LastInst.getOperand(0).getMBB();
586     return false;
587   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
588              LastInst.getOpcode() == PPC::B) {
589     if (!SecondLastInst.getOperand(1).isMBB() ||
590         !LastInst.getOperand(0).isMBB())
591       return true;
592     TBB = SecondLastInst.getOperand(1).getMBB();
593     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
594     Cond.push_back(SecondLastInst.getOperand(0));
595     FBB = LastInst.getOperand(0).getMBB();
596     return false;
597   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
598               SecondLastInst.getOpcode() == PPC::BDNZ) &&
599              LastInst.getOpcode() == PPC::B) {
600     if (!SecondLastInst.getOperand(0).isMBB() ||
601         !LastInst.getOperand(0).isMBB())
602       return true;
603     if (DisableCTRLoopAnal)
604       return true;
605     TBB = SecondLastInst.getOperand(0).getMBB();
606     Cond.push_back(MachineOperand::CreateImm(1));
607     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
608                                              true));
609     FBB = LastInst.getOperand(0).getMBB();
610     return false;
611   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
612               SecondLastInst.getOpcode() == PPC::BDZ) &&
613              LastInst.getOpcode() == PPC::B) {
614     if (!SecondLastInst.getOperand(0).isMBB() ||
615         !LastInst.getOperand(0).isMBB())
616       return true;
617     if (DisableCTRLoopAnal)
618       return true;
619     TBB = SecondLastInst.getOperand(0).getMBB();
620     Cond.push_back(MachineOperand::CreateImm(0));
621     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
622                                              true));
623     FBB = LastInst.getOperand(0).getMBB();
624     return false;
625   }
626 
627   // If the block ends with two PPC:Bs, handle it.  The second one is not
628   // executed, so remove it.
629   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
630     if (!SecondLastInst.getOperand(0).isMBB())
631       return true;
632     TBB = SecondLastInst.getOperand(0).getMBB();
633     I = LastInst;
634     if (AllowModify)
635       I->eraseFromParent();
636     return false;
637   }
638 
639   // Otherwise, can't handle this.
640   return true;
641 }
642 
643 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
644                                     int *BytesRemoved) const {
645   assert(!BytesRemoved && "code size not handled");
646 
647   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
648   if (I == MBB.end())
649     return 0;
650 
651   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
652       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
653       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
654       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
655     return 0;
656 
657   // Remove the branch.
658   I->eraseFromParent();
659 
660   I = MBB.end();
661 
662   if (I == MBB.begin()) return 1;
663   --I;
664   if (I->getOpcode() != PPC::BCC &&
665       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
666       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
667       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
668     return 1;
669 
670   // Remove the branch.
671   I->eraseFromParent();
672   return 2;
673 }
674 
675 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
676                                     MachineBasicBlock *TBB,
677                                     MachineBasicBlock *FBB,
678                                     ArrayRef<MachineOperand> Cond,
679                                     const DebugLoc &DL,
680                                     int *BytesAdded) const {
681   // Shouldn't be a fall through.
682   assert(TBB && "insertBranch must not be told to insert a fallthrough");
683   assert((Cond.size() == 2 || Cond.size() == 0) &&
684          "PPC branch conditions have two components!");
685   assert(!BytesAdded && "code size not handled");
686 
687   bool isPPC64 = Subtarget.isPPC64();
688 
689   // One-way branch.
690   if (!FBB) {
691     if (Cond.empty())   // Unconditional branch
692       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
693     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
694       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
695                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
696                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
697     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
698       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
699     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
700       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
701     else                // Conditional branch
702       BuildMI(&MBB, DL, get(PPC::BCC))
703           .addImm(Cond[0].getImm())
704           .add(Cond[1])
705           .addMBB(TBB);
706     return 1;
707   }
708 
709   // Two-way Conditional Branch.
710   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
711     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
712                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
713                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
714   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
715     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
716   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
717     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
718   else
719     BuildMI(&MBB, DL, get(PPC::BCC))
720         .addImm(Cond[0].getImm())
721         .add(Cond[1])
722         .addMBB(TBB);
723   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
724   return 2;
725 }
726 
727 // Select analysis.
728 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
729                 ArrayRef<MachineOperand> Cond,
730                 unsigned TrueReg, unsigned FalseReg,
731                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
732   if (Cond.size() != 2)
733     return false;
734 
735   // If this is really a bdnz-like condition, then it cannot be turned into a
736   // select.
737   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
738     return false;
739 
740   // Check register classes.
741   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
742   const TargetRegisterClass *RC =
743     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
744   if (!RC)
745     return false;
746 
747   // isel is for regular integer GPRs only.
748   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
749       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
750       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
751       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
752     return false;
753 
754   // FIXME: These numbers are for the A2, how well they work for other cores is
755   // an open question. On the A2, the isel instruction has a 2-cycle latency
756   // but single-cycle throughput. These numbers are used in combination with
757   // the MispredictPenalty setting from the active SchedMachineModel.
758   CondCycles = 1;
759   TrueCycles = 1;
760   FalseCycles = 1;
761 
762   return true;
763 }
764 
765 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
766                                 MachineBasicBlock::iterator MI,
767                                 const DebugLoc &dl, unsigned DestReg,
768                                 ArrayRef<MachineOperand> Cond, unsigned TrueReg,
769                                 unsigned FalseReg) const {
770   assert(Cond.size() == 2 &&
771          "PPC branch conditions have two components!");
772 
773   // Get the register classes.
774   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
775   const TargetRegisterClass *RC =
776     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
777   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
778 
779   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
780                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
781   assert((Is64Bit ||
782           PPC::GPRCRegClass.hasSubClassEq(RC) ||
783           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
784          "isel is for regular integer GPRs only");
785 
786   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
787   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
788 
789   unsigned SubIdx = 0;
790   bool SwapOps = false;
791   switch (SelectPred) {
792   case PPC::PRED_EQ:
793   case PPC::PRED_EQ_MINUS:
794   case PPC::PRED_EQ_PLUS:
795       SubIdx = PPC::sub_eq; SwapOps = false; break;
796   case PPC::PRED_NE:
797   case PPC::PRED_NE_MINUS:
798   case PPC::PRED_NE_PLUS:
799       SubIdx = PPC::sub_eq; SwapOps = true; break;
800   case PPC::PRED_LT:
801   case PPC::PRED_LT_MINUS:
802   case PPC::PRED_LT_PLUS:
803       SubIdx = PPC::sub_lt; SwapOps = false; break;
804   case PPC::PRED_GE:
805   case PPC::PRED_GE_MINUS:
806   case PPC::PRED_GE_PLUS:
807       SubIdx = PPC::sub_lt; SwapOps = true; break;
808   case PPC::PRED_GT:
809   case PPC::PRED_GT_MINUS:
810   case PPC::PRED_GT_PLUS:
811       SubIdx = PPC::sub_gt; SwapOps = false; break;
812   case PPC::PRED_LE:
813   case PPC::PRED_LE_MINUS:
814   case PPC::PRED_LE_PLUS:
815       SubIdx = PPC::sub_gt; SwapOps = true; break;
816   case PPC::PRED_UN:
817   case PPC::PRED_UN_MINUS:
818   case PPC::PRED_UN_PLUS:
819       SubIdx = PPC::sub_un; SwapOps = false; break;
820   case PPC::PRED_NU:
821   case PPC::PRED_NU_MINUS:
822   case PPC::PRED_NU_PLUS:
823       SubIdx = PPC::sub_un; SwapOps = true; break;
824   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
825   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
826   }
827 
828   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
829            SecondReg = SwapOps ? TrueReg  : FalseReg;
830 
831   // The first input register of isel cannot be r0. If it is a member
832   // of a register class that can be r0, then copy it first (the
833   // register allocator should eliminate the copy).
834   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
835       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
836     const TargetRegisterClass *FirstRC =
837       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
838         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
839     unsigned OldFirstReg = FirstReg;
840     FirstReg = MRI.createVirtualRegister(FirstRC);
841     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
842       .addReg(OldFirstReg);
843   }
844 
845   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
846     .addReg(FirstReg).addReg(SecondReg)
847     .addReg(Cond[1].getReg(), 0, SubIdx);
848 }
849 
850 static unsigned getCRBitValue(unsigned CRBit) {
851   unsigned Ret = 4;
852   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
853       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
854       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
855       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
856     Ret = 3;
857   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
858       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
859       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
860       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
861     Ret = 2;
862   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
863       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
864       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
865       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
866     Ret = 1;
867   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
868       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
869       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
870       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
871     Ret = 0;
872 
873   assert(Ret != 4 && "Invalid CR bit register");
874   return Ret;
875 }
876 
877 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
878                                MachineBasicBlock::iterator I,
879                                const DebugLoc &DL, unsigned DestReg,
880                                unsigned SrcReg, bool KillSrc) const {
881   // We can end up with self copies and similar things as a result of VSX copy
882   // legalization. Promote them here.
883   const TargetRegisterInfo *TRI = &getRegisterInfo();
884   if (PPC::F8RCRegClass.contains(DestReg) &&
885       PPC::VSRCRegClass.contains(SrcReg)) {
886     unsigned SuperReg =
887       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
888 
889     if (VSXSelfCopyCrash && SrcReg == SuperReg)
890       llvm_unreachable("nop VSX copy");
891 
892     DestReg = SuperReg;
893   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
894              PPC::VSRCRegClass.contains(DestReg)) {
895     unsigned SuperReg =
896       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
897 
898     if (VSXSelfCopyCrash && DestReg == SuperReg)
899       llvm_unreachable("nop VSX copy");
900 
901     SrcReg = SuperReg;
902   }
903 
904   // Different class register copy
905   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
906       PPC::GPRCRegClass.contains(DestReg)) {
907     unsigned CRReg = getCRFromCRBit(SrcReg);
908     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
909     getKillRegState(KillSrc);
910     // Rotate the CR bit in the CR fields to be the least significant bit and
911     // then mask with 0x1 (MB = ME = 31).
912     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
913        .addReg(DestReg, RegState::Kill)
914        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
915        .addImm(31)
916        .addImm(31);
917     return;
918   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
919       PPC::G8RCRegClass.contains(DestReg)) {
920     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg);
921     getKillRegState(KillSrc);
922     return;
923   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
924       PPC::GPRCRegClass.contains(DestReg)) {
925     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg);
926     getKillRegState(KillSrc);
927     return;
928   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
929              PPC::VSFRCRegClass.contains(DestReg)) {
930     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
931     NumGPRtoVSRSpill++;
932     getKillRegState(KillSrc);
933     return;
934   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
935              PPC::G8RCRegClass.contains(DestReg)) {
936     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
937     getKillRegState(KillSrc);
938     return;
939   }
940 
941   unsigned Opc;
942   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
943     Opc = PPC::OR;
944   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
945     Opc = PPC::OR8;
946   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
947     Opc = PPC::FMR;
948   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
949     Opc = PPC::MCRF;
950   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
951     Opc = PPC::VOR;
952   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
953     // There are two different ways this can be done:
954     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
955     //      issue in VSU pipeline 0.
956     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
957     //      can go to either pipeline.
958     // We'll always use xxlor here, because in practically all cases where
959     // copies are generated, they are close enough to some use that the
960     // lower-latency form is preferable.
961     Opc = PPC::XXLOR;
962   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
963            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
964     Opc = PPC::XXLORf;
965   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
966     Opc = PPC::QVFMR;
967   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
968     Opc = PPC::QVFMRs;
969   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
970     Opc = PPC::QVFMRb;
971   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
972     Opc = PPC::CROR;
973   else
974     llvm_unreachable("Impossible reg-to-reg copy");
975 
976   const MCInstrDesc &MCID = get(Opc);
977   if (MCID.getNumOperands() == 3)
978     BuildMI(MBB, I, DL, MCID, DestReg)
979       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
980   else
981     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
982 }
983 
984 // This function returns true if a CR spill is necessary and false otherwise.
985 bool
986 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
987                                   unsigned SrcReg, bool isKill,
988                                   int FrameIdx,
989                                   const TargetRegisterClass *RC,
990                                   SmallVectorImpl<MachineInstr*> &NewMIs,
991                                   bool &NonRI, bool &SpillsVRS) const{
992   // Note: If additional store instructions are added here,
993   // update isStoreToStackSlot.
994 
995   DebugLoc DL;
996   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
997       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
998     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
999                                        .addReg(SrcReg,
1000                                                getKillRegState(isKill)),
1001                                        FrameIdx));
1002   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1003              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1004     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
1005                                        .addReg(SrcReg,
1006                                                getKillRegState(isKill)),
1007                                        FrameIdx));
1008   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1009     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
1010                                        .addReg(SrcReg,
1011                                                getKillRegState(isKill)),
1012                                        FrameIdx));
1013   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1014     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
1015                                        .addReg(SrcReg,
1016                                                getKillRegState(isKill)),
1017                                        FrameIdx));
1018   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1019     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
1020                                        .addReg(SrcReg,
1021                                                getKillRegState(isKill)),
1022                                        FrameIdx));
1023     return true;
1024   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1025     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
1026                                        .addReg(SrcReg,
1027                                                getKillRegState(isKill)),
1028                                        FrameIdx));
1029     return true;
1030   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1031     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
1032                                        .addReg(SrcReg,
1033                                                getKillRegState(isKill)),
1034                                        FrameIdx));
1035     NonRI = true;
1036   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1037     unsigned Op = Subtarget.hasP9Vector() ? PPC::STXVX : PPC::STXVD2X;
1038     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Op))
1039                                        .addReg(SrcReg,
1040                                                getKillRegState(isKill)),
1041                                        FrameIdx));
1042     NonRI = true;
1043   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1044     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFSTOREf64 : PPC::STXSDX;
1045     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc))
1046                                        .addReg(SrcReg,
1047                                                getKillRegState(isKill)),
1048                                        FrameIdx));
1049     NonRI = true;
1050   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1051     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFSTOREf32 : PPC::STXSSPX;
1052     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc))
1053                                        .addReg(SrcReg,
1054                                                getKillRegState(isKill)),
1055                                        FrameIdx));
1056     NonRI = true;
1057   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1058     assert(Subtarget.isDarwin() &&
1059            "VRSAVE only needs spill/restore on Darwin");
1060     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
1061                                        .addReg(SrcReg,
1062                                                getKillRegState(isKill)),
1063                                        FrameIdx));
1064     SpillsVRS = true;
1065   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1066     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
1067                                        .addReg(SrcReg,
1068                                                getKillRegState(isKill)),
1069                                        FrameIdx));
1070     NonRI = true;
1071   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1072     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
1073                                        .addReg(SrcReg,
1074                                                getKillRegState(isKill)),
1075                                        FrameIdx));
1076     NonRI = true;
1077   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1078     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
1079                                        .addReg(SrcReg,
1080                                                getKillRegState(isKill)),
1081                                        FrameIdx));
1082     NonRI = true;
1083   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1084     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILLTOVSR_ST))
1085                                        .addReg(SrcReg,
1086                                                getKillRegState(isKill)),
1087                                        FrameIdx));
1088   } else {
1089     llvm_unreachable("Unknown regclass!");
1090   }
1091 
1092   return false;
1093 }
1094 
1095 void
1096 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1097                                   MachineBasicBlock::iterator MI,
1098                                   unsigned SrcReg, bool isKill, int FrameIdx,
1099                                   const TargetRegisterClass *RC,
1100                                   const TargetRegisterInfo *TRI) const {
1101   MachineFunction &MF = *MBB.getParent();
1102   SmallVector<MachineInstr*, 4> NewMIs;
1103 
1104   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1105   FuncInfo->setHasSpills();
1106 
1107   // We need to avoid a situation in which the value from a VRRC register is
1108   // spilled using an Altivec instruction and reloaded into a VSRC register
1109   // using a VSX instruction. The issue with this is that the VSX
1110   // load/store instructions swap the doublewords in the vector and the Altivec
1111   // ones don't. The register classes on the spill/reload may be different if
1112   // the register is defined using an Altivec instruction and is then used by a
1113   // VSX instruction.
1114   RC = updatedRC(RC);
1115 
1116   bool NonRI = false, SpillsVRS = false;
1117   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
1118                           NonRI, SpillsVRS))
1119     FuncInfo->setSpillsCR();
1120 
1121   if (SpillsVRS)
1122     FuncInfo->setSpillsVRSAVE();
1123 
1124   if (NonRI)
1125     FuncInfo->setHasNonRISpills();
1126 
1127   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1128     MBB.insert(MI, NewMIs[i]);
1129 
1130   const MachineFrameInfo &MFI = MF.getFrameInfo();
1131   MachineMemOperand *MMO = MF.getMachineMemOperand(
1132       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1133       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1134       MFI.getObjectAlignment(FrameIdx));
1135   NewMIs.back()->addMemOperand(MF, MMO);
1136 }
1137 
1138 bool PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1139                                         unsigned DestReg, int FrameIdx,
1140                                         const TargetRegisterClass *RC,
1141                                         SmallVectorImpl<MachineInstr *> &NewMIs,
1142                                         bool &NonRI, bool &SpillsVRS) const {
1143   // Note: If additional load instructions are added here,
1144   // update isLoadFromStackSlot.
1145 
1146   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1147       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1148     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
1149                                                DestReg), FrameIdx));
1150   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1151              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1152     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
1153                                        FrameIdx));
1154   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1155     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
1156                                        FrameIdx));
1157   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1158     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
1159                                        FrameIdx));
1160   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1161     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1162                                                get(PPC::RESTORE_CR), DestReg),
1163                                        FrameIdx));
1164     return true;
1165   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1166     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1167                                                get(PPC::RESTORE_CRBIT), DestReg),
1168                                        FrameIdx));
1169     return true;
1170   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1171     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
1172                                        FrameIdx));
1173     NonRI = true;
1174   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1175     unsigned Op = Subtarget.hasP9Vector() ? PPC::LXVX : PPC::LXVD2X;
1176     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Op), DestReg),
1177                                        FrameIdx));
1178     NonRI = true;
1179   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1180     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFLOADf64 : PPC::LXSDX;
1181     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc),
1182                                                DestReg), FrameIdx));
1183     NonRI = true;
1184   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1185     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFLOADf32 : PPC::LXSSPX;
1186     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc),
1187                                                DestReg), FrameIdx));
1188     NonRI = true;
1189   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1190     assert(Subtarget.isDarwin() &&
1191            "VRSAVE only needs spill/restore on Darwin");
1192     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1193                                                get(PPC::RESTORE_VRSAVE),
1194                                                DestReg),
1195                                        FrameIdx));
1196     SpillsVRS = true;
1197   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1198     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
1199                                        FrameIdx));
1200     NonRI = true;
1201   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1202     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
1203                                        FrameIdx));
1204     NonRI = true;
1205   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1206     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
1207                                        FrameIdx));
1208     NonRI = true;
1209   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1210     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILLTOVSR_LD),
1211                                                DestReg), FrameIdx));
1212   } else {
1213     llvm_unreachable("Unknown regclass!");
1214   }
1215 
1216   return false;
1217 }
1218 
1219 void
1220 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1221                                    MachineBasicBlock::iterator MI,
1222                                    unsigned DestReg, int FrameIdx,
1223                                    const TargetRegisterClass *RC,
1224                                    const TargetRegisterInfo *TRI) const {
1225   MachineFunction &MF = *MBB.getParent();
1226   SmallVector<MachineInstr*, 4> NewMIs;
1227   DebugLoc DL;
1228   if (MI != MBB.end()) DL = MI->getDebugLoc();
1229 
1230   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1231   FuncInfo->setHasSpills();
1232 
1233   // We need to avoid a situation in which the value from a VRRC register is
1234   // spilled using an Altivec instruction and reloaded into a VSRC register
1235   // using a VSX instruction. The issue with this is that the VSX
1236   // load/store instructions swap the doublewords in the vector and the Altivec
1237   // ones don't. The register classes on the spill/reload may be different if
1238   // the register is defined using an Altivec instruction and is then used by a
1239   // VSX instruction.
1240   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
1241     RC = &PPC::VSRCRegClass;
1242 
1243   bool NonRI = false, SpillsVRS = false;
1244   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
1245                            NonRI, SpillsVRS))
1246     FuncInfo->setSpillsCR();
1247 
1248   if (SpillsVRS)
1249     FuncInfo->setSpillsVRSAVE();
1250 
1251   if (NonRI)
1252     FuncInfo->setHasNonRISpills();
1253 
1254   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1255     MBB.insert(MI, NewMIs[i]);
1256 
1257   const MachineFrameInfo &MFI = MF.getFrameInfo();
1258   MachineMemOperand *MMO = MF.getMachineMemOperand(
1259       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1260       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1261       MFI.getObjectAlignment(FrameIdx));
1262   NewMIs.back()->addMemOperand(MF, MMO);
1263 }
1264 
1265 bool PPCInstrInfo::
1266 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1267   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1268   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1269     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1270   else
1271     // Leave the CR# the same, but invert the condition.
1272     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1273   return false;
1274 }
1275 
1276 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1277                                  unsigned Reg, MachineRegisterInfo *MRI) const {
1278   // For some instructions, it is legal to fold ZERO into the RA register field.
1279   // A zero immediate should always be loaded with a single li.
1280   unsigned DefOpc = DefMI.getOpcode();
1281   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1282     return false;
1283   if (!DefMI.getOperand(1).isImm())
1284     return false;
1285   if (DefMI.getOperand(1).getImm() != 0)
1286     return false;
1287 
1288   // Note that we cannot here invert the arguments of an isel in order to fold
1289   // a ZERO into what is presented as the second argument. All we have here
1290   // is the condition bit, and that might come from a CR-logical bit operation.
1291 
1292   const MCInstrDesc &UseMCID = UseMI.getDesc();
1293 
1294   // Only fold into real machine instructions.
1295   if (UseMCID.isPseudo())
1296     return false;
1297 
1298   unsigned UseIdx;
1299   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1300     if (UseMI.getOperand(UseIdx).isReg() &&
1301         UseMI.getOperand(UseIdx).getReg() == Reg)
1302       break;
1303 
1304   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1305   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1306 
1307   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1308 
1309   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1310   // register (which might also be specified as a pointer class kind).
1311   if (UseInfo->isLookupPtrRegClass()) {
1312     if (UseInfo->RegClass /* Kind */ != 1)
1313       return false;
1314   } else {
1315     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1316         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1317       return false;
1318   }
1319 
1320   // Make sure this is not tied to an output register (or otherwise
1321   // constrained). This is true for ST?UX registers, for example, which
1322   // are tied to their output registers.
1323   if (UseInfo->Constraints != 0)
1324     return false;
1325 
1326   unsigned ZeroReg;
1327   if (UseInfo->isLookupPtrRegClass()) {
1328     bool isPPC64 = Subtarget.isPPC64();
1329     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1330   } else {
1331     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1332               PPC::ZERO8 : PPC::ZERO;
1333   }
1334 
1335   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1336   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1337 
1338   if (DeleteDef)
1339     DefMI.eraseFromParent();
1340 
1341   return true;
1342 }
1343 
1344 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1345   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1346        I != IE; ++I)
1347     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1348       return true;
1349   return false;
1350 }
1351 
1352 // We should make sure that, if we're going to predicate both sides of a
1353 // condition (a diamond), that both sides don't define the counter register. We
1354 // can predicate counter-decrement-based branches, but while that predicates
1355 // the branching, it does not predicate the counter decrement. If we tried to
1356 // merge the triangle into one predicated block, we'd decrement the counter
1357 // twice.
1358 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1359                      unsigned NumT, unsigned ExtraT,
1360                      MachineBasicBlock &FMBB,
1361                      unsigned NumF, unsigned ExtraF,
1362                      BranchProbability Probability) const {
1363   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1364 }
1365 
1366 
1367 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1368   // The predicated branches are identified by their type, not really by the
1369   // explicit presence of a predicate. Furthermore, some of them can be
1370   // predicated more than once. Because if conversion won't try to predicate
1371   // any instruction which already claims to be predicated (by returning true
1372   // here), always return false. In doing so, we let isPredicable() be the
1373   // final word on whether not the instruction can be (further) predicated.
1374 
1375   return false;
1376 }
1377 
1378 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
1379   if (!MI.isTerminator())
1380     return false;
1381 
1382   // Conditional branch is a special case.
1383   if (MI.isBranch() && !MI.isBarrier())
1384     return true;
1385 
1386   return !isPredicated(MI);
1387 }
1388 
1389 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1390                                         ArrayRef<MachineOperand> Pred) const {
1391   unsigned OpC = MI.getOpcode();
1392   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1393     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1394       bool isPPC64 = Subtarget.isPPC64();
1395       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1396                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1397     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1398       MI.setDesc(get(PPC::BCLR));
1399       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1400           .addReg(Pred[1].getReg());
1401     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1402       MI.setDesc(get(PPC::BCLRn));
1403       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1404           .addReg(Pred[1].getReg());
1405     } else {
1406       MI.setDesc(get(PPC::BCCLR));
1407       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1408           .addImm(Pred[0].getImm())
1409           .addReg(Pred[1].getReg());
1410     }
1411 
1412     return true;
1413   } else if (OpC == PPC::B) {
1414     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1415       bool isPPC64 = Subtarget.isPPC64();
1416       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1417                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1418     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1419       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1420       MI.RemoveOperand(0);
1421 
1422       MI.setDesc(get(PPC::BC));
1423       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1424           .addReg(Pred[1].getReg())
1425           .addMBB(MBB);
1426     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1427       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1428       MI.RemoveOperand(0);
1429 
1430       MI.setDesc(get(PPC::BCn));
1431       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1432           .addReg(Pred[1].getReg())
1433           .addMBB(MBB);
1434     } else {
1435       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1436       MI.RemoveOperand(0);
1437 
1438       MI.setDesc(get(PPC::BCC));
1439       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1440           .addImm(Pred[0].getImm())
1441           .addReg(Pred[1].getReg())
1442           .addMBB(MBB);
1443     }
1444 
1445     return true;
1446   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1447              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1448     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1449       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1450 
1451     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1452     bool isPPC64 = Subtarget.isPPC64();
1453 
1454     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1455       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1456                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1457       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1458           .addReg(Pred[1].getReg());
1459       return true;
1460     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1461       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1462                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1463       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1464           .addReg(Pred[1].getReg());
1465       return true;
1466     }
1467 
1468     MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1469                            : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1470     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1471         .addImm(Pred[0].getImm())
1472         .addReg(Pred[1].getReg());
1473     return true;
1474   }
1475 
1476   return false;
1477 }
1478 
1479 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1480                                      ArrayRef<MachineOperand> Pred2) const {
1481   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1482   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1483 
1484   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1485     return false;
1486   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1487     return false;
1488 
1489   // P1 can only subsume P2 if they test the same condition register.
1490   if (Pred1[1].getReg() != Pred2[1].getReg())
1491     return false;
1492 
1493   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1494   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1495 
1496   if (P1 == P2)
1497     return true;
1498 
1499   // Does P1 subsume P2, e.g. GE subsumes GT.
1500   if (P1 == PPC::PRED_LE &&
1501       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1502     return true;
1503   if (P1 == PPC::PRED_GE &&
1504       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1505     return true;
1506 
1507   return false;
1508 }
1509 
1510 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1511                                     std::vector<MachineOperand> &Pred) const {
1512   // Note: At the present time, the contents of Pred from this function is
1513   // unused by IfConversion. This implementation follows ARM by pushing the
1514   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1515   // predicate, instructions defining CTR or CTR8 are also included as
1516   // predicate-defining instructions.
1517 
1518   const TargetRegisterClass *RCs[] =
1519     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1520       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1521 
1522   bool Found = false;
1523   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1524     const MachineOperand &MO = MI.getOperand(i);
1525     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1526       const TargetRegisterClass *RC = RCs[c];
1527       if (MO.isReg()) {
1528         if (MO.isDef() && RC->contains(MO.getReg())) {
1529           Pred.push_back(MO);
1530           Found = true;
1531         }
1532       } else if (MO.isRegMask()) {
1533         for (TargetRegisterClass::iterator I = RC->begin(),
1534              IE = RC->end(); I != IE; ++I)
1535           if (MO.clobbersPhysReg(*I)) {
1536             Pred.push_back(MO);
1537             Found = true;
1538           }
1539       }
1540     }
1541   }
1542 
1543   return Found;
1544 }
1545 
1546 bool PPCInstrInfo::isPredicable(const MachineInstr &MI) const {
1547   unsigned OpC = MI.getOpcode();
1548   switch (OpC) {
1549   default:
1550     return false;
1551   case PPC::B:
1552   case PPC::BLR:
1553   case PPC::BLR8:
1554   case PPC::BCTR:
1555   case PPC::BCTR8:
1556   case PPC::BCTRL:
1557   case PPC::BCTRL8:
1558     return true;
1559   }
1560 }
1561 
1562 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1563                                   unsigned &SrcReg2, int &Mask,
1564                                   int &Value) const {
1565   unsigned Opc = MI.getOpcode();
1566 
1567   switch (Opc) {
1568   default: return false;
1569   case PPC::CMPWI:
1570   case PPC::CMPLWI:
1571   case PPC::CMPDI:
1572   case PPC::CMPLDI:
1573     SrcReg = MI.getOperand(1).getReg();
1574     SrcReg2 = 0;
1575     Value = MI.getOperand(2).getImm();
1576     Mask = 0xFFFF;
1577     return true;
1578   case PPC::CMPW:
1579   case PPC::CMPLW:
1580   case PPC::CMPD:
1581   case PPC::CMPLD:
1582   case PPC::FCMPUS:
1583   case PPC::FCMPUD:
1584     SrcReg = MI.getOperand(1).getReg();
1585     SrcReg2 = MI.getOperand(2).getReg();
1586     Value = 0;
1587     Mask = 0;
1588     return true;
1589   }
1590 }
1591 
1592 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1593                                         unsigned SrcReg2, int Mask, int Value,
1594                                         const MachineRegisterInfo *MRI) const {
1595   if (DisableCmpOpt)
1596     return false;
1597 
1598   int OpC = CmpInstr.getOpcode();
1599   unsigned CRReg = CmpInstr.getOperand(0).getReg();
1600 
1601   // FP record forms set CR1 based on the execption status bits, not a
1602   // comparison with zero.
1603   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1604     return false;
1605 
1606   // The record forms set the condition register based on a signed comparison
1607   // with zero (so says the ISA manual). This is not as straightforward as it
1608   // seems, however, because this is always a 64-bit comparison on PPC64, even
1609   // for instructions that are 32-bit in nature (like slw for example).
1610   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1611   // for equality checks (as those don't depend on the sign). On PPC64,
1612   // we are restricted to equality for unsigned 64-bit comparisons and for
1613   // signed 32-bit comparisons the applicability is more restricted.
1614   bool isPPC64 = Subtarget.isPPC64();
1615   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1616   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1617   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1618 
1619   // Get the unique definition of SrcReg.
1620   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1621   if (!MI) return false;
1622   int MIOpC = MI->getOpcode();
1623 
1624   bool equalityOnly = false;
1625   bool noSub = false;
1626   if (isPPC64) {
1627     if (is32BitSignedCompare) {
1628       // We can perform this optimization only if MI is sign-extending.
1629       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1630           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1631           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1632           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1633           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1634         noSub = true;
1635       } else
1636         return false;
1637     } else if (is32BitUnsignedCompare) {
1638       // 32-bit rotate and mask instructions are zero extending only if MB <= ME
1639       bool isZeroExtendingRotate  =
1640           (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINMo ||
1641            MIOpC == PPC::RLWNM || MIOpC == PPC::RLWNMo)
1642           && MI->getOperand(3).getImm() <= MI->getOperand(4).getImm();
1643 
1644       // We can perform this optimization, equality only, if MI is
1645       // zero-extending.
1646       // FIXME: Other possible target instructions include ANDISo and
1647       //        RLWINM aliases, such as ROTRWI, EXTLWI, SLWI and SRWI.
1648       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1649           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1650           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo ||
1651           MIOpC == PPC::ANDIo  ||
1652           isZeroExtendingRotate) {
1653         noSub = true;
1654         equalityOnly = true;
1655       } else
1656         return false;
1657     } else
1658       equalityOnly = is64BitUnsignedCompare;
1659   } else
1660     equalityOnly = is32BitUnsignedCompare;
1661 
1662   if (equalityOnly) {
1663     // We need to check the uses of the condition register in order to reject
1664     // non-equality comparisons.
1665     for (MachineRegisterInfo::use_instr_iterator
1666          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1667          I != IE; ++I) {
1668       MachineInstr *UseMI = &*I;
1669       if (UseMI->getOpcode() == PPC::BCC) {
1670         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1671         unsigned PredCond = PPC::getPredicateCondition(Pred);
1672         // We ignore hint bits when checking for non-equality comparisons.
1673         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1674           return false;
1675       } else if (UseMI->getOpcode() == PPC::ISEL ||
1676                  UseMI->getOpcode() == PPC::ISEL8) {
1677         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1678         if (SubIdx != PPC::sub_eq)
1679           return false;
1680       } else
1681         return false;
1682     }
1683   }
1684 
1685   MachineBasicBlock::iterator I = CmpInstr;
1686 
1687   // Scan forward to find the first use of the compare.
1688   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1689        ++I) {
1690     bool FoundUse = false;
1691     for (MachineRegisterInfo::use_instr_iterator
1692          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1693          J != JE; ++J)
1694       if (&*J == &*I) {
1695         FoundUse = true;
1696         break;
1697       }
1698 
1699     if (FoundUse)
1700       break;
1701   }
1702 
1703   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1704   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1705 
1706   // There are two possible candidates which can be changed to set CR[01].
1707   // One is MI, the other is a SUB instruction.
1708   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1709   MachineInstr *Sub = nullptr;
1710   if (SrcReg2 != 0)
1711     // MI is not a candidate for CMPrr.
1712     MI = nullptr;
1713   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1714   // same BB as the comparison. This is to allow the check below to avoid calls
1715   // (and other explicit clobbers); instead we should really check for these
1716   // more explicitly (in at least a few predecessors).
1717   else if (MI->getParent() != CmpInstr.getParent())
1718     return false;
1719   else if (Value != 0) {
1720     // The record-form instructions set CR bit based on signed comparison against 0.
1721     // We try to convert a compare against 1 or -1 into a compare against 0.
1722     bool Success = false;
1723     if (!equalityOnly && MRI->hasOneUse(CRReg)) {
1724       MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1725       if (UseMI->getOpcode() == PPC::BCC) {
1726         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1727         unsigned PredCond = PPC::getPredicateCondition(Pred);
1728         unsigned PredHint = PPC::getPredicateHint(Pred);
1729         int16_t Immed = (int16_t)Value;
1730 
1731         // When modyfing the condition in the predicate, we propagate hint bits
1732         // from the original predicate to the new one.
1733         if (Immed == -1 && PredCond == PPC::PRED_GT) {
1734           // We convert "greater than -1" into "greater than or equal to 0",
1735           // since we are assuming signed comparison by !equalityOnly
1736           PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1737                                   PPC::getPredicate(PPC::PRED_GE, PredHint)));
1738           Success = true;
1739         }
1740         else if (Immed == 1 && PredCond == PPC::PRED_LT) {
1741           // We convert "less than 1" into "less than or equal to 0".
1742           PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1743                                   PPC::getPredicate(PPC::PRED_LE, PredHint)));
1744           Success = true;
1745         }
1746       }
1747     }
1748 
1749     // PPC does not have a record-form SUBri.
1750     if (!Success)
1751       return false;
1752   }
1753 
1754   // Search for Sub.
1755   const TargetRegisterInfo *TRI = &getRegisterInfo();
1756   --I;
1757 
1758   // Get ready to iterate backward from CmpInstr.
1759   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1760 
1761   for (; I != E && !noSub; --I) {
1762     const MachineInstr &Instr = *I;
1763     unsigned IOpC = Instr.getOpcode();
1764 
1765     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1766                              Instr.readsRegister(PPC::CR0, TRI)))
1767       // This instruction modifies or uses the record condition register after
1768       // the one we want to change. While we could do this transformation, it
1769       // would likely not be profitable. This transformation removes one
1770       // instruction, and so even forcing RA to generate one move probably
1771       // makes it unprofitable.
1772       return false;
1773 
1774     // Check whether CmpInstr can be made redundant by the current instruction.
1775     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1776          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1777         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1778         ((Instr.getOperand(1).getReg() == SrcReg &&
1779           Instr.getOperand(2).getReg() == SrcReg2) ||
1780         (Instr.getOperand(1).getReg() == SrcReg2 &&
1781          Instr.getOperand(2).getReg() == SrcReg))) {
1782       Sub = &*I;
1783       break;
1784     }
1785 
1786     if (I == B)
1787       // The 'and' is below the comparison instruction.
1788       return false;
1789   }
1790 
1791   // Return false if no candidates exist.
1792   if (!MI && !Sub)
1793     return false;
1794 
1795   // The single candidate is called MI.
1796   if (!MI) MI = Sub;
1797 
1798   int NewOpC = -1;
1799   MIOpC = MI->getOpcode();
1800   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1801     NewOpC = MIOpC;
1802   else {
1803     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1804     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1805       NewOpC = MIOpC;
1806   }
1807 
1808   // FIXME: On the non-embedded POWER architectures, only some of the record
1809   // forms are fast, and we should use only the fast ones.
1810 
1811   // The defining instruction has a record form (or is already a record
1812   // form). It is possible, however, that we'll need to reverse the condition
1813   // code of the users.
1814   if (NewOpC == -1)
1815     return false;
1816 
1817   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1818   // needs to be updated to be based on SUB.  Push the condition code
1819   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1820   // condition code of these operands will be modified.
1821   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1822   // comparison against 0, which may modify predicate.
1823   bool ShouldSwap = false;
1824   if (Sub && Value == 0) {
1825     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1826       Sub->getOperand(2).getReg() == SrcReg;
1827 
1828     // The operands to subf are the opposite of sub, so only in the fixed-point
1829     // case, invert the order.
1830     ShouldSwap = !ShouldSwap;
1831   }
1832 
1833   if (ShouldSwap)
1834     for (MachineRegisterInfo::use_instr_iterator
1835          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1836          I != IE; ++I) {
1837       MachineInstr *UseMI = &*I;
1838       if (UseMI->getOpcode() == PPC::BCC) {
1839         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1840         unsigned PredCond = PPC::getPredicateCondition(Pred);
1841         assert((!equalityOnly ||
1842                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1843                "Invalid predicate for equality-only optimization");
1844         (void)PredCond; // To suppress warning in release build.
1845         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1846                                 PPC::getSwappedPredicate(Pred)));
1847       } else if (UseMI->getOpcode() == PPC::ISEL ||
1848                  UseMI->getOpcode() == PPC::ISEL8) {
1849         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1850         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1851                "Invalid CR bit for equality-only optimization");
1852 
1853         if (NewSubReg == PPC::sub_lt)
1854           NewSubReg = PPC::sub_gt;
1855         else if (NewSubReg == PPC::sub_gt)
1856           NewSubReg = PPC::sub_lt;
1857 
1858         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1859                                                  NewSubReg));
1860       } else // We need to abort on a user we don't understand.
1861         return false;
1862     }
1863   assert(!(Value != 0 && ShouldSwap) &&
1864          "Non-zero immediate support and ShouldSwap"
1865          "may conflict in updating predicate");
1866 
1867   // Create a new virtual register to hold the value of the CR set by the
1868   // record-form instruction. If the instruction was not previously in
1869   // record form, then set the kill flag on the CR.
1870   CmpInstr.eraseFromParent();
1871 
1872   MachineBasicBlock::iterator MII = MI;
1873   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1874           get(TargetOpcode::COPY), CRReg)
1875     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1876 
1877   // Even if CR0 register were dead before, it is alive now since the
1878   // instruction we just built uses it.
1879   MI->clearRegisterDeads(PPC::CR0);
1880 
1881   if (MIOpC != NewOpC) {
1882     // We need to be careful here: we're replacing one instruction with
1883     // another, and we need to make sure that we get all of the right
1884     // implicit uses and defs. On the other hand, the caller may be holding
1885     // an iterator to this instruction, and so we can't delete it (this is
1886     // specifically the case if this is the instruction directly after the
1887     // compare).
1888 
1889     const MCInstrDesc &NewDesc = get(NewOpC);
1890     MI->setDesc(NewDesc);
1891 
1892     if (NewDesc.ImplicitDefs)
1893       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
1894            *ImpDefs; ++ImpDefs)
1895         if (!MI->definesRegister(*ImpDefs))
1896           MI->addOperand(*MI->getParent()->getParent(),
1897                          MachineOperand::CreateReg(*ImpDefs, true, true));
1898     if (NewDesc.ImplicitUses)
1899       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
1900            *ImpUses; ++ImpUses)
1901         if (!MI->readsRegister(*ImpUses))
1902           MI->addOperand(*MI->getParent()->getParent(),
1903                          MachineOperand::CreateReg(*ImpUses, false, true));
1904   }
1905   assert(MI->definesRegister(PPC::CR0) &&
1906          "Record-form instruction does not define cr0?");
1907 
1908   // Modify the condition code of operands in OperandsToUpdate.
1909   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1910   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1911   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1912     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1913 
1914   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1915     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1916 
1917   return true;
1918 }
1919 
1920 /// GetInstSize - Return the number of bytes of code the specified
1921 /// instruction may be.  This returns the maximum number of bytes.
1922 ///
1923 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
1924   unsigned Opcode = MI.getOpcode();
1925 
1926   if (Opcode == PPC::INLINEASM) {
1927     const MachineFunction *MF = MI.getParent()->getParent();
1928     const char *AsmStr = MI.getOperand(0).getSymbolName();
1929     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1930   } else if (Opcode == TargetOpcode::STACKMAP) {
1931     StackMapOpers Opers(&MI);
1932     return Opers.getNumPatchBytes();
1933   } else if (Opcode == TargetOpcode::PATCHPOINT) {
1934     PatchPointOpers Opers(&MI);
1935     return Opers.getNumPatchBytes();
1936   } else {
1937     return get(Opcode).getSize();
1938   }
1939 }
1940 
1941 std::pair<unsigned, unsigned>
1942 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1943   const unsigned Mask = PPCII::MO_ACCESS_MASK;
1944   return std::make_pair(TF & Mask, TF & ~Mask);
1945 }
1946 
1947 ArrayRef<std::pair<unsigned, const char *>>
1948 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
1949   using namespace PPCII;
1950   static const std::pair<unsigned, const char *> TargetFlags[] = {
1951       {MO_LO, "ppc-lo"},
1952       {MO_HA, "ppc-ha"},
1953       {MO_TPREL_LO, "ppc-tprel-lo"},
1954       {MO_TPREL_HA, "ppc-tprel-ha"},
1955       {MO_DTPREL_LO, "ppc-dtprel-lo"},
1956       {MO_TLSLD_LO, "ppc-tlsld-lo"},
1957       {MO_TOC_LO, "ppc-toc-lo"},
1958       {MO_TLS, "ppc-tls"}};
1959   return makeArrayRef(TargetFlags);
1960 }
1961 
1962 ArrayRef<std::pair<unsigned, const char *>>
1963 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
1964   using namespace PPCII;
1965   static const std::pair<unsigned, const char *> TargetFlags[] = {
1966       {MO_PLT, "ppc-plt"},
1967       {MO_PIC_FLAG, "ppc-pic"},
1968       {MO_NLP_FLAG, "ppc-nlp"},
1969       {MO_NLP_HIDDEN_FLAG, "ppc-nlp-hidden"}};
1970   return makeArrayRef(TargetFlags);
1971 }
1972 
1973 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1974   auto &MBB = *MI.getParent();
1975   auto DL = MI.getDebugLoc();
1976   switch (MI.getOpcode()) {
1977   case TargetOpcode::LOAD_STACK_GUARD: {
1978     assert(Subtarget.isTargetLinux() &&
1979            "Only Linux target is expected to contain LOAD_STACK_GUARD");
1980     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
1981     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
1982     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
1983     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1984         .addImm(Offset)
1985         .addReg(Reg);
1986     return true;
1987   }
1988   case PPC::DFLOADf32:
1989   case PPC::DFLOADf64:
1990   case PPC::DFSTOREf32:
1991   case PPC::DFSTOREf64: {
1992     assert(Subtarget.hasP9Vector() &&
1993            "Invalid D-Form Pseudo-ops on non-P9 target.");
1994     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isImm() &&
1995            "D-form op must have register and immediate operands");
1996     unsigned UpperOpcode, LowerOpcode;
1997     switch (MI.getOpcode()) {
1998     case PPC::DFLOADf32:
1999       UpperOpcode = PPC::LXSSP;
2000       LowerOpcode = PPC::LFS;
2001       break;
2002     case PPC::DFLOADf64:
2003       UpperOpcode = PPC::LXSD;
2004       LowerOpcode = PPC::LFD;
2005       break;
2006     case PPC::DFSTOREf32:
2007       UpperOpcode = PPC::STXSSP;
2008       LowerOpcode = PPC::STFS;
2009       break;
2010     case PPC::DFSTOREf64:
2011       UpperOpcode = PPC::STXSD;
2012       LowerOpcode = PPC::STFD;
2013       break;
2014     }
2015     unsigned TargetReg = MI.getOperand(0).getReg();
2016     unsigned Opcode;
2017     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2018         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2019       Opcode = LowerOpcode;
2020     else
2021       Opcode = UpperOpcode;
2022     MI.setDesc(get(Opcode));
2023     return true;
2024   }
2025   case PPC::SPILLTOVSR_LD: {
2026     unsigned TargetReg = MI.getOperand(0).getReg();
2027     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2028       MI.setDesc(get(PPC::DFLOADf64));
2029       return expandPostRAPseudo(MI);
2030     }
2031     else
2032       MI.setDesc(get(PPC::LD));
2033     return true;
2034   }
2035   case PPC::SPILLTOVSR_ST: {
2036     unsigned SrcReg = MI.getOperand(0).getReg();
2037     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2038       NumStoreSPILLVSRRCAsVec++;
2039       MI.setDesc(get(PPC::DFSTOREf64));
2040       return expandPostRAPseudo(MI);
2041     } else {
2042       NumStoreSPILLVSRRCAsGpr++;
2043       MI.setDesc(get(PPC::STD));
2044     }
2045     return true;
2046   }
2047   case PPC::SPILLTOVSR_LDX: {
2048     unsigned TargetReg = MI.getOperand(0).getReg();
2049     if (PPC::VSFRCRegClass.contains(TargetReg))
2050       MI.setDesc(get(PPC::LXSDX));
2051     else
2052       MI.setDesc(get(PPC::LDX));
2053     return true;
2054   }
2055   case PPC::SPILLTOVSR_STX: {
2056     unsigned SrcReg = MI.getOperand(0).getReg();
2057     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2058       NumStoreSPILLVSRRCAsVec++;
2059       MI.setDesc(get(PPC::STXSDX));
2060     } else {
2061       NumStoreSPILLVSRRCAsGpr++;
2062       MI.setDesc(get(PPC::STDX));
2063     }
2064     return true;
2065   }
2066 
2067   case PPC::CFENCE8: {
2068     auto Val = MI.getOperand(0).getReg();
2069     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2070     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2071         .addImm(PPC::PRED_NE_MINUS)
2072         .addReg(PPC::CR7)
2073         .addImm(1);
2074     MI.setDesc(get(PPC::ISYNC));
2075     MI.RemoveOperand(0);
2076     return true;
2077   }
2078   }
2079   return false;
2080 }
2081 
2082 const TargetRegisterClass *
2083 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
2084   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
2085     return &PPC::VSRCRegClass;
2086   return RC;
2087 }
2088 
2089 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
2090   return PPC::getRecordFormOpcode(Opcode);
2091 }
2092