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_DTOR
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 // Pin the vtable to this file.
49 void PPCInstrInfo::anchor() {}
51 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
52 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
53 TM(tm), RI(*TM.getSubtargetImpl()) {}
55 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
56 /// this target when scheduling the DAG.
57 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
58 const TargetMachine *TM,
59 const ScheduleDAG *DAG) const {
60 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
61 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
62 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
63 const InstrItineraryData *II = TM->getInstrItineraryData();
64 return new PPCScoreboardHazardRecognizer(II, DAG);
67 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
70 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
71 /// to use for this target when scheduling the DAG.
72 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
73 const InstrItineraryData *II,
74 const ScheduleDAG *DAG) const {
75 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
77 // Most subtargets use a PPC970 recognizer.
78 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
79 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
80 assert(TM.getInstrInfo() && "No InstrInfo?");
82 return new PPCHazardRecognizer970(TM);
85 return new PPCScoreboardHazardRecognizer(II, DAG);
88 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
89 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
90 unsigned &SrcReg, unsigned &DstReg,
91 unsigned &SubIdx) const {
92 switch (MI.getOpcode()) {
93 default: return false;
95 case PPC::EXTSW_32_64:
96 SrcReg = MI.getOperand(1).getReg();
97 DstReg = MI.getOperand(0).getReg();
103 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
104 int &FrameIndex) const {
105 // Note: This list must be kept consistent with LoadRegFromStackSlot.
106 switch (MI->getOpcode()) {
112 case PPC::RESTORE_CR:
114 case PPC::RESTORE_VRSAVE:
115 // Check for the operands added by addFrameReference (the immediate is the
116 // offset which defaults to 0).
117 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
118 MI->getOperand(2).isFI()) {
119 FrameIndex = MI->getOperand(2).getIndex();
120 return MI->getOperand(0).getReg();
127 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
128 int &FrameIndex) const {
129 // Note: This list must be kept consistent with StoreRegToStackSlot.
130 switch (MI->getOpcode()) {
138 case PPC::SPILL_VRSAVE:
139 // Check for the operands added by addFrameReference (the immediate is the
140 // offset which defaults to 0).
141 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
142 MI->getOperand(2).isFI()) {
143 FrameIndex = MI->getOperand(2).getIndex();
144 return MI->getOperand(0).getReg();
151 // commuteInstruction - We can commute rlwimi instructions, but only if the
152 // rotate amt is zero. We also have to munge the immediates a bit.
154 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
155 MachineFunction &MF = *MI->getParent()->getParent();
157 // Normal instructions can be commuted the obvious way.
158 if (MI->getOpcode() != PPC::RLWIMI &&
159 MI->getOpcode() != PPC::RLWIMIo)
160 return TargetInstrInfo::commuteInstruction(MI, NewMI);
162 // Cannot commute if it has a non-zero rotate count.
163 if (MI->getOperand(3).getImm() != 0)
166 // If we have a zero rotate count, we have:
168 // Op0 = (Op1 & ~M) | (Op2 & M)
170 // M = mask((ME+1)&31, (MB-1)&31)
171 // Op0 = (Op2 & ~M) | (Op1 & M)
174 unsigned Reg0 = MI->getOperand(0).getReg();
175 unsigned Reg1 = MI->getOperand(1).getReg();
176 unsigned Reg2 = MI->getOperand(2).getReg();
177 bool Reg1IsKill = MI->getOperand(1).isKill();
178 bool Reg2IsKill = MI->getOperand(2).isKill();
179 bool ChangeReg0 = false;
180 // If machine instrs are no longer in two-address forms, update
181 // destination register as well.
183 // Must be two address instruction!
184 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
185 "Expecting a two-address instruction!");
191 unsigned MB = MI->getOperand(4).getImm();
192 unsigned ME = MI->getOperand(5).getImm();
195 // Create a new instruction.
196 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
197 bool Reg0IsDead = MI->getOperand(0).isDead();
198 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
199 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
200 .addReg(Reg2, getKillRegState(Reg2IsKill))
201 .addReg(Reg1, getKillRegState(Reg1IsKill))
203 .addImm((MB-1) & 31);
207 MI->getOperand(0).setReg(Reg2);
208 MI->getOperand(2).setReg(Reg1);
209 MI->getOperand(1).setReg(Reg2);
210 MI->getOperand(2).setIsKill(Reg1IsKill);
211 MI->getOperand(1).setIsKill(Reg2IsKill);
213 // Swap the mask around.
214 MI->getOperand(4).setImm((ME+1) & 31);
215 MI->getOperand(5).setImm((MB-1) & 31);
219 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
220 MachineBasicBlock::iterator MI) const {
222 BuildMI(MBB, MI, DL, get(PPC::NOP));
227 // Note: If the condition register is set to CTR or CTR8 then this is a
228 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
229 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
230 MachineBasicBlock *&FBB,
231 SmallVectorImpl<MachineOperand> &Cond,
232 bool AllowModify) const {
233 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
235 // If the block has no terminators, it just falls into the block after it.
236 MachineBasicBlock::iterator I = MBB.end();
237 if (I == MBB.begin())
240 while (I->isDebugValue()) {
241 if (I == MBB.begin())
245 if (!isUnpredicatedTerminator(I))
248 // Get the last instruction in the block.
249 MachineInstr *LastInst = I;
251 // If there is only one terminator instruction, process it.
252 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
253 if (LastInst->getOpcode() == PPC::B) {
254 if (!LastInst->getOperand(0).isMBB())
256 TBB = LastInst->getOperand(0).getMBB();
258 } else if (LastInst->getOpcode() == PPC::BCC) {
259 if (!LastInst->getOperand(2).isMBB())
261 // Block ends with fall-through condbranch.
262 TBB = LastInst->getOperand(2).getMBB();
263 Cond.push_back(LastInst->getOperand(0));
264 Cond.push_back(LastInst->getOperand(1));
266 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
267 LastInst->getOpcode() == PPC::BDNZ) {
268 if (!LastInst->getOperand(0).isMBB())
270 if (DisableCTRLoopAnal)
272 TBB = LastInst->getOperand(0).getMBB();
273 Cond.push_back(MachineOperand::CreateImm(1));
274 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
277 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
278 LastInst->getOpcode() == PPC::BDZ) {
279 if (!LastInst->getOperand(0).isMBB())
281 if (DisableCTRLoopAnal)
283 TBB = LastInst->getOperand(0).getMBB();
284 Cond.push_back(MachineOperand::CreateImm(0));
285 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
290 // Otherwise, don't know what this is.
294 // Get the instruction before it if it's a terminator.
295 MachineInstr *SecondLastInst = I;
297 // If there are three terminators, we don't know what sort of block this is.
298 if (SecondLastInst && I != MBB.begin() &&
299 isUnpredicatedTerminator(--I))
302 // If the block ends with PPC::B and PPC:BCC, handle it.
303 if (SecondLastInst->getOpcode() == PPC::BCC &&
304 LastInst->getOpcode() == PPC::B) {
305 if (!SecondLastInst->getOperand(2).isMBB() ||
306 !LastInst->getOperand(0).isMBB())
308 TBB = SecondLastInst->getOperand(2).getMBB();
309 Cond.push_back(SecondLastInst->getOperand(0));
310 Cond.push_back(SecondLastInst->getOperand(1));
311 FBB = LastInst->getOperand(0).getMBB();
313 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
314 SecondLastInst->getOpcode() == PPC::BDNZ) &&
315 LastInst->getOpcode() == PPC::B) {
316 if (!SecondLastInst->getOperand(0).isMBB() ||
317 !LastInst->getOperand(0).isMBB())
319 if (DisableCTRLoopAnal)
321 TBB = SecondLastInst->getOperand(0).getMBB();
322 Cond.push_back(MachineOperand::CreateImm(1));
323 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
325 FBB = LastInst->getOperand(0).getMBB();
327 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
328 SecondLastInst->getOpcode() == PPC::BDZ) &&
329 LastInst->getOpcode() == PPC::B) {
330 if (!SecondLastInst->getOperand(0).isMBB() ||
331 !LastInst->getOperand(0).isMBB())
333 if (DisableCTRLoopAnal)
335 TBB = SecondLastInst->getOperand(0).getMBB();
336 Cond.push_back(MachineOperand::CreateImm(0));
337 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
339 FBB = LastInst->getOperand(0).getMBB();
343 // If the block ends with two PPC:Bs, handle it. The second one is not
344 // executed, so remove it.
345 if (SecondLastInst->getOpcode() == PPC::B &&
346 LastInst->getOpcode() == PPC::B) {
347 if (!SecondLastInst->getOperand(0).isMBB())
349 TBB = SecondLastInst->getOperand(0).getMBB();
352 I->eraseFromParent();
356 // Otherwise, can't handle this.
360 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
361 MachineBasicBlock::iterator I = MBB.end();
362 if (I == MBB.begin()) return 0;
364 while (I->isDebugValue()) {
365 if (I == MBB.begin())
369 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
370 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
371 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
374 // Remove the branch.
375 I->eraseFromParent();
379 if (I == MBB.begin()) return 1;
381 if (I->getOpcode() != PPC::BCC &&
382 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
383 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
386 // Remove the branch.
387 I->eraseFromParent();
392 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
393 MachineBasicBlock *FBB,
394 const SmallVectorImpl<MachineOperand> &Cond,
396 // Shouldn't be a fall through.
397 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
398 assert((Cond.size() == 2 || Cond.size() == 0) &&
399 "PPC branch conditions have two components!");
401 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
405 if (Cond.empty()) // Unconditional branch
406 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
407 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
408 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
409 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
410 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
411 else // Conditional branch
412 BuildMI(&MBB, DL, get(PPC::BCC))
413 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
417 // Two-way Conditional Branch.
418 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
419 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
420 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
421 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
423 BuildMI(&MBB, DL, get(PPC::BCC))
424 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
425 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
430 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
431 const SmallVectorImpl<MachineOperand> &Cond,
432 unsigned TrueReg, unsigned FalseReg,
433 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
434 if (!TM.getSubtargetImpl()->hasISEL())
437 if (Cond.size() != 2)
440 // If this is really a bdnz-like condition, then it cannot be turned into a
442 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
445 // Check register classes.
446 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
447 const TargetRegisterClass *RC =
448 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
452 // isel is for regular integer GPRs only.
453 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
454 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
455 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
456 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
459 // FIXME: These numbers are for the A2, how well they work for other cores is
460 // an open question. On the A2, the isel instruction has a 2-cycle latency
461 // but single-cycle throughput. These numbers are used in combination with
462 // the MispredictPenalty setting from the active SchedMachineModel.
470 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
471 MachineBasicBlock::iterator MI, DebugLoc dl,
473 const SmallVectorImpl<MachineOperand> &Cond,
474 unsigned TrueReg, unsigned FalseReg) const {
475 assert(Cond.size() == 2 &&
476 "PPC branch conditions have two components!");
478 assert(TM.getSubtargetImpl()->hasISEL() &&
479 "Cannot insert select on target without ISEL support");
481 // Get the register classes.
482 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
483 const TargetRegisterClass *RC =
484 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
485 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
487 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
488 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
490 PPC::GPRCRegClass.hasSubClassEq(RC) ||
491 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
492 "isel is for regular integer GPRs only");
494 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
495 unsigned SelectPred = Cond[0].getImm();
499 switch (SelectPred) {
500 default: llvm_unreachable("invalid predicate for isel");
501 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
502 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
503 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
504 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
505 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
506 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
507 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
508 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
511 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
512 SecondReg = SwapOps ? TrueReg : FalseReg;
514 // The first input register of isel cannot be r0. If it is a member
515 // of a register class that can be r0, then copy it first (the
516 // register allocator should eliminate the copy).
517 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
518 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
519 const TargetRegisterClass *FirstRC =
520 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
521 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
522 unsigned OldFirstReg = FirstReg;
523 FirstReg = MRI.createVirtualRegister(FirstRC);
524 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
525 .addReg(OldFirstReg);
528 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
529 .addReg(FirstReg).addReg(SecondReg)
530 .addReg(Cond[1].getReg(), 0, SubIdx);
533 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
534 MachineBasicBlock::iterator I, DebugLoc DL,
535 unsigned DestReg, unsigned SrcReg,
536 bool KillSrc) const {
538 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
540 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
542 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
544 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
546 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
548 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
551 llvm_unreachable("Impossible reg-to-reg copy");
553 const MCInstrDesc &MCID = get(Opc);
554 if (MCID.getNumOperands() == 3)
555 BuildMI(MBB, I, DL, MCID, DestReg)
556 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
558 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
561 // This function returns true if a CR spill is necessary and false otherwise.
563 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
564 unsigned SrcReg, bool isKill,
566 const TargetRegisterClass *RC,
567 SmallVectorImpl<MachineInstr*> &NewMIs,
568 bool &NonRI, bool &SpillsVRS) const{
569 // Note: If additional store instructions are added here,
570 // update isStoreToStackSlot.
573 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
574 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
575 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
577 getKillRegState(isKill)),
579 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
580 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
581 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
583 getKillRegState(isKill)),
585 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
586 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
588 getKillRegState(isKill)),
590 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
591 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
593 getKillRegState(isKill)),
595 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
596 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
598 getKillRegState(isKill)),
601 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
602 // FIXME: We use CRi here because there is no mtcrf on a bit. Since the
603 // backend currently only uses CR1EQ as an individual bit, this should
604 // not cause any bug. If we need other uses of CR bits, the following
605 // code may be invalid.
607 if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
608 SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
610 else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
611 SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
613 else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
614 SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
616 else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
617 SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
619 else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
620 SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
622 else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
623 SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
625 else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
626 SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
628 else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
629 SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
632 return StoreRegToStackSlot(MF, Reg, isKill, FrameIdx,
633 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
635 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
636 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
638 getKillRegState(isKill)),
641 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
642 assert(TM.getSubtargetImpl()->isDarwin() &&
643 "VRSAVE only needs spill/restore on Darwin");
644 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
646 getKillRegState(isKill)),
650 llvm_unreachable("Unknown regclass!");
657 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
658 MachineBasicBlock::iterator MI,
659 unsigned SrcReg, bool isKill, int FrameIdx,
660 const TargetRegisterClass *RC,
661 const TargetRegisterInfo *TRI) const {
662 MachineFunction &MF = *MBB.getParent();
663 SmallVector<MachineInstr*, 4> NewMIs;
665 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
666 FuncInfo->setHasSpills();
668 bool NonRI = false, SpillsVRS = false;
669 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
671 FuncInfo->setSpillsCR();
674 FuncInfo->setSpillsVRSAVE();
677 FuncInfo->setHasNonRISpills();
679 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
680 MBB.insert(MI, NewMIs[i]);
682 const MachineFrameInfo &MFI = *MF.getFrameInfo();
683 MachineMemOperand *MMO =
684 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
685 MachineMemOperand::MOStore,
686 MFI.getObjectSize(FrameIdx),
687 MFI.getObjectAlignment(FrameIdx));
688 NewMIs.back()->addMemOperand(MF, MMO);
692 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
693 unsigned DestReg, int FrameIdx,
694 const TargetRegisterClass *RC,
695 SmallVectorImpl<MachineInstr*> &NewMIs,
696 bool &NonRI, bool &SpillsVRS) const{
697 // Note: If additional load instructions are added here,
698 // update isLoadFromStackSlot.
700 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
701 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
702 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
703 DestReg), FrameIdx));
704 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
705 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
706 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
708 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
709 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
711 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
712 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
714 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
715 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
716 get(PPC::RESTORE_CR), DestReg),
719 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
722 if (DestReg == PPC::CR0LT || DestReg == PPC::CR0GT ||
723 DestReg == PPC::CR0EQ || DestReg == PPC::CR0UN)
725 else if (DestReg == PPC::CR1LT || DestReg == PPC::CR1GT ||
726 DestReg == PPC::CR1EQ || DestReg == PPC::CR1UN)
728 else if (DestReg == PPC::CR2LT || DestReg == PPC::CR2GT ||
729 DestReg == PPC::CR2EQ || DestReg == PPC::CR2UN)
731 else if (DestReg == PPC::CR3LT || DestReg == PPC::CR3GT ||
732 DestReg == PPC::CR3EQ || DestReg == PPC::CR3UN)
734 else if (DestReg == PPC::CR4LT || DestReg == PPC::CR4GT ||
735 DestReg == PPC::CR4EQ || DestReg == PPC::CR4UN)
737 else if (DestReg == PPC::CR5LT || DestReg == PPC::CR5GT ||
738 DestReg == PPC::CR5EQ || DestReg == PPC::CR5UN)
740 else if (DestReg == PPC::CR6LT || DestReg == PPC::CR6GT ||
741 DestReg == PPC::CR6EQ || DestReg == PPC::CR6UN)
743 else if (DestReg == PPC::CR7LT || DestReg == PPC::CR7GT ||
744 DestReg == PPC::CR7EQ || DestReg == PPC::CR7UN)
747 return LoadRegFromStackSlot(MF, DL, Reg, FrameIdx,
748 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
750 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
751 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
754 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
755 assert(TM.getSubtargetImpl()->isDarwin() &&
756 "VRSAVE only needs spill/restore on Darwin");
757 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
758 get(PPC::RESTORE_VRSAVE),
763 llvm_unreachable("Unknown regclass!");
770 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
771 MachineBasicBlock::iterator MI,
772 unsigned DestReg, int FrameIdx,
773 const TargetRegisterClass *RC,
774 const TargetRegisterInfo *TRI) const {
775 MachineFunction &MF = *MBB.getParent();
776 SmallVector<MachineInstr*, 4> NewMIs;
778 if (MI != MBB.end()) DL = MI->getDebugLoc();
780 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
781 FuncInfo->setHasSpills();
783 bool NonRI = false, SpillsVRS = false;
784 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
786 FuncInfo->setSpillsCR();
789 FuncInfo->setSpillsVRSAVE();
792 FuncInfo->setHasNonRISpills();
794 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
795 MBB.insert(MI, NewMIs[i]);
797 const MachineFrameInfo &MFI = *MF.getFrameInfo();
798 MachineMemOperand *MMO =
799 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
800 MachineMemOperand::MOLoad,
801 MFI.getObjectSize(FrameIdx),
802 MFI.getObjectAlignment(FrameIdx));
803 NewMIs.back()->addMemOperand(MF, MMO);
807 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
808 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
809 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
810 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
812 // Leave the CR# the same, but invert the condition.
813 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
817 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
818 unsigned Reg, MachineRegisterInfo *MRI) const {
819 // For some instructions, it is legal to fold ZERO into the RA register field.
820 // A zero immediate should always be loaded with a single li.
821 unsigned DefOpc = DefMI->getOpcode();
822 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
824 if (!DefMI->getOperand(1).isImm())
826 if (DefMI->getOperand(1).getImm() != 0)
829 // Note that we cannot here invert the arguments of an isel in order to fold
830 // a ZERO into what is presented as the second argument. All we have here
831 // is the condition bit, and that might come from a CR-logical bit operation.
833 const MCInstrDesc &UseMCID = UseMI->getDesc();
835 // Only fold into real machine instructions.
836 if (UseMCID.isPseudo())
840 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
841 if (UseMI->getOperand(UseIdx).isReg() &&
842 UseMI->getOperand(UseIdx).getReg() == Reg)
845 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
846 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
848 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
850 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
851 // register (which might also be specified as a pointer class kind).
852 if (UseInfo->isLookupPtrRegClass()) {
853 if (UseInfo->RegClass /* Kind */ != 1)
856 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
857 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
861 // Make sure this is not tied to an output register (or otherwise
862 // constrained). This is true for ST?UX registers, for example, which
863 // are tied to their output registers.
864 if (UseInfo->Constraints != 0)
868 if (UseInfo->isLookupPtrRegClass()) {
869 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
870 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
872 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
873 PPC::ZERO8 : PPC::ZERO;
876 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
877 UseMI->getOperand(UseIdx).setReg(ZeroReg);
880 DefMI->eraseFromParent();
885 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
886 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
888 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
893 // We should make sure that, if we're going to predicate both sides of a
894 // condition (a diamond), that both sides don't define the counter register. We
895 // can predicate counter-decrement-based branches, but while that predicates
896 // the branching, it does not predicate the counter decrement. If we tried to
897 // merge the triangle into one predicated block, we'd decrement the counter
899 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
900 unsigned NumT, unsigned ExtraT,
901 MachineBasicBlock &FMBB,
902 unsigned NumF, unsigned ExtraF,
903 const BranchProbability &Probability) const {
904 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
908 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
909 // The predicated branches are identified by their type, not really by the
910 // explicit presence of a predicate. Furthermore, some of them can be
911 // predicated more than once. Because if conversion won't try to predicate
912 // any instruction which already claims to be predicated (by returning true
913 // here), always return false. In doing so, we let isPredicable() be the
914 // final word on whether not the instruction can be (further) predicated.
919 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
920 if (!MI->isTerminator())
923 // Conditional branch is a special case.
924 if (MI->isBranch() && !MI->isBarrier())
927 return !isPredicated(MI);
930 bool PPCInstrInfo::PredicateInstruction(
932 const SmallVectorImpl<MachineOperand> &Pred) const {
933 unsigned OpC = MI->getOpcode();
934 if (OpC == PPC::BLR) {
935 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
936 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
937 MI->setDesc(get(Pred[0].getImm() ?
938 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
939 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
941 MI->setDesc(get(PPC::BCLR));
942 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
943 .addImm(Pred[0].getImm())
944 .addReg(Pred[1].getReg());
948 } else if (OpC == PPC::B) {
949 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
950 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
951 MI->setDesc(get(Pred[0].getImm() ?
952 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
953 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
955 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
956 MI->RemoveOperand(0);
958 MI->setDesc(get(PPC::BCC));
959 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
960 .addImm(Pred[0].getImm())
961 .addReg(Pred[1].getReg())
966 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
967 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
968 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
969 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
971 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
972 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
973 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
974 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
975 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
976 .addImm(Pred[0].getImm())
977 .addReg(Pred[1].getReg());
984 bool PPCInstrInfo::SubsumesPredicate(
985 const SmallVectorImpl<MachineOperand> &Pred1,
986 const SmallVectorImpl<MachineOperand> &Pred2) const {
987 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
988 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
990 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
992 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
995 // P1 can only subsume P2 if they test the same condition register.
996 if (Pred1[1].getReg() != Pred2[1].getReg())
999 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1000 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1005 // Does P1 subsume P2, e.g. GE subsumes GT.
1006 if (P1 == PPC::PRED_LE &&
1007 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1009 if (P1 == PPC::PRED_GE &&
1010 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1016 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1017 std::vector<MachineOperand> &Pred) const {
1018 // Note: At the present time, the contents of Pred from this function is
1019 // unused by IfConversion. This implementation follows ARM by pushing the
1020 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1021 // predicate, instructions defining CTR or CTR8 are also included as
1022 // predicate-defining instructions.
1024 const TargetRegisterClass *RCs[] =
1025 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1026 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1029 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1030 const MachineOperand &MO = MI->getOperand(i);
1031 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1032 const TargetRegisterClass *RC = RCs[c];
1034 if (MO.isDef() && RC->contains(MO.getReg())) {
1038 } else if (MO.isRegMask()) {
1039 for (TargetRegisterClass::iterator I = RC->begin(),
1040 IE = RC->end(); I != IE; ++I)
1041 if (MO.clobbersPhysReg(*I)) {
1052 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1053 unsigned OpC = MI->getOpcode();
1067 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1068 unsigned &SrcReg, unsigned &SrcReg2,
1069 int &Mask, int &Value) const {
1070 unsigned Opc = MI->getOpcode();
1073 default: return false;
1078 SrcReg = MI->getOperand(1).getReg();
1080 Value = MI->getOperand(2).getImm();
1089 SrcReg = MI->getOperand(1).getReg();
1090 SrcReg2 = MI->getOperand(2).getReg();
1095 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1096 unsigned SrcReg, unsigned SrcReg2,
1097 int Mask, int Value,
1098 const MachineRegisterInfo *MRI) const {
1102 int OpC = CmpInstr->getOpcode();
1103 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1105 // FP record forms set CR1 based on the execption status bits, not a
1106 // comparison with zero.
1107 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1110 // The record forms set the condition register based on a signed comparison
1111 // with zero (so says the ISA manual). This is not as straightforward as it
1112 // seems, however, because this is always a 64-bit comparison on PPC64, even
1113 // for instructions that are 32-bit in nature (like slw for example).
1114 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1115 // for equality checks (as those don't depend on the sign). On PPC64,
1116 // we are restricted to equality for unsigned 64-bit comparisons and for
1117 // signed 32-bit comparisons the applicability is more restricted.
1118 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1119 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1120 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1121 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1123 // Get the unique definition of SrcReg.
1124 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1125 if (!MI) return false;
1126 int MIOpC = MI->getOpcode();
1128 bool equalityOnly = false;
1131 if (is32BitSignedCompare) {
1132 // We can perform this optimization only if MI is sign-extending.
1133 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1134 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1135 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1136 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1137 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1141 } else if (is32BitUnsignedCompare) {
1142 // We can perform this optimization, equality only, if MI is
1144 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1145 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1146 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1148 equalityOnly = true;
1152 equalityOnly = is64BitUnsignedCompare;
1154 equalityOnly = is32BitUnsignedCompare;
1157 // We need to check the uses of the condition register in order to reject
1158 // non-equality comparisons.
1159 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1160 IE = MRI->use_end(); I != IE; ++I) {
1161 MachineInstr *UseMI = &*I;
1162 if (UseMI->getOpcode() == PPC::BCC) {
1163 unsigned Pred = UseMI->getOperand(0).getImm();
1164 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1166 } else if (UseMI->getOpcode() == PPC::ISEL ||
1167 UseMI->getOpcode() == PPC::ISEL8) {
1168 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1169 if (SubIdx != PPC::sub_eq)
1176 MachineBasicBlock::iterator I = CmpInstr;
1178 // Scan forward to find the first use of the compare.
1179 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1181 bool FoundUse = false;
1182 for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1183 JE = MRI->use_end(); J != JE; ++J)
1193 // There are two possible candidates which can be changed to set CR[01].
1194 // One is MI, the other is a SUB instruction.
1195 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1196 MachineInstr *Sub = NULL;
1198 // MI is not a candidate for CMPrr.
1200 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1201 // same BB as the comparison. This is to allow the check below to avoid calls
1202 // (and other explicit clobbers); instead we should really check for these
1203 // more explicitly (in at least a few predecessors).
1204 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1205 // PPC does not have a record-form SUBri.
1210 const TargetRegisterInfo *TRI = &getRegisterInfo();
1213 // Get ready to iterate backward from CmpInstr.
1214 MachineBasicBlock::iterator E = MI,
1215 B = CmpInstr->getParent()->begin();
1217 for (; I != E && !noSub; --I) {
1218 const MachineInstr &Instr = *I;
1219 unsigned IOpC = Instr.getOpcode();
1221 if (&*I != CmpInstr && (
1222 Instr.modifiesRegister(PPC::CR0, TRI) ||
1223 Instr.readsRegister(PPC::CR0, TRI)))
1224 // This instruction modifies or uses the record condition register after
1225 // the one we want to change. While we could do this transformation, it
1226 // would likely not be profitable. This transformation removes one
1227 // instruction, and so even forcing RA to generate one move probably
1228 // makes it unprofitable.
1231 // Check whether CmpInstr can be made redundant by the current instruction.
1232 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1233 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1234 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1235 ((Instr.getOperand(1).getReg() == SrcReg &&
1236 Instr.getOperand(2).getReg() == SrcReg2) ||
1237 (Instr.getOperand(1).getReg() == SrcReg2 &&
1238 Instr.getOperand(2).getReg() == SrcReg))) {
1244 // The 'and' is below the comparison instruction.
1248 // Return false if no candidates exist.
1252 // The single candidate is called MI.
1256 MIOpC = MI->getOpcode();
1257 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1260 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1261 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1265 // FIXME: On the non-embedded POWER architectures, only some of the record
1266 // forms are fast, and we should use only the fast ones.
1268 // The defining instruction has a record form (or is already a record
1269 // form). It is possible, however, that we'll need to reverse the condition
1270 // code of the users.
1274 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1275 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1277 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1278 // needs to be updated to be based on SUB. Push the condition code
1279 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1280 // condition code of these operands will be modified.
1281 bool ShouldSwap = false;
1283 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1284 Sub->getOperand(2).getReg() == SrcReg;
1286 // The operands to subf are the opposite of sub, so only in the fixed-point
1287 // case, invert the order.
1288 ShouldSwap = !ShouldSwap;
1292 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1293 IE = MRI->use_end(); I != IE; ++I) {
1294 MachineInstr *UseMI = &*I;
1295 if (UseMI->getOpcode() == PPC::BCC) {
1296 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1297 assert((!equalityOnly ||
1298 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1299 "Invalid predicate for equality-only optimization");
1300 PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1301 PPC::getSwappedPredicate(Pred)));
1302 } else if (UseMI->getOpcode() == PPC::ISEL ||
1303 UseMI->getOpcode() == PPC::ISEL8) {
1304 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1305 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1306 "Invalid CR bit for equality-only optimization");
1308 if (NewSubReg == PPC::sub_lt)
1309 NewSubReg = PPC::sub_gt;
1310 else if (NewSubReg == PPC::sub_gt)
1311 NewSubReg = PPC::sub_lt;
1313 SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1315 } else // We need to abort on a user we don't understand.
1319 // Create a new virtual register to hold the value of the CR set by the
1320 // record-form instruction. If the instruction was not previously in
1321 // record form, then set the kill flag on the CR.
1322 CmpInstr->eraseFromParent();
1324 MachineBasicBlock::iterator MII = MI;
1325 BuildMI(*MI->getParent(), llvm::next(MII), MI->getDebugLoc(),
1326 get(TargetOpcode::COPY), CRReg)
1327 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1329 if (MIOpC != NewOpC) {
1330 // We need to be careful here: we're replacing one instruction with
1331 // another, and we need to make sure that we get all of the right
1332 // implicit uses and defs. On the other hand, the caller may be holding
1333 // an iterator to this instruction, and so we can't delete it (this is
1334 // specifically the case if this is the instruction directly after the
1337 const MCInstrDesc &NewDesc = get(NewOpC);
1338 MI->setDesc(NewDesc);
1340 if (NewDesc.ImplicitDefs)
1341 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1342 *ImpDefs; ++ImpDefs)
1343 if (!MI->definesRegister(*ImpDefs))
1344 MI->addOperand(*MI->getParent()->getParent(),
1345 MachineOperand::CreateReg(*ImpDefs, true, true));
1346 if (NewDesc.ImplicitUses)
1347 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1348 *ImpUses; ++ImpUses)
1349 if (!MI->readsRegister(*ImpUses))
1350 MI->addOperand(*MI->getParent()->getParent(),
1351 MachineOperand::CreateReg(*ImpUses, false, true));
1354 // Modify the condition code of operands in OperandsToUpdate.
1355 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1356 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1357 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1358 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1360 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1361 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1366 /// GetInstSize - Return the number of bytes of code the specified
1367 /// instruction may be. This returns the maximum number of bytes.
1369 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1370 switch (MI->getOpcode()) {
1371 case PPC::INLINEASM: { // Inline Asm: Variable size.
1372 const MachineFunction *MF = MI->getParent()->getParent();
1373 const char *AsmStr = MI->getOperand(0).getSymbolName();
1374 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1376 case PPC::PROLOG_LABEL:
1379 case PPC::DBG_VALUE:
1385 return 4; // PowerPC instructions are all 4 bytes
1390 #define DEBUG_TYPE "ppc-early-ret"
1391 STATISTIC(NumBCLR, "Number of early conditional returns");
1392 STATISTIC(NumBLR, "Number of early returns");
1395 void initializePPCEarlyReturnPass(PassRegistry&);
1399 // PPCEarlyReturn pass - For simple functions without epilogue code, move
1400 // returns up, and create conditional returns, to avoid unnecessary
1401 // branch-to-blr sequences.
1402 struct PPCEarlyReturn : public MachineFunctionPass {
1404 PPCEarlyReturn() : MachineFunctionPass(ID) {
1405 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1408 const PPCTargetMachine *TM;
1409 const PPCInstrInfo *TII;
1412 bool processBlock(MachineBasicBlock &ReturnMBB) {
1413 bool Changed = false;
1415 MachineBasicBlock::iterator I = ReturnMBB.begin();
1416 I = ReturnMBB.SkipPHIsAndLabels(I);
1418 // The block must be essentially empty except for the blr.
1419 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1420 I != ReturnMBB.getLastNonDebugInstr())
1423 SmallVector<MachineBasicBlock*, 8> PredToRemove;
1424 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1425 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1426 bool OtherReference = false, BlockChanged = false;
1427 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1428 if (J->getOpcode() == PPC::B) {
1429 if (J->getOperand(0).getMBB() == &ReturnMBB) {
1430 // This is an unconditional branch to the return. Replace the
1431 // branch with a blr.
1432 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1433 MachineBasicBlock::iterator K = J--;
1434 K->eraseFromParent();
1435 BlockChanged = true;
1439 } else if (J->getOpcode() == PPC::BCC) {
1440 if (J->getOperand(2).getMBB() == &ReturnMBB) {
1441 // This is a conditional branch to the return. Replace the branch
1443 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCLR))
1444 .addImm(J->getOperand(0).getImm())
1445 .addReg(J->getOperand(1).getReg());
1446 MachineBasicBlock::iterator K = J--;
1447 K->eraseFromParent();
1448 BlockChanged = true;
1452 } else if (J->isBranch()) {
1453 if (J->isIndirectBranch()) {
1454 if (ReturnMBB.hasAddressTaken())
1455 OtherReference = true;
1457 for (unsigned i = 0; i < J->getNumOperands(); ++i)
1458 if (J->getOperand(i).isMBB() &&
1459 J->getOperand(i).getMBB() == &ReturnMBB)
1460 OtherReference = true;
1461 } else if (!J->isTerminator() && !J->isDebugValue())
1464 if (J == (*PI)->begin())
1470 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1471 OtherReference = true;
1473 // Predecessors are stored in a vector and can't be removed here.
1474 if (!OtherReference && BlockChanged) {
1475 PredToRemove.push_back(*PI);
1482 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1483 PredToRemove[i]->removeSuccessor(&ReturnMBB);
1485 if (Changed && !ReturnMBB.hasAddressTaken()) {
1486 // We now might be able to merge this blr-only block into its
1487 // by-layout predecessor.
1488 if (ReturnMBB.pred_size() == 1 &&
1489 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1490 // Move the blr into the preceding block.
1491 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1492 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1493 PrevMBB.removeSuccessor(&ReturnMBB);
1496 if (ReturnMBB.pred_empty())
1497 ReturnMBB.eraseFromParent();
1504 virtual bool runOnMachineFunction(MachineFunction &MF) {
1505 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1506 TII = TM->getInstrInfo();
1508 bool Changed = false;
1510 // If the function does not have at least two blocks, then there is
1515 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1516 MachineBasicBlock &B = *I++;
1517 if (processBlock(B))
1524 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1525 MachineFunctionPass::getAnalysisUsage(AU);
1530 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1531 "PowerPC Early-Return Creation", false, false)
1533 char PPCEarlyReturn::ID = 0;
1535 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }