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/MC/MCAsmInfo.h"
00033 #include "llvm/Support/CommandLine.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/ErrorHandling.h"
00036 #include "llvm/Support/TargetRegistry.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "ppc-instr-info"
00042 
00043 #define GET_INSTRMAP_INFO
00044 #define GET_INSTRINFO_CTOR_DTOR
00045 #include "PPCGenInstrInfo.inc"
00046 
00047 static cl::
00048 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
00049             cl::desc("Disable analysis for CTR loops"));
00050 
00051 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
00052 cl::desc("Disable compare instruction optimization"), cl::Hidden);
00053 
00054 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
00055 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
00056 
00057 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
00058 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
00059 cl::Hidden);
00060 
00061 // Pin the vtable to this file.
00062 void PPCInstrInfo::anchor() {}
00063 
00064 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
00065     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
00066       Subtarget(STI), RI(STI) {}
00067 
00068 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
00069 /// this target when scheduling the DAG.
00070 ScheduleHazardRecognizer *
00071 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
00072                                            const ScheduleDAG *DAG) const {
00073   unsigned Directive =
00074       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
00075   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
00076       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
00077     const InstrItineraryData *II =
00078         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
00079     return new ScoreboardHazardRecognizer(II, DAG);
00080   }
00081 
00082   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
00083 }
00084 
00085 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
00086 /// to use for this target when scheduling the DAG.
00087 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
00088   const InstrItineraryData *II,
00089   const ScheduleDAG *DAG) const {
00090   unsigned Directive =
00091       DAG->TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
00092 
00093   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
00094     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
00095 
00096   // Most subtargets use a PPC970 recognizer.
00097   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
00098       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
00099     assert(DAG->TII && "No InstrInfo?");
00100 
00101     return new PPCHazardRecognizer970(*DAG);
00102   }
00103 
00104   return new ScoreboardHazardRecognizer(II, DAG);
00105 }
00106 
00107 
00108 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
00109                                     const MachineInstr *DefMI, unsigned DefIdx,
00110                                     const MachineInstr *UseMI,
00111                                     unsigned UseIdx) const {
00112   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
00113                                                    UseMI, UseIdx);
00114 
00115   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
00116   unsigned Reg = DefMO.getReg();
00117 
00118   const TargetRegisterInfo *TRI = &getRegisterInfo();
00119   bool IsRegCR;
00120   if (TRI->isVirtualRegister(Reg)) {
00121     const MachineRegisterInfo *MRI =
00122       &DefMI->getParent()->getParent()->getRegInfo();
00123     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
00124               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
00125   } else {
00126     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
00127               PPC::CRBITRCRegClass.contains(Reg);
00128   }
00129 
00130   if (UseMI->isBranch() && IsRegCR) {
00131     if (Latency < 0)
00132       Latency = getInstrLatency(ItinData, DefMI);
00133 
00134     // On some cores, there is an additional delay between writing to a condition
00135     // register, and using it from a branch.
00136     unsigned Directive = Subtarget.getDarwinDirective();
00137     switch (Directive) {
00138     default: break;
00139     case PPC::DIR_7400:
00140     case PPC::DIR_750:
00141     case PPC::DIR_970:
00142     case PPC::DIR_E5500:
00143     case PPC::DIR_PWR4:
00144     case PPC::DIR_PWR5:
00145     case PPC::DIR_PWR5X:
00146     case PPC::DIR_PWR6:
00147     case PPC::DIR_PWR6X:
00148     case PPC::DIR_PWR7:
00149     case PPC::DIR_PWR8:
00150       Latency += 2;
00151       break;
00152     }
00153   }
00154 
00155   return Latency;
00156 }
00157 
00158 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
00159 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
00160                                          unsigned &SrcReg, unsigned &DstReg,
00161                                          unsigned &SubIdx) const {
00162   switch (MI.getOpcode()) {
00163   default: return false;
00164   case PPC::EXTSW:
00165   case PPC::EXTSW_32_64:
00166     SrcReg = MI.getOperand(1).getReg();
00167     DstReg = MI.getOperand(0).getReg();
00168     SubIdx = PPC::sub_32;
00169     return true;
00170   }
00171 }
00172 
00173 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
00174                                            int &FrameIndex) const {
00175   // Note: This list must be kept consistent with LoadRegFromStackSlot.
00176   switch (MI->getOpcode()) {
00177   default: break;
00178   case PPC::LD:
00179   case PPC::LWZ:
00180   case PPC::LFS:
00181   case PPC::LFD:
00182   case PPC::RESTORE_CR:
00183   case PPC::RESTORE_CRBIT:
00184   case PPC::LVX:
00185   case PPC::LXVD2X:
00186   case PPC::RESTORE_VRSAVE:
00187     // Check for the operands added by addFrameReference (the immediate is the
00188     // offset which defaults to 0).
00189     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00190         MI->getOperand(2).isFI()) {
00191       FrameIndex = MI->getOperand(2).getIndex();
00192       return MI->getOperand(0).getReg();
00193     }
00194     break;
00195   }
00196   return 0;
00197 }
00198 
00199 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
00200                                           int &FrameIndex) const {
00201   // Note: This list must be kept consistent with StoreRegToStackSlot.
00202   switch (MI->getOpcode()) {
00203   default: break;
00204   case PPC::STD:
00205   case PPC::STW:
00206   case PPC::STFS:
00207   case PPC::STFD:
00208   case PPC::SPILL_CR:
00209   case PPC::SPILL_CRBIT:
00210   case PPC::STVX:
00211   case PPC::STXVD2X:
00212   case PPC::SPILL_VRSAVE:
00213     // Check for the operands added by addFrameReference (the immediate is the
00214     // offset which defaults to 0).
00215     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
00216         MI->getOperand(2).isFI()) {
00217       FrameIndex = MI->getOperand(2).getIndex();
00218       return MI->getOperand(0).getReg();
00219     }
00220     break;
00221   }
00222   return 0;
00223 }
00224 
00225 // commuteInstruction - We can commute rlwimi instructions, but only if the
00226 // rotate amt is zero.  We also have to munge the immediates a bit.
00227 MachineInstr *
00228 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
00229   MachineFunction &MF = *MI->getParent()->getParent();
00230 
00231   // Normal instructions can be commuted the obvious way.
00232   if (MI->getOpcode() != PPC::RLWIMI &&
00233       MI->getOpcode() != PPC::RLWIMIo &&
00234       MI->getOpcode() != PPC::RLWIMI8 &&
00235       MI->getOpcode() != PPC::RLWIMI8o)
00236     return TargetInstrInfo::commuteInstruction(MI, NewMI);
00237 
00238   // Cannot commute if it has a non-zero rotate count.
00239   if (MI->getOperand(3).getImm() != 0)
00240     return nullptr;
00241 
00242   // If we have a zero rotate count, we have:
00243   //   M = mask(MB,ME)
00244   //   Op0 = (Op1 & ~M) | (Op2 & M)
00245   // Change this to:
00246   //   M = mask((ME+1)&31, (MB-1)&31)
00247   //   Op0 = (Op2 & ~M) | (Op1 & M)
00248 
00249   // Swap op1/op2
00250   unsigned Reg0 = MI->getOperand(0).getReg();
00251   unsigned Reg1 = MI->getOperand(1).getReg();
00252   unsigned Reg2 = MI->getOperand(2).getReg();
00253   unsigned SubReg1 = MI->getOperand(1).getSubReg();
00254   unsigned SubReg2 = MI->getOperand(2).getSubReg();
00255   bool Reg1IsKill = MI->getOperand(1).isKill();
00256   bool Reg2IsKill = MI->getOperand(2).isKill();
00257   bool ChangeReg0 = false;
00258   // If machine instrs are no longer in two-address forms, update
00259   // destination register as well.
00260   if (Reg0 == Reg1) {
00261     // Must be two address instruction!
00262     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
00263            "Expecting a two-address instruction!");
00264     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
00265     Reg2IsKill = false;
00266     ChangeReg0 = true;
00267   }
00268 
00269   // Masks.
00270   unsigned MB = MI->getOperand(4).getImm();
00271   unsigned ME = MI->getOperand(5).getImm();
00272 
00273   if (NewMI) {
00274     // Create a new instruction.
00275     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
00276     bool Reg0IsDead = MI->getOperand(0).isDead();
00277     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
00278       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
00279       .addReg(Reg2, getKillRegState(Reg2IsKill))
00280       .addReg(Reg1, getKillRegState(Reg1IsKill))
00281       .addImm((ME+1) & 31)
00282       .addImm((MB-1) & 31);
00283   }
00284 
00285   if (ChangeReg0) {
00286     MI->getOperand(0).setReg(Reg2);
00287     MI->getOperand(0).setSubReg(SubReg2);
00288   }
00289   MI->getOperand(2).setReg(Reg1);
00290   MI->getOperand(1).setReg(Reg2);
00291   MI->getOperand(2).setSubReg(SubReg1);
00292   MI->getOperand(1).setSubReg(SubReg2);
00293   MI->getOperand(2).setIsKill(Reg1IsKill);
00294   MI->getOperand(1).setIsKill(Reg2IsKill);
00295 
00296   // Swap the mask around.
00297   MI->getOperand(4).setImm((ME+1) & 31);
00298   MI->getOperand(5).setImm((MB-1) & 31);
00299   return MI;
00300 }
00301 
00302 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
00303                                          unsigned &SrcOpIdx2) const {
00304   // For VSX A-Type FMA instructions, it is the first two operands that can be
00305   // commuted, however, because the non-encoded tied input operand is listed
00306   // first, the operands to swap are actually the second and third.
00307 
00308   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
00309   if (AltOpc == -1)
00310     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
00311 
00312   SrcOpIdx1 = 2;
00313   SrcOpIdx2 = 3;
00314   return true;
00315 }
00316 
00317 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
00318                               MachineBasicBlock::iterator MI) const {
00319   // This function is used for scheduling, and the nop wanted here is the type
00320   // that terminates dispatch groups on the POWER cores.
00321   unsigned Directive = Subtarget.getDarwinDirective();
00322   unsigned Opcode;
00323   switch (Directive) {
00324   default:            Opcode = PPC::NOP; break;
00325   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
00326   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
00327   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
00328   }
00329 
00330   DebugLoc DL;
00331   BuildMI(MBB, MI, DL, get(Opcode));
00332 }
00333 
00334 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
00335 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
00336   NopInst.setOpcode(PPC::NOP);
00337 }
00338 
00339 // Branch analysis.
00340 // Note: If the condition register is set to CTR or CTR8 then this is a
00341 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
00342 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
00343                                  MachineBasicBlock *&FBB,
00344                                  SmallVectorImpl<MachineOperand> &Cond,
00345                                  bool AllowModify) const {
00346   bool isPPC64 = Subtarget.isPPC64();
00347 
00348   // If the block has no terminators, it just falls into the block after it.
00349   MachineBasicBlock::iterator I = MBB.end();
00350   if (I == MBB.begin())
00351     return false;
00352   --I;
00353   while (I->isDebugValue()) {
00354     if (I == MBB.begin())
00355       return false;
00356     --I;
00357   }
00358   if (!isUnpredicatedTerminator(I))
00359     return false;
00360 
00361   // Get the last instruction in the block.
00362   MachineInstr *LastInst = I;
00363 
00364   // If there is only one terminator instruction, process it.
00365   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
00366     if (LastInst->getOpcode() == PPC::B) {
00367       if (!LastInst->getOperand(0).isMBB())
00368         return true;
00369       TBB = LastInst->getOperand(0).getMBB();
00370       return false;
00371     } else if (LastInst->getOpcode() == PPC::BCC) {
00372       if (!LastInst->getOperand(2).isMBB())
00373         return true;
00374       // Block ends with fall-through condbranch.
00375       TBB = LastInst->getOperand(2).getMBB();
00376       Cond.push_back(LastInst->getOperand(0));
00377       Cond.push_back(LastInst->getOperand(1));
00378       return false;
00379     } else if (LastInst->getOpcode() == PPC::BC) {
00380       if (!LastInst->getOperand(1).isMBB())
00381         return true;
00382       // Block ends with fall-through condbranch.
00383       TBB = LastInst->getOperand(1).getMBB();
00384       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00385       Cond.push_back(LastInst->getOperand(0));
00386       return false;
00387     } else if (LastInst->getOpcode() == PPC::BCn) {
00388       if (!LastInst->getOperand(1).isMBB())
00389         return true;
00390       // Block ends with fall-through condbranch.
00391       TBB = LastInst->getOperand(1).getMBB();
00392       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00393       Cond.push_back(LastInst->getOperand(0));
00394       return false;
00395     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
00396                LastInst->getOpcode() == PPC::BDNZ) {
00397       if (!LastInst->getOperand(0).isMBB())
00398         return true;
00399       if (DisableCTRLoopAnal)
00400         return true;
00401       TBB = LastInst->getOperand(0).getMBB();
00402       Cond.push_back(MachineOperand::CreateImm(1));
00403       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00404                                                true));
00405       return false;
00406     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
00407                LastInst->getOpcode() == PPC::BDZ) {
00408       if (!LastInst->getOperand(0).isMBB())
00409         return true;
00410       if (DisableCTRLoopAnal)
00411         return true;
00412       TBB = LastInst->getOperand(0).getMBB();
00413       Cond.push_back(MachineOperand::CreateImm(0));
00414       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00415                                                true));
00416       return false;
00417     }
00418 
00419     // Otherwise, don't know what this is.
00420     return true;
00421   }
00422 
00423   // Get the instruction before it if it's a terminator.
00424   MachineInstr *SecondLastInst = I;
00425 
00426   // If there are three terminators, we don't know what sort of block this is.
00427   if (SecondLastInst && I != MBB.begin() &&
00428       isUnpredicatedTerminator(--I))
00429     return true;
00430 
00431   // If the block ends with PPC::B and PPC:BCC, handle it.
00432   if (SecondLastInst->getOpcode() == PPC::BCC &&
00433       LastInst->getOpcode() == PPC::B) {
00434     if (!SecondLastInst->getOperand(2).isMBB() ||
00435         !LastInst->getOperand(0).isMBB())
00436       return true;
00437     TBB =  SecondLastInst->getOperand(2).getMBB();
00438     Cond.push_back(SecondLastInst->getOperand(0));
00439     Cond.push_back(SecondLastInst->getOperand(1));
00440     FBB = LastInst->getOperand(0).getMBB();
00441     return false;
00442   } else if (SecondLastInst->getOpcode() == PPC::BC &&
00443       LastInst->getOpcode() == PPC::B) {
00444     if (!SecondLastInst->getOperand(1).isMBB() ||
00445         !LastInst->getOperand(0).isMBB())
00446       return true;
00447     TBB =  SecondLastInst->getOperand(1).getMBB();
00448     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
00449     Cond.push_back(SecondLastInst->getOperand(0));
00450     FBB = LastInst->getOperand(0).getMBB();
00451     return false;
00452   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
00453       LastInst->getOpcode() == PPC::B) {
00454     if (!SecondLastInst->getOperand(1).isMBB() ||
00455         !LastInst->getOperand(0).isMBB())
00456       return true;
00457     TBB =  SecondLastInst->getOperand(1).getMBB();
00458     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
00459     Cond.push_back(SecondLastInst->getOperand(0));
00460     FBB = LastInst->getOperand(0).getMBB();
00461     return false;
00462   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
00463               SecondLastInst->getOpcode() == PPC::BDNZ) &&
00464       LastInst->getOpcode() == PPC::B) {
00465     if (!SecondLastInst->getOperand(0).isMBB() ||
00466         !LastInst->getOperand(0).isMBB())
00467       return true;
00468     if (DisableCTRLoopAnal)
00469       return true;
00470     TBB = SecondLastInst->getOperand(0).getMBB();
00471     Cond.push_back(MachineOperand::CreateImm(1));
00472     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00473                                              true));
00474     FBB = LastInst->getOperand(0).getMBB();
00475     return false;
00476   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
00477               SecondLastInst->getOpcode() == PPC::BDZ) &&
00478       LastInst->getOpcode() == PPC::B) {
00479     if (!SecondLastInst->getOperand(0).isMBB() ||
00480         !LastInst->getOperand(0).isMBB())
00481       return true;
00482     if (DisableCTRLoopAnal)
00483       return true;
00484     TBB = SecondLastInst->getOperand(0).getMBB();
00485     Cond.push_back(MachineOperand::CreateImm(0));
00486     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
00487                                              true));
00488     FBB = LastInst->getOperand(0).getMBB();
00489     return false;
00490   }
00491 
00492   // If the block ends with two PPC:Bs, handle it.  The second one is not
00493   // executed, so remove it.
00494   if (SecondLastInst->getOpcode() == PPC::B &&
00495       LastInst->getOpcode() == PPC::B) {
00496     if (!SecondLastInst->getOperand(0).isMBB())
00497       return true;
00498     TBB = SecondLastInst->getOperand(0).getMBB();
00499     I = LastInst;
00500     if (AllowModify)
00501       I->eraseFromParent();
00502     return false;
00503   }
00504 
00505   // Otherwise, can't handle this.
00506   return true;
00507 }
00508 
00509 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
00510   MachineBasicBlock::iterator I = MBB.end();
00511   if (I == MBB.begin()) return 0;
00512   --I;
00513   while (I->isDebugValue()) {
00514     if (I == MBB.begin())
00515       return 0;
00516     --I;
00517   }
00518   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
00519       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00520       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00521       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00522     return 0;
00523 
00524   // Remove the branch.
00525   I->eraseFromParent();
00526 
00527   I = MBB.end();
00528 
00529   if (I == MBB.begin()) return 1;
00530   --I;
00531   if (I->getOpcode() != PPC::BCC &&
00532       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
00533       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
00534       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
00535     return 1;
00536 
00537   // Remove the branch.
00538   I->eraseFromParent();
00539   return 2;
00540 }
00541 
00542 unsigned
00543 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
00544                            MachineBasicBlock *FBB,
00545                            const SmallVectorImpl<MachineOperand> &Cond,
00546                            DebugLoc DL) const {
00547   // Shouldn't be a fall through.
00548   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
00549   assert((Cond.size() == 2 || Cond.size() == 0) &&
00550          "PPC branch conditions have two components!");
00551 
00552   bool isPPC64 = Subtarget.isPPC64();
00553 
00554   // One-way branch.
00555   if (!FBB) {
00556     if (Cond.empty())   // Unconditional branch
00557       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
00558     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00559       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00560                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00561                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00562     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00563       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00564     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00565       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00566     else                // Conditional branch
00567       BuildMI(&MBB, DL, get(PPC::BCC))
00568         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00569     return 1;
00570   }
00571 
00572   // Two-way Conditional Branch.
00573   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00574     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
00575                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
00576                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
00577   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
00578     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
00579   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
00580     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
00581   else
00582     BuildMI(&MBB, DL, get(PPC::BCC))
00583       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
00584   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
00585   return 2;
00586 }
00587 
00588 // Select analysis.
00589 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
00590                 const SmallVectorImpl<MachineOperand> &Cond,
00591                 unsigned TrueReg, unsigned FalseReg,
00592                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
00593   if (!Subtarget.hasISEL())
00594     return false;
00595 
00596   if (Cond.size() != 2)
00597     return false;
00598 
00599   // If this is really a bdnz-like condition, then it cannot be turned into a
00600   // select.
00601   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
00602     return false;
00603 
00604   // Check register classes.
00605   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00606   const TargetRegisterClass *RC =
00607     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00608   if (!RC)
00609     return false;
00610 
00611   // isel is for regular integer GPRs only.
00612   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
00613       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
00614       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
00615       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
00616     return false;
00617 
00618   // FIXME: These numbers are for the A2, how well they work for other cores is
00619   // an open question. On the A2, the isel instruction has a 2-cycle latency
00620   // but single-cycle throughput. These numbers are used in combination with
00621   // the MispredictPenalty setting from the active SchedMachineModel.
00622   CondCycles = 1;
00623   TrueCycles = 1;
00624   FalseCycles = 1;
00625 
00626   return true;
00627 }
00628 
00629 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
00630                                 MachineBasicBlock::iterator MI, DebugLoc dl,
00631                                 unsigned DestReg,
00632                                 const SmallVectorImpl<MachineOperand> &Cond,
00633                                 unsigned TrueReg, unsigned FalseReg) const {
00634   assert(Cond.size() == 2 &&
00635          "PPC branch conditions have two components!");
00636 
00637   assert(Subtarget.hasISEL() &&
00638          "Cannot insert select on target without ISEL support");
00639 
00640   // Get the register classes.
00641   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
00642   const TargetRegisterClass *RC =
00643     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
00644   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
00645 
00646   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
00647                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
00648   assert((Is64Bit ||
00649           PPC::GPRCRegClass.hasSubClassEq(RC) ||
00650           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
00651          "isel is for regular integer GPRs only");
00652 
00653   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
00654   unsigned SelectPred = Cond[0].getImm();
00655 
00656   unsigned SubIdx;
00657   bool SwapOps;
00658   switch (SelectPred) {
00659   default: llvm_unreachable("invalid predicate for isel");
00660   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
00661   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
00662   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
00663   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
00664   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
00665   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
00666   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
00667   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
00668   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
00669   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
00670   }
00671 
00672   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
00673            SecondReg = SwapOps ? TrueReg  : FalseReg;
00674 
00675   // The first input register of isel cannot be r0. If it is a member
00676   // of a register class that can be r0, then copy it first (the
00677   // register allocator should eliminate the copy).
00678   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
00679       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
00680     const TargetRegisterClass *FirstRC =
00681       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
00682         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
00683     unsigned OldFirstReg = FirstReg;
00684     FirstReg = MRI.createVirtualRegister(FirstRC);
00685     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
00686       .addReg(OldFirstReg);
00687   }
00688 
00689   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
00690     .addReg(FirstReg).addReg(SecondReg)
00691     .addReg(Cond[1].getReg(), 0, SubIdx);
00692 }
00693 
00694 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
00695                                MachineBasicBlock::iterator I, DebugLoc DL,
00696                                unsigned DestReg, unsigned SrcReg,
00697                                bool KillSrc) const {
00698   // We can end up with self copies and similar things as a result of VSX copy
00699   // legalization. Promote them here.
00700   const TargetRegisterInfo *TRI = &getRegisterInfo();
00701   if (PPC::F8RCRegClass.contains(DestReg) &&
00702       PPC::VSLRCRegClass.contains(SrcReg)) {
00703     unsigned SuperReg =
00704       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
00705 
00706     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00707       llvm_unreachable("nop VSX copy");
00708 
00709     DestReg = SuperReg;
00710   } else if (PPC::VRRCRegClass.contains(DestReg) &&
00711              PPC::VSHRCRegClass.contains(SrcReg)) {
00712     unsigned SuperReg =
00713       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
00714 
00715     if (VSXSelfCopyCrash && SrcReg == SuperReg)
00716       llvm_unreachable("nop VSX copy");
00717 
00718     DestReg = SuperReg;
00719   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
00720              PPC::VSLRCRegClass.contains(DestReg)) {
00721     unsigned SuperReg =
00722       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
00723 
00724     if (VSXSelfCopyCrash && DestReg == SuperReg)
00725       llvm_unreachable("nop VSX copy");
00726 
00727     SrcReg = SuperReg;
00728   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
00729              PPC::VSHRCRegClass.contains(DestReg)) {
00730     unsigned SuperReg =
00731       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
00732 
00733     if (VSXSelfCopyCrash && DestReg == SuperReg)
00734       llvm_unreachable("nop VSX copy");
00735 
00736     SrcReg = SuperReg;
00737   }
00738 
00739   unsigned Opc;
00740   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
00741     Opc = PPC::OR;
00742   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
00743     Opc = PPC::OR8;
00744   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
00745     Opc = PPC::FMR;
00746   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
00747     Opc = PPC::MCRF;
00748   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
00749     Opc = PPC::VOR;
00750   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
00751     // There are two different ways this can be done:
00752     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
00753     //      issue in VSU pipeline 0.
00754     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
00755     //      can go to either pipeline.
00756     // We'll always use xxlor here, because in practically all cases where
00757     // copies are generated, they are close enough to some use that the
00758     // lower-latency form is preferable.
00759     Opc = PPC::XXLOR;
00760   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
00761     Opc = PPC::XXLORf;
00762   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
00763     Opc = PPC::CROR;
00764   else
00765     llvm_unreachable("Impossible reg-to-reg copy");
00766 
00767   const MCInstrDesc &MCID = get(Opc);
00768   if (MCID.getNumOperands() == 3)
00769     BuildMI(MBB, I, DL, MCID, DestReg)
00770       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
00771   else
00772     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
00773 }
00774 
00775 // This function returns true if a CR spill is necessary and false otherwise.
00776 bool
00777 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
00778                                   unsigned SrcReg, bool isKill,
00779                                   int FrameIdx,
00780                                   const TargetRegisterClass *RC,
00781                                   SmallVectorImpl<MachineInstr*> &NewMIs,
00782                                   bool &NonRI, bool &SpillsVRS) const{
00783   // Note: If additional store instructions are added here,
00784   // update isStoreToStackSlot.
00785 
00786   DebugLoc DL;
00787   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00788       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00789     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
00790                                        .addReg(SrcReg,
00791                                                getKillRegState(isKill)),
00792                                        FrameIdx));
00793   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00794              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00795     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
00796                                        .addReg(SrcReg,
00797                                                getKillRegState(isKill)),
00798                                        FrameIdx));
00799   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00800     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
00801                                        .addReg(SrcReg,
00802                                                getKillRegState(isKill)),
00803                                        FrameIdx));
00804   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00805     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
00806                                        .addReg(SrcReg,
00807                                                getKillRegState(isKill)),
00808                                        FrameIdx));
00809   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00810     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
00811                                        .addReg(SrcReg,
00812                                                getKillRegState(isKill)),
00813                                        FrameIdx));
00814     return true;
00815   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00816     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
00817                                        .addReg(SrcReg,
00818                                                getKillRegState(isKill)),
00819                                        FrameIdx));
00820     return true;
00821   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00822     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
00823                                        .addReg(SrcReg,
00824                                                getKillRegState(isKill)),
00825                                        FrameIdx));
00826     NonRI = true;
00827   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00828     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
00829                                        .addReg(SrcReg,
00830                                                getKillRegState(isKill)),
00831                                        FrameIdx));
00832     NonRI = true;
00833   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00834     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
00835                                        .addReg(SrcReg,
00836                                                getKillRegState(isKill)),
00837                                        FrameIdx));
00838     NonRI = true;
00839   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00840     assert(Subtarget.isDarwin() &&
00841            "VRSAVE only needs spill/restore on Darwin");
00842     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
00843                                        .addReg(SrcReg,
00844                                                getKillRegState(isKill)),
00845                                        FrameIdx));
00846     SpillsVRS = true;
00847   } else {
00848     llvm_unreachable("Unknown regclass!");
00849   }
00850 
00851   return false;
00852 }
00853 
00854 void
00855 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
00856                                   MachineBasicBlock::iterator MI,
00857                                   unsigned SrcReg, bool isKill, int FrameIdx,
00858                                   const TargetRegisterClass *RC,
00859                                   const TargetRegisterInfo *TRI) const {
00860   MachineFunction &MF = *MBB.getParent();
00861   SmallVector<MachineInstr*, 4> NewMIs;
00862 
00863   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00864   FuncInfo->setHasSpills();
00865 
00866   bool NonRI = false, SpillsVRS = false;
00867   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
00868                           NonRI, SpillsVRS))
00869     FuncInfo->setSpillsCR();
00870 
00871   if (SpillsVRS)
00872     FuncInfo->setSpillsVRSAVE();
00873 
00874   if (NonRI)
00875     FuncInfo->setHasNonRISpills();
00876 
00877   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00878     MBB.insert(MI, NewMIs[i]);
00879 
00880   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00881   MachineMemOperand *MMO =
00882     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00883                             MachineMemOperand::MOStore,
00884                             MFI.getObjectSize(FrameIdx),
00885                             MFI.getObjectAlignment(FrameIdx));
00886   NewMIs.back()->addMemOperand(MF, MMO);
00887 }
00888 
00889 bool
00890 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
00891                                    unsigned DestReg, int FrameIdx,
00892                                    const TargetRegisterClass *RC,
00893                                    SmallVectorImpl<MachineInstr*> &NewMIs,
00894                                    bool &NonRI, bool &SpillsVRS) const{
00895   // Note: If additional load instructions are added here,
00896   // update isLoadFromStackSlot.
00897 
00898   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
00899       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
00900     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
00901                                                DestReg), FrameIdx));
00902   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
00903              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
00904     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
00905                                        FrameIdx));
00906   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
00907     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
00908                                        FrameIdx));
00909   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
00910     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
00911                                        FrameIdx));
00912   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
00913     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00914                                                get(PPC::RESTORE_CR), DestReg),
00915                                        FrameIdx));
00916     return true;
00917   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
00918     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00919                                                get(PPC::RESTORE_CRBIT), DestReg),
00920                                        FrameIdx));
00921     return true;
00922   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
00923     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
00924                                        FrameIdx));
00925     NonRI = true;
00926   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
00927     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
00928                                        FrameIdx));
00929     NonRI = true;
00930   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
00931     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
00932                                        FrameIdx));
00933     NonRI = true;
00934   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
00935     assert(Subtarget.isDarwin() &&
00936            "VRSAVE only needs spill/restore on Darwin");
00937     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
00938                                                get(PPC::RESTORE_VRSAVE),
00939                                                DestReg),
00940                                        FrameIdx));
00941     SpillsVRS = true;
00942   } else {
00943     llvm_unreachable("Unknown regclass!");
00944   }
00945 
00946   return false;
00947 }
00948 
00949 void
00950 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
00951                                    MachineBasicBlock::iterator MI,
00952                                    unsigned DestReg, int FrameIdx,
00953                                    const TargetRegisterClass *RC,
00954                                    const TargetRegisterInfo *TRI) const {
00955   MachineFunction &MF = *MBB.getParent();
00956   SmallVector<MachineInstr*, 4> NewMIs;
00957   DebugLoc DL;
00958   if (MI != MBB.end()) DL = MI->getDebugLoc();
00959 
00960   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
00961   FuncInfo->setHasSpills();
00962 
00963   bool NonRI = false, SpillsVRS = false;
00964   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
00965                            NonRI, SpillsVRS))
00966     FuncInfo->setSpillsCR();
00967 
00968   if (SpillsVRS)
00969     FuncInfo->setSpillsVRSAVE();
00970 
00971   if (NonRI)
00972     FuncInfo->setHasNonRISpills();
00973 
00974   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
00975     MBB.insert(MI, NewMIs[i]);
00976 
00977   const MachineFrameInfo &MFI = *MF.getFrameInfo();
00978   MachineMemOperand *MMO =
00979     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
00980                             MachineMemOperand::MOLoad,
00981                             MFI.getObjectSize(FrameIdx),
00982                             MFI.getObjectAlignment(FrameIdx));
00983   NewMIs.back()->addMemOperand(MF, MMO);
00984 }
00985 
00986 bool PPCInstrInfo::
00987 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
00988   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
00989   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
00990     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
00991   else
00992     // Leave the CR# the same, but invert the condition.
00993     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
00994   return false;
00995 }
00996 
00997 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
00998                              unsigned Reg, MachineRegisterInfo *MRI) const {
00999   // For some instructions, it is legal to fold ZERO into the RA register field.
01000   // A zero immediate should always be loaded with a single li.
01001   unsigned DefOpc = DefMI->getOpcode();
01002   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
01003     return false;
01004   if (!DefMI->getOperand(1).isImm())
01005     return false;
01006   if (DefMI->getOperand(1).getImm() != 0)
01007     return false;
01008 
01009   // Note that we cannot here invert the arguments of an isel in order to fold
01010   // a ZERO into what is presented as the second argument. All we have here
01011   // is the condition bit, and that might come from a CR-logical bit operation.
01012 
01013   const MCInstrDesc &UseMCID = UseMI->getDesc();
01014 
01015   // Only fold into real machine instructions.
01016   if (UseMCID.isPseudo())
01017     return false;
01018 
01019   unsigned UseIdx;
01020   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
01021     if (UseMI->getOperand(UseIdx).isReg() &&
01022         UseMI->getOperand(UseIdx).getReg() == Reg)
01023       break;
01024 
01025   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
01026   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
01027 
01028   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
01029 
01030   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
01031   // register (which might also be specified as a pointer class kind).
01032   if (UseInfo->isLookupPtrRegClass()) {
01033     if (UseInfo->RegClass /* Kind */ != 1)
01034       return false;
01035   } else {
01036     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
01037         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
01038       return false;
01039   }
01040 
01041   // Make sure this is not tied to an output register (or otherwise
01042   // constrained). This is true for ST?UX registers, for example, which
01043   // are tied to their output registers.
01044   if (UseInfo->Constraints != 0)
01045     return false;
01046 
01047   unsigned ZeroReg;
01048   if (UseInfo->isLookupPtrRegClass()) {
01049     bool isPPC64 = Subtarget.isPPC64();
01050     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
01051   } else {
01052     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
01053               PPC::ZERO8 : PPC::ZERO;
01054   }
01055 
01056   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
01057   UseMI->getOperand(UseIdx).setReg(ZeroReg);
01058 
01059   if (DeleteDef)
01060     DefMI->eraseFromParent();
01061 
01062   return true;
01063 }
01064 
01065 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
01066   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01067        I != IE; ++I)
01068     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
01069       return true;
01070   return false;
01071 }
01072 
01073 // We should make sure that, if we're going to predicate both sides of a
01074 // condition (a diamond), that both sides don't define the counter register. We
01075 // can predicate counter-decrement-based branches, but while that predicates
01076 // the branching, it does not predicate the counter decrement. If we tried to
01077 // merge the triangle into one predicated block, we'd decrement the counter
01078 // twice.
01079 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
01080                      unsigned NumT, unsigned ExtraT,
01081                      MachineBasicBlock &FMBB,
01082                      unsigned NumF, unsigned ExtraF,
01083                      const BranchProbability &Probability) const {
01084   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
01085 }
01086 
01087 
01088 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
01089   // The predicated branches are identified by their type, not really by the
01090   // explicit presence of a predicate. Furthermore, some of them can be
01091   // predicated more than once. Because if conversion won't try to predicate
01092   // any instruction which already claims to be predicated (by returning true
01093   // here), always return false. In doing so, we let isPredicable() be the
01094   // final word on whether not the instruction can be (further) predicated.
01095 
01096   return false;
01097 }
01098 
01099 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
01100   if (!MI->isTerminator())
01101     return false;
01102 
01103   // Conditional branch is a special case.
01104   if (MI->isBranch() && !MI->isBarrier())
01105     return true;
01106 
01107   return !isPredicated(MI);
01108 }
01109 
01110 bool PPCInstrInfo::PredicateInstruction(
01111                      MachineInstr *MI,
01112                      const SmallVectorImpl<MachineOperand> &Pred) const {
01113   unsigned OpC = MI->getOpcode();
01114   if (OpC == PPC::BLR) {
01115     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01116       bool isPPC64 = Subtarget.isPPC64();
01117       MI->setDesc(get(Pred[0].getImm() ?
01118                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
01119                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
01120     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01121       MI->setDesc(get(PPC::BCLR));
01122       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01123         .addReg(Pred[1].getReg());
01124     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01125       MI->setDesc(get(PPC::BCLRn));
01126       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01127         .addReg(Pred[1].getReg());
01128     } else {
01129       MI->setDesc(get(PPC::BCCLR));
01130       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01131         .addImm(Pred[0].getImm())
01132         .addReg(Pred[1].getReg());
01133     }
01134 
01135     return true;
01136   } else if (OpC == PPC::B) {
01137     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
01138       bool isPPC64 = Subtarget.isPPC64();
01139       MI->setDesc(get(Pred[0].getImm() ?
01140                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
01141                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
01142     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01143       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01144       MI->RemoveOperand(0);
01145 
01146       MI->setDesc(get(PPC::BC));
01147       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01148         .addReg(Pred[1].getReg())
01149         .addMBB(MBB);
01150     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01151       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01152       MI->RemoveOperand(0);
01153 
01154       MI->setDesc(get(PPC::BCn));
01155       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01156         .addReg(Pred[1].getReg())
01157         .addMBB(MBB);
01158     } else {
01159       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
01160       MI->RemoveOperand(0);
01161 
01162       MI->setDesc(get(PPC::BCC));
01163       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01164         .addImm(Pred[0].getImm())
01165         .addReg(Pred[1].getReg())
01166         .addMBB(MBB);
01167     }
01168 
01169     return true;
01170   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
01171              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
01172     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
01173       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
01174 
01175     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
01176     bool isPPC64 = Subtarget.isPPC64();
01177 
01178     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
01179       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
01180                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
01181       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01182         .addReg(Pred[1].getReg());
01183       return true;
01184     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
01185       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
01186                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
01187       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01188         .addReg(Pred[1].getReg());
01189       return true;
01190     }
01191 
01192     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
01193                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
01194     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
01195       .addImm(Pred[0].getImm())
01196       .addReg(Pred[1].getReg());
01197     return true;
01198   }
01199 
01200   return false;
01201 }
01202 
01203 bool PPCInstrInfo::SubsumesPredicate(
01204                      const SmallVectorImpl<MachineOperand> &Pred1,
01205                      const SmallVectorImpl<MachineOperand> &Pred2) const {
01206   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
01207   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
01208 
01209   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
01210     return false;
01211   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
01212     return false;
01213 
01214   // P1 can only subsume P2 if they test the same condition register.
01215   if (Pred1[1].getReg() != Pred2[1].getReg())
01216     return false;
01217 
01218   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
01219   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
01220 
01221   if (P1 == P2)
01222     return true;
01223 
01224   // Does P1 subsume P2, e.g. GE subsumes GT.
01225   if (P1 == PPC::PRED_LE &&
01226       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
01227     return true;
01228   if (P1 == PPC::PRED_GE &&
01229       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
01230     return true;
01231 
01232   return false;
01233 }
01234 
01235 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
01236                                     std::vector<MachineOperand> &Pred) const {
01237   // Note: At the present time, the contents of Pred from this function is
01238   // unused by IfConversion. This implementation follows ARM by pushing the
01239   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
01240   // predicate, instructions defining CTR or CTR8 are also included as
01241   // predicate-defining instructions.
01242 
01243   const TargetRegisterClass *RCs[] =
01244     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
01245       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
01246 
01247   bool Found = false;
01248   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01249     const MachineOperand &MO = MI->getOperand(i);
01250     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
01251       const TargetRegisterClass *RC = RCs[c];
01252       if (MO.isReg()) {
01253         if (MO.isDef() && RC->contains(MO.getReg())) {
01254           Pred.push_back(MO);
01255           Found = true;
01256         }
01257       } else if (MO.isRegMask()) {
01258         for (TargetRegisterClass::iterator I = RC->begin(),
01259              IE = RC->end(); I != IE; ++I)
01260           if (MO.clobbersPhysReg(*I)) {
01261             Pred.push_back(MO);
01262             Found = true;
01263           }
01264       }
01265     }
01266   }
01267 
01268   return Found;
01269 }
01270 
01271 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
01272   unsigned OpC = MI->getOpcode();
01273   switch (OpC) {
01274   default:
01275     return false;
01276   case PPC::B:
01277   case PPC::BLR:
01278   case PPC::BCTR:
01279   case PPC::BCTR8:
01280   case PPC::BCTRL:
01281   case PPC::BCTRL8:
01282     return true;
01283   }
01284 }
01285 
01286 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
01287                                   unsigned &SrcReg, unsigned &SrcReg2,
01288                                   int &Mask, int &Value) const {
01289   unsigned Opc = MI->getOpcode();
01290 
01291   switch (Opc) {
01292   default: return false;
01293   case PPC::CMPWI:
01294   case PPC::CMPLWI:
01295   case PPC::CMPDI:
01296   case PPC::CMPLDI:
01297     SrcReg = MI->getOperand(1).getReg();
01298     SrcReg2 = 0;
01299     Value = MI->getOperand(2).getImm();
01300     Mask = 0xFFFF;
01301     return true;
01302   case PPC::CMPW:
01303   case PPC::CMPLW:
01304   case PPC::CMPD:
01305   case PPC::CMPLD:
01306   case PPC::FCMPUS:
01307   case PPC::FCMPUD:
01308     SrcReg = MI->getOperand(1).getReg();
01309     SrcReg2 = MI->getOperand(2).getReg();
01310     return true;
01311   }
01312 }
01313 
01314 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
01315                                         unsigned SrcReg, unsigned SrcReg2,
01316                                         int Mask, int Value,
01317                                         const MachineRegisterInfo *MRI) const {
01318   if (DisableCmpOpt)
01319     return false;
01320 
01321   int OpC = CmpInstr->getOpcode();
01322   unsigned CRReg = CmpInstr->getOperand(0).getReg();
01323 
01324   // FP record forms set CR1 based on the execption status bits, not a
01325   // comparison with zero.
01326   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
01327     return false;
01328 
01329   // The record forms set the condition register based on a signed comparison
01330   // with zero (so says the ISA manual). This is not as straightforward as it
01331   // seems, however, because this is always a 64-bit comparison on PPC64, even
01332   // for instructions that are 32-bit in nature (like slw for example).
01333   // So, on PPC32, for unsigned comparisons, we can use the record forms only
01334   // for equality checks (as those don't depend on the sign). On PPC64,
01335   // we are restricted to equality for unsigned 64-bit comparisons and for
01336   // signed 32-bit comparisons the applicability is more restricted.
01337   bool isPPC64 = Subtarget.isPPC64();
01338   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
01339   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
01340   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
01341 
01342   // Get the unique definition of SrcReg.
01343   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
01344   if (!MI) return false;
01345   int MIOpC = MI->getOpcode();
01346 
01347   bool equalityOnly = false;
01348   bool noSub = false;
01349   if (isPPC64) {
01350     if (is32BitSignedCompare) {
01351       // We can perform this optimization only if MI is sign-extending.
01352       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
01353           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
01354           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
01355           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
01356           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
01357         noSub = true;
01358       } else
01359         return false;
01360     } else if (is32BitUnsignedCompare) {
01361       // We can perform this optimization, equality only, if MI is
01362       // zero-extending.
01363       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
01364           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
01365           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
01366         noSub = true;
01367         equalityOnly = true;
01368       } else
01369         return false;
01370     } else
01371       equalityOnly = is64BitUnsignedCompare;
01372   } else
01373     equalityOnly = is32BitUnsignedCompare;
01374 
01375   if (equalityOnly) {
01376     // We need to check the uses of the condition register in order to reject
01377     // non-equality comparisons.
01378     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
01379          IE = MRI->use_instr_end(); I != IE; ++I) {
01380       MachineInstr *UseMI = &*I;
01381       if (UseMI->getOpcode() == PPC::BCC) {
01382         unsigned Pred = UseMI->getOperand(0).getImm();
01383         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
01384           return false;
01385       } else if (UseMI->getOpcode() == PPC::ISEL ||
01386                  UseMI->getOpcode() == PPC::ISEL8) {
01387         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
01388         if (SubIdx != PPC::sub_eq)
01389           return false;
01390       } else
01391         return false;
01392     }
01393   }
01394 
01395   MachineBasicBlock::iterator I = CmpInstr;
01396 
01397   // Scan forward to find the first use of the compare.
01398   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
01399        I != EL; ++I) {
01400     bool FoundUse = false;
01401     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
01402          JE = MRI->use_instr_end(); J != JE; ++J)
01403       if (&*J == &*I) {
01404         FoundUse = true;
01405         break;
01406       }
01407 
01408     if (FoundUse)
01409       break;
01410   }
01411 
01412   // There are two possible candidates which can be changed to set CR[01].
01413   // One is MI, the other is a SUB instruction.
01414   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
01415   MachineInstr *Sub = nullptr;
01416   if (SrcReg2 != 0)
01417     // MI is not a candidate for CMPrr.
01418     MI = nullptr;
01419   // FIXME: Conservatively refuse to convert an instruction which isn't in the
01420   // same BB as the comparison. This is to allow the check below to avoid calls
01421   // (and other explicit clobbers); instead we should really check for these
01422   // more explicitly (in at least a few predecessors).
01423   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
01424     // PPC does not have a record-form SUBri.
01425     return false;
01426   }
01427 
01428   // Search for Sub.
01429   const TargetRegisterInfo *TRI = &getRegisterInfo();
01430   --I;
01431 
01432   // Get ready to iterate backward from CmpInstr.
01433   MachineBasicBlock::iterator E = MI,
01434                               B = CmpInstr->getParent()->begin();
01435 
01436   for (; I != E && !noSub; --I) {
01437     const MachineInstr &Instr = *I;
01438     unsigned IOpC = Instr.getOpcode();
01439 
01440     if (&*I != CmpInstr && (
01441         Instr.modifiesRegister(PPC::CR0, TRI) ||
01442         Instr.readsRegister(PPC::CR0, TRI)))
01443       // This instruction modifies or uses the record condition register after
01444       // the one we want to change. While we could do this transformation, it
01445       // would likely not be profitable. This transformation removes one
01446       // instruction, and so even forcing RA to generate one move probably
01447       // makes it unprofitable.
01448       return false;
01449 
01450     // Check whether CmpInstr can be made redundant by the current instruction.
01451     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
01452          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
01453         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
01454         ((Instr.getOperand(1).getReg() == SrcReg &&
01455           Instr.getOperand(2).getReg() == SrcReg2) ||
01456         (Instr.getOperand(1).getReg() == SrcReg2 &&
01457          Instr.getOperand(2).getReg() == SrcReg))) {
01458       Sub = &*I;
01459       break;
01460     }
01461 
01462     if (I == B)
01463       // The 'and' is below the comparison instruction.
01464       return false;
01465   }
01466 
01467   // Return false if no candidates exist.
01468   if (!MI && !Sub)
01469     return false;
01470 
01471   // The single candidate is called MI.
01472   if (!MI) MI = Sub;
01473 
01474   int NewOpC = -1;
01475   MIOpC = MI->getOpcode();
01476   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
01477     NewOpC = MIOpC;
01478   else {
01479     NewOpC = PPC::getRecordFormOpcode(MIOpC);
01480     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
01481       NewOpC = MIOpC;
01482   }
01483 
01484   // FIXME: On the non-embedded POWER architectures, only some of the record
01485   // forms are fast, and we should use only the fast ones.
01486 
01487   // The defining instruction has a record form (or is already a record
01488   // form). It is possible, however, that we'll need to reverse the condition
01489   // code of the users.
01490   if (NewOpC == -1)
01491     return false;
01492 
01493   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
01494   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
01495 
01496   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
01497   // needs to be updated to be based on SUB.  Push the condition code
01498   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
01499   // condition code of these operands will be modified.
01500   bool ShouldSwap = false;
01501   if (Sub) {
01502     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
01503       Sub->getOperand(2).getReg() == SrcReg;
01504 
01505     // The operands to subf are the opposite of sub, so only in the fixed-point
01506     // case, invert the order.
01507     ShouldSwap = !ShouldSwap;
01508   }
01509 
01510   if (ShouldSwap)
01511     for (MachineRegisterInfo::use_instr_iterator
01512          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
01513          I != IE; ++I) {
01514       MachineInstr *UseMI = &*I;
01515       if (UseMI->getOpcode() == PPC::BCC) {
01516         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
01517         assert((!equalityOnly ||
01518                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
01519                "Invalid predicate for equality-only optimization");
01520         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
01521                                 PPC::getSwappedPredicate(Pred)));
01522       } else if (UseMI->getOpcode() == PPC::ISEL ||
01523                  UseMI->getOpcode() == PPC::ISEL8) {
01524         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
01525         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
01526                "Invalid CR bit for equality-only optimization");
01527 
01528         if (NewSubReg == PPC::sub_lt)
01529           NewSubReg = PPC::sub_gt;
01530         else if (NewSubReg == PPC::sub_gt)
01531           NewSubReg = PPC::sub_lt;
01532 
01533         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
01534                                                  NewSubReg));
01535       } else // We need to abort on a user we don't understand.
01536         return false;
01537     }
01538 
01539   // Create a new virtual register to hold the value of the CR set by the
01540   // record-form instruction. If the instruction was not previously in
01541   // record form, then set the kill flag on the CR.
01542   CmpInstr->eraseFromParent();
01543 
01544   MachineBasicBlock::iterator MII = MI;
01545   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
01546           get(TargetOpcode::COPY), CRReg)
01547     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
01548 
01549   if (MIOpC != NewOpC) {
01550     // We need to be careful here: we're replacing one instruction with
01551     // another, and we need to make sure that we get all of the right
01552     // implicit uses and defs. On the other hand, the caller may be holding
01553     // an iterator to this instruction, and so we can't delete it (this is
01554     // specifically the case if this is the instruction directly after the
01555     // compare).
01556 
01557     const MCInstrDesc &NewDesc = get(NewOpC);
01558     MI->setDesc(NewDesc);
01559 
01560     if (NewDesc.ImplicitDefs)
01561       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
01562            *ImpDefs; ++ImpDefs)
01563         if (!MI->definesRegister(*ImpDefs))
01564           MI->addOperand(*MI->getParent()->getParent(),
01565                          MachineOperand::CreateReg(*ImpDefs, true, true));
01566     if (NewDesc.ImplicitUses)
01567       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
01568            *ImpUses; ++ImpUses)
01569         if (!MI->readsRegister(*ImpUses))
01570           MI->addOperand(*MI->getParent()->getParent(),
01571                          MachineOperand::CreateReg(*ImpUses, false, true));
01572   }
01573 
01574   // Modify the condition code of operands in OperandsToUpdate.
01575   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
01576   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
01577   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
01578     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
01579 
01580   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
01581     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
01582 
01583   return true;
01584 }
01585 
01586 /// GetInstSize - Return the number of bytes of code the specified
01587 /// instruction may be.  This returns the maximum number of bytes.
01588 ///
01589 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
01590   unsigned Opcode = MI->getOpcode();
01591 
01592   if (Opcode == PPC::INLINEASM) {
01593     const MachineFunction *MF = MI->getParent()->getParent();
01594     const char *AsmStr = MI->getOperand(0).getSymbolName();
01595     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
01596   } else {
01597     const MCInstrDesc &Desc = get(Opcode);
01598     return Desc.getSize();
01599   }
01600 }
01601 
01602 #undef DEBUG_TYPE
01603 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
01604 
01605 namespace {
01606   // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
01607   // (Altivec and scalar floating-point registers), we need to transform the
01608   // copies into subregister copies with other restrictions.
01609   struct PPCVSXFMAMutate : public MachineFunctionPass {
01610     static char ID;
01611     PPCVSXFMAMutate() : MachineFunctionPass(ID) {
01612       initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
01613     }
01614 
01615     LiveIntervals *LIS;
01616 
01617     const PPCTargetMachine *TM;
01618     const PPCInstrInfo *TII;
01619 
01620 protected:
01621     bool processBlock(MachineBasicBlock &MBB) {
01622       bool Changed = false;
01623 
01624       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
01625       const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
01626       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01627            I != IE; ++I) {
01628         MachineInstr *MI = I;
01629 
01630         // The default (A-type) VSX FMA form kills the addend (it is taken from
01631         // the target register, which is then updated to reflect the result of
01632         // the FMA). If the instruction, however, kills one of the registers
01633         // used for the product, then we can use the M-form instruction (which
01634         // will take that value from the to-be-defined register).
01635 
01636         int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
01637         if (AltOpc == -1)
01638           continue;
01639 
01640         // This pass is run after register coalescing, and so we're looking for
01641         // a situation like this:
01642         //   ...
01643         //   %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
01644         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
01645         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
01646         //   ...
01647         //   %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
01648         //                         %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
01649         //   ...
01650         // Where we can eliminate the copy by changing from the A-type to the
01651         // M-type instruction. Specifically, for this example, this means:
01652         //   %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
01653         //                         %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
01654         // is replaced by:
01655         //   %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
01656         //                         %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
01657         // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
01658 
01659         SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
01660 
01661         VNInfo *AddendValNo =
01662           LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
01663         MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
01664 
01665         // The addend and this instruction must be in the same block.
01666 
01667         if (!AddendMI || AddendMI->getParent() != MI->getParent())
01668           continue;
01669 
01670         // The addend must be a full copy within the same register class.
01671 
01672         if (!AddendMI->isFullCopy())
01673           continue;
01674 
01675         unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
01676         if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
01677           if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
01678               MRI.getRegClass(AddendSrcReg))
01679             continue;
01680         } else {
01681           // If AddendSrcReg is a physical register, make sure the destination
01682           // register class contains it.
01683           if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
01684                 ->contains(AddendSrcReg))
01685             continue;
01686         }
01687 
01688         // In theory, there could be other uses of the addend copy before this
01689         // fma.  We could deal with this, but that would require additional
01690         // logic below and I suspect it will not occur in any relevant
01691         // situations.  Additionally, check whether the copy source is killed
01692         // prior to the fma.  In order to replace the addend here with the
01693         // source of the copy, it must still be live here.  We can't use
01694         // interval testing for a physical register, so as long as we're
01695         // walking the MIs we may as well test liveness here.
01696         bool OtherUsers = false, KillsAddendSrc = false;
01697         for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
01698              J != JE; --J) {
01699           if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
01700             OtherUsers = true;
01701             break;
01702           }
01703           if (J->modifiesRegister(AddendSrcReg, TRI) ||
01704               J->killsRegister(AddendSrcReg, TRI)) {
01705             KillsAddendSrc = true;
01706             break;
01707           }
01708         }
01709 
01710         if (OtherUsers || KillsAddendSrc)
01711           continue;
01712 
01713         // Find one of the product operands that is killed by this instruction.
01714 
01715         unsigned KilledProdOp = 0, OtherProdOp = 0;
01716         if (LIS->getInterval(MI->getOperand(2).getReg())
01717                      .Query(FMAIdx).isKill()) {
01718           KilledProdOp = 2;
01719           OtherProdOp  = 3;
01720         } else if (LIS->getInterval(MI->getOperand(3).getReg())
01721                      .Query(FMAIdx).isKill()) {
01722           KilledProdOp = 3;
01723           OtherProdOp  = 2;
01724         }
01725 
01726         // If there are no killed product operands, then this transformation is
01727         // likely not profitable.
01728         if (!KilledProdOp)
01729           continue;
01730 
01731         // For virtual registers, verify that the addend source register
01732         // is live here (as should have been assured above).
01733         assert((!TargetRegisterInfo::isVirtualRegister(AddendSrcReg) ||
01734                 LIS->getInterval(AddendSrcReg).liveAt(FMAIdx)) &&
01735                "Addend source register is not live!");
01736 
01737         // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
01738 
01739         unsigned AddReg = AddendMI->getOperand(1).getReg();
01740         unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
01741         unsigned OtherProdReg  = MI->getOperand(OtherProdOp).getReg();
01742 
01743         unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
01744         unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
01745         unsigned OtherProdSubReg  = MI->getOperand(OtherProdOp).getSubReg();
01746 
01747         bool AddRegKill = AddendMI->getOperand(1).isKill();
01748         bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
01749         bool OtherProdRegKill  = MI->getOperand(OtherProdOp).isKill();
01750 
01751         bool AddRegUndef = AddendMI->getOperand(1).isUndef();
01752         bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
01753         bool OtherProdRegUndef  = MI->getOperand(OtherProdOp).isUndef();
01754 
01755         unsigned OldFMAReg = MI->getOperand(0).getReg();
01756 
01757         // The transformation doesn't work well with things like:
01758         //    %vreg5 = A-form-op %vreg5, %vreg11, %vreg5;
01759         // so leave such things alone.
01760         if (OldFMAReg == KilledProdReg)
01761           continue;
01762 
01763         assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
01764                "Addend copy not tied to old FMA output!");
01765 
01766         DEBUG(dbgs() << "VSX FMA Mutation:\n    " << *MI;);
01767 
01768         MI->getOperand(0).setReg(KilledProdReg);
01769         MI->getOperand(1).setReg(KilledProdReg);
01770         MI->getOperand(3).setReg(AddReg);
01771         MI->getOperand(2).setReg(OtherProdReg);
01772 
01773         MI->getOperand(0).setSubReg(KilledProdSubReg);
01774         MI->getOperand(1).setSubReg(KilledProdSubReg);
01775         MI->getOperand(3).setSubReg(AddSubReg);
01776         MI->getOperand(2).setSubReg(OtherProdSubReg);
01777 
01778         MI->getOperand(1).setIsKill(KilledProdRegKill);
01779         MI->getOperand(3).setIsKill(AddRegKill);
01780         MI->getOperand(2).setIsKill(OtherProdRegKill);
01781 
01782         MI->getOperand(1).setIsUndef(KilledProdRegUndef);
01783         MI->getOperand(3).setIsUndef(AddRegUndef);
01784         MI->getOperand(2).setIsUndef(OtherProdRegUndef);
01785 
01786         MI->setDesc(TII->get(AltOpc));
01787 
01788         DEBUG(dbgs() << " -> " << *MI);
01789 
01790         // The killed product operand was killed here, so we can reuse it now
01791         // for the result of the fma.
01792 
01793         LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
01794         VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
01795         for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
01796              UI != UE;) {
01797           MachineOperand &UseMO = *UI;
01798           MachineInstr *UseMI = UseMO.getParent();
01799           ++UI;
01800 
01801           // Don't replace the result register of the copy we're about to erase.
01802           if (UseMI == AddendMI)
01803             continue;
01804 
01805           UseMO.setReg(KilledProdReg);
01806           UseMO.setSubReg(KilledProdSubReg);
01807         }
01808 
01809         // Extend the live intervals of the killed product operand to hold the
01810         // fma result.
01811 
01812         LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
01813         for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
01814              AI != AE; ++AI) {
01815           // Don't add the segment that corresponds to the original copy.
01816           if (AI->valno == AddendValNo)
01817             continue;
01818 
01819           VNInfo *NewFMAValNo =
01820             NewFMAInt.getNextValue(AI->start,
01821                                    LIS->getVNInfoAllocator());
01822 
01823           NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
01824                                                      NewFMAValNo));
01825         }
01826         DEBUG(dbgs() << "  extended: " << NewFMAInt << '\n');
01827 
01828         FMAInt.removeValNo(FMAValNo);
01829         DEBUG(dbgs() << "  trimmed:  " << FMAInt << '\n');
01830 
01831         // Remove the (now unused) copy.
01832 
01833         DEBUG(dbgs() << "  removing: " << *AddendMI << '\n');
01834         LIS->RemoveMachineInstrFromMaps(AddendMI);
01835         AddendMI->eraseFromParent();
01836 
01837         Changed = true;
01838       }
01839 
01840       return Changed;
01841     }
01842 
01843 public:
01844     bool runOnMachineFunction(MachineFunction &MF) override {
01845       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
01846       // If we don't have VSX then go ahead and return without doing
01847       // anything.
01848       if (!TM->getSubtargetImpl()->hasVSX())
01849         return false;
01850 
01851       LIS = &getAnalysis<LiveIntervals>();
01852 
01853       TII = TM->getSubtargetImpl()->getInstrInfo();
01854 
01855       bool Changed = false;
01856 
01857       if (DisableVSXFMAMutate)
01858         return Changed;
01859 
01860       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
01861         MachineBasicBlock &B = *I++;
01862         if (processBlock(B))
01863           Changed = true;
01864       }
01865 
01866       return Changed;
01867     }
01868 
01869     void getAnalysisUsage(AnalysisUsage &AU) const override {
01870       AU.addRequired<LiveIntervals>();
01871       AU.addPreserved<LiveIntervals>();
01872       AU.addRequired<SlotIndexes>();
01873       AU.addPreserved<SlotIndexes>();
01874       MachineFunctionPass::getAnalysisUsage(AU);
01875     }
01876   };
01877 }
01878 
01879 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
01880                       "PowerPC VSX FMA Mutation", false, false)
01881 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
01882 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
01883 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
01884                     "PowerPC VSX FMA Mutation", false, false)
01885 
01886 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
01887 
01888 char PPCVSXFMAMutate::ID = 0;
01889 FunctionPass*
01890 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
01891 
01892 #undef DEBUG_TYPE
01893 #define DEBUG_TYPE "ppc-vsx-copy"
01894 
01895 namespace llvm {
01896   void initializePPCVSXCopyPass(PassRegistry&);
01897 }
01898 
01899 namespace {
01900   // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
01901   // (Altivec and scalar floating-point registers), we need to transform the
01902   // copies into subregister copies with other restrictions.
01903   struct PPCVSXCopy : public MachineFunctionPass {
01904     static char ID;
01905     PPCVSXCopy() : MachineFunctionPass(ID) {
01906       initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
01907     }
01908 
01909     const PPCTargetMachine *TM;
01910     const PPCInstrInfo *TII;
01911 
01912     bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
01913                       MachineRegisterInfo &MRI) {
01914       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
01915         return RC->hasSubClassEq(MRI.getRegClass(Reg));
01916       } else if (RC->contains(Reg)) {
01917         return true;
01918       }
01919 
01920       return false;
01921     }
01922 
01923     bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
01924       return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
01925     }
01926 
01927     bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
01928       return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
01929     }
01930 
01931     bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
01932       return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
01933     }
01934 
01935 protected:
01936     bool processBlock(MachineBasicBlock &MBB) {
01937       bool Changed = false;
01938 
01939       MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
01940       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
01941            I != IE; ++I) {
01942         MachineInstr *MI = I;
01943         if (!MI->isFullCopy())
01944           continue;
01945 
01946         MachineOperand &DstMO = MI->getOperand(0);
01947         MachineOperand &SrcMO = MI->getOperand(1);
01948 
01949         if ( IsVSReg(DstMO.getReg(), MRI) &&
01950             !IsVSReg(SrcMO.getReg(), MRI)) {
01951           // This is a copy *to* a VSX register from a non-VSX register.
01952           Changed = true;
01953 
01954           const TargetRegisterClass *SrcRC =
01955             IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
01956                                            &PPC::VSLRCRegClass;
01957           assert((IsF8Reg(SrcMO.getReg(), MRI) ||
01958                   IsVRReg(SrcMO.getReg(), MRI)) &&
01959                  "Unknown source for a VSX copy");
01960 
01961           unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
01962           BuildMI(MBB, MI, MI->getDebugLoc(),
01963                   TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
01964             .addImm(1) // add 1, not 0, because there is no implicit clearing
01965                        // of the high bits.
01966             .addOperand(SrcMO)
01967             .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
01968                                                    PPC::sub_64);
01969 
01970           // The source of the original copy is now the new virtual register.
01971           SrcMO.setReg(NewVReg);
01972         } else if (!IsVSReg(DstMO.getReg(), MRI) &&
01973                     IsVSReg(SrcMO.getReg(), MRI)) {
01974           // This is a copy *from* a VSX register to a non-VSX register.
01975           Changed = true;
01976 
01977           const TargetRegisterClass *DstRC =
01978             IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
01979                                            &PPC::VSLRCRegClass;
01980           assert((IsF8Reg(DstMO.getReg(), MRI) ||
01981                   IsVRReg(DstMO.getReg(), MRI)) &&
01982                  "Unknown destination for a VSX copy");
01983 
01984           // Copy the VSX value into a new VSX register of the correct subclass.
01985           unsigned NewVReg = MRI.createVirtualRegister(DstRC);
01986           BuildMI(MBB, MI, MI->getDebugLoc(),
01987                   TII->get(TargetOpcode::COPY), NewVReg)
01988             .addOperand(SrcMO);
01989 
01990           // Transform the original copy into a subregister extraction copy.
01991           SrcMO.setReg(NewVReg);
01992           SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
01993                                                          PPC::sub_64);
01994         }
01995       }
01996 
01997       return Changed;
01998     }
01999 
02000 public:
02001     bool runOnMachineFunction(MachineFunction &MF) override {
02002       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
02003       // If we don't have VSX on the subtarget, don't do anything.
02004       if (!TM->getSubtargetImpl()->hasVSX())
02005         return false;
02006       TII = TM->getSubtargetImpl()->getInstrInfo();
02007 
02008       bool Changed = false;
02009 
02010       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
02011         MachineBasicBlock &B = *I++;
02012         if (processBlock(B))
02013           Changed = true;
02014       }
02015 
02016       return Changed;
02017     }
02018 
02019     void getAnalysisUsage(AnalysisUsage &AU) const override {
02020       MachineFunctionPass::getAnalysisUsage(AU);
02021     }
02022   };
02023 }
02024 
02025 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
02026                 "PowerPC VSX Copy Legalization", false, false)
02027 
02028 char PPCVSXCopy::ID = 0;
02029 FunctionPass*
02030 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
02031 
02032 #undef DEBUG_TYPE
02033 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
02034 
02035 namespace llvm {
02036   void initializePPCVSXCopyCleanupPass(PassRegistry&);
02037 }
02038 
02039 namespace {
02040   // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
02041   // registers (mostly because the ABI code still places all values into the
02042   // "traditional" floating-point and vector registers). Remove them here.
02043   struct PPCVSXCopyCleanup : public MachineFunctionPass {
02044     static char ID;
02045     PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
02046       initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
02047     }
02048 
02049     const PPCTargetMachine *TM;
02050     const PPCInstrInfo *TII;
02051 
02052 protected:
02053     bool processBlock(MachineBasicBlock &MBB) {
02054       bool Changed = false;
02055 
02056       SmallVector<MachineInstr *, 4> ToDelete;
02057       for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
02058            I != IE; ++I) {
02059         MachineInstr *MI = I;
02060         if (MI->getOpcode() == PPC::XXLOR &&
02061             MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
02062             MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
02063           ToDelete.push_back(MI);
02064       }
02065 
02066       if (!ToDelete.empty())
02067         Changed = true;
02068 
02069       for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
02070         DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
02071         ToDelete[i]->eraseFromParent();
02072       }
02073 
02074       return Changed;
02075     }
02076 
02077 public:
02078     bool runOnMachineFunction(MachineFunction &MF) override {
02079       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
02080       // If we don't have VSX don't bother doing anything here.
02081       if (!TM->getSubtargetImpl()->hasVSX())
02082         return false;
02083       TII = TM->getSubtargetImpl()->getInstrInfo();
02084 
02085       bool Changed = false;
02086 
02087       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
02088         MachineBasicBlock &B = *I++;
02089         if (processBlock(B))
02090           Changed = true;
02091       }
02092 
02093       return Changed;
02094     }
02095 
02096     void getAnalysisUsage(AnalysisUsage &AU) const override {
02097       MachineFunctionPass::getAnalysisUsage(AU);
02098     }
02099   };
02100 }
02101 
02102 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
02103                 "PowerPC VSX Copy Cleanup", false, false)
02104 
02105 char PPCVSXCopyCleanup::ID = 0;
02106 FunctionPass*
02107 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
02108 
02109 #undef DEBUG_TYPE
02110 #define DEBUG_TYPE "ppc-early-ret"
02111 STATISTIC(NumBCLR, "Number of early conditional returns");
02112 STATISTIC(NumBLR,  "Number of early returns");
02113 
02114 namespace llvm {
02115   void initializePPCEarlyReturnPass(PassRegistry&);
02116 }
02117 
02118 namespace {
02119   // PPCEarlyReturn pass - For simple functions without epilogue code, move
02120   // returns up, and create conditional returns, to avoid unnecessary
02121   // branch-to-blr sequences.
02122   struct PPCEarlyReturn : public MachineFunctionPass {
02123     static char ID;
02124     PPCEarlyReturn() : MachineFunctionPass(ID) {
02125       initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
02126     }
02127 
02128     const PPCTargetMachine *TM;
02129     const PPCInstrInfo *TII;
02130 
02131 protected:
02132     bool processBlock(MachineBasicBlock &ReturnMBB) {
02133       bool Changed = false;
02134 
02135       MachineBasicBlock::iterator I = ReturnMBB.begin();
02136       I = ReturnMBB.SkipPHIsAndLabels(I);
02137 
02138       // The block must be essentially empty except for the blr.
02139       if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
02140           I != ReturnMBB.getLastNonDebugInstr())
02141         return Changed;
02142 
02143       SmallVector<MachineBasicBlock*, 8> PredToRemove;
02144       for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
02145            PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
02146         bool OtherReference = false, BlockChanged = false;
02147         for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
02148           if (J->getOpcode() == PPC::B) {
02149             if (J->getOperand(0).getMBB() == &ReturnMBB) {
02150               // This is an unconditional branch to the return. Replace the
02151               // branch with a blr.
02152               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
02153               MachineBasicBlock::iterator K = J--;
02154               K->eraseFromParent();
02155               BlockChanged = true;
02156               ++NumBLR;
02157               continue;
02158             }
02159           } else if (J->getOpcode() == PPC::BCC) {
02160             if (J->getOperand(2).getMBB() == &ReturnMBB) {
02161               // This is a conditional branch to the return. Replace the branch
02162               // with a bclr.
02163               BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
02164                 .addImm(J->getOperand(0).getImm())
02165                 .addReg(J->getOperand(1).getReg());
02166               MachineBasicBlock::iterator K = J--;
02167               K->eraseFromParent();
02168               BlockChanged = true;
02169               ++NumBCLR;
02170               continue;
02171             }
02172           } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
02173             if (J->getOperand(1).getMBB() == &ReturnMBB) {
02174               // This is a conditional branch to the return. Replace the branch
02175               // with a bclr.
02176               BuildMI(**PI, J, J->getDebugLoc(),
02177                       TII->get(J->getOpcode() == PPC::BC ?
02178                                PPC::BCLR : PPC::BCLRn))
02179                 .addReg(J->getOperand(0).getReg());
02180               MachineBasicBlock::iterator K = J--;
02181               K->eraseFromParent();
02182               BlockChanged = true;
02183               ++NumBCLR;
02184               continue;
02185             }
02186           } else if (J->isBranch()) {
02187             if (J->isIndirectBranch()) {
02188               if (ReturnMBB.hasAddressTaken())
02189                 OtherReference = true;
02190             } else
02191               for (unsigned i = 0; i < J->getNumOperands(); ++i)
02192                 if (J->getOperand(i).isMBB() &&
02193                     J->getOperand(i).getMBB() == &ReturnMBB)
02194                   OtherReference = true;
02195           } else if (!J->isTerminator() && !J->isDebugValue())
02196             break;
02197 
02198           if (J == (*PI)->begin())
02199             break;
02200 
02201           --J;
02202         }
02203 
02204         if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
02205           OtherReference = true;
02206 
02207         // Predecessors are stored in a vector and can't be removed here.
02208         if (!OtherReference && BlockChanged) {
02209           PredToRemove.push_back(*PI);
02210         }
02211 
02212         if (BlockChanged)
02213           Changed = true;
02214       }
02215 
02216       for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
02217         PredToRemove[i]->removeSuccessor(&ReturnMBB);
02218 
02219       if (Changed && !ReturnMBB.hasAddressTaken()) {
02220         // We now might be able to merge this blr-only block into its
02221         // by-layout predecessor.
02222         if (ReturnMBB.pred_size() == 1 &&
02223             (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
02224           // Move the blr into the preceding block.
02225           MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
02226           PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
02227           PrevMBB.removeSuccessor(&ReturnMBB);
02228         }
02229 
02230         if (ReturnMBB.pred_empty())
02231           ReturnMBB.eraseFromParent();
02232       }
02233 
02234       return Changed;
02235     }
02236 
02237 public:
02238     bool runOnMachineFunction(MachineFunction &MF) override {
02239       TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
02240       TII = TM->getSubtargetImpl()->getInstrInfo();
02241 
02242       bool Changed = false;
02243 
02244       // If the function does not have at least two blocks, then there is
02245       // nothing to do.
02246       if (MF.size() < 2)
02247         return Changed;
02248 
02249       for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
02250         MachineBasicBlock &B = *I++;
02251         if (processBlock(B))
02252           Changed = true;
02253       }
02254 
02255       return Changed;
02256     }
02257 
02258     void getAnalysisUsage(AnalysisUsage &AU) const override {
02259       MachineFunctionPass::getAnalysisUsage(AU);
02260     }
02261   };
02262 }
02263 
02264 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
02265                 "PowerPC Early-Return Creation", false, false)
02266 
02267 char PPCEarlyReturn::ID = 0;
02268 FunctionPass*
02269 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }