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_LastOpcodeSpill  // This must be last on the enum.
94 };
95 
96 // Pin the vtable to this file.
97 void PPCInstrInfo::anchor() {}
98 
99 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
100     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
101                       /* CatchRetOpcode */ -1,
102                       STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
103       Subtarget(STI), RI(STI.getTargetMachine()) {}
104 
105 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
106 /// this target when scheduling the DAG.
107 ScheduleHazardRecognizer *
108 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
109                                            const ScheduleDAG *DAG) const {
110   unsigned Directive =
111       static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
112   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
113       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
114     const InstrItineraryData *II =
115         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
116     return new ScoreboardHazardRecognizer(II, DAG);
117   }
118 
119   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
120 }
121 
122 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
123 /// to use for this target when scheduling the DAG.
124 ScheduleHazardRecognizer *
125 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
126                                                  const ScheduleDAG *DAG) const {
127   unsigned Directive =
128       DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
129 
130   // FIXME: Leaving this as-is until we have POWER9 scheduling info
131   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
132     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
133 
134   // Most subtargets use a PPC970 recognizer.
135   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
136       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
137     assert(DAG->TII && "No InstrInfo?");
138 
139     return new PPCHazardRecognizer970(*DAG);
140   }
141 
142   return new ScoreboardHazardRecognizer(II, DAG);
143 }
144 
145 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
146                                        const MachineInstr &MI,
147                                        unsigned *PredCost) const {
148   if (!ItinData || UseOldLatencyCalc)
149     return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
150 
151   // The default implementation of getInstrLatency calls getStageLatency, but
152   // getStageLatency does not do the right thing for us. While we have
153   // itinerary, most cores are fully pipelined, and so the itineraries only
154   // express the first part of the pipeline, not every stage. Instead, we need
155   // to use the listed output operand cycle number (using operand 0 here, which
156   // is an output).
157 
158   unsigned Latency = 1;
159   unsigned DefClass = MI.getDesc().getSchedClass();
160   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
161     const MachineOperand &MO = MI.getOperand(i);
162     if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
163       continue;
164 
165     int Cycle = ItinData->getOperandCycle(DefClass, i);
166     if (Cycle < 0)
167       continue;
168 
169     Latency = std::max(Latency, (unsigned) Cycle);
170   }
171 
172   return Latency;
173 }
174 
175 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
176                                     const MachineInstr &DefMI, unsigned DefIdx,
177                                     const MachineInstr &UseMI,
178                                     unsigned UseIdx) const {
179   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
180                                                    UseMI, UseIdx);
181 
182   if (!DefMI.getParent())
183     return Latency;
184 
185   const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
186   Register Reg = DefMO.getReg();
187 
188   bool IsRegCR;
189   if (Register::isVirtualRegister(Reg)) {
190     const MachineRegisterInfo *MRI =
191         &DefMI.getParent()->getParent()->getRegInfo();
192     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
193               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
194   } else {
195     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
196               PPC::CRBITRCRegClass.contains(Reg);
197   }
198 
199   if (UseMI.isBranch() && IsRegCR) {
200     if (Latency < 0)
201       Latency = getInstrLatency(ItinData, DefMI);
202 
203     // On some cores, there is an additional delay between writing to a condition
204     // register, and using it from a branch.
205     unsigned Directive = Subtarget.getCPUDirective();
206     switch (Directive) {
207     default: break;
208     case PPC::DIR_7400:
209     case PPC::DIR_750:
210     case PPC::DIR_970:
211     case PPC::DIR_E5500:
212     case PPC::DIR_PWR4:
213     case PPC::DIR_PWR5:
214     case PPC::DIR_PWR5X:
215     case PPC::DIR_PWR6:
216     case PPC::DIR_PWR6X:
217     case PPC::DIR_PWR7:
218     case PPC::DIR_PWR8:
219     // FIXME: Is this needed for POWER9?
220       Latency += 2;
221       break;
222     }
223   }
224 
225   return Latency;
226 }
227 
228 /// This is an architecture-specific helper function of reassociateOps.
229 /// Set special operand attributes for new instructions after reassociation.
230 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1,
231                                          MachineInstr &OldMI2,
232                                          MachineInstr &NewMI1,
233                                          MachineInstr &NewMI2) const {
234   // Propagate FP flags from the original instructions.
235   // But clear poison-generating flags because those may not be valid now.
236   uint16_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags();
237   NewMI1.setFlags(IntersectedFlags);
238   NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap);
239   NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap);
240   NewMI1.clearFlag(MachineInstr::MIFlag::IsExact);
241 
242   NewMI2.setFlags(IntersectedFlags);
243   NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap);
244   NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap);
245   NewMI2.clearFlag(MachineInstr::MIFlag::IsExact);
246 }
247 
248 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &MI,
249                                          uint16_t Flags) const {
250   MI.setFlags(Flags);
251   MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
252   MI.clearFlag(MachineInstr::MIFlag::NoUWrap);
253   MI.clearFlag(MachineInstr::MIFlag::IsExact);
254 }
255 
256 // This function does not list all associative and commutative operations, but
257 // only those worth feeding through the machine combiner in an attempt to
258 // reduce the critical path. Mostly, this means floating-point operations,
259 // because they have high latencies (compared to other operations, such and
260 // and/or, which are also associative and commutative, but have low latencies).
261 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
262   switch (Inst.getOpcode()) {
263   // FP Add:
264   case PPC::FADD:
265   case PPC::FADDS:
266   // FP Multiply:
267   case PPC::FMUL:
268   case PPC::FMULS:
269   // Altivec Add:
270   case PPC::VADDFP:
271   // VSX Add:
272   case PPC::XSADDDP:
273   case PPC::XVADDDP:
274   case PPC::XVADDSP:
275   case PPC::XSADDSP:
276   // VSX Multiply:
277   case PPC::XSMULDP:
278   case PPC::XVMULDP:
279   case PPC::XVMULSP:
280   case PPC::XSMULSP:
281   // QPX Add:
282   case PPC::QVFADD:
283   case PPC::QVFADDS:
284   case PPC::QVFADDSs:
285   // QPX Multiply:
286   case PPC::QVFMUL:
287   case PPC::QVFMULS:
288   case PPC::QVFMULSs:
289     return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) &&
290            Inst.getFlag(MachineInstr::MIFlag::FmNsz);
291   default:
292     return false;
293   }
294 }
295 
296 bool PPCInstrInfo::getMachineCombinerPatterns(
297     MachineInstr &Root,
298     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
299   // Using the machine combiner in this way is potentially expensive, so
300   // restrict to when aggressive optimizations are desired.
301   if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
302     return false;
303 
304   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
305 }
306 
307 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
308 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
309                                          Register &SrcReg, Register &DstReg,
310                                          unsigned &SubIdx) const {
311   switch (MI.getOpcode()) {
312   default: return false;
313   case PPC::EXTSW:
314   case PPC::EXTSW_32:
315   case PPC::EXTSW_32_64:
316     SrcReg = MI.getOperand(1).getReg();
317     DstReg = MI.getOperand(0).getReg();
318     SubIdx = PPC::sub_32;
319     return true;
320   }
321 }
322 
323 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
324                                            int &FrameIndex) const {
325   unsigned Opcode = MI.getOpcode();
326   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
327   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
328 
329   if (End != std::find(OpcodesForSpill, End, Opcode)) {
330     // Check for the operands added by addFrameReference (the immediate is the
331     // offset which defaults to 0).
332     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
333         MI.getOperand(2).isFI()) {
334       FrameIndex = MI.getOperand(2).getIndex();
335       return MI.getOperand(0).getReg();
336     }
337   }
338   return 0;
339 }
340 
341 // For opcodes with the ReMaterializable flag set, this function is called to
342 // verify the instruction is really rematable.
343 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
344                                                      AliasAnalysis *AA) const {
345   switch (MI.getOpcode()) {
346   default:
347     // This function should only be called for opcodes with the ReMaterializable
348     // flag set.
349     llvm_unreachable("Unknown rematerializable operation!");
350     break;
351   case PPC::LI:
352   case PPC::LI8:
353   case PPC::LIS:
354   case PPC::LIS8:
355   case PPC::QVGPCI:
356   case PPC::ADDIStocHA:
357   case PPC::ADDIStocHA8:
358   case PPC::ADDItocL:
359   case PPC::LOAD_STACK_GUARD:
360   case PPC::XXLXORz:
361   case PPC::XXLXORspz:
362   case PPC::XXLXORdpz:
363   case PPC::XXLEQVOnes:
364   case PPC::V_SET0B:
365   case PPC::V_SET0H:
366   case PPC::V_SET0:
367   case PPC::V_SETALLONESB:
368   case PPC::V_SETALLONESH:
369   case PPC::V_SETALLONES:
370   case PPC::CRSET:
371   case PPC::CRUNSET:
372     return true;
373   }
374   return false;
375 }
376 
377 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
378                                           int &FrameIndex) const {
379   unsigned Opcode = MI.getOpcode();
380   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
381   const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
382 
383   if (End != std::find(OpcodesForSpill, End, Opcode)) {
384     if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
385         MI.getOperand(2).isFI()) {
386       FrameIndex = MI.getOperand(2).getIndex();
387       return MI.getOperand(0).getReg();
388     }
389   }
390   return 0;
391 }
392 
393 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
394                                                    unsigned OpIdx1,
395                                                    unsigned OpIdx2) const {
396   MachineFunction &MF = *MI.getParent()->getParent();
397 
398   // Normal instructions can be commuted the obvious way.
399   if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
400     return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
401   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
402   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
403   // changing the relative order of the mask operands might change what happens
404   // to the high-bits of the mask (and, thus, the result).
405 
406   // Cannot commute if it has a non-zero rotate count.
407   if (MI.getOperand(3).getImm() != 0)
408     return nullptr;
409 
410   // If we have a zero rotate count, we have:
411   //   M = mask(MB,ME)
412   //   Op0 = (Op1 & ~M) | (Op2 & M)
413   // Change this to:
414   //   M = mask((ME+1)&31, (MB-1)&31)
415   //   Op0 = (Op2 & ~M) | (Op1 & M)
416 
417   // Swap op1/op2
418   assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
419          "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
420   Register Reg0 = MI.getOperand(0).getReg();
421   Register Reg1 = MI.getOperand(1).getReg();
422   Register Reg2 = MI.getOperand(2).getReg();
423   unsigned SubReg1 = MI.getOperand(1).getSubReg();
424   unsigned SubReg2 = MI.getOperand(2).getSubReg();
425   bool Reg1IsKill = MI.getOperand(1).isKill();
426   bool Reg2IsKill = MI.getOperand(2).isKill();
427   bool ChangeReg0 = false;
428   // If machine instrs are no longer in two-address forms, update
429   // destination register as well.
430   if (Reg0 == Reg1) {
431     // Must be two address instruction!
432     assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
433            "Expecting a two-address instruction!");
434     assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
435     Reg2IsKill = false;
436     ChangeReg0 = true;
437   }
438 
439   // Masks.
440   unsigned MB = MI.getOperand(4).getImm();
441   unsigned ME = MI.getOperand(5).getImm();
442 
443   // We can't commute a trivial mask (there is no way to represent an all-zero
444   // mask).
445   if (MB == 0 && ME == 31)
446     return nullptr;
447 
448   if (NewMI) {
449     // Create a new instruction.
450     Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
451     bool Reg0IsDead = MI.getOperand(0).isDead();
452     return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
453         .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
454         .addReg(Reg2, getKillRegState(Reg2IsKill))
455         .addReg(Reg1, getKillRegState(Reg1IsKill))
456         .addImm((ME + 1) & 31)
457         .addImm((MB - 1) & 31);
458   }
459 
460   if (ChangeReg0) {
461     MI.getOperand(0).setReg(Reg2);
462     MI.getOperand(0).setSubReg(SubReg2);
463   }
464   MI.getOperand(2).setReg(Reg1);
465   MI.getOperand(1).setReg(Reg2);
466   MI.getOperand(2).setSubReg(SubReg1);
467   MI.getOperand(1).setSubReg(SubReg2);
468   MI.getOperand(2).setIsKill(Reg1IsKill);
469   MI.getOperand(1).setIsKill(Reg2IsKill);
470 
471   // Swap the mask around.
472   MI.getOperand(4).setImm((ME + 1) & 31);
473   MI.getOperand(5).setImm((MB - 1) & 31);
474   return &MI;
475 }
476 
477 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
478                                          unsigned &SrcOpIdx1,
479                                          unsigned &SrcOpIdx2) const {
480   // For VSX A-Type FMA instructions, it is the first two operands that can be
481   // commuted, however, because the non-encoded tied input operand is listed
482   // first, the operands to swap are actually the second and third.
483 
484   int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
485   if (AltOpc == -1)
486     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
487 
488   // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
489   // and SrcOpIdx2.
490   return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
491 }
492 
493 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
494                               MachineBasicBlock::iterator MI) const {
495   // This function is used for scheduling, and the nop wanted here is the type
496   // that terminates dispatch groups on the POWER cores.
497   unsigned Directive = Subtarget.getCPUDirective();
498   unsigned Opcode;
499   switch (Directive) {
500   default:            Opcode = PPC::NOP; break;
501   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
502   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
503   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
504   // FIXME: Update when POWER9 scheduling model is ready.
505   case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
506   }
507 
508   DebugLoc DL;
509   BuildMI(MBB, MI, DL, get(Opcode));
510 }
511 
512 /// Return the noop instruction to use for a noop.
513 void PPCInstrInfo::getNoop(MCInst &NopInst) const {
514   NopInst.setOpcode(PPC::NOP);
515 }
516 
517 // Branch analysis.
518 // Note: If the condition register is set to CTR or CTR8 then this is a
519 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
520 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
521                                  MachineBasicBlock *&TBB,
522                                  MachineBasicBlock *&FBB,
523                                  SmallVectorImpl<MachineOperand> &Cond,
524                                  bool AllowModify) const {
525   bool isPPC64 = Subtarget.isPPC64();
526 
527   // If the block has no terminators, it just falls into the block after it.
528   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
529   if (I == MBB.end())
530     return false;
531 
532   if (!isUnpredicatedTerminator(*I))
533     return false;
534 
535   if (AllowModify) {
536     // If the BB ends with an unconditional branch to the fallthrough BB,
537     // we eliminate the branch instruction.
538     if (I->getOpcode() == PPC::B &&
539         MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
540       I->eraseFromParent();
541 
542       // We update iterator after deleting the last branch.
543       I = MBB.getLastNonDebugInstr();
544       if (I == MBB.end() || !isUnpredicatedTerminator(*I))
545         return false;
546     }
547   }
548 
549   // Get the last instruction in the block.
550   MachineInstr &LastInst = *I;
551 
552   // If there is only one terminator instruction, process it.
553   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
554     if (LastInst.getOpcode() == PPC::B) {
555       if (!LastInst.getOperand(0).isMBB())
556         return true;
557       TBB = LastInst.getOperand(0).getMBB();
558       return false;
559     } else if (LastInst.getOpcode() == PPC::BCC) {
560       if (!LastInst.getOperand(2).isMBB())
561         return true;
562       // Block ends with fall-through condbranch.
563       TBB = LastInst.getOperand(2).getMBB();
564       Cond.push_back(LastInst.getOperand(0));
565       Cond.push_back(LastInst.getOperand(1));
566       return false;
567     } else if (LastInst.getOpcode() == PPC::BC) {
568       if (!LastInst.getOperand(1).isMBB())
569         return true;
570       // Block ends with fall-through condbranch.
571       TBB = LastInst.getOperand(1).getMBB();
572       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
573       Cond.push_back(LastInst.getOperand(0));
574       return false;
575     } else if (LastInst.getOpcode() == PPC::BCn) {
576       if (!LastInst.getOperand(1).isMBB())
577         return true;
578       // Block ends with fall-through condbranch.
579       TBB = LastInst.getOperand(1).getMBB();
580       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
581       Cond.push_back(LastInst.getOperand(0));
582       return false;
583     } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
584                LastInst.getOpcode() == PPC::BDNZ) {
585       if (!LastInst.getOperand(0).isMBB())
586         return true;
587       if (DisableCTRLoopAnal)
588         return true;
589       TBB = LastInst.getOperand(0).getMBB();
590       Cond.push_back(MachineOperand::CreateImm(1));
591       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
592                                                true));
593       return false;
594     } else if (LastInst.getOpcode() == PPC::BDZ8 ||
595                LastInst.getOpcode() == PPC::BDZ) {
596       if (!LastInst.getOperand(0).isMBB())
597         return true;
598       if (DisableCTRLoopAnal)
599         return true;
600       TBB = LastInst.getOperand(0).getMBB();
601       Cond.push_back(MachineOperand::CreateImm(0));
602       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
603                                                true));
604       return false;
605     }
606 
607     // Otherwise, don't know what this is.
608     return true;
609   }
610 
611   // Get the instruction before it if it's a terminator.
612   MachineInstr &SecondLastInst = *I;
613 
614   // If there are three terminators, we don't know what sort of block this is.
615   if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
616     return true;
617 
618   // If the block ends with PPC::B and PPC:BCC, handle it.
619   if (SecondLastInst.getOpcode() == PPC::BCC &&
620       LastInst.getOpcode() == PPC::B) {
621     if (!SecondLastInst.getOperand(2).isMBB() ||
622         !LastInst.getOperand(0).isMBB())
623       return true;
624     TBB = SecondLastInst.getOperand(2).getMBB();
625     Cond.push_back(SecondLastInst.getOperand(0));
626     Cond.push_back(SecondLastInst.getOperand(1));
627     FBB = LastInst.getOperand(0).getMBB();
628     return false;
629   } else if (SecondLastInst.getOpcode() == PPC::BC &&
630              LastInst.getOpcode() == PPC::B) {
631     if (!SecondLastInst.getOperand(1).isMBB() ||
632         !LastInst.getOperand(0).isMBB())
633       return true;
634     TBB = SecondLastInst.getOperand(1).getMBB();
635     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
636     Cond.push_back(SecondLastInst.getOperand(0));
637     FBB = LastInst.getOperand(0).getMBB();
638     return false;
639   } else if (SecondLastInst.getOpcode() == PPC::BCn &&
640              LastInst.getOpcode() == PPC::B) {
641     if (!SecondLastInst.getOperand(1).isMBB() ||
642         !LastInst.getOperand(0).isMBB())
643       return true;
644     TBB = SecondLastInst.getOperand(1).getMBB();
645     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
646     Cond.push_back(SecondLastInst.getOperand(0));
647     FBB = LastInst.getOperand(0).getMBB();
648     return false;
649   } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
650               SecondLastInst.getOpcode() == PPC::BDNZ) &&
651              LastInst.getOpcode() == PPC::B) {
652     if (!SecondLastInst.getOperand(0).isMBB() ||
653         !LastInst.getOperand(0).isMBB())
654       return true;
655     if (DisableCTRLoopAnal)
656       return true;
657     TBB = SecondLastInst.getOperand(0).getMBB();
658     Cond.push_back(MachineOperand::CreateImm(1));
659     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
660                                              true));
661     FBB = LastInst.getOperand(0).getMBB();
662     return false;
663   } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
664               SecondLastInst.getOpcode() == PPC::BDZ) &&
665              LastInst.getOpcode() == PPC::B) {
666     if (!SecondLastInst.getOperand(0).isMBB() ||
667         !LastInst.getOperand(0).isMBB())
668       return true;
669     if (DisableCTRLoopAnal)
670       return true;
671     TBB = SecondLastInst.getOperand(0).getMBB();
672     Cond.push_back(MachineOperand::CreateImm(0));
673     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
674                                              true));
675     FBB = LastInst.getOperand(0).getMBB();
676     return false;
677   }
678 
679   // If the block ends with two PPC:Bs, handle it.  The second one is not
680   // executed, so remove it.
681   if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
682     if (!SecondLastInst.getOperand(0).isMBB())
683       return true;
684     TBB = SecondLastInst.getOperand(0).getMBB();
685     I = LastInst;
686     if (AllowModify)
687       I->eraseFromParent();
688     return false;
689   }
690 
691   // Otherwise, can't handle this.
692   return true;
693 }
694 
695 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
696                                     int *BytesRemoved) const {
697   assert(!BytesRemoved && "code size not handled");
698 
699   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
700   if (I == MBB.end())
701     return 0;
702 
703   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
704       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
705       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
706       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
707     return 0;
708 
709   // Remove the branch.
710   I->eraseFromParent();
711 
712   I = MBB.end();
713 
714   if (I == MBB.begin()) return 1;
715   --I;
716   if (I->getOpcode() != PPC::BCC &&
717       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
718       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
719       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
720     return 1;
721 
722   // Remove the branch.
723   I->eraseFromParent();
724   return 2;
725 }
726 
727 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
728                                     MachineBasicBlock *TBB,
729                                     MachineBasicBlock *FBB,
730                                     ArrayRef<MachineOperand> Cond,
731                                     const DebugLoc &DL,
732                                     int *BytesAdded) const {
733   // Shouldn't be a fall through.
734   assert(TBB && "insertBranch must not be told to insert a fallthrough");
735   assert((Cond.size() == 2 || Cond.size() == 0) &&
736          "PPC branch conditions have two components!");
737   assert(!BytesAdded && "code size not handled");
738 
739   bool isPPC64 = Subtarget.isPPC64();
740 
741   // One-way branch.
742   if (!FBB) {
743     if (Cond.empty())   // Unconditional branch
744       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
745     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
746       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
747                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
748                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
749     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
750       BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
751     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
752       BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
753     else                // Conditional branch
754       BuildMI(&MBB, DL, get(PPC::BCC))
755           .addImm(Cond[0].getImm())
756           .add(Cond[1])
757           .addMBB(TBB);
758     return 1;
759   }
760 
761   // Two-way Conditional Branch.
762   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
763     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
764                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
765                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
766   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
767     BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
768   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
769     BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
770   else
771     BuildMI(&MBB, DL, get(PPC::BCC))
772         .addImm(Cond[0].getImm())
773         .add(Cond[1])
774         .addMBB(TBB);
775   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
776   return 2;
777 }
778 
779 // Select analysis.
780 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
781                                    ArrayRef<MachineOperand> Cond,
782                                    Register DstReg, Register TrueReg,
783                                    Register FalseReg, int &CondCycles,
784                                    int &TrueCycles, int &FalseCycles) const {
785   if (Cond.size() != 2)
786     return false;
787 
788   // If this is really a bdnz-like condition, then it cannot be turned into a
789   // select.
790   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
791     return false;
792 
793   // Check register classes.
794   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
795   const TargetRegisterClass *RC =
796     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
797   if (!RC)
798     return false;
799 
800   // isel is for regular integer GPRs only.
801   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
802       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
803       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
804       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
805     return false;
806 
807   // FIXME: These numbers are for the A2, how well they work for other cores is
808   // an open question. On the A2, the isel instruction has a 2-cycle latency
809   // but single-cycle throughput. These numbers are used in combination with
810   // the MispredictPenalty setting from the active SchedMachineModel.
811   CondCycles = 1;
812   TrueCycles = 1;
813   FalseCycles = 1;
814 
815   return true;
816 }
817 
818 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
819                                 MachineBasicBlock::iterator MI,
820                                 const DebugLoc &dl, Register DestReg,
821                                 ArrayRef<MachineOperand> Cond, Register TrueReg,
822                                 Register FalseReg) const {
823   assert(Cond.size() == 2 &&
824          "PPC branch conditions have two components!");
825 
826   // Get the register classes.
827   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
828   const TargetRegisterClass *RC =
829     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
830   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
831 
832   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
833                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
834   assert((Is64Bit ||
835           PPC::GPRCRegClass.hasSubClassEq(RC) ||
836           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
837          "isel is for regular integer GPRs only");
838 
839   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
840   auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
841 
842   unsigned SubIdx = 0;
843   bool SwapOps = false;
844   switch (SelectPred) {
845   case PPC::PRED_EQ:
846   case PPC::PRED_EQ_MINUS:
847   case PPC::PRED_EQ_PLUS:
848       SubIdx = PPC::sub_eq; SwapOps = false; break;
849   case PPC::PRED_NE:
850   case PPC::PRED_NE_MINUS:
851   case PPC::PRED_NE_PLUS:
852       SubIdx = PPC::sub_eq; SwapOps = true; break;
853   case PPC::PRED_LT:
854   case PPC::PRED_LT_MINUS:
855   case PPC::PRED_LT_PLUS:
856       SubIdx = PPC::sub_lt; SwapOps = false; break;
857   case PPC::PRED_GE:
858   case PPC::PRED_GE_MINUS:
859   case PPC::PRED_GE_PLUS:
860       SubIdx = PPC::sub_lt; SwapOps = true; break;
861   case PPC::PRED_GT:
862   case PPC::PRED_GT_MINUS:
863   case PPC::PRED_GT_PLUS:
864       SubIdx = PPC::sub_gt; SwapOps = false; break;
865   case PPC::PRED_LE:
866   case PPC::PRED_LE_MINUS:
867   case PPC::PRED_LE_PLUS:
868       SubIdx = PPC::sub_gt; SwapOps = true; break;
869   case PPC::PRED_UN:
870   case PPC::PRED_UN_MINUS:
871   case PPC::PRED_UN_PLUS:
872       SubIdx = PPC::sub_un; SwapOps = false; break;
873   case PPC::PRED_NU:
874   case PPC::PRED_NU_MINUS:
875   case PPC::PRED_NU_PLUS:
876       SubIdx = PPC::sub_un; SwapOps = true; break;
877   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
878   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
879   }
880 
881   Register FirstReg =  SwapOps ? FalseReg : TrueReg,
882            SecondReg = SwapOps ? TrueReg  : FalseReg;
883 
884   // The first input register of isel cannot be r0. If it is a member
885   // of a register class that can be r0, then copy it first (the
886   // register allocator should eliminate the copy).
887   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
888       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
889     const TargetRegisterClass *FirstRC =
890       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
891         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
892     Register OldFirstReg = FirstReg;
893     FirstReg = MRI.createVirtualRegister(FirstRC);
894     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
895       .addReg(OldFirstReg);
896   }
897 
898   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
899     .addReg(FirstReg).addReg(SecondReg)
900     .addReg(Cond[1].getReg(), 0, SubIdx);
901 }
902 
903 static unsigned getCRBitValue(unsigned CRBit) {
904   unsigned Ret = 4;
905   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
906       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
907       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
908       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
909     Ret = 3;
910   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
911       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
912       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
913       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
914     Ret = 2;
915   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
916       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
917       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
918       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
919     Ret = 1;
920   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
921       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
922       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
923       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
924     Ret = 0;
925 
926   assert(Ret != 4 && "Invalid CR bit register");
927   return Ret;
928 }
929 
930 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
931                                MachineBasicBlock::iterator I,
932                                const DebugLoc &DL, MCRegister DestReg,
933                                MCRegister SrcReg, bool KillSrc) const {
934   // We can end up with self copies and similar things as a result of VSX copy
935   // legalization. Promote them here.
936   const TargetRegisterInfo *TRI = &getRegisterInfo();
937   if (PPC::F8RCRegClass.contains(DestReg) &&
938       PPC::VSRCRegClass.contains(SrcReg)) {
939     MCRegister SuperReg =
940         TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
941 
942     if (VSXSelfCopyCrash && SrcReg == SuperReg)
943       llvm_unreachable("nop VSX copy");
944 
945     DestReg = SuperReg;
946   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
947              PPC::VSRCRegClass.contains(DestReg)) {
948     MCRegister SuperReg =
949         TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
950 
951     if (VSXSelfCopyCrash && DestReg == SuperReg)
952       llvm_unreachable("nop VSX copy");
953 
954     SrcReg = SuperReg;
955   }
956 
957   // Different class register copy
958   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
959       PPC::GPRCRegClass.contains(DestReg)) {
960     MCRegister CRReg = getCRFromCRBit(SrcReg);
961     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
962     getKillRegState(KillSrc);
963     // Rotate the CR bit in the CR fields to be the least significant bit and
964     // then mask with 0x1 (MB = ME = 31).
965     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
966        .addReg(DestReg, RegState::Kill)
967        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
968        .addImm(31)
969        .addImm(31);
970     return;
971   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
972       PPC::G8RCRegClass.contains(DestReg)) {
973     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg);
974     getKillRegState(KillSrc);
975     return;
976   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
977       PPC::GPRCRegClass.contains(DestReg)) {
978     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg);
979     getKillRegState(KillSrc);
980     return;
981   } else if (PPC::G8RCRegClass.contains(SrcReg) &&
982              PPC::VSFRCRegClass.contains(DestReg)) {
983     assert(Subtarget.hasDirectMove() &&
984            "Subtarget doesn't support directmove, don't know how to copy.");
985     BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
986     NumGPRtoVSRSpill++;
987     getKillRegState(KillSrc);
988     return;
989   } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
990              PPC::G8RCRegClass.contains(DestReg)) {
991     assert(Subtarget.hasDirectMove() &&
992            "Subtarget doesn't support directmove, don't know how to copy.");
993     BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
994     getKillRegState(KillSrc);
995     return;
996   } else if (PPC::SPERCRegClass.contains(SrcReg) &&
997              PPC::GPRCRegClass.contains(DestReg)) {
998     BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
999     getKillRegState(KillSrc);
1000     return;
1001   } else if (PPC::GPRCRegClass.contains(SrcReg) &&
1002              PPC::SPERCRegClass.contains(DestReg)) {
1003     BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
1004     getKillRegState(KillSrc);
1005     return;
1006   }
1007 
1008   unsigned Opc;
1009   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
1010     Opc = PPC::OR;
1011   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
1012     Opc = PPC::OR8;
1013   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
1014     Opc = PPC::FMR;
1015   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
1016     Opc = PPC::MCRF;
1017   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
1018     Opc = PPC::VOR;
1019   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
1020     // There are two different ways this can be done:
1021     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1022     //      issue in VSU pipeline 0.
1023     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1024     //      can go to either pipeline.
1025     // We'll always use xxlor here, because in practically all cases where
1026     // copies are generated, they are close enough to some use that the
1027     // lower-latency form is preferable.
1028     Opc = PPC::XXLOR;
1029   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1030            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1031     Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1032   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
1033     Opc = PPC::QVFMR;
1034   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
1035     Opc = PPC::QVFMRs;
1036   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
1037     Opc = PPC::QVFMRb;
1038   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1039     Opc = PPC::CROR;
1040   else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1041     Opc = PPC::EVOR;
1042   else
1043     llvm_unreachable("Impossible reg-to-reg copy");
1044 
1045   const MCInstrDesc &MCID = get(Opc);
1046   if (MCID.getNumOperands() == 3)
1047     BuildMI(MBB, I, DL, MCID, DestReg)
1048       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1049   else
1050     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1051 }
1052 
1053 unsigned PPCInstrInfo::getStoreOpcodeForSpill(unsigned Reg,
1054                                               const TargetRegisterClass *RC)
1055                                               const {
1056   const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1057   int OpcodeIndex = 0;
1058 
1059   if (RC != nullptr) {
1060     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1061         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1062       OpcodeIndex = SOK_Int4Spill;
1063     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1064                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1065       OpcodeIndex = SOK_Int8Spill;
1066     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1067       OpcodeIndex = SOK_Float8Spill;
1068     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1069       OpcodeIndex = SOK_Float4Spill;
1070     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1071       OpcodeIndex = SOK_SPESpill;
1072     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1073       OpcodeIndex = SOK_CRSpill;
1074     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1075       OpcodeIndex = SOK_CRBitSpill;
1076     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1077       OpcodeIndex = SOK_VRVectorSpill;
1078     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1079       OpcodeIndex = SOK_VSXVectorSpill;
1080     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1081       OpcodeIndex = SOK_VectorFloat8Spill;
1082     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1083       OpcodeIndex = SOK_VectorFloat4Spill;
1084     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1085       OpcodeIndex = SOK_VRSaveSpill;
1086     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1087       OpcodeIndex = SOK_QuadFloat8Spill;
1088     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1089       OpcodeIndex = SOK_QuadFloat4Spill;
1090     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1091       OpcodeIndex = SOK_QuadBitSpill;
1092     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1093       OpcodeIndex = SOK_SpillToVSR;
1094     } else {
1095       llvm_unreachable("Unknown regclass!");
1096     }
1097   } else {
1098     if (PPC::GPRCRegClass.contains(Reg) ||
1099         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1100       OpcodeIndex = SOK_Int4Spill;
1101     } else if (PPC::G8RCRegClass.contains(Reg) ||
1102                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1103       OpcodeIndex = SOK_Int8Spill;
1104     } else if (PPC::F8RCRegClass.contains(Reg)) {
1105       OpcodeIndex = SOK_Float8Spill;
1106     } else if (PPC::F4RCRegClass.contains(Reg)) {
1107       OpcodeIndex = SOK_Float4Spill;
1108     } else if (PPC::SPERCRegClass.contains(Reg)) {
1109       OpcodeIndex = SOK_SPESpill;
1110     } else if (PPC::CRRCRegClass.contains(Reg)) {
1111       OpcodeIndex = SOK_CRSpill;
1112     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1113       OpcodeIndex = SOK_CRBitSpill;
1114     } else if (PPC::VRRCRegClass.contains(Reg)) {
1115       OpcodeIndex = SOK_VRVectorSpill;
1116     } else if (PPC::VSRCRegClass.contains(Reg)) {
1117       OpcodeIndex = SOK_VSXVectorSpill;
1118     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1119       OpcodeIndex = SOK_VectorFloat8Spill;
1120     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1121       OpcodeIndex = SOK_VectorFloat4Spill;
1122     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1123       OpcodeIndex = SOK_VRSaveSpill;
1124     } else if (PPC::QFRCRegClass.contains(Reg)) {
1125       OpcodeIndex = SOK_QuadFloat8Spill;
1126     } else if (PPC::QSRCRegClass.contains(Reg)) {
1127       OpcodeIndex = SOK_QuadFloat4Spill;
1128     } else if (PPC::QBRCRegClass.contains(Reg)) {
1129       OpcodeIndex = SOK_QuadBitSpill;
1130     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1131       OpcodeIndex = SOK_SpillToVSR;
1132     } else {
1133       llvm_unreachable("Unknown regclass!");
1134     }
1135   }
1136   return OpcodesForSpill[OpcodeIndex];
1137 }
1138 
1139 unsigned
1140 PPCInstrInfo::getLoadOpcodeForSpill(unsigned Reg,
1141                                     const TargetRegisterClass *RC) const {
1142   const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1143   int OpcodeIndex = 0;
1144 
1145   if (RC != nullptr) {
1146     if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1147         PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1148       OpcodeIndex = SOK_Int4Spill;
1149     } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1150                PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1151       OpcodeIndex = SOK_Int8Spill;
1152     } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1153       OpcodeIndex = SOK_Float8Spill;
1154     } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1155       OpcodeIndex = SOK_Float4Spill;
1156     } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1157       OpcodeIndex = SOK_SPESpill;
1158     } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1159       OpcodeIndex = SOK_CRSpill;
1160     } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1161       OpcodeIndex = SOK_CRBitSpill;
1162     } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1163       OpcodeIndex = SOK_VRVectorSpill;
1164     } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1165       OpcodeIndex = SOK_VSXVectorSpill;
1166     } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1167       OpcodeIndex = SOK_VectorFloat8Spill;
1168     } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1169       OpcodeIndex = SOK_VectorFloat4Spill;
1170     } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1171       OpcodeIndex = SOK_VRSaveSpill;
1172     } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1173       OpcodeIndex = SOK_QuadFloat8Spill;
1174     } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1175       OpcodeIndex = SOK_QuadFloat4Spill;
1176     } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1177       OpcodeIndex = SOK_QuadBitSpill;
1178     } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1179       OpcodeIndex = SOK_SpillToVSR;
1180     } else {
1181       llvm_unreachable("Unknown regclass!");
1182     }
1183   } else {
1184     if (PPC::GPRCRegClass.contains(Reg) ||
1185         PPC::GPRC_NOR0RegClass.contains(Reg)) {
1186       OpcodeIndex = SOK_Int4Spill;
1187     } else if (PPC::G8RCRegClass.contains(Reg) ||
1188                PPC::G8RC_NOX0RegClass.contains(Reg)) {
1189       OpcodeIndex = SOK_Int8Spill;
1190     } else if (PPC::F8RCRegClass.contains(Reg)) {
1191       OpcodeIndex = SOK_Float8Spill;
1192     } else if (PPC::F4RCRegClass.contains(Reg)) {
1193       OpcodeIndex = SOK_Float4Spill;
1194     } else if (PPC::SPERCRegClass.contains(Reg)) {
1195       OpcodeIndex = SOK_SPESpill;
1196     } else if (PPC::CRRCRegClass.contains(Reg)) {
1197       OpcodeIndex = SOK_CRSpill;
1198     } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1199       OpcodeIndex = SOK_CRBitSpill;
1200     } else if (PPC::VRRCRegClass.contains(Reg)) {
1201       OpcodeIndex = SOK_VRVectorSpill;
1202     } else if (PPC::VSRCRegClass.contains(Reg)) {
1203       OpcodeIndex = SOK_VSXVectorSpill;
1204     } else if (PPC::VSFRCRegClass.contains(Reg)) {
1205       OpcodeIndex = SOK_VectorFloat8Spill;
1206     } else if (PPC::VSSRCRegClass.contains(Reg)) {
1207       OpcodeIndex = SOK_VectorFloat4Spill;
1208     } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1209       OpcodeIndex = SOK_VRSaveSpill;
1210     } else if (PPC::QFRCRegClass.contains(Reg)) {
1211       OpcodeIndex = SOK_QuadFloat8Spill;
1212     } else if (PPC::QSRCRegClass.contains(Reg)) {
1213       OpcodeIndex = SOK_QuadFloat4Spill;
1214     } else if (PPC::QBRCRegClass.contains(Reg)) {
1215       OpcodeIndex = SOK_QuadBitSpill;
1216     } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1217       OpcodeIndex = SOK_SpillToVSR;
1218     } else {
1219       llvm_unreachable("Unknown regclass!");
1220     }
1221   }
1222   return OpcodesForSpill[OpcodeIndex];
1223 }
1224 
1225 void PPCInstrInfo::StoreRegToStackSlot(
1226     MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1227     const TargetRegisterClass *RC,
1228     SmallVectorImpl<MachineInstr *> &NewMIs) const {
1229   unsigned Opcode = getStoreOpcodeForSpill(PPC::NoRegister, RC);
1230   DebugLoc DL;
1231 
1232   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1233   FuncInfo->setHasSpills();
1234 
1235   NewMIs.push_back(addFrameReference(
1236       BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1237       FrameIdx));
1238 
1239   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1240       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1241     FuncInfo->setSpillsCR();
1242 
1243   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1244     FuncInfo->setSpillsVRSAVE();
1245 
1246   if (isXFormMemOp(Opcode))
1247     FuncInfo->setHasNonRISpills();
1248 }
1249 
1250 void PPCInstrInfo::storeRegToStackSlotNoUpd(
1251     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
1252     bool isKill, int FrameIdx, const TargetRegisterClass *RC,
1253     const TargetRegisterInfo *TRI) const {
1254   MachineFunction &MF = *MBB.getParent();
1255   SmallVector<MachineInstr *, 4> NewMIs;
1256 
1257   StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1258 
1259   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1260     MBB.insert(MI, NewMIs[i]);
1261 
1262   const MachineFrameInfo &MFI = MF.getFrameInfo();
1263   MachineMemOperand *MMO = MF.getMachineMemOperand(
1264       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1265       MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1266       MFI.getObjectAlign(FrameIdx));
1267   NewMIs.back()->addMemOperand(MF, MMO);
1268 }
1269 
1270 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1271                                        MachineBasicBlock::iterator MI,
1272                                        Register SrcReg, bool isKill,
1273                                        int FrameIdx,
1274                                        const TargetRegisterClass *RC,
1275                                        const TargetRegisterInfo *TRI) const {
1276   // We need to avoid a situation in which the value from a VRRC register is
1277   // spilled using an Altivec instruction and reloaded into a VSRC register
1278   // using a VSX instruction. The issue with this is that the VSX
1279   // load/store instructions swap the doublewords in the vector and the Altivec
1280   // ones don't. The register classes on the spill/reload may be different if
1281   // the register is defined using an Altivec instruction and is then used by a
1282   // VSX instruction.
1283   RC = updatedRC(RC);
1284   storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI);
1285 }
1286 
1287 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1288                                         unsigned DestReg, int FrameIdx,
1289                                         const TargetRegisterClass *RC,
1290                                         SmallVectorImpl<MachineInstr *> &NewMIs)
1291                                         const {
1292   unsigned Opcode = getLoadOpcodeForSpill(PPC::NoRegister, RC);
1293   NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1294                                      FrameIdx));
1295   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1296 
1297   if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1298       PPC::CRBITRCRegClass.hasSubClassEq(RC))
1299     FuncInfo->setSpillsCR();
1300 
1301   if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1302     FuncInfo->setSpillsVRSAVE();
1303 
1304   if (isXFormMemOp(Opcode))
1305     FuncInfo->setHasNonRISpills();
1306 }
1307 
1308 void PPCInstrInfo::loadRegFromStackSlotNoUpd(
1309     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
1310     int FrameIdx, const TargetRegisterClass *RC,
1311     const TargetRegisterInfo *TRI) const {
1312   MachineFunction &MF = *MBB.getParent();
1313   SmallVector<MachineInstr*, 4> NewMIs;
1314   DebugLoc DL;
1315   if (MI != MBB.end()) DL = MI->getDebugLoc();
1316 
1317   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1318   FuncInfo->setHasSpills();
1319 
1320   LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1321 
1322   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1323     MBB.insert(MI, NewMIs[i]);
1324 
1325   const MachineFrameInfo &MFI = MF.getFrameInfo();
1326   MachineMemOperand *MMO = MF.getMachineMemOperand(
1327       MachinePointerInfo::getFixedStack(MF, FrameIdx),
1328       MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1329       MFI.getObjectAlign(FrameIdx));
1330   NewMIs.back()->addMemOperand(MF, MMO);
1331 }
1332 
1333 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1334                                         MachineBasicBlock::iterator MI,
1335                                         Register DestReg, int FrameIdx,
1336                                         const TargetRegisterClass *RC,
1337                                         const TargetRegisterInfo *TRI) const {
1338   // We need to avoid a situation in which the value from a VRRC register is
1339   // spilled using an Altivec instruction and reloaded into a VSRC register
1340   // using a VSX instruction. The issue with this is that the VSX
1341   // load/store instructions swap the doublewords in the vector and the Altivec
1342   // ones don't. The register classes on the spill/reload may be different if
1343   // the register is defined using an Altivec instruction and is then used by a
1344   // VSX instruction.
1345   RC = updatedRC(RC);
1346 
1347   loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI);
1348 }
1349 
1350 bool PPCInstrInfo::
1351 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1352   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1353   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1354     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1355   else
1356     // Leave the CR# the same, but invert the condition.
1357     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1358   return false;
1359 }
1360 
1361 // For some instructions, it is legal to fold ZERO into the RA register field.
1362 // This function performs that fold by replacing the operand with PPC::ZERO,
1363 // it does not consider whether the load immediate zero is no longer in use.
1364 bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1365                                      Register Reg) const {
1366   // A zero immediate should always be loaded with a single li.
1367   unsigned DefOpc = DefMI.getOpcode();
1368   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1369     return false;
1370   if (!DefMI.getOperand(1).isImm())
1371     return false;
1372   if (DefMI.getOperand(1).getImm() != 0)
1373     return false;
1374 
1375   // Note that we cannot here invert the arguments of an isel in order to fold
1376   // a ZERO into what is presented as the second argument. All we have here
1377   // is the condition bit, and that might come from a CR-logical bit operation.
1378 
1379   const MCInstrDesc &UseMCID = UseMI.getDesc();
1380 
1381   // Only fold into real machine instructions.
1382   if (UseMCID.isPseudo())
1383     return false;
1384 
1385   // We need to find which of the User's operands is to be folded, that will be
1386   // the operand that matches the given register ID.
1387   unsigned UseIdx;
1388   for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1389     if (UseMI.getOperand(UseIdx).isReg() &&
1390         UseMI.getOperand(UseIdx).getReg() == Reg)
1391       break;
1392 
1393   assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1394   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1395 
1396   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1397 
1398   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1399   // register (which might also be specified as a pointer class kind).
1400   if (UseInfo->isLookupPtrRegClass()) {
1401     if (UseInfo->RegClass /* Kind */ != 1)
1402       return false;
1403   } else {
1404     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1405         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1406       return false;
1407   }
1408 
1409   // Make sure this is not tied to an output register (or otherwise
1410   // constrained). This is true for ST?UX registers, for example, which
1411   // are tied to their output registers.
1412   if (UseInfo->Constraints != 0)
1413     return false;
1414 
1415   MCRegister ZeroReg;
1416   if (UseInfo->isLookupPtrRegClass()) {
1417     bool isPPC64 = Subtarget.isPPC64();
1418     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1419   } else {
1420     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1421               PPC::ZERO8 : PPC::ZERO;
1422   }
1423 
1424   UseMI.getOperand(UseIdx).setReg(ZeroReg);
1425   return true;
1426 }
1427 
1428 // Folds zero into instructions which have a load immediate zero as an operand
1429 // but also recognize zero as immediate zero. If the definition of the load
1430 // has no more users it is deleted.
1431 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1432                                  Register Reg, MachineRegisterInfo *MRI) const {
1433   bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
1434   if (MRI->use_nodbg_empty(Reg))
1435     DefMI.eraseFromParent();
1436   return Changed;
1437 }
1438 
1439 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1440   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1441        I != IE; ++I)
1442     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1443       return true;
1444   return false;
1445 }
1446 
1447 // We should make sure that, if we're going to predicate both sides of a
1448 // condition (a diamond), that both sides don't define the counter register. We
1449 // can predicate counter-decrement-based branches, but while that predicates
1450 // the branching, it does not predicate the counter decrement. If we tried to
1451 // merge the triangle into one predicated block, we'd decrement the counter
1452 // twice.
1453 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1454                      unsigned NumT, unsigned ExtraT,
1455                      MachineBasicBlock &FMBB,
1456                      unsigned NumF, unsigned ExtraF,
1457                      BranchProbability Probability) const {
1458   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1459 }
1460 
1461 
1462 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1463   // The predicated branches are identified by their type, not really by the
1464   // explicit presence of a predicate. Furthermore, some of them can be
1465   // predicated more than once. Because if conversion won't try to predicate
1466   // any instruction which already claims to be predicated (by returning true
1467   // here), always return false. In doing so, we let isPredicable() be the
1468   // final word on whether not the instruction can be (further) predicated.
1469 
1470   return false;
1471 }
1472 
1473 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1474                                         ArrayRef<MachineOperand> Pred) const {
1475   unsigned OpC = MI.getOpcode();
1476   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1477     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1478       bool isPPC64 = Subtarget.isPPC64();
1479       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1480                                       : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1481     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1482       MI.setDesc(get(PPC::BCLR));
1483       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1484     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1485       MI.setDesc(get(PPC::BCLRn));
1486       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1487     } else {
1488       MI.setDesc(get(PPC::BCCLR));
1489       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1490           .addImm(Pred[0].getImm())
1491           .add(Pred[1]);
1492     }
1493 
1494     return true;
1495   } else if (OpC == PPC::B) {
1496     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1497       bool isPPC64 = Subtarget.isPPC64();
1498       MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1499                                       : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1500     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1501       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1502       MI.RemoveOperand(0);
1503 
1504       MI.setDesc(get(PPC::BC));
1505       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1506           .add(Pred[1])
1507           .addMBB(MBB);
1508     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1509       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1510       MI.RemoveOperand(0);
1511 
1512       MI.setDesc(get(PPC::BCn));
1513       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1514           .add(Pred[1])
1515           .addMBB(MBB);
1516     } else {
1517       MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1518       MI.RemoveOperand(0);
1519 
1520       MI.setDesc(get(PPC::BCC));
1521       MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1522           .addImm(Pred[0].getImm())
1523           .add(Pred[1])
1524           .addMBB(MBB);
1525     }
1526 
1527     return true;
1528   } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
1529              OpC == PPC::BCTRL8) {
1530     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1531       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1532 
1533     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1534     bool isPPC64 = Subtarget.isPPC64();
1535 
1536     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1537       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1538                              : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1539       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1540       return true;
1541     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1542       MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1543                              : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1544       MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1545       return true;
1546     }
1547 
1548     MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1549                            : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1550     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1551         .addImm(Pred[0].getImm())
1552         .add(Pred[1]);
1553     return true;
1554   }
1555 
1556   return false;
1557 }
1558 
1559 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1560                                      ArrayRef<MachineOperand> Pred2) const {
1561   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1562   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1563 
1564   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1565     return false;
1566   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1567     return false;
1568 
1569   // P1 can only subsume P2 if they test the same condition register.
1570   if (Pred1[1].getReg() != Pred2[1].getReg())
1571     return false;
1572 
1573   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1574   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1575 
1576   if (P1 == P2)
1577     return true;
1578 
1579   // Does P1 subsume P2, e.g. GE subsumes GT.
1580   if (P1 == PPC::PRED_LE &&
1581       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1582     return true;
1583   if (P1 == PPC::PRED_GE &&
1584       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1585     return true;
1586 
1587   return false;
1588 }
1589 
1590 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1591                                     std::vector<MachineOperand> &Pred) const {
1592   // Note: At the present time, the contents of Pred from this function is
1593   // unused by IfConversion. This implementation follows ARM by pushing the
1594   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1595   // predicate, instructions defining CTR or CTR8 are also included as
1596   // predicate-defining instructions.
1597 
1598   const TargetRegisterClass *RCs[] =
1599     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1600       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1601 
1602   bool Found = false;
1603   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1604     const MachineOperand &MO = MI.getOperand(i);
1605     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1606       const TargetRegisterClass *RC = RCs[c];
1607       if (MO.isReg()) {
1608         if (MO.isDef() && RC->contains(MO.getReg())) {
1609           Pred.push_back(MO);
1610           Found = true;
1611         }
1612       } else if (MO.isRegMask()) {
1613         for (TargetRegisterClass::iterator I = RC->begin(),
1614              IE = RC->end(); I != IE; ++I)
1615           if (MO.clobbersPhysReg(*I)) {
1616             Pred.push_back(MO);
1617             Found = true;
1618           }
1619       }
1620     }
1621   }
1622 
1623   return Found;
1624 }
1625 
1626 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1627                                   Register &SrcReg2, int &Mask,
1628                                   int &Value) const {
1629   unsigned Opc = MI.getOpcode();
1630 
1631   switch (Opc) {
1632   default: return false;
1633   case PPC::CMPWI:
1634   case PPC::CMPLWI:
1635   case PPC::CMPDI:
1636   case PPC::CMPLDI:
1637     SrcReg = MI.getOperand(1).getReg();
1638     SrcReg2 = 0;
1639     Value = MI.getOperand(2).getImm();
1640     Mask = 0xFFFF;
1641     return true;
1642   case PPC::CMPW:
1643   case PPC::CMPLW:
1644   case PPC::CMPD:
1645   case PPC::CMPLD:
1646   case PPC::FCMPUS:
1647   case PPC::FCMPUD:
1648     SrcReg = MI.getOperand(1).getReg();
1649     SrcReg2 = MI.getOperand(2).getReg();
1650     Value = 0;
1651     Mask = 0;
1652     return true;
1653   }
1654 }
1655 
1656 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1657                                         Register SrcReg2, int Mask, int Value,
1658                                         const MachineRegisterInfo *MRI) const {
1659   if (DisableCmpOpt)
1660     return false;
1661 
1662   int OpC = CmpInstr.getOpcode();
1663   Register CRReg = CmpInstr.getOperand(0).getReg();
1664 
1665   // FP record forms set CR1 based on the exception status bits, not a
1666   // comparison with zero.
1667   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1668     return false;
1669 
1670   const TargetRegisterInfo *TRI = &getRegisterInfo();
1671   // The record forms set the condition register based on a signed comparison
1672   // with zero (so says the ISA manual). This is not as straightforward as it
1673   // seems, however, because this is always a 64-bit comparison on PPC64, even
1674   // for instructions that are 32-bit in nature (like slw for example).
1675   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1676   // for equality checks (as those don't depend on the sign). On PPC64,
1677   // we are restricted to equality for unsigned 64-bit comparisons and for
1678   // signed 32-bit comparisons the applicability is more restricted.
1679   bool isPPC64 = Subtarget.isPPC64();
1680   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1681   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1682   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1683 
1684   // Look through copies unless that gets us to a physical register.
1685   Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
1686   if (ActualSrc.isVirtual())
1687     SrcReg = ActualSrc;
1688 
1689   // Get the unique definition of SrcReg.
1690   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1691   if (!MI) return false;
1692 
1693   bool equalityOnly = false;
1694   bool noSub = false;
1695   if (isPPC64) {
1696     if (is32BitSignedCompare) {
1697       // We can perform this optimization only if MI is sign-extending.
1698       if (isSignExtended(*MI))
1699         noSub = true;
1700       else
1701         return false;
1702     } else if (is32BitUnsignedCompare) {
1703       // We can perform this optimization, equality only, if MI is
1704       // zero-extending.
1705       if (isZeroExtended(*MI)) {
1706         noSub = true;
1707         equalityOnly = true;
1708       } else
1709         return false;
1710     } else
1711       equalityOnly = is64BitUnsignedCompare;
1712   } else
1713     equalityOnly = is32BitUnsignedCompare;
1714 
1715   if (equalityOnly) {
1716     // We need to check the uses of the condition register in order to reject
1717     // non-equality comparisons.
1718     for (MachineRegisterInfo::use_instr_iterator
1719          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1720          I != IE; ++I) {
1721       MachineInstr *UseMI = &*I;
1722       if (UseMI->getOpcode() == PPC::BCC) {
1723         PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1724         unsigned PredCond = PPC::getPredicateCondition(Pred);
1725         // We ignore hint bits when checking for non-equality comparisons.
1726         if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1727           return false;
1728       } else if (UseMI->getOpcode() == PPC::ISEL ||
1729                  UseMI->getOpcode() == PPC::ISEL8) {
1730         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1731         if (SubIdx != PPC::sub_eq)
1732           return false;
1733       } else
1734         return false;
1735     }
1736   }
1737 
1738   MachineBasicBlock::iterator I = CmpInstr;
1739 
1740   // Scan forward to find the first use of the compare.
1741   for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1742        ++I) {
1743     bool FoundUse = false;
1744     for (MachineRegisterInfo::use_instr_iterator
1745          J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1746          J != JE; ++J)
1747       if (&*J == &*I) {
1748         FoundUse = true;
1749         break;
1750       }
1751 
1752     if (FoundUse)
1753       break;
1754   }
1755 
1756   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1757   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1758 
1759   // There are two possible candidates which can be changed to set CR[01].
1760   // One is MI, the other is a SUB instruction.
1761   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1762   MachineInstr *Sub = nullptr;
1763   if (SrcReg2 != 0)
1764     // MI is not a candidate for CMPrr.
1765     MI = nullptr;
1766   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1767   // same BB as the comparison. This is to allow the check below to avoid calls
1768   // (and other explicit clobbers); instead we should really check for these
1769   // more explicitly (in at least a few predecessors).
1770   else if (MI->getParent() != CmpInstr.getParent())
1771     return false;
1772   else if (Value != 0) {
1773     // The record-form instructions set CR bit based on signed comparison
1774     // against 0. We try to convert a compare against 1 or -1 into a compare
1775     // against 0 to exploit record-form instructions. For example, we change
1776     // the condition "greater than -1" into "greater than or equal to 0"
1777     // and "less than 1" into "less than or equal to 0".
1778 
1779     // Since we optimize comparison based on a specific branch condition,
1780     // we don't optimize if condition code is used by more than once.
1781     if (equalityOnly || !MRI->hasOneUse(CRReg))
1782       return false;
1783 
1784     MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1785     if (UseMI->getOpcode() != PPC::BCC)
1786       return false;
1787 
1788     PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1789     unsigned PredCond = PPC::getPredicateCondition(Pred);
1790     unsigned PredHint = PPC::getPredicateHint(Pred);
1791     int16_t Immed = (int16_t)Value;
1792 
1793     // When modifying the condition in the predicate, we propagate hint bits
1794     // from the original predicate to the new one.
1795     if (Immed == -1 && PredCond == PPC::PRED_GT)
1796       // We convert "greater than -1" into "greater than or equal to 0",
1797       // since we are assuming signed comparison by !equalityOnly
1798       Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
1799     else if (Immed == -1 && PredCond == PPC::PRED_LE)
1800       // We convert "less than or equal to -1" into "less than 0".
1801       Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
1802     else if (Immed == 1 && PredCond == PPC::PRED_LT)
1803       // We convert "less than 1" into "less than or equal to 0".
1804       Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
1805     else if (Immed == 1 && PredCond == PPC::PRED_GE)
1806       // We convert "greater than or equal to 1" into "greater than 0".
1807       Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
1808     else
1809       return false;
1810 
1811     PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
1812   }
1813 
1814   // Search for Sub.
1815   --I;
1816 
1817   // Get ready to iterate backward from CmpInstr.
1818   MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1819 
1820   for (; I != E && !noSub; --I) {
1821     const MachineInstr &Instr = *I;
1822     unsigned IOpC = Instr.getOpcode();
1823 
1824     if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1825                              Instr.readsRegister(PPC::CR0, TRI)))
1826       // This instruction modifies or uses the record condition register after
1827       // the one we want to change. While we could do this transformation, it
1828       // would likely not be profitable. This transformation removes one
1829       // instruction, and so even forcing RA to generate one move probably
1830       // makes it unprofitable.
1831       return false;
1832 
1833     // Check whether CmpInstr can be made redundant by the current instruction.
1834     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1835          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1836         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1837         ((Instr.getOperand(1).getReg() == SrcReg &&
1838           Instr.getOperand(2).getReg() == SrcReg2) ||
1839         (Instr.getOperand(1).getReg() == SrcReg2 &&
1840          Instr.getOperand(2).getReg() == SrcReg))) {
1841       Sub = &*I;
1842       break;
1843     }
1844 
1845     if (I == B)
1846       // The 'and' is below the comparison instruction.
1847       return false;
1848   }
1849 
1850   // Return false if no candidates exist.
1851   if (!MI && !Sub)
1852     return false;
1853 
1854   // The single candidate is called MI.
1855   if (!MI) MI = Sub;
1856 
1857   int NewOpC = -1;
1858   int MIOpC = MI->getOpcode();
1859   if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
1860       MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
1861     NewOpC = MIOpC;
1862   else {
1863     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1864     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1865       NewOpC = MIOpC;
1866   }
1867 
1868   // FIXME: On the non-embedded POWER architectures, only some of the record
1869   // forms are fast, and we should use only the fast ones.
1870 
1871   // The defining instruction has a record form (or is already a record
1872   // form). It is possible, however, that we'll need to reverse the condition
1873   // code of the users.
1874   if (NewOpC == -1)
1875     return false;
1876 
1877   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1878   // needs to be updated to be based on SUB.  Push the condition code
1879   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1880   // condition code of these operands will be modified.
1881   // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1882   // comparison against 0, which may modify predicate.
1883   bool ShouldSwap = false;
1884   if (Sub && Value == 0) {
1885     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1886       Sub->getOperand(2).getReg() == SrcReg;
1887 
1888     // The operands to subf are the opposite of sub, so only in the fixed-point
1889     // case, invert the order.
1890     ShouldSwap = !ShouldSwap;
1891   }
1892 
1893   if (ShouldSwap)
1894     for (MachineRegisterInfo::use_instr_iterator
1895          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1896          I != IE; ++I) {
1897       MachineInstr *UseMI = &*I;
1898       if (UseMI->getOpcode() == PPC::BCC) {
1899         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1900         unsigned PredCond = PPC::getPredicateCondition(Pred);
1901         assert((!equalityOnly ||
1902                 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1903                "Invalid predicate for equality-only optimization");
1904         (void)PredCond; // To suppress warning in release build.
1905         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1906                                 PPC::getSwappedPredicate(Pred)));
1907       } else if (UseMI->getOpcode() == PPC::ISEL ||
1908                  UseMI->getOpcode() == PPC::ISEL8) {
1909         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1910         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1911                "Invalid CR bit for equality-only optimization");
1912 
1913         if (NewSubReg == PPC::sub_lt)
1914           NewSubReg = PPC::sub_gt;
1915         else if (NewSubReg == PPC::sub_gt)
1916           NewSubReg = PPC::sub_lt;
1917 
1918         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1919                                                  NewSubReg));
1920       } else // We need to abort on a user we don't understand.
1921         return false;
1922     }
1923   assert(!(Value != 0 && ShouldSwap) &&
1924          "Non-zero immediate support and ShouldSwap"
1925          "may conflict in updating predicate");
1926 
1927   // Create a new virtual register to hold the value of the CR set by the
1928   // record-form instruction. If the instruction was not previously in
1929   // record form, then set the kill flag on the CR.
1930   CmpInstr.eraseFromParent();
1931 
1932   MachineBasicBlock::iterator MII = MI;
1933   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1934           get(TargetOpcode::COPY), CRReg)
1935     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1936 
1937   // Even if CR0 register were dead before, it is alive now since the
1938   // instruction we just built uses it.
1939   MI->clearRegisterDeads(PPC::CR0);
1940 
1941   if (MIOpC != NewOpC) {
1942     // We need to be careful here: we're replacing one instruction with
1943     // another, and we need to make sure that we get all of the right
1944     // implicit uses and defs. On the other hand, the caller may be holding
1945     // an iterator to this instruction, and so we can't delete it (this is
1946     // specifically the case if this is the instruction directly after the
1947     // compare).
1948 
1949     // Rotates are expensive instructions. If we're emitting a record-form
1950     // rotate that can just be an andi/andis, we should just emit that.
1951     if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
1952       Register GPRRes = MI->getOperand(0).getReg();
1953       int64_t SH = MI->getOperand(2).getImm();
1954       int64_t MB = MI->getOperand(3).getImm();
1955       int64_t ME = MI->getOperand(4).getImm();
1956       // We can only do this if both the start and end of the mask are in the
1957       // same halfword.
1958       bool MBInLoHWord = MB >= 16;
1959       bool MEInLoHWord = ME >= 16;
1960       uint64_t Mask = ~0LLU;
1961 
1962       if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
1963         Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
1964         // The mask value needs to shift right 16 if we're emitting andis.
1965         Mask >>= MBInLoHWord ? 0 : 16;
1966         NewOpC = MIOpC == PPC::RLWINM
1967                      ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
1968                      : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
1969       } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
1970                  (ME - MB + 1 == SH) && (MB >= 16)) {
1971         // If we are rotating by the exact number of bits as are in the mask
1972         // and the mask is in the least significant bits of the register,
1973         // that's just an andis. (as long as the GPR result has no uses).
1974         Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
1975         Mask >>= 16;
1976         NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
1977       }
1978       // If we've set the mask, we can transform.
1979       if (Mask != ~0LLU) {
1980         MI->RemoveOperand(4);
1981         MI->RemoveOperand(3);
1982         MI->getOperand(2).setImm(Mask);
1983         NumRcRotatesConvertedToRcAnd++;
1984       }
1985     } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
1986       int64_t MB = MI->getOperand(3).getImm();
1987       if (MB >= 48) {
1988         uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
1989         NewOpC = PPC::ANDI8_rec;
1990         MI->RemoveOperand(3);
1991         MI->getOperand(2).setImm(Mask);
1992         NumRcRotatesConvertedToRcAnd++;
1993       }
1994     }
1995 
1996     const MCInstrDesc &NewDesc = get(NewOpC);
1997     MI->setDesc(NewDesc);
1998 
1999     if (NewDesc.ImplicitDefs)
2000       for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
2001            *ImpDefs; ++ImpDefs)
2002         if (!MI->definesRegister(*ImpDefs))
2003           MI->addOperand(*MI->getParent()->getParent(),
2004                          MachineOperand::CreateReg(*ImpDefs, true, true));
2005     if (NewDesc.ImplicitUses)
2006       for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
2007            *ImpUses; ++ImpUses)
2008         if (!MI->readsRegister(*ImpUses))
2009           MI->addOperand(*MI->getParent()->getParent(),
2010                          MachineOperand::CreateReg(*ImpUses, false, true));
2011   }
2012   assert(MI->definesRegister(PPC::CR0) &&
2013          "Record-form instruction does not define cr0?");
2014 
2015   // Modify the condition code of operands in OperandsToUpdate.
2016   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2017   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2018   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2019     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2020 
2021   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2022     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2023 
2024   return true;
2025 }
2026 
2027 /// GetInstSize - Return the number of bytes of code the specified
2028 /// instruction may be.  This returns the maximum number of bytes.
2029 ///
2030 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2031   unsigned Opcode = MI.getOpcode();
2032 
2033   if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2034     const MachineFunction *MF = MI.getParent()->getParent();
2035     const char *AsmStr = MI.getOperand(0).getSymbolName();
2036     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2037   } else if (Opcode == TargetOpcode::STACKMAP) {
2038     StackMapOpers Opers(&MI);
2039     return Opers.getNumPatchBytes();
2040   } else if (Opcode == TargetOpcode::PATCHPOINT) {
2041     PatchPointOpers Opers(&MI);
2042     return Opers.getNumPatchBytes();
2043   } else {
2044     return get(Opcode).getSize();
2045   }
2046 }
2047 
2048 std::pair<unsigned, unsigned>
2049 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2050   const unsigned Mask = PPCII::MO_ACCESS_MASK;
2051   return std::make_pair(TF & Mask, TF & ~Mask);
2052 }
2053 
2054 ArrayRef<std::pair<unsigned, const char *>>
2055 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2056   using namespace PPCII;
2057   static const std::pair<unsigned, const char *> TargetFlags[] = {
2058       {MO_LO, "ppc-lo"},
2059       {MO_HA, "ppc-ha"},
2060       {MO_TPREL_LO, "ppc-tprel-lo"},
2061       {MO_TPREL_HA, "ppc-tprel-ha"},
2062       {MO_DTPREL_LO, "ppc-dtprel-lo"},
2063       {MO_TLSLD_LO, "ppc-tlsld-lo"},
2064       {MO_TOC_LO, "ppc-toc-lo"},
2065       {MO_TLS, "ppc-tls"}};
2066   return makeArrayRef(TargetFlags);
2067 }
2068 
2069 ArrayRef<std::pair<unsigned, const char *>>
2070 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2071   using namespace PPCII;
2072   static const std::pair<unsigned, const char *> TargetFlags[] = {
2073       {MO_PLT, "ppc-plt"},
2074       {MO_PIC_FLAG, "ppc-pic"},
2075       {MO_PCREL_FLAG, "ppc-pcrel"},
2076       {MO_GOT_FLAG, "ppc-got"}};
2077   return makeArrayRef(TargetFlags);
2078 }
2079 
2080 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2081 // The VSX versions have the advantage of a full 64-register target whereas
2082 // the FP ones have the advantage of lower latency and higher throughput. So
2083 // what we are after is using the faster instructions in low register pressure
2084 // situations and using the larger register file in high register pressure
2085 // situations.
2086 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2087     unsigned UpperOpcode, LowerOpcode;
2088     switch (MI.getOpcode()) {
2089     case PPC::DFLOADf32:
2090       UpperOpcode = PPC::LXSSP;
2091       LowerOpcode = PPC::LFS;
2092       break;
2093     case PPC::DFLOADf64:
2094       UpperOpcode = PPC::LXSD;
2095       LowerOpcode = PPC::LFD;
2096       break;
2097     case PPC::DFSTOREf32:
2098       UpperOpcode = PPC::STXSSP;
2099       LowerOpcode = PPC::STFS;
2100       break;
2101     case PPC::DFSTOREf64:
2102       UpperOpcode = PPC::STXSD;
2103       LowerOpcode = PPC::STFD;
2104       break;
2105     case PPC::XFLOADf32:
2106       UpperOpcode = PPC::LXSSPX;
2107       LowerOpcode = PPC::LFSX;
2108       break;
2109     case PPC::XFLOADf64:
2110       UpperOpcode = PPC::LXSDX;
2111       LowerOpcode = PPC::LFDX;
2112       break;
2113     case PPC::XFSTOREf32:
2114       UpperOpcode = PPC::STXSSPX;
2115       LowerOpcode = PPC::STFSX;
2116       break;
2117     case PPC::XFSTOREf64:
2118       UpperOpcode = PPC::STXSDX;
2119       LowerOpcode = PPC::STFDX;
2120       break;
2121     case PPC::LIWAX:
2122       UpperOpcode = PPC::LXSIWAX;
2123       LowerOpcode = PPC::LFIWAX;
2124       break;
2125     case PPC::LIWZX:
2126       UpperOpcode = PPC::LXSIWZX;
2127       LowerOpcode = PPC::LFIWZX;
2128       break;
2129     case PPC::STIWX:
2130       UpperOpcode = PPC::STXSIWX;
2131       LowerOpcode = PPC::STFIWX;
2132       break;
2133     default:
2134       llvm_unreachable("Unknown Operation!");
2135     }
2136 
2137     Register TargetReg = MI.getOperand(0).getReg();
2138     unsigned Opcode;
2139     if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2140         (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2141       Opcode = LowerOpcode;
2142     else
2143       Opcode = UpperOpcode;
2144     MI.setDesc(get(Opcode));
2145     return true;
2146 }
2147 
2148 static bool isAnImmediateOperand(const MachineOperand &MO) {
2149   return MO.isCPI() || MO.isGlobal() || MO.isImm();
2150 }
2151 
2152 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2153   auto &MBB = *MI.getParent();
2154   auto DL = MI.getDebugLoc();
2155 
2156   switch (MI.getOpcode()) {
2157   case TargetOpcode::LOAD_STACK_GUARD: {
2158     assert(Subtarget.isTargetLinux() &&
2159            "Only Linux target is expected to contain LOAD_STACK_GUARD");
2160     const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2161     const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2162     MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2163     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2164         .addImm(Offset)
2165         .addReg(Reg);
2166     return true;
2167   }
2168   case PPC::DFLOADf32:
2169   case PPC::DFLOADf64:
2170   case PPC::DFSTOREf32:
2171   case PPC::DFSTOREf64: {
2172     assert(Subtarget.hasP9Vector() &&
2173            "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2174     assert(MI.getOperand(2).isReg() &&
2175            isAnImmediateOperand(MI.getOperand(1)) &&
2176            "D-form op must have register and immediate operands");
2177     return expandVSXMemPseudo(MI);
2178   }
2179   case PPC::XFLOADf32:
2180   case PPC::XFSTOREf32:
2181   case PPC::LIWAX:
2182   case PPC::LIWZX:
2183   case PPC::STIWX: {
2184     assert(Subtarget.hasP8Vector() &&
2185            "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2186     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2187            "X-form op must have register and register operands");
2188     return expandVSXMemPseudo(MI);
2189   }
2190   case PPC::XFLOADf64:
2191   case PPC::XFSTOREf64: {
2192     assert(Subtarget.hasVSX() &&
2193            "Invalid X-Form Pseudo-ops on target that has no VSX.");
2194     assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2195            "X-form op must have register and register operands");
2196     return expandVSXMemPseudo(MI);
2197   }
2198   case PPC::SPILLTOVSR_LD: {
2199     Register TargetReg = MI.getOperand(0).getReg();
2200     if (PPC::VSFRCRegClass.contains(TargetReg)) {
2201       MI.setDesc(get(PPC::DFLOADf64));
2202       return expandPostRAPseudo(MI);
2203     }
2204     else
2205       MI.setDesc(get(PPC::LD));
2206     return true;
2207   }
2208   case PPC::SPILLTOVSR_ST: {
2209     Register SrcReg = MI.getOperand(0).getReg();
2210     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2211       NumStoreSPILLVSRRCAsVec++;
2212       MI.setDesc(get(PPC::DFSTOREf64));
2213       return expandPostRAPseudo(MI);
2214     } else {
2215       NumStoreSPILLVSRRCAsGpr++;
2216       MI.setDesc(get(PPC::STD));
2217     }
2218     return true;
2219   }
2220   case PPC::SPILLTOVSR_LDX: {
2221     Register TargetReg = MI.getOperand(0).getReg();
2222     if (PPC::VSFRCRegClass.contains(TargetReg))
2223       MI.setDesc(get(PPC::LXSDX));
2224     else
2225       MI.setDesc(get(PPC::LDX));
2226     return true;
2227   }
2228   case PPC::SPILLTOVSR_STX: {
2229     Register SrcReg = MI.getOperand(0).getReg();
2230     if (PPC::VSFRCRegClass.contains(SrcReg)) {
2231       NumStoreSPILLVSRRCAsVec++;
2232       MI.setDesc(get(PPC::STXSDX));
2233     } else {
2234       NumStoreSPILLVSRRCAsGpr++;
2235       MI.setDesc(get(PPC::STDX));
2236     }
2237     return true;
2238   }
2239 
2240   case PPC::CFENCE8: {
2241     auto Val = MI.getOperand(0).getReg();
2242     BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2243     BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2244         .addImm(PPC::PRED_NE_MINUS)
2245         .addReg(PPC::CR7)
2246         .addImm(1);
2247     MI.setDesc(get(PPC::ISYNC));
2248     MI.RemoveOperand(0);
2249     return true;
2250   }
2251   }
2252   return false;
2253 }
2254 
2255 // Essentially a compile-time implementation of a compare->isel sequence.
2256 // It takes two constants to compare, along with the true/false registers
2257 // and the comparison type (as a subreg to a CR field) and returns one
2258 // of the true/false registers, depending on the comparison results.
2259 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2260                           unsigned TrueReg, unsigned FalseReg,
2261                           unsigned CRSubReg) {
2262   // Signed comparisons. The immediates are assumed to be sign-extended.
2263   if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2264     switch (CRSubReg) {
2265     default: llvm_unreachable("Unknown integer comparison type.");
2266     case PPC::sub_lt:
2267       return Imm1 < Imm2 ? TrueReg : FalseReg;
2268     case PPC::sub_gt:
2269       return Imm1 > Imm2 ? TrueReg : FalseReg;
2270     case PPC::sub_eq:
2271       return Imm1 == Imm2 ? TrueReg : FalseReg;
2272     }
2273   }
2274   // Unsigned comparisons.
2275   else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2276     switch (CRSubReg) {
2277     default: llvm_unreachable("Unknown integer comparison type.");
2278     case PPC::sub_lt:
2279       return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2280     case PPC::sub_gt:
2281       return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2282     case PPC::sub_eq:
2283       return Imm1 == Imm2 ? TrueReg : FalseReg;
2284     }
2285   }
2286   return PPC::NoRegister;
2287 }
2288 
2289 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2290                                               unsigned OpNo,
2291                                               int64_t Imm) const {
2292   assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2293   // Replace the REG with the Immediate.
2294   Register InUseReg = MI.getOperand(OpNo).getReg();
2295   MI.getOperand(OpNo).ChangeToImmediate(Imm);
2296 
2297   if (MI.implicit_operands().empty())
2298     return;
2299 
2300   // We need to make sure that the MI didn't have any implicit use
2301   // of this REG any more.
2302   const TargetRegisterInfo *TRI = &getRegisterInfo();
2303   int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2304   if (UseOpIdx >= 0) {
2305     MachineOperand &MO = MI.getOperand(UseOpIdx);
2306     if (MO.isImplicit())
2307       // The operands must always be in the following order:
2308       // - explicit reg defs,
2309       // - other explicit operands (reg uses, immediates, etc.),
2310       // - implicit reg defs
2311       // - implicit reg uses
2312       // Therefore, removing the implicit operand won't change the explicit
2313       // operands layout.
2314       MI.RemoveOperand(UseOpIdx);
2315   }
2316 }
2317 
2318 // Replace an instruction with one that materializes a constant (and sets
2319 // CR0 if the original instruction was a record-form instruction).
2320 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2321                                       const LoadImmediateInfo &LII) const {
2322   // Remove existing operands.
2323   int OperandToKeep = LII.SetCR ? 1 : 0;
2324   for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2325     MI.RemoveOperand(i);
2326 
2327   // Replace the instruction.
2328   if (LII.SetCR) {
2329     MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
2330     // Set the immediate.
2331     MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2332         .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2333     return;
2334   }
2335   else
2336     MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2337 
2338   // Set the immediate.
2339   MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2340       .addImm(LII.Imm);
2341 }
2342 
2343 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2344                                            bool &SeenIntermediateUse) const {
2345   assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2346          "Should be called after register allocation.");
2347   const TargetRegisterInfo *TRI = &getRegisterInfo();
2348   MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2349   It++;
2350   SeenIntermediateUse = false;
2351   for (; It != E; ++It) {
2352     if (It->modifiesRegister(Reg, TRI))
2353       return &*It;
2354     if (It->readsRegister(Reg, TRI))
2355       SeenIntermediateUse = true;
2356   }
2357   return nullptr;
2358 }
2359 
2360 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2361   MachineInstr &MI,
2362   unsigned &OpNoForForwarding,
2363   bool &SeenIntermediateUse) const {
2364   OpNoForForwarding = ~0U;
2365   MachineInstr *DefMI = nullptr;
2366   MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2367   const TargetRegisterInfo *TRI = &getRegisterInfo();
2368   // If we're in SSA, get the defs through the MRI. Otherwise, only look
2369   // within the basic block to see if the register is defined using an LI/LI8.
2370   if (MRI->isSSA()) {
2371     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2372       if (!MI.getOperand(i).isReg())
2373         continue;
2374       Register Reg = MI.getOperand(i).getReg();
2375       if (!Register::isVirtualRegister(Reg))
2376         continue;
2377       unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2378       if (Register::isVirtualRegister(TrueReg)) {
2379         DefMI = MRI->getVRegDef(TrueReg);
2380         if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) {
2381           OpNoForForwarding = i;
2382           break;
2383         }
2384       }
2385     }
2386   } else {
2387     // Looking back through the definition for each operand could be expensive,
2388     // so exit early if this isn't an instruction that either has an immediate
2389     // form or is already an immediate form that we can handle.
2390     ImmInstrInfo III;
2391     unsigned Opc = MI.getOpcode();
2392     bool ConvertibleImmForm =
2393         Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
2394         Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2395         Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
2396         Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
2397         Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2398         Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
2399         Opc == PPC::RLWINM8_rec;
2400     bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2401                        ? isVFRegister(MI.getOperand(0).getReg())
2402                        : false;
2403     if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2404       return nullptr;
2405 
2406     // Don't convert or %X, %Y, %Y since that's just a register move.
2407     if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2408         MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2409       return nullptr;
2410     for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2411       MachineOperand &MO = MI.getOperand(i);
2412       SeenIntermediateUse = false;
2413       if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2414         Register Reg = MI.getOperand(i).getReg();
2415         // If we see another use of this reg between the def and the MI,
2416         // we want to flat it so the def isn't deleted.
2417         MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2418         if (DefMI) {
2419           // Is this register defined by some form of add-immediate (including
2420           // load-immediate) within this basic block?
2421           switch (DefMI->getOpcode()) {
2422           default:
2423             break;
2424           case PPC::LI:
2425           case PPC::LI8:
2426           case PPC::ADDItocL:
2427           case PPC::ADDI:
2428           case PPC::ADDI8:
2429             OpNoForForwarding = i;
2430             return DefMI;
2431           }
2432         }
2433       }
2434     }
2435   }
2436   return OpNoForForwarding == ~0U ? nullptr : DefMI;
2437 }
2438 
2439 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2440   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2441       // Power 8
2442       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2443        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,
2444        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2445        PPC::SPILLTOVSR_ST, PPC::EVSTDD},
2446       // Power 9
2447       {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2448        PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,
2449        PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2450        PPC::SPILLTOVSR_ST}};
2451 
2452   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2453 }
2454 
2455 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2456   static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2457       // Power 8
2458       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2459        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,
2460        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2461        PPC::SPILLTOVSR_LD, PPC::EVLDD},
2462       // Power 9
2463       {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2464        PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32,
2465        PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2466        PPC::SPILLTOVSR_LD}};
2467 
2468   return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2469 }
2470 
2471 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI,
2472                                      unsigned RegNo) const {
2473   const MachineRegisterInfo &MRI =
2474       StartMI.getParent()->getParent()->getRegInfo();
2475   if (MRI.isSSA())
2476     return;
2477 
2478   // Instructions between [StartMI, EndMI] should be in same basic block.
2479   assert((StartMI.getParent() == EndMI.getParent()) &&
2480          "Instructions are not in same basic block");
2481 
2482   bool IsKillSet = false;
2483 
2484   auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2485     MachineOperand &MO = MI.getOperand(Index);
2486     if (MO.isReg() && MO.isUse() && MO.isKill() &&
2487         getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2488       MO.setIsKill(false);
2489   };
2490 
2491   // Set killed flag for EndMI.
2492   // No need to do anything if EndMI defines RegNo.
2493   int UseIndex =
2494       EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2495   if (UseIndex != -1) {
2496     EndMI.getOperand(UseIndex).setIsKill(true);
2497     IsKillSet = true;
2498     // Clear killed flag for other EndMI operands related to RegNo. In some
2499     // upexpected cases, killed may be set multiple times for same register
2500     // operand in same MI.
2501     for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i)
2502       if (i != UseIndex)
2503         clearOperandKillInfo(EndMI, i);
2504   }
2505 
2506   // Walking the inst in reverse order (EndMI -> StartMI].
2507   MachineBasicBlock::reverse_iterator It = EndMI;
2508   MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend();
2509   // EndMI has been handled above, skip it here.
2510   It++;
2511   MachineOperand *MO = nullptr;
2512   for (; It != E; ++It) {
2513     // Skip insturctions which could not be a def/use of RegNo.
2514     if (It->isDebugInstr() || It->isPosition())
2515       continue;
2516 
2517     // Clear killed flag for all It operands related to RegNo. In some
2518     // upexpected cases, killed may be set multiple times for same register
2519     // operand in same MI.
2520     for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2521         clearOperandKillInfo(*It, i);
2522 
2523     // If killed is not set, set killed for its last use or set dead for its def
2524     // if no use found.
2525     if (!IsKillSet) {
2526       if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2527         // Use found, set it killed.
2528         IsKillSet = true;
2529         MO->setIsKill(true);
2530         continue;
2531       } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2532                                                   &getRegisterInfo()))) {
2533         // No use found, set dead for its def.
2534         assert(&*It == &StartMI && "No new def between StartMI and EndMI.");
2535         MO->setIsDead(true);
2536         break;
2537       }
2538     }
2539 
2540     if ((&*It) == &StartMI)
2541       break;
2542   }
2543   // Ensure RegMo liveness is killed after EndMI.
2544   assert((IsKillSet || (MO && MO->isDead())) &&
2545          "RegNo should be killed or dead");
2546 }
2547 
2548 // This opt tries to convert the following imm form to an index form to save an
2549 // add for stack variables.
2550 // Return false if no such pattern found.
2551 //
2552 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
2553 // ADD instr:  ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
2554 // Imm instr:  Reg            = op OffsetImm, ToBeDeletedReg(killed)
2555 //
2556 // can be converted to:
2557 //
2558 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
2559 // Index instr:    Reg            = opx ScaleReg, ToBeChangedReg(killed)
2560 //
2561 // In order to eliminate ADD instr, make sure that:
2562 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
2563 //    new ADDI instr and ADDI can only take int16 Imm.
2564 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use
2565 //    between ADDI and ADD instr since its original def in ADDI will be changed
2566 //    in new ADDI instr. And also there should be no new def for it between
2567 //    ADD and Imm instr as ToBeChangedReg will be used in Index instr.
2568 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
2569 //    between ADD and Imm instr since ADD instr will be eliminated.
2570 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
2571 //    moved to Index instr.
2572 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
2573   MachineFunction *MF = MI.getParent()->getParent();
2574   MachineRegisterInfo *MRI = &MF->getRegInfo();
2575   bool PostRA = !MRI->isSSA();
2576   // Do this opt after PEI which is after RA. The reason is stack slot expansion
2577   // in PEI may expose such opportunities since in PEI, stack slot offsets to
2578   // frame base(OffsetAddi) are determined.
2579   if (!PostRA)
2580     return false;
2581   unsigned ToBeDeletedReg = 0;
2582   int64_t OffsetImm = 0;
2583   unsigned XFormOpcode = 0;
2584   ImmInstrInfo III;
2585 
2586   // Check if Imm instr meets requirement.
2587   if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm,
2588                                     III))
2589     return false;
2590 
2591   bool OtherIntermediateUse = false;
2592   MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse);
2593 
2594   // Exit if there is other use between ADD and Imm instr or no def found.
2595   if (OtherIntermediateUse || !ADDMI)
2596     return false;
2597 
2598   // Check if ADD instr meets requirement.
2599   if (!isADDInstrEligibleForFolding(*ADDMI))
2600     return false;
2601 
2602   unsigned ScaleRegIdx = 0;
2603   int64_t OffsetAddi = 0;
2604   MachineInstr *ADDIMI = nullptr;
2605 
2606   // Check if there is a valid ToBeChangedReg in ADDMI.
2607   // 1: It must be killed.
2608   // 2: Its definition must be a valid ADDIMI.
2609   // 3: It must satify int16 offset requirement.
2610   if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm))
2611     ScaleRegIdx = 2;
2612   else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm))
2613     ScaleRegIdx = 1;
2614   else
2615     return false;
2616 
2617   assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
2618   unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg();
2619   unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg();
2620   auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
2621                        MachineBasicBlock::iterator End) {
2622     for (auto It = ++Start; It != End; It++)
2623       if (It->modifiesRegister(Reg, &getRegisterInfo()))
2624         return true;
2625     return false;
2626   };
2627 
2628   // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
2629   // treated as special zero when ScaleReg is R0/X0 register.
2630   if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
2631       (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
2632     return false;
2633 
2634   // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
2635   // and Imm Instr.
2636   if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
2637     return false;
2638 
2639   // Now start to do the transformation.
2640   LLVM_DEBUG(dbgs() << "Replace instruction: "
2641                     << "\n");
2642   LLVM_DEBUG(ADDIMI->dump());
2643   LLVM_DEBUG(ADDMI->dump());
2644   LLVM_DEBUG(MI.dump());
2645   LLVM_DEBUG(dbgs() << "with: "
2646                     << "\n");
2647 
2648   // Update ADDI instr.
2649   ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm);
2650 
2651   // Update Imm instr.
2652   MI.setDesc(get(XFormOpcode));
2653   MI.getOperand(III.ImmOpNo)
2654       .ChangeToRegister(ScaleReg, false, false,
2655                         ADDMI->getOperand(ScaleRegIdx).isKill());
2656 
2657   MI.getOperand(III.OpNoForForwarding)
2658       .ChangeToRegister(ToBeChangedReg, false, false, true);
2659 
2660   // Eliminate ADD instr.
2661   ADDMI->eraseFromParent();
2662 
2663   LLVM_DEBUG(ADDIMI->dump());
2664   LLVM_DEBUG(MI.dump());
2665 
2666   return true;
2667 }
2668 
2669 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
2670                                                  int64_t &Imm) const {
2671   unsigned Opc = ADDIMI.getOpcode();
2672 
2673   // Exit if the instruction is not ADDI.
2674   if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
2675     return false;
2676 
2677   Imm = ADDIMI.getOperand(2).getImm();
2678 
2679   return true;
2680 }
2681 
2682 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
2683   unsigned Opc = ADDMI.getOpcode();
2684 
2685   // Exit if the instruction is not ADD.
2686   return Opc == PPC::ADD4 || Opc == PPC::ADD8;
2687 }
2688 
2689 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
2690                                                 unsigned &ToBeDeletedReg,
2691                                                 unsigned &XFormOpcode,
2692                                                 int64_t &OffsetImm,
2693                                                 ImmInstrInfo &III) const {
2694   // Only handle load/store.
2695   if (!MI.mayLoadOrStore())
2696     return false;
2697 
2698   unsigned Opc = MI.getOpcode();
2699 
2700   XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc);
2701 
2702   // Exit if instruction has no index form.
2703   if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
2704     return false;
2705 
2706   // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
2707   if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()),
2708                        III, true))
2709     return false;
2710 
2711   if (!III.IsSummingOperands)
2712     return false;
2713 
2714   MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo);
2715   MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding);
2716   // Only support imm operands, not relocation slots or others.
2717   if (!ImmOperand.isImm())
2718     return false;
2719 
2720   assert(RegOperand.isReg() && "Instruction format is not right");
2721 
2722   // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
2723   if (!RegOperand.isKill())
2724     return false;
2725 
2726   ToBeDeletedReg = RegOperand.getReg();
2727   OffsetImm = ImmOperand.getImm();
2728 
2729   return true;
2730 }
2731 
2732 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
2733                                          MachineInstr *&ADDIMI,
2734                                          int64_t &OffsetAddi,
2735                                          int64_t OffsetImm) const {
2736   assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
2737   MachineOperand &MO = ADDMI->getOperand(Index);
2738 
2739   if (!MO.isKill())
2740     return false;
2741 
2742   bool OtherIntermediateUse = false;
2743 
2744   ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse);
2745   // Currently handle only one "add + Imminstr" pair case, exit if other
2746   // intermediate use for ToBeChangedReg found.
2747   // TODO: handle the cases where there are other "add + Imminstr" pairs
2748   // with same offset in Imminstr which is like:
2749   //
2750   // ADDI instr: ToBeChangedReg  = ADDI FrameBaseReg, OffsetAddi
2751   // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
2752   // Imm instr1: Reg1            = op1 OffsetImm, ToBeDeletedReg1(killed)
2753   // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
2754   // Imm instr2: Reg2            = op2 OffsetImm, ToBeDeletedReg2(killed)
2755   //
2756   // can be converted to:
2757   //
2758   // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
2759   //                                       (OffsetAddi + OffsetImm)
2760   // Index instr1:   Reg1           = opx1 ScaleReg1, ToBeChangedReg
2761   // Index instr2:   Reg2           = opx2 ScaleReg2, ToBeChangedReg(killed)
2762 
2763   if (OtherIntermediateUse || !ADDIMI)
2764     return false;
2765   // Check if ADDI instr meets requirement.
2766   if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi))
2767     return false;
2768 
2769   if (isInt<16>(OffsetAddi + OffsetImm))
2770     return true;
2771   return false;
2772 }
2773 
2774 // If this instruction has an immediate form and one of its operands is a
2775 // result of a load-immediate or an add-immediate, convert it to
2776 // the immediate form if the constant is in range.
2777 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
2778                                           MachineInstr **KilledDef) const {
2779   MachineFunction *MF = MI.getParent()->getParent();
2780   MachineRegisterInfo *MRI = &MF->getRegInfo();
2781   bool PostRA = !MRI->isSSA();
2782   bool SeenIntermediateUse = true;
2783   unsigned ForwardingOperand = ~0U;
2784   MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
2785                                            SeenIntermediateUse);
2786   if (!DefMI)
2787     return false;
2788   assert(ForwardingOperand < MI.getNumOperands() &&
2789          "The forwarding operand needs to be valid at this point");
2790   bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
2791   bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
2792   Register ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg();
2793   if (KilledDef && KillFwdDefMI)
2794     *KilledDef = DefMI;
2795 
2796   ImmInstrInfo III;
2797   bool IsVFReg = MI.getOperand(0).isReg()
2798                      ? isVFRegister(MI.getOperand(0).getReg())
2799                      : false;
2800   bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
2801   // If this is a reg+reg instruction that has a reg+imm form,
2802   // and one of the operands is produced by an add-immediate,
2803   // try to convert it.
2804   if (HasImmForm &&
2805       transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
2806                                  KillFwdDefMI))
2807     return true;
2808 
2809   if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) ||
2810       !DefMI->getOperand(1).isImm())
2811     return false;
2812 
2813   int64_t Immediate = DefMI->getOperand(1).getImm();
2814   // Sign-extend to 64-bits.
2815   int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
2816     (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
2817 
2818   // If this is a reg+reg instruction that has a reg+imm form,
2819   // and one of the operands is produced by LI, convert it now.
2820   if (HasImmForm)
2821     return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm);
2822 
2823   bool ReplaceWithLI = false;
2824   bool Is64BitLI = false;
2825   int64_t NewImm = 0;
2826   bool SetCR = false;
2827   unsigned Opc = MI.getOpcode();
2828   switch (Opc) {
2829   default: return false;
2830 
2831   // FIXME: Any branches conditional on such a comparison can be made
2832   // unconditional. At this time, this happens too infrequently to be worth
2833   // the implementation effort, but if that ever changes, we could convert
2834   // such a pattern here.
2835   case PPC::CMPWI:
2836   case PPC::CMPLWI:
2837   case PPC::CMPDI:
2838   case PPC::CMPLDI: {
2839     // Doing this post-RA would require dataflow analysis to reliably find uses
2840     // of the CR register set by the compare.
2841     // No need to fixup killed/dead flag since this transformation is only valid
2842     // before RA.
2843     if (PostRA)
2844       return false;
2845     // If a compare-immediate is fed by an immediate and is itself an input of
2846     // an ISEL (the most common case) into a COPY of the correct register.
2847     bool Changed = false;
2848     Register DefReg = MI.getOperand(0).getReg();
2849     int64_t Comparand = MI.getOperand(2).getImm();
2850     int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ?
2851       (Comparand | 0xFFFFFFFFFFFF0000) : Comparand;
2852 
2853     for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
2854       unsigned UseOpc = CompareUseMI.getOpcode();
2855       if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
2856         continue;
2857       unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
2858       Register TrueReg = CompareUseMI.getOperand(1).getReg();
2859       Register FalseReg = CompareUseMI.getOperand(2).getReg();
2860       unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg,
2861                                      FalseReg, CRSubReg);
2862       if (RegToCopy == PPC::NoRegister)
2863         continue;
2864       // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
2865       if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
2866         CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
2867         replaceInstrOperandWithImm(CompareUseMI, 1, 0);
2868         CompareUseMI.RemoveOperand(3);
2869         CompareUseMI.RemoveOperand(2);
2870         continue;
2871       }
2872       LLVM_DEBUG(
2873           dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
2874       LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump());
2875       LLVM_DEBUG(dbgs() << "Is converted to:\n");
2876       // Convert to copy and remove unneeded operands.
2877       CompareUseMI.setDesc(get(PPC::COPY));
2878       CompareUseMI.RemoveOperand(3);
2879       CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
2880       CmpIselsConverted++;
2881       Changed = true;
2882       LLVM_DEBUG(CompareUseMI.dump());
2883     }
2884     if (Changed)
2885       return true;
2886     // This may end up incremented multiple times since this function is called
2887     // during a fixed-point transformation, but it is only meant to indicate the
2888     // presence of this opportunity.
2889     MissedConvertibleImmediateInstrs++;
2890     return false;
2891   }
2892 
2893   // Immediate forms - may simply be convertable to an LI.
2894   case PPC::ADDI:
2895   case PPC::ADDI8: {
2896     // Does the sum fit in a 16-bit signed field?
2897     int64_t Addend = MI.getOperand(2).getImm();
2898     if (isInt<16>(Addend + SExtImm)) {
2899       ReplaceWithLI = true;
2900       Is64BitLI = Opc == PPC::ADDI8;
2901       NewImm = Addend + SExtImm;
2902       break;
2903     }
2904     return false;
2905   }
2906   case PPC::RLDICL:
2907   case PPC::RLDICL_rec:
2908   case PPC::RLDICL_32:
2909   case PPC::RLDICL_32_64: {
2910     // Use APInt's rotate function.
2911     int64_t SH = MI.getOperand(2).getImm();
2912     int64_t MB = MI.getOperand(3).getImm();
2913     APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
2914                 SExtImm, true);
2915     InVal = InVal.rotl(SH);
2916     uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
2917     InVal &= Mask;
2918     // Can't replace negative values with an LI as that will sign-extend
2919     // and not clear the left bits. If we're setting the CR bit, we will use
2920     // ANDI_rec which won't sign extend, so that's safe.
2921     if (isUInt<15>(InVal.getSExtValue()) ||
2922         (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) {
2923       ReplaceWithLI = true;
2924       Is64BitLI = Opc != PPC::RLDICL_32;
2925       NewImm = InVal.getSExtValue();
2926       SetCR = Opc == PPC::RLDICL_rec;
2927       break;
2928     }
2929     return false;
2930   }
2931   case PPC::RLWINM:
2932   case PPC::RLWINM8:
2933   case PPC::RLWINM_rec:
2934   case PPC::RLWINM8_rec: {
2935     int64_t SH = MI.getOperand(2).getImm();
2936     int64_t MB = MI.getOperand(3).getImm();
2937     int64_t ME = MI.getOperand(4).getImm();
2938     APInt InVal(32, SExtImm, true);
2939     InVal = InVal.rotl(SH);
2940     // Set the bits (        MB + 32        ) to (        ME + 32        ).
2941     uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2942     InVal &= Mask;
2943     // Can't replace negative values with an LI as that will sign-extend
2944     // and not clear the left bits. If we're setting the CR bit, we will use
2945     // ANDI_rec which won't sign extend, so that's safe.
2946     bool ValueFits = isUInt<15>(InVal.getSExtValue());
2947     ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
2948                   isUInt<16>(InVal.getSExtValue()));
2949     if (ValueFits) {
2950       ReplaceWithLI = true;
2951       Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
2952       NewImm = InVal.getSExtValue();
2953       SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
2954       break;
2955     }
2956     return false;
2957   }
2958   case PPC::ORI:
2959   case PPC::ORI8:
2960   case PPC::XORI:
2961   case PPC::XORI8: {
2962     int64_t LogicalImm = MI.getOperand(2).getImm();
2963     int64_t Result = 0;
2964     if (Opc == PPC::ORI || Opc == PPC::ORI8)
2965       Result = LogicalImm | SExtImm;
2966     else
2967       Result = LogicalImm ^ SExtImm;
2968     if (isInt<16>(Result)) {
2969       ReplaceWithLI = true;
2970       Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
2971       NewImm = Result;
2972       break;
2973     }
2974     return false;
2975   }
2976   }
2977 
2978   if (ReplaceWithLI) {
2979     // We need to be careful with CR-setting instructions we're replacing.
2980     if (SetCR) {
2981       // We don't know anything about uses when we're out of SSA, so only
2982       // replace if the new immediate will be reproduced.
2983       bool ImmChanged = (SExtImm & NewImm) != NewImm;
2984       if (PostRA && ImmChanged)
2985         return false;
2986 
2987       if (!PostRA) {
2988         // If the defining load-immediate has no other uses, we can just replace
2989         // the immediate with the new immediate.
2990         if (MRI->hasOneUse(DefMI->getOperand(0).getReg()))
2991           DefMI->getOperand(1).setImm(NewImm);
2992 
2993         // If we're not using the GPR result of the CR-setting instruction, we
2994         // just need to and with zero/non-zero depending on the new immediate.
2995         else if (MRI->use_empty(MI.getOperand(0).getReg())) {
2996           if (NewImm) {
2997             assert(Immediate && "Transformation converted zero to non-zero?");
2998             NewImm = Immediate;
2999           }
3000         }
3001         else if (ImmChanged)
3002           return false;
3003       }
3004     }
3005 
3006     LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3007     LLVM_DEBUG(MI.dump());
3008     LLVM_DEBUG(dbgs() << "Fed by:\n");
3009     LLVM_DEBUG(DefMI->dump());
3010     LoadImmediateInfo LII;
3011     LII.Imm = NewImm;
3012     LII.Is64Bit = Is64BitLI;
3013     LII.SetCR = SetCR;
3014     // If we're setting the CR, the original load-immediate must be kept (as an
3015     // operand to ANDI_rec/ANDI8_rec).
3016     if (KilledDef && SetCR)
3017       *KilledDef = nullptr;
3018     replaceInstrWithLI(MI, LII);
3019 
3020     // Fixup killed/dead flag after transformation.
3021     // Pattern:
3022     // ForwardingOperandReg = LI imm1
3023     // y = op2 imm2, ForwardingOperandReg(killed)
3024     if (IsForwardingOperandKilled)
3025       fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg);
3026 
3027     LLVM_DEBUG(dbgs() << "With:\n");
3028     LLVM_DEBUG(MI.dump());
3029     return true;
3030   }
3031   return false;
3032 }
3033 
3034 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
3035                                    ImmInstrInfo &III, bool PostRA) const {
3036   // The vast majority of the instructions would need their operand 2 replaced
3037   // with an immediate when switching to the reg+imm form. A marked exception
3038   // are the update form loads/stores for which a constant operand 2 would need
3039   // to turn into a displacement and move operand 1 to the operand 2 position.
3040   III.ImmOpNo = 2;
3041   III.OpNoForForwarding = 2;
3042   III.ImmWidth = 16;
3043   III.ImmMustBeMultipleOf = 1;
3044   III.TruncateImmTo = 0;
3045   III.IsSummingOperands = false;
3046   switch (Opc) {
3047   default: return false;
3048   case PPC::ADD4:
3049   case PPC::ADD8:
3050     III.SignedImm = true;
3051     III.ZeroIsSpecialOrig = 0;
3052     III.ZeroIsSpecialNew = 1;
3053     III.IsCommutative = true;
3054     III.IsSummingOperands = true;
3055     III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
3056     break;
3057   case PPC::ADDC:
3058   case PPC::ADDC8:
3059     III.SignedImm = true;
3060     III.ZeroIsSpecialOrig = 0;
3061     III.ZeroIsSpecialNew = 0;
3062     III.IsCommutative = true;
3063     III.IsSummingOperands = true;
3064     III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
3065     break;
3066   case PPC::ADDC_rec:
3067     III.SignedImm = true;
3068     III.ZeroIsSpecialOrig = 0;
3069     III.ZeroIsSpecialNew = 0;
3070     III.IsCommutative = true;
3071     III.IsSummingOperands = true;
3072     III.ImmOpcode = PPC::ADDIC_rec;
3073     break;
3074   case PPC::SUBFC:
3075   case PPC::SUBFC8:
3076     III.SignedImm = true;
3077     III.ZeroIsSpecialOrig = 0;
3078     III.ZeroIsSpecialNew = 0;
3079     III.IsCommutative = false;
3080     III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
3081     break;
3082   case PPC::CMPW:
3083   case PPC::CMPD:
3084     III.SignedImm = true;
3085     III.ZeroIsSpecialOrig = 0;
3086     III.ZeroIsSpecialNew = 0;
3087     III.IsCommutative = false;
3088     III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
3089     break;
3090   case PPC::CMPLW:
3091   case PPC::CMPLD:
3092     III.SignedImm = false;
3093     III.ZeroIsSpecialOrig = 0;
3094     III.ZeroIsSpecialNew = 0;
3095     III.IsCommutative = false;
3096     III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
3097     break;
3098   case PPC::AND_rec:
3099   case PPC::AND8_rec:
3100   case PPC::OR:
3101   case PPC::OR8:
3102   case PPC::XOR:
3103   case PPC::XOR8:
3104     III.SignedImm = false;
3105     III.ZeroIsSpecialOrig = 0;
3106     III.ZeroIsSpecialNew = 0;
3107     III.IsCommutative = true;
3108     switch(Opc) {
3109     default: llvm_unreachable("Unknown opcode");
3110     case PPC::AND_rec:
3111       III.ImmOpcode = PPC::ANDI_rec;
3112       break;
3113     case PPC::AND8_rec:
3114       III.ImmOpcode = PPC::ANDI8_rec;
3115       break;
3116     case PPC::OR: III.ImmOpcode = PPC::ORI; break;
3117     case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
3118     case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
3119     case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
3120     }
3121     break;
3122   case PPC::RLWNM:
3123   case PPC::RLWNM8:
3124   case PPC::RLWNM_rec:
3125   case PPC::RLWNM8_rec:
3126   case PPC::SLW:
3127   case PPC::SLW8:
3128   case PPC::SLW_rec:
3129   case PPC::SLW8_rec:
3130   case PPC::SRW:
3131   case PPC::SRW8:
3132   case PPC::SRW_rec:
3133   case PPC::SRW8_rec:
3134   case PPC::SRAW:
3135   case PPC::SRAW_rec:
3136     III.SignedImm = false;
3137     III.ZeroIsSpecialOrig = 0;
3138     III.ZeroIsSpecialNew = 0;
3139     III.IsCommutative = false;
3140     // This isn't actually true, but the instructions ignore any of the
3141     // upper bits, so any immediate loaded with an LI is acceptable.
3142     // This does not apply to shift right algebraic because a value
3143     // out of range will produce a -1/0.
3144     III.ImmWidth = 16;
3145     if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
3146         Opc == PPC::RLWNM8_rec)
3147       III.TruncateImmTo = 5;
3148     else
3149       III.TruncateImmTo = 6;
3150     switch(Opc) {
3151     default: llvm_unreachable("Unknown opcode");
3152     case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
3153     case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
3154     case PPC::RLWNM_rec:
3155       III.ImmOpcode = PPC::RLWINM_rec;
3156       break;
3157     case PPC::RLWNM8_rec:
3158       III.ImmOpcode = PPC::RLWINM8_rec;
3159       break;
3160     case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
3161     case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
3162     case PPC::SLW_rec:
3163       III.ImmOpcode = PPC::RLWINM_rec;
3164       break;
3165     case PPC::SLW8_rec:
3166       III.ImmOpcode = PPC::RLWINM8_rec;
3167       break;
3168     case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
3169     case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
3170     case PPC::SRW_rec:
3171       III.ImmOpcode = PPC::RLWINM_rec;
3172       break;
3173     case PPC::SRW8_rec:
3174       III.ImmOpcode = PPC::RLWINM8_rec;
3175       break;
3176     case PPC::SRAW:
3177       III.ImmWidth = 5;
3178       III.TruncateImmTo = 0;
3179       III.ImmOpcode = PPC::SRAWI;
3180       break;
3181     case PPC::SRAW_rec:
3182       III.ImmWidth = 5;
3183       III.TruncateImmTo = 0;
3184       III.ImmOpcode = PPC::SRAWI_rec;
3185       break;
3186     }
3187     break;
3188   case PPC::RLDCL:
3189   case PPC::RLDCL_rec:
3190   case PPC::RLDCR:
3191   case PPC::RLDCR_rec:
3192   case PPC::SLD:
3193   case PPC::SLD_rec:
3194   case PPC::SRD:
3195   case PPC::SRD_rec:
3196   case PPC::SRAD:
3197   case PPC::SRAD_rec:
3198     III.SignedImm = false;
3199     III.ZeroIsSpecialOrig = 0;
3200     III.ZeroIsSpecialNew = 0;
3201     III.IsCommutative = false;
3202     // This isn't actually true, but the instructions ignore any of the
3203     // upper bits, so any immediate loaded with an LI is acceptable.
3204     // This does not apply to shift right algebraic because a value
3205     // out of range will produce a -1/0.
3206     III.ImmWidth = 16;
3207     if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
3208         Opc == PPC::RLDCR_rec)
3209       III.TruncateImmTo = 6;
3210     else
3211       III.TruncateImmTo = 7;
3212     switch(Opc) {
3213     default: llvm_unreachable("Unknown opcode");
3214     case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
3215     case PPC::RLDCL_rec:
3216       III.ImmOpcode = PPC::RLDICL_rec;
3217       break;
3218     case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
3219     case PPC::RLDCR_rec:
3220       III.ImmOpcode = PPC::RLDICR_rec;
3221       break;
3222     case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
3223     case PPC::SLD_rec:
3224       III.ImmOpcode = PPC::RLDICR_rec;
3225       break;
3226     case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
3227     case PPC::SRD_rec:
3228       III.ImmOpcode = PPC::RLDICL_rec;
3229       break;
3230     case PPC::SRAD:
3231       III.ImmWidth = 6;
3232       III.TruncateImmTo = 0;
3233       III.ImmOpcode = PPC::SRADI;
3234        break;
3235     case PPC::SRAD_rec:
3236       III.ImmWidth = 6;
3237       III.TruncateImmTo = 0;
3238       III.ImmOpcode = PPC::SRADI_rec;
3239       break;
3240     }
3241     break;
3242   // Loads and stores:
3243   case PPC::LBZX:
3244   case PPC::LBZX8:
3245   case PPC::LHZX:
3246   case PPC::LHZX8:
3247   case PPC::LHAX:
3248   case PPC::LHAX8:
3249   case PPC::LWZX:
3250   case PPC::LWZX8:
3251   case PPC::LWAX:
3252   case PPC::LDX:
3253   case PPC::LFSX:
3254   case PPC::LFDX:
3255   case PPC::STBX:
3256   case PPC::STBX8:
3257   case PPC::STHX:
3258   case PPC::STHX8:
3259   case PPC::STWX:
3260   case PPC::STWX8:
3261   case PPC::STDX:
3262   case PPC::STFSX:
3263   case PPC::STFDX:
3264     III.SignedImm = true;
3265     III.ZeroIsSpecialOrig = 1;
3266     III.ZeroIsSpecialNew = 2;
3267     III.IsCommutative = true;
3268     III.IsSummingOperands = true;
3269     III.ImmOpNo = 1;
3270     III.OpNoForForwarding = 2;
3271     switch(Opc) {
3272     default: llvm_unreachable("Unknown opcode");
3273     case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3274     case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3275     case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3276     case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3277     case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3278     case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3279     case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3280     case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3281     case PPC::LWAX:
3282       III.ImmOpcode = PPC::LWA;
3283       III.ImmMustBeMultipleOf = 4;
3284       break;
3285     case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3286     case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3287     case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3288     case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3289     case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3290     case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3291     case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3292     case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3293     case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3294     case PPC::STDX:
3295       III.ImmOpcode = PPC::STD;
3296       III.ImmMustBeMultipleOf = 4;
3297       break;
3298     case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3299     case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3300     }
3301     break;
3302   case PPC::LBZUX:
3303   case PPC::LBZUX8:
3304   case PPC::LHZUX:
3305   case PPC::LHZUX8:
3306   case PPC::LHAUX:
3307   case PPC::LHAUX8:
3308   case PPC::LWZUX:
3309   case PPC::LWZUX8:
3310   case PPC::LDUX:
3311   case PPC::LFSUX:
3312   case PPC::LFDUX:
3313   case PPC::STBUX:
3314   case PPC::STBUX8:
3315   case PPC::STHUX:
3316   case PPC::STHUX8:
3317   case PPC::STWUX:
3318   case PPC::STWUX8:
3319   case PPC::STDUX:
3320   case PPC::STFSUX:
3321   case PPC::STFDUX:
3322     III.SignedImm = true;
3323     III.ZeroIsSpecialOrig = 2;
3324     III.ZeroIsSpecialNew = 3;
3325     III.IsCommutative = false;
3326     III.IsSummingOperands = true;
3327     III.ImmOpNo = 2;
3328     III.OpNoForForwarding = 3;
3329     switch(Opc) {
3330     default: llvm_unreachable("Unknown opcode");
3331     case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3332     case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3333     case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3334     case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3335     case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3336     case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3337     case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3338     case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3339     case PPC::LDUX:
3340       III.ImmOpcode = PPC::LDU;
3341       III.ImmMustBeMultipleOf = 4;
3342       break;
3343     case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3344     case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3345     case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3346     case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3347     case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3348     case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3349     case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3350     case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3351     case PPC::STDUX:
3352       III.ImmOpcode = PPC::STDU;
3353       III.ImmMustBeMultipleOf = 4;
3354       break;
3355     case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3356     case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3357     }
3358     break;
3359   // Power9 and up only. For some of these, the X-Form version has access to all
3360   // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3361   // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3362   // into or stored from is one of the VR registers.
3363   case PPC::LXVX:
3364   case PPC::LXSSPX:
3365   case PPC::LXSDX:
3366   case PPC::STXVX:
3367   case PPC::STXSSPX:
3368   case PPC::STXSDX:
3369   case PPC::XFLOADf32:
3370   case PPC::XFLOADf64:
3371   case PPC::XFSTOREf32:
3372   case PPC::XFSTOREf64:
3373     if (!Subtarget.hasP9Vector())
3374       return false;
3375     III.SignedImm = true;
3376     III.ZeroIsSpecialOrig = 1;
3377     III.ZeroIsSpecialNew = 2;
3378     III.IsCommutative = true;
3379     III.IsSummingOperands = true;
3380     III.ImmOpNo = 1;
3381     III.OpNoForForwarding = 2;
3382     III.ImmMustBeMultipleOf = 4;
3383     switch(Opc) {
3384     default: llvm_unreachable("Unknown opcode");
3385     case PPC::LXVX:
3386       III.ImmOpcode = PPC::LXV;
3387       III.ImmMustBeMultipleOf = 16;
3388       break;
3389     case PPC::LXSSPX:
3390       if (PostRA) {
3391         if (IsVFReg)
3392           III.ImmOpcode = PPC::LXSSP;
3393         else {
3394           III.ImmOpcode = PPC::LFS;
3395           III.ImmMustBeMultipleOf = 1;
3396         }
3397         break;
3398       }
3399       LLVM_FALLTHROUGH;
3400     case PPC::XFLOADf32:
3401       III.ImmOpcode = PPC::DFLOADf32;
3402       break;
3403     case PPC::LXSDX:
3404       if (PostRA) {
3405         if (IsVFReg)
3406           III.ImmOpcode = PPC::LXSD;
3407         else {
3408           III.ImmOpcode = PPC::LFD;
3409           III.ImmMustBeMultipleOf = 1;
3410         }
3411         break;
3412       }
3413       LLVM_FALLTHROUGH;
3414     case PPC::XFLOADf64:
3415       III.ImmOpcode = PPC::DFLOADf64;
3416       break;
3417     case PPC::STXVX:
3418       III.ImmOpcode = PPC::STXV;
3419       III.ImmMustBeMultipleOf = 16;
3420       break;
3421     case PPC::STXSSPX:
3422       if (PostRA) {
3423         if (IsVFReg)
3424           III.ImmOpcode = PPC::STXSSP;
3425         else {
3426           III.ImmOpcode = PPC::STFS;
3427           III.ImmMustBeMultipleOf = 1;
3428         }
3429         break;
3430       }
3431       LLVM_FALLTHROUGH;
3432     case PPC::XFSTOREf32:
3433       III.ImmOpcode = PPC::DFSTOREf32;
3434       break;
3435     case PPC::STXSDX:
3436       if (PostRA) {
3437         if (IsVFReg)
3438           III.ImmOpcode = PPC::STXSD;
3439         else {
3440           III.ImmOpcode = PPC::STFD;
3441           III.ImmMustBeMultipleOf = 1;
3442         }
3443         break;
3444       }
3445       LLVM_FALLTHROUGH;
3446     case PPC::XFSTOREf64:
3447       III.ImmOpcode = PPC::DFSTOREf64;
3448       break;
3449     }
3450     break;
3451   }
3452   return true;
3453 }
3454 
3455 // Utility function for swaping two arbitrary operands of an instruction.
3456 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3457   assert(Op1 != Op2 && "Cannot swap operand with itself.");
3458 
3459   unsigned MaxOp = std::max(Op1, Op2);
3460   unsigned MinOp = std::min(Op1, Op2);
3461   MachineOperand MOp1 = MI.getOperand(MinOp);
3462   MachineOperand MOp2 = MI.getOperand(MaxOp);
3463   MI.RemoveOperand(std::max(Op1, Op2));
3464   MI.RemoveOperand(std::min(Op1, Op2));
3465 
3466   // If the operands we are swapping are the two at the end (the common case)
3467   // we can just remove both and add them in the opposite order.
3468   if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3469     MI.addOperand(MOp2);
3470     MI.addOperand(MOp1);
3471   } else {
3472     // Store all operands in a temporary vector, remove them and re-add in the
3473     // right order.
3474     SmallVector<MachineOperand, 2> MOps;
3475     unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3476     for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3477       MOps.push_back(MI.getOperand(i));
3478       MI.RemoveOperand(i);
3479     }
3480     // MOp2 needs to be added next.
3481     MI.addOperand(MOp2);
3482     // Now add the rest.
3483     for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3484       if (i == MaxOp)
3485         MI.addOperand(MOp1);
3486       else {
3487         MI.addOperand(MOps.back());
3488         MOps.pop_back();
3489       }
3490     }
3491   }
3492 }
3493 
3494 // Check if the 'MI' that has the index OpNoForForwarding
3495 // meets the requirement described in the ImmInstrInfo.
3496 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3497                                                const ImmInstrInfo &III,
3498                                                unsigned OpNoForForwarding
3499                                                ) const {
3500   // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3501   // would not work pre-RA, we can only do the check post RA.
3502   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3503   if (MRI.isSSA())
3504     return false;
3505 
3506   // Cannot do the transform if MI isn't summing the operands.
3507   if (!III.IsSummingOperands)
3508     return false;
3509 
3510   // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3511   if (!III.ZeroIsSpecialOrig)
3512     return false;
3513 
3514   // We cannot do the transform if the operand we are trying to replace
3515   // isn't the same as the operand the instruction allows.
3516   if (OpNoForForwarding != III.OpNoForForwarding)
3517     return false;
3518 
3519   // Check if the instruction we are trying to transform really has
3520   // the special zero register as its operand.
3521   if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3522       MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3523     return false;
3524 
3525   // This machine instruction is convertible if it is,
3526   // 1. summing the operands.
3527   // 2. one of the operands is special zero register.
3528   // 3. the operand we are trying to replace is allowed by the MI.
3529   return true;
3530 }
3531 
3532 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3533 // accordingly.
3534 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3535                                                const ImmInstrInfo &III,
3536                                                MachineOperand *&ImmMO,
3537                                                MachineOperand *&RegMO) const {
3538   unsigned Opc = DefMI.getOpcode();
3539   if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3540     return false;
3541 
3542   assert(DefMI.getNumOperands() >= 3 &&
3543          "Add inst must have at least three operands");
3544   RegMO = &DefMI.getOperand(1);
3545   ImmMO = &DefMI.getOperand(2);
3546 
3547   // This DefMI is elgible for forwarding if it is:
3548   // 1. add inst
3549   // 2. one of the operands is Imm/CPI/Global.
3550   return isAnImmediateOperand(*ImmMO);
3551 }
3552 
3553 bool PPCInstrInfo::isRegElgibleForForwarding(
3554     const MachineOperand &RegMO, const MachineInstr &DefMI,
3555     const MachineInstr &MI, bool KillDefMI,
3556     bool &IsFwdFeederRegKilled) const {
3557   // x = addi y, imm
3558   // ...
3559   // z = lfdx 0, x   -> z = lfd imm(y)
3560   // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3561   // of "y" between the DEF of "x" and "z".
3562   // The query is only valid post RA.
3563   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3564   if (MRI.isSSA())
3565     return false;
3566 
3567   Register Reg = RegMO.getReg();
3568 
3569   // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3570   MachineBasicBlock::const_reverse_iterator It = MI;
3571   MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3572   It++;
3573   for (; It != E; ++It) {
3574     if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3575       return false;
3576     else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3577       IsFwdFeederRegKilled = true;
3578     // Made it to DefMI without encountering a clobber.
3579     if ((&*It) == &DefMI)
3580       break;
3581   }
3582   assert((&*It) == &DefMI && "DefMI is missing");
3583 
3584   // If DefMI also defines the register to be forwarded, we can only forward it
3585   // if DefMI is being erased.
3586   if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3587     return KillDefMI;
3588 
3589   return true;
3590 }
3591 
3592 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3593                                              const MachineInstr &DefMI,
3594                                              const ImmInstrInfo &III,
3595                                              int64_t &Imm) const {
3596   assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3597   if (DefMI.getOpcode() == PPC::ADDItocL) {
3598     // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3599     // However, we know that, it is 16-bit width, and has the alignment of 4.
3600     // Check if the instruction met the requirement.
3601     if (III.ImmMustBeMultipleOf > 4 ||
3602        III.TruncateImmTo || III.ImmWidth != 16)
3603       return false;
3604 
3605     // Going from XForm to DForm loads means that the displacement needs to be
3606     // not just an immediate but also a multiple of 4, or 16 depending on the
3607     // load. A DForm load cannot be represented if it is a multiple of say 2.
3608     // XForm loads do not have this restriction.
3609     if (ImmMO.isGlobal() &&
3610         ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf)
3611       return false;
3612 
3613     return true;
3614   }
3615 
3616   if (ImmMO.isImm()) {
3617     // It is Imm, we need to check if the Imm fit the range.
3618     int64_t Immediate = ImmMO.getImm();
3619     // Sign-extend to 64-bits.
3620     Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
3621       (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
3622 
3623     if (Imm % III.ImmMustBeMultipleOf)
3624       return false;
3625     if (III.TruncateImmTo)
3626       Imm &= ((1 << III.TruncateImmTo) - 1);
3627     if (III.SignedImm) {
3628       APInt ActualValue(64, Imm, true);
3629       if (!ActualValue.isSignedIntN(III.ImmWidth))
3630         return false;
3631     } else {
3632       uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3633       if ((uint64_t)Imm > UnsignedMax)
3634         return false;
3635     }
3636   }
3637   else
3638     return false;
3639 
3640   // This ImmMO is forwarded if it meets the requriement describle
3641   // in ImmInstrInfo
3642   return true;
3643 }
3644 
3645 // If an X-Form instruction is fed by an add-immediate and one of its operands
3646 // is the literal zero, attempt to forward the source of the add-immediate to
3647 // the corresponding D-Form instruction with the displacement coming from
3648 // the immediate being added.
3649 bool PPCInstrInfo::transformToImmFormFedByAdd(
3650     MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
3651     MachineInstr &DefMI, bool KillDefMI) const {
3652   //         RegMO ImmMO
3653   //           |    |
3654   // x = addi reg, imm  <----- DefMI
3655   // y = op    0 ,  x   <----- MI
3656   //                |
3657   //         OpNoForForwarding
3658   // Check if the MI meet the requirement described in the III.
3659   if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
3660     return false;
3661 
3662   // Check if the DefMI meet the requirement
3663   // described in the III. If yes, set the ImmMO and RegMO accordingly.
3664   MachineOperand *ImmMO = nullptr;
3665   MachineOperand *RegMO = nullptr;
3666   if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
3667     return false;
3668   assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
3669 
3670   // As we get the Imm operand now, we need to check if the ImmMO meet
3671   // the requirement described in the III. If yes set the Imm.
3672   int64_t Imm = 0;
3673   if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
3674     return false;
3675 
3676   bool IsFwdFeederRegKilled = false;
3677   // Check if the RegMO can be forwarded to MI.
3678   if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
3679                                  IsFwdFeederRegKilled))
3680     return false;
3681 
3682   // Get killed info in case fixup needed after transformation.
3683   unsigned ForwardKilledOperandReg = ~0U;
3684   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3685   bool PostRA = !MRI.isSSA();
3686   if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
3687     ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
3688 
3689   // We know that, the MI and DefMI both meet the pattern, and
3690   // the Imm also meet the requirement with the new Imm-form.
3691   // It is safe to do the transformation now.
3692   LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3693   LLVM_DEBUG(MI.dump());
3694   LLVM_DEBUG(dbgs() << "Fed by:\n");
3695   LLVM_DEBUG(DefMI.dump());
3696 
3697   // Update the base reg first.
3698   MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
3699                                                         false, false,
3700                                                         RegMO->isKill());
3701 
3702   // Then, update the imm.
3703   if (ImmMO->isImm()) {
3704     // If the ImmMO is Imm, change the operand that has ZERO to that Imm
3705     // directly.
3706     replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
3707   }
3708   else {
3709     // Otherwise, it is Constant Pool Index(CPI) or Global,
3710     // which is relocation in fact. We need to replace the special zero
3711     // register with ImmMO.
3712     // Before that, we need to fixup the target flags for imm.
3713     // For some reason, we miss to set the flag for the ImmMO if it is CPI.
3714     if (DefMI.getOpcode() == PPC::ADDItocL)
3715       ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
3716 
3717     // MI didn't have the interface such as MI.setOperand(i) though
3718     // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
3719     // ImmMO, we need to remove ZERO operand and all the operands behind it,
3720     // and, add the ImmMO, then, move back all the operands behind ZERO.
3721     SmallVector<MachineOperand, 2> MOps;
3722     for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
3723       MOps.push_back(MI.getOperand(i));
3724       MI.RemoveOperand(i);
3725     }
3726 
3727     // Remove the last MO in the list, which is ZERO operand in fact.
3728     MOps.pop_back();
3729     // Add the imm operand.
3730     MI.addOperand(*ImmMO);
3731     // Now add the rest back.
3732     for (auto &MO : MOps)
3733       MI.addOperand(MO);
3734   }
3735 
3736   // Update the opcode.
3737   MI.setDesc(get(III.ImmOpcode));
3738 
3739   // Fix up killed/dead flag after transformation.
3740   // Pattern 1:
3741   // x = ADD KilledFwdFeederReg, imm
3742   // n = opn KilledFwdFeederReg(killed), regn
3743   // y = XOP 0, x
3744   // Pattern 2:
3745   // x = ADD reg(killed), imm
3746   // y = XOP 0, x
3747   if (IsFwdFeederRegKilled || RegMO->isKill())
3748     fixupIsDeadOrKill(DefMI, MI, RegMO->getReg());
3749   // Pattern 3:
3750   // ForwardKilledOperandReg = ADD reg, imm
3751   // y = XOP 0, ForwardKilledOperandReg(killed)
3752   if (ForwardKilledOperandReg != ~0U)
3753     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3754 
3755   LLVM_DEBUG(dbgs() << "With:\n");
3756   LLVM_DEBUG(MI.dump());
3757 
3758   return true;
3759 }
3760 
3761 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
3762                                              const ImmInstrInfo &III,
3763                                              unsigned ConstantOpNo,
3764                                              MachineInstr &DefMI,
3765                                              int64_t Imm) const {
3766   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3767   bool PostRA = !MRI.isSSA();
3768   // Exit early if we can't convert this.
3769   if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
3770     return false;
3771   if (Imm % III.ImmMustBeMultipleOf)
3772     return false;
3773   if (III.TruncateImmTo)
3774     Imm &= ((1 << III.TruncateImmTo) - 1);
3775   if (III.SignedImm) {
3776     APInt ActualValue(64, Imm, true);
3777     if (!ActualValue.isSignedIntN(III.ImmWidth))
3778       return false;
3779   } else {
3780     uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3781     if ((uint64_t)Imm > UnsignedMax)
3782       return false;
3783   }
3784 
3785   // If we're post-RA, the instructions don't agree on whether register zero is
3786   // special, we can transform this as long as the register operand that will
3787   // end up in the location where zero is special isn't R0.
3788   if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3789     unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
3790       III.ZeroIsSpecialNew + 1;
3791     Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
3792     Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3793     // If R0 is in the operand where zero is special for the new instruction,
3794     // it is unsafe to transform if the constant operand isn't that operand.
3795     if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
3796         ConstantOpNo != III.ZeroIsSpecialNew)
3797       return false;
3798     if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
3799         ConstantOpNo != PosForOrigZero)
3800       return false;
3801   }
3802 
3803   // Get killed info in case fixup needed after transformation.
3804   unsigned ForwardKilledOperandReg = ~0U;
3805   if (PostRA && MI.getOperand(ConstantOpNo).isKill())
3806     ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
3807 
3808   unsigned Opc = MI.getOpcode();
3809   bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
3810                         Opc == PPC::SRW || Opc == PPC::SRW_rec ||
3811                         Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
3812                         Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
3813   bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
3814                         Opc == PPC::SRD || Opc == PPC::SRD_rec;
3815   bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
3816                Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
3817   bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
3818                     Opc == PPC::SRD_rec;
3819 
3820   MI.setDesc(get(III.ImmOpcode));
3821   if (ConstantOpNo == III.OpNoForForwarding) {
3822     // Converting shifts to immediate form is a bit tricky since they may do
3823     // one of three things:
3824     // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
3825     // 2. If the shift amount is zero, the result is unchanged (save for maybe
3826     //    setting CR0)
3827     // 3. If the shift amount is in [1, OpSize), it's just a shift
3828     if (SpecialShift32 || SpecialShift64) {
3829       LoadImmediateInfo LII;
3830       LII.Imm = 0;
3831       LII.SetCR = SetCR;
3832       LII.Is64Bit = SpecialShift64;
3833       uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
3834       if (Imm & (SpecialShift32 ? 0x20 : 0x40))
3835         replaceInstrWithLI(MI, LII);
3836       // Shifts by zero don't change the value. If we don't need to set CR0,
3837       // just convert this to a COPY. Can't do this post-RA since we've already
3838       // cleaned up the copies.
3839       else if (!SetCR && ShAmt == 0 && !PostRA) {
3840         MI.RemoveOperand(2);
3841         MI.setDesc(get(PPC::COPY));
3842       } else {
3843         // The 32 bit and 64 bit instructions are quite different.
3844         if (SpecialShift32) {
3845           // Left shifts use (N, 0, 31-N).
3846           // Right shifts use (32-N, N, 31) if 0 < N < 32.
3847           //              use (0, 0, 31)    if N == 0.
3848           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
3849           uint64_t MB = RightShift ? ShAmt : 0;
3850           uint64_t ME = RightShift ? 31 : 31 - ShAmt;
3851           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3852           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
3853             .addImm(ME);
3854         } else {
3855           // Left shifts use (N, 63-N).
3856           // Right shifts use (64-N, N) if 0 < N < 64.
3857           //              use (0, 0)    if N == 0.
3858           uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
3859           uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
3860           replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3861           MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
3862         }
3863       }
3864     } else
3865       replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3866   }
3867   // Convert commutative instructions (switch the operands and convert the
3868   // desired one to an immediate.
3869   else if (III.IsCommutative) {
3870     replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3871     swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
3872   } else
3873     llvm_unreachable("Should have exited early!");
3874 
3875   // For instructions for which the constant register replaces a different
3876   // operand than where the immediate goes, we need to swap them.
3877   if (III.OpNoForForwarding != III.ImmOpNo)
3878     swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
3879 
3880   // If the special R0/X0 register index are different for original instruction
3881   // and new instruction, we need to fix up the register class in new
3882   // instruction.
3883   if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3884     if (III.ZeroIsSpecialNew) {
3885       // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
3886       // need to fix up register class.
3887       Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3888       if (Register::isVirtualRegister(RegToModify)) {
3889         const TargetRegisterClass *NewRC =
3890           MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
3891           &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
3892         MRI.setRegClass(RegToModify, NewRC);
3893       }
3894     }
3895   }
3896 
3897   // Fix up killed/dead flag after transformation.
3898   // Pattern:
3899   // ForwardKilledOperandReg = LI imm
3900   // y = XOP reg, ForwardKilledOperandReg(killed)
3901   if (ForwardKilledOperandReg != ~0U)
3902     fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3903   return true;
3904 }
3905 
3906 const TargetRegisterClass *
3907 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
3908   if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
3909     return &PPC::VSRCRegClass;
3910   return RC;
3911 }
3912 
3913 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
3914   return PPC::getRecordFormOpcode(Opcode);
3915 }
3916 
3917 // This function returns true if the machine instruction
3918 // always outputs a value by sign-extending a 32 bit value,
3919 // i.e. 0 to 31-th bits are same as 32-th bit.
3920 static bool isSignExtendingOp(const MachineInstr &MI) {
3921   int Opcode = MI.getOpcode();
3922   if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS ||
3923       Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec ||
3924       Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA ||
3925       Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
3926       Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 ||
3927       Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
3928       Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU ||
3929       Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3930       Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 ||
3931       Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
3932       Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB ||
3933       Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH ||
3934       Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 ||
3935       Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW ||
3936       Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
3937       Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
3938       Opcode == PPC::EXTSB8_32_64)
3939     return true;
3940 
3941   if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
3942     return true;
3943 
3944   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3945        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
3946       MI.getOperand(3).getImm() > 0 &&
3947       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3948     return true;
3949 
3950   return false;
3951 }
3952 
3953 // This function returns true if the machine instruction
3954 // always outputs zeros in higher 32 bits.
3955 static bool isZeroExtendingOp(const MachineInstr &MI) {
3956   int Opcode = MI.getOpcode();
3957   // The 16-bit immediate is sign-extended in li/lis.
3958   // If the most significant bit is zero, all higher bits are zero.
3959   if (Opcode == PPC::LI  || Opcode == PPC::LI8 ||
3960       Opcode == PPC::LIS || Opcode == PPC::LIS8) {
3961     int64_t Imm = MI.getOperand(1).getImm();
3962     if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
3963       return true;
3964   }
3965 
3966   // We have some variations of rotate-and-mask instructions
3967   // that clear higher 32-bits.
3968   if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
3969        Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
3970        Opcode == PPC::RLDICL_32_64) &&
3971       MI.getOperand(3).getImm() >= 32)
3972     return true;
3973 
3974   if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
3975       MI.getOperand(3).getImm() >= 32 &&
3976       MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
3977     return true;
3978 
3979   if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
3980        Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
3981        Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
3982       MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3983     return true;
3984 
3985   // There are other instructions that clear higher 32-bits.
3986   if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec ||
3987       Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec ||
3988       Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
3989       Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec ||
3990       Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec ||
3991       Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW ||
3992       Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec ||
3993       Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI ||
3994       Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI ||
3995       Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
3996       Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX ||
3997       Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
3998       Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ ||
3999       Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
4000       Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 ||
4001       Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
4002       Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 ||
4003       Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
4004       Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
4005       Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec ||
4006       Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec ||
4007       Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec ||
4008       Opcode == PPC::MFVSRWZ)
4009     return true;
4010 
4011   return false;
4012 }
4013 
4014 // This function returns true if the input MachineInstr is a TOC save
4015 // instruction.
4016 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
4017   if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
4018     return false;
4019   unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4020   unsigned StackOffset = MI.getOperand(1).getImm();
4021   Register StackReg = MI.getOperand(2).getReg();
4022   if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
4023     return true;
4024 
4025   return false;
4026 }
4027 
4028 // We limit the max depth to track incoming values of PHIs or binary ops
4029 // (e.g. AND) to avoid excessive cost.
4030 const unsigned MAX_DEPTH = 1;
4031 
4032 bool
4033 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
4034                                    const unsigned Depth) const {
4035   const MachineFunction *MF = MI.getParent()->getParent();
4036   const MachineRegisterInfo *MRI = &MF->getRegInfo();
4037 
4038   // If we know this instruction returns sign- or zero-extended result,
4039   // return true.
4040   if (SignExt ? isSignExtendingOp(MI):
4041                 isZeroExtendingOp(MI))
4042     return true;
4043 
4044   switch (MI.getOpcode()) {
4045   case PPC::COPY: {
4046     Register SrcReg = MI.getOperand(1).getReg();
4047 
4048     // In both ELFv1 and v2 ABI, method parameters and the return value
4049     // are sign- or zero-extended.
4050     if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
4051       const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
4052       // We check the ZExt/SExt flags for a method parameter.
4053       if (MI.getParent()->getBasicBlock() ==
4054           &MF->getFunction().getEntryBlock()) {
4055         Register VReg = MI.getOperand(0).getReg();
4056         if (MF->getRegInfo().isLiveIn(VReg))
4057           return SignExt ? FuncInfo->isLiveInSExt(VReg) :
4058                            FuncInfo->isLiveInZExt(VReg);
4059       }
4060 
4061       // For a method return value, we check the ZExt/SExt flags in attribute.
4062       // We assume the following code sequence for method call.
4063       //   ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
4064       //   BL8_NOP @func,...
4065       //   ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
4066       //   %5 = COPY %x3; G8RC:%5
4067       if (SrcReg == PPC::X3) {
4068         const MachineBasicBlock *MBB = MI.getParent();
4069         MachineBasicBlock::const_instr_iterator II =
4070           MachineBasicBlock::const_instr_iterator(&MI);
4071         if (II != MBB->instr_begin() &&
4072             (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
4073           const MachineInstr &CallMI = *(--II);
4074           if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
4075             const Function *CalleeFn =
4076               dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
4077             if (!CalleeFn)
4078               return false;
4079             const IntegerType *IntTy =
4080               dyn_cast<IntegerType>(CalleeFn->getReturnType());
4081             const AttributeSet &Attrs =
4082               CalleeFn->getAttributes().getRetAttributes();
4083             if (IntTy && IntTy->getBitWidth() <= 32)
4084               return Attrs.hasAttribute(SignExt ? Attribute::SExt :
4085                                                   Attribute::ZExt);
4086           }
4087         }
4088       }
4089     }
4090 
4091     // If this is a copy from another register, we recursively check source.
4092     if (!Register::isVirtualRegister(SrcReg))
4093       return false;
4094     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4095     if (SrcMI != NULL)
4096       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4097 
4098     return false;
4099   }
4100 
4101   case PPC::ANDI_rec:
4102   case PPC::ANDIS_rec:
4103   case PPC::ORI:
4104   case PPC::ORIS:
4105   case PPC::XORI:
4106   case PPC::XORIS:
4107   case PPC::ANDI8_rec:
4108   case PPC::ANDIS8_rec:
4109   case PPC::ORI8:
4110   case PPC::ORIS8:
4111   case PPC::XORI8:
4112   case PPC::XORIS8: {
4113     // logical operation with 16-bit immediate does not change the upper bits.
4114     // So, we track the operand register as we do for register copy.
4115     Register SrcReg = MI.getOperand(1).getReg();
4116     if (!Register::isVirtualRegister(SrcReg))
4117       return false;
4118     const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4119     if (SrcMI != NULL)
4120       return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
4121 
4122     return false;
4123   }
4124 
4125   // If all incoming values are sign-/zero-extended,
4126   // the output of OR, ISEL or PHI is also sign-/zero-extended.
4127   case PPC::OR:
4128   case PPC::OR8:
4129   case PPC::ISEL:
4130   case PPC::PHI: {
4131     if (Depth >= MAX_DEPTH)
4132       return false;
4133 
4134     // The input registers for PHI are operand 1, 3, ...
4135     // The input registers for others are operand 1 and 2.
4136     unsigned E = 3, D = 1;
4137     if (MI.getOpcode() == PPC::PHI) {
4138       E = MI.getNumOperands();
4139       D = 2;
4140     }
4141 
4142     for (unsigned I = 1; I != E; I += D) {
4143       if (MI.getOperand(I).isReg()) {
4144         Register SrcReg = MI.getOperand(I).getReg();
4145         if (!Register::isVirtualRegister(SrcReg))
4146           return false;
4147         const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
4148         if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
4149           return false;
4150       }
4151       else
4152         return false;
4153     }
4154     return true;
4155   }
4156 
4157   // If at least one of the incoming values of an AND is zero extended
4158   // then the output is also zero-extended. If both of the incoming values
4159   // are sign-extended then the output is also sign extended.
4160   case PPC::AND:
4161   case PPC::AND8: {
4162     if (Depth >= MAX_DEPTH)
4163        return false;
4164 
4165     assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
4166 
4167     Register SrcReg1 = MI.getOperand(1).getReg();
4168     Register SrcReg2 = MI.getOperand(2).getReg();
4169 
4170     if (!Register::isVirtualRegister(SrcReg1) ||
4171         !Register::isVirtualRegister(SrcReg2))
4172       return false;
4173 
4174     const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
4175     const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
4176     if (!MISrc1 || !MISrc2)
4177         return false;
4178 
4179     if(SignExt)
4180         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
4181                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4182     else
4183         return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
4184                isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
4185   }
4186 
4187   default:
4188     break;
4189   }
4190   return false;
4191 }
4192 
4193 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
4194   return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
4195 }
4196 
4197 namespace {
4198 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
4199   MachineInstr *Loop, *EndLoop, *LoopCount;
4200   MachineFunction *MF;
4201   const TargetInstrInfo *TII;
4202   int64_t TripCount;
4203 
4204 public:
4205   PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
4206                        MachineInstr *LoopCount)
4207       : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
4208         MF(Loop->getParent()->getParent()),
4209         TII(MF->getSubtarget().getInstrInfo()) {
4210     // Inspect the Loop instruction up-front, as it may be deleted when we call
4211     // createTripCountGreaterCondition.
4212     if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
4213       TripCount = LoopCount->getOperand(1).getImm();
4214     else
4215       TripCount = -1;
4216   }
4217 
4218   bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
4219     // Only ignore the terminator.
4220     return MI == EndLoop;
4221   }
4222 
4223   Optional<bool>
4224   createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
4225                                   SmallVectorImpl<MachineOperand> &Cond) override {
4226     if (TripCount == -1) {
4227       // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4228       // so we don't need to generate any thing here.
4229       Cond.push_back(MachineOperand::CreateImm(0));
4230       Cond.push_back(MachineOperand::CreateReg(
4231           MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
4232           true));
4233       return {};
4234     }
4235 
4236     return TripCount > TC;
4237   }
4238 
4239   void setPreheader(MachineBasicBlock *NewPreheader) override {
4240     // Do nothing. We want the LOOP setup instruction to stay in the *old*
4241     // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
4242   }
4243 
4244   void adjustTripCount(int TripCountAdjust) override {
4245     // If the loop trip count is a compile-time value, then just change the
4246     // value.
4247     if (LoopCount->getOpcode() == PPC::LI8 ||
4248         LoopCount->getOpcode() == PPC::LI) {
4249       int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
4250       LoopCount->getOperand(1).setImm(TripCount);
4251       return;
4252     }
4253 
4254     // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
4255     // so we don't need to generate any thing here.
4256   }
4257 
4258   void disposed() override {
4259     Loop->eraseFromParent();
4260     // Ensure the loop setup instruction is deleted too.
4261     LoopCount->eraseFromParent();
4262   }
4263 };
4264 } // namespace
4265 
4266 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4267 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4268   // We really "analyze" only hardware loops right now.
4269   MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4270   MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4271   if (Preheader == LoopBB)
4272     Preheader = *std::next(LoopBB->pred_begin());
4273   MachineFunction *MF = Preheader->getParent();
4274 
4275   if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
4276     SmallPtrSet<MachineBasicBlock *, 8> Visited;
4277     if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
4278       Register LoopCountReg = LoopInst->getOperand(0).getReg();
4279       MachineRegisterInfo &MRI = MF->getRegInfo();
4280       MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
4281       return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
4282     }
4283   }
4284   return nullptr;
4285 }
4286 
4287 MachineInstr *PPCInstrInfo::findLoopInstr(
4288     MachineBasicBlock &PreHeader,
4289     SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
4290 
4291   unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
4292 
4293   // The loop set-up instruction should be in preheader
4294   for (auto &I : PreHeader.instrs())
4295     if (I.getOpcode() == LOOPi)
4296       return &I;
4297   return nullptr;
4298 }
4299 
4300 // Return true if get the base operand, byte offset of an instruction and the
4301 // memory width. Width is the size of memory that is being loaded/stored.
4302 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
4303     const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
4304     unsigned &Width, const TargetRegisterInfo *TRI) const {
4305   if (!LdSt.mayLoadOrStore())
4306     return false;
4307 
4308   // Handle only loads/stores with base register followed by immediate offset.
4309   if (LdSt.getNumExplicitOperands() != 3)
4310     return false;
4311   if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg())
4312     return false;
4313 
4314   if (!LdSt.hasOneMemOperand())
4315     return false;
4316 
4317   Width = (*LdSt.memoperands_begin())->getSize();
4318   Offset = LdSt.getOperand(1).getImm();
4319   BaseReg = &LdSt.getOperand(2);
4320   return true;
4321 }
4322 
4323 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
4324     const MachineInstr &MIa, const MachineInstr &MIb) const {
4325   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
4326   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
4327 
4328   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
4329       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4330     return false;
4331 
4332   // Retrieve the base register, offset from the base register and width. Width
4333   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4).  If
4334   // base registers are identical, and the offset of a lower memory access +
4335   // the width doesn't overlap the offset of a higher memory access,
4336   // then the memory accesses are different.
4337   const TargetRegisterInfo *TRI = &getRegisterInfo();
4338   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
4339   int64_t OffsetA = 0, OffsetB = 0;
4340   unsigned int WidthA = 0, WidthB = 0;
4341   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
4342       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
4343     if (BaseOpA->isIdenticalTo(*BaseOpB)) {
4344       int LowOffset = std::min(OffsetA, OffsetB);
4345       int HighOffset = std::max(OffsetA, OffsetB);
4346       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4347       if (LowOffset + LowWidth <= HighOffset)
4348         return true;
4349     }
4350   }
4351   return false;
4352 }
4353