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