1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the PowerPC implementation of the TargetInstrInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
35 #define GET_INSTRMAP_INFO
36 #define GET_INSTRINFO_CTOR
37 #include "PPCGenInstrInfo.inc"
42 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
43 cl::desc("Disable analysis for CTR loops"));
45 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
46 cl::desc("Disable compare instruction optimization"), cl::Hidden);
48 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
49 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
50 TM(tm), RI(*TM.getSubtargetImpl(), *this) {}
52 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
53 /// this target when scheduling the DAG.
54 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
55 const TargetMachine *TM,
56 const ScheduleDAG *DAG) const {
57 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
58 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
59 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
60 const InstrItineraryData *II = TM->getInstrItineraryData();
61 return new PPCScoreboardHazardRecognizer(II, DAG);
64 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
67 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
68 /// to use for this target when scheduling the DAG.
69 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
70 const InstrItineraryData *II,
71 const ScheduleDAG *DAG) const {
72 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
74 // Most subtargets use a PPC970 recognizer.
75 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
76 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
77 const TargetInstrInfo *TII = TM.getInstrInfo();
78 assert(TII && "No InstrInfo?");
80 return new PPCHazardRecognizer970(*TII);
83 return new PPCScoreboardHazardRecognizer(II, DAG);
86 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
87 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
88 unsigned &SrcReg, unsigned &DstReg,
89 unsigned &SubIdx) const {
90 switch (MI.getOpcode()) {
91 default: return false;
93 case PPC::EXTSW_32_64:
94 SrcReg = MI.getOperand(1).getReg();
95 DstReg = MI.getOperand(0).getReg();
101 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
102 int &FrameIndex) const {
103 // Note: This list must be kept consistent with LoadRegFromStackSlot.
104 switch (MI->getOpcode()) {
110 case PPC::RESTORE_CR:
112 case PPC::RESTORE_VRSAVE:
113 // Check for the operands added by addFrameReference (the immediate is the
114 // offset which defaults to 0).
115 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
116 MI->getOperand(2).isFI()) {
117 FrameIndex = MI->getOperand(2).getIndex();
118 return MI->getOperand(0).getReg();
125 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
126 int &FrameIndex) const {
127 // Note: This list must be kept consistent with StoreRegToStackSlot.
128 switch (MI->getOpcode()) {
136 case PPC::SPILL_VRSAVE:
137 // Check for the operands added by addFrameReference (the immediate is the
138 // offset which defaults to 0).
139 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
140 MI->getOperand(2).isFI()) {
141 FrameIndex = MI->getOperand(2).getIndex();
142 return MI->getOperand(0).getReg();
149 // commuteInstruction - We can commute rlwimi instructions, but only if the
150 // rotate amt is zero. We also have to munge the immediates a bit.
152 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
153 MachineFunction &MF = *MI->getParent()->getParent();
155 // Normal instructions can be commuted the obvious way.
156 if (MI->getOpcode() != PPC::RLWIMI &&
157 MI->getOpcode() != PPC::RLWIMIo)
158 return TargetInstrInfo::commuteInstruction(MI, NewMI);
160 // Cannot commute if it has a non-zero rotate count.
161 if (MI->getOperand(3).getImm() != 0)
164 // If we have a zero rotate count, we have:
166 // Op0 = (Op1 & ~M) | (Op2 & M)
168 // M = mask((ME+1)&31, (MB-1)&31)
169 // Op0 = (Op2 & ~M) | (Op1 & M)
172 unsigned Reg0 = MI->getOperand(0).getReg();
173 unsigned Reg1 = MI->getOperand(1).getReg();
174 unsigned Reg2 = MI->getOperand(2).getReg();
175 bool Reg1IsKill = MI->getOperand(1).isKill();
176 bool Reg2IsKill = MI->getOperand(2).isKill();
177 bool ChangeReg0 = false;
178 // If machine instrs are no longer in two-address forms, update
179 // destination register as well.
181 // Must be two address instruction!
182 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
183 "Expecting a two-address instruction!");
189 unsigned MB = MI->getOperand(4).getImm();
190 unsigned ME = MI->getOperand(5).getImm();
193 // Create a new instruction.
194 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
195 bool Reg0IsDead = MI->getOperand(0).isDead();
196 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
197 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
198 .addReg(Reg2, getKillRegState(Reg2IsKill))
199 .addReg(Reg1, getKillRegState(Reg1IsKill))
201 .addImm((MB-1) & 31);
205 MI->getOperand(0).setReg(Reg2);
206 MI->getOperand(2).setReg(Reg1);
207 MI->getOperand(1).setReg(Reg2);
208 MI->getOperand(2).setIsKill(Reg1IsKill);
209 MI->getOperand(1).setIsKill(Reg2IsKill);
211 // Swap the mask around.
212 MI->getOperand(4).setImm((ME+1) & 31);
213 MI->getOperand(5).setImm((MB-1) & 31);
217 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
218 MachineBasicBlock::iterator MI) const {
220 BuildMI(MBB, MI, DL, get(PPC::NOP));
225 // Note: If the condition register is set to CTR or CTR8 then this is a
226 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
227 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
228 MachineBasicBlock *&FBB,
229 SmallVectorImpl<MachineOperand> &Cond,
230 bool AllowModify) const {
231 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
233 // If the block has no terminators, it just falls into the block after it.
234 MachineBasicBlock::iterator I = MBB.end();
235 if (I == MBB.begin())
238 while (I->isDebugValue()) {
239 if (I == MBB.begin())
243 if (!isUnpredicatedTerminator(I))
246 // Get the last instruction in the block.
247 MachineInstr *LastInst = I;
249 // If there is only one terminator instruction, process it.
250 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
251 if (LastInst->getOpcode() == PPC::B) {
252 if (!LastInst->getOperand(0).isMBB())
254 TBB = LastInst->getOperand(0).getMBB();
256 } else if (LastInst->getOpcode() == PPC::BCC) {
257 if (!LastInst->getOperand(2).isMBB())
259 // Block ends with fall-through condbranch.
260 TBB = LastInst->getOperand(2).getMBB();
261 Cond.push_back(LastInst->getOperand(0));
262 Cond.push_back(LastInst->getOperand(1));
264 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
265 LastInst->getOpcode() == PPC::BDNZ) {
266 if (!LastInst->getOperand(0).isMBB())
268 if (DisableCTRLoopAnal)
270 TBB = LastInst->getOperand(0).getMBB();
271 Cond.push_back(MachineOperand::CreateImm(1));
272 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
275 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
276 LastInst->getOpcode() == PPC::BDZ) {
277 if (!LastInst->getOperand(0).isMBB())
279 if (DisableCTRLoopAnal)
281 TBB = LastInst->getOperand(0).getMBB();
282 Cond.push_back(MachineOperand::CreateImm(0));
283 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
288 // Otherwise, don't know what this is.
292 // Get the instruction before it if it's a terminator.
293 MachineInstr *SecondLastInst = I;
295 // If there are three terminators, we don't know what sort of block this is.
296 if (SecondLastInst && I != MBB.begin() &&
297 isUnpredicatedTerminator(--I))
300 // If the block ends with PPC::B and PPC:BCC, handle it.
301 if (SecondLastInst->getOpcode() == PPC::BCC &&
302 LastInst->getOpcode() == PPC::B) {
303 if (!SecondLastInst->getOperand(2).isMBB() ||
304 !LastInst->getOperand(0).isMBB())
306 TBB = SecondLastInst->getOperand(2).getMBB();
307 Cond.push_back(SecondLastInst->getOperand(0));
308 Cond.push_back(SecondLastInst->getOperand(1));
309 FBB = LastInst->getOperand(0).getMBB();
311 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
312 SecondLastInst->getOpcode() == PPC::BDNZ) &&
313 LastInst->getOpcode() == PPC::B) {
314 if (!SecondLastInst->getOperand(0).isMBB() ||
315 !LastInst->getOperand(0).isMBB())
317 if (DisableCTRLoopAnal)
319 TBB = SecondLastInst->getOperand(0).getMBB();
320 Cond.push_back(MachineOperand::CreateImm(1));
321 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
323 FBB = LastInst->getOperand(0).getMBB();
325 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
326 SecondLastInst->getOpcode() == PPC::BDZ) &&
327 LastInst->getOpcode() == PPC::B) {
328 if (!SecondLastInst->getOperand(0).isMBB() ||
329 !LastInst->getOperand(0).isMBB())
331 if (DisableCTRLoopAnal)
333 TBB = SecondLastInst->getOperand(0).getMBB();
334 Cond.push_back(MachineOperand::CreateImm(0));
335 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
337 FBB = LastInst->getOperand(0).getMBB();
341 // If the block ends with two PPC:Bs, handle it. The second one is not
342 // executed, so remove it.
343 if (SecondLastInst->getOpcode() == PPC::B &&
344 LastInst->getOpcode() == PPC::B) {
345 if (!SecondLastInst->getOperand(0).isMBB())
347 TBB = SecondLastInst->getOperand(0).getMBB();
350 I->eraseFromParent();
354 // Otherwise, can't handle this.
358 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
359 MachineBasicBlock::iterator I = MBB.end();
360 if (I == MBB.begin()) return 0;
362 while (I->isDebugValue()) {
363 if (I == MBB.begin())
367 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
368 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
369 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
372 // Remove the branch.
373 I->eraseFromParent();
377 if (I == MBB.begin()) return 1;
379 if (I->getOpcode() != PPC::BCC &&
380 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
381 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
384 // Remove the branch.
385 I->eraseFromParent();
390 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
391 MachineBasicBlock *FBB,
392 const SmallVectorImpl<MachineOperand> &Cond,
394 // Shouldn't be a fall through.
395 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
396 assert((Cond.size() == 2 || Cond.size() == 0) &&
397 "PPC branch conditions have two components!");
399 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
403 if (Cond.empty()) // Unconditional branch
404 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
405 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
406 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
407 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
408 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
409 else // Conditional branch
410 BuildMI(&MBB, DL, get(PPC::BCC))
411 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
415 // Two-way Conditional Branch.
416 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
417 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
418 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
419 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
421 BuildMI(&MBB, DL, get(PPC::BCC))
422 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
423 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
428 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
429 const SmallVectorImpl<MachineOperand> &Cond,
430 unsigned TrueReg, unsigned FalseReg,
431 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
432 if (!TM.getSubtargetImpl()->hasISEL())
435 if (Cond.size() != 2)
438 // If this is really a bdnz-like condition, then it cannot be turned into a
440 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
443 // Check register classes.
444 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
445 const TargetRegisterClass *RC =
446 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
450 // isel is for regular integer GPRs only.
451 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
452 !PPC::G8RCRegClass.hasSubClassEq(RC))
455 // FIXME: These numbers are for the A2, how well they work for other cores is
456 // an open question. On the A2, the isel instruction has a 2-cycle latency
457 // but single-cycle throughput. These numbers are used in combination with
458 // the MispredictPenalty setting from the active SchedMachineModel.
466 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
467 MachineBasicBlock::iterator MI, DebugLoc dl,
469 const SmallVectorImpl<MachineOperand> &Cond,
470 unsigned TrueReg, unsigned FalseReg) const {
471 assert(Cond.size() == 2 &&
472 "PPC branch conditions have two components!");
474 assert(TM.getSubtargetImpl()->hasISEL() &&
475 "Cannot insert select on target without ISEL support");
477 // Get the register classes.
478 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
479 const TargetRegisterClass *RC =
480 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
481 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
482 assert((PPC::GPRCRegClass.hasSubClassEq(RC) ||
483 PPC::G8RCRegClass.hasSubClassEq(RC)) &&
484 "isel is for regular integer GPRs only");
487 PPC::GPRCRegClass.hasSubClassEq(RC) ? PPC::ISEL : PPC::ISEL8;
488 unsigned SelectPred = Cond[0].getImm();
492 switch (SelectPred) {
493 default: llvm_unreachable("invalid predicate for isel");
494 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
495 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
496 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
497 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
498 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
499 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
500 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
501 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
504 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
505 SecondReg = SwapOps ? TrueReg : FalseReg;
507 // The first input register of isel cannot be r0. If it is a member
508 // of a register class that can be r0, then copy it first (the
509 // register allocator should eliminate the copy).
510 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
511 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
512 const TargetRegisterClass *FirstRC =
513 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
514 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
515 unsigned OldFirstReg = FirstReg;
516 FirstReg = MRI.createVirtualRegister(FirstRC);
517 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
518 .addReg(OldFirstReg);
521 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
522 .addReg(FirstReg).addReg(SecondReg)
523 .addReg(Cond[1].getReg(), 0, SubIdx);
526 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
527 MachineBasicBlock::iterator I, DebugLoc DL,
528 unsigned DestReg, unsigned SrcReg,
529 bool KillSrc) const {
531 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
533 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
535 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
537 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
539 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
541 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
544 llvm_unreachable("Impossible reg-to-reg copy");
546 const MCInstrDesc &MCID = get(Opc);
547 if (MCID.getNumOperands() == 3)
548 BuildMI(MBB, I, DL, MCID, DestReg)
549 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
551 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
554 // This function returns true if a CR spill is necessary and false otherwise.
556 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
557 unsigned SrcReg, bool isKill,
559 const TargetRegisterClass *RC,
560 SmallVectorImpl<MachineInstr*> &NewMIs,
561 bool &NonRI, bool &SpillsVRS) const{
562 // Note: If additional store instructions are added here,
563 // update isStoreToStackSlot.
566 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
567 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
569 getKillRegState(isKill)),
571 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
572 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
574 getKillRegState(isKill)),
576 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
577 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
579 getKillRegState(isKill)),
581 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
582 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
584 getKillRegState(isKill)),
586 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
587 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
589 getKillRegState(isKill)),
592 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
593 // FIXME: We use CRi here because there is no mtcrf on a bit. Since the
594 // backend currently only uses CR1EQ as an individual bit, this should
595 // not cause any bug. If we need other uses of CR bits, the following
596 // code may be invalid.
598 if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
599 SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
601 else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
602 SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
604 else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
605 SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
607 else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
608 SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
610 else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
611 SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
613 else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
614 SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
616 else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
617 SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
619 else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
620 SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
623 return StoreRegToStackSlot(MF, Reg, isKill, FrameIdx,
624 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
626 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
627 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
629 getKillRegState(isKill)),
632 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
633 assert(TM.getSubtargetImpl()->isDarwin() &&
634 "VRSAVE only needs spill/restore on Darwin");
635 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
637 getKillRegState(isKill)),
641 llvm_unreachable("Unknown regclass!");
648 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
649 MachineBasicBlock::iterator MI,
650 unsigned SrcReg, bool isKill, int FrameIdx,
651 const TargetRegisterClass *RC,
652 const TargetRegisterInfo *TRI) const {
653 MachineFunction &MF = *MBB.getParent();
654 SmallVector<MachineInstr*, 4> NewMIs;
656 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
657 FuncInfo->setHasSpills();
659 bool NonRI = false, SpillsVRS = false;
660 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
662 FuncInfo->setSpillsCR();
665 FuncInfo->setSpillsVRSAVE();
668 FuncInfo->setHasNonRISpills();
670 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
671 MBB.insert(MI, NewMIs[i]);
673 const MachineFrameInfo &MFI = *MF.getFrameInfo();
674 MachineMemOperand *MMO =
675 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
676 MachineMemOperand::MOStore,
677 MFI.getObjectSize(FrameIdx),
678 MFI.getObjectAlignment(FrameIdx));
679 NewMIs.back()->addMemOperand(MF, MMO);
683 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
684 unsigned DestReg, int FrameIdx,
685 const TargetRegisterClass *RC,
686 SmallVectorImpl<MachineInstr*> &NewMIs,
687 bool &NonRI, bool &SpillsVRS) const{
688 // Note: If additional load instructions are added here,
689 // update isLoadFromStackSlot.
691 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
692 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
693 DestReg), FrameIdx));
694 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
695 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
697 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
698 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
700 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
701 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
703 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
704 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
705 get(PPC::RESTORE_CR), DestReg),
708 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
711 if (DestReg == PPC::CR0LT || DestReg == PPC::CR0GT ||
712 DestReg == PPC::CR0EQ || DestReg == PPC::CR0UN)
714 else if (DestReg == PPC::CR1LT || DestReg == PPC::CR1GT ||
715 DestReg == PPC::CR1EQ || DestReg == PPC::CR1UN)
717 else if (DestReg == PPC::CR2LT || DestReg == PPC::CR2GT ||
718 DestReg == PPC::CR2EQ || DestReg == PPC::CR2UN)
720 else if (DestReg == PPC::CR3LT || DestReg == PPC::CR3GT ||
721 DestReg == PPC::CR3EQ || DestReg == PPC::CR3UN)
723 else if (DestReg == PPC::CR4LT || DestReg == PPC::CR4GT ||
724 DestReg == PPC::CR4EQ || DestReg == PPC::CR4UN)
726 else if (DestReg == PPC::CR5LT || DestReg == PPC::CR5GT ||
727 DestReg == PPC::CR5EQ || DestReg == PPC::CR5UN)
729 else if (DestReg == PPC::CR6LT || DestReg == PPC::CR6GT ||
730 DestReg == PPC::CR6EQ || DestReg == PPC::CR6UN)
732 else if (DestReg == PPC::CR7LT || DestReg == PPC::CR7GT ||
733 DestReg == PPC::CR7EQ || DestReg == PPC::CR7UN)
736 return LoadRegFromStackSlot(MF, DL, Reg, FrameIdx,
737 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
739 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
740 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
743 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
744 assert(TM.getSubtargetImpl()->isDarwin() &&
745 "VRSAVE only needs spill/restore on Darwin");
746 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
747 get(PPC::RESTORE_VRSAVE),
752 llvm_unreachable("Unknown regclass!");
759 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
760 MachineBasicBlock::iterator MI,
761 unsigned DestReg, int FrameIdx,
762 const TargetRegisterClass *RC,
763 const TargetRegisterInfo *TRI) const {
764 MachineFunction &MF = *MBB.getParent();
765 SmallVector<MachineInstr*, 4> NewMIs;
767 if (MI != MBB.end()) DL = MI->getDebugLoc();
769 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
770 FuncInfo->setHasSpills();
772 bool NonRI = false, SpillsVRS = false;
773 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
775 FuncInfo->setSpillsCR();
778 FuncInfo->setSpillsVRSAVE();
781 FuncInfo->setHasNonRISpills();
783 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
784 MBB.insert(MI, NewMIs[i]);
786 const MachineFrameInfo &MFI = *MF.getFrameInfo();
787 MachineMemOperand *MMO =
788 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
789 MachineMemOperand::MOLoad,
790 MFI.getObjectSize(FrameIdx),
791 MFI.getObjectAlignment(FrameIdx));
792 NewMIs.back()->addMemOperand(MF, MMO);
796 PPCInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
797 int FrameIx, uint64_t Offset,
800 MachineInstrBuilder MIB = BuildMI(MF, DL, get(PPC::DBG_VALUE));
801 addFrameReference(MIB, FrameIx, 0, false).addImm(Offset).addMetadata(MDPtr);
806 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
807 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
808 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
809 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
811 // Leave the CR# the same, but invert the condition.
812 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
816 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
817 unsigned Reg, MachineRegisterInfo *MRI) const {
818 // For some instructions, it is legal to fold ZERO into the RA register field.
819 // A zero immediate should always be loaded with a single li.
820 unsigned DefOpc = DefMI->getOpcode();
821 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
823 if (!DefMI->getOperand(1).isImm())
825 if (DefMI->getOperand(1).getImm() != 0)
828 // Note that we cannot here invert the arguments of an isel in order to fold
829 // a ZERO into what is presented as the second argument. All we have here
830 // is the condition bit, and that might come from a CR-logical bit operation.
832 const MCInstrDesc &UseMCID = UseMI->getDesc();
834 // Only fold into real machine instructions.
835 if (UseMCID.isPseudo())
839 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
840 if (UseMI->getOperand(UseIdx).isReg() &&
841 UseMI->getOperand(UseIdx).getReg() == Reg)
844 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
845 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
847 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
849 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
850 // register (which might also be specified as a pointer class kind).
851 if (UseInfo->isLookupPtrRegClass()) {
852 if (UseInfo->RegClass /* Kind */ != 1)
855 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
856 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
860 // Make sure this is not tied to an output register (or otherwise
861 // constrained). This is true for ST?UX registers, for example, which
862 // are tied to their output registers.
863 if (UseInfo->Constraints != 0)
867 if (UseInfo->isLookupPtrRegClass()) {
868 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
869 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
871 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
872 PPC::ZERO8 : PPC::ZERO;
875 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
876 UseMI->getOperand(UseIdx).setReg(ZeroReg);
879 DefMI->eraseFromParent();
884 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
885 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
887 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
892 // We should make sure that, if we're going to predicate both sides of a
893 // condition (a diamond), that both sides don't define the counter register. We
894 // can predicate counter-decrement-based branches, but while that predicates
895 // the branching, it does not predicate the counter decrement. If we tried to
896 // merge the triangle into one predicated block, we'd decrement the counter
898 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
899 unsigned NumT, unsigned ExtraT,
900 MachineBasicBlock &FMBB,
901 unsigned NumF, unsigned ExtraF,
902 const BranchProbability &Probability) const {
903 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
907 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
908 // The predicated branches are identified by their type, not really by the
909 // explicit presence of a predicate. Furthermore, some of them can be
910 // predicated more than once. Because if conversion won't try to predicate
911 // any instruction which already claims to be predicated (by returning true
912 // here), always return false. In doing so, we let isPredicable() be the
913 // final word on whether not the instruction can be (further) predicated.
918 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
919 if (!MI->isTerminator())
922 // Conditional branch is a special case.
923 if (MI->isBranch() && !MI->isBarrier())
926 return !isPredicated(MI);
929 bool PPCInstrInfo::PredicateInstruction(
931 const SmallVectorImpl<MachineOperand> &Pred) const {
932 unsigned OpC = MI->getOpcode();
933 if (OpC == PPC::BLR) {
934 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
935 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
936 MI->setDesc(get(Pred[0].getImm() ?
937 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
938 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
940 MI->setDesc(get(PPC::BCLR));
941 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
942 .addImm(Pred[0].getImm())
943 .addReg(Pred[1].getReg());
947 } else if (OpC == PPC::B) {
948 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
949 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
950 MI->setDesc(get(Pred[0].getImm() ?
951 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
952 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
954 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
955 MI->RemoveOperand(0);
957 MI->setDesc(get(PPC::BCC));
958 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
959 .addImm(Pred[0].getImm())
960 .addReg(Pred[1].getReg())
965 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
966 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
967 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
968 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
970 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
971 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
972 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
973 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
974 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
975 .addImm(Pred[0].getImm())
976 .addReg(Pred[1].getReg());
983 bool PPCInstrInfo::SubsumesPredicate(
984 const SmallVectorImpl<MachineOperand> &Pred1,
985 const SmallVectorImpl<MachineOperand> &Pred2) const {
986 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
987 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
989 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
991 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
994 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
995 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1000 // Does P1 subsume P2, e.g. GE subsumes GT.
1001 if (P1 == PPC::PRED_LE &&
1002 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1004 if (P1 == PPC::PRED_GE &&
1005 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1011 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1012 std::vector<MachineOperand> &Pred) const {
1013 // Note: At the present time, the contents of Pred from this function is
1014 // unused by IfConversion. This implementation follows ARM by pushing the
1015 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1016 // predicate, instructions defining CTR or CTR8 are also included as
1017 // predicate-defining instructions.
1019 const TargetRegisterClass *RCs[] =
1020 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1021 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1024 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1025 const MachineOperand &MO = MI->getOperand(i);
1026 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1027 const TargetRegisterClass *RC = RCs[c];
1029 if (MO.isDef() && RC->contains(MO.getReg())) {
1033 } else if (MO.isRegMask()) {
1034 for (TargetRegisterClass::iterator I = RC->begin(),
1035 IE = RC->end(); I != IE; ++I)
1036 if (MO.clobbersPhysReg(*I)) {
1047 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1048 unsigned OpC = MI->getOpcode();
1062 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1063 unsigned &SrcReg, unsigned &SrcReg2,
1064 int &Mask, int &Value) const {
1065 unsigned Opc = MI->getOpcode();
1068 default: return false;
1073 SrcReg = MI->getOperand(1).getReg();
1075 Value = MI->getOperand(2).getImm();
1084 SrcReg = MI->getOperand(1).getReg();
1085 SrcReg2 = MI->getOperand(2).getReg();
1090 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1091 unsigned SrcReg, unsigned SrcReg2,
1092 int Mask, int Value,
1093 const MachineRegisterInfo *MRI) const {
1097 int OpC = CmpInstr->getOpcode();
1098 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1100 // FP record forms set CR1 based on the execption status bits, not a
1101 // comparison with zero.
1102 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1105 // The record forms set the condition register based on a signed comparison
1106 // with zero (so says the ISA manual). This is not as straightforward as it
1107 // seems, however, because this is always a 64-bit comparison on PPC64, even
1108 // for instructions that are 32-bit in nature (like slw for example).
1109 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1110 // for equality checks (as those don't depend on the sign). On PPC64,
1111 // we are restricted to equality for unsigned 64-bit comparisons and for
1112 // signed 32-bit comparisons the applicability is more restricted.
1113 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1114 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1115 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1116 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1118 // Get the unique definition of SrcReg.
1119 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1120 if (!MI) return false;
1121 int MIOpC = MI->getOpcode();
1123 bool equalityOnly = false;
1126 if (is32BitSignedCompare) {
1127 // We can perform this optimization only if MI is sign-extending.
1128 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1129 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1130 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1131 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1132 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1136 } else if (is32BitUnsignedCompare) {
1137 // We can perform this optimization, equality only, if MI is
1139 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1140 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1141 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1143 equalityOnly = true;
1147 equalityOnly = is64BitUnsignedCompare;
1149 equalityOnly = is32BitUnsignedCompare;
1152 // We need to check the uses of the condition register in order to reject
1153 // non-equality comparisons.
1154 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1155 IE = MRI->use_end(); I != IE; ++I) {
1156 MachineInstr *UseMI = &*I;
1157 if (UseMI->getOpcode() == PPC::BCC) {
1158 unsigned Pred = UseMI->getOperand(0).getImm();
1159 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1161 } else if (UseMI->getOpcode() == PPC::ISEL ||
1162 UseMI->getOpcode() == PPC::ISEL8) {
1163 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1164 if (SubIdx != PPC::sub_eq)
1171 MachineBasicBlock::iterator I = CmpInstr;
1173 // Scan forward to find the first use of the compare.
1174 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1176 bool FoundUse = false;
1177 for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1178 JE = MRI->use_end(); J != JE; ++J)
1188 // There are two possible candidates which can be changed to set CR[01].
1189 // One is MI, the other is a SUB instruction.
1190 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1191 MachineInstr *Sub = NULL;
1193 // MI is not a candidate for CMPrr.
1195 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1196 // same BB as the comparison. This is to allow the check below to avoid calls
1197 // (and other explicit clobbers); instead we should really check for these
1198 // more explicitly (in at least a few predecessors).
1199 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1200 // PPC does not have a record-form SUBri.
1205 const TargetRegisterInfo *TRI = &getRegisterInfo();
1208 // Get ready to iterate backward from CmpInstr.
1209 MachineBasicBlock::iterator E = MI,
1210 B = CmpInstr->getParent()->begin();
1212 for (; I != E && !noSub; --I) {
1213 const MachineInstr &Instr = *I;
1214 unsigned IOpC = Instr.getOpcode();
1216 if (&*I != CmpInstr && (
1217 Instr.modifiesRegister(PPC::CR0, TRI) ||
1218 Instr.readsRegister(PPC::CR0, TRI)))
1219 // This instruction modifies or uses the record condition register after
1220 // the one we want to change. While we could do this transformation, it
1221 // would likely not be profitable. This transformation removes one
1222 // instruction, and so even forcing RA to generate one move probably
1223 // makes it unprofitable.
1226 // Check whether CmpInstr can be made redundant by the current instruction.
1227 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1228 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1229 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1230 ((Instr.getOperand(1).getReg() == SrcReg &&
1231 Instr.getOperand(2).getReg() == SrcReg2) ||
1232 (Instr.getOperand(1).getReg() == SrcReg2 &&
1233 Instr.getOperand(2).getReg() == SrcReg))) {
1239 // The 'and' is below the comparison instruction.
1243 // Return false if no candidates exist.
1247 // The single candidate is called MI.
1251 MIOpC = MI->getOpcode();
1252 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1255 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1256 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1260 // FIXME: On the non-embedded POWER architectures, only some of the record
1261 // forms are fast, and we should use only the fast ones.
1263 // The defining instruction has a record form (or is already a record
1264 // form). It is possible, however, that we'll need to reverse the condition
1265 // code of the users.
1269 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1270 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1272 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1273 // needs to be updated to be based on SUB. Push the condition code
1274 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1275 // condition code of these operands will be modified.
1276 bool ShouldSwap = false;
1278 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1279 Sub->getOperand(2).getReg() == SrcReg;
1281 // The operands to subf are the opposite of sub, so only in the fixed-point
1282 // case, invert the order.
1283 ShouldSwap = !ShouldSwap;
1287 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1288 IE = MRI->use_end(); I != IE; ++I) {
1289 MachineInstr *UseMI = &*I;
1290 if (UseMI->getOpcode() == PPC::BCC) {
1291 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1292 assert((!equalityOnly ||
1293 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1294 "Invalid predicate for equality-only optimization");
1295 PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1296 PPC::getSwappedPredicate(Pred)));
1297 } else if (UseMI->getOpcode() == PPC::ISEL ||
1298 UseMI->getOpcode() == PPC::ISEL8) {
1299 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1300 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1301 "Invalid CR bit for equality-only optimization");
1303 if (NewSubReg == PPC::sub_lt)
1304 NewSubReg = PPC::sub_gt;
1305 else if (NewSubReg == PPC::sub_gt)
1306 NewSubReg = PPC::sub_lt;
1308 SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1310 } else // We need to abort on a user we don't understand.
1314 // Create a new virtual register to hold the value of the CR set by the
1315 // record-form instruction. If the instruction was not previously in
1316 // record form, then set the kill flag on the CR.
1317 CmpInstr->eraseFromParent();
1319 MachineBasicBlock::iterator MII = MI;
1320 BuildMI(*MI->getParent(), llvm::next(MII), MI->getDebugLoc(),
1321 get(TargetOpcode::COPY), CRReg)
1322 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1324 if (MIOpC != NewOpC) {
1325 // We need to be careful here: we're replacing one instruction with
1326 // another, and we need to make sure that we get all of the right
1327 // implicit uses and defs. On the other hand, the caller may be holding
1328 // an iterator to this instruction, and so we can't delete it (this is
1329 // specifically the case if this is the instruction directly after the
1332 const MCInstrDesc &NewDesc = get(NewOpC);
1333 MI->setDesc(NewDesc);
1335 if (NewDesc.ImplicitDefs)
1336 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1337 *ImpDefs; ++ImpDefs)
1338 if (!MI->definesRegister(*ImpDefs))
1339 MI->addOperand(*MI->getParent()->getParent(),
1340 MachineOperand::CreateReg(*ImpDefs, true, true));
1341 if (NewDesc.ImplicitUses)
1342 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1343 *ImpUses; ++ImpUses)
1344 if (!MI->readsRegister(*ImpUses))
1345 MI->addOperand(*MI->getParent()->getParent(),
1346 MachineOperand::CreateReg(*ImpUses, false, true));
1349 // Modify the condition code of operands in OperandsToUpdate.
1350 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1351 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1352 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1353 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1355 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1356 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1361 /// GetInstSize - Return the number of bytes of code the specified
1362 /// instruction may be. This returns the maximum number of bytes.
1364 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1365 switch (MI->getOpcode()) {
1366 case PPC::INLINEASM: { // Inline Asm: Variable size.
1367 const MachineFunction *MF = MI->getParent()->getParent();
1368 const char *AsmStr = MI->getOperand(0).getSymbolName();
1369 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1371 case PPC::PROLOG_LABEL:
1374 case PPC::DBG_VALUE:
1380 return 4; // PowerPC instructions are all 4 bytes
1385 #define DEBUG_TYPE "ppc-early-ret"
1386 STATISTIC(NumBCLR, "Number of early conditional returns");
1387 STATISTIC(NumBLR, "Number of early returns");
1390 void initializePPCEarlyReturnPass(PassRegistry&);
1394 // PPCEarlyReturn pass - For simple functions without epilogue code, move
1395 // returns up, and create conditional returns, to avoid unnecessary
1396 // branch-to-blr sequences.
1397 struct PPCEarlyReturn : public MachineFunctionPass {
1399 PPCEarlyReturn() : MachineFunctionPass(ID) {
1400 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1403 const PPCTargetMachine *TM;
1404 const PPCInstrInfo *TII;
1407 bool processBlock(MachineBasicBlock &ReturnMBB) {
1408 bool Changed = false;
1410 MachineBasicBlock::iterator I = ReturnMBB.begin();
1411 I = ReturnMBB.SkipPHIsAndLabels(I);
1413 // The block must be essentially empty except for the blr.
1414 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1415 I != ReturnMBB.getLastNonDebugInstr())
1418 SmallVector<MachineBasicBlock*, 8> PredToRemove;
1419 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1420 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1421 bool OtherReference = false, BlockChanged = false;
1422 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1423 if (J->getOpcode() == PPC::B) {
1424 if (J->getOperand(0).getMBB() == &ReturnMBB) {
1425 // This is an unconditional branch to the return. Replace the
1426 // branch with a blr.
1427 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1428 MachineBasicBlock::iterator K = J--;
1429 K->eraseFromParent();
1430 BlockChanged = true;
1434 } else if (J->getOpcode() == PPC::BCC) {
1435 if (J->getOperand(2).getMBB() == &ReturnMBB) {
1436 // This is a conditional branch to the return. Replace the branch
1438 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCLR))
1439 .addImm(J->getOperand(0).getImm())
1440 .addReg(J->getOperand(1).getReg());
1441 MachineBasicBlock::iterator K = J--;
1442 K->eraseFromParent();
1443 BlockChanged = true;
1447 } else if (J->isBranch()) {
1448 if (J->isIndirectBranch()) {
1449 if (ReturnMBB.hasAddressTaken())
1450 OtherReference = true;
1452 for (unsigned i = 0; i < J->getNumOperands(); ++i)
1453 if (J->getOperand(i).isMBB() &&
1454 J->getOperand(i).getMBB() == &ReturnMBB)
1455 OtherReference = true;
1456 } else if (!J->isTerminator() && !J->isDebugValue())
1459 if (J == (*PI)->begin())
1465 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1466 OtherReference = true;
1468 // Predecessors are stored in a vector and can't be removed here.
1469 if (!OtherReference && BlockChanged) {
1470 PredToRemove.push_back(*PI);
1477 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1478 PredToRemove[i]->removeSuccessor(&ReturnMBB);
1480 if (Changed && !ReturnMBB.hasAddressTaken()) {
1481 // We now might be able to merge this blr-only block into its
1482 // by-layout predecessor.
1483 if (ReturnMBB.pred_size() == 1 &&
1484 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1485 // Move the blr into the preceding block.
1486 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1487 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1488 PrevMBB.removeSuccessor(&ReturnMBB);
1491 if (ReturnMBB.pred_empty())
1492 ReturnMBB.eraseFromParent();
1499 virtual bool runOnMachineFunction(MachineFunction &MF) {
1500 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1501 TII = TM->getInstrInfo();
1503 bool Changed = false;
1505 // If the function does not have at least two blocks, then there is
1510 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1511 MachineBasicBlock &B = *I++;
1512 if (processBlock(B))
1519 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1520 MachineFunctionPass::getAnalysisUsage(AU);
1525 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1526 "PowerPC Early-Return Creation", false, false)
1528 char PPCEarlyReturn::ID = 0;
1530 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }