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   if (AllowModify) {
498     // If the BB ends with an unconditional branch to the fallthrough BB,
499     // we eliminate the branch instruction.
500     if (I->getOpcode() == PPC::B &&
501         MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
502       I->eraseFromParent();
503 
504       // We update iterator after deleting the last branch.
505       I = MBB.getLastNonDebugInstr();
506       if (I == MBB.end() || !isUnpredicatedTerminator(*I))
507         return false;
508     }
509   }
510 
511   // Get the last instruction in the block.
512   MachineInstr &LastInst = *I;
513 
514   // If there is only one terminator instruction, process it.
515   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
516     if (LastInst.getOpcode() == PPC::B) {
517       if (!LastInst.getOperand(0).isMBB())
518         return true;
519       TBB = LastInst.getOperand(0).getMBB();
520       return false;
521     } else if (LastInst.getOpcode() == PPC::BCC) {
522       if (!LastInst.getOperand(2).isMBB())
523         return true;
524       // Block ends with fall-through condbranch.
525       TBB = LastInst.getOperand(2).getMBB();
526       Cond.push_back(LastInst.getOperand(0));
527       Cond.push_back(LastInst.getOperand(1));
528       return false;
529     } else if (LastInst.getOpcode() == PPC::BC) {
530       if (!LastInst.getOperand(1).isMBB())
531         return true;
532       // Block ends with fall-through condbranch.
533       TBB = LastInst.getOperand(1).getMBB();
534       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
535       Cond.push_back(LastInst.getOperand(0));
536       return false;
537     } else if (LastInst.getOpcode() == PPC::BCn) {
538       if (!LastInst.getOperand(1).isMBB())
539         return true;
540       // Block ends with fall-through condbranch.
541       TBB = LastInst.getOperand(1).getMBB();
542       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
543       Cond.push_back(LastInst.getOperand(0));
544       return false;
545     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
546                LastInst.getOpcode() == PPC::BDNZ) {
547       if (!LastInst.getOperand(0).isMBB())
548         return true;
549       if (DisableCTRLoopAnal)
550         return true;
551       TBB = LastInst.getOperand(0).getMBB();
552       Cond.push_back(MachineOperand::CreateImm(1));
553       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
554                                                true));
555       return false;
556     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
557                LastInst.getOpcode() == PPC::BDZ) {
558       if (!LastInst.getOperand(0).isMBB())
559         return true;
560       if (DisableCTRLoopAnal)
561         return true;
562       TBB = LastInst.getOperand(0).getMBB();
563       Cond.push_back(MachineOperand::CreateImm(0));
564       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
565                                                true));
566       return false;
567     }
568 
569     // Otherwise, don't know what this is.
570     return true;
571   }
572 
573   // Get the instruction before it if it's a terminator.
574   MachineInstr &SecondLastInst = *I;
575 
576   // If there are three terminators, we don't know what sort of block this is.
577   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
578     return true;
579 
580   // If the block ends with PPC::B and PPC:BCC, handle it.
581   if (SecondLastInst.getOpcode() == PPC::BCC &&
582       LastInst.getOpcode() == PPC::B) {
583     if (!SecondLastInst.getOperand(2).isMBB() ||
584         !LastInst.getOperand(0).isMBB())
585       return true;
586     TBB = SecondLastInst.getOperand(2).getMBB();
587     Cond.push_back(SecondLastInst.getOperand(0));
588     Cond.push_back(SecondLastInst.getOperand(1));
589     FBB = LastInst.getOperand(0).getMBB();
590     return false;
591   } else if (SecondLastInst.getOpcode() == PPC::BC &&
592              LastInst.getOpcode() == PPC::B) {
593     if (!SecondLastInst.getOperand(1).isMBB() ||
594         !LastInst.getOperand(0).isMBB())
595       return true;
596     TBB = SecondLastInst.getOperand(1).getMBB();
597     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
598     Cond.push_back(SecondLastInst.getOperand(0));
599     FBB = LastInst.getOperand(0).getMBB();
600     return false;
601   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
602              LastInst.getOpcode() == PPC::B) {
603     if (!SecondLastInst.getOperand(1).isMBB() ||
604         !LastInst.getOperand(0).isMBB())
605       return true;
606     TBB = SecondLastInst.getOperand(1).getMBB();
607     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
608     Cond.push_back(SecondLastInst.getOperand(0));
609     FBB = LastInst.getOperand(0).getMBB();
610     return false;
611   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
612               SecondLastInst.getOpcode() == PPC::BDNZ) &&
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(1));
621     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
622                                              true));
623     FBB = LastInst.getOperand(0).getMBB();
624     return false;
625   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
626               SecondLastInst.getOpcode() == PPC::BDZ) &&
627              LastInst.getOpcode() == PPC::B) {
628     if (!SecondLastInst.getOperand(0).isMBB() ||
629         !LastInst.getOperand(0).isMBB())
630       return true;
631     if (DisableCTRLoopAnal)
632       return true;
633     TBB = SecondLastInst.getOperand(0).getMBB();
634     Cond.push_back(MachineOperand::CreateImm(0));
635     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
636                                              true));
637     FBB = LastInst.getOperand(0).getMBB();
638     return false;
639   }
640 
641   // If the block ends with two PPC:Bs, handle it.  The second one is not
642   // executed, so remove it.
643   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
644     if (!SecondLastInst.getOperand(0).isMBB())
645       return true;
646     TBB = SecondLastInst.getOperand(0).getMBB();
647     I = LastInst;
648     if (AllowModify)
649       I->eraseFromParent();
650     return false;
651   }
652 
653   // Otherwise, can't handle this.
654   return true;
655 }
656 
657 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
658                                     int *BytesRemoved) const {
659   assert(!BytesRemoved && "code size not handled");
660 
661   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
662   if (I == MBB.end())
663     return 0;
664 
665   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
666       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
667       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
668       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
669     return 0;
670 
671   // Remove the branch.
672   I->eraseFromParent();
673 
674   I = MBB.end();
675 
676   if (I == MBB.begin()) return 1;
677   --I;
678   if (I->getOpcode() != PPC::BCC &&
679       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
680       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
681       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
682     return 1;
683 
684   // Remove the branch.
685   I->eraseFromParent();
686   return 2;
687 }
688 
689 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
690                                     MachineBasicBlock *TBB,
691                                     MachineBasicBlock *FBB,
692                                     ArrayRef<MachineOperand> Cond,
693                                     const DebugLoc &DL,
694                                     int *BytesAdded) const {
695   // Shouldn't be a fall through.
696   assert(TBB && "insertBranch must not be told to insert a fallthrough");
697   assert((Cond.size() == 2 || Cond.size() == 0) &&
698          "PPC branch conditions have two components!");
699   assert(!BytesAdded && "code size not handled");
700 
701   bool isPPC64 = Subtarget.isPPC64();
702 
703   // One-way branch.
704   if (!FBB) {
705     if (Cond.empty())   // Unconditional branch
706       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
707     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
708       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
709                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
710                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
711     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
712       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
713     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
714       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
715     else                // Conditional branch
716       BuildMI(&MBB, DL, get(PPC::BCC))
717           .addImm(Cond[0].getImm())
718           .add(Cond[1])
719           .addMBB(TBB);
720     return 1;
721   }
722 
723   // Two-way Conditional Branch.
724   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
725     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
726                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
727                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
728   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
729     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
730   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
731     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
732   else
733     BuildMI(&MBB, DL, get(PPC::BCC))
734         .addImm(Cond[0].getImm())
735         .add(Cond[1])
736         .addMBB(TBB);
737   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
738   return 2;
739 }
740 
741 // Select analysis.
742 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
743                 ArrayRef<MachineOperand> Cond,
744                 unsigned TrueReg, unsigned FalseReg,
745                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
746   if (Cond.size() != 2)
747     return false;
748 
749   // If this is really a bdnz-like condition, then it cannot be turned into a
750   // select.
751   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
752     return false;
753 
754   // Check register classes.
755   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
756   const TargetRegisterClass *RC =
757     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
758   if (!RC)
759     return false;
760 
761   // isel is for regular integer GPRs only.
762   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
763       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
764       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
765       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
766     return false;
767 
768   // FIXME: These numbers are for the A2, how well they work for other cores is
769   // an open question. On the A2, the isel instruction has a 2-cycle latency
770   // but single-cycle throughput. These numbers are used in combination with
771   // the MispredictPenalty setting from the active SchedMachineModel.
772   CondCycles = 1;
773   TrueCycles = 1;
774   FalseCycles = 1;
775 
776   return true;
777 }
778 
779 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
780                                 MachineBasicBlock::iterator MI,
781                                 const DebugLoc &dl, unsigned DestReg,
782                                 ArrayRef<MachineOperand> Cond, unsigned TrueReg,
783                                 unsigned FalseReg) const {
784   assert(Cond.size() == 2 &&
785          "PPC branch conditions have two components!");
786 
787   // Get the register classes.
788   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
789   const TargetRegisterClass *RC =
790     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
791   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
792 
793   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
794                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
795   assert((Is64Bit ||
796           PPC::GPRCRegClass.hasSubClassEq(RC) ||
797           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
798          "isel is for regular integer GPRs only");
799 
800   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
801   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
802 
803   unsigned SubIdx = 0;
804   bool SwapOps = false;
805   switch (SelectPred) {
806   case PPC::PRED_EQ:
807   case PPC::PRED_EQ_MINUS:
808   case PPC::PRED_EQ_PLUS:
809       SubIdx = PPC::sub_eq; SwapOps = false; break;
810   case PPC::PRED_NE:
811   case PPC::PRED_NE_MINUS:
812   case PPC::PRED_NE_PLUS:
813       SubIdx = PPC::sub_eq; SwapOps = true; break;
814   case PPC::PRED_LT:
815   case PPC::PRED_LT_MINUS:
816   case PPC::PRED_LT_PLUS:
817       SubIdx = PPC::sub_lt; SwapOps = false; break;
818   case PPC::PRED_GE:
819   case PPC::PRED_GE_MINUS:
820   case PPC::PRED_GE_PLUS:
821       SubIdx = PPC::sub_lt; SwapOps = true; break;
822   case PPC::PRED_GT:
823   case PPC::PRED_GT_MINUS:
824   case PPC::PRED_GT_PLUS:
825       SubIdx = PPC::sub_gt; SwapOps = false; break;
826   case PPC::PRED_LE:
827   case PPC::PRED_LE_MINUS:
828   case PPC::PRED_LE_PLUS:
829       SubIdx = PPC::sub_gt; SwapOps = true; break;
830   case PPC::PRED_UN:
831   case PPC::PRED_UN_MINUS:
832   case PPC::PRED_UN_PLUS:
833       SubIdx = PPC::sub_un; SwapOps = false; break;
834   case PPC::PRED_NU:
835   case PPC::PRED_NU_MINUS:
836   case PPC::PRED_NU_PLUS:
837       SubIdx = PPC::sub_un; SwapOps = true; break;
838   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
839   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
840   }
841 
842   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
843            SecondReg = SwapOps ? TrueReg  : FalseReg;
844 
845   // The first input register of isel cannot be r0. If it is a member
846   // of a register class that can be r0, then copy it first (the
847   // register allocator should eliminate the copy).
848   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
849       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
850     const TargetRegisterClass *FirstRC =
851       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
852         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
853     unsigned OldFirstReg = FirstReg;
854     FirstReg = MRI.createVirtualRegister(FirstRC);
855     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
856       .addReg(OldFirstReg);
857   }
858 
859   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
860     .addReg(FirstReg).addReg(SecondReg)
861     .addReg(Cond[1].getReg(), 0, SubIdx);
862 }
863 
864 static unsigned getCRBitValue(unsigned CRBit) {
865   unsigned Ret = 4;
866   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
867       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
868       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
869       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
870     Ret = 3;
871   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
872       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
873       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
874       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
875     Ret = 2;
876   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
877       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
878       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
879       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
880     Ret = 1;
881   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
882       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
883       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
884       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
885     Ret = 0;
886 
887   assert(Ret != 4 && "Invalid CR bit register");
888   return Ret;
889 }
890 
891 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
892                                MachineBasicBlock::iterator I,
893                                const DebugLoc &DL, unsigned DestReg,
894                                unsigned SrcReg, bool KillSrc) const {
895   // We can end up with self copies and similar things as a result of VSX copy
896   // legalization. Promote them here.
897   const TargetRegisterInfo *TRI = &getRegisterInfo();
898   if (PPC::F8RCRegClass.contains(DestReg) &&
899       PPC::VSRCRegClass.contains(SrcReg)) {
900     unsigned SuperReg =
901       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
902 
903     if (VSXSelfCopyCrash && SrcReg == SuperReg)
904       llvm_unreachable("nop VSX copy");
905 
906     DestReg = SuperReg;
907   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
908              PPC::VSRCRegClass.contains(DestReg)) {
909     unsigned SuperReg =
910       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
911 
912     if (VSXSelfCopyCrash && DestReg == SuperReg)
913       llvm_unreachable("nop VSX copy");
914 
915     SrcReg = SuperReg;
916   }
917 
918   // Different class register copy
919   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
920       PPC::GPRCRegClass.contains(DestReg)) {
921     unsigned CRReg = getCRFromCRBit(SrcReg);
922     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
923     getKillRegState(KillSrc);
924     // Rotate the CR bit in the CR fields to be the least significant bit and
925     // then mask with 0x1 (MB = ME = 31).
926     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
927        .addReg(DestReg, RegState::Kill)
928        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
929        .addImm(31)
930        .addImm(31);
931     return;
932   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
933       PPC::G8RCRegClass.contains(DestReg)) {
934     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg);
935     getKillRegState(KillSrc);
936     return;
937   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
938       PPC::GPRCRegClass.contains(DestReg)) {
939     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg);
940     getKillRegState(KillSrc);
941     return;
942   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
943              PPC::VSFRCRegClass.contains(DestReg)) {
944     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
945     NumGPRtoVSRSpill++;
946     getKillRegState(KillSrc);
947     return;
948   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
949              PPC::G8RCRegClass.contains(DestReg)) {
950     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
951     getKillRegState(KillSrc);
952     return;
953   }
954 
955   unsigned Opc;
956   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
957     Opc = PPC::OR;
958   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
959     Opc = PPC::OR8;
960   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
961     Opc = PPC::FMR;
962   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
963     Opc = PPC::MCRF;
964   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
965     Opc = PPC::VOR;
966   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
967     // There are two different ways this can be done:
968     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
969     //      issue in VSU pipeline 0.
970     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
971     //      can go to either pipeline.
972     // We'll always use xxlor here, because in practically all cases where
973     // copies are generated, they are close enough to some use that the
974     // lower-latency form is preferable.
975     Opc = PPC::XXLOR;
976   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
977            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
978     Opc = PPC::XXLORf;
979   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
980     Opc = PPC::QVFMR;
981   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
982     Opc = PPC::QVFMRs;
983   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
984     Opc = PPC::QVFMRb;
985   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
986     Opc = PPC::CROR;
987   else
988     llvm_unreachable("Impossible reg-to-reg copy");
989 
990   const MCInstrDesc &MCID = get(Opc);
991   if (MCID.getNumOperands() == 3)
992     BuildMI(MBB, I, DL, MCID, DestReg)
993       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
994   else
995     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
996 }
997 
998 // This function returns true if a CR spill is necessary and false otherwise.
999 bool
1000 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
1001                                   unsigned SrcReg, bool isKill,
1002                                   int FrameIdx,
1003                                   const TargetRegisterClass *RC,
1004                                   SmallVectorImpl<MachineInstr*> &NewMIs,
1005                                   bool &NonRI, bool &SpillsVRS) const{
1006   // Note: If additional store instructions are added here,
1007   // update isStoreToStackSlot.
1008 
1009   DebugLoc DL;
1010   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1011       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1012     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
1013                                        .addReg(SrcReg,
1014                                                getKillRegState(isKill)),
1015                                        FrameIdx));
1016   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1017              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1018     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
1019                                        .addReg(SrcReg,
1020                                                getKillRegState(isKill)),
1021                                        FrameIdx));
1022   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1023     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
1024                                        .addReg(SrcReg,
1025                                                getKillRegState(isKill)),
1026                                        FrameIdx));
1027   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1028     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
1029                                        .addReg(SrcReg,
1030                                                getKillRegState(isKill)),
1031                                        FrameIdx));
1032   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1033     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
1034                                        .addReg(SrcReg,
1035                                                getKillRegState(isKill)),
1036                                        FrameIdx));
1037     return true;
1038   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1039     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
1040                                        .addReg(SrcReg,
1041                                                getKillRegState(isKill)),
1042                                        FrameIdx));
1043     return true;
1044   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1045     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
1046                                        .addReg(SrcReg,
1047                                                getKillRegState(isKill)),
1048                                        FrameIdx));
1049     NonRI = true;
1050   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1051     unsigned Op = Subtarget.hasP9Vector() ? PPC::STXVX : PPC::STXVD2X;
1052     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Op))
1053                                        .addReg(SrcReg,
1054                                                getKillRegState(isKill)),
1055                                        FrameIdx));
1056     NonRI = true;
1057   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1058     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFSTOREf64 : PPC::STXSDX;
1059     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc))
1060                                        .addReg(SrcReg,
1061                                                getKillRegState(isKill)),
1062                                        FrameIdx));
1063     NonRI = true;
1064   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1065     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFSTOREf32 : PPC::STXSSPX;
1066     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc))
1067                                        .addReg(SrcReg,
1068                                                getKillRegState(isKill)),
1069                                        FrameIdx));
1070     NonRI = true;
1071   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1072     assert(Subtarget.isDarwin() &&
1073            "VRSAVE only needs spill/restore on Darwin");
1074     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
1075                                        .addReg(SrcReg,
1076                                                getKillRegState(isKill)),
1077                                        FrameIdx));
1078     SpillsVRS = true;
1079   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1080     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
1081                                        .addReg(SrcReg,
1082                                                getKillRegState(isKill)),
1083                                        FrameIdx));
1084     NonRI = true;
1085   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1086     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
1087                                        .addReg(SrcReg,
1088                                                getKillRegState(isKill)),
1089                                        FrameIdx));
1090     NonRI = true;
1091   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1092     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
1093                                        .addReg(SrcReg,
1094                                                getKillRegState(isKill)),
1095                                        FrameIdx));
1096     NonRI = true;
1097   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1098     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILLTOVSR_ST))
1099                                        .addReg(SrcReg,
1100                                                getKillRegState(isKill)),
1101                                        FrameIdx));
1102   } else {
1103     llvm_unreachable("Unknown regclass!");
1104   }
1105 
1106   return false;
1107 }
1108 
1109 void
1110 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1111                                   MachineBasicBlock::iterator MI,
1112                                   unsigned SrcReg, bool isKill, int FrameIdx,
1113                                   const TargetRegisterClass *RC,
1114                                   const TargetRegisterInfo *TRI) const {
1115   MachineFunction &MF = *MBB.getParent();
1116   SmallVector<MachineInstr*, 4> NewMIs;
1117 
1118   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1119   FuncInfo->setHasSpills();
1120 
1121   // We need to avoid a situation in which the value from a VRRC register is
1122   // spilled using an Altivec instruction and reloaded into a VSRC register
1123   // using a VSX instruction. The issue with this is that the VSX
1124   // load/store instructions swap the doublewords in the vector and the Altivec
1125   // ones don't. The register classes on the spill/reload may be different if
1126   // the register is defined using an Altivec instruction and is then used by a
1127   // VSX instruction.
1128   RC = updatedRC(RC);
1129 
1130   bool NonRI = false, SpillsVRS = false;
1131   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
1132                           NonRI, SpillsVRS))
1133     FuncInfo->setSpillsCR();
1134 
1135   if (SpillsVRS)
1136     FuncInfo->setSpillsVRSAVE();
1137 
1138   if (NonRI)
1139     FuncInfo->setHasNonRISpills();
1140 
1141   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1142     MBB.insert(MI, NewMIs[i]);
1143 
1144   const MachineFrameInfo &MFI = MF.getFrameInfo();
1145   MachineMemOperand *MMO = MF.getMachineMemOperand(
1146       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1147       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1148       MFI.getObjectAlignment(FrameIdx));
1149   NewMIs.back()->addMemOperand(MF, MMO);
1150 }
1151 
1152 bool PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1153                                         unsigned DestReg, int FrameIdx,
1154                                         const TargetRegisterClass *RC,
1155                                         SmallVectorImpl<MachineInstr *> &NewMIs,
1156                                         bool &NonRI, bool &SpillsVRS) const {
1157   // Note: If additional load instructions are added here,
1158   // update isLoadFromStackSlot.
1159 
1160   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1161       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1162     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
1163                                                DestReg), FrameIdx));
1164   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1165              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1166     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
1167                                        FrameIdx));
1168   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1169     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
1170                                        FrameIdx));
1171   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1172     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
1173                                        FrameIdx));
1174   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1175     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1176                                                get(PPC::RESTORE_CR), DestReg),
1177                                        FrameIdx));
1178     return true;
1179   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1180     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1181                                                get(PPC::RESTORE_CRBIT), DestReg),
1182                                        FrameIdx));
1183     return true;
1184   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1185     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
1186                                        FrameIdx));
1187     NonRI = true;
1188   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1189     unsigned Op = Subtarget.hasP9Vector() ? PPC::LXVX : PPC::LXVD2X;
1190     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Op), DestReg),
1191                                        FrameIdx));
1192     NonRI = true;
1193   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1194     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFLOADf64 : PPC::LXSDX;
1195     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc),
1196                                                DestReg), FrameIdx));
1197     NonRI = true;
1198   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1199     unsigned Opc = Subtarget.hasP9Vector() ? PPC::DFLOADf32 : PPC::LXSSPX;
1200     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opc),
1201                                                DestReg), FrameIdx));
1202     NonRI = true;
1203   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1204     assert(Subtarget.isDarwin() &&
1205            "VRSAVE only needs spill/restore on Darwin");
1206     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1207                                                get(PPC::RESTORE_VRSAVE),
1208                                                DestReg),
1209                                        FrameIdx));
1210     SpillsVRS = true;
1211   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1212     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
1213                                        FrameIdx));
1214     NonRI = true;
1215   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1216     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
1217                                        FrameIdx));
1218     NonRI = true;
1219   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1220     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
1221                                        FrameIdx));
1222     NonRI = true;
1223   } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1224     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILLTOVSR_LD),
1225                                                DestReg), FrameIdx));
1226   } else {
1227     llvm_unreachable("Unknown regclass!");
1228   }
1229 
1230   return false;
1231 }
1232 
1233 void
1234 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1235                                    MachineBasicBlock::iterator MI,
1236                                    unsigned DestReg, int FrameIdx,
1237                                    const TargetRegisterClass *RC,
1238                                    const TargetRegisterInfo *TRI) const {
1239   MachineFunction &MF = *MBB.getParent();
1240   SmallVector<MachineInstr*, 4> NewMIs;
1241   DebugLoc DL;
1242   if (MI != MBB.end()) DL = MI->getDebugLoc();
1243 
1244   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1245   FuncInfo->setHasSpills();
1246 
1247   // We need to avoid a situation in which the value from a VRRC register is
1248   // spilled using an Altivec instruction and reloaded into a VSRC register
1249   // using a VSX instruction. The issue with this is that the VSX
1250   // load/store instructions swap the doublewords in the vector and the Altivec
1251   // ones don't. The register classes on the spill/reload may be different if
1252   // the register is defined using an Altivec instruction and is then used by a
1253   // VSX instruction.
1254   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
1255     RC = &PPC::VSRCRegClass;
1256 
1257   bool NonRI = false, SpillsVRS = false;
1258   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
1259                            NonRI, SpillsVRS))
1260     FuncInfo->setSpillsCR();
1261 
1262   if (SpillsVRS)
1263     FuncInfo->setSpillsVRSAVE();
1264 
1265   if (NonRI)
1266     FuncInfo->setHasNonRISpills();
1267 
1268   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1269     MBB.insert(MI, NewMIs[i]);
1270 
1271   const MachineFrameInfo &MFI = MF.getFrameInfo();
1272   MachineMemOperand *MMO = MF.getMachineMemOperand(
1273       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1274       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1275       MFI.getObjectAlignment(FrameIdx));
1276   NewMIs.back()->addMemOperand(MF, MMO);
1277 }
1278 
1279 bool PPCInstrInfo::
1280 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1281   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1282   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1283     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1284   else
1285     // Leave the CR# the same, but invert the condition.
1286     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1287   return false;
1288 }
1289 
1290 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1291                                  unsigned Reg, MachineRegisterInfo *MRI) const {
1292   // For some instructions, it is legal to fold ZERO into the RA register field.
1293   // A zero immediate should always be loaded with a single li.
1294   unsigned DefOpc = DefMI.getOpcode();
1295   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1296     return false;
1297   if (!DefMI.getOperand(1).isImm())
1298     return false;
1299   if (DefMI.getOperand(1).getImm() != 0)
1300     return false;
1301 
1302   // Note that we cannot here invert the arguments of an isel in order to fold
1303   // a ZERO into what is presented as the second argument. All we have here
1304   // is the condition bit, and that might come from a CR-logical bit operation.
1305 
1306   const MCInstrDesc &UseMCID = UseMI.getDesc();
1307 
1308   // Only fold into real machine instructions.
1309   if (UseMCID.isPseudo())
1310     return false;
1311 
1312   unsigned UseIdx;
1313   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1314     if (UseMI.getOperand(UseIdx).isReg() &&
1315         UseMI.getOperand(UseIdx).getReg() == Reg)
1316       break;
1317 
1318   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1319   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1320 
1321   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1322 
1323   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1324   // register (which might also be specified as a pointer class kind).
1325   if (UseInfo->isLookupPtrRegClass()) {
1326     if (UseInfo->RegClass /* Kind */ != 1)
1327       return false;
1328   } else {
1329     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1330         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1331       return false;
1332   }
1333 
1334   // Make sure this is not tied to an output register (or otherwise
1335   // constrained). This is true for ST?UX registers, for example, which
1336   // are tied to their output registers.
1337   if (UseInfo->Constraints != 0)
1338     return false;
1339 
1340   unsigned ZeroReg;
1341   if (UseInfo->isLookupPtrRegClass()) {
1342     bool isPPC64 = Subtarget.isPPC64();
1343     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1344   } else {
1345     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1346               PPC::ZERO8 : PPC::ZERO;
1347   }
1348 
1349   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1350   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1351 
1352   if (DeleteDef)
1353     DefMI.eraseFromParent();
1354 
1355   return true;
1356 }
1357 
1358 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1359   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1360        I != IE; ++I)
1361     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1362       return true;
1363   return false;
1364 }
1365 
1366 // We should make sure that, if we're going to predicate both sides of a
1367 // condition (a diamond), that both sides don't define the counter register. We
1368 // can predicate counter-decrement-based branches, but while that predicates
1369 // the branching, it does not predicate the counter decrement. If we tried to
1370 // merge the triangle into one predicated block, we'd decrement the counter
1371 // twice.
1372 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1373                      unsigned NumT, unsigned ExtraT,
1374                      MachineBasicBlock &FMBB,
1375                      unsigned NumF, unsigned ExtraF,
1376                      BranchProbability Probability) const {
1377   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1378 }
1379 
1380 
1381 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1382   // The predicated branches are identified by their type, not really by the
1383   // explicit presence of a predicate. Furthermore, some of them can be
1384   // predicated more than once. Because if conversion won't try to predicate
1385   // any instruction which already claims to be predicated (by returning true
1386   // here), always return false. In doing so, we let isPredicable() be the
1387   // final word on whether not the instruction can be (further) predicated.
1388 
1389   return false;
1390 }
1391 
1392 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
1393   if (!MI.isTerminator())
1394     return false;
1395 
1396   // Conditional branch is a special case.
1397   if (MI.isBranch() && !MI.isBarrier())
1398     return true;
1399 
1400   return !isPredicated(MI);
1401 }
1402 
1403 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1404                                         ArrayRef<MachineOperand> Pred) const {
1405   unsigned OpC = MI.getOpcode();
1406   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1407     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1408       bool isPPC64 = Subtarget.isPPC64();
1409       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1410                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1411     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1412       MI.setDesc(get(PPC::BCLR));
1413       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1414           .addReg(Pred[1].getReg());
1415     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1416       MI.setDesc(get(PPC::BCLRn));
1417       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1418           .addReg(Pred[1].getReg());
1419     } else {
1420       MI.setDesc(get(PPC::BCCLR));
1421       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1422           .addImm(Pred[0].getImm())
1423           .addReg(Pred[1].getReg());
1424     }
1425 
1426     return true;
1427   } else if (OpC == PPC::B) {
1428     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1429       bool isPPC64 = Subtarget.isPPC64();
1430       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1431                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1432     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1433       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1434       MI.RemoveOperand(0);
1435 
1436       MI.setDesc(get(PPC::BC));
1437       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1438           .addReg(Pred[1].getReg())
1439           .addMBB(MBB);
1440     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1441       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1442       MI.RemoveOperand(0);
1443 
1444       MI.setDesc(get(PPC::BCn));
1445       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1446           .addReg(Pred[1].getReg())
1447           .addMBB(MBB);
1448     } else {
1449       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1450       MI.RemoveOperand(0);
1451 
1452       MI.setDesc(get(PPC::BCC));
1453       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1454           .addImm(Pred[0].getImm())
1455           .addReg(Pred[1].getReg())
1456           .addMBB(MBB);
1457     }
1458 
1459     return true;
1460   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1461              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1462     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1463       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1464 
1465     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1466     bool isPPC64 = Subtarget.isPPC64();
1467 
1468     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1469       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1470                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1471       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1472           .addReg(Pred[1].getReg());
1473       return true;
1474     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1475       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1476                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1477       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1478           .addReg(Pred[1].getReg());
1479       return true;
1480     }
1481 
1482     MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1483                            : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1484     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1485         .addImm(Pred[0].getImm())
1486         .addReg(Pred[1].getReg());
1487     return true;
1488   }
1489 
1490   return false;
1491 }
1492 
1493 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1494                                      ArrayRef<MachineOperand> Pred2) const {
1495   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1496   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1497 
1498   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1499     return false;
1500   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1501     return false;
1502 
1503   // P1 can only subsume P2 if they test the same condition register.
1504   if (Pred1[1].getReg() != Pred2[1].getReg())
1505     return false;
1506 
1507   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1508   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1509 
1510   if (P1 == P2)
1511     return true;
1512 
1513   // Does P1 subsume P2, e.g. GE subsumes GT.
1514   if (P1 == PPC::PRED_LE &&
1515       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1516     return true;
1517   if (P1 == PPC::PRED_GE &&
1518       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1519     return true;
1520 
1521   return false;
1522 }
1523 
1524 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1525                                     std::vector<MachineOperand> &Pred) const {
1526   // Note: At the present time, the contents of Pred from this function is
1527   // unused by IfConversion. This implementation follows ARM by pushing the
1528   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1529   // predicate, instructions defining CTR or CTR8 are also included as
1530   // predicate-defining instructions.
1531 
1532   const TargetRegisterClass *RCs[] =
1533     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1534       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1535 
1536   bool Found = false;
1537   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1538     const MachineOperand &MO = MI.getOperand(i);
1539     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1540       const TargetRegisterClass *RC = RCs[c];
1541       if (MO.isReg()) {
1542         if (MO.isDef() && RC->contains(MO.getReg())) {
1543           Pred.push_back(MO);
1544           Found = true;
1545         }
1546       } else if (MO.isRegMask()) {
1547         for (TargetRegisterClass::iterator I = RC->begin(),
1548              IE = RC->end(); I != IE; ++I)
1549           if (MO.clobbersPhysReg(*I)) {
1550             Pred.push_back(MO);
1551             Found = true;
1552           }
1553       }
1554     }
1555   }
1556 
1557   return Found;
1558 }
1559 
1560 bool PPCInstrInfo::isPredicable(const MachineInstr &MI) const {
1561   unsigned OpC = MI.getOpcode();
1562   switch (OpC) {
1563   default:
1564     return false;
1565   case PPC::B:
1566   case PPC::BLR:
1567   case PPC::BLR8:
1568   case PPC::BCTR:
1569   case PPC::BCTR8:
1570   case PPC::BCTRL:
1571   case PPC::BCTRL8:
1572     return true;
1573   }
1574 }
1575 
1576 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1577                                   unsigned &SrcReg2, int &Mask,
1578                                   int &Value) const {
1579   unsigned Opc = MI.getOpcode();
1580 
1581   switch (Opc) {
1582   default: return false;
1583   case PPC::CMPWI:
1584   case PPC::CMPLWI:
1585   case PPC::CMPDI:
1586   case PPC::CMPLDI:
1587     SrcReg = MI.getOperand(1).getReg();
1588     SrcReg2 = 0;
1589     Value = MI.getOperand(2).getImm();
1590     Mask = 0xFFFF;
1591     return true;
1592   case PPC::CMPW:
1593   case PPC::CMPLW:
1594   case PPC::CMPD:
1595   case PPC::CMPLD:
1596   case PPC::FCMPUS:
1597   case PPC::FCMPUD:
1598     SrcReg = MI.getOperand(1).getReg();
1599     SrcReg2 = MI.getOperand(2).getReg();
1600     Value = 0;
1601     Mask = 0;
1602     return true;
1603   }
1604 }
1605 
1606 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1607                                         unsigned SrcReg2, int Mask, int Value,
1608                                         const MachineRegisterInfo *MRI) const {
1609   if (DisableCmpOpt)
1610     return false;
1611 
1612   int OpC = CmpInstr.getOpcode();
1613   unsigned CRReg = CmpInstr.getOperand(0).getReg();
1614 
1615   // FP record forms set CR1 based on the execption status bits, not a
1616   // comparison with zero.
1617   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1618     return false;
1619 
1620   // The record forms set the condition register based on a signed comparison
1621   // with zero (so says the ISA manual). This is not as straightforward as it
1622   // seems, however, because this is always a 64-bit comparison on PPC64, even
1623   // for instructions that are 32-bit in nature (like slw for example).
1624   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1625   // for equality checks (as those don't depend on the sign). On PPC64,
1626   // we are restricted to equality for unsigned 64-bit comparisons and for
1627   // signed 32-bit comparisons the applicability is more restricted.
1628   bool isPPC64 = Subtarget.isPPC64();
1629   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1630   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1631   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1632 
1633   // Get the unique definition of SrcReg.
1634   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1635   if (!MI) return false;
1636   int MIOpC = MI->getOpcode();
1637 
1638   bool equalityOnly = false;
1639   bool noSub = false;
1640   if (isPPC64) {
1641     if (is32BitSignedCompare) {
1642       // We can perform this optimization only if MI is sign-extending.
1643       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1644           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1645           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1646           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1647           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1648         noSub = true;
1649       } else
1650         return false;
1651     } else if (is32BitUnsignedCompare) {
1652       // 32-bit rotate and mask instructions are zero extending only if MB <= ME
1653       bool isZeroExtendingRotate  =
1654           (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINMo ||
1655            MIOpC == PPC::RLWNM || MIOpC == PPC::RLWNMo)
1656           && MI->getOperand(3).getImm() <= MI->getOperand(4).getImm();
1657 
1658       // We can perform this optimization, equality only, if MI is
1659       // zero-extending.
1660       // FIXME: Other possible target instructions include ANDISo and
1661       //        RLWINM aliases, such as ROTRWI, EXTLWI, SLWI and SRWI.
1662       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1663           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1664           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo ||
1665           MIOpC == PPC::ANDIo  ||
1666           isZeroExtendingRotate) {
1667         noSub = true;
1668         equalityOnly = true;
1669       } else
1670         return false;
1671     } else
1672       equalityOnly = is64BitUnsignedCompare;
1673   } else
1674     equalityOnly = is32BitUnsignedCompare;
1675 
1676   if (equalityOnly) {
1677     // We need to check the uses of the condition register in order to reject
1678     // non-equality comparisons.
1679     for (MachineRegisterInfo::use_instr_iterator
1680          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1681          I != IE; ++I) {
1682       MachineInstr *UseMI = &*I;
1683       if (UseMI->getOpcode() == PPC::BCC) {
1684         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1685         unsigned PredCond = PPC::getPredicateCondition(Pred);
1686         // We ignore hint bits when checking for non-equality comparisons.
1687         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1688           return false;
1689       } else if (UseMI->getOpcode() == PPC::ISEL ||
1690                  UseMI->getOpcode() == PPC::ISEL8) {
1691         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1692         if (SubIdx != PPC::sub_eq)
1693           return false;
1694       } else
1695         return false;
1696     }
1697   }
1698 
1699   MachineBasicBlock::iterator I = CmpInstr;
1700 
1701   // Scan forward to find the first use of the compare.
1702   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1703        ++I) {
1704     bool FoundUse = false;
1705     for (MachineRegisterInfo::use_instr_iterator
1706          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1707          J != JE; ++J)
1708       if (&*J == &*I) {
1709         FoundUse = true;
1710         break;
1711       }
1712 
1713     if (FoundUse)
1714       break;
1715   }
1716 
1717   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1718   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1719 
1720   // There are two possible candidates which can be changed to set CR[01].
1721   // One is MI, the other is a SUB instruction.
1722   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1723   MachineInstr *Sub = nullptr;
1724   if (SrcReg2 != 0)
1725     // MI is not a candidate for CMPrr.
1726     MI = nullptr;
1727   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1728   // same BB as the comparison. This is to allow the check below to avoid calls
1729   // (and other explicit clobbers); instead we should really check for these
1730   // more explicitly (in at least a few predecessors).
1731   else if (MI->getParent() != CmpInstr.getParent())
1732     return false;
1733   else if (Value != 0) {
1734     // The record-form instructions set CR bit based on signed comparison against 0.
1735     // We try to convert a compare against 1 or -1 into a compare against 0.
1736     bool Success = false;
1737     if (!equalityOnly && MRI->hasOneUse(CRReg)) {
1738       MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1739       if (UseMI->getOpcode() == PPC::BCC) {
1740         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1741         unsigned PredCond = PPC::getPredicateCondition(Pred);
1742         unsigned PredHint = PPC::getPredicateHint(Pred);
1743         int16_t Immed = (int16_t)Value;
1744 
1745         // When modyfing the condition in the predicate, we propagate hint bits
1746         // from the original predicate to the new one.
1747         if (Immed == -1 && PredCond == PPC::PRED_GT) {
1748           // We convert "greater than -1" into "greater than or equal to 0",
1749           // since we are assuming signed comparison by !equalityOnly
1750           PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1751                                   PPC::getPredicate(PPC::PRED_GE, PredHint)));
1752           Success = true;
1753         }
1754         else if (Immed == 1 && PredCond == PPC::PRED_LT) {
1755           // We convert "less than 1" into "less than or equal to 0".
1756           PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1757                                   PPC::getPredicate(PPC::PRED_LE, PredHint)));
1758           Success = true;
1759         }
1760       }
1761     }
1762 
1763     // PPC does not have a record-form SUBri.
1764     if (!Success)
1765       return false;
1766   }
1767 
1768   // Search for Sub.
1769   const TargetRegisterInfo *TRI = &getRegisterInfo();
1770   --I;
1771 
1772   // Get ready to iterate backward from CmpInstr.
1773   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1774 
1775   for (; I != E && !noSub; --I) {
1776     const MachineInstr &Instr = *I;
1777     unsigned IOpC = Instr.getOpcode();
1778 
1779     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1780                              Instr.readsRegister(PPC::CR0, TRI)))
1781       // This instruction modifies or uses the record condition register after
1782       // the one we want to change. While we could do this transformation, it
1783       // would likely not be profitable. This transformation removes one
1784       // instruction, and so even forcing RA to generate one move probably
1785       // makes it unprofitable.
1786       return false;
1787 
1788     // Check whether CmpInstr can be made redundant by the current instruction.
1789     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1790          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1791         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1792         ((Instr.getOperand(1).getReg() == SrcReg &&
1793           Instr.getOperand(2).getReg() == SrcReg2) ||
1794         (Instr.getOperand(1).getReg() == SrcReg2 &&
1795          Instr.getOperand(2).getReg() == SrcReg))) {
1796       Sub = &*I;
1797       break;
1798     }
1799 
1800     if (I == B)
1801       // The 'and' is below the comparison instruction.
1802       return false;
1803   }
1804 
1805   // Return false if no candidates exist.
1806   if (!MI && !Sub)
1807     return false;
1808 
1809   // The single candidate is called MI.
1810   if (!MI) MI = Sub;
1811 
1812   int NewOpC = -1;
1813   MIOpC = MI->getOpcode();
1814   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1815     NewOpC = MIOpC;
1816   else {
1817     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1818     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1819       NewOpC = MIOpC;
1820   }
1821 
1822   // FIXME: On the non-embedded POWER architectures, only some of the record
1823   // forms are fast, and we should use only the fast ones.
1824 
1825   // The defining instruction has a record form (or is already a record
1826   // form). It is possible, however, that we'll need to reverse the condition
1827   // code of the users.
1828   if (NewOpC == -1)
1829     return false;
1830 
1831   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1832   // needs to be updated to be based on SUB.  Push the condition code
1833   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1834   // condition code of these operands will be modified.
1835   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1836   // comparison against 0, which may modify predicate.
1837   bool ShouldSwap = false;
1838   if (Sub && Value == 0) {
1839     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1840       Sub->getOperand(2).getReg() == SrcReg;
1841 
1842     // The operands to subf are the opposite of sub, so only in the fixed-point
1843     // case, invert the order.
1844     ShouldSwap = !ShouldSwap;
1845   }
1846 
1847   if (ShouldSwap)
1848     for (MachineRegisterInfo::use_instr_iterator
1849          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1850          I != IE; ++I) {
1851       MachineInstr *UseMI = &*I;
1852       if (UseMI->getOpcode() == PPC::BCC) {
1853         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1854         unsigned PredCond = PPC::getPredicateCondition(Pred);
1855         assert((!equalityOnly ||
1856                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1857                "Invalid predicate for equality-only optimization");
1858         (void)PredCond; // To suppress warning in release build.
1859         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1860                                 PPC::getSwappedPredicate(Pred)));
1861       } else if (UseMI->getOpcode() == PPC::ISEL ||
1862                  UseMI->getOpcode() == PPC::ISEL8) {
1863         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1864         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1865                "Invalid CR bit for equality-only optimization");
1866 
1867         if (NewSubReg == PPC::sub_lt)
1868           NewSubReg = PPC::sub_gt;
1869         else if (NewSubReg == PPC::sub_gt)
1870           NewSubReg = PPC::sub_lt;
1871 
1872         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1873                                                  NewSubReg));
1874       } else // We need to abort on a user we don't understand.
1875         return false;
1876     }
1877   assert(!(Value != 0 && ShouldSwap) &&
1878          "Non-zero immediate support and ShouldSwap"
1879          "may conflict in updating predicate");
1880 
1881   // Create a new virtual register to hold the value of the CR set by the
1882   // record-form instruction. If the instruction was not previously in
1883   // record form, then set the kill flag on the CR.
1884   CmpInstr.eraseFromParent();
1885 
1886   MachineBasicBlock::iterator MII = MI;
1887   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1888           get(TargetOpcode::COPY), CRReg)
1889     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1890 
1891   // Even if CR0 register were dead before, it is alive now since the
1892   // instruction we just built uses it.
1893   MI->clearRegisterDeads(PPC::CR0);
1894 
1895   if (MIOpC != NewOpC) {
1896     // We need to be careful here: we're replacing one instruction with
1897     // another, and we need to make sure that we get all of the right
1898     // implicit uses and defs. On the other hand, the caller may be holding
1899     // an iterator to this instruction, and so we can't delete it (this is
1900     // specifically the case if this is the instruction directly after the
1901     // compare).
1902 
1903     const MCInstrDesc &NewDesc = get(NewOpC);
1904     MI->setDesc(NewDesc);
1905 
1906     if (NewDesc.ImplicitDefs)
1907       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
1908            *ImpDefs; ++ImpDefs)
1909         if (!MI->definesRegister(*ImpDefs))
1910           MI->addOperand(*MI->getParent()->getParent(),
1911                          MachineOperand::CreateReg(*ImpDefs, true, true));
1912     if (NewDesc.ImplicitUses)
1913       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
1914            *ImpUses; ++ImpUses)
1915         if (!MI->readsRegister(*ImpUses))
1916           MI->addOperand(*MI->getParent()->getParent(),
1917                          MachineOperand::CreateReg(*ImpUses, false, true));
1918   }
1919   assert(MI->definesRegister(PPC::CR0) &&
1920          "Record-form instruction does not define cr0?");
1921 
1922   // Modify the condition code of operands in OperandsToUpdate.
1923   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1924   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1925   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1926     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1927 
1928   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1929     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1930 
1931   return true;
1932 }
1933 
1934 /// GetInstSize - Return the number of bytes of code the specified
1935 /// instruction may be.  This returns the maximum number of bytes.
1936 ///
1937 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
1938   unsigned Opcode = MI.getOpcode();
1939 
1940   if (Opcode == PPC::INLINEASM) {
1941     const MachineFunction *MF = MI.getParent()->getParent();
1942     const char *AsmStr = MI.getOperand(0).getSymbolName();
1943     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1944   } else if (Opcode == TargetOpcode::STACKMAP) {
1945     StackMapOpers Opers(&MI);
1946     return Opers.getNumPatchBytes();
1947   } else if (Opcode == TargetOpcode::PATCHPOINT) {
1948     PatchPointOpers Opers(&MI);
1949     return Opers.getNumPatchBytes();
1950   } else {
1951     return get(Opcode).getSize();
1952   }
1953 }
1954 
1955 std::pair<unsigned, unsigned>
1956 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1957   const unsigned Mask = PPCII::MO_ACCESS_MASK;
1958   return std::make_pair(TF & Mask, TF & ~Mask);
1959 }
1960 
1961 ArrayRef<std::pair<unsigned, const char *>>
1962 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
1963   using namespace PPCII;
1964   static const std::pair<unsigned, const char *> TargetFlags[] = {
1965       {MO_LO, "ppc-lo"},
1966       {MO_HA, "ppc-ha"},
1967       {MO_TPREL_LO, "ppc-tprel-lo"},
1968       {MO_TPREL_HA, "ppc-tprel-ha"},
1969       {MO_DTPREL_LO, "ppc-dtprel-lo"},
1970       {MO_TLSLD_LO, "ppc-tlsld-lo"},
1971       {MO_TOC_LO, "ppc-toc-lo"},
1972       {MO_TLS, "ppc-tls"}};
1973   return makeArrayRef(TargetFlags);
1974 }
1975 
1976 ArrayRef<std::pair<unsigned, const char *>>
1977 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
1978   using namespace PPCII;
1979   static const std::pair<unsigned, const char *> TargetFlags[] = {
1980       {MO_PLT, "ppc-plt"},
1981       {MO_PIC_FLAG, "ppc-pic"},
1982       {MO_NLP_FLAG, "ppc-nlp"},
1983       {MO_NLP_HIDDEN_FLAG, "ppc-nlp-hidden"}};
1984   return makeArrayRef(TargetFlags);
1985 }
1986 
1987 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1988   auto &MBB = *MI.getParent();
1989   auto DL = MI.getDebugLoc();
1990   switch (MI.getOpcode()) {
1991   case TargetOpcode::LOAD_STACK_GUARD: {
1992     assert(Subtarget.isTargetLinux() &&
1993            "Only Linux target is expected to contain LOAD_STACK_GUARD");
1994     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
1995     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
1996     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
1997     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1998         .addImm(Offset)
1999         .addReg(Reg);
2000     return true;
2001   }
2002   case PPC::DFLOADf32:
2003   case PPC::DFLOADf64:
2004   case PPC::DFSTOREf32:
2005   case PPC::DFSTOREf64: {
2006     assert(Subtarget.hasP9Vector() &&
2007            "Invalid D-Form Pseudo-ops on non-P9 target.");
2008     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isImm() &&
2009            "D-form op must have register and immediate operands");
2010     unsigned UpperOpcode, LowerOpcode;
2011     switch (MI.getOpcode()) {
2012     case PPC::DFLOADf32:
2013       UpperOpcode = PPC::LXSSP;
2014       LowerOpcode = PPC::LFS;
2015       break;
2016     case PPC::DFLOADf64:
2017       UpperOpcode = PPC::LXSD;
2018       LowerOpcode = PPC::LFD;
2019       break;
2020     case PPC::DFSTOREf32:
2021       UpperOpcode = PPC::STXSSP;
2022       LowerOpcode = PPC::STFS;
2023       break;
2024     case PPC::DFSTOREf64:
2025       UpperOpcode = PPC::STXSD;
2026       LowerOpcode = PPC::STFD;
2027       break;
2028     }
2029     unsigned TargetReg = MI.getOperand(0).getReg();
2030     unsigned Opcode;
2031     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2032         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2033       Opcode = LowerOpcode;
2034     else
2035       Opcode = UpperOpcode;
2036     MI.setDesc(get(Opcode));
2037     return true;
2038   }
2039   case PPC::SPILLTOVSR_LD: {
2040     unsigned TargetReg = MI.getOperand(0).getReg();
2041     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2042       MI.setDesc(get(PPC::DFLOADf64));
2043       return expandPostRAPseudo(MI);
2044     }
2045     else
2046       MI.setDesc(get(PPC::LD));
2047     return true;
2048   }
2049   case PPC::SPILLTOVSR_ST: {
2050     unsigned SrcReg = MI.getOperand(0).getReg();
2051     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2052       NumStoreSPILLVSRRCAsVec++;
2053       MI.setDesc(get(PPC::DFSTOREf64));
2054       return expandPostRAPseudo(MI);
2055     } else {
2056       NumStoreSPILLVSRRCAsGpr++;
2057       MI.setDesc(get(PPC::STD));
2058     }
2059     return true;
2060   }
2061   case PPC::SPILLTOVSR_LDX: {
2062     unsigned TargetReg = MI.getOperand(0).getReg();
2063     if (PPC::VSFRCRegClass.contains(TargetReg))
2064       MI.setDesc(get(PPC::LXSDX));
2065     else
2066       MI.setDesc(get(PPC::LDX));
2067     return true;
2068   }
2069   case PPC::SPILLTOVSR_STX: {
2070     unsigned SrcReg = MI.getOperand(0).getReg();
2071     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2072       NumStoreSPILLVSRRCAsVec++;
2073       MI.setDesc(get(PPC::STXSDX));
2074     } else {
2075       NumStoreSPILLVSRRCAsGpr++;
2076       MI.setDesc(get(PPC::STDX));
2077     }
2078     return true;
2079   }
2080 
2081   case PPC::CFENCE8: {
2082     auto Val = MI.getOperand(0).getReg();
2083     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2084     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2085         .addImm(PPC::PRED_NE_MINUS)
2086         .addReg(PPC::CR7)
2087         .addImm(1);
2088     MI.setDesc(get(PPC::ISYNC));
2089     MI.RemoveOperand(0);
2090     return true;
2091   }
2092   }
2093   return false;
2094 }
2095 
2096 const TargetRegisterClass *
2097 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
2098   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
2099     return &PPC::VSRCRegClass;
2100   return RC;
2101 }
2102 
2103 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
2104   return PPC::getRecordFormOpcode(Opcode);
2105 }
2106