LLVM API Documentation

PPCInstrInfo.cpp
Go to the documentation of this file.
00001 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the PowerPC implementation of the TargetInstrInfo class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCInstrInfo.h"
00015 #include "MCTargetDesc/PPCPredicates.h"
00016 #include "PPC.h"
00017 #include "PPCHazardRecognizers.h"
00018 #include "PPCInstrBuilder.h"
00019 #include "PPCMachineFunctionInfo.h"
00020 #include "PPCTargetMachine.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunctionPass.h"
00026 #include "llvm/CodeGen/MachineInstrBuilder.h"
00027 #include "llvm/CodeGen/MachineMemOperand.h"
00028 #include "llvm/CodeGen/MachineRegisterInfo.h"
00029 #include "llvm/CodeGen/PseudoSourceValue.h"
00030 #include "llvm/CodeGen/ScheduleDAG.h"
00031 #include "llvm/CodeGen/SlotIndexes.h"
00032 #include "llvm/CodeGen/StackMaps.h"
00033 #include "llvm/MC/MCAsmInfo.h"
00034 #include "llvm/Support/CommandLine.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/TargetRegistry.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 
00040 using namespace llvm;
00041 
00042 #define DEBUG_TYPE "ppc-instr-info"
00043 
00044 #define GET_INSTRMAP_INFO
00045 #define GET_INSTRINFO_CTOR_DTOR
00046 #include "PPCGenInstrInfo.inc"
00047 
00048 static cl::
00049 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
00050             cl::desc("Disable analysis for CTR loops"));
00051 
00052 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
00053 cl::desc("Disable compare instruction optimization"), cl::Hidden);
00054 
00055 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
00056 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
00057 cl::Hidden);
00058 
00059 // Pin the vtable to this file.
00060 void PPCInstrInfo::anchor() {}
00061 
00062 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
00063     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
00064       Subtarget(STI), RI(STI) {}
00065 
00066 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
00067 /// this target when scheduling the DAG.
00068 ScheduleHazardRecognizer *
00069 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
00070                                            const ScheduleDAG *DAG) const {
00071   unsigned Directive =
00072       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
00073   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
00074       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
00075     const InstrItineraryData *II =
00076         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
00077     return new ScoreboardHazardRecognizer(II, DAG);
00078   }
00079 
00080   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
00081 }
00082 
00083 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
00084 /// to use for this target when scheduling the DAG.
00085 ScheduleHazardRecognizer *
00086 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
00087                                                  const ScheduleDAG *DAG) const {
00088   unsigned Directive =
00089       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
00090 
00091   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
00092     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
00093 
00094   // Most subtargets use a PPC970 recognizer.
00095   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
00096       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
00097     assert(DAG->TII && "No InstrInfo?");
00098 
00099     return new PPCHazardRecognizer970(*DAG);
00100   }
00101 
00102   return new ScoreboardHazardRecognizer(II, DAG);
00103 }
00104 
00105 
00106 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
00107                                     const MachineInstr *DefMI, unsigned DefIdx,
00108                                     const MachineInstr *UseMI,
00109                                     unsigned UseIdx) const {
00110   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
00111                                                    UseMI, UseIdx);
00112 
00113   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
00114   unsigned Reg = DefMO.getReg();
00115 
00116   const TargetRegisterInfo *TRI = &getRegisterInfo();
00117   bool IsRegCR;
00118   if (TRI->isVirtualRegister(Reg)) {
00119     const MachineRegisterInfo *MRI =
00120       &DefMI->getParent()->getParent()->getRegInfo();
00121     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
00122               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
00123   } else {
00124     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
00125               PPC::CRBITRCRegClass.contains(Reg);
00126   }
00127 
00128   if (UseMI->isBranch() && IsRegCR) {
00129     if (Latency < 0)
00130       Latency = getInstrLatency(ItinData, DefMI);
00131 
00132     // On some cores, there is an additional delay between writing to a condition
00133     // register, and using it from a branch.
00134     unsigned Directive = Subtarget.getDarwinDirective();
00135     switch (Directive) {
00136     default: break;
00137     case PPC::DIR_7400:
00138     case PPC::DIR_750:
00139     case PPC::DIR_970:
00140     case PPC::DIR_E5500:
00141     case PPC::DIR_PWR4:
00142     case PPC::DIR_PWR5:
00143     case PPC::DIR_PWR5X:
00144     case PPC::DIR_PWR6:
00145     case PPC::DIR_PWR6X:
00146     case PPC::DIR_PWR7:
00147     case PPC::DIR_PWR8:
00148       Latency += 2;
00149       break;
00150     }
00151   }
00152 
00153   return Latency;
00154 }
00155 
00156 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
00157 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
00158                                          unsigned &SrcReg, unsigned &DstReg,
00159                                          unsigned &SubIdx) const {
00160   switch (MI.getOpcode()) {
00161   default: return false;
00162   case PPC::EXTSW:
00163   case PPC::EXTSW_32_64:
00164     SrcReg = MI.getOperand(1).getReg();
00165     DstReg = MI.getOperand(0).getReg();
00166     SubIdx = PPC::sub_32;
00167     return true;
00168   }
00169 }
00170 
00171 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
00172                                            int &FrameIndex) const {
00173   // Note: This list must be kept consistent with LoadRegFromStackSlot.
00174   switch (MI->getOpcode()) {
00175   default: break;
00176   case PPC::LD:
00177   case PPC::LWZ:
00178   case PPC::LFS:
00179   case PPC::LFD:
00180   case PPC::RESTORE_CR:
00181   case PPC::RESTORE_CRBIT:
00182   case PPC::LVX:
00183   case PPC::LXVD2X:
00184   case PPC::QVLFDX:
00185   case PPC::QVLFSXs:
00186   case PPC::QVLFDXb:
00187   case PPC::RESTORE_VRSAVE:
00188     // Check for the operands added by addFrameReference (the immediate is the
00189     // offset which defaults to 0).
00190     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00191         MI->getOperand(2).isFI()) {
00192       FrameIndex = MI->getOperand(2).getIndex();
00193       return MI->getOperand(0).getReg();
00194     }
00195     break;
00196   }
00197   return 0;
00198 }
00199 
00200 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
00201                                           int &FrameIndex) const {
00202   // Note: This list must be kept consistent with StoreRegToStackSlot.
00203   switch (MI->getOpcode()) {
00204   default: break;
00205   case PPC::STD:
00206   case PPC::STW:
00207   case PPC::STFS:
00208   case PPC::STFD:
00209   case PPC::SPILL_CR:
00210   case PPC::SPILL_CRBIT:
00211   case PPC::STVX:
00212   case PPC::STXVD2X:
00213   case PPC::QVSTFDX:
00214   case PPC::QVSTFSXs:
00215   case PPC::QVSTFDXb:
00216   case PPC::SPILL_VRSAVE:
00217     // Check for the operands added by addFrameReference (the immediate is the
00218     // offset which defaults to 0).
00219     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00220         MI->getOperand(2).isFI()) {
00221       FrameIndex = MI->getOperand(2).getIndex();
00222       return MI->getOperand(0).getReg();
00223     }
00224     break;
00225   }
00226   return 0;
00227 }
00228 
00229 // commuteInstruction - We can commute rlwimi instructions, but only if the
00230 // rotate amt is zero.  We also have to munge the immediates a bit.
00231 MachineInstr *
00232 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
00233   MachineFunction &MF = *MI->getParent()->getParent();
00234 
00235   // Normal instructions can be commuted the obvious way.
00236   if (MI->getOpcode() != PPC::RLWIMI &&
00237       MI->getOpcode() != PPC::RLWIMIo)
00238     return TargetInstrInfo::commuteInstruction(MI, NewMI);
00239   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
00240   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
00241   // changing the relative order of the mask operands might change what happens
00242   // to the high-bits of the mask (and, thus, the result).
00243 
00244   // Cannot commute if it has a non-zero rotate count.
00245   if (MI->getOperand(3).getImm() != 0)
00246     return nullptr;
00247 
00248   // If we have a zero rotate count, we have:
00249   //   M = mask(MB,ME)
00250   //   Op0 = (Op1 & ~M) | (Op2 & M)
00251   // Change this to:
00252   //   M = mask((ME+1)&31, (MB-1)&31)
00253   //   Op0 = (Op2 & ~M) | (Op1 & M)
00254 
00255   // Swap op1/op2
00256   unsigned Reg0 = MI->getOperand(0).getReg();
00257   unsigned Reg1 = MI->getOperand(1).getReg();
00258   unsigned Reg2 = MI->getOperand(2).getReg();
00259   unsigned SubReg1 = MI->getOperand(1).getSubReg();
00260   unsigned SubReg2 = MI->getOperand(2).getSubReg();
00261   bool Reg1IsKill = MI->getOperand(1).isKill();
00262   bool Reg2IsKill = MI->getOperand(2).isKill();
00263   bool ChangeReg0 = false;
00264   // If machine instrs are no longer in two-address forms, update
00265   // destination register as well.
00266   if (Reg0 == Reg1) {
00267     // Must be two address instruction!
00268     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
00269            "Expecting a two-address instruction!");
00270     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
00271     Reg2IsKill = false;
00272     ChangeReg0 = true;
00273   }
00274 
00275   // Masks.
00276   unsigned MB = MI->getOperand(4).getImm();
00277   unsigned ME = MI->getOperand(5).getImm();
00278 
00279   if (NewMI) {
00280     // Create a new instruction.
00281     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
00282     bool Reg0IsDead = MI->getOperand(0).isDead();
00283     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
00284       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
00285       .addReg(Reg2, getKillRegState(Reg2IsKill))
00286       .addReg(Reg1, getKillRegState(Reg1IsKill))
00287       .addImm((ME+1) & 31)
00288       .addImm((MB-1) & 31);
00289   }
00290 
00291   if (ChangeReg0) {
00292     MI->getOperand(0).setReg(Reg2);
00293     MI->getOperand(0).setSubReg(SubReg2);
00294   }
00295   MI->getOperand(2).setReg(Reg1);
00296   MI->getOperand(1).setReg(Reg2);
00297   MI->getOperand(2).setSubReg(SubReg1);
00298   MI->getOperand(1).setSubReg(SubReg2);
00299   MI->getOperand(2).setIsKill(Reg1IsKill);
00300   MI->getOperand(1).setIsKill(Reg2IsKill);
00301 
00302   // Swap the mask around.
00303   MI->getOperand(4).setImm((ME+1) & 31);
00304   MI->getOperand(5).setImm((MB-1) & 31);
00305   return MI;
00306 }
00307 
00308 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
00309                                          unsigned &SrcOpIdx2) const {
00310   // For VSX A-Type FMA instructions, it is the first two operands that can be
00311   // commuted, however, because the non-encoded tied input operand is listed
00312   // first, the operands to swap are actually the second and third.
00313 
00314   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
00315   if (AltOpc == -1)
00316     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
00317 
00318   SrcOpIdx1 = 2;
00319   SrcOpIdx2 = 3;
00320   return true;
00321 }
00322 
00323 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
00324                               MachineBasicBlock::iterator MI) const {
00325   // This function is used for scheduling, and the nop wanted here is the type
00326   // that terminates dispatch groups on the POWER cores.
00327   unsigned Directive = Subtarget.getDarwinDirective();
00328   unsigned Opcode;
00329   switch (Directive) {
00330   default:            Opcode = PPC::NOP; break;
00331   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
00332   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
00333   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
00334   }
00335 
00336   DebugLoc DL;
00337   BuildMI(MBB, MI, DL, get(Opcode));
00338 }
00339 
00340 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
00341 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
00342   NopInst.setOpcode(PPC::NOP);
00343 }
00344 
00345 // Branch analysis.
00346 // Note: If the condition register is set to CTR or CTR8 then this is a
00347 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
00348 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
00349                                  MachineBasicBlock *&FBB,
00350                                  SmallVectorImpl<MachineOperand> &Cond,
00351                                  bool AllowModify) const {
00352   bool isPPC64 = Subtarget.isPPC64();
00353 
00354   // If the block has no terminators, it just falls into the block after it.
00355   MachineBasicBlock::iterator I = MBB.end();
00356   if (I == MBB.begin())
00357     return false;
00358   --I;
00359   while (I->isDebugValue()) {
00360     if (I == MBB.begin())
00361       return false;
00362     --I;
00363   }
00364   if (!isUnpredicatedTerminator(I))
00365     return false;
00366 
00367   // Get the last instruction in the block.
00368   MachineInstr *LastInst = I;
00369 
00370   // If there is only one terminator instruction, process it.
00371   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
00372     if (LastInst->getOpcode() == PPC::B) {
00373       if (!LastInst->getOperand(0).isMBB())
00374         return true;
00375       TBB = LastInst->getOperand(0).getMBB();
00376       return false;
00377     } else if (LastInst->getOpcode() == PPC::BCC) {
00378       if (!LastInst->getOperand(2).isMBB())
00379         return true;
00380       // Block ends with fall-through condbranch.
00381       TBB = LastInst->getOperand(2).getMBB();
00382       Cond.push_back(LastInst->getOperand(0));
00383       Cond.push_back(LastInst->getOperand(1));
00384       return false;
00385     } else if (LastInst->getOpcode() == PPC::BC) {
00386       if (!LastInst->getOperand(1).isMBB())
00387         return true;
00388       // Block ends with fall-through condbranch.
00389       TBB = LastInst->getOperand(1).getMBB();
00390       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00391       Cond.push_back(LastInst->getOperand(0));
00392       return false;
00393     } else if (LastInst->getOpcode() == PPC::BCn) {
00394       if (!LastInst->getOperand(1).isMBB())
00395         return true;
00396       // Block ends with fall-through condbranch.
00397       TBB = LastInst->getOperand(1).getMBB();
00398       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00399       Cond.push_back(LastInst->getOperand(0));
00400       return false;
00401     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
00402                LastInst->getOpcode() == PPC::BDNZ) {
00403       if (!LastInst->getOperand(0).isMBB())
00404         return true;
00405       if (DisableCTRLoopAnal)
00406         return true;
00407       TBB = LastInst->getOperand(0).getMBB();
00408       Cond.push_back(MachineOperand::CreateImm(1));
00409       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00410                                                true));
00411       return false;
00412     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
00413                LastInst->getOpcode() == PPC::BDZ) {
00414       if (!LastInst->getOperand(0).isMBB())
00415         return true;
00416       if (DisableCTRLoopAnal)
00417         return true;
00418       TBB = LastInst->getOperand(0).getMBB();
00419       Cond.push_back(MachineOperand::CreateImm(0));
00420       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00421                                                true));
00422       return false;
00423     }
00424 
00425     // Otherwise, don't know what this is.
00426     return true;
00427   }
00428 
00429   // Get the instruction before it if it's a terminator.
00430   MachineInstr *SecondLastInst = I;
00431 
00432   // If there are three terminators, we don't know what sort of block this is.
00433   if (SecondLastInst && I != MBB.begin() &&
00434       isUnpredicatedTerminator(--I))
00435     return true;
00436 
00437   // If the block ends with PPC::B and PPC:BCC, handle it.
00438   if (SecondLastInst->getOpcode() == PPC::BCC &&
00439       LastInst->getOpcode() == PPC::B) {
00440     if (!SecondLastInst->getOperand(2).isMBB() ||
00441         !LastInst->getOperand(0).isMBB())
00442       return true;
00443     TBB =  SecondLastInst->getOperand(2).getMBB();
00444     Cond.push_back(SecondLastInst->getOperand(0));
00445     Cond.push_back(SecondLastInst->getOperand(1));
00446     FBB = LastInst->getOperand(0).getMBB();
00447     return false;
00448   } else if (SecondLastInst->getOpcode() == PPC::BC &&
00449       LastInst->getOpcode() == PPC::B) {
00450     if (!SecondLastInst->getOperand(1).isMBB() ||
00451         !LastInst->getOperand(0).isMBB())
00452       return true;
00453     TBB =  SecondLastInst->getOperand(1).getMBB();
00454     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00455     Cond.push_back(SecondLastInst->getOperand(0));
00456     FBB = LastInst->getOperand(0).getMBB();
00457     return false;
00458   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
00459       LastInst->getOpcode() == PPC::B) {
00460     if (!SecondLastInst->getOperand(1).isMBB() ||
00461         !LastInst->getOperand(0).isMBB())
00462       return true;
00463     TBB =  SecondLastInst->getOperand(1).getMBB();
00464     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00465     Cond.push_back(SecondLastInst->getOperand(0));
00466     FBB = LastInst->getOperand(0).getMBB();
00467     return false;
00468   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
00469               SecondLastInst->getOpcode() == PPC::BDNZ) &&
00470       LastInst->getOpcode() == PPC::B) {
00471     if (!SecondLastInst->getOperand(0).isMBB() ||
00472         !LastInst->getOperand(0).isMBB())
00473       return true;
00474     if (DisableCTRLoopAnal)
00475       return true;
00476     TBB = SecondLastInst->getOperand(0).getMBB();
00477     Cond.push_back(MachineOperand::CreateImm(1));
00478     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00479                                              true));
00480     FBB = LastInst->getOperand(0).getMBB();
00481     return false;
00482   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
00483               SecondLastInst->getOpcode() == PPC::BDZ) &&
00484       LastInst->getOpcode() == PPC::B) {
00485     if (!SecondLastInst->getOperand(0).isMBB() ||
00486         !LastInst->getOperand(0).isMBB())
00487       return true;
00488     if (DisableCTRLoopAnal)
00489       return true;
00490     TBB = SecondLastInst->getOperand(0).getMBB();
00491     Cond.push_back(MachineOperand::CreateImm(0));
00492     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00493                                              true));
00494     FBB = LastInst->getOperand(0).getMBB();
00495     return false;
00496   }
00497 
00498   // If the block ends with two PPC:Bs, handle it.  The second one is not
00499   // executed, so remove it.
00500   if (SecondLastInst->getOpcode() == PPC::B &&
00501       LastInst->getOpcode() == PPC::B) {
00502     if (!SecondLastInst->getOperand(0).isMBB())
00503       return true;
00504     TBB = SecondLastInst->getOperand(0).getMBB();
00505     I = LastInst;
00506     if (AllowModify)
00507       I->eraseFromParent();
00508     return false;
00509   }
00510 
00511   // Otherwise, can't handle this.
00512   return true;
00513 }
00514 
00515 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
00516   MachineBasicBlock::iterator I = MBB.end();
00517   if (I == MBB.begin()) return 0;
00518   --I;
00519   while (I->isDebugValue()) {
00520     if (I == MBB.begin())
00521       return 0;
00522     --I;
00523   }
00524   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
00525       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00526       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00527       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00528     return 0;
00529 
00530   // Remove the branch.
00531   I->eraseFromParent();
00532 
00533   I = MBB.end();
00534 
00535   if (I == MBB.begin()) return 1;
00536   --I;
00537   if (I->getOpcode() != PPC::BCC &&
00538       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00539       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00540       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00541     return 1;
00542 
00543   // Remove the branch.
00544   I->eraseFromParent();
00545   return 2;
00546 }
00547 
00548 unsigned
00549 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
00550                            MachineBasicBlock *FBB,
00551                            const SmallVectorImpl<MachineOperand> &Cond,
00552                            DebugLoc DL) const {
00553   // Shouldn't be a fall through.
00554   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
00555   assert((Cond.size() == 2 || Cond.size() == 0) &&
00556          "PPC branch conditions have two components!");
00557 
00558   bool isPPC64 = Subtarget.isPPC64();
00559 
00560   // One-way branch.
00561   if (!FBB) {
00562     if (Cond.empty())   // Unconditional branch
00563       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
00564     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00565       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00566                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00567                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00568     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00569       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00570     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00571       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00572     else                // Conditional branch
00573       BuildMI(&MBB, DL, get(PPC::BCC))
00574         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00575     return 1;
00576   }
00577 
00578   // Two-way Conditional Branch.
00579   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00580     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00581                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00582                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00583   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00584     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00585   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00586     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00587   else
00588     BuildMI(&MBB, DL, get(PPC::BCC))
00589       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00590   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
00591   return 2;
00592 }
00593 
00594 // Select analysis.
00595 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
00596                 const SmallVectorImpl<MachineOperand> &Cond,
00597                 unsigned TrueReg, unsigned FalseReg,
00598                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
00599   if (!Subtarget.hasISEL())
00600     return false;
00601 
00602   if (Cond.size() != 2)
00603     return false;
00604 
00605   // If this is really a bdnz-like condition, then it cannot be turned into a
00606   // select.
00607   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00608     return false;
00609 
00610   // Check register classes.
00611   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00612   const TargetRegisterClass *RC =
00613     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00614   if (!RC)
00615     return false;
00616 
00617   // isel is for regular integer GPRs only.
00618   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
00619       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
00620       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
00621       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
00622     return false;
00623 
00624   // FIXME: These numbers are for the A2, how well they work for other cores is
00625   // an open question. On the A2, the isel instruction has a 2-cycle latency
00626   // but single-cycle throughput. These numbers are used in combination with
00627   // the MispredictPenalty setting from the active SchedMachineModel.
00628   CondCycles = 1;
00629   TrueCycles = 1;
00630   FalseCycles = 1;
00631 
00632   return true;
00633 }
00634 
00635 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
00636                                 MachineBasicBlock::iterator MI, DebugLoc dl,
00637                                 unsigned DestReg,
00638                                 const SmallVectorImpl<MachineOperand> &Cond,
00639                                 unsigned TrueReg, unsigned FalseReg) const {
00640   assert(Cond.size() == 2 &&
00641          "PPC branch conditions have two components!");
00642 
00643   assert(Subtarget.hasISEL() &&
00644          "Cannot insert select on target without ISEL support");
00645 
00646   // Get the register classes.
00647   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00648   const TargetRegisterClass *RC =
00649     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00650   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
00651 
00652   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
00653                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
00654   assert((Is64Bit ||
00655           PPC::GPRCRegClass.hasSubClassEq(RC) ||
00656           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
00657          "isel is for regular integer GPRs only");
00658 
00659   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
00660   unsigned SelectPred = Cond[0].getImm();
00661 
00662   unsigned SubIdx;
00663   bool SwapOps;
00664   switch (SelectPred) {
00665   default: llvm_unreachable("invalid predicate for isel");
00666   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
00667   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
00668   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
00669   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
00670   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
00671   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
00672   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
00673   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
00674   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
00675   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
00676   }
00677 
00678   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
00679            SecondReg = SwapOps ? TrueReg  : FalseReg;
00680 
00681   // The first input register of isel cannot be r0. If it is a member
00682   // of a register class that can be r0, then copy it first (the
00683   // register allocator should eliminate the copy).
00684   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
00685       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
00686     const TargetRegisterClass *FirstRC =
00687       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
00688         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
00689     unsigned OldFirstReg = FirstReg;
00690     FirstReg = MRI.createVirtualRegister(FirstRC);
00691     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
00692       .addReg(OldFirstReg);
00693   }
00694 
00695   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
00696     .addReg(FirstReg).addReg(SecondReg)
00697     .addReg(Cond[1].getReg(), 0, SubIdx);
00698 }
00699 
00700 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
00701                                MachineBasicBlock::iterator I, DebugLoc DL,
00702                                unsigned DestReg, unsigned SrcReg,
00703                                bool KillSrc) const {
00704   // We can end up with self copies and similar things as a result of VSX copy
00705   // legalization. Promote them here.
00706   const TargetRegisterInfo *TRI = &getRegisterInfo();
00707   if (PPC::F8RCRegClass.contains(DestReg) &&
00708       PPC::VSRCRegClass.contains(SrcReg)) {
00709     unsigned SuperReg =
00710       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
00711 
00712     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00713       llvm_unreachable("nop VSX copy");
00714 
00715     DestReg = SuperReg;
00716   } else if (PPC::VRRCRegClass.contains(DestReg) &&
00717              PPC::VSRCRegClass.contains(SrcReg)) {
00718     unsigned SuperReg =
00719       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
00720 
00721     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00722       llvm_unreachable("nop VSX copy");
00723 
00724     DestReg = SuperReg;
00725   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
00726              PPC::VSRCRegClass.contains(DestReg)) {
00727     unsigned SuperReg =
00728       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
00729 
00730     if (VSXSelfCopyCrash && DestReg == SuperReg)
00731       llvm_unreachable("nop VSX copy");
00732 
00733     SrcReg = SuperReg;
00734   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
00735              PPC::VSRCRegClass.contains(DestReg)) {
00736     unsigned SuperReg =
00737       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
00738 
00739     if (VSXSelfCopyCrash && DestReg == SuperReg)
00740       llvm_unreachable("nop VSX copy");
00741 
00742     SrcReg = SuperReg;
00743   }
00744 
00745   unsigned Opc;
00746   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
00747     Opc = PPC::OR;
00748   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
00749     Opc = PPC::OR8;
00750   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
00751     Opc = PPC::FMR;
00752   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
00753     Opc = PPC::MCRF;
00754   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
00755     Opc = PPC::VOR;
00756   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
00757     // There are two different ways this can be done:
00758     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
00759     //      issue in VSU pipeline 0.
00760     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
00761     //      can go to either pipeline.
00762     // We'll always use xxlor here, because in practically all cases where
00763     // copies are generated, they are close enough to some use that the
00764     // lower-latency form is preferable.
00765     Opc = PPC::XXLOR;
00766   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
00767     Opc = PPC::XXLORf;
00768   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
00769     Opc = PPC::QVFMR;
00770   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
00771     Opc = PPC::QVFMRs;
00772   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
00773     Opc = PPC::QVFMRb;
00774   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
00775     Opc = PPC::CROR;
00776   else
00777     llvm_unreachable("Impossible reg-to-reg copy");
00778 
00779   const MCInstrDesc &MCID = get(Opc);
00780   if (MCID.getNumOperands() == 3)
00781     BuildMI(MBB, I, DL, MCID, DestReg)
00782       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
00783   else
00784     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
00785 }
00786 
00787 // This function returns true if a CR spill is necessary and false otherwise.
00788 bool
00789 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
00790                                   unsigned SrcReg, bool isKill,
00791                                   int FrameIdx,
00792                                   const TargetRegisterClass *RC,
00793                                   SmallVectorImpl<MachineInstr*> &NewMIs,
00794                                   bool &NonRI, bool &SpillsVRS) const{
00795   // Note: If additional store instructions are added here,
00796   // update isStoreToStackSlot.
00797 
00798   DebugLoc DL;
00799   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00800       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00801     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
00802                                        .addReg(SrcReg,
00803                                                getKillRegState(isKill)),
00804                                        FrameIdx));
00805   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00806              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00807     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
00808                                        .addReg(SrcReg,
00809                                                getKillRegState(isKill)),
00810                                        FrameIdx));
00811   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00812     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
00813                                        .addReg(SrcReg,
00814                                                getKillRegState(isKill)),
00815                                        FrameIdx));
00816   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00817     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
00818                                        .addReg(SrcReg,
00819                                                getKillRegState(isKill)),
00820                                        FrameIdx));
00821   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00822     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
00823                                        .addReg(SrcReg,
00824                                                getKillRegState(isKill)),
00825                                        FrameIdx));
00826     return true;
00827   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00828     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
00829                                        .addReg(SrcReg,
00830                                                getKillRegState(isKill)),
00831                                        FrameIdx));
00832     return true;
00833   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00834     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
00835                                        .addReg(SrcReg,
00836                                                getKillRegState(isKill)),
00837                                        FrameIdx));
00838     NonRI = true;
00839   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00840     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
00841                                        .addReg(SrcReg,
00842                                                getKillRegState(isKill)),
00843                                        FrameIdx));
00844     NonRI = true;
00845   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00846     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
00847                                        .addReg(SrcReg,
00848                                                getKillRegState(isKill)),
00849                                        FrameIdx));
00850     NonRI = true;
00851   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00852     assert(Subtarget.isDarwin() &&
00853            "VRSAVE only needs spill/restore on Darwin");
00854     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
00855                                        .addReg(SrcReg,
00856                                                getKillRegState(isKill)),
00857                                        FrameIdx));
00858     SpillsVRS = true;
00859   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
00860     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
00861                                        .addReg(SrcReg,
00862                                                getKillRegState(isKill)),
00863                                        FrameIdx));
00864     NonRI = true;
00865   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
00866     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
00867                                        .addReg(SrcReg,
00868                                                getKillRegState(isKill)),
00869                                        FrameIdx));
00870     NonRI = true;
00871   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
00872     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
00873                                        .addReg(SrcReg,
00874                                                getKillRegState(isKill)),
00875                                        FrameIdx));
00876     NonRI = true;
00877   } else {
00878     llvm_unreachable("Unknown regclass!");
00879   }
00880 
00881   return false;
00882 }
00883 
00884 void
00885 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
00886                                   MachineBasicBlock::iterator MI,
00887                                   unsigned SrcReg, bool isKill, int FrameIdx,
00888                                   const TargetRegisterClass *RC,
00889                                   const TargetRegisterInfo *TRI) const {
00890   MachineFunction &MF = *MBB.getParent();
00891   SmallVector<MachineInstr*, 4> NewMIs;
00892 
00893   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00894   FuncInfo->setHasSpills();
00895 
00896   bool NonRI = false, SpillsVRS = false;
00897   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
00898                           NonRI, SpillsVRS))
00899     FuncInfo->setSpillsCR();
00900 
00901   if (SpillsVRS)
00902     FuncInfo->setSpillsVRSAVE();
00903 
00904   if (NonRI)
00905     FuncInfo->setHasNonRISpills();
00906 
00907   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00908     MBB.insert(MI, NewMIs[i]);
00909 
00910   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00911   MachineMemOperand *MMO =
00912     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00913                             MachineMemOperand::MOStore,
00914                             MFI.getObjectSize(FrameIdx),
00915                             MFI.getObjectAlignment(FrameIdx));
00916   NewMIs.back()->addMemOperand(MF, MMO);
00917 }
00918 
00919 bool
00920 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
00921                                    unsigned DestReg, int FrameIdx,
00922                                    const TargetRegisterClass *RC,
00923                                    SmallVectorImpl<MachineInstr*> &NewMIs,
00924                                    bool &NonRI, bool &SpillsVRS) const{
00925   // Note: If additional load instructions are added here,
00926   // update isLoadFromStackSlot.
00927 
00928   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00929       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00930     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
00931                                                DestReg), FrameIdx));
00932   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00933              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00934     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
00935                                        FrameIdx));
00936   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00937     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
00938                                        FrameIdx));
00939   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00940     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
00941                                        FrameIdx));
00942   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00943     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00944                                                get(PPC::RESTORE_CR), DestReg),
00945                                        FrameIdx));
00946     return true;
00947   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00948     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00949                                                get(PPC::RESTORE_CRBIT), DestReg),
00950                                        FrameIdx));
00951     return true;
00952   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00953     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
00954                                        FrameIdx));
00955     NonRI = true;
00956   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00957     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
00958                                        FrameIdx));
00959     NonRI = true;
00960   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00961     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
00962                                        FrameIdx));
00963     NonRI = true;
00964   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00965     assert(Subtarget.isDarwin() &&
00966            "VRSAVE only needs spill/restore on Darwin");
00967     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00968                                                get(PPC::RESTORE_VRSAVE),
00969                                                DestReg),
00970                                        FrameIdx));
00971     SpillsVRS = true;
00972   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
00973     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
00974                                        FrameIdx));
00975     NonRI = true;
00976   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
00977     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
00978                                        FrameIdx));
00979     NonRI = true;
00980   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
00981     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
00982                                        FrameIdx));
00983     NonRI = true;
00984   } else {
00985     llvm_unreachable("Unknown regclass!");
00986   }
00987 
00988   return false;
00989 }
00990 
00991 void
00992 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
00993                                    MachineBasicBlock::iterator MI,
00994                                    unsigned DestReg, int FrameIdx,
00995                                    const TargetRegisterClass *RC,
00996                                    const TargetRegisterInfo *TRI) const {
00997   MachineFunction &MF = *MBB.getParent();
00998   SmallVector<MachineInstr*, 4> NewMIs;
00999   DebugLoc DL;
01000   if (MI != MBB.end()) DL = MI->getDebugLoc();
01001 
01002   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
01003   FuncInfo->setHasSpills();
01004 
01005   bool NonRI = false, SpillsVRS = false;
01006   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
01007                            NonRI, SpillsVRS))
01008     FuncInfo->setSpillsCR();
01009 
01010   if (SpillsVRS)
01011     FuncInfo->setSpillsVRSAVE();
01012 
01013   if (NonRI)
01014     FuncInfo->setHasNonRISpills();
01015 
01016   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
01017     MBB.insert(MI, NewMIs[i]);
01018 
01019   const MachineFrameInfo &MFI = *MF.getFrameInfo();
01020   MachineMemOperand *MMO =
01021     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
01022                             MachineMemOperand::MOLoad,
01023                             MFI.getObjectSize(FrameIdx),
01024                             MFI.getObjectAlignment(FrameIdx));
01025   NewMIs.back()->addMemOperand(MF, MMO);
01026 }
01027 
01028 bool PPCInstrInfo::
01029 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
01030   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
01031   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
01032     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
01033   else
01034     // Leave the CR# the same, but invert the condition.
01035     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
01036   return false;
01037 }
01038 
01039 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
01040                              unsigned Reg, MachineRegisterInfo *MRI) const {
01041   // For some instructions, it is legal to fold ZERO into the RA register field.
01042   // A zero immediate should always be loaded with a single li.
01043   unsigned DefOpc = DefMI->getOpcode();
01044   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
01045     return false;
01046   if (!DefMI->getOperand(1).isImm())
01047     return false;
01048   if (DefMI->getOperand(1).getImm() != 0)
01049     return false;
01050 
01051   // Note that we cannot here invert the arguments of an isel in order to fold
01052   // a ZERO into what is presented as the second argument. All we have here
01053   // is the condition bit, and that might come from a CR-logical bit operation.
01054 
01055   const MCInstrDesc &UseMCID = UseMI->getDesc();
01056 
01057   // Only fold into real machine instructions.
01058   if (UseMCID.isPseudo())
01059     return false;
01060 
01061   unsigned UseIdx;
01062   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
01063     if (UseMI->getOperand(UseIdx).isReg() &&
01064         UseMI->getOperand(UseIdx).getReg() == Reg)
01065       break;
01066 
01067   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
01068   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
01069 
01070   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
01071 
01072   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
01073   // register (which might also be specified as a pointer class kind).
01074   if (UseInfo->isLookupPtrRegClass()) {
01075     if (UseInfo->RegClass /* Kind */ != 1)
01076       return false;
01077   } else {
01078     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
01079         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
01080       return false;
01081   }
01082 
01083   // Make sure this is not tied to an output register (or otherwise
01084   // constrained). This is true for ST?UX registers, for example, which
01085   // are tied to their output registers.
01086   if (UseInfo->Constraints != 0)
01087     return false;
01088 
01089   unsigned ZeroReg;
01090   if (UseInfo->isLookupPtrRegClass()) {
01091     bool isPPC64 = Subtarget.isPPC64();
01092     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
01093   } else {
01094     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
01095               PPC::ZERO8 : PPC::ZERO;
01096   }
01097 
01098   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
01099   UseMI->getOperand(UseIdx).setReg(ZeroReg);
01100 
01101   if (DeleteDef)
01102     DefMI->eraseFromParent();
01103 
01104   return true;
01105 }
01106 
01107 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
01108   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01109        I != IE; ++I)
01110     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
01111       return true;
01112   return false;
01113 }
01114 
01115 // We should make sure that, if we're going to predicate both sides of a
01116 // condition (a diamond), that both sides don't define the counter register. We
01117 // can predicate counter-decrement-based branches, but while that predicates
01118 // the branching, it does not predicate the counter decrement. If we tried to
01119 // merge the triangle into one predicated block, we'd decrement the counter
01120 // twice.
01121 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
01122                      unsigned NumT, unsigned ExtraT,
01123                      MachineBasicBlock &FMBB,
01124                      unsigned NumF, unsigned ExtraF,
01125                      const BranchProbability &Probability) const {
01126   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
01127 }
01128 
01129 
01130 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
01131   // The predicated branches are identified by their type, not really by the
01132   // explicit presence of a predicate. Furthermore, some of them can be
01133   // predicated more than once. Because if conversion won't try to predicate
01134   // any instruction which already claims to be predicated (by returning true
01135   // here), always return false. In doing so, we let isPredicable() be the
01136   // final word on whether not the instruction can be (further) predicated.
01137 
01138   return false;
01139 }
01140 
01141 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
01142   if (!MI->isTerminator())
01143     return false;
01144 
01145   // Conditional branch is a special case.
01146   if (MI->isBranch() && !MI->isBarrier())
01147     return true;
01148 
01149   return !isPredicated(MI);
01150 }
01151 
01152 bool PPCInstrInfo::PredicateInstruction(
01153                      MachineInstr *MI,
01154                      const SmallVectorImpl<MachineOperand> &Pred) const {
01155   unsigned OpC = MI->getOpcode();
01156   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
01157     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01158       bool isPPC64 = Subtarget.isPPC64();
01159       MI->setDesc(get(Pred[0].getImm() ?
01160                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
01161                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
01162     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01163       MI->setDesc(get(PPC::BCLR));
01164       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01165         .addReg(Pred[1].getReg());
01166     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01167       MI->setDesc(get(PPC::BCLRn));
01168       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01169         .addReg(Pred[1].getReg());
01170     } else {
01171       MI->setDesc(get(PPC::BCCLR));
01172       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01173         .addImm(Pred[0].getImm())
01174         .addReg(Pred[1].getReg());
01175     }
01176 
01177     return true;
01178   } else if (OpC == PPC::B) {
01179     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01180       bool isPPC64 = Subtarget.isPPC64();
01181       MI->setDesc(get(Pred[0].getImm() ?
01182                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01183                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
01184     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01185       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01186       MI->RemoveOperand(0);
01187 
01188       MI->setDesc(get(PPC::BC));
01189       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01190         .addReg(Pred[1].getReg())
01191         .addMBB(MBB);
01192     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01193       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01194       MI->RemoveOperand(0);
01195 
01196       MI->setDesc(get(PPC::BCn));
01197       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01198         .addReg(Pred[1].getReg())
01199         .addMBB(MBB);
01200     } else {
01201       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01202       MI->RemoveOperand(0);
01203 
01204       MI->setDesc(get(PPC::BCC));
01205       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01206         .addImm(Pred[0].getImm())
01207         .addReg(Pred[1].getReg())
01208         .addMBB(MBB);
01209     }
01210 
01211     return true;
01212   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
01213              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
01214     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
01215       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
01216 
01217     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
01218     bool isPPC64 = Subtarget.isPPC64();
01219 
01220     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01221       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
01222                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
01223       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01224         .addReg(Pred[1].getReg());
01225       return true;
01226     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01227       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
01228                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
01229       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01230         .addReg(Pred[1].getReg());
01231       return true;
01232     }
01233 
01234     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
01235                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
01236     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01237       .addImm(Pred[0].getImm())
01238       .addReg(Pred[1].getReg());
01239     return true;
01240   }
01241 
01242   return false;
01243 }
01244 
01245 bool PPCInstrInfo::SubsumesPredicate(
01246                      const SmallVectorImpl<MachineOperand> &Pred1,
01247                      const SmallVectorImpl<MachineOperand> &Pred2) const {
01248   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
01249   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
01250 
01251   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
01252     return false;
01253   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
01254     return false;
01255 
01256   // P1 can only subsume P2 if they test the same condition register.
01257   if (Pred1[1].getReg() != Pred2[1].getReg())
01258     return false;
01259 
01260   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
01261   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
01262 
01263   if (P1 == P2)
01264     return true;
01265 
01266   // Does P1 subsume P2, e.g. GE subsumes GT.
01267   if (P1 == PPC::PRED_LE &&
01268       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
01269     return true;
01270   if (P1 == PPC::PRED_GE &&
01271       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
01272     return true;
01273 
01274   return false;
01275 }
01276 
01277 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
01278                                     std::vector<MachineOperand> &Pred) const {
01279   // Note: At the present time, the contents of Pred from this function is
01280   // unused by IfConversion. This implementation follows ARM by pushing the
01281   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
01282   // predicate, instructions defining CTR or CTR8 are also included as
01283   // predicate-defining instructions.
01284 
01285   const TargetRegisterClass *RCs[] =
01286     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
01287       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
01288 
01289   bool Found = false;
01290   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01291     const MachineOperand &MO = MI->getOperand(i);
01292     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
01293       const TargetRegisterClass *RC = RCs[c];
01294       if (MO.isReg()) {
01295         if (MO.isDef() && RC->contains(MO.getReg())) {
01296           Pred.push_back(MO);
01297           Found = true;
01298         }
01299       } else if (MO.isRegMask()) {
01300         for (TargetRegisterClass::iterator I = RC->begin(),
01301              IE = RC->end(); I != IE; ++I)
01302           if (MO.clobbersPhysReg(*I)) {
01303             Pred.push_back(MO);
01304             Found = true;
01305           }
01306       }
01307     }
01308   }
01309 
01310   return Found;
01311 }
01312 
01313 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
01314   unsigned OpC = MI->getOpcode();
01315   switch (OpC) {
01316   default:
01317     return false;
01318   case PPC::B:
01319   case PPC::BLR:
01320   case PPC::BLR8:
01321   case PPC::BCTR:
01322   case PPC::BCTR8:
01323   case PPC::BCTRL:
01324   case PPC::BCTRL8:
01325     return true;
01326   }
01327 }
01328 
01329 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
01330                                   unsigned &SrcReg, unsigned &SrcReg2,
01331                                   int &Mask, int &Value) const {
01332   unsigned Opc = MI->getOpcode();
01333 
01334   switch (Opc) {
01335   default: return false;
01336   case PPC::CMPWI:
01337   case PPC::CMPLWI:
01338   case PPC::CMPDI:
01339   case PPC::CMPLDI:
01340     SrcReg = MI->getOperand(1).getReg();
01341     SrcReg2 = 0;
01342     Value = MI->getOperand(2).getImm();
01343     Mask = 0xFFFF;
01344     return true;
01345   case PPC::CMPW:
01346   case PPC::CMPLW:
01347   case PPC::CMPD:
01348   case PPC::CMPLD:
01349   case PPC::FCMPUS:
01350   case PPC::FCMPUD:
01351     SrcReg = MI->getOperand(1).getReg();
01352     SrcReg2 = MI->getOperand(2).getReg();
01353     return true;
01354   }
01355 }
01356 
01357 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
01358                                         unsigned SrcReg, unsigned SrcReg2,
01359                                         int Mask, int Value,
01360                                         const MachineRegisterInfo *MRI) const {
01361   if (DisableCmpOpt)
01362     return false;
01363 
01364   int OpC = CmpInstr->getOpcode();
01365   unsigned CRReg = CmpInstr->getOperand(0).getReg();
01366 
01367   // FP record forms set CR1 based on the execption status bits, not a
01368   // comparison with zero.
01369   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
01370     return false;
01371 
01372   // The record forms set the condition register based on a signed comparison
01373   // with zero (so says the ISA manual). This is not as straightforward as it
01374   // seems, however, because this is always a 64-bit comparison on PPC64, even
01375   // for instructions that are 32-bit in nature (like slw for example).
01376   // So, on PPC32, for unsigned comparisons, we can use the record forms only
01377   // for equality checks (as those don't depend on the sign). On PPC64,
01378   // we are restricted to equality for unsigned 64-bit comparisons and for
01379   // signed 32-bit comparisons the applicability is more restricted.
01380   bool isPPC64 = Subtarget.isPPC64();
01381   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
01382   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
01383   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
01384 
01385   // Get the unique definition of SrcReg.
01386   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
01387   if (!MI) return false;
01388   int MIOpC = MI->getOpcode();
01389 
01390   bool equalityOnly = false;
01391   bool noSub = false;
01392   if (isPPC64) {
01393     if (is32BitSignedCompare) {
01394       // We can perform this optimization only if MI is sign-extending.
01395       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
01396           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
01397           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
01398           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
01399           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
01400         noSub = true;
01401       } else
01402         return false;
01403     } else if (is32BitUnsignedCompare) {
01404       // We can perform this optimization, equality only, if MI is
01405       // zero-extending.
01406       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
01407           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
01408           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
01409         noSub = true;
01410         equalityOnly = true;
01411       } else
01412         return false;
01413     } else
01414       equalityOnly = is64BitUnsignedCompare;
01415   } else
01416     equalityOnly = is32BitUnsignedCompare;
01417 
01418   if (equalityOnly) {
01419     // We need to check the uses of the condition register in order to reject
01420     // non-equality comparisons.
01421     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
01422          IE = MRI->use_instr_end(); I != IE; ++I) {
01423       MachineInstr *UseMI = &*I;
01424       if (UseMI->getOpcode() == PPC::BCC) {
01425         unsigned Pred = UseMI->getOperand(0).getImm();
01426         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
01427           return false;
01428       } else if (UseMI->getOpcode() == PPC::ISEL ||
01429                  UseMI->getOpcode() == PPC::ISEL8) {
01430         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
01431         if (SubIdx != PPC::sub_eq)
01432           return false;
01433       } else
01434         return false;
01435     }
01436   }
01437 
01438   MachineBasicBlock::iterator I = CmpInstr;
01439 
01440   // Scan forward to find the first use of the compare.
01441   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
01442        I != EL; ++I) {
01443     bool FoundUse = false;
01444     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
01445          JE = MRI->use_instr_end(); J != JE; ++J)
01446       if (&*J == &*I) {
01447         FoundUse = true;
01448         break;
01449       }
01450 
01451     if (FoundUse)
01452       break;
01453   }
01454 
01455   // There are two possible candidates which can be changed to set CR[01].
01456   // One is MI, the other is a SUB instruction.
01457   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
01458   MachineInstr *Sub = nullptr;
01459   if (SrcReg2 != 0)
01460     // MI is not a candidate for CMPrr.
01461     MI = nullptr;
01462   // FIXME: Conservatively refuse to convert an instruction which isn't in the
01463   // same BB as the comparison. This is to allow the check below to avoid calls
01464   // (and other explicit clobbers); instead we should really check for these
01465   // more explicitly (in at least a few predecessors).
01466   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
01467     // PPC does not have a record-form SUBri.
01468     return false;
01469   }
01470 
01471   // Search for Sub.
01472   const TargetRegisterInfo *TRI = &getRegisterInfo();
01473   --I;
01474 
01475   // Get ready to iterate backward from CmpInstr.
01476   MachineBasicBlock::iterator E = MI,
01477                               B = CmpInstr->getParent()->begin();
01478 
01479   for (; I != E && !noSub; --I) {
01480     const MachineInstr &Instr = *I;
01481     unsigned IOpC = Instr.getOpcode();
01482 
01483     if (&*I != CmpInstr && (
01484         Instr.modifiesRegister(PPC::CR0, TRI) ||
01485         Instr.readsRegister(PPC::CR0, TRI)))
01486       // This instruction modifies or uses the record condition register after
01487       // the one we want to change. While we could do this transformation, it
01488       // would likely not be profitable. This transformation removes one
01489       // instruction, and so even forcing RA to generate one move probably
01490       // makes it unprofitable.
01491       return false;
01492 
01493     // Check whether CmpInstr can be made redundant by the current instruction.
01494     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
01495          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
01496         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
01497         ((Instr.getOperand(1).getReg() == SrcReg &&
01498           Instr.getOperand(2).getReg() == SrcReg2) ||
01499         (Instr.getOperand(1).getReg() == SrcReg2 &&
01500          Instr.getOperand(2).getReg() == SrcReg))) {
01501       Sub = &*I;
01502       break;
01503     }
01504 
01505     if (I == B)
01506       // The 'and' is below the comparison instruction.
01507       return false;
01508   }
01509 
01510   // Return false if no candidates exist.
01511   if (!MI && !Sub)
01512     return false;
01513 
01514   // The single candidate is called MI.
01515   if (!MI) MI = Sub;
01516 
01517   int NewOpC = -1;
01518   MIOpC = MI->getOpcode();
01519   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
01520     NewOpC = MIOpC;
01521   else {
01522     NewOpC = PPC::getRecordFormOpcode(MIOpC);
01523     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
01524       NewOpC = MIOpC;
01525   }
01526 
01527   // FIXME: On the non-embedded POWER architectures, only some of the record
01528   // forms are fast, and we should use only the fast ones.
01529 
01530   // The defining instruction has a record form (or is already a record
01531   // form). It is possible, however, that we'll need to reverse the condition
01532   // code of the users.
01533   if (NewOpC == -1)
01534     return false;
01535 
01536   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
01537   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
01538 
01539   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
01540   // needs to be updated to be based on SUB.  Push the condition code
01541   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
01542   // condition code of these operands will be modified.
01543   bool ShouldSwap = false;
01544   if (Sub) {
01545     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
01546       Sub->getOperand(2).getReg() == SrcReg;
01547 
01548     // The operands to subf are the opposite of sub, so only in the fixed-point
01549     // case, invert the order.
01550     ShouldSwap = !ShouldSwap;
01551   }
01552 
01553   if (ShouldSwap)
01554     for (MachineRegisterInfo::use_instr_iterator
01555          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
01556          I != IE; ++I) {
01557       MachineInstr *UseMI = &*I;
01558       if (UseMI->getOpcode() == PPC::BCC) {
01559         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
01560         assert((!equalityOnly ||
01561                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
01562                "Invalid predicate for equality-only optimization");
01563         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
01564                                 PPC::getSwappedPredicate(Pred)));
01565       } else if (UseMI->getOpcode() == PPC::ISEL ||
01566                  UseMI->getOpcode() == PPC::ISEL8) {
01567         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
01568         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
01569                "Invalid CR bit for equality-only optimization");
01570 
01571         if (NewSubReg == PPC::sub_lt)
01572           NewSubReg = PPC::sub_gt;
01573         else if (NewSubReg == PPC::sub_gt)
01574           NewSubReg = PPC::sub_lt;
01575 
01576         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
01577                                                  NewSubReg));
01578       } else // We need to abort on a user we don't understand.
01579         return false;
01580     }
01581 
01582   // Create a new virtual register to hold the value of the CR set by the
01583   // record-form instruction. If the instruction was not previously in
01584   // record form, then set the kill flag on the CR.
01585   CmpInstr->eraseFromParent();
01586 
01587   MachineBasicBlock::iterator MII = MI;
01588   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
01589           get(TargetOpcode::COPY), CRReg)
01590     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
01591 
01592   if (MIOpC != NewOpC) {
01593     // We need to be careful here: we're replacing one instruction with
01594     // another, and we need to make sure that we get all of the right
01595     // implicit uses and defs. On the other hand, the caller may be holding
01596     // an iterator to this instruction, and so we can't delete it (this is
01597     // specifically the case if this is the instruction directly after the
01598     // compare).
01599 
01600     const MCInstrDesc &NewDesc = get(NewOpC);
01601     MI->setDesc(NewDesc);
01602 
01603     if (NewDesc.ImplicitDefs)
01604       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
01605            *ImpDefs; ++ImpDefs)
01606         if (!MI->definesRegister(*ImpDefs))
01607           MI->addOperand(*MI->getParent()->getParent(),
01608                          MachineOperand::CreateReg(*ImpDefs, true, true));
01609     if (NewDesc.ImplicitUses)
01610       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
01611            *ImpUses; ++ImpUses)
01612         if (!MI->readsRegister(*ImpUses))
01613           MI->addOperand(*MI->getParent()->getParent(),
01614                          MachineOperand::CreateReg(*ImpUses, false, true));
01615   }
01616 
01617   // Modify the condition code of operands in OperandsToUpdate.
01618   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
01619   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
01620   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
01621     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
01622 
01623   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
01624     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
01625 
01626   return true;
01627 }
01628 
01629 /// GetInstSize - Return the number of bytes of code the specified
01630 /// instruction may be.  This returns the maximum number of bytes.
01631 ///
01632 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
01633   unsigned Opcode = MI->getOpcode();
01634 
01635   if (Opcode == PPC::INLINEASM) {
01636     const MachineFunction *MF = MI->getParent()->getParent();
01637     const char *AsmStr = MI->getOperand(0).getSymbolName();
01638     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
01639   } else if (Opcode == TargetOpcode::STACKMAP) {
01640     return MI->getOperand(1).getImm();
01641   } else if (Opcode == TargetOpcode::PATCHPOINT) {
01642     PatchPointOpers Opers(MI);
01643     return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
01644   } else {
01645     const MCInstrDesc &Desc = get(Opcode);
01646     return Desc.getSize();
01647   }
01648 }
01649