1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the PowerPC implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCInstrInfo.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCHazardRecognizers.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/CodeGen/ScheduleDAG.h"
30 #include "llvm/CodeGen/SlotIndexes.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "ppc-instr-info"
43 
44 #define GET_INSTRMAP_INFO
45 #define GET_INSTRINFO_CTOR_DTOR
46 #include "PPCGenInstrInfo.inc"
47 
48 STATISTIC(NumStoreSPILLVSRRCAsVec,
49           "Number of spillvsrrc spilled to stack as vec");
50 STATISTIC(NumStoreSPILLVSRRCAsGpr,
51           "Number of spillvsrrc spilled to stack as gpr");
52 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
53 STATISTIC(CmpIselsConverted,
54           "Number of ISELs that depend on comparison of constants converted");
55 STATISTIC(MissedConvertibleImmediateInstrs,
56           "Number of compare-immediate instructions fed by constants");
57 STATISTIC(NumRcRotatesConvertedToRcAnd,
58           "Number of record-form rotates converted to record-form andi");
59 
60 static cl::
61 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
62             cl::desc("Disable analysis for CTR loops"));
63 
64 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
65 cl::desc("Disable compare instruction optimization"), cl::Hidden);
66 
67 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
68 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
69 cl::Hidden);
70 
71 static cl::opt<bool>
72 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
73   cl::desc("Use the old (incorrect) instruction latency calculation"));
74 
75 // Index into the OpcodesForSpill array.
76 enum SpillOpcodeKey {
77   SOK_Int4Spill,
78   SOK_Int8Spill,
79   SOK_Float8Spill,
80   SOK_Float4Spill,
81   SOK_CRSpill,
82   SOK_CRBitSpill,
83   SOK_VRVectorSpill,
84   SOK_VSXVectorSpill,
85   SOK_VectorFloat8Spill,
86   SOK_VectorFloat4Spill,
87   SOK_VRSaveSpill,
88   SOK_QuadFloat8Spill,
89   SOK_QuadFloat4Spill,
90   SOK_QuadBitSpill,
91   SOK_SpillToVSR,
92   SOK_SPESpill,
93   SOK_SPE4Spill,
94   SOK_LastOpcodeSpill  // This must be last on the enum.
95 };
96 
97 // Pin the vtable to this file.
98 void PPCInstrInfo::anchor() {}
99 
100 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
101     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
102                       /* CatchRetOpcode */ -1,
103                       STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
104       Subtarget(STI), RI(STI.getTargetMachine()) {}
105 
106 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
107 /// this target when scheduling the DAG.
108 ScheduleHazardRecognizer *
109 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
110                                            const ScheduleDAG *DAG) const {
111   unsigned Directive =
112       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
113   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
114       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
115     const InstrItineraryData *II =
116         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
117     return new ScoreboardHazardRecognizer(II, DAG);
118   }
119 
120   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
121 }
122 
123 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
124 /// to use for this target when scheduling the DAG.
125 ScheduleHazardRecognizer *
126 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
127                                                  const ScheduleDAG *DAG) const {
128   unsigned Directive =
129       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
130 
131   // FIXME: Leaving this as-is until we have POWER9 scheduling info
132   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
133     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
134 
135   // Most subtargets use a PPC970 recognizer.
136   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
137       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
138     assert(DAG->TII && "No InstrInfo?");
139 
140     return new PPCHazardRecognizer970(*DAG);
141   }
142 
143   return new ScoreboardHazardRecognizer(II, DAG);
144 }
145 
146 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
147                                        const MachineInstr &MI,
148                                        unsigned *PredCost) const {
149   if (!ItinData || UseOldLatencyCalc)
150     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
151 
152   // The default implementation of getInstrLatency calls getStageLatency, but
153   // getStageLatency does not do the right thing for us. While we have
154   // itinerary, most cores are fully pipelined, and so the itineraries only
155   // express the first part of the pipeline, not every stage. Instead, we need
156   // to use the listed output operand cycle number (using operand 0 here, which
157   // is an output).
158 
159   unsigned Latency = 1;
160   unsigned DefClass = MI.getDesc().getSchedClass();
161   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
162     const MachineOperand &MO = MI.getOperand(i);
163     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
164       continue;
165 
166     int Cycle = ItinData->getOperandCycle(DefClass, i);
167     if (Cycle < 0)
168       continue;
169 
170     Latency = std::max(Latency, (unsigned) Cycle);
171   }
172 
173   return Latency;
174 }
175 
176 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
177                                     const MachineInstr &DefMI, unsigned DefIdx,
178                                     const MachineInstr &UseMI,
179                                     unsigned UseIdx) const {
180   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
181                                                    UseMI, UseIdx);
182 
183   if (!DefMI.getParent())
184     return Latency;
185 
186   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
187   unsigned Reg = DefMO.getReg();
188 
189   bool IsRegCR;
190   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
191     const MachineRegisterInfo *MRI =
192         &DefMI.getParent()->getParent()->getRegInfo();
193     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
194               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
195   } else {
196     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
197               PPC::CRBITRCRegClass.contains(Reg);
198   }
199 
200   if (UseMI.isBranch() && IsRegCR) {
201     if (Latency < 0)
202       Latency = getInstrLatency(ItinData, DefMI);
203 
204     // On some cores, there is an additional delay between writing to a condition
205     // register, and using it from a branch.
206     unsigned Directive = Subtarget.getDarwinDirective();
207     switch (Directive) {
208     default: break;
209     case PPC::DIR_7400:
210     case PPC::DIR_750:
211     case PPC::DIR_970:
212     case PPC::DIR_E5500:
213     case PPC::DIR_PWR4:
214     case PPC::DIR_PWR5:
215     case PPC::DIR_PWR5X:
216     case PPC::DIR_PWR6:
217     case PPC::DIR_PWR6X:
218     case PPC::DIR_PWR7:
219     case PPC::DIR_PWR8:
220     // FIXME: Is this needed for POWER9?
221       Latency += 2;
222       break;
223     }
224   }
225 
226   return Latency;
227 }
228 
229 // This function does not list all associative and commutative operations, but
230 // only those worth feeding through the machine combiner in an attempt to
231 // reduce the critical path. Mostly, this means floating-point operations,
232 // because they have high latencies (compared to other operations, such and
233 // and/or, which are also associative and commutative, but have low latencies).
234 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
235   switch (Inst.getOpcode()) {
236   // FP Add:
237   case PPC::FADD:
238   case PPC::FADDS:
239   // FP Multiply:
240   case PPC::FMUL:
241   case PPC::FMULS:
242   // Altivec Add:
243   case PPC::VADDFP:
244   // VSX Add:
245   case PPC::XSADDDP:
246   case PPC::XVADDDP:
247   case PPC::XVADDSP:
248   case PPC::XSADDSP:
249   // VSX Multiply:
250   case PPC::XSMULDP:
251   case PPC::XVMULDP:
252   case PPC::XVMULSP:
253   case PPC::XSMULSP:
254   // QPX Add:
255   case PPC::QVFADD:
256   case PPC::QVFADDS:
257   case PPC::QVFADDSs:
258   // QPX Multiply:
259   case PPC::QVFMUL:
260   case PPC::QVFMULS:
261   case PPC::QVFMULSs:
262     return true;
263   default:
264     return false;
265   }
266 }
267 
268 bool PPCInstrInfo::getMachineCombinerPatterns(
269     MachineInstr &Root,
270     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
271   // Using the machine combiner in this way is potentially expensive, so
272   // restrict to when aggressive optimizations are desired.
273   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
274     return false;
275 
276   // FP reassociation is only legal when we don't need strict IEEE semantics.
277   if (!Root.getParent()->getParent()->getTarget().Options.UnsafeFPMath)
278     return false;
279 
280   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
281 }
282 
283 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
284 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
285                                          unsigned &SrcReg, unsigned &DstReg,
286                                          unsigned &SubIdx) const {
287   switch (MI.getOpcode()) {
288   default: return false;
289   case PPC::EXTSW:
290   case PPC::EXTSW_32:
291   case PPC::EXTSW_32_64:
292     SrcReg = MI.getOperand(1).getReg();
293     DstReg = MI.getOperand(0).getReg();
294     SubIdx = PPC::sub_32;
295     return true;
296   }
297 }
298 
299 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
300                                            int &FrameIndex) const {
301   unsigned Opcode = MI.getOpcode();
302   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
303   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
304 
305   if (End != std::find(OpcodesForSpill, End, Opcode)) {
306     // Check for the operands added by addFrameReference (the immediate is the
307     // offset which defaults to 0).
308     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
309         MI.getOperand(2).isFI()) {
310       FrameIndex = MI.getOperand(2).getIndex();
311       return MI.getOperand(0).getReg();
312     }
313   }
314   return 0;
315 }
316 
317 // For opcodes with the ReMaterializable flag set, this function is called to
318 // verify the instruction is really rematable.
319 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
320                                                      AliasAnalysis *AA) const {
321   switch (MI.getOpcode()) {
322   default:
323     // This function should only be called for opcodes with the ReMaterializable
324     // flag set.
325     llvm_unreachable("Unknown rematerializable operation!");
326     break;
327   case PPC::LI:
328   case PPC::LI8:
329   case PPC::LIS:
330   case PPC::LIS8:
331   case PPC::QVGPCI:
332   case PPC::ADDIStocHA:
333   case PPC::ADDItocL:
334   case PPC::LOAD_STACK_GUARD:
335     return true;
336   }
337   return false;
338 }
339 
340 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
341                                           int &FrameIndex) const {
342   unsigned Opcode = MI.getOpcode();
343   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
344   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
345 
346   if (End != std::find(OpcodesForSpill, End, Opcode)) {
347     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
348         MI.getOperand(2).isFI()) {
349       FrameIndex = MI.getOperand(2).getIndex();
350       return MI.getOperand(0).getReg();
351     }
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   } else if (PPC::SPERCRegClass.contains(SrcReg) &&
954              PPC::SPE4RCRegClass.contains(DestReg)) {
955     BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
956     getKillRegState(KillSrc);
957     return;
958   } else if (PPC::SPE4RCRegClass.contains(SrcReg) &&
959              PPC::SPERCRegClass.contains(DestReg)) {
960     BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
961     getKillRegState(KillSrc);
962     return;
963   }
964 
965 
966   unsigned Opc;
967   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
968     Opc = PPC::OR;
969   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
970     Opc = PPC::OR8;
971   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
972     Opc = PPC::FMR;
973   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
974     Opc = PPC::MCRF;
975   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
976     Opc = PPC::VOR;
977   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
978     // There are two different ways this can be done:
979     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
980     //      issue in VSU pipeline 0.
981     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
982     //      can go to either pipeline.
983     // We'll always use xxlor here, because in practically all cases where
984     // copies are generated, they are close enough to some use that the
985     // lower-latency form is preferable.
986     Opc = PPC::XXLOR;
987   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
988            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
989     Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
990   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
991     Opc = PPC::QVFMR;
992   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
993     Opc = PPC::QVFMRs;
994   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
995     Opc = PPC::QVFMRb;
996   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
997     Opc = PPC::CROR;
998   else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
999     Opc = PPC::EVOR;
1000   else
1001     llvm_unreachable("Impossible reg-to-reg copy");
1002 
1003   const MCInstrDesc &MCID = get(Opc);
1004   if (MCID.getNumOperands() == 3)
1005     BuildMI(MBB, I, DL, MCID, DestReg)
1006       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1007   else
1008     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1009 }
1010 
1011 unsigned PPCInstrInfo::getStoreOpcodeForSpill(unsigned Reg,
1012                                               const TargetRegisterClass *RC)
1013                                               const {
1014   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1015   int OpcodeIndex = 0;
1016 
1017   if (RC != nullptr) {
1018     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1019         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1020       OpcodeIndex = SOK_Int4Spill;
1021     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1022                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1023       OpcodeIndex = SOK_Int8Spill;
1024     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1025       OpcodeIndex = SOK_Float8Spill;
1026     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1027       OpcodeIndex = SOK_Float4Spill;
1028     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1029       OpcodeIndex = SOK_SPESpill;
1030     } else if (PPC::SPE4RCRegClass.hasSubClassEq(RC)) {
1031       OpcodeIndex = SOK_SPE4Spill;
1032     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1033       OpcodeIndex = SOK_CRSpill;
1034     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1035       OpcodeIndex = SOK_CRBitSpill;
1036     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1037       OpcodeIndex = SOK_VRVectorSpill;
1038     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1039       OpcodeIndex = SOK_VSXVectorSpill;
1040     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1041       OpcodeIndex = SOK_VectorFloat8Spill;
1042     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1043       OpcodeIndex = SOK_VectorFloat4Spill;
1044     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1045       OpcodeIndex = SOK_VRSaveSpill;
1046     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1047       OpcodeIndex = SOK_QuadFloat8Spill;
1048     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1049       OpcodeIndex = SOK_QuadFloat4Spill;
1050     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1051       OpcodeIndex = SOK_QuadBitSpill;
1052     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1053       OpcodeIndex = SOK_SpillToVSR;
1054     } else {
1055       llvm_unreachable("Unknown regclass!");
1056     }
1057   } else {
1058     if (PPC::GPRCRegClass.contains(Reg) ||
1059         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1060       OpcodeIndex = SOK_Int4Spill;
1061     } else if (PPC::G8RCRegClass.contains(Reg) ||
1062                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1063       OpcodeIndex = SOK_Int8Spill;
1064     } else if (PPC::F8RCRegClass.contains(Reg)) {
1065       OpcodeIndex = SOK_Float8Spill;
1066     } else if (PPC::F4RCRegClass.contains(Reg)) {
1067       OpcodeIndex = SOK_Float4Spill;
1068     } else if (PPC::SPERCRegClass.contains(Reg)) {
1069       OpcodeIndex = SOK_SPESpill;
1070     } else if (PPC::SPE4RCRegClass.contains(Reg)) {
1071       OpcodeIndex = SOK_SPE4Spill;
1072     } else if (PPC::CRRCRegClass.contains(Reg)) {
1073       OpcodeIndex = SOK_CRSpill;
1074     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1075       OpcodeIndex = SOK_CRBitSpill;
1076     } else if (PPC::VRRCRegClass.contains(Reg)) {
1077       OpcodeIndex = SOK_VRVectorSpill;
1078     } else if (PPC::VSRCRegClass.contains(Reg)) {
1079       OpcodeIndex = SOK_VSXVectorSpill;
1080     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1081       OpcodeIndex = SOK_VectorFloat8Spill;
1082     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1083       OpcodeIndex = SOK_VectorFloat4Spill;
1084     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1085       OpcodeIndex = SOK_VRSaveSpill;
1086     } else if (PPC::QFRCRegClass.contains(Reg)) {
1087       OpcodeIndex = SOK_QuadFloat8Spill;
1088     } else if (PPC::QSRCRegClass.contains(Reg)) {
1089       OpcodeIndex = SOK_QuadFloat4Spill;
1090     } else if (PPC::QBRCRegClass.contains(Reg)) {
1091       OpcodeIndex = SOK_QuadBitSpill;
1092     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1093       OpcodeIndex = SOK_SpillToVSR;
1094     } else {
1095       llvm_unreachable("Unknown regclass!");
1096     }
1097   }
1098   return OpcodesForSpill[OpcodeIndex];
1099 }
1100 
1101 unsigned
1102 PPCInstrInfo::getLoadOpcodeForSpill(unsigned Reg,
1103                                     const TargetRegisterClass *RC) const {
1104   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1105   int OpcodeIndex = 0;
1106 
1107   if (RC != nullptr) {
1108     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1109         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1110       OpcodeIndex = SOK_Int4Spill;
1111     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1112                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1113       OpcodeIndex = SOK_Int8Spill;
1114     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1115       OpcodeIndex = SOK_Float8Spill;
1116     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1117       OpcodeIndex = SOK_Float4Spill;
1118     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1119       OpcodeIndex = SOK_SPESpill;
1120     } else if (PPC::SPE4RCRegClass.hasSubClassEq(RC)) {
1121       OpcodeIndex = SOK_SPE4Spill;
1122     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1123       OpcodeIndex = SOK_CRSpill;
1124     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1125       OpcodeIndex = SOK_CRBitSpill;
1126     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1127       OpcodeIndex = SOK_VRVectorSpill;
1128     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1129       OpcodeIndex = SOK_VSXVectorSpill;
1130     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1131       OpcodeIndex = SOK_VectorFloat8Spill;
1132     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1133       OpcodeIndex = SOK_VectorFloat4Spill;
1134     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1135       OpcodeIndex = SOK_VRSaveSpill;
1136     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1137       OpcodeIndex = SOK_QuadFloat8Spill;
1138     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1139       OpcodeIndex = SOK_QuadFloat4Spill;
1140     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1141       OpcodeIndex = SOK_QuadBitSpill;
1142     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1143       OpcodeIndex = SOK_SpillToVSR;
1144     } else {
1145       llvm_unreachable("Unknown regclass!");
1146     }
1147   } else {
1148     if (PPC::GPRCRegClass.contains(Reg) ||
1149         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1150       OpcodeIndex = SOK_Int4Spill;
1151     } else if (PPC::G8RCRegClass.contains(Reg) ||
1152                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1153       OpcodeIndex = SOK_Int8Spill;
1154     } else if (PPC::F8RCRegClass.contains(Reg)) {
1155       OpcodeIndex = SOK_Float8Spill;
1156     } else if (PPC::F4RCRegClass.contains(Reg)) {
1157       OpcodeIndex = SOK_Float4Spill;
1158     } else if (PPC::SPERCRegClass.contains(Reg)) {
1159       OpcodeIndex = SOK_SPESpill;
1160     } else if (PPC::SPE4RCRegClass.contains(Reg)) {
1161       OpcodeIndex = SOK_SPE4Spill;
1162     } else if (PPC::CRRCRegClass.contains(Reg)) {
1163       OpcodeIndex = SOK_CRSpill;
1164     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1165       OpcodeIndex = SOK_CRBitSpill;
1166     } else if (PPC::VRRCRegClass.contains(Reg)) {
1167       OpcodeIndex = SOK_VRVectorSpill;
1168     } else if (PPC::VSRCRegClass.contains(Reg)) {
1169       OpcodeIndex = SOK_VSXVectorSpill;
1170     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1171       OpcodeIndex = SOK_VectorFloat8Spill;
1172     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1173       OpcodeIndex = SOK_VectorFloat4Spill;
1174     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1175       OpcodeIndex = SOK_VRSaveSpill;
1176     } else if (PPC::QFRCRegClass.contains(Reg)) {
1177       OpcodeIndex = SOK_QuadFloat8Spill;
1178     } else if (PPC::QSRCRegClass.contains(Reg)) {
1179       OpcodeIndex = SOK_QuadFloat4Spill;
1180     } else if (PPC::QBRCRegClass.contains(Reg)) {
1181       OpcodeIndex = SOK_QuadBitSpill;
1182     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1183       OpcodeIndex = SOK_SpillToVSR;
1184     } else {
1185       llvm_unreachable("Unknown regclass!");
1186     }
1187   }
1188   return OpcodesForSpill[OpcodeIndex];
1189 }
1190 
1191 void PPCInstrInfo::StoreRegToStackSlot(
1192     MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1193     const TargetRegisterClass *RC,
1194     SmallVectorImpl<MachineInstr *> &NewMIs) const {
1195   unsigned Opcode = getStoreOpcodeForSpill(PPC::NoRegister, RC);
1196   DebugLoc DL;
1197 
1198   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1199   FuncInfo->setHasSpills();
1200 
1201   NewMIs.push_back(addFrameReference(
1202       BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1203       FrameIdx));
1204 
1205   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1206       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1207     FuncInfo->setSpillsCR();
1208 
1209   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1210     FuncInfo->setSpillsVRSAVE();
1211 
1212   if (isXFormMemOp(Opcode))
1213     FuncInfo->setHasNonRISpills();
1214 }
1215 
1216 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1217                                        MachineBasicBlock::iterator MI,
1218                                        unsigned SrcReg, bool isKill,
1219                                        int FrameIdx,
1220                                        const TargetRegisterClass *RC,
1221                                        const TargetRegisterInfo *TRI) const {
1222   MachineFunction &MF = *MBB.getParent();
1223   SmallVector<MachineInstr *, 4> NewMIs;
1224 
1225   // We need to avoid a situation in which the value from a VRRC register is
1226   // spilled using an Altivec instruction and reloaded into a VSRC register
1227   // using a VSX instruction. The issue with this is that the VSX
1228   // load/store instructions swap the doublewords in the vector and the Altivec
1229   // ones don't. The register classes on the spill/reload may be different if
1230   // the register is defined using an Altivec instruction and is then used by a
1231   // VSX instruction.
1232   RC = updatedRC(RC);
1233 
1234   StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1235 
1236   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1237     MBB.insert(MI, NewMIs[i]);
1238 
1239   const MachineFrameInfo &MFI = MF.getFrameInfo();
1240   MachineMemOperand *MMO = MF.getMachineMemOperand(
1241       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1242       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1243       MFI.getObjectAlignment(FrameIdx));
1244   NewMIs.back()->addMemOperand(MF, MMO);
1245 }
1246 
1247 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1248                                         unsigned DestReg, int FrameIdx,
1249                                         const TargetRegisterClass *RC,
1250                                         SmallVectorImpl<MachineInstr *> &NewMIs)
1251                                         const {
1252   unsigned Opcode = getLoadOpcodeForSpill(PPC::NoRegister, RC);
1253   NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1254                                      FrameIdx));
1255   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1256 
1257   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1258       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1259     FuncInfo->setSpillsCR();
1260 
1261   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1262     FuncInfo->setSpillsVRSAVE();
1263 
1264   if (isXFormMemOp(Opcode))
1265     FuncInfo->setHasNonRISpills();
1266 }
1267 
1268 void
1269 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1270                                    MachineBasicBlock::iterator MI,
1271                                    unsigned DestReg, int FrameIdx,
1272                                    const TargetRegisterClass *RC,
1273                                    const TargetRegisterInfo *TRI) const {
1274   MachineFunction &MF = *MBB.getParent();
1275   SmallVector<MachineInstr*, 4> NewMIs;
1276   DebugLoc DL;
1277   if (MI != MBB.end()) DL = MI->getDebugLoc();
1278 
1279   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1280   FuncInfo->setHasSpills();
1281 
1282   // We need to avoid a situation in which the value from a VRRC register is
1283   // spilled using an Altivec instruction and reloaded into a VSRC register
1284   // using a VSX instruction. The issue with this is that the VSX
1285   // load/store instructions swap the doublewords in the vector and the Altivec
1286   // ones don't. The register classes on the spill/reload may be different if
1287   // the register is defined using an Altivec instruction and is then used by a
1288   // VSX instruction.
1289   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
1290     RC = &PPC::VSRCRegClass;
1291 
1292   LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1293 
1294   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1295     MBB.insert(MI, NewMIs[i]);
1296 
1297   const MachineFrameInfo &MFI = MF.getFrameInfo();
1298   MachineMemOperand *MMO = MF.getMachineMemOperand(
1299       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1300       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1301       MFI.getObjectAlignment(FrameIdx));
1302   NewMIs.back()->addMemOperand(MF, MMO);
1303 }
1304 
1305 bool PPCInstrInfo::
1306 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1307   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1308   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1309     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1310   else
1311     // Leave the CR# the same, but invert the condition.
1312     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1313   return false;
1314 }
1315 
1316 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1317                                  unsigned Reg, MachineRegisterInfo *MRI) const {
1318   // For some instructions, it is legal to fold ZERO into the RA register field.
1319   // A zero immediate should always be loaded with a single li.
1320   unsigned DefOpc = DefMI.getOpcode();
1321   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1322     return false;
1323   if (!DefMI.getOperand(1).isImm())
1324     return false;
1325   if (DefMI.getOperand(1).getImm() != 0)
1326     return false;
1327 
1328   // Note that we cannot here invert the arguments of an isel in order to fold
1329   // a ZERO into what is presented as the second argument. All we have here
1330   // is the condition bit, and that might come from a CR-logical bit operation.
1331 
1332   const MCInstrDesc &UseMCID = UseMI.getDesc();
1333 
1334   // Only fold into real machine instructions.
1335   if (UseMCID.isPseudo())
1336     return false;
1337 
1338   unsigned UseIdx;
1339   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1340     if (UseMI.getOperand(UseIdx).isReg() &&
1341         UseMI.getOperand(UseIdx).getReg() == Reg)
1342       break;
1343 
1344   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1345   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1346 
1347   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1348 
1349   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1350   // register (which might also be specified as a pointer class kind).
1351   if (UseInfo->isLookupPtrRegClass()) {
1352     if (UseInfo->RegClass /* Kind */ != 1)
1353       return false;
1354   } else {
1355     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1356         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1357       return false;
1358   }
1359 
1360   // Make sure this is not tied to an output register (or otherwise
1361   // constrained). This is true for ST?UX registers, for example, which
1362   // are tied to their output registers.
1363   if (UseInfo->Constraints != 0)
1364     return false;
1365 
1366   unsigned ZeroReg;
1367   if (UseInfo->isLookupPtrRegClass()) {
1368     bool isPPC64 = Subtarget.isPPC64();
1369     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1370   } else {
1371     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1372               PPC::ZERO8 : PPC::ZERO;
1373   }
1374 
1375   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1376   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1377 
1378   if (DeleteDef)
1379     DefMI.eraseFromParent();
1380 
1381   return true;
1382 }
1383 
1384 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1385   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1386        I != IE; ++I)
1387     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1388       return true;
1389   return false;
1390 }
1391 
1392 // We should make sure that, if we're going to predicate both sides of a
1393 // condition (a diamond), that both sides don't define the counter register. We
1394 // can predicate counter-decrement-based branches, but while that predicates
1395 // the branching, it does not predicate the counter decrement. If we tried to
1396 // merge the triangle into one predicated block, we'd decrement the counter
1397 // twice.
1398 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1399                      unsigned NumT, unsigned ExtraT,
1400                      MachineBasicBlock &FMBB,
1401                      unsigned NumF, unsigned ExtraF,
1402                      BranchProbability Probability) const {
1403   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1404 }
1405 
1406 
1407 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1408   // The predicated branches are identified by their type, not really by the
1409   // explicit presence of a predicate. Furthermore, some of them can be
1410   // predicated more than once. Because if conversion won't try to predicate
1411   // any instruction which already claims to be predicated (by returning true
1412   // here), always return false. In doing so, we let isPredicable() be the
1413   // final word on whether not the instruction can be (further) predicated.
1414 
1415   return false;
1416 }
1417 
1418 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
1419   if (!MI.isTerminator())
1420     return false;
1421 
1422   // Conditional branch is a special case.
1423   if (MI.isBranch() && !MI.isBarrier())
1424     return true;
1425 
1426   return !isPredicated(MI);
1427 }
1428 
1429 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1430                                         ArrayRef<MachineOperand> Pred) const {
1431   unsigned OpC = MI.getOpcode();
1432   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1433     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1434       bool isPPC64 = Subtarget.isPPC64();
1435       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1436                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1437     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1438       MI.setDesc(get(PPC::BCLR));
1439       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1440     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1441       MI.setDesc(get(PPC::BCLRn));
1442       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1443     } else {
1444       MI.setDesc(get(PPC::BCCLR));
1445       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1446           .addImm(Pred[0].getImm())
1447           .add(Pred[1]);
1448     }
1449 
1450     return true;
1451   } else if (OpC == PPC::B) {
1452     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1453       bool isPPC64 = Subtarget.isPPC64();
1454       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1455                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1456     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1457       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1458       MI.RemoveOperand(0);
1459 
1460       MI.setDesc(get(PPC::BC));
1461       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1462           .add(Pred[1])
1463           .addMBB(MBB);
1464     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1465       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1466       MI.RemoveOperand(0);
1467 
1468       MI.setDesc(get(PPC::BCn));
1469       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1470           .add(Pred[1])
1471           .addMBB(MBB);
1472     } else {
1473       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1474       MI.RemoveOperand(0);
1475 
1476       MI.setDesc(get(PPC::BCC));
1477       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1478           .addImm(Pred[0].getImm())
1479           .add(Pred[1])
1480           .addMBB(MBB);
1481     }
1482 
1483     return true;
1484   } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
1485              OpC == PPC::BCTRL8) {
1486     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1487       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1488 
1489     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1490     bool isPPC64 = Subtarget.isPPC64();
1491 
1492     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1493       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1494                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1495       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1496       return true;
1497     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1498       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1499                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1500       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1501       return true;
1502     }
1503 
1504     MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1505                            : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1506     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1507         .addImm(Pred[0].getImm())
1508         .add(Pred[1]);
1509     return true;
1510   }
1511 
1512   return false;
1513 }
1514 
1515 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1516                                      ArrayRef<MachineOperand> Pred2) const {
1517   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1518   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1519 
1520   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1521     return false;
1522   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1523     return false;
1524 
1525   // P1 can only subsume P2 if they test the same condition register.
1526   if (Pred1[1].getReg() != Pred2[1].getReg())
1527     return false;
1528 
1529   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1530   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1531 
1532   if (P1 == P2)
1533     return true;
1534 
1535   // Does P1 subsume P2, e.g. GE subsumes GT.
1536   if (P1 == PPC::PRED_LE &&
1537       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1538     return true;
1539   if (P1 == PPC::PRED_GE &&
1540       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1541     return true;
1542 
1543   return false;
1544 }
1545 
1546 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1547                                     std::vector<MachineOperand> &Pred) const {
1548   // Note: At the present time, the contents of Pred from this function is
1549   // unused by IfConversion. This implementation follows ARM by pushing the
1550   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1551   // predicate, instructions defining CTR or CTR8 are also included as
1552   // predicate-defining instructions.
1553 
1554   const TargetRegisterClass *RCs[] =
1555     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1556       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1557 
1558   bool Found = false;
1559   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1560     const MachineOperand &MO = MI.getOperand(i);
1561     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1562       const TargetRegisterClass *RC = RCs[c];
1563       if (MO.isReg()) {
1564         if (MO.isDef() && RC->contains(MO.getReg())) {
1565           Pred.push_back(MO);
1566           Found = true;
1567         }
1568       } else if (MO.isRegMask()) {
1569         for (TargetRegisterClass::iterator I = RC->begin(),
1570              IE = RC->end(); I != IE; ++I)
1571           if (MO.clobbersPhysReg(*I)) {
1572             Pred.push_back(MO);
1573             Found = true;
1574           }
1575       }
1576     }
1577   }
1578 
1579   return Found;
1580 }
1581 
1582 bool PPCInstrInfo::isPredicable(const MachineInstr &MI) const {
1583   unsigned OpC = MI.getOpcode();
1584   switch (OpC) {
1585   default:
1586     return false;
1587   case PPC::B:
1588   case PPC::BLR:
1589   case PPC::BLR8:
1590   case PPC::BCTR:
1591   case PPC::BCTR8:
1592   case PPC::BCTRL:
1593   case PPC::BCTRL8:
1594     return true;
1595   }
1596 }
1597 
1598 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1599                                   unsigned &SrcReg2, int &Mask,
1600                                   int &Value) const {
1601   unsigned Opc = MI.getOpcode();
1602 
1603   switch (Opc) {
1604   default: return false;
1605   case PPC::CMPWI:
1606   case PPC::CMPLWI:
1607   case PPC::CMPDI:
1608   case PPC::CMPLDI:
1609     SrcReg = MI.getOperand(1).getReg();
1610     SrcReg2 = 0;
1611     Value = MI.getOperand(2).getImm();
1612     Mask = 0xFFFF;
1613     return true;
1614   case PPC::CMPW:
1615   case PPC::CMPLW:
1616   case PPC::CMPD:
1617   case PPC::CMPLD:
1618   case PPC::FCMPUS:
1619   case PPC::FCMPUD:
1620     SrcReg = MI.getOperand(1).getReg();
1621     SrcReg2 = MI.getOperand(2).getReg();
1622     Value = 0;
1623     Mask = 0;
1624     return true;
1625   }
1626 }
1627 
1628 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1629                                         unsigned SrcReg2, int Mask, int Value,
1630                                         const MachineRegisterInfo *MRI) const {
1631   if (DisableCmpOpt)
1632     return false;
1633 
1634   int OpC = CmpInstr.getOpcode();
1635   unsigned CRReg = CmpInstr.getOperand(0).getReg();
1636 
1637   // FP record forms set CR1 based on the exception status bits, not a
1638   // comparison with zero.
1639   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1640     return false;
1641 
1642   // The record forms set the condition register based on a signed comparison
1643   // with zero (so says the ISA manual). This is not as straightforward as it
1644   // seems, however, because this is always a 64-bit comparison on PPC64, even
1645   // for instructions that are 32-bit in nature (like slw for example).
1646   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1647   // for equality checks (as those don't depend on the sign). On PPC64,
1648   // we are restricted to equality for unsigned 64-bit comparisons and for
1649   // signed 32-bit comparisons the applicability is more restricted.
1650   bool isPPC64 = Subtarget.isPPC64();
1651   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1652   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1653   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1654 
1655   // Get the unique definition of SrcReg.
1656   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1657   if (!MI) return false;
1658 
1659   bool equalityOnly = false;
1660   bool noSub = false;
1661   if (isPPC64) {
1662     if (is32BitSignedCompare) {
1663       // We can perform this optimization only if MI is sign-extending.
1664       if (isSignExtended(*MI))
1665         noSub = true;
1666       else
1667         return false;
1668     } else if (is32BitUnsignedCompare) {
1669       // We can perform this optimization, equality only, if MI is
1670       // zero-extending.
1671       if (isZeroExtended(*MI)) {
1672         noSub = true;
1673         equalityOnly = true;
1674       } else
1675         return false;
1676     } else
1677       equalityOnly = is64BitUnsignedCompare;
1678   } else
1679     equalityOnly = is32BitUnsignedCompare;
1680 
1681   if (equalityOnly) {
1682     // We need to check the uses of the condition register in order to reject
1683     // non-equality comparisons.
1684     for (MachineRegisterInfo::use_instr_iterator
1685          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1686          I != IE; ++I) {
1687       MachineInstr *UseMI = &*I;
1688       if (UseMI->getOpcode() == PPC::BCC) {
1689         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1690         unsigned PredCond = PPC::getPredicateCondition(Pred);
1691         // We ignore hint bits when checking for non-equality comparisons.
1692         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1693           return false;
1694       } else if (UseMI->getOpcode() == PPC::ISEL ||
1695                  UseMI->getOpcode() == PPC::ISEL8) {
1696         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1697         if (SubIdx != PPC::sub_eq)
1698           return false;
1699       } else
1700         return false;
1701     }
1702   }
1703 
1704   MachineBasicBlock::iterator I = CmpInstr;
1705 
1706   // Scan forward to find the first use of the compare.
1707   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1708        ++I) {
1709     bool FoundUse = false;
1710     for (MachineRegisterInfo::use_instr_iterator
1711          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1712          J != JE; ++J)
1713       if (&*J == &*I) {
1714         FoundUse = true;
1715         break;
1716       }
1717 
1718     if (FoundUse)
1719       break;
1720   }
1721 
1722   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1723   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1724 
1725   // There are two possible candidates which can be changed to set CR[01].
1726   // One is MI, the other is a SUB instruction.
1727   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1728   MachineInstr *Sub = nullptr;
1729   if (SrcReg2 != 0)
1730     // MI is not a candidate for CMPrr.
1731     MI = nullptr;
1732   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1733   // same BB as the comparison. This is to allow the check below to avoid calls
1734   // (and other explicit clobbers); instead we should really check for these
1735   // more explicitly (in at least a few predecessors).
1736   else if (MI->getParent() != CmpInstr.getParent())
1737     return false;
1738   else if (Value != 0) {
1739     // The record-form instructions set CR bit based on signed comparison
1740     // against 0. We try to convert a compare against 1 or -1 into a compare
1741     // against 0 to exploit record-form instructions. For example, we change
1742     // the condition "greater than -1" into "greater than or equal to 0"
1743     // and "less than 1" into "less than or equal to 0".
1744 
1745     // Since we optimize comparison based on a specific branch condition,
1746     // we don't optimize if condition code is used by more than once.
1747     if (equalityOnly || !MRI->hasOneUse(CRReg))
1748       return false;
1749 
1750     MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1751     if (UseMI->getOpcode() != PPC::BCC)
1752       return false;
1753 
1754     PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1755     PPC::Predicate NewPred = Pred;
1756     unsigned PredCond = PPC::getPredicateCondition(Pred);
1757     unsigned PredHint = PPC::getPredicateHint(Pred);
1758     int16_t Immed = (int16_t)Value;
1759 
1760     // When modifying the condition in the predicate, we propagate hint bits
1761     // from the original predicate to the new one.
1762     if (Immed == -1 && PredCond == PPC::PRED_GT)
1763       // We convert "greater than -1" into "greater than or equal to 0",
1764       // since we are assuming signed comparison by !equalityOnly
1765       NewPred = PPC::getPredicate(PPC::PRED_GE, PredHint);
1766     else if (Immed == -1 && PredCond == PPC::PRED_LE)
1767       // We convert "less than or equal to -1" into "less than 0".
1768       NewPred = PPC::getPredicate(PPC::PRED_LT, PredHint);
1769     else if (Immed == 1 && PredCond == PPC::PRED_LT)
1770       // We convert "less than 1" into "less than or equal to 0".
1771       NewPred = PPC::getPredicate(PPC::PRED_LE, PredHint);
1772     else if (Immed == 1 && PredCond == PPC::PRED_GE)
1773       // We convert "greater than or equal to 1" into "greater than 0".
1774       NewPred = PPC::getPredicate(PPC::PRED_GT, PredHint);
1775     else
1776       return false;
1777 
1778     PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1779                                             NewPred));
1780   }
1781 
1782   // Search for Sub.
1783   const TargetRegisterInfo *TRI = &getRegisterInfo();
1784   --I;
1785 
1786   // Get ready to iterate backward from CmpInstr.
1787   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1788 
1789   for (; I != E && !noSub; --I) {
1790     const MachineInstr &Instr = *I;
1791     unsigned IOpC = Instr.getOpcode();
1792 
1793     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1794                              Instr.readsRegister(PPC::CR0, TRI)))
1795       // This instruction modifies or uses the record condition register after
1796       // the one we want to change. While we could do this transformation, it
1797       // would likely not be profitable. This transformation removes one
1798       // instruction, and so even forcing RA to generate one move probably
1799       // makes it unprofitable.
1800       return false;
1801 
1802     // Check whether CmpInstr can be made redundant by the current instruction.
1803     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1804          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1805         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1806         ((Instr.getOperand(1).getReg() == SrcReg &&
1807           Instr.getOperand(2).getReg() == SrcReg2) ||
1808         (Instr.getOperand(1).getReg() == SrcReg2 &&
1809          Instr.getOperand(2).getReg() == SrcReg))) {
1810       Sub = &*I;
1811       break;
1812     }
1813 
1814     if (I == B)
1815       // The 'and' is below the comparison instruction.
1816       return false;
1817   }
1818 
1819   // Return false if no candidates exist.
1820   if (!MI && !Sub)
1821     return false;
1822 
1823   // The single candidate is called MI.
1824   if (!MI) MI = Sub;
1825 
1826   int NewOpC = -1;
1827   int MIOpC = MI->getOpcode();
1828   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8 ||
1829       MIOpC == PPC::ANDISo || MIOpC == PPC::ANDISo8)
1830     NewOpC = MIOpC;
1831   else {
1832     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1833     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1834       NewOpC = MIOpC;
1835   }
1836 
1837   // FIXME: On the non-embedded POWER architectures, only some of the record
1838   // forms are fast, and we should use only the fast ones.
1839 
1840   // The defining instruction has a record form (or is already a record
1841   // form). It is possible, however, that we'll need to reverse the condition
1842   // code of the users.
1843   if (NewOpC == -1)
1844     return false;
1845 
1846   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1847   // needs to be updated to be based on SUB.  Push the condition code
1848   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1849   // condition code of these operands will be modified.
1850   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1851   // comparison against 0, which may modify predicate.
1852   bool ShouldSwap = false;
1853   if (Sub && Value == 0) {
1854     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1855       Sub->getOperand(2).getReg() == SrcReg;
1856 
1857     // The operands to subf are the opposite of sub, so only in the fixed-point
1858     // case, invert the order.
1859     ShouldSwap = !ShouldSwap;
1860   }
1861 
1862   if (ShouldSwap)
1863     for (MachineRegisterInfo::use_instr_iterator
1864          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1865          I != IE; ++I) {
1866       MachineInstr *UseMI = &*I;
1867       if (UseMI->getOpcode() == PPC::BCC) {
1868         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1869         unsigned PredCond = PPC::getPredicateCondition(Pred);
1870         assert((!equalityOnly ||
1871                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1872                "Invalid predicate for equality-only optimization");
1873         (void)PredCond; // To suppress warning in release build.
1874         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1875                                 PPC::getSwappedPredicate(Pred)));
1876       } else if (UseMI->getOpcode() == PPC::ISEL ||
1877                  UseMI->getOpcode() == PPC::ISEL8) {
1878         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1879         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1880                "Invalid CR bit for equality-only optimization");
1881 
1882         if (NewSubReg == PPC::sub_lt)
1883           NewSubReg = PPC::sub_gt;
1884         else if (NewSubReg == PPC::sub_gt)
1885           NewSubReg = PPC::sub_lt;
1886 
1887         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1888                                                  NewSubReg));
1889       } else // We need to abort on a user we don't understand.
1890         return false;
1891     }
1892   assert(!(Value != 0 && ShouldSwap) &&
1893          "Non-zero immediate support and ShouldSwap"
1894          "may conflict in updating predicate");
1895 
1896   // Create a new virtual register to hold the value of the CR set by the
1897   // record-form instruction. If the instruction was not previously in
1898   // record form, then set the kill flag on the CR.
1899   CmpInstr.eraseFromParent();
1900 
1901   MachineBasicBlock::iterator MII = MI;
1902   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1903           get(TargetOpcode::COPY), CRReg)
1904     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1905 
1906   // Even if CR0 register were dead before, it is alive now since the
1907   // instruction we just built uses it.
1908   MI->clearRegisterDeads(PPC::CR0);
1909 
1910   if (MIOpC != NewOpC) {
1911     // We need to be careful here: we're replacing one instruction with
1912     // another, and we need to make sure that we get all of the right
1913     // implicit uses and defs. On the other hand, the caller may be holding
1914     // an iterator to this instruction, and so we can't delete it (this is
1915     // specifically the case if this is the instruction directly after the
1916     // compare).
1917 
1918     // Rotates are expensive instructions. If we're emitting a record-form
1919     // rotate that can just be an andi/andis, we should just emit that.
1920     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
1921       unsigned GPRRes = MI->getOperand(0).getReg();
1922       int64_t SH = MI->getOperand(2).getImm();
1923       int64_t MB = MI->getOperand(3).getImm();
1924       int64_t ME = MI->getOperand(4).getImm();
1925       // We can only do this if both the start and end of the mask are in the
1926       // same halfword.
1927       bool MBInLoHWord = MB >= 16;
1928       bool MEInLoHWord = ME >= 16;
1929       uint64_t Mask = ~0LLU;
1930 
1931       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
1932         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
1933         // The mask value needs to shift right 16 if we're emitting andis.
1934         Mask >>= MBInLoHWord ? 0 : 16;
1935         NewOpC = MIOpC == PPC::RLWINM ?
1936           (MBInLoHWord ? PPC::ANDIo : PPC::ANDISo) :
1937           (MBInLoHWord ? PPC::ANDIo8 :PPC::ANDISo8);
1938       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
1939                  (ME - MB + 1 == SH) && (MB >= 16)) {
1940         // If we are rotating by the exact number of bits as are in the mask
1941         // and the mask is in the least significant bits of the register,
1942         // that's just an andis. (as long as the GPR result has no uses).
1943         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
1944         Mask >>= 16;
1945         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDISo :PPC::ANDISo8;
1946       }
1947       // If we've set the mask, we can transform.
1948       if (Mask != ~0LLU) {
1949         MI->RemoveOperand(4);
1950         MI->RemoveOperand(3);
1951         MI->getOperand(2).setImm(Mask);
1952         NumRcRotatesConvertedToRcAnd++;
1953       }
1954     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
1955       int64_t MB = MI->getOperand(3).getImm();
1956       if (MB >= 48) {
1957         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
1958         NewOpC = PPC::ANDIo8;
1959         MI->RemoveOperand(3);
1960         MI->getOperand(2).setImm(Mask);
1961         NumRcRotatesConvertedToRcAnd++;
1962       }
1963     }
1964 
1965     const MCInstrDesc &NewDesc = get(NewOpC);
1966     MI->setDesc(NewDesc);
1967 
1968     if (NewDesc.ImplicitDefs)
1969       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
1970            *ImpDefs; ++ImpDefs)
1971         if (!MI->definesRegister(*ImpDefs))
1972           MI->addOperand(*MI->getParent()->getParent(),
1973                          MachineOperand::CreateReg(*ImpDefs, true, true));
1974     if (NewDesc.ImplicitUses)
1975       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
1976            *ImpUses; ++ImpUses)
1977         if (!MI->readsRegister(*ImpUses))
1978           MI->addOperand(*MI->getParent()->getParent(),
1979                          MachineOperand::CreateReg(*ImpUses, false, true));
1980   }
1981   assert(MI->definesRegister(PPC::CR0) &&
1982          "Record-form instruction does not define cr0?");
1983 
1984   // Modify the condition code of operands in OperandsToUpdate.
1985   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1986   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1987   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1988     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1989 
1990   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1991     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1992 
1993   return true;
1994 }
1995 
1996 /// GetInstSize - Return the number of bytes of code the specified
1997 /// instruction may be.  This returns the maximum number of bytes.
1998 ///
1999 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2000   unsigned Opcode = MI.getOpcode();
2001 
2002   if (Opcode == PPC::INLINEASM) {
2003     const MachineFunction *MF = MI.getParent()->getParent();
2004     const char *AsmStr = MI.getOperand(0).getSymbolName();
2005     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2006   } else if (Opcode == TargetOpcode::STACKMAP) {
2007     StackMapOpers Opers(&MI);
2008     return Opers.getNumPatchBytes();
2009   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2010     PatchPointOpers Opers(&MI);
2011     return Opers.getNumPatchBytes();
2012   } else {
2013     return get(Opcode).getSize();
2014   }
2015 }
2016 
2017 std::pair<unsigned, unsigned>
2018 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2019   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2020   return std::make_pair(TF & Mask, TF & ~Mask);
2021 }
2022 
2023 ArrayRef<std::pair<unsigned, const char *>>
2024 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2025   using namespace PPCII;
2026   static const std::pair<unsigned, const char *> TargetFlags[] = {
2027       {MO_LO, "ppc-lo"},
2028       {MO_HA, "ppc-ha"},
2029       {MO_TPREL_LO, "ppc-tprel-lo"},
2030       {MO_TPREL_HA, "ppc-tprel-ha"},
2031       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2032       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2033       {MO_TOC_LO, "ppc-toc-lo"},
2034       {MO_TLS, "ppc-tls"}};
2035   return makeArrayRef(TargetFlags);
2036 }
2037 
2038 ArrayRef<std::pair<unsigned, const char *>>
2039 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2040   using namespace PPCII;
2041   static const std::pair<unsigned, const char *> TargetFlags[] = {
2042       {MO_PLT, "ppc-plt"},
2043       {MO_PIC_FLAG, "ppc-pic"},
2044       {MO_NLP_FLAG, "ppc-nlp"},
2045       {MO_NLP_HIDDEN_FLAG, "ppc-nlp-hidden"}};
2046   return makeArrayRef(TargetFlags);
2047 }
2048 
2049 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2050 // The VSX versions have the advantage of a full 64-register target whereas
2051 // the FP ones have the advantage of lower latency and higher throughput. So
2052 // what we are after is using the faster instructions in low register pressure
2053 // situations and using the larger register file in high register pressure
2054 // situations.
2055 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2056     unsigned UpperOpcode, LowerOpcode;
2057     switch (MI.getOpcode()) {
2058     case PPC::DFLOADf32:
2059       UpperOpcode = PPC::LXSSP;
2060       LowerOpcode = PPC::LFS;
2061       break;
2062     case PPC::DFLOADf64:
2063       UpperOpcode = PPC::LXSD;
2064       LowerOpcode = PPC::LFD;
2065       break;
2066     case PPC::DFSTOREf32:
2067       UpperOpcode = PPC::STXSSP;
2068       LowerOpcode = PPC::STFS;
2069       break;
2070     case PPC::DFSTOREf64:
2071       UpperOpcode = PPC::STXSD;
2072       LowerOpcode = PPC::STFD;
2073       break;
2074     case PPC::XFLOADf32:
2075       UpperOpcode = PPC::LXSSPX;
2076       LowerOpcode = PPC::LFSX;
2077       break;
2078     case PPC::XFLOADf64:
2079       UpperOpcode = PPC::LXSDX;
2080       LowerOpcode = PPC::LFDX;
2081       break;
2082     case PPC::XFSTOREf32:
2083       UpperOpcode = PPC::STXSSPX;
2084       LowerOpcode = PPC::STFSX;
2085       break;
2086     case PPC::XFSTOREf64:
2087       UpperOpcode = PPC::STXSDX;
2088       LowerOpcode = PPC::STFDX;
2089       break;
2090     case PPC::LIWAX:
2091       UpperOpcode = PPC::LXSIWAX;
2092       LowerOpcode = PPC::LFIWAX;
2093       break;
2094     case PPC::LIWZX:
2095       UpperOpcode = PPC::LXSIWZX;
2096       LowerOpcode = PPC::LFIWZX;
2097       break;
2098     case PPC::STIWX:
2099       UpperOpcode = PPC::STXSIWX;
2100       LowerOpcode = PPC::STFIWX;
2101       break;
2102     default:
2103       llvm_unreachable("Unknown Operation!");
2104     }
2105 
2106     unsigned TargetReg = MI.getOperand(0).getReg();
2107     unsigned Opcode;
2108     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2109         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2110       Opcode = LowerOpcode;
2111     else
2112       Opcode = UpperOpcode;
2113     MI.setDesc(get(Opcode));
2114     return true;
2115 }
2116 
2117 static bool isAnImmediateOperand(const MachineOperand &MO) {
2118   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2119 }
2120 
2121 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2122   auto &MBB = *MI.getParent();
2123   auto DL = MI.getDebugLoc();
2124 
2125   switch (MI.getOpcode()) {
2126   case TargetOpcode::LOAD_STACK_GUARD: {
2127     assert(Subtarget.isTargetLinux() &&
2128            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2129     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2130     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2131     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2132     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2133         .addImm(Offset)
2134         .addReg(Reg);
2135     return true;
2136   }
2137   case PPC::DFLOADf32:
2138   case PPC::DFLOADf64:
2139   case PPC::DFSTOREf32:
2140   case PPC::DFSTOREf64: {
2141     assert(Subtarget.hasP9Vector() &&
2142            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2143     assert(MI.getOperand(2).isReg() &&
2144            isAnImmediateOperand(MI.getOperand(1)) &&
2145            "D-form op must have register and immediate operands");
2146     return expandVSXMemPseudo(MI);
2147   }
2148   case PPC::XFLOADf32:
2149   case PPC::XFSTOREf32:
2150   case PPC::LIWAX:
2151   case PPC::LIWZX:
2152   case PPC::STIWX: {
2153     assert(Subtarget.hasP8Vector() &&
2154            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2155     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2156            "X-form op must have register and register operands");
2157     return expandVSXMemPseudo(MI);
2158   }
2159   case PPC::XFLOADf64:
2160   case PPC::XFSTOREf64: {
2161     assert(Subtarget.hasVSX() &&
2162            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2163     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2164            "X-form op must have register and register operands");
2165     return expandVSXMemPseudo(MI);
2166   }
2167   case PPC::SPILLTOVSR_LD: {
2168     unsigned TargetReg = MI.getOperand(0).getReg();
2169     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2170       MI.setDesc(get(PPC::DFLOADf64));
2171       return expandPostRAPseudo(MI);
2172     }
2173     else
2174       MI.setDesc(get(PPC::LD));
2175     return true;
2176   }
2177   case PPC::SPILLTOVSR_ST: {
2178     unsigned SrcReg = MI.getOperand(0).getReg();
2179     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2180       NumStoreSPILLVSRRCAsVec++;
2181       MI.setDesc(get(PPC::DFSTOREf64));
2182       return expandPostRAPseudo(MI);
2183     } else {
2184       NumStoreSPILLVSRRCAsGpr++;
2185       MI.setDesc(get(PPC::STD));
2186     }
2187     return true;
2188   }
2189   case PPC::SPILLTOVSR_LDX: {
2190     unsigned TargetReg = MI.getOperand(0).getReg();
2191     if (PPC::VSFRCRegClass.contains(TargetReg))
2192       MI.setDesc(get(PPC::LXSDX));
2193     else
2194       MI.setDesc(get(PPC::LDX));
2195     return true;
2196   }
2197   case PPC::SPILLTOVSR_STX: {
2198     unsigned SrcReg = MI.getOperand(0).getReg();
2199     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2200       NumStoreSPILLVSRRCAsVec++;
2201       MI.setDesc(get(PPC::STXSDX));
2202     } else {
2203       NumStoreSPILLVSRRCAsGpr++;
2204       MI.setDesc(get(PPC::STDX));
2205     }
2206     return true;
2207   }
2208 
2209   case PPC::CFENCE8: {
2210     auto Val = MI.getOperand(0).getReg();
2211     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2212     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2213         .addImm(PPC::PRED_NE_MINUS)
2214         .addReg(PPC::CR7)
2215         .addImm(1);
2216     MI.setDesc(get(PPC::ISYNC));
2217     MI.RemoveOperand(0);
2218     return true;
2219   }
2220   }
2221   return false;
2222 }
2223 
2224 // Essentially a compile-time implementation of a compare->isel sequence.
2225 // It takes two constants to compare, along with the true/false registers
2226 // and the comparison type (as a subreg to a CR field) and returns one
2227 // of the true/false registers, depending on the comparison results.
2228 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2229                           unsigned TrueReg, unsigned FalseReg,
2230                           unsigned CRSubReg) {
2231   // Signed comparisons. The immediates are assumed to be sign-extended.
2232   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2233     switch (CRSubReg) {
2234     default: llvm_unreachable("Unknown integer comparison type.");
2235     case PPC::sub_lt:
2236       return Imm1 < Imm2 ? TrueReg : FalseReg;
2237     case PPC::sub_gt:
2238       return Imm1 > Imm2 ? TrueReg : FalseReg;
2239     case PPC::sub_eq:
2240       return Imm1 == Imm2 ? TrueReg : FalseReg;
2241     }
2242   }
2243   // Unsigned comparisons.
2244   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2245     switch (CRSubReg) {
2246     default: llvm_unreachable("Unknown integer comparison type.");
2247     case PPC::sub_lt:
2248       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2249     case PPC::sub_gt:
2250       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2251     case PPC::sub_eq:
2252       return Imm1 == Imm2 ? TrueReg : FalseReg;
2253     }
2254   }
2255   return PPC::NoRegister;
2256 }
2257 
2258 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2259                                               unsigned OpNo,
2260                                               int64_t Imm) const {
2261   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2262   // Replace the REG with the Immediate.
2263   unsigned InUseReg = MI.getOperand(OpNo).getReg();
2264   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2265 
2266   if (empty(MI.implicit_operands()))
2267     return;
2268 
2269   // We need to make sure that the MI didn't have any implicit use
2270   // of this REG any more.
2271   const TargetRegisterInfo *TRI = &getRegisterInfo();
2272   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2273   if (UseOpIdx >= 0) {
2274     MachineOperand &MO = MI.getOperand(UseOpIdx);
2275     if (MO.isImplicit())
2276       // The operands must always be in the following order:
2277       // - explicit reg defs,
2278       // - other explicit operands (reg uses, immediates, etc.),
2279       // - implicit reg defs
2280       // - implicit reg uses
2281       // Therefore, removing the implicit operand won't change the explicit
2282       // operands layout.
2283       MI.RemoveOperand(UseOpIdx);
2284   }
2285 }
2286 
2287 // Replace an instruction with one that materializes a constant (and sets
2288 // CR0 if the original instruction was a record-form instruction).
2289 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2290                                       const LoadImmediateInfo &LII) const {
2291   // Remove existing operands.
2292   int OperandToKeep = LII.SetCR ? 1 : 0;
2293   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2294     MI.RemoveOperand(i);
2295 
2296   // Replace the instruction.
2297   if (LII.SetCR) {
2298     MI.setDesc(get(LII.Is64Bit ? PPC::ANDIo8 : PPC::ANDIo));
2299     // Set the immediate.
2300     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2301         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2302     return;
2303   }
2304   else
2305     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2306 
2307   // Set the immediate.
2308   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2309       .addImm(LII.Imm);
2310 }
2311 
2312 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2313   MachineInstr &MI,
2314   unsigned &OpNoForForwarding,
2315   bool &SeenIntermediateUse) const {
2316   OpNoForForwarding = ~0U;
2317   MachineInstr *DefMI = nullptr;
2318   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2319   const TargetRegisterInfo *TRI = &getRegisterInfo();
2320   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2321   // within the basic block to see if the register is defined using an LI/LI8.
2322   if (MRI->isSSA()) {
2323     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2324       if (!MI.getOperand(i).isReg())
2325         continue;
2326       unsigned Reg = MI.getOperand(i).getReg();
2327       if (!TargetRegisterInfo::isVirtualRegister(Reg))
2328         continue;
2329       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2330       if (TargetRegisterInfo::isVirtualRegister(TrueReg)) {
2331         DefMI = MRI->getVRegDef(TrueReg);
2332         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) {
2333           OpNoForForwarding = i;
2334           break;
2335         }
2336       }
2337     }
2338   } else {
2339     // Looking back through the definition for each operand could be expensive,
2340     // so exit early if this isn't an instruction that either has an immediate
2341     // form or is already an immediate form that we can handle.
2342     ImmInstrInfo III;
2343     unsigned Opc = MI.getOpcode();
2344     bool ConvertibleImmForm =
2345       Opc == PPC::CMPWI || Opc == PPC::CMPLWI ||
2346       Opc == PPC::CMPDI || Opc == PPC::CMPLDI ||
2347       Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2348       Opc == PPC::ORI || Opc == PPC::ORI8 ||
2349       Opc == PPC::XORI || Opc == PPC::XORI8 ||
2350       Opc == PPC::RLDICL || Opc == PPC::RLDICLo ||
2351       Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2352       Opc == PPC::RLWINM || Opc == PPC::RLWINMo ||
2353       Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8o;
2354     if (!instrHasImmForm(MI, III, true) && !ConvertibleImmForm)
2355       return nullptr;
2356 
2357     // Don't convert or %X, %Y, %Y since that's just a register move.
2358     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2359         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2360       return nullptr;
2361     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2362       MachineOperand &MO = MI.getOperand(i);
2363       SeenIntermediateUse = false;
2364       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2365         MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2366         It++;
2367         unsigned Reg = MI.getOperand(i).getReg();
2368 
2369         // Is this register defined by some form of add-immediate (including
2370         // load-immediate) within this basic block?
2371         for ( ; It != E; ++It) {
2372           if (It->modifiesRegister(Reg, &getRegisterInfo())) {
2373             switch (It->getOpcode()) {
2374             default: break;
2375             case PPC::LI:
2376             case PPC::LI8:
2377             case PPC::ADDItocL:
2378             case PPC::ADDI:
2379             case PPC::ADDI8:
2380               OpNoForForwarding = i;
2381               return &*It;
2382             }
2383             break;
2384           } else if (It->readsRegister(Reg, &getRegisterInfo()))
2385             // If we see another use of this reg between the def and the MI,
2386             // we want to flat it so the def isn't deleted.
2387             SeenIntermediateUse = true;
2388         }
2389       }
2390     }
2391   }
2392   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2393 }
2394 
2395 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2396   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2397       // Power 8
2398       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2399        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,
2400        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2401        PPC::SPILLTOVSR_ST, PPC::EVSTDD, PPC::SPESTW},
2402       // Power 9
2403       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2404        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,
2405        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2406        PPC::SPILLTOVSR_ST}};
2407 
2408   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2409 }
2410 
2411 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2412   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2413       // Power 8
2414       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2415        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,
2416        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2417        PPC::SPILLTOVSR_LD, PPC::EVLDD, PPC::SPELWZ},
2418       // Power 9
2419       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2420        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32,
2421        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2422        PPC::SPILLTOVSR_LD}};
2423 
2424   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2425 }
2426 
2427 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI,
2428                                      unsigned RegNo) const {
2429   const MachineRegisterInfo &MRI =
2430       StartMI.getParent()->getParent()->getRegInfo();
2431   if (MRI.isSSA())
2432     return;
2433 
2434   // Instructions between [StartMI, EndMI] should be in same basic block.
2435   assert((StartMI.getParent() == EndMI.getParent()) &&
2436          "Instructions are not in same basic block");
2437 
2438   bool IsKillSet = false;
2439 
2440   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2441     MachineOperand &MO = MI.getOperand(Index);
2442     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2443         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2444       MO.setIsKill(false);
2445   };
2446 
2447   // Set killed flag for EndMI.
2448   // No need to do anything if EndMI defines RegNo.
2449   int UseIndex =
2450       EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2451   if (UseIndex != -1) {
2452     EndMI.getOperand(UseIndex).setIsKill(true);
2453     IsKillSet = true;
2454     // Clear killed flag for other EndMI operands related to RegNo. In some
2455     // upexpected cases, killed may be set multiple times for same register
2456     // operand in same MI.
2457     for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i)
2458       if (i != UseIndex)
2459         clearOperandKillInfo(EndMI, i);
2460   }
2461 
2462   // Walking the inst in reverse order (EndMI -> StartMI].
2463   MachineBasicBlock::reverse_iterator It = EndMI;
2464   MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend();
2465   // EndMI has been handled above, skip it here.
2466   It++;
2467   MachineOperand *MO = nullptr;
2468   for (; It != E; ++It) {
2469     // Skip insturctions which could not be a def/use of RegNo.
2470     if (It->isDebugInstr() || It->isPosition())
2471       continue;
2472 
2473     // Clear killed flag for all It operands related to RegNo. In some
2474     // upexpected cases, killed may be set multiple times for same register
2475     // operand in same MI.
2476     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2477         clearOperandKillInfo(*It, i);
2478 
2479     // If killed is not set, set killed for its last use or set dead for its def
2480     // if no use found.
2481     if (!IsKillSet) {
2482       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2483         // Use found, set it killed.
2484         IsKillSet = true;
2485         MO->setIsKill(true);
2486         continue;
2487       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2488                                                   &getRegisterInfo()))) {
2489         // No use found, set dead for its def.
2490         assert(&*It == &StartMI && "No new def between StartMI and EndMI.");
2491         MO->setIsDead(true);
2492         break;
2493       }
2494     }
2495 
2496     if ((&*It) == &StartMI)
2497       break;
2498   }
2499   // Ensure RegMo liveness is killed after EndMI.
2500   assert((IsKillSet || (MO && MO->isDead())) &&
2501          "RegNo should be killed or dead");
2502 }
2503 
2504 // If this instruction has an immediate form and one of its operands is a
2505 // result of a load-immediate or an add-immediate, convert it to
2506 // the immediate form if the constant is in range.
2507 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
2508                                           MachineInstr **KilledDef) const {
2509   MachineFunction *MF = MI.getParent()->getParent();
2510   MachineRegisterInfo *MRI = &MF->getRegInfo();
2511   bool PostRA = !MRI->isSSA();
2512   bool SeenIntermediateUse = true;
2513   unsigned ForwardingOperand = ~0U;
2514   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
2515                                            SeenIntermediateUse);
2516   if (!DefMI)
2517     return false;
2518   assert(ForwardingOperand < MI.getNumOperands() &&
2519          "The forwarding operand needs to be valid at this point");
2520   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
2521   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
2522   unsigned ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg();
2523   if (KilledDef && KillFwdDefMI)
2524     *KilledDef = DefMI;
2525 
2526   ImmInstrInfo III;
2527   bool HasImmForm = instrHasImmForm(MI, III, PostRA);
2528   // If this is a reg+reg instruction that has a reg+imm form,
2529   // and one of the operands is produced by an add-immediate,
2530   // try to convert it.
2531   if (HasImmForm &&
2532       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
2533                                  KillFwdDefMI))
2534     return true;
2535 
2536   if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) ||
2537       !DefMI->getOperand(1).isImm())
2538     return false;
2539 
2540   int64_t Immediate = DefMI->getOperand(1).getImm();
2541   // Sign-extend to 64-bits.
2542   int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
2543     (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
2544 
2545   // If this is a reg+reg instruction that has a reg+imm form,
2546   // and one of the operands is produced by LI, convert it now.
2547   if (HasImmForm)
2548     return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm);
2549 
2550   bool ReplaceWithLI = false;
2551   bool Is64BitLI = false;
2552   int64_t NewImm = 0;
2553   bool SetCR = false;
2554   unsigned Opc = MI.getOpcode();
2555   switch (Opc) {
2556   default: return false;
2557 
2558   // FIXME: Any branches conditional on such a comparison can be made
2559   // unconditional. At this time, this happens too infrequently to be worth
2560   // the implementation effort, but if that ever changes, we could convert
2561   // such a pattern here.
2562   case PPC::CMPWI:
2563   case PPC::CMPLWI:
2564   case PPC::CMPDI:
2565   case PPC::CMPLDI: {
2566     // Doing this post-RA would require dataflow analysis to reliably find uses
2567     // of the CR register set by the compare.
2568     // No need to fixup killed/dead flag since this transformation is only valid
2569     // before RA.
2570     if (PostRA)
2571       return false;
2572     // If a compare-immediate is fed by an immediate and is itself an input of
2573     // an ISEL (the most common case) into a COPY of the correct register.
2574     bool Changed = false;
2575     unsigned DefReg = MI.getOperand(0).getReg();
2576     int64_t Comparand = MI.getOperand(2).getImm();
2577     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ?
2578       (Comparand | 0xFFFFFFFFFFFF0000) : Comparand;
2579 
2580     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
2581       unsigned UseOpc = CompareUseMI.getOpcode();
2582       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
2583         continue;
2584       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
2585       unsigned TrueReg = CompareUseMI.getOperand(1).getReg();
2586       unsigned FalseReg = CompareUseMI.getOperand(2).getReg();
2587       unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg,
2588                                      FalseReg, CRSubReg);
2589       if (RegToCopy == PPC::NoRegister)
2590         continue;
2591       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
2592       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
2593         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
2594         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
2595         CompareUseMI.RemoveOperand(3);
2596         CompareUseMI.RemoveOperand(2);
2597         continue;
2598       }
2599       LLVM_DEBUG(
2600           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
2601       LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump());
2602       LLVM_DEBUG(dbgs() << "Is converted to:\n");
2603       // Convert to copy and remove unneeded operands.
2604       CompareUseMI.setDesc(get(PPC::COPY));
2605       CompareUseMI.RemoveOperand(3);
2606       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
2607       CmpIselsConverted++;
2608       Changed = true;
2609       LLVM_DEBUG(CompareUseMI.dump());
2610     }
2611     if (Changed)
2612       return true;
2613     // This may end up incremented multiple times since this function is called
2614     // during a fixed-point transformation, but it is only meant to indicate the
2615     // presence of this opportunity.
2616     MissedConvertibleImmediateInstrs++;
2617     return false;
2618   }
2619 
2620   // Immediate forms - may simply be convertable to an LI.
2621   case PPC::ADDI:
2622   case PPC::ADDI8: {
2623     // Does the sum fit in a 16-bit signed field?
2624     int64_t Addend = MI.getOperand(2).getImm();
2625     if (isInt<16>(Addend + SExtImm)) {
2626       ReplaceWithLI = true;
2627       Is64BitLI = Opc == PPC::ADDI8;
2628       NewImm = Addend + SExtImm;
2629       break;
2630     }
2631     return false;
2632   }
2633   case PPC::RLDICL:
2634   case PPC::RLDICLo:
2635   case PPC::RLDICL_32:
2636   case PPC::RLDICL_32_64: {
2637     // Use APInt's rotate function.
2638     int64_t SH = MI.getOperand(2).getImm();
2639     int64_t MB = MI.getOperand(3).getImm();
2640     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICLo) ?
2641                 64 : 32, SExtImm, true);
2642     InVal = InVal.rotl(SH);
2643     uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2644     InVal &= Mask;
2645     // Can't replace negative values with an LI as that will sign-extend
2646     // and not clear the left bits. If we're setting the CR bit, we will use
2647     // ANDIo which won't sign extend, so that's safe.
2648     if (isUInt<15>(InVal.getSExtValue()) ||
2649         (Opc == PPC::RLDICLo && isUInt<16>(InVal.getSExtValue()))) {
2650       ReplaceWithLI = true;
2651       Is64BitLI = Opc != PPC::RLDICL_32;
2652       NewImm = InVal.getSExtValue();
2653       SetCR = Opc == PPC::RLDICLo;
2654       break;
2655     }
2656     return false;
2657   }
2658   case PPC::RLWINM:
2659   case PPC::RLWINM8:
2660   case PPC::RLWINMo:
2661   case PPC::RLWINM8o: {
2662     int64_t SH = MI.getOperand(2).getImm();
2663     int64_t MB = MI.getOperand(3).getImm();
2664     int64_t ME = MI.getOperand(4).getImm();
2665     APInt InVal(32, SExtImm, true);
2666     InVal = InVal.rotl(SH);
2667     // Set the bits (        MB + 32        ) to (        ME + 32        ).
2668     uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2669     InVal &= Mask;
2670     // Can't replace negative values with an LI as that will sign-extend
2671     // and not clear the left bits. If we're setting the CR bit, we will use
2672     // ANDIo which won't sign extend, so that's safe.
2673     bool ValueFits = isUInt<15>(InVal.getSExtValue());
2674     ValueFits |= ((Opc == PPC::RLWINMo || Opc == PPC::RLWINM8o) &&
2675                   isUInt<16>(InVal.getSExtValue()));
2676     if (ValueFits) {
2677       ReplaceWithLI = true;
2678       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8o;
2679       NewImm = InVal.getSExtValue();
2680       SetCR = Opc == PPC::RLWINMo || Opc == PPC::RLWINM8o;
2681       break;
2682     }
2683     return false;
2684   }
2685   case PPC::ORI:
2686   case PPC::ORI8:
2687   case PPC::XORI:
2688   case PPC::XORI8: {
2689     int64_t LogicalImm = MI.getOperand(2).getImm();
2690     int64_t Result = 0;
2691     if (Opc == PPC::ORI || Opc == PPC::ORI8)
2692       Result = LogicalImm | SExtImm;
2693     else
2694       Result = LogicalImm ^ SExtImm;
2695     if (isInt<16>(Result)) {
2696       ReplaceWithLI = true;
2697       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
2698       NewImm = Result;
2699       break;
2700     }
2701     return false;
2702   }
2703   }
2704 
2705   if (ReplaceWithLI) {
2706     // We need to be careful with CR-setting instructions we're replacing.
2707     if (SetCR) {
2708       // We don't know anything about uses when we're out of SSA, so only
2709       // replace if the new immediate will be reproduced.
2710       bool ImmChanged = (SExtImm & NewImm) != NewImm;
2711       if (PostRA && ImmChanged)
2712         return false;
2713 
2714       if (!PostRA) {
2715         // If the defining load-immediate has no other uses, we can just replace
2716         // the immediate with the new immediate.
2717         if (MRI->hasOneUse(DefMI->getOperand(0).getReg()))
2718           DefMI->getOperand(1).setImm(NewImm);
2719 
2720         // If we're not using the GPR result of the CR-setting instruction, we
2721         // just need to and with zero/non-zero depending on the new immediate.
2722         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
2723           if (NewImm) {
2724             assert(Immediate && "Transformation converted zero to non-zero?");
2725             NewImm = Immediate;
2726           }
2727         }
2728         else if (ImmChanged)
2729           return false;
2730       }
2731     }
2732 
2733     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
2734     LLVM_DEBUG(MI.dump());
2735     LLVM_DEBUG(dbgs() << "Fed by:\n");
2736     LLVM_DEBUG(DefMI->dump());
2737     LoadImmediateInfo LII;
2738     LII.Imm = NewImm;
2739     LII.Is64Bit = Is64BitLI;
2740     LII.SetCR = SetCR;
2741     // If we're setting the CR, the original load-immediate must be kept (as an
2742     // operand to ANDIo/ANDI8o).
2743     if (KilledDef && SetCR)
2744       *KilledDef = nullptr;
2745     replaceInstrWithLI(MI, LII);
2746 
2747     // Fixup killed/dead flag after transformation.
2748     // Pattern:
2749     // ForwardingOperandReg = LI imm1
2750     // y = op2 imm2, ForwardingOperandReg(killed)
2751     if (IsForwardingOperandKilled)
2752       fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg);
2753 
2754     LLVM_DEBUG(dbgs() << "With:\n");
2755     LLVM_DEBUG(MI.dump());
2756     return true;
2757   }
2758   return false;
2759 }
2760 
2761 static bool isVFReg(unsigned Reg) {
2762   return PPC::VFRCRegClass.contains(Reg);
2763 }
2764 
2765 bool PPCInstrInfo::instrHasImmForm(const MachineInstr &MI,
2766                                    ImmInstrInfo &III, bool PostRA) const {
2767   unsigned Opc = MI.getOpcode();
2768   // The vast majority of the instructions would need their operand 2 replaced
2769   // with an immediate when switching to the reg+imm form. A marked exception
2770   // are the update form loads/stores for which a constant operand 2 would need
2771   // to turn into a displacement and move operand 1 to the operand 2 position.
2772   III.ImmOpNo = 2;
2773   III.OpNoForForwarding = 2;
2774   III.ImmWidth = 16;
2775   III.ImmMustBeMultipleOf = 1;
2776   III.TruncateImmTo = 0;
2777   III.IsSummingOperands = false;
2778   switch (Opc) {
2779   default: return false;
2780   case PPC::ADD4:
2781   case PPC::ADD8:
2782     III.SignedImm = true;
2783     III.ZeroIsSpecialOrig = 0;
2784     III.ZeroIsSpecialNew = 1;
2785     III.IsCommutative = true;
2786     III.IsSummingOperands = true;
2787     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
2788     break;
2789   case PPC::ADDC:
2790   case PPC::ADDC8:
2791     III.SignedImm = true;
2792     III.ZeroIsSpecialOrig = 0;
2793     III.ZeroIsSpecialNew = 0;
2794     III.IsCommutative = true;
2795     III.IsSummingOperands = true;
2796     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
2797     break;
2798   case PPC::ADDCo:
2799     III.SignedImm = true;
2800     III.ZeroIsSpecialOrig = 0;
2801     III.ZeroIsSpecialNew = 0;
2802     III.IsCommutative = true;
2803     III.IsSummingOperands = true;
2804     III.ImmOpcode = PPC::ADDICo;
2805     break;
2806   case PPC::SUBFC:
2807   case PPC::SUBFC8:
2808     III.SignedImm = true;
2809     III.ZeroIsSpecialOrig = 0;
2810     III.ZeroIsSpecialNew = 0;
2811     III.IsCommutative = false;
2812     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
2813     break;
2814   case PPC::CMPW:
2815   case PPC::CMPD:
2816     III.SignedImm = true;
2817     III.ZeroIsSpecialOrig = 0;
2818     III.ZeroIsSpecialNew = 0;
2819     III.IsCommutative = false;
2820     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
2821     break;
2822   case PPC::CMPLW:
2823   case PPC::CMPLD:
2824     III.SignedImm = false;
2825     III.ZeroIsSpecialOrig = 0;
2826     III.ZeroIsSpecialNew = 0;
2827     III.IsCommutative = false;
2828     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
2829     break;
2830   case PPC::ANDo:
2831   case PPC::AND8o:
2832   case PPC::OR:
2833   case PPC::OR8:
2834   case PPC::XOR:
2835   case PPC::XOR8:
2836     III.SignedImm = false;
2837     III.ZeroIsSpecialOrig = 0;
2838     III.ZeroIsSpecialNew = 0;
2839     III.IsCommutative = true;
2840     switch(Opc) {
2841     default: llvm_unreachable("Unknown opcode");
2842     case PPC::ANDo: III.ImmOpcode = PPC::ANDIo; break;
2843     case PPC::AND8o: III.ImmOpcode = PPC::ANDIo8; break;
2844     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
2845     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
2846     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
2847     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
2848     }
2849     break;
2850   case PPC::RLWNM:
2851   case PPC::RLWNM8:
2852   case PPC::RLWNMo:
2853   case PPC::RLWNM8o:
2854   case PPC::SLW:
2855   case PPC::SLW8:
2856   case PPC::SLWo:
2857   case PPC::SLW8o:
2858   case PPC::SRW:
2859   case PPC::SRW8:
2860   case PPC::SRWo:
2861   case PPC::SRW8o:
2862   case PPC::SRAW:
2863   case PPC::SRAWo:
2864     III.SignedImm = false;
2865     III.ZeroIsSpecialOrig = 0;
2866     III.ZeroIsSpecialNew = 0;
2867     III.IsCommutative = false;
2868     // This isn't actually true, but the instructions ignore any of the
2869     // upper bits, so any immediate loaded with an LI is acceptable.
2870     // This does not apply to shift right algebraic because a value
2871     // out of range will produce a -1/0.
2872     III.ImmWidth = 16;
2873     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 ||
2874         Opc == PPC::RLWNMo || Opc == PPC::RLWNM8o)
2875       III.TruncateImmTo = 5;
2876     else
2877       III.TruncateImmTo = 6;
2878     switch(Opc) {
2879     default: llvm_unreachable("Unknown opcode");
2880     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
2881     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
2882     case PPC::RLWNMo: III.ImmOpcode = PPC::RLWINMo; break;
2883     case PPC::RLWNM8o: III.ImmOpcode = PPC::RLWINM8o; break;
2884     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
2885     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
2886     case PPC::SLWo: III.ImmOpcode = PPC::RLWINMo; break;
2887     case PPC::SLW8o: III.ImmOpcode = PPC::RLWINM8o; break;
2888     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
2889     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
2890     case PPC::SRWo: III.ImmOpcode = PPC::RLWINMo; break;
2891     case PPC::SRW8o: III.ImmOpcode = PPC::RLWINM8o; break;
2892     case PPC::SRAW:
2893       III.ImmWidth = 5;
2894       III.TruncateImmTo = 0;
2895       III.ImmOpcode = PPC::SRAWI;
2896       break;
2897     case PPC::SRAWo:
2898       III.ImmWidth = 5;
2899       III.TruncateImmTo = 0;
2900       III.ImmOpcode = PPC::SRAWIo;
2901       break;
2902     }
2903     break;
2904   case PPC::RLDCL:
2905   case PPC::RLDCLo:
2906   case PPC::RLDCR:
2907   case PPC::RLDCRo:
2908   case PPC::SLD:
2909   case PPC::SLDo:
2910   case PPC::SRD:
2911   case PPC::SRDo:
2912   case PPC::SRAD:
2913   case PPC::SRADo:
2914     III.SignedImm = false;
2915     III.ZeroIsSpecialOrig = 0;
2916     III.ZeroIsSpecialNew = 0;
2917     III.IsCommutative = false;
2918     // This isn't actually true, but the instructions ignore any of the
2919     // upper bits, so any immediate loaded with an LI is acceptable.
2920     // This does not apply to shift right algebraic because a value
2921     // out of range will produce a -1/0.
2922     III.ImmWidth = 16;
2923     if (Opc == PPC::RLDCL || Opc == PPC::RLDCLo ||
2924         Opc == PPC::RLDCR || Opc == PPC::RLDCRo)
2925       III.TruncateImmTo = 6;
2926     else
2927       III.TruncateImmTo = 7;
2928     switch(Opc) {
2929     default: llvm_unreachable("Unknown opcode");
2930     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
2931     case PPC::RLDCLo: III.ImmOpcode = PPC::RLDICLo; break;
2932     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
2933     case PPC::RLDCRo: III.ImmOpcode = PPC::RLDICRo; break;
2934     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
2935     case PPC::SLDo: III.ImmOpcode = PPC::RLDICRo; break;
2936     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
2937     case PPC::SRDo: III.ImmOpcode = PPC::RLDICLo; break;
2938     case PPC::SRAD:
2939       III.ImmWidth = 6;
2940       III.TruncateImmTo = 0;
2941       III.ImmOpcode = PPC::SRADI;
2942        break;
2943     case PPC::SRADo:
2944       III.ImmWidth = 6;
2945       III.TruncateImmTo = 0;
2946       III.ImmOpcode = PPC::SRADIo;
2947       break;
2948     }
2949     break;
2950   // Loads and stores:
2951   case PPC::LBZX:
2952   case PPC::LBZX8:
2953   case PPC::LHZX:
2954   case PPC::LHZX8:
2955   case PPC::LHAX:
2956   case PPC::LHAX8:
2957   case PPC::LWZX:
2958   case PPC::LWZX8:
2959   case PPC::LWAX:
2960   case PPC::LDX:
2961   case PPC::LFSX:
2962   case PPC::LFDX:
2963   case PPC::STBX:
2964   case PPC::STBX8:
2965   case PPC::STHX:
2966   case PPC::STHX8:
2967   case PPC::STWX:
2968   case PPC::STWX8:
2969   case PPC::STDX:
2970   case PPC::STFSX:
2971   case PPC::STFDX:
2972     III.SignedImm = true;
2973     III.ZeroIsSpecialOrig = 1;
2974     III.ZeroIsSpecialNew = 2;
2975     III.IsCommutative = true;
2976     III.IsSummingOperands = true;
2977     III.ImmOpNo = 1;
2978     III.OpNoForForwarding = 2;
2979     switch(Opc) {
2980     default: llvm_unreachable("Unknown opcode");
2981     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
2982     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
2983     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
2984     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
2985     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
2986     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
2987     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
2988     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
2989     case PPC::LWAX:
2990       III.ImmOpcode = PPC::LWA;
2991       III.ImmMustBeMultipleOf = 4;
2992       break;
2993     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
2994     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
2995     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
2996     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
2997     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
2998     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
2999     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3000     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3001     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3002     case PPC::STDX:
3003       III.ImmOpcode = PPC::STD;
3004       III.ImmMustBeMultipleOf = 4;
3005       break;
3006     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3007     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3008     }
3009     break;
3010   case PPC::LBZUX:
3011   case PPC::LBZUX8:
3012   case PPC::LHZUX:
3013   case PPC::LHZUX8:
3014   case PPC::LHAUX:
3015   case PPC::LHAUX8:
3016   case PPC::LWZUX:
3017   case PPC::LWZUX8:
3018   case PPC::LDUX:
3019   case PPC::LFSUX:
3020   case PPC::LFDUX:
3021   case PPC::STBUX:
3022   case PPC::STBUX8:
3023   case PPC::STHUX:
3024   case PPC::STHUX8:
3025   case PPC::STWUX:
3026   case PPC::STWUX8:
3027   case PPC::STDUX:
3028   case PPC::STFSUX:
3029   case PPC::STFDUX:
3030     III.SignedImm = true;
3031     III.ZeroIsSpecialOrig = 2;
3032     III.ZeroIsSpecialNew = 3;
3033     III.IsCommutative = false;
3034     III.IsSummingOperands = true;
3035     III.ImmOpNo = 2;
3036     III.OpNoForForwarding = 3;
3037     switch(Opc) {
3038     default: llvm_unreachable("Unknown opcode");
3039     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3040     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3041     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3042     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3043     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3044     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3045     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3046     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3047     case PPC::LDUX:
3048       III.ImmOpcode = PPC::LDU;
3049       III.ImmMustBeMultipleOf = 4;
3050       break;
3051     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3052     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3053     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3054     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3055     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3056     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3057     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3058     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3059     case PPC::STDUX:
3060       III.ImmOpcode = PPC::STDU;
3061       III.ImmMustBeMultipleOf = 4;
3062       break;
3063     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3064     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3065     }
3066     break;
3067   // Power9 and up only. For some of these, the X-Form version has access to all
3068   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3069   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3070   // into or stored from is one of the VR registers.
3071   case PPC::LXVX:
3072   case PPC::LXSSPX:
3073   case PPC::LXSDX:
3074   case PPC::STXVX:
3075   case PPC::STXSSPX:
3076   case PPC::STXSDX:
3077   case PPC::XFLOADf32:
3078   case PPC::XFLOADf64:
3079   case PPC::XFSTOREf32:
3080   case PPC::XFSTOREf64:
3081     if (!Subtarget.hasP9Vector())
3082       return false;
3083     III.SignedImm = true;
3084     III.ZeroIsSpecialOrig = 1;
3085     III.ZeroIsSpecialNew = 2;
3086     III.IsCommutative = true;
3087     III.IsSummingOperands = true;
3088     III.ImmOpNo = 1;
3089     III.OpNoForForwarding = 2;
3090     III.ImmMustBeMultipleOf = 4;
3091     switch(Opc) {
3092     default: llvm_unreachable("Unknown opcode");
3093     case PPC::LXVX:
3094       III.ImmOpcode = PPC::LXV;
3095       III.ImmMustBeMultipleOf = 16;
3096       break;
3097     case PPC::LXSSPX:
3098       if (PostRA) {
3099         if (isVFReg(MI.getOperand(0).getReg()))
3100           III.ImmOpcode = PPC::LXSSP;
3101         else {
3102           III.ImmOpcode = PPC::LFS;
3103           III.ImmMustBeMultipleOf = 1;
3104         }
3105         break;
3106       }
3107       LLVM_FALLTHROUGH;
3108     case PPC::XFLOADf32:
3109       III.ImmOpcode = PPC::DFLOADf32;
3110       break;
3111     case PPC::LXSDX:
3112       if (PostRA) {
3113         if (isVFReg(MI.getOperand(0).getReg()))
3114           III.ImmOpcode = PPC::LXSD;
3115         else {
3116           III.ImmOpcode = PPC::LFD;
3117           III.ImmMustBeMultipleOf = 1;
3118         }
3119         break;
3120       }
3121       LLVM_FALLTHROUGH;
3122     case PPC::XFLOADf64:
3123       III.ImmOpcode = PPC::DFLOADf64;
3124       break;
3125     case PPC::STXVX:
3126       III.ImmOpcode = PPC::STXV;
3127       III.ImmMustBeMultipleOf = 16;
3128       break;
3129     case PPC::STXSSPX:
3130       if (PostRA) {
3131         if (isVFReg(MI.getOperand(0).getReg()))
3132           III.ImmOpcode = PPC::STXSSP;
3133         else {
3134           III.ImmOpcode = PPC::STFS;
3135           III.ImmMustBeMultipleOf = 1;
3136         }
3137         break;
3138       }
3139       LLVM_FALLTHROUGH;
3140     case PPC::XFSTOREf32:
3141       III.ImmOpcode = PPC::DFSTOREf32;
3142       break;
3143     case PPC::STXSDX:
3144       if (PostRA) {
3145         if (isVFReg(MI.getOperand(0).getReg()))
3146           III.ImmOpcode = PPC::STXSD;
3147         else {
3148           III.ImmOpcode = PPC::STFD;
3149           III.ImmMustBeMultipleOf = 1;
3150         }
3151         break;
3152       }
3153       LLVM_FALLTHROUGH;
3154     case PPC::XFSTOREf64:
3155       III.ImmOpcode = PPC::DFSTOREf64;
3156       break;
3157     }
3158     break;
3159   }
3160   return true;
3161 }
3162 
3163 // Utility function for swaping two arbitrary operands of an instruction.
3164 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3165   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3166 
3167   unsigned MaxOp = std::max(Op1, Op2);
3168   unsigned MinOp = std::min(Op1, Op2);
3169   MachineOperand MOp1 = MI.getOperand(MinOp);
3170   MachineOperand MOp2 = MI.getOperand(MaxOp);
3171   MI.RemoveOperand(std::max(Op1, Op2));
3172   MI.RemoveOperand(std::min(Op1, Op2));
3173 
3174   // If the operands we are swapping are the two at the end (the common case)
3175   // we can just remove both and add them in the opposite order.
3176   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3177     MI.addOperand(MOp2);
3178     MI.addOperand(MOp1);
3179   } else {
3180     // Store all operands in a temporary vector, remove them and re-add in the
3181     // right order.
3182     SmallVector<MachineOperand, 2> MOps;
3183     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3184     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3185       MOps.push_back(MI.getOperand(i));
3186       MI.RemoveOperand(i);
3187     }
3188     // MOp2 needs to be added next.
3189     MI.addOperand(MOp2);
3190     // Now add the rest.
3191     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3192       if (i == MaxOp)
3193         MI.addOperand(MOp1);
3194       else {
3195         MI.addOperand(MOps.back());
3196         MOps.pop_back();
3197       }
3198     }
3199   }
3200 }
3201 
3202 // Check if the 'MI' that has the index OpNoForForwarding
3203 // meets the requirement described in the ImmInstrInfo.
3204 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3205                                                const ImmInstrInfo &III,
3206                                                unsigned OpNoForForwarding
3207                                                ) const {
3208   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3209   // would not work pre-RA, we can only do the check post RA.
3210   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3211   if (MRI.isSSA())
3212     return false;
3213 
3214   // Cannot do the transform if MI isn't summing the operands.
3215   if (!III.IsSummingOperands)
3216     return false;
3217 
3218   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3219   if (!III.ZeroIsSpecialOrig)
3220     return false;
3221 
3222   // We cannot do the transform if the operand we are trying to replace
3223   // isn't the same as the operand the instruction allows.
3224   if (OpNoForForwarding != III.OpNoForForwarding)
3225     return false;
3226 
3227   // Check if the instruction we are trying to transform really has
3228   // the special zero register as its operand.
3229   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3230       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3231     return false;
3232 
3233   // This machine instruction is convertible if it is,
3234   // 1. summing the operands.
3235   // 2. one of the operands is special zero register.
3236   // 3. the operand we are trying to replace is allowed by the MI.
3237   return true;
3238 }
3239 
3240 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3241 // accordingly.
3242 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3243                                                const ImmInstrInfo &III,
3244                                                MachineOperand *&ImmMO,
3245                                                MachineOperand *&RegMO) const {
3246   unsigned Opc = DefMI.getOpcode();
3247   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3248     return false;
3249 
3250   assert(DefMI.getNumOperands() >= 3 &&
3251          "Add inst must have at least three operands");
3252   RegMO = &DefMI.getOperand(1);
3253   ImmMO = &DefMI.getOperand(2);
3254 
3255   // This DefMI is elgible for forwarding if it is:
3256   // 1. add inst
3257   // 2. one of the operands is Imm/CPI/Global.
3258   return isAnImmediateOperand(*ImmMO);
3259 }
3260 
3261 bool PPCInstrInfo::isRegElgibleForForwarding(
3262     const MachineOperand &RegMO, const MachineInstr &DefMI,
3263     const MachineInstr &MI, bool KillDefMI,
3264     bool &IsFwdFeederRegKilled) const {
3265   // x = addi y, imm
3266   // ...
3267   // z = lfdx 0, x   -> z = lfd imm(y)
3268   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3269   // of "y" between the DEF of "x" and "z".
3270   // The query is only valid post RA.
3271   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3272   if (MRI.isSSA())
3273     return false;
3274 
3275   unsigned Reg = RegMO.getReg();
3276 
3277   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3278   MachineBasicBlock::const_reverse_iterator It = MI;
3279   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3280   It++;
3281   for (; It != E; ++It) {
3282     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3283       return false;
3284     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3285       IsFwdFeederRegKilled = true;
3286     // Made it to DefMI without encountering a clobber.
3287     if ((&*It) == &DefMI)
3288       break;
3289   }
3290   assert((&*It) == &DefMI && "DefMI is missing");
3291 
3292   // If DefMI also defines the register to be forwarded, we can only forward it
3293   // if DefMI is being erased.
3294   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3295     return KillDefMI;
3296 
3297   return true;
3298 }
3299 
3300 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3301                                              const MachineInstr &DefMI,
3302                                              const ImmInstrInfo &III,
3303                                              int64_t &Imm) const {
3304   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3305   if (DefMI.getOpcode() == PPC::ADDItocL) {
3306     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3307     // However, we know that, it is 16-bit width, and has the alignment of 4.
3308     // Check if the instruction met the requirement.
3309     if (III.ImmMustBeMultipleOf > 4 ||
3310        III.TruncateImmTo || III.ImmWidth != 16)
3311       return false;
3312 
3313     // Going from XForm to DForm loads means that the displacement needs to be
3314     // not just an immediate but also a multiple of 4, or 16 depending on the
3315     // load. A DForm load cannot be represented if it is a multiple of say 2.
3316     // XForm loads do not have this restriction.
3317     if (ImmMO.isGlobal() &&
3318         ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf)
3319       return false;
3320 
3321     return true;
3322   }
3323 
3324   if (ImmMO.isImm()) {
3325     // It is Imm, we need to check if the Imm fit the range.
3326     int64_t Immediate = ImmMO.getImm();
3327     // Sign-extend to 64-bits.
3328     Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
3329       (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
3330 
3331     if (Imm % III.ImmMustBeMultipleOf)
3332       return false;
3333     if (III.TruncateImmTo)
3334       Imm &= ((1 << III.TruncateImmTo) - 1);
3335     if (III.SignedImm) {
3336       APInt ActualValue(64, Imm, true);
3337       if (!ActualValue.isSignedIntN(III.ImmWidth))
3338         return false;
3339     } else {
3340       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3341       if ((uint64_t)Imm > UnsignedMax)
3342         return false;
3343     }
3344   }
3345   else
3346     return false;
3347 
3348   // This ImmMO is forwarded if it meets the requriement describle
3349   // in ImmInstrInfo
3350   return true;
3351 }
3352 
3353 // If an X-Form instruction is fed by an add-immediate and one of its operands
3354 // is the literal zero, attempt to forward the source of the add-immediate to
3355 // the corresponding D-Form instruction with the displacement coming from
3356 // the immediate being added.
3357 bool PPCInstrInfo::transformToImmFormFedByAdd(
3358     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
3359     MachineInstr &DefMI, bool KillDefMI) const {
3360   //         RegMO ImmMO
3361   //           |    |
3362   // x = addi reg, imm  <----- DefMI
3363   // y = op    0 ,  x   <----- MI
3364   //                |
3365   //         OpNoForForwarding
3366   // Check if the MI meet the requirement described in the III.
3367   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
3368     return false;
3369 
3370   // Check if the DefMI meet the requirement
3371   // described in the III. If yes, set the ImmMO and RegMO accordingly.
3372   MachineOperand *ImmMO = nullptr;
3373   MachineOperand *RegMO = nullptr;
3374   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
3375     return false;
3376   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
3377 
3378   // As we get the Imm operand now, we need to check if the ImmMO meet
3379   // the requirement described in the III. If yes set the Imm.
3380   int64_t Imm = 0;
3381   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
3382     return false;
3383 
3384   bool IsFwdFeederRegKilled = false;
3385   // Check if the RegMO can be forwarded to MI.
3386   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
3387                                  IsFwdFeederRegKilled))
3388     return false;
3389 
3390   // Get killed info in case fixup needed after transformation.
3391   unsigned ForwardKilledOperandReg = ~0U;
3392   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3393   bool PostRA = !MRI.isSSA();
3394   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
3395     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
3396 
3397   // We know that, the MI and DefMI both meet the pattern, and
3398   // the Imm also meet the requirement with the new Imm-form.
3399   // It is safe to do the transformation now.
3400   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3401   LLVM_DEBUG(MI.dump());
3402   LLVM_DEBUG(dbgs() << "Fed by:\n");
3403   LLVM_DEBUG(DefMI.dump());
3404 
3405   // Update the base reg first.
3406   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
3407                                                         false, false,
3408                                                         RegMO->isKill());
3409 
3410   // Then, update the imm.
3411   if (ImmMO->isImm()) {
3412     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
3413     // directly.
3414     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
3415   }
3416   else {
3417     // Otherwise, it is Constant Pool Index(CPI) or Global,
3418     // which is relocation in fact. We need to replace the special zero
3419     // register with ImmMO.
3420     // Before that, we need to fixup the target flags for imm.
3421     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
3422     if (DefMI.getOpcode() == PPC::ADDItocL)
3423       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
3424 
3425     // MI didn't have the interface such as MI.setOperand(i) though
3426     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
3427     // ImmMO, we need to remove ZERO operand and all the operands behind it,
3428     // and, add the ImmMO, then, move back all the operands behind ZERO.
3429     SmallVector<MachineOperand, 2> MOps;
3430     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
3431       MOps.push_back(MI.getOperand(i));
3432       MI.RemoveOperand(i);
3433     }
3434 
3435     // Remove the last MO in the list, which is ZERO operand in fact.
3436     MOps.pop_back();
3437     // Add the imm operand.
3438     MI.addOperand(*ImmMO);
3439     // Now add the rest back.
3440     for (auto &MO : MOps)
3441       MI.addOperand(MO);
3442   }
3443 
3444   // Update the opcode.
3445   MI.setDesc(get(III.ImmOpcode));
3446 
3447   // Fix up killed/dead flag after transformation.
3448   // Pattern 1:
3449   // x = ADD KilledFwdFeederReg, imm
3450   // n = opn KilledFwdFeederReg(killed), regn
3451   // y = XOP 0, x
3452   // Pattern 2:
3453   // x = ADD reg(killed), imm
3454   // y = XOP 0, x
3455   if (IsFwdFeederRegKilled || RegMO->isKill())
3456     fixupIsDeadOrKill(DefMI, MI, RegMO->getReg());
3457   // Pattern 3:
3458   // ForwardKilledOperandReg = ADD reg, imm
3459   // y = XOP 0, ForwardKilledOperandReg(killed)
3460   if (ForwardKilledOperandReg != ~0U)
3461     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3462 
3463   LLVM_DEBUG(dbgs() << "With:\n");
3464   LLVM_DEBUG(MI.dump());
3465 
3466   return true;
3467 }
3468 
3469 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
3470                                              const ImmInstrInfo &III,
3471                                              unsigned ConstantOpNo,
3472                                              MachineInstr &DefMI,
3473                                              int64_t Imm) const {
3474   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3475   bool PostRA = !MRI.isSSA();
3476   // Exit early if we can't convert this.
3477   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
3478     return false;
3479   if (Imm % III.ImmMustBeMultipleOf)
3480     return false;
3481   if (III.TruncateImmTo)
3482     Imm &= ((1 << III.TruncateImmTo) - 1);
3483   if (III.SignedImm) {
3484     APInt ActualValue(64, Imm, true);
3485     if (!ActualValue.isSignedIntN(III.ImmWidth))
3486       return false;
3487   } else {
3488     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3489     if ((uint64_t)Imm > UnsignedMax)
3490       return false;
3491   }
3492 
3493   // If we're post-RA, the instructions don't agree on whether register zero is
3494   // special, we can transform this as long as the register operand that will
3495   // end up in the location where zero is special isn't R0.
3496   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3497     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
3498       III.ZeroIsSpecialNew + 1;
3499     unsigned OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
3500     unsigned NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3501     // If R0 is in the operand where zero is special for the new instruction,
3502     // it is unsafe to transform if the constant operand isn't that operand.
3503     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
3504         ConstantOpNo != III.ZeroIsSpecialNew)
3505       return false;
3506     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
3507         ConstantOpNo != PosForOrigZero)
3508       return false;
3509   }
3510 
3511   // Get killed info in case fixup needed after transformation.
3512   unsigned ForwardKilledOperandReg = ~0U;
3513   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
3514     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
3515 
3516   unsigned Opc = MI.getOpcode();
3517   bool SpecialShift32 =
3518     Opc == PPC::SLW || Opc == PPC::SLWo || Opc == PPC::SRW || Opc == PPC::SRWo;
3519   bool SpecialShift64 =
3520     Opc == PPC::SLD || Opc == PPC::SLDo || Opc == PPC::SRD || Opc == PPC::SRDo;
3521   bool SetCR = Opc == PPC::SLWo || Opc == PPC::SRWo ||
3522     Opc == PPC::SLDo || Opc == PPC::SRDo;
3523   bool RightShift =
3524     Opc == PPC::SRW || Opc == PPC::SRWo || Opc == PPC::SRD || Opc == PPC::SRDo;
3525 
3526   MI.setDesc(get(III.ImmOpcode));
3527   if (ConstantOpNo == III.OpNoForForwarding) {
3528     // Converting shifts to immediate form is a bit tricky since they may do
3529     // one of three things:
3530     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
3531     // 2. If the shift amount is zero, the result is unchanged (save for maybe
3532     //    setting CR0)
3533     // 3. If the shift amount is in [1, OpSize), it's just a shift
3534     if (SpecialShift32 || SpecialShift64) {
3535       LoadImmediateInfo LII;
3536       LII.Imm = 0;
3537       LII.SetCR = SetCR;
3538       LII.Is64Bit = SpecialShift64;
3539       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
3540       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
3541         replaceInstrWithLI(MI, LII);
3542       // Shifts by zero don't change the value. If we don't need to set CR0,
3543       // just convert this to a COPY. Can't do this post-RA since we've already
3544       // cleaned up the copies.
3545       else if (!SetCR && ShAmt == 0 && !PostRA) {
3546         MI.RemoveOperand(2);
3547         MI.setDesc(get(PPC::COPY));
3548       } else {
3549         // The 32 bit and 64 bit instructions are quite different.
3550         if (SpecialShift32) {
3551           // Left shifts use (N, 0, 31-N), right shifts use (32-N, N, 31).
3552           uint64_t SH = RightShift ? 32 - ShAmt : ShAmt;
3553           uint64_t MB = RightShift ? ShAmt : 0;
3554           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
3555           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3556           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
3557             .addImm(ME);
3558         } else {
3559           // Left shifts use (N, 63-N), right shifts use (64-N, N).
3560           uint64_t SH = RightShift ? 64 - ShAmt : ShAmt;
3561           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
3562           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3563           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
3564         }
3565       }
3566     } else
3567       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3568   }
3569   // Convert commutative instructions (switch the operands and convert the
3570   // desired one to an immediate.
3571   else if (III.IsCommutative) {
3572     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3573     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
3574   } else
3575     llvm_unreachable("Should have exited early!");
3576 
3577   // For instructions for which the constant register replaces a different
3578   // operand than where the immediate goes, we need to swap them.
3579   if (III.OpNoForForwarding != III.ImmOpNo)
3580     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
3581 
3582   // If the special R0/X0 register index are different for original instruction
3583   // and new instruction, we need to fix up the register class in new
3584   // instruction.
3585   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3586     if (III.ZeroIsSpecialNew) {
3587       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
3588       // need to fix up register class.
3589       unsigned RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3590       if (TargetRegisterInfo::isVirtualRegister(RegToModify)) {
3591         const TargetRegisterClass *NewRC =
3592           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
3593           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
3594         MRI.setRegClass(RegToModify, NewRC);
3595       }
3596     }
3597   }
3598 
3599   // Fix up killed/dead flag after transformation.
3600   // Pattern:
3601   // ForwardKilledOperandReg = LI imm
3602   // y = XOP reg, ForwardKilledOperandReg(killed)
3603   if (ForwardKilledOperandReg != ~0U)
3604     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3605   return true;
3606 }
3607 
3608 const TargetRegisterClass *
3609 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
3610   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
3611     return &PPC::VSRCRegClass;
3612   return RC;
3613 }
3614 
3615 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
3616   return PPC::getRecordFormOpcode(Opcode);
3617 }
3618 
3619 // This function returns true if the machine instruction
3620 // always outputs a value by sign-extending a 32 bit value,
3621 // i.e. 0 to 31-th bits are same as 32-th bit.
3622 static bool isSignExtendingOp(const MachineInstr &MI) {
3623   int Opcode = MI.getOpcode();
3624   if (Opcode == PPC::LI     || Opcode == PPC::LI8     ||
3625       Opcode == PPC::LIS    || Opcode == PPC::LIS8    ||
3626       Opcode == PPC::SRAW   || Opcode == PPC::SRAWo   ||
3627       Opcode == PPC::SRAWI  || Opcode == PPC::SRAWIo  ||
3628       Opcode == PPC::LWA    || Opcode == PPC::LWAX    ||
3629       Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
3630       Opcode == PPC::LHA    || Opcode == PPC::LHAX    ||
3631       Opcode == PPC::LHA8   || Opcode == PPC::LHAX8   ||
3632       Opcode == PPC::LBZ    || Opcode == PPC::LBZX    ||
3633       Opcode == PPC::LBZ8   || Opcode == PPC::LBZX8   ||
3634       Opcode == PPC::LBZU   || Opcode == PPC::LBZUX   ||
3635       Opcode == PPC::LBZU8  || Opcode == PPC::LBZUX8  ||
3636       Opcode == PPC::LHZ    || Opcode == PPC::LHZX    ||
3637       Opcode == PPC::LHZ8   || Opcode == PPC::LHZX8   ||
3638       Opcode == PPC::LHZU   || Opcode == PPC::LHZUX   ||
3639       Opcode == PPC::LHZU8  || Opcode == PPC::LHZUX8  ||
3640       Opcode == PPC::EXTSB  || Opcode == PPC::EXTSBo  ||
3641       Opcode == PPC::EXTSH  || Opcode == PPC::EXTSHo  ||
3642       Opcode == PPC::EXTSB8 || Opcode == PPC::EXTSH8  ||
3643       Opcode == PPC::EXTSW  || Opcode == PPC::EXTSWo  ||
3644       Opcode == PPC::SETB   || Opcode == PPC::SETB8   ||
3645       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
3646       Opcode == PPC::EXTSB8_32_64)
3647     return true;
3648 
3649   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
3650     return true;
3651 
3652   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINMo ||
3653        Opcode == PPC::RLWNM  || Opcode == PPC::RLWNMo) &&
3654       MI.getOperand(3).getImm() > 0 &&
3655       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3656     return true;
3657 
3658   return false;
3659 }
3660 
3661 // This function returns true if the machine instruction
3662 // always outputs zeros in higher 32 bits.
3663 static bool isZeroExtendingOp(const MachineInstr &MI) {
3664   int Opcode = MI.getOpcode();
3665   // The 16-bit immediate is sign-extended in li/lis.
3666   // If the most significant bit is zero, all higher bits are zero.
3667   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
3668       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
3669     int64_t Imm = MI.getOperand(1).getImm();
3670     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
3671       return true;
3672   }
3673 
3674   // We have some variations of rotate-and-mask instructions
3675   // that clear higher 32-bits.
3676   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICLo ||
3677        Opcode == PPC::RLDCL  || Opcode == PPC::RLDCLo  ||
3678        Opcode == PPC::RLDICL_32_64) &&
3679       MI.getOperand(3).getImm() >= 32)
3680     return true;
3681 
3682   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDICo) &&
3683       MI.getOperand(3).getImm() >= 32 &&
3684       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
3685     return true;
3686 
3687   if ((Opcode == PPC::RLWINM  || Opcode == PPC::RLWINMo ||
3688        Opcode == PPC::RLWNM   || Opcode == PPC::RLWNMo  ||
3689        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
3690       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3691     return true;
3692 
3693   // There are other instructions that clear higher 32-bits.
3694   if (Opcode == PPC::CNTLZW  || Opcode == PPC::CNTLZWo ||
3695       Opcode == PPC::CNTTZW  || Opcode == PPC::CNTTZWo ||
3696       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
3697       Opcode == PPC::CNTLZD  || Opcode == PPC::CNTLZDo ||
3698       Opcode == PPC::CNTTZD  || Opcode == PPC::CNTTZDo ||
3699       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW ||
3700       Opcode == PPC::SLW     || Opcode == PPC::SLWo    ||
3701       Opcode == PPC::SRW     || Opcode == PPC::SRWo    ||
3702       Opcode == PPC::SLW8    || Opcode == PPC::SRW8    ||
3703       Opcode == PPC::SLWI    || Opcode == PPC::SLWIo   ||
3704       Opcode == PPC::SRWI    || Opcode == PPC::SRWIo   ||
3705       Opcode == PPC::LWZ     || Opcode == PPC::LWZX    ||
3706       Opcode == PPC::LWZU    || Opcode == PPC::LWZUX   ||
3707       Opcode == PPC::LWBRX   || Opcode == PPC::LHBRX   ||
3708       Opcode == PPC::LHZ     || Opcode == PPC::LHZX    ||
3709       Opcode == PPC::LHZU    || Opcode == PPC::LHZUX   ||
3710       Opcode == PPC::LBZ     || Opcode == PPC::LBZX    ||
3711       Opcode == PPC::LBZU    || Opcode == PPC::LBZUX   ||
3712       Opcode == PPC::LWZ8    || Opcode == PPC::LWZX8   ||
3713       Opcode == PPC::LWZU8   || Opcode == PPC::LWZUX8  ||
3714       Opcode == PPC::LWBRX8  || Opcode == PPC::LHBRX8  ||
3715       Opcode == PPC::LHZ8    || Opcode == PPC::LHZX8   ||
3716       Opcode == PPC::LHZU8   || Opcode == PPC::LHZUX8  ||
3717       Opcode == PPC::LBZ8    || Opcode == PPC::LBZX8   ||
3718       Opcode == PPC::LBZU8   || Opcode == PPC::LBZUX8  ||
3719       Opcode == PPC::ANDIo   || Opcode == PPC::ANDISo  ||
3720       Opcode == PPC::ROTRWI  || Opcode == PPC::ROTRWIo ||
3721       Opcode == PPC::EXTLWI  || Opcode == PPC::EXTLWIo ||
3722       Opcode == PPC::MFVSRWZ)
3723     return true;
3724 
3725   return false;
3726 }
3727 
3728 // This function returns true if the input MachineInstr is a TOC save
3729 // instruction.
3730 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
3731   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
3732     return false;
3733   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
3734   unsigned StackOffset = MI.getOperand(1).getImm();
3735   unsigned StackReg = MI.getOperand(2).getReg();
3736   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
3737     return true;
3738 
3739   return false;
3740 }
3741 
3742 // We limit the max depth to track incoming values of PHIs or binary ops
3743 // (e.g. AND) to avoid excessive cost.
3744 const unsigned MAX_DEPTH = 1;
3745 
3746 bool
3747 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
3748                                    const unsigned Depth) const {
3749   const MachineFunction *MF = MI.getParent()->getParent();
3750   const MachineRegisterInfo *MRI = &MF->getRegInfo();
3751 
3752   // If we know this instruction returns sign- or zero-extended result,
3753   // return true.
3754   if (SignExt ? isSignExtendingOp(MI):
3755                 isZeroExtendingOp(MI))
3756     return true;
3757 
3758   switch (MI.getOpcode()) {
3759   case PPC::COPY: {
3760     unsigned SrcReg = MI.getOperand(1).getReg();
3761 
3762     // In both ELFv1 and v2 ABI, method parameters and the return value
3763     // are sign- or zero-extended.
3764     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
3765       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
3766       // We check the ZExt/SExt flags for a method parameter.
3767       if (MI.getParent()->getBasicBlock() ==
3768           &MF->getFunction().getEntryBlock()) {
3769         unsigned VReg = MI.getOperand(0).getReg();
3770         if (MF->getRegInfo().isLiveIn(VReg))
3771           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
3772                            FuncInfo->isLiveInZExt(VReg);
3773       }
3774 
3775       // For a method return value, we check the ZExt/SExt flags in attribute.
3776       // We assume the following code sequence for method call.
3777       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
3778       //   BL8_NOP @func,...
3779       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
3780       //   %5 = COPY %x3; G8RC:%5
3781       if (SrcReg == PPC::X3) {
3782         const MachineBasicBlock *MBB = MI.getParent();
3783         MachineBasicBlock::const_instr_iterator II =
3784           MachineBasicBlock::const_instr_iterator(&MI);
3785         if (II != MBB->instr_begin() &&
3786             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
3787           const MachineInstr &CallMI = *(--II);
3788           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
3789             const Function *CalleeFn =
3790               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
3791             if (!CalleeFn)
3792               return false;
3793             const IntegerType *IntTy =
3794               dyn_cast<IntegerType>(CalleeFn->getReturnType());
3795             const AttributeSet &Attrs =
3796               CalleeFn->getAttributes().getRetAttributes();
3797             if (IntTy && IntTy->getBitWidth() <= 32)
3798               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
3799                                                   Attribute::ZExt);
3800           }
3801         }
3802       }
3803     }
3804 
3805     // If this is a copy from another register, we recursively check source.
3806     if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
3807       return false;
3808     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3809     if (SrcMI != NULL)
3810       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
3811 
3812     return false;
3813   }
3814 
3815   case PPC::ANDIo:
3816   case PPC::ANDISo:
3817   case PPC::ORI:
3818   case PPC::ORIS:
3819   case PPC::XORI:
3820   case PPC::XORIS:
3821   case PPC::ANDIo8:
3822   case PPC::ANDISo8:
3823   case PPC::ORI8:
3824   case PPC::ORIS8:
3825   case PPC::XORI8:
3826   case PPC::XORIS8: {
3827     // logical operation with 16-bit immediate does not change the upper bits.
3828     // So, we track the operand register as we do for register copy.
3829     unsigned SrcReg = MI.getOperand(1).getReg();
3830     if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
3831       return false;
3832     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3833     if (SrcMI != NULL)
3834       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
3835 
3836     return false;
3837   }
3838 
3839   // If all incoming values are sign-/zero-extended,
3840   // the output of OR, ISEL or PHI is also sign-/zero-extended.
3841   case PPC::OR:
3842   case PPC::OR8:
3843   case PPC::ISEL:
3844   case PPC::PHI: {
3845     if (Depth >= MAX_DEPTH)
3846       return false;
3847 
3848     // The input registers for PHI are operand 1, 3, ...
3849     // The input registers for others are operand 1 and 2.
3850     unsigned E = 3, D = 1;
3851     if (MI.getOpcode() == PPC::PHI) {
3852       E = MI.getNumOperands();
3853       D = 2;
3854     }
3855 
3856     for (unsigned I = 1; I != E; I += D) {
3857       if (MI.getOperand(I).isReg()) {
3858         unsigned SrcReg = MI.getOperand(I).getReg();
3859         if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
3860           return false;
3861         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3862         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
3863           return false;
3864       }
3865       else
3866         return false;
3867     }
3868     return true;
3869   }
3870 
3871   // If at least one of the incoming values of an AND is zero extended
3872   // then the output is also zero-extended. If both of the incoming values
3873   // are sign-extended then the output is also sign extended.
3874   case PPC::AND:
3875   case PPC::AND8: {
3876     if (Depth >= MAX_DEPTH)
3877        return false;
3878 
3879     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
3880 
3881     unsigned SrcReg1 = MI.getOperand(1).getReg();
3882     unsigned SrcReg2 = MI.getOperand(2).getReg();
3883 
3884     if (!TargetRegisterInfo::isVirtualRegister(SrcReg1) ||
3885         !TargetRegisterInfo::isVirtualRegister(SrcReg2))
3886        return false;
3887 
3888     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
3889     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
3890     if (!MISrc1 || !MISrc2)
3891         return false;
3892 
3893     if(SignExt)
3894         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
3895                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
3896     else
3897         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
3898                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
3899   }
3900 
3901   default:
3902     break;
3903   }
3904   return false;
3905 }
3906