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/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/ScheduleDAG.h"
31 #include "llvm/CodeGen/SlotIndexes.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "ppc-instr-info"
43 #define GET_INSTRMAP_INFO
44 #define GET_INSTRINFO_CTOR_DTOR
45 #include "PPCGenInstrInfo.inc"
48 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
49 cl::desc("Disable analysis for CTR loops"));
51 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
52 cl::desc("Disable compare instruction optimization"), cl::Hidden);
54 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
55 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
57 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
58 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
61 // Pin the vtable to this file.
62 void PPCInstrInfo::anchor() {}
64 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
65 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
66 Subtarget(STI), RI(STI) {}
68 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
69 /// this target when scheduling the DAG.
70 ScheduleHazardRecognizer *
71 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
72 const ScheduleDAG *DAG) const {
74 static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
75 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
76 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
77 const InstrItineraryData *II =
78 &static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
79 return new ScoreboardHazardRecognizer(II, DAG);
82 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
85 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
86 /// to use for this target when scheduling the DAG.
87 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
88 const InstrItineraryData *II,
89 const ScheduleDAG *DAG) const {
91 DAG->TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
93 if (Directive == PPC::DIR_PWR7)
94 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
96 // Most subtargets use a PPC970 recognizer.
97 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
98 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
99 assert(DAG->TII && "No InstrInfo?");
101 return new PPCHazardRecognizer970(*DAG);
104 return new ScoreboardHazardRecognizer(II, DAG);
108 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
109 const MachineInstr *DefMI, unsigned DefIdx,
110 const MachineInstr *UseMI,
111 unsigned UseIdx) const {
112 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
115 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
116 unsigned Reg = DefMO.getReg();
118 const TargetRegisterInfo *TRI = &getRegisterInfo();
120 if (TRI->isVirtualRegister(Reg)) {
121 const MachineRegisterInfo *MRI =
122 &DefMI->getParent()->getParent()->getRegInfo();
123 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
124 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
126 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
127 PPC::CRBITRCRegClass.contains(Reg);
130 if (UseMI->isBranch() && IsRegCR) {
132 Latency = getInstrLatency(ItinData, DefMI);
134 // On some cores, there is an additional delay between writing to a condition
135 // register, and using it from a branch.
136 unsigned Directive = Subtarget.getDarwinDirective();
157 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
158 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
159 unsigned &SrcReg, unsigned &DstReg,
160 unsigned &SubIdx) const {
161 switch (MI.getOpcode()) {
162 default: return false;
164 case PPC::EXTSW_32_64:
165 SrcReg = MI.getOperand(1).getReg();
166 DstReg = MI.getOperand(0).getReg();
167 SubIdx = PPC::sub_32;
172 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
173 int &FrameIndex) const {
174 // Note: This list must be kept consistent with LoadRegFromStackSlot.
175 switch (MI->getOpcode()) {
181 case PPC::RESTORE_CR:
182 case PPC::RESTORE_CRBIT:
185 case PPC::RESTORE_VRSAVE:
186 // Check for the operands added by addFrameReference (the immediate is the
187 // offset which defaults to 0).
188 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
189 MI->getOperand(2).isFI()) {
190 FrameIndex = MI->getOperand(2).getIndex();
191 return MI->getOperand(0).getReg();
198 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
199 int &FrameIndex) const {
200 // Note: This list must be kept consistent with StoreRegToStackSlot.
201 switch (MI->getOpcode()) {
208 case PPC::SPILL_CRBIT:
211 case PPC::SPILL_VRSAVE:
212 // Check for the operands added by addFrameReference (the immediate is the
213 // offset which defaults to 0).
214 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
215 MI->getOperand(2).isFI()) {
216 FrameIndex = MI->getOperand(2).getIndex();
217 return MI->getOperand(0).getReg();
224 // commuteInstruction - We can commute rlwimi instructions, but only if the
225 // rotate amt is zero. We also have to munge the immediates a bit.
227 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
228 MachineFunction &MF = *MI->getParent()->getParent();
230 // Normal instructions can be commuted the obvious way.
231 if (MI->getOpcode() != PPC::RLWIMI &&
232 MI->getOpcode() != PPC::RLWIMIo &&
233 MI->getOpcode() != PPC::RLWIMI8 &&
234 MI->getOpcode() != PPC::RLWIMI8o)
235 return TargetInstrInfo::commuteInstruction(MI, NewMI);
237 // Cannot commute if it has a non-zero rotate count.
238 if (MI->getOperand(3).getImm() != 0)
241 // If we have a zero rotate count, we have:
243 // Op0 = (Op1 & ~M) | (Op2 & M)
245 // M = mask((ME+1)&31, (MB-1)&31)
246 // Op0 = (Op2 & ~M) | (Op1 & M)
249 unsigned Reg0 = MI->getOperand(0).getReg();
250 unsigned Reg1 = MI->getOperand(1).getReg();
251 unsigned Reg2 = MI->getOperand(2).getReg();
252 unsigned SubReg1 = MI->getOperand(1).getSubReg();
253 unsigned SubReg2 = MI->getOperand(2).getSubReg();
254 bool Reg1IsKill = MI->getOperand(1).isKill();
255 bool Reg2IsKill = MI->getOperand(2).isKill();
256 bool ChangeReg0 = false;
257 // If machine instrs are no longer in two-address forms, update
258 // destination register as well.
260 // Must be two address instruction!
261 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
262 "Expecting a two-address instruction!");
263 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
269 unsigned MB = MI->getOperand(4).getImm();
270 unsigned ME = MI->getOperand(5).getImm();
273 // Create a new instruction.
274 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
275 bool Reg0IsDead = MI->getOperand(0).isDead();
276 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
277 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
278 .addReg(Reg2, getKillRegState(Reg2IsKill))
279 .addReg(Reg1, getKillRegState(Reg1IsKill))
281 .addImm((MB-1) & 31);
285 MI->getOperand(0).setReg(Reg2);
286 MI->getOperand(0).setSubReg(SubReg2);
288 MI->getOperand(2).setReg(Reg1);
289 MI->getOperand(1).setReg(Reg2);
290 MI->getOperand(2).setSubReg(SubReg1);
291 MI->getOperand(1).setSubReg(SubReg2);
292 MI->getOperand(2).setIsKill(Reg1IsKill);
293 MI->getOperand(1).setIsKill(Reg2IsKill);
295 // Swap the mask around.
296 MI->getOperand(4).setImm((ME+1) & 31);
297 MI->getOperand(5).setImm((MB-1) & 31);
301 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
302 unsigned &SrcOpIdx2) const {
303 // For VSX A-Type FMA instructions, it is the first two operands that can be
304 // commuted, however, because the non-encoded tied input operand is listed
305 // first, the operands to swap are actually the second and third.
307 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
309 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
316 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator MI) const {
318 // This function is used for scheduling, and the nop wanted here is the type
319 // that terminates dispatch groups on the POWER cores.
320 unsigned Directive = Subtarget.getDarwinDirective();
323 default: Opcode = PPC::NOP; break;
324 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
325 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
329 BuildMI(MBB, MI, DL, get(Opcode));
333 // Note: If the condition register is set to CTR or CTR8 then this is a
334 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
335 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
336 MachineBasicBlock *&FBB,
337 SmallVectorImpl<MachineOperand> &Cond,
338 bool AllowModify) const {
339 bool isPPC64 = Subtarget.isPPC64();
341 // If the block has no terminators, it just falls into the block after it.
342 MachineBasicBlock::iterator I = MBB.end();
343 if (I == MBB.begin())
346 while (I->isDebugValue()) {
347 if (I == MBB.begin())
351 if (!isUnpredicatedTerminator(I))
354 // Get the last instruction in the block.
355 MachineInstr *LastInst = I;
357 // If there is only one terminator instruction, process it.
358 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
359 if (LastInst->getOpcode() == PPC::B) {
360 if (!LastInst->getOperand(0).isMBB())
362 TBB = LastInst->getOperand(0).getMBB();
364 } else if (LastInst->getOpcode() == PPC::BCC) {
365 if (!LastInst->getOperand(2).isMBB())
367 // Block ends with fall-through condbranch.
368 TBB = LastInst->getOperand(2).getMBB();
369 Cond.push_back(LastInst->getOperand(0));
370 Cond.push_back(LastInst->getOperand(1));
372 } else if (LastInst->getOpcode() == PPC::BC) {
373 if (!LastInst->getOperand(1).isMBB())
375 // Block ends with fall-through condbranch.
376 TBB = LastInst->getOperand(1).getMBB();
377 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
378 Cond.push_back(LastInst->getOperand(0));
380 } else if (LastInst->getOpcode() == PPC::BCn) {
381 if (!LastInst->getOperand(1).isMBB())
383 // Block ends with fall-through condbranch.
384 TBB = LastInst->getOperand(1).getMBB();
385 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
386 Cond.push_back(LastInst->getOperand(0));
388 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
389 LastInst->getOpcode() == PPC::BDNZ) {
390 if (!LastInst->getOperand(0).isMBB())
392 if (DisableCTRLoopAnal)
394 TBB = LastInst->getOperand(0).getMBB();
395 Cond.push_back(MachineOperand::CreateImm(1));
396 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
399 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
400 LastInst->getOpcode() == PPC::BDZ) {
401 if (!LastInst->getOperand(0).isMBB())
403 if (DisableCTRLoopAnal)
405 TBB = LastInst->getOperand(0).getMBB();
406 Cond.push_back(MachineOperand::CreateImm(0));
407 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
412 // Otherwise, don't know what this is.
416 // Get the instruction before it if it's a terminator.
417 MachineInstr *SecondLastInst = I;
419 // If there are three terminators, we don't know what sort of block this is.
420 if (SecondLastInst && I != MBB.begin() &&
421 isUnpredicatedTerminator(--I))
424 // If the block ends with PPC::B and PPC:BCC, handle it.
425 if (SecondLastInst->getOpcode() == PPC::BCC &&
426 LastInst->getOpcode() == PPC::B) {
427 if (!SecondLastInst->getOperand(2).isMBB() ||
428 !LastInst->getOperand(0).isMBB())
430 TBB = SecondLastInst->getOperand(2).getMBB();
431 Cond.push_back(SecondLastInst->getOperand(0));
432 Cond.push_back(SecondLastInst->getOperand(1));
433 FBB = LastInst->getOperand(0).getMBB();
435 } else if (SecondLastInst->getOpcode() == PPC::BC &&
436 LastInst->getOpcode() == PPC::B) {
437 if (!SecondLastInst->getOperand(1).isMBB() ||
438 !LastInst->getOperand(0).isMBB())
440 TBB = SecondLastInst->getOperand(1).getMBB();
441 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
442 Cond.push_back(SecondLastInst->getOperand(0));
443 FBB = LastInst->getOperand(0).getMBB();
445 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
446 LastInst->getOpcode() == PPC::B) {
447 if (!SecondLastInst->getOperand(1).isMBB() ||
448 !LastInst->getOperand(0).isMBB())
450 TBB = SecondLastInst->getOperand(1).getMBB();
451 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
452 Cond.push_back(SecondLastInst->getOperand(0));
453 FBB = LastInst->getOperand(0).getMBB();
455 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
456 SecondLastInst->getOpcode() == PPC::BDNZ) &&
457 LastInst->getOpcode() == PPC::B) {
458 if (!SecondLastInst->getOperand(0).isMBB() ||
459 !LastInst->getOperand(0).isMBB())
461 if (DisableCTRLoopAnal)
463 TBB = SecondLastInst->getOperand(0).getMBB();
464 Cond.push_back(MachineOperand::CreateImm(1));
465 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
467 FBB = LastInst->getOperand(0).getMBB();
469 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
470 SecondLastInst->getOpcode() == PPC::BDZ) &&
471 LastInst->getOpcode() == PPC::B) {
472 if (!SecondLastInst->getOperand(0).isMBB() ||
473 !LastInst->getOperand(0).isMBB())
475 if (DisableCTRLoopAnal)
477 TBB = SecondLastInst->getOperand(0).getMBB();
478 Cond.push_back(MachineOperand::CreateImm(0));
479 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
481 FBB = LastInst->getOperand(0).getMBB();
485 // If the block ends with two PPC:Bs, handle it. The second one is not
486 // executed, so remove it.
487 if (SecondLastInst->getOpcode() == PPC::B &&
488 LastInst->getOpcode() == PPC::B) {
489 if (!SecondLastInst->getOperand(0).isMBB())
491 TBB = SecondLastInst->getOperand(0).getMBB();
494 I->eraseFromParent();
498 // Otherwise, can't handle this.
502 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
503 MachineBasicBlock::iterator I = MBB.end();
504 if (I == MBB.begin()) return 0;
506 while (I->isDebugValue()) {
507 if (I == MBB.begin())
511 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
512 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
513 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
514 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
517 // Remove the branch.
518 I->eraseFromParent();
522 if (I == MBB.begin()) return 1;
524 if (I->getOpcode() != PPC::BCC &&
525 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
526 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
527 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
530 // Remove the branch.
531 I->eraseFromParent();
536 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
537 MachineBasicBlock *FBB,
538 const SmallVectorImpl<MachineOperand> &Cond,
540 // Shouldn't be a fall through.
541 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
542 assert((Cond.size() == 2 || Cond.size() == 0) &&
543 "PPC branch conditions have two components!");
545 bool isPPC64 = Subtarget.isPPC64();
549 if (Cond.empty()) // Unconditional branch
550 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
551 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
552 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
553 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
554 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
555 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
556 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
557 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
558 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
559 else // Conditional branch
560 BuildMI(&MBB, DL, get(PPC::BCC))
561 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
565 // Two-way Conditional Branch.
566 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
567 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
568 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
569 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
570 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
571 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
572 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
573 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
575 BuildMI(&MBB, DL, get(PPC::BCC))
576 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
577 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
582 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
583 const SmallVectorImpl<MachineOperand> &Cond,
584 unsigned TrueReg, unsigned FalseReg,
585 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
586 if (!Subtarget.hasISEL())
589 if (Cond.size() != 2)
592 // If this is really a bdnz-like condition, then it cannot be turned into a
594 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
597 // Check register classes.
598 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
599 const TargetRegisterClass *RC =
600 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
604 // isel is for regular integer GPRs only.
605 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
606 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
607 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
608 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
611 // FIXME: These numbers are for the A2, how well they work for other cores is
612 // an open question. On the A2, the isel instruction has a 2-cycle latency
613 // but single-cycle throughput. These numbers are used in combination with
614 // the MispredictPenalty setting from the active SchedMachineModel.
622 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
623 MachineBasicBlock::iterator MI, DebugLoc dl,
625 const SmallVectorImpl<MachineOperand> &Cond,
626 unsigned TrueReg, unsigned FalseReg) const {
627 assert(Cond.size() == 2 &&
628 "PPC branch conditions have two components!");
630 assert(Subtarget.hasISEL() &&
631 "Cannot insert select on target without ISEL support");
633 // Get the register classes.
634 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
635 const TargetRegisterClass *RC =
636 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
637 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
639 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
640 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
642 PPC::GPRCRegClass.hasSubClassEq(RC) ||
643 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
644 "isel is for regular integer GPRs only");
646 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
647 unsigned SelectPred = Cond[0].getImm();
651 switch (SelectPred) {
652 default: llvm_unreachable("invalid predicate for isel");
653 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
654 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
655 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
656 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
657 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
658 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
659 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
660 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
661 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
662 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
665 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
666 SecondReg = SwapOps ? TrueReg : FalseReg;
668 // The first input register of isel cannot be r0. If it is a member
669 // of a register class that can be r0, then copy it first (the
670 // register allocator should eliminate the copy).
671 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
672 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
673 const TargetRegisterClass *FirstRC =
674 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
675 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
676 unsigned OldFirstReg = FirstReg;
677 FirstReg = MRI.createVirtualRegister(FirstRC);
678 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
679 .addReg(OldFirstReg);
682 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
683 .addReg(FirstReg).addReg(SecondReg)
684 .addReg(Cond[1].getReg(), 0, SubIdx);
687 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
688 MachineBasicBlock::iterator I, DebugLoc DL,
689 unsigned DestReg, unsigned SrcReg,
690 bool KillSrc) const {
691 // We can end up with self copies and similar things as a result of VSX copy
692 // legalization. Promote them here.
693 const TargetRegisterInfo *TRI = &getRegisterInfo();
694 if (PPC::F8RCRegClass.contains(DestReg) &&
695 PPC::VSLRCRegClass.contains(SrcReg)) {
697 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
699 if (VSXSelfCopyCrash && SrcReg == SuperReg)
700 llvm_unreachable("nop VSX copy");
703 } else if (PPC::VRRCRegClass.contains(DestReg) &&
704 PPC::VSHRCRegClass.contains(SrcReg)) {
706 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
708 if (VSXSelfCopyCrash && SrcReg == SuperReg)
709 llvm_unreachable("nop VSX copy");
712 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
713 PPC::VSLRCRegClass.contains(DestReg)) {
715 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
717 if (VSXSelfCopyCrash && DestReg == SuperReg)
718 llvm_unreachable("nop VSX copy");
721 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
722 PPC::VSHRCRegClass.contains(DestReg)) {
724 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
726 if (VSXSelfCopyCrash && DestReg == SuperReg)
727 llvm_unreachable("nop VSX copy");
733 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
735 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
737 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
739 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
741 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
743 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
744 // There are two different ways this can be done:
745 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
746 // issue in VSU pipeline 0.
747 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
748 // can go to either pipeline.
749 // We'll always use xxlor here, because in practically all cases where
750 // copies are generated, they are close enough to some use that the
751 // lower-latency form is preferable.
753 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
755 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
758 llvm_unreachable("Impossible reg-to-reg copy");
760 const MCInstrDesc &MCID = get(Opc);
761 if (MCID.getNumOperands() == 3)
762 BuildMI(MBB, I, DL, MCID, DestReg)
763 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
765 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
768 // This function returns true if a CR spill is necessary and false otherwise.
770 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
771 unsigned SrcReg, bool isKill,
773 const TargetRegisterClass *RC,
774 SmallVectorImpl<MachineInstr*> &NewMIs,
775 bool &NonRI, bool &SpillsVRS) const{
776 // Note: If additional store instructions are added here,
777 // update isStoreToStackSlot.
780 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
781 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
782 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
784 getKillRegState(isKill)),
786 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
787 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
788 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
790 getKillRegState(isKill)),
792 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
793 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
795 getKillRegState(isKill)),
797 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
798 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
800 getKillRegState(isKill)),
802 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
803 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
805 getKillRegState(isKill)),
808 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
809 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
811 getKillRegState(isKill)),
814 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
815 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
817 getKillRegState(isKill)),
820 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
821 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
823 getKillRegState(isKill)),
826 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
827 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
829 getKillRegState(isKill)),
832 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
833 assert(Subtarget.isDarwin() &&
834 "VRSAVE only needs spill/restore on Darwin");
835 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
837 getKillRegState(isKill)),
841 llvm_unreachable("Unknown regclass!");
848 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
849 MachineBasicBlock::iterator MI,
850 unsigned SrcReg, bool isKill, int FrameIdx,
851 const TargetRegisterClass *RC,
852 const TargetRegisterInfo *TRI) const {
853 MachineFunction &MF = *MBB.getParent();
854 SmallVector<MachineInstr*, 4> NewMIs;
856 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
857 FuncInfo->setHasSpills();
859 bool NonRI = false, SpillsVRS = false;
860 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
862 FuncInfo->setSpillsCR();
865 FuncInfo->setSpillsVRSAVE();
868 FuncInfo->setHasNonRISpills();
870 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
871 MBB.insert(MI, NewMIs[i]);
873 const MachineFrameInfo &MFI = *MF.getFrameInfo();
874 MachineMemOperand *MMO =
875 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
876 MachineMemOperand::MOStore,
877 MFI.getObjectSize(FrameIdx),
878 MFI.getObjectAlignment(FrameIdx));
879 NewMIs.back()->addMemOperand(MF, MMO);
883 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
884 unsigned DestReg, int FrameIdx,
885 const TargetRegisterClass *RC,
886 SmallVectorImpl<MachineInstr*> &NewMIs,
887 bool &NonRI, bool &SpillsVRS) const{
888 // Note: If additional load instructions are added here,
889 // update isLoadFromStackSlot.
891 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
892 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
893 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
894 DestReg), FrameIdx));
895 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
896 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
897 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
899 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
900 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
902 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
903 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
905 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
906 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
907 get(PPC::RESTORE_CR), DestReg),
910 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
911 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
912 get(PPC::RESTORE_CRBIT), DestReg),
915 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
916 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
919 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
920 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
923 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
924 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
927 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
928 assert(Subtarget.isDarwin() &&
929 "VRSAVE only needs spill/restore on Darwin");
930 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
931 get(PPC::RESTORE_VRSAVE),
936 llvm_unreachable("Unknown regclass!");
943 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
944 MachineBasicBlock::iterator MI,
945 unsigned DestReg, int FrameIdx,
946 const TargetRegisterClass *RC,
947 const TargetRegisterInfo *TRI) const {
948 MachineFunction &MF = *MBB.getParent();
949 SmallVector<MachineInstr*, 4> NewMIs;
951 if (MI != MBB.end()) DL = MI->getDebugLoc();
953 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
954 FuncInfo->setHasSpills();
956 bool NonRI = false, SpillsVRS = false;
957 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
959 FuncInfo->setSpillsCR();
962 FuncInfo->setSpillsVRSAVE();
965 FuncInfo->setHasNonRISpills();
967 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
968 MBB.insert(MI, NewMIs[i]);
970 const MachineFrameInfo &MFI = *MF.getFrameInfo();
971 MachineMemOperand *MMO =
972 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
973 MachineMemOperand::MOLoad,
974 MFI.getObjectSize(FrameIdx),
975 MFI.getObjectAlignment(FrameIdx));
976 NewMIs.back()->addMemOperand(MF, MMO);
980 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
981 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
982 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
983 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
985 // Leave the CR# the same, but invert the condition.
986 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
990 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
991 unsigned Reg, MachineRegisterInfo *MRI) const {
992 // For some instructions, it is legal to fold ZERO into the RA register field.
993 // A zero immediate should always be loaded with a single li.
994 unsigned DefOpc = DefMI->getOpcode();
995 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
997 if (!DefMI->getOperand(1).isImm())
999 if (DefMI->getOperand(1).getImm() != 0)
1002 // Note that we cannot here invert the arguments of an isel in order to fold
1003 // a ZERO into what is presented as the second argument. All we have here
1004 // is the condition bit, and that might come from a CR-logical bit operation.
1006 const MCInstrDesc &UseMCID = UseMI->getDesc();
1008 // Only fold into real machine instructions.
1009 if (UseMCID.isPseudo())
1013 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1014 if (UseMI->getOperand(UseIdx).isReg() &&
1015 UseMI->getOperand(UseIdx).getReg() == Reg)
1018 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1019 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1021 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1023 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1024 // register (which might also be specified as a pointer class kind).
1025 if (UseInfo->isLookupPtrRegClass()) {
1026 if (UseInfo->RegClass /* Kind */ != 1)
1029 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1030 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1034 // Make sure this is not tied to an output register (or otherwise
1035 // constrained). This is true for ST?UX registers, for example, which
1036 // are tied to their output registers.
1037 if (UseInfo->Constraints != 0)
1041 if (UseInfo->isLookupPtrRegClass()) {
1042 bool isPPC64 = Subtarget.isPPC64();
1043 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1045 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1046 PPC::ZERO8 : PPC::ZERO;
1049 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1050 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1053 DefMI->eraseFromParent();
1058 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1059 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1061 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1066 // We should make sure that, if we're going to predicate both sides of a
1067 // condition (a diamond), that both sides don't define the counter register. We
1068 // can predicate counter-decrement-based branches, but while that predicates
1069 // the branching, it does not predicate the counter decrement. If we tried to
1070 // merge the triangle into one predicated block, we'd decrement the counter
1072 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1073 unsigned NumT, unsigned ExtraT,
1074 MachineBasicBlock &FMBB,
1075 unsigned NumF, unsigned ExtraF,
1076 const BranchProbability &Probability) const {
1077 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1081 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1082 // The predicated branches are identified by their type, not really by the
1083 // explicit presence of a predicate. Furthermore, some of them can be
1084 // predicated more than once. Because if conversion won't try to predicate
1085 // any instruction which already claims to be predicated (by returning true
1086 // here), always return false. In doing so, we let isPredicable() be the
1087 // final word on whether not the instruction can be (further) predicated.
1092 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1093 if (!MI->isTerminator())
1096 // Conditional branch is a special case.
1097 if (MI->isBranch() && !MI->isBarrier())
1100 return !isPredicated(MI);
1103 bool PPCInstrInfo::PredicateInstruction(
1105 const SmallVectorImpl<MachineOperand> &Pred) const {
1106 unsigned OpC = MI->getOpcode();
1107 if (OpC == PPC::BLR) {
1108 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1109 bool isPPC64 = Subtarget.isPPC64();
1110 MI->setDesc(get(Pred[0].getImm() ?
1111 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1112 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1113 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1114 MI->setDesc(get(PPC::BCLR));
1115 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1116 .addReg(Pred[1].getReg());
1117 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1118 MI->setDesc(get(PPC::BCLRn));
1119 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1120 .addReg(Pred[1].getReg());
1122 MI->setDesc(get(PPC::BCCLR));
1123 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1124 .addImm(Pred[0].getImm())
1125 .addReg(Pred[1].getReg());
1129 } else if (OpC == PPC::B) {
1130 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1131 bool isPPC64 = Subtarget.isPPC64();
1132 MI->setDesc(get(Pred[0].getImm() ?
1133 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1134 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1135 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1136 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1137 MI->RemoveOperand(0);
1139 MI->setDesc(get(PPC::BC));
1140 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1141 .addReg(Pred[1].getReg())
1143 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1144 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1145 MI->RemoveOperand(0);
1147 MI->setDesc(get(PPC::BCn));
1148 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1149 .addReg(Pred[1].getReg())
1152 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1153 MI->RemoveOperand(0);
1155 MI->setDesc(get(PPC::BCC));
1156 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1157 .addImm(Pred[0].getImm())
1158 .addReg(Pred[1].getReg())
1163 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1164 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1165 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1166 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1168 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1169 bool isPPC64 = Subtarget.isPPC64();
1171 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1172 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1173 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1174 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1175 .addReg(Pred[1].getReg());
1177 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1178 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1179 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1180 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1181 .addReg(Pred[1].getReg());
1185 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1186 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1187 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1188 .addImm(Pred[0].getImm())
1189 .addReg(Pred[1].getReg());
1196 bool PPCInstrInfo::SubsumesPredicate(
1197 const SmallVectorImpl<MachineOperand> &Pred1,
1198 const SmallVectorImpl<MachineOperand> &Pred2) const {
1199 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1200 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1202 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1204 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1207 // P1 can only subsume P2 if they test the same condition register.
1208 if (Pred1[1].getReg() != Pred2[1].getReg())
1211 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1212 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1217 // Does P1 subsume P2, e.g. GE subsumes GT.
1218 if (P1 == PPC::PRED_LE &&
1219 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1221 if (P1 == PPC::PRED_GE &&
1222 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1228 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1229 std::vector<MachineOperand> &Pred) const {
1230 // Note: At the present time, the contents of Pred from this function is
1231 // unused by IfConversion. This implementation follows ARM by pushing the
1232 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1233 // predicate, instructions defining CTR or CTR8 are also included as
1234 // predicate-defining instructions.
1236 const TargetRegisterClass *RCs[] =
1237 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1238 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1241 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1242 const MachineOperand &MO = MI->getOperand(i);
1243 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1244 const TargetRegisterClass *RC = RCs[c];
1246 if (MO.isDef() && RC->contains(MO.getReg())) {
1250 } else if (MO.isRegMask()) {
1251 for (TargetRegisterClass::iterator I = RC->begin(),
1252 IE = RC->end(); I != IE; ++I)
1253 if (MO.clobbersPhysReg(*I)) {
1264 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1265 unsigned OpC = MI->getOpcode();
1279 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1280 unsigned &SrcReg, unsigned &SrcReg2,
1281 int &Mask, int &Value) const {
1282 unsigned Opc = MI->getOpcode();
1285 default: return false;
1290 SrcReg = MI->getOperand(1).getReg();
1292 Value = MI->getOperand(2).getImm();
1301 SrcReg = MI->getOperand(1).getReg();
1302 SrcReg2 = MI->getOperand(2).getReg();
1307 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1308 unsigned SrcReg, unsigned SrcReg2,
1309 int Mask, int Value,
1310 const MachineRegisterInfo *MRI) const {
1314 int OpC = CmpInstr->getOpcode();
1315 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1317 // FP record forms set CR1 based on the execption status bits, not a
1318 // comparison with zero.
1319 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1322 // The record forms set the condition register based on a signed comparison
1323 // with zero (so says the ISA manual). This is not as straightforward as it
1324 // seems, however, because this is always a 64-bit comparison on PPC64, even
1325 // for instructions that are 32-bit in nature (like slw for example).
1326 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1327 // for equality checks (as those don't depend on the sign). On PPC64,
1328 // we are restricted to equality for unsigned 64-bit comparisons and for
1329 // signed 32-bit comparisons the applicability is more restricted.
1330 bool isPPC64 = Subtarget.isPPC64();
1331 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1332 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1333 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1335 // Get the unique definition of SrcReg.
1336 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1337 if (!MI) return false;
1338 int MIOpC = MI->getOpcode();
1340 bool equalityOnly = false;
1343 if (is32BitSignedCompare) {
1344 // We can perform this optimization only if MI is sign-extending.
1345 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1346 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1347 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1348 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1349 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1353 } else if (is32BitUnsignedCompare) {
1354 // We can perform this optimization, equality only, if MI is
1356 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1357 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1358 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1360 equalityOnly = true;
1364 equalityOnly = is64BitUnsignedCompare;
1366 equalityOnly = is32BitUnsignedCompare;
1369 // We need to check the uses of the condition register in order to reject
1370 // non-equality comparisons.
1371 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1372 IE = MRI->use_instr_end(); I != IE; ++I) {
1373 MachineInstr *UseMI = &*I;
1374 if (UseMI->getOpcode() == PPC::BCC) {
1375 unsigned Pred = UseMI->getOperand(0).getImm();
1376 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1378 } else if (UseMI->getOpcode() == PPC::ISEL ||
1379 UseMI->getOpcode() == PPC::ISEL8) {
1380 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1381 if (SubIdx != PPC::sub_eq)
1388 MachineBasicBlock::iterator I = CmpInstr;
1390 // Scan forward to find the first use of the compare.
1391 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1393 bool FoundUse = false;
1394 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1395 JE = MRI->use_instr_end(); J != JE; ++J)
1405 // There are two possible candidates which can be changed to set CR[01].
1406 // One is MI, the other is a SUB instruction.
1407 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1408 MachineInstr *Sub = nullptr;
1410 // MI is not a candidate for CMPrr.
1412 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1413 // same BB as the comparison. This is to allow the check below to avoid calls
1414 // (and other explicit clobbers); instead we should really check for these
1415 // more explicitly (in at least a few predecessors).
1416 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1417 // PPC does not have a record-form SUBri.
1422 const TargetRegisterInfo *TRI = &getRegisterInfo();
1425 // Get ready to iterate backward from CmpInstr.
1426 MachineBasicBlock::iterator E = MI,
1427 B = CmpInstr->getParent()->begin();
1429 for (; I != E && !noSub; --I) {
1430 const MachineInstr &Instr = *I;
1431 unsigned IOpC = Instr.getOpcode();
1433 if (&*I != CmpInstr && (
1434 Instr.modifiesRegister(PPC::CR0, TRI) ||
1435 Instr.readsRegister(PPC::CR0, TRI)))
1436 // This instruction modifies or uses the record condition register after
1437 // the one we want to change. While we could do this transformation, it
1438 // would likely not be profitable. This transformation removes one
1439 // instruction, and so even forcing RA to generate one move probably
1440 // makes it unprofitable.
1443 // Check whether CmpInstr can be made redundant by the current instruction.
1444 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1445 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1446 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1447 ((Instr.getOperand(1).getReg() == SrcReg &&
1448 Instr.getOperand(2).getReg() == SrcReg2) ||
1449 (Instr.getOperand(1).getReg() == SrcReg2 &&
1450 Instr.getOperand(2).getReg() == SrcReg))) {
1456 // The 'and' is below the comparison instruction.
1460 // Return false if no candidates exist.
1464 // The single candidate is called MI.
1468 MIOpC = MI->getOpcode();
1469 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1472 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1473 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1477 // FIXME: On the non-embedded POWER architectures, only some of the record
1478 // forms are fast, and we should use only the fast ones.
1480 // The defining instruction has a record form (or is already a record
1481 // form). It is possible, however, that we'll need to reverse the condition
1482 // code of the users.
1486 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1487 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1489 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1490 // needs to be updated to be based on SUB. Push the condition code
1491 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1492 // condition code of these operands will be modified.
1493 bool ShouldSwap = false;
1495 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1496 Sub->getOperand(2).getReg() == SrcReg;
1498 // The operands to subf are the opposite of sub, so only in the fixed-point
1499 // case, invert the order.
1500 ShouldSwap = !ShouldSwap;
1504 for (MachineRegisterInfo::use_instr_iterator
1505 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1507 MachineInstr *UseMI = &*I;
1508 if (UseMI->getOpcode() == PPC::BCC) {
1509 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1510 assert((!equalityOnly ||
1511 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1512 "Invalid predicate for equality-only optimization");
1513 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1514 PPC::getSwappedPredicate(Pred)));
1515 } else if (UseMI->getOpcode() == PPC::ISEL ||
1516 UseMI->getOpcode() == PPC::ISEL8) {
1517 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1518 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1519 "Invalid CR bit for equality-only optimization");
1521 if (NewSubReg == PPC::sub_lt)
1522 NewSubReg = PPC::sub_gt;
1523 else if (NewSubReg == PPC::sub_gt)
1524 NewSubReg = PPC::sub_lt;
1526 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1528 } else // We need to abort on a user we don't understand.
1532 // Create a new virtual register to hold the value of the CR set by the
1533 // record-form instruction. If the instruction was not previously in
1534 // record form, then set the kill flag on the CR.
1535 CmpInstr->eraseFromParent();
1537 MachineBasicBlock::iterator MII = MI;
1538 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1539 get(TargetOpcode::COPY), CRReg)
1540 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1542 if (MIOpC != NewOpC) {
1543 // We need to be careful here: we're replacing one instruction with
1544 // another, and we need to make sure that we get all of the right
1545 // implicit uses and defs. On the other hand, the caller may be holding
1546 // an iterator to this instruction, and so we can't delete it (this is
1547 // specifically the case if this is the instruction directly after the
1550 const MCInstrDesc &NewDesc = get(NewOpC);
1551 MI->setDesc(NewDesc);
1553 if (NewDesc.ImplicitDefs)
1554 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1555 *ImpDefs; ++ImpDefs)
1556 if (!MI->definesRegister(*ImpDefs))
1557 MI->addOperand(*MI->getParent()->getParent(),
1558 MachineOperand::CreateReg(*ImpDefs, true, true));
1559 if (NewDesc.ImplicitUses)
1560 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1561 *ImpUses; ++ImpUses)
1562 if (!MI->readsRegister(*ImpUses))
1563 MI->addOperand(*MI->getParent()->getParent(),
1564 MachineOperand::CreateReg(*ImpUses, false, true));
1567 // Modify the condition code of operands in OperandsToUpdate.
1568 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1569 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1570 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1571 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1573 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1574 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1579 /// GetInstSize - Return the number of bytes of code the specified
1580 /// instruction may be. This returns the maximum number of bytes.
1582 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1583 unsigned Opcode = MI->getOpcode();
1585 if (Opcode == PPC::INLINEASM) {
1586 const MachineFunction *MF = MI->getParent()->getParent();
1587 const char *AsmStr = MI->getOperand(0).getSymbolName();
1588 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1590 const MCInstrDesc &Desc = get(Opcode);
1591 return Desc.getSize();
1596 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1599 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1600 // (Altivec and scalar floating-point registers), we need to transform the
1601 // copies into subregister copies with other restrictions.
1602 struct PPCVSXFMAMutate : public MachineFunctionPass {
1604 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1605 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1610 const PPCTargetMachine *TM;
1611 const PPCInstrInfo *TII;
1614 bool processBlock(MachineBasicBlock &MBB) {
1615 bool Changed = false;
1617 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1618 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1620 MachineInstr *MI = I;
1622 // The default (A-type) VSX FMA form kills the addend (it is taken from
1623 // the target register, which is then updated to reflect the result of
1624 // the FMA). If the instruction, however, kills one of the registers
1625 // used for the product, then we can use the M-form instruction (which
1626 // will take that value from the to-be-defined register).
1628 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1632 // This pass is run after register coalescing, and so we're looking for
1633 // a situation like this:
1635 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1636 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1637 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1639 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1640 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1642 // Where we can eliminate the copy by changing from the A-type to the
1643 // M-type instruction. Specifically, for this example, this means:
1644 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1645 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1647 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1648 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1649 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1651 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1653 VNInfo *AddendValNo =
1654 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1655 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1657 // The addend and this instruction must be in the same block.
1659 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1662 // The addend must be a full copy within the same register class.
1664 if (!AddendMI->isFullCopy())
1667 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1668 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1669 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1670 MRI.getRegClass(AddendSrcReg))
1673 // If AddendSrcReg is a physical register, make sure the destination
1674 // register class contains it.
1675 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1676 ->contains(AddendSrcReg))
1680 // In theory, there could be other uses of the addend copy before this
1681 // fma. We could deal with this, but that would require additional
1682 // logic below and I suspect it will not occur in any relevant
1684 bool OtherUsers = false;
1685 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1687 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1695 // Find one of the product operands that is killed by this instruction.
1697 unsigned KilledProdOp = 0, OtherProdOp = 0;
1698 if (LIS->getInterval(MI->getOperand(2).getReg())
1699 .Query(FMAIdx).isKill()) {
1702 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1703 .Query(FMAIdx).isKill()) {
1708 // If there are no killed product operands, then this transformation is
1709 // likely not profitable.
1713 // In order to replace the addend here with the source of the copy,
1714 // it must still be live here.
1715 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1718 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1720 unsigned AddReg = AddendMI->getOperand(1).getReg();
1721 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1722 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1724 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1725 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1726 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1728 bool AddRegKill = AddendMI->getOperand(1).isKill();
1729 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1730 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1732 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1733 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1734 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1736 unsigned OldFMAReg = MI->getOperand(0).getReg();
1738 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1739 "Addend copy not tied to old FMA output!");
1741 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1743 MI->getOperand(0).setReg(KilledProdReg);
1744 MI->getOperand(1).setReg(KilledProdReg);
1745 MI->getOperand(3).setReg(AddReg);
1746 MI->getOperand(2).setReg(OtherProdReg);
1748 MI->getOperand(0).setSubReg(KilledProdSubReg);
1749 MI->getOperand(1).setSubReg(KilledProdSubReg);
1750 MI->getOperand(3).setSubReg(AddSubReg);
1751 MI->getOperand(2).setSubReg(OtherProdSubReg);
1753 MI->getOperand(1).setIsKill(KilledProdRegKill);
1754 MI->getOperand(3).setIsKill(AddRegKill);
1755 MI->getOperand(2).setIsKill(OtherProdRegKill);
1757 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1758 MI->getOperand(3).setIsUndef(AddRegUndef);
1759 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1761 MI->setDesc(TII->get(AltOpc));
1763 DEBUG(dbgs() << " -> " << *MI);
1765 // The killed product operand was killed here, so we can reuse it now
1766 // for the result of the fma.
1768 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1769 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1770 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1772 MachineOperand &UseMO = *UI;
1773 MachineInstr *UseMI = UseMO.getParent();
1776 // Don't replace the result register of the copy we're about to erase.
1777 if (UseMI == AddendMI)
1780 UseMO.setReg(KilledProdReg);
1781 UseMO.setSubReg(KilledProdSubReg);
1784 // Extend the live intervals of the killed product operand to hold the
1787 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1788 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1790 // Don't add the segment that corresponds to the original copy.
1791 if (AI->valno == AddendValNo)
1794 VNInfo *NewFMAValNo =
1795 NewFMAInt.getNextValue(AI->start,
1796 LIS->getVNInfoAllocator());
1798 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1801 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1803 FMAInt.removeValNo(FMAValNo);
1804 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1806 // Remove the (now unused) copy.
1808 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1809 LIS->RemoveMachineInstrFromMaps(AddendMI);
1810 AddendMI->eraseFromParent();
1819 bool runOnMachineFunction(MachineFunction &MF) override {
1820 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1821 // If we don't have VSX then go ahead and return without doing
1823 if (!TM->getSubtargetImpl()->hasVSX())
1826 LIS = &getAnalysis<LiveIntervals>();
1828 TII = TM->getInstrInfo();
1830 bool Changed = false;
1832 if (DisableVSXFMAMutate)
1835 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1836 MachineBasicBlock &B = *I++;
1837 if (processBlock(B))
1844 void getAnalysisUsage(AnalysisUsage &AU) const override {
1845 AU.addRequired<LiveIntervals>();
1846 AU.addPreserved<LiveIntervals>();
1847 AU.addRequired<SlotIndexes>();
1848 AU.addPreserved<SlotIndexes>();
1849 MachineFunctionPass::getAnalysisUsage(AU);
1854 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1855 "PowerPC VSX FMA Mutation", false, false)
1856 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1857 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1858 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1859 "PowerPC VSX FMA Mutation", false, false)
1861 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1863 char PPCVSXFMAMutate::ID = 0;
1865 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1868 #define DEBUG_TYPE "ppc-vsx-copy"
1871 void initializePPCVSXCopyPass(PassRegistry&);
1875 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1876 // (Altivec and scalar floating-point registers), we need to transform the
1877 // copies into subregister copies with other restrictions.
1878 struct PPCVSXCopy : public MachineFunctionPass {
1880 PPCVSXCopy() : MachineFunctionPass(ID) {
1881 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1884 const PPCTargetMachine *TM;
1885 const PPCInstrInfo *TII;
1887 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1888 MachineRegisterInfo &MRI) {
1889 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1890 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1891 } else if (RC->contains(Reg)) {
1898 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1899 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1902 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1903 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1906 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1907 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1911 bool processBlock(MachineBasicBlock &MBB) {
1912 bool Changed = false;
1914 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1915 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1917 MachineInstr *MI = I;
1918 if (!MI->isFullCopy())
1921 MachineOperand &DstMO = MI->getOperand(0);
1922 MachineOperand &SrcMO = MI->getOperand(1);
1924 if ( IsVSReg(DstMO.getReg(), MRI) &&
1925 !IsVSReg(SrcMO.getReg(), MRI)) {
1926 // This is a copy *to* a VSX register from a non-VSX register.
1929 const TargetRegisterClass *SrcRC =
1930 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1931 &PPC::VSLRCRegClass;
1932 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1933 IsVRReg(SrcMO.getReg(), MRI)) &&
1934 "Unknown source for a VSX copy");
1936 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1937 BuildMI(MBB, MI, MI->getDebugLoc(),
1938 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1939 .addImm(1) // add 1, not 0, because there is no implicit clearing
1940 // of the high bits.
1942 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1945 // The source of the original copy is now the new virtual register.
1946 SrcMO.setReg(NewVReg);
1947 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1948 IsVSReg(SrcMO.getReg(), MRI)) {
1949 // This is a copy *from* a VSX register to a non-VSX register.
1952 const TargetRegisterClass *DstRC =
1953 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1954 &PPC::VSLRCRegClass;
1955 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1956 IsVRReg(DstMO.getReg(), MRI)) &&
1957 "Unknown destination for a VSX copy");
1959 // Copy the VSX value into a new VSX register of the correct subclass.
1960 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1961 BuildMI(MBB, MI, MI->getDebugLoc(),
1962 TII->get(TargetOpcode::COPY), NewVReg)
1965 // Transform the original copy into a subregister extraction copy.
1966 SrcMO.setReg(NewVReg);
1967 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1976 bool runOnMachineFunction(MachineFunction &MF) override {
1977 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1978 // If we don't have VSX on the subtarget, don't do anything.
1979 if (!TM->getSubtargetImpl()->hasVSX())
1981 TII = TM->getInstrInfo();
1983 bool Changed = false;
1985 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1986 MachineBasicBlock &B = *I++;
1987 if (processBlock(B))
1994 void getAnalysisUsage(AnalysisUsage &AU) const override {
1995 MachineFunctionPass::getAnalysisUsage(AU);
2000 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2001 "PowerPC VSX Copy Legalization", false, false)
2003 char PPCVSXCopy::ID = 0;
2005 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2008 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2011 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2015 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2016 // registers (mostly because the ABI code still places all values into the
2017 // "traditional" floating-point and vector registers). Remove them here.
2018 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2020 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2021 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2024 const PPCTargetMachine *TM;
2025 const PPCInstrInfo *TII;
2028 bool processBlock(MachineBasicBlock &MBB) {
2029 bool Changed = false;
2031 SmallVector<MachineInstr *, 4> ToDelete;
2032 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2034 MachineInstr *MI = I;
2035 if (MI->getOpcode() == PPC::XXLOR &&
2036 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2037 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2038 ToDelete.push_back(MI);
2041 if (!ToDelete.empty())
2044 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2045 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2046 ToDelete[i]->eraseFromParent();
2053 bool runOnMachineFunction(MachineFunction &MF) override {
2054 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2055 // If we don't have VSX don't bother doing anything here.
2056 if (!TM->getSubtargetImpl()->hasVSX())
2058 TII = TM->getInstrInfo();
2060 bool Changed = false;
2062 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2063 MachineBasicBlock &B = *I++;
2064 if (processBlock(B))
2071 void getAnalysisUsage(AnalysisUsage &AU) const override {
2072 MachineFunctionPass::getAnalysisUsage(AU);
2077 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2078 "PowerPC VSX Copy Cleanup", false, false)
2080 char PPCVSXCopyCleanup::ID = 0;
2082 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2085 #define DEBUG_TYPE "ppc-early-ret"
2086 STATISTIC(NumBCLR, "Number of early conditional returns");
2087 STATISTIC(NumBLR, "Number of early returns");
2090 void initializePPCEarlyReturnPass(PassRegistry&);
2094 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2095 // returns up, and create conditional returns, to avoid unnecessary
2096 // branch-to-blr sequences.
2097 struct PPCEarlyReturn : public MachineFunctionPass {
2099 PPCEarlyReturn() : MachineFunctionPass(ID) {
2100 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2103 const PPCTargetMachine *TM;
2104 const PPCInstrInfo *TII;
2107 bool processBlock(MachineBasicBlock &ReturnMBB) {
2108 bool Changed = false;
2110 MachineBasicBlock::iterator I = ReturnMBB.begin();
2111 I = ReturnMBB.SkipPHIsAndLabels(I);
2113 // The block must be essentially empty except for the blr.
2114 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2115 I != ReturnMBB.getLastNonDebugInstr())
2118 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2119 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2120 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2121 bool OtherReference = false, BlockChanged = false;
2122 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2123 if (J->getOpcode() == PPC::B) {
2124 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2125 // This is an unconditional branch to the return. Replace the
2126 // branch with a blr.
2127 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2128 MachineBasicBlock::iterator K = J--;
2129 K->eraseFromParent();
2130 BlockChanged = true;
2134 } else if (J->getOpcode() == PPC::BCC) {
2135 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2136 // This is a conditional branch to the return. Replace the branch
2138 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2139 .addImm(J->getOperand(0).getImm())
2140 .addReg(J->getOperand(1).getReg());
2141 MachineBasicBlock::iterator K = J--;
2142 K->eraseFromParent();
2143 BlockChanged = true;
2147 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2148 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2149 // This is a conditional branch to the return. Replace the branch
2151 BuildMI(**PI, J, J->getDebugLoc(),
2152 TII->get(J->getOpcode() == PPC::BC ?
2153 PPC::BCLR : PPC::BCLRn))
2154 .addReg(J->getOperand(0).getReg());
2155 MachineBasicBlock::iterator K = J--;
2156 K->eraseFromParent();
2157 BlockChanged = true;
2161 } else if (J->isBranch()) {
2162 if (J->isIndirectBranch()) {
2163 if (ReturnMBB.hasAddressTaken())
2164 OtherReference = true;
2166 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2167 if (J->getOperand(i).isMBB() &&
2168 J->getOperand(i).getMBB() == &ReturnMBB)
2169 OtherReference = true;
2170 } else if (!J->isTerminator() && !J->isDebugValue())
2173 if (J == (*PI)->begin())
2179 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2180 OtherReference = true;
2182 // Predecessors are stored in a vector and can't be removed here.
2183 if (!OtherReference && BlockChanged) {
2184 PredToRemove.push_back(*PI);
2191 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2192 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2194 if (Changed && !ReturnMBB.hasAddressTaken()) {
2195 // We now might be able to merge this blr-only block into its
2196 // by-layout predecessor.
2197 if (ReturnMBB.pred_size() == 1 &&
2198 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2199 // Move the blr into the preceding block.
2200 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2201 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2202 PrevMBB.removeSuccessor(&ReturnMBB);
2205 if (ReturnMBB.pred_empty())
2206 ReturnMBB.eraseFromParent();
2213 bool runOnMachineFunction(MachineFunction &MF) override {
2214 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2215 TII = TM->getInstrInfo();
2217 bool Changed = false;
2219 // If the function does not have at least two blocks, then there is
2224 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2225 MachineBasicBlock &B = *I++;
2226 if (processBlock(B))
2233 void getAnalysisUsage(AnalysisUsage &AU) const override {
2234 MachineFunctionPass::getAnalysisUsage(AU);
2239 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2240 "PowerPC Early-Return Creation", false, false)
2242 char PPCEarlyReturn::ID = 0;
2244 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }