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/SlotIndexes.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
40 #define DEBUG_TYPE "ppc-instr-info"
42 #define GET_INSTRMAP_INFO
43 #define GET_INSTRINFO_CTOR_DTOR
44 #include "PPCGenInstrInfo.inc"
47 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
48 cl::desc("Disable analysis for CTR loops"));
50 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
51 cl::desc("Disable compare instruction optimization"), cl::Hidden);
53 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
54 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
56 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
57 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
60 // Pin the vtable to this file.
61 void PPCInstrInfo::anchor() {}
63 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
64 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
65 TM(tm), RI(*TM.getSubtargetImpl()) {}
67 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
68 /// this target when scheduling the DAG.
69 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
70 const TargetMachine *TM,
71 const ScheduleDAG *DAG) const {
72 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
73 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
74 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
75 const InstrItineraryData *II = TM->getInstrItineraryData();
76 return new ScoreboardHazardRecognizer(II, DAG);
79 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
82 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
83 /// to use for this target when scheduling the DAG.
84 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
85 const InstrItineraryData *II,
86 const ScheduleDAG *DAG) const {
87 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
89 if (Directive == PPC::DIR_PWR7)
90 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
92 // Most subtargets use a PPC970 recognizer.
93 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
94 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
95 assert(TM.getInstrInfo() && "No InstrInfo?");
97 return new PPCHazardRecognizer970(TM);
100 return new ScoreboardHazardRecognizer(II, DAG);
104 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
105 const MachineInstr *DefMI, unsigned DefIdx,
106 const MachineInstr *UseMI,
107 unsigned UseIdx) const {
108 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
111 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
112 unsigned Reg = DefMO.getReg();
114 const TargetRegisterInfo *TRI = &getRegisterInfo();
116 if (TRI->isVirtualRegister(Reg)) {
117 const MachineRegisterInfo *MRI =
118 &DefMI->getParent()->getParent()->getRegInfo();
119 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
120 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
122 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
123 PPC::CRBITRCRegClass.contains(Reg);
126 if (UseMI->isBranch() && IsRegCR) {
128 Latency = getInstrLatency(ItinData, DefMI);
130 // On some cores, there is an additional delay between writing to a condition
131 // register, and using it from a branch.
132 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
153 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
154 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
155 unsigned &SrcReg, unsigned &DstReg,
156 unsigned &SubIdx) const {
157 switch (MI.getOpcode()) {
158 default: return false;
160 case PPC::EXTSW_32_64:
161 SrcReg = MI.getOperand(1).getReg();
162 DstReg = MI.getOperand(0).getReg();
163 SubIdx = PPC::sub_32;
168 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
169 int &FrameIndex) const {
170 // Note: This list must be kept consistent with LoadRegFromStackSlot.
171 switch (MI->getOpcode()) {
177 case PPC::RESTORE_CR:
178 case PPC::RESTORE_CRBIT:
181 case PPC::RESTORE_VRSAVE:
182 // Check for the operands added by addFrameReference (the immediate is the
183 // offset which defaults to 0).
184 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
185 MI->getOperand(2).isFI()) {
186 FrameIndex = MI->getOperand(2).getIndex();
187 return MI->getOperand(0).getReg();
194 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
195 int &FrameIndex) const {
196 // Note: This list must be kept consistent with StoreRegToStackSlot.
197 switch (MI->getOpcode()) {
204 case PPC::SPILL_CRBIT:
207 case PPC::SPILL_VRSAVE:
208 // Check for the operands added by addFrameReference (the immediate is the
209 // offset which defaults to 0).
210 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
211 MI->getOperand(2).isFI()) {
212 FrameIndex = MI->getOperand(2).getIndex();
213 return MI->getOperand(0).getReg();
220 // commuteInstruction - We can commute rlwimi instructions, but only if the
221 // rotate amt is zero. We also have to munge the immediates a bit.
223 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
224 MachineFunction &MF = *MI->getParent()->getParent();
226 // Normal instructions can be commuted the obvious way.
227 if (MI->getOpcode() != PPC::RLWIMI &&
228 MI->getOpcode() != PPC::RLWIMIo &&
229 MI->getOpcode() != PPC::RLWIMI8 &&
230 MI->getOpcode() != PPC::RLWIMI8o)
231 return TargetInstrInfo::commuteInstruction(MI, NewMI);
233 // Cannot commute if it has a non-zero rotate count.
234 if (MI->getOperand(3).getImm() != 0)
237 // If we have a zero rotate count, we have:
239 // Op0 = (Op1 & ~M) | (Op2 & M)
241 // M = mask((ME+1)&31, (MB-1)&31)
242 // Op0 = (Op2 & ~M) | (Op1 & M)
245 unsigned Reg0 = MI->getOperand(0).getReg();
246 unsigned Reg1 = MI->getOperand(1).getReg();
247 unsigned Reg2 = MI->getOperand(2).getReg();
248 unsigned SubReg1 = MI->getOperand(1).getSubReg();
249 unsigned SubReg2 = MI->getOperand(2).getSubReg();
250 bool Reg1IsKill = MI->getOperand(1).isKill();
251 bool Reg2IsKill = MI->getOperand(2).isKill();
252 bool ChangeReg0 = false;
253 // If machine instrs are no longer in two-address forms, update
254 // destination register as well.
256 // Must be two address instruction!
257 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
258 "Expecting a two-address instruction!");
259 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
265 unsigned MB = MI->getOperand(4).getImm();
266 unsigned ME = MI->getOperand(5).getImm();
269 // Create a new instruction.
270 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
271 bool Reg0IsDead = MI->getOperand(0).isDead();
272 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
273 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
274 .addReg(Reg2, getKillRegState(Reg2IsKill))
275 .addReg(Reg1, getKillRegState(Reg1IsKill))
277 .addImm((MB-1) & 31);
281 MI->getOperand(0).setReg(Reg2);
282 MI->getOperand(0).setSubReg(SubReg2);
284 MI->getOperand(2).setReg(Reg1);
285 MI->getOperand(1).setReg(Reg2);
286 MI->getOperand(2).setSubReg(SubReg1);
287 MI->getOperand(1).setSubReg(SubReg2);
288 MI->getOperand(2).setIsKill(Reg1IsKill);
289 MI->getOperand(1).setIsKill(Reg2IsKill);
291 // Swap the mask around.
292 MI->getOperand(4).setImm((ME+1) & 31);
293 MI->getOperand(5).setImm((MB-1) & 31);
297 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
298 unsigned &SrcOpIdx2) const {
299 // For VSX A-Type FMA instructions, it is the first two operands that can be
300 // commuted, however, because the non-encoded tied input operand is listed
301 // first, the operands to swap are actually the second and third.
303 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
305 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
312 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
313 MachineBasicBlock::iterator MI) const {
314 // This function is used for scheduling, and the nop wanted here is the type
315 // that terminates dispatch groups on the POWER cores.
316 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
319 default: Opcode = PPC::NOP; break;
320 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
321 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
325 BuildMI(MBB, MI, DL, get(Opcode));
329 // Note: If the condition register is set to CTR or CTR8 then this is a
330 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
331 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
332 MachineBasicBlock *&FBB,
333 SmallVectorImpl<MachineOperand> &Cond,
334 bool AllowModify) const {
335 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
337 // If the block has no terminators, it just falls into the block after it.
338 MachineBasicBlock::iterator I = MBB.end();
339 if (I == MBB.begin())
342 while (I->isDebugValue()) {
343 if (I == MBB.begin())
347 if (!isUnpredicatedTerminator(I))
350 // Get the last instruction in the block.
351 MachineInstr *LastInst = I;
353 // If there is only one terminator instruction, process it.
354 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
355 if (LastInst->getOpcode() == PPC::B) {
356 if (!LastInst->getOperand(0).isMBB())
358 TBB = LastInst->getOperand(0).getMBB();
360 } else if (LastInst->getOpcode() == PPC::BCC) {
361 if (!LastInst->getOperand(2).isMBB())
363 // Block ends with fall-through condbranch.
364 TBB = LastInst->getOperand(2).getMBB();
365 Cond.push_back(LastInst->getOperand(0));
366 Cond.push_back(LastInst->getOperand(1));
368 } else if (LastInst->getOpcode() == PPC::BC) {
369 if (!LastInst->getOperand(1).isMBB())
371 // Block ends with fall-through condbranch.
372 TBB = LastInst->getOperand(1).getMBB();
373 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
374 Cond.push_back(LastInst->getOperand(0));
376 } else if (LastInst->getOpcode() == PPC::BCn) {
377 if (!LastInst->getOperand(1).isMBB())
379 // Block ends with fall-through condbranch.
380 TBB = LastInst->getOperand(1).getMBB();
381 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
382 Cond.push_back(LastInst->getOperand(0));
384 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
385 LastInst->getOpcode() == PPC::BDNZ) {
386 if (!LastInst->getOperand(0).isMBB())
388 if (DisableCTRLoopAnal)
390 TBB = LastInst->getOperand(0).getMBB();
391 Cond.push_back(MachineOperand::CreateImm(1));
392 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
395 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
396 LastInst->getOpcode() == PPC::BDZ) {
397 if (!LastInst->getOperand(0).isMBB())
399 if (DisableCTRLoopAnal)
401 TBB = LastInst->getOperand(0).getMBB();
402 Cond.push_back(MachineOperand::CreateImm(0));
403 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
408 // Otherwise, don't know what this is.
412 // Get the instruction before it if it's a terminator.
413 MachineInstr *SecondLastInst = I;
415 // If there are three terminators, we don't know what sort of block this is.
416 if (SecondLastInst && I != MBB.begin() &&
417 isUnpredicatedTerminator(--I))
420 // If the block ends with PPC::B and PPC:BCC, handle it.
421 if (SecondLastInst->getOpcode() == PPC::BCC &&
422 LastInst->getOpcode() == PPC::B) {
423 if (!SecondLastInst->getOperand(2).isMBB() ||
424 !LastInst->getOperand(0).isMBB())
426 TBB = SecondLastInst->getOperand(2).getMBB();
427 Cond.push_back(SecondLastInst->getOperand(0));
428 Cond.push_back(SecondLastInst->getOperand(1));
429 FBB = LastInst->getOperand(0).getMBB();
431 } else if (SecondLastInst->getOpcode() == PPC::BC &&
432 LastInst->getOpcode() == PPC::B) {
433 if (!SecondLastInst->getOperand(1).isMBB() ||
434 !LastInst->getOperand(0).isMBB())
436 TBB = SecondLastInst->getOperand(1).getMBB();
437 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
438 Cond.push_back(SecondLastInst->getOperand(0));
439 FBB = LastInst->getOperand(0).getMBB();
441 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
442 LastInst->getOpcode() == PPC::B) {
443 if (!SecondLastInst->getOperand(1).isMBB() ||
444 !LastInst->getOperand(0).isMBB())
446 TBB = SecondLastInst->getOperand(1).getMBB();
447 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
448 Cond.push_back(SecondLastInst->getOperand(0));
449 FBB = LastInst->getOperand(0).getMBB();
451 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
452 SecondLastInst->getOpcode() == PPC::BDNZ) &&
453 LastInst->getOpcode() == PPC::B) {
454 if (!SecondLastInst->getOperand(0).isMBB() ||
455 !LastInst->getOperand(0).isMBB())
457 if (DisableCTRLoopAnal)
459 TBB = SecondLastInst->getOperand(0).getMBB();
460 Cond.push_back(MachineOperand::CreateImm(1));
461 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
463 FBB = LastInst->getOperand(0).getMBB();
465 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
466 SecondLastInst->getOpcode() == PPC::BDZ) &&
467 LastInst->getOpcode() == PPC::B) {
468 if (!SecondLastInst->getOperand(0).isMBB() ||
469 !LastInst->getOperand(0).isMBB())
471 if (DisableCTRLoopAnal)
473 TBB = SecondLastInst->getOperand(0).getMBB();
474 Cond.push_back(MachineOperand::CreateImm(0));
475 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
477 FBB = LastInst->getOperand(0).getMBB();
481 // If the block ends with two PPC:Bs, handle it. The second one is not
482 // executed, so remove it.
483 if (SecondLastInst->getOpcode() == PPC::B &&
484 LastInst->getOpcode() == PPC::B) {
485 if (!SecondLastInst->getOperand(0).isMBB())
487 TBB = SecondLastInst->getOperand(0).getMBB();
490 I->eraseFromParent();
494 // Otherwise, can't handle this.
498 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
499 MachineBasicBlock::iterator I = MBB.end();
500 if (I == MBB.begin()) return 0;
502 while (I->isDebugValue()) {
503 if (I == MBB.begin())
507 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
508 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
509 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
510 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
513 // Remove the branch.
514 I->eraseFromParent();
518 if (I == MBB.begin()) return 1;
520 if (I->getOpcode() != PPC::BCC &&
521 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
522 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
523 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
526 // Remove the branch.
527 I->eraseFromParent();
532 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
533 MachineBasicBlock *FBB,
534 const SmallVectorImpl<MachineOperand> &Cond,
536 // Shouldn't be a fall through.
537 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
538 assert((Cond.size() == 2 || Cond.size() == 0) &&
539 "PPC branch conditions have two components!");
541 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
545 if (Cond.empty()) // Unconditional branch
546 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
547 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
548 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
549 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
550 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
551 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
552 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
553 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
554 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
555 else // Conditional branch
556 BuildMI(&MBB, DL, get(PPC::BCC))
557 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
561 // Two-way Conditional Branch.
562 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
563 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
564 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
565 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
566 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
567 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
568 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
569 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
571 BuildMI(&MBB, DL, get(PPC::BCC))
572 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
573 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
578 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
579 const SmallVectorImpl<MachineOperand> &Cond,
580 unsigned TrueReg, unsigned FalseReg,
581 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
582 if (!TM.getSubtargetImpl()->hasISEL())
585 if (Cond.size() != 2)
588 // If this is really a bdnz-like condition, then it cannot be turned into a
590 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
593 // Check register classes.
594 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
595 const TargetRegisterClass *RC =
596 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
600 // isel is for regular integer GPRs only.
601 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
602 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
603 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
604 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
607 // FIXME: These numbers are for the A2, how well they work for other cores is
608 // an open question. On the A2, the isel instruction has a 2-cycle latency
609 // but single-cycle throughput. These numbers are used in combination with
610 // the MispredictPenalty setting from the active SchedMachineModel.
618 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
619 MachineBasicBlock::iterator MI, DebugLoc dl,
621 const SmallVectorImpl<MachineOperand> &Cond,
622 unsigned TrueReg, unsigned FalseReg) const {
623 assert(Cond.size() == 2 &&
624 "PPC branch conditions have two components!");
626 assert(TM.getSubtargetImpl()->hasISEL() &&
627 "Cannot insert select on target without ISEL support");
629 // Get the register classes.
630 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
631 const TargetRegisterClass *RC =
632 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
633 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
635 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
636 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
638 PPC::GPRCRegClass.hasSubClassEq(RC) ||
639 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
640 "isel is for regular integer GPRs only");
642 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
643 unsigned SelectPred = Cond[0].getImm();
647 switch (SelectPred) {
648 default: llvm_unreachable("invalid predicate for isel");
649 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
650 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
651 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
652 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
653 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
654 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
655 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
656 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
657 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
658 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
661 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
662 SecondReg = SwapOps ? TrueReg : FalseReg;
664 // The first input register of isel cannot be r0. If it is a member
665 // of a register class that can be r0, then copy it first (the
666 // register allocator should eliminate the copy).
667 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
668 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
669 const TargetRegisterClass *FirstRC =
670 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
671 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
672 unsigned OldFirstReg = FirstReg;
673 FirstReg = MRI.createVirtualRegister(FirstRC);
674 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
675 .addReg(OldFirstReg);
678 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
679 .addReg(FirstReg).addReg(SecondReg)
680 .addReg(Cond[1].getReg(), 0, SubIdx);
683 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
684 MachineBasicBlock::iterator I, DebugLoc DL,
685 unsigned DestReg, unsigned SrcReg,
686 bool KillSrc) const {
687 // We can end up with self copies and similar things as a result of VSX copy
688 // legalization. Promote them here.
689 const TargetRegisterInfo *TRI = &getRegisterInfo();
690 if (PPC::F8RCRegClass.contains(DestReg) &&
691 PPC::VSLRCRegClass.contains(SrcReg)) {
693 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
695 if (VSXSelfCopyCrash && SrcReg == SuperReg)
696 llvm_unreachable("nop VSX copy");
699 } else if (PPC::VRRCRegClass.contains(DestReg) &&
700 PPC::VSHRCRegClass.contains(SrcReg)) {
702 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
704 if (VSXSelfCopyCrash && SrcReg == SuperReg)
705 llvm_unreachable("nop VSX copy");
708 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
709 PPC::VSLRCRegClass.contains(DestReg)) {
711 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
713 if (VSXSelfCopyCrash && DestReg == SuperReg)
714 llvm_unreachable("nop VSX copy");
717 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
718 PPC::VSHRCRegClass.contains(DestReg)) {
720 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
722 if (VSXSelfCopyCrash && DestReg == SuperReg)
723 llvm_unreachable("nop VSX copy");
729 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
731 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
733 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
735 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
737 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
739 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
740 // There are two different ways this can be done:
741 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
742 // issue in VSU pipeline 0.
743 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
744 // can go to either pipeline.
745 // We'll always use xxlor here, because in practically all cases where
746 // copies are generated, they are close enough to some use that the
747 // lower-latency form is preferable.
749 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
751 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
754 llvm_unreachable("Impossible reg-to-reg copy");
756 const MCInstrDesc &MCID = get(Opc);
757 if (MCID.getNumOperands() == 3)
758 BuildMI(MBB, I, DL, MCID, DestReg)
759 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
761 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
764 // This function returns true if a CR spill is necessary and false otherwise.
766 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
767 unsigned SrcReg, bool isKill,
769 const TargetRegisterClass *RC,
770 SmallVectorImpl<MachineInstr*> &NewMIs,
771 bool &NonRI, bool &SpillsVRS) const{
772 // Note: If additional store instructions are added here,
773 // update isStoreToStackSlot.
776 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
777 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
778 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
780 getKillRegState(isKill)),
782 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
783 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
784 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
786 getKillRegState(isKill)),
788 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
789 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
791 getKillRegState(isKill)),
793 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
794 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
796 getKillRegState(isKill)),
798 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
799 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
801 getKillRegState(isKill)),
804 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
805 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
807 getKillRegState(isKill)),
810 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
811 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
813 getKillRegState(isKill)),
816 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
817 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
819 getKillRegState(isKill)),
822 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
823 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
825 getKillRegState(isKill)),
828 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
829 assert(TM.getSubtargetImpl()->isDarwin() &&
830 "VRSAVE only needs spill/restore on Darwin");
831 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
833 getKillRegState(isKill)),
837 llvm_unreachable("Unknown regclass!");
844 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
845 MachineBasicBlock::iterator MI,
846 unsigned SrcReg, bool isKill, int FrameIdx,
847 const TargetRegisterClass *RC,
848 const TargetRegisterInfo *TRI) const {
849 MachineFunction &MF = *MBB.getParent();
850 SmallVector<MachineInstr*, 4> NewMIs;
852 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
853 FuncInfo->setHasSpills();
855 bool NonRI = false, SpillsVRS = false;
856 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
858 FuncInfo->setSpillsCR();
861 FuncInfo->setSpillsVRSAVE();
864 FuncInfo->setHasNonRISpills();
866 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
867 MBB.insert(MI, NewMIs[i]);
869 const MachineFrameInfo &MFI = *MF.getFrameInfo();
870 MachineMemOperand *MMO =
871 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
872 MachineMemOperand::MOStore,
873 MFI.getObjectSize(FrameIdx),
874 MFI.getObjectAlignment(FrameIdx));
875 NewMIs.back()->addMemOperand(MF, MMO);
879 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
880 unsigned DestReg, int FrameIdx,
881 const TargetRegisterClass *RC,
882 SmallVectorImpl<MachineInstr*> &NewMIs,
883 bool &NonRI, bool &SpillsVRS) const{
884 // Note: If additional load instructions are added here,
885 // update isLoadFromStackSlot.
887 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
888 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
889 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
890 DestReg), FrameIdx));
891 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
892 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
893 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
895 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
896 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
898 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
899 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
901 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
902 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
903 get(PPC::RESTORE_CR), DestReg),
906 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
907 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
908 get(PPC::RESTORE_CRBIT), DestReg),
911 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
912 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
915 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
916 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
919 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
920 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
923 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
924 assert(TM.getSubtargetImpl()->isDarwin() &&
925 "VRSAVE only needs spill/restore on Darwin");
926 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
927 get(PPC::RESTORE_VRSAVE),
932 llvm_unreachable("Unknown regclass!");
939 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
940 MachineBasicBlock::iterator MI,
941 unsigned DestReg, int FrameIdx,
942 const TargetRegisterClass *RC,
943 const TargetRegisterInfo *TRI) const {
944 MachineFunction &MF = *MBB.getParent();
945 SmallVector<MachineInstr*, 4> NewMIs;
947 if (MI != MBB.end()) DL = MI->getDebugLoc();
949 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
950 FuncInfo->setHasSpills();
952 bool NonRI = false, SpillsVRS = false;
953 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
955 FuncInfo->setSpillsCR();
958 FuncInfo->setSpillsVRSAVE();
961 FuncInfo->setHasNonRISpills();
963 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
964 MBB.insert(MI, NewMIs[i]);
966 const MachineFrameInfo &MFI = *MF.getFrameInfo();
967 MachineMemOperand *MMO =
968 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
969 MachineMemOperand::MOLoad,
970 MFI.getObjectSize(FrameIdx),
971 MFI.getObjectAlignment(FrameIdx));
972 NewMIs.back()->addMemOperand(MF, MMO);
976 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
977 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
978 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
979 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
981 // Leave the CR# the same, but invert the condition.
982 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
986 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
987 unsigned Reg, MachineRegisterInfo *MRI) const {
988 // For some instructions, it is legal to fold ZERO into the RA register field.
989 // A zero immediate should always be loaded with a single li.
990 unsigned DefOpc = DefMI->getOpcode();
991 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
993 if (!DefMI->getOperand(1).isImm())
995 if (DefMI->getOperand(1).getImm() != 0)
998 // Note that we cannot here invert the arguments of an isel in order to fold
999 // a ZERO into what is presented as the second argument. All we have here
1000 // is the condition bit, and that might come from a CR-logical bit operation.
1002 const MCInstrDesc &UseMCID = UseMI->getDesc();
1004 // Only fold into real machine instructions.
1005 if (UseMCID.isPseudo())
1009 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1010 if (UseMI->getOperand(UseIdx).isReg() &&
1011 UseMI->getOperand(UseIdx).getReg() == Reg)
1014 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1015 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1017 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1019 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1020 // register (which might also be specified as a pointer class kind).
1021 if (UseInfo->isLookupPtrRegClass()) {
1022 if (UseInfo->RegClass /* Kind */ != 1)
1025 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1026 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1030 // Make sure this is not tied to an output register (or otherwise
1031 // constrained). This is true for ST?UX registers, for example, which
1032 // are tied to their output registers.
1033 if (UseInfo->Constraints != 0)
1037 if (UseInfo->isLookupPtrRegClass()) {
1038 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1039 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1041 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1042 PPC::ZERO8 : PPC::ZERO;
1045 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1046 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1049 DefMI->eraseFromParent();
1054 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1055 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1057 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1062 // We should make sure that, if we're going to predicate both sides of a
1063 // condition (a diamond), that both sides don't define the counter register. We
1064 // can predicate counter-decrement-based branches, but while that predicates
1065 // the branching, it does not predicate the counter decrement. If we tried to
1066 // merge the triangle into one predicated block, we'd decrement the counter
1068 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1069 unsigned NumT, unsigned ExtraT,
1070 MachineBasicBlock &FMBB,
1071 unsigned NumF, unsigned ExtraF,
1072 const BranchProbability &Probability) const {
1073 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1077 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1078 // The predicated branches are identified by their type, not really by the
1079 // explicit presence of a predicate. Furthermore, some of them can be
1080 // predicated more than once. Because if conversion won't try to predicate
1081 // any instruction which already claims to be predicated (by returning true
1082 // here), always return false. In doing so, we let isPredicable() be the
1083 // final word on whether not the instruction can be (further) predicated.
1088 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1089 if (!MI->isTerminator())
1092 // Conditional branch is a special case.
1093 if (MI->isBranch() && !MI->isBarrier())
1096 return !isPredicated(MI);
1099 bool PPCInstrInfo::PredicateInstruction(
1101 const SmallVectorImpl<MachineOperand> &Pred) const {
1102 unsigned OpC = MI->getOpcode();
1103 if (OpC == PPC::BLR) {
1104 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1105 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1106 MI->setDesc(get(Pred[0].getImm() ?
1107 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1108 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1109 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1110 MI->setDesc(get(PPC::BCLR));
1111 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1112 .addReg(Pred[1].getReg());
1113 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1114 MI->setDesc(get(PPC::BCLRn));
1115 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1116 .addReg(Pred[1].getReg());
1118 MI->setDesc(get(PPC::BCCLR));
1119 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1120 .addImm(Pred[0].getImm())
1121 .addReg(Pred[1].getReg());
1125 } else if (OpC == PPC::B) {
1126 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1127 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1128 MI->setDesc(get(Pred[0].getImm() ?
1129 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1130 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1131 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1132 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1133 MI->RemoveOperand(0);
1135 MI->setDesc(get(PPC::BC));
1136 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1137 .addReg(Pred[1].getReg())
1139 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1140 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1141 MI->RemoveOperand(0);
1143 MI->setDesc(get(PPC::BCn));
1144 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1145 .addReg(Pred[1].getReg())
1148 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1149 MI->RemoveOperand(0);
1151 MI->setDesc(get(PPC::BCC));
1152 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1153 .addImm(Pred[0].getImm())
1154 .addReg(Pred[1].getReg())
1159 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1160 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1161 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1162 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1164 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1165 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1167 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1168 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1169 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1170 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1171 .addReg(Pred[1].getReg());
1173 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1174 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1175 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1176 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1177 .addReg(Pred[1].getReg());
1181 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1182 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1183 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1184 .addImm(Pred[0].getImm())
1185 .addReg(Pred[1].getReg());
1192 bool PPCInstrInfo::SubsumesPredicate(
1193 const SmallVectorImpl<MachineOperand> &Pred1,
1194 const SmallVectorImpl<MachineOperand> &Pred2) const {
1195 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1196 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1198 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1200 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1203 // P1 can only subsume P2 if they test the same condition register.
1204 if (Pred1[1].getReg() != Pred2[1].getReg())
1207 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1208 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1213 // Does P1 subsume P2, e.g. GE subsumes GT.
1214 if (P1 == PPC::PRED_LE &&
1215 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1217 if (P1 == PPC::PRED_GE &&
1218 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1224 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1225 std::vector<MachineOperand> &Pred) const {
1226 // Note: At the present time, the contents of Pred from this function is
1227 // unused by IfConversion. This implementation follows ARM by pushing the
1228 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1229 // predicate, instructions defining CTR or CTR8 are also included as
1230 // predicate-defining instructions.
1232 const TargetRegisterClass *RCs[] =
1233 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1234 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1237 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1238 const MachineOperand &MO = MI->getOperand(i);
1239 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1240 const TargetRegisterClass *RC = RCs[c];
1242 if (MO.isDef() && RC->contains(MO.getReg())) {
1246 } else if (MO.isRegMask()) {
1247 for (TargetRegisterClass::iterator I = RC->begin(),
1248 IE = RC->end(); I != IE; ++I)
1249 if (MO.clobbersPhysReg(*I)) {
1260 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1261 unsigned OpC = MI->getOpcode();
1275 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1276 unsigned &SrcReg, unsigned &SrcReg2,
1277 int &Mask, int &Value) const {
1278 unsigned Opc = MI->getOpcode();
1281 default: return false;
1286 SrcReg = MI->getOperand(1).getReg();
1288 Value = MI->getOperand(2).getImm();
1297 SrcReg = MI->getOperand(1).getReg();
1298 SrcReg2 = MI->getOperand(2).getReg();
1303 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1304 unsigned SrcReg, unsigned SrcReg2,
1305 int Mask, int Value,
1306 const MachineRegisterInfo *MRI) const {
1310 int OpC = CmpInstr->getOpcode();
1311 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1313 // FP record forms set CR1 based on the execption status bits, not a
1314 // comparison with zero.
1315 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1318 // The record forms set the condition register based on a signed comparison
1319 // with zero (so says the ISA manual). This is not as straightforward as it
1320 // seems, however, because this is always a 64-bit comparison on PPC64, even
1321 // for instructions that are 32-bit in nature (like slw for example).
1322 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1323 // for equality checks (as those don't depend on the sign). On PPC64,
1324 // we are restricted to equality for unsigned 64-bit comparisons and for
1325 // signed 32-bit comparisons the applicability is more restricted.
1326 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1327 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1328 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1329 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1331 // Get the unique definition of SrcReg.
1332 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1333 if (!MI) return false;
1334 int MIOpC = MI->getOpcode();
1336 bool equalityOnly = false;
1339 if (is32BitSignedCompare) {
1340 // We can perform this optimization only if MI is sign-extending.
1341 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1342 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1343 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1344 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1345 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1349 } else if (is32BitUnsignedCompare) {
1350 // We can perform this optimization, equality only, if MI is
1352 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1353 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1354 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1356 equalityOnly = true;
1360 equalityOnly = is64BitUnsignedCompare;
1362 equalityOnly = is32BitUnsignedCompare;
1365 // We need to check the uses of the condition register in order to reject
1366 // non-equality comparisons.
1367 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1368 IE = MRI->use_instr_end(); I != IE; ++I) {
1369 MachineInstr *UseMI = &*I;
1370 if (UseMI->getOpcode() == PPC::BCC) {
1371 unsigned Pred = UseMI->getOperand(0).getImm();
1372 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1374 } else if (UseMI->getOpcode() == PPC::ISEL ||
1375 UseMI->getOpcode() == PPC::ISEL8) {
1376 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1377 if (SubIdx != PPC::sub_eq)
1384 MachineBasicBlock::iterator I = CmpInstr;
1386 // Scan forward to find the first use of the compare.
1387 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1389 bool FoundUse = false;
1390 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1391 JE = MRI->use_instr_end(); J != JE; ++J)
1401 // There are two possible candidates which can be changed to set CR[01].
1402 // One is MI, the other is a SUB instruction.
1403 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1404 MachineInstr *Sub = nullptr;
1406 // MI is not a candidate for CMPrr.
1408 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1409 // same BB as the comparison. This is to allow the check below to avoid calls
1410 // (and other explicit clobbers); instead we should really check for these
1411 // more explicitly (in at least a few predecessors).
1412 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1413 // PPC does not have a record-form SUBri.
1418 const TargetRegisterInfo *TRI = &getRegisterInfo();
1421 // Get ready to iterate backward from CmpInstr.
1422 MachineBasicBlock::iterator E = MI,
1423 B = CmpInstr->getParent()->begin();
1425 for (; I != E && !noSub; --I) {
1426 const MachineInstr &Instr = *I;
1427 unsigned IOpC = Instr.getOpcode();
1429 if (&*I != CmpInstr && (
1430 Instr.modifiesRegister(PPC::CR0, TRI) ||
1431 Instr.readsRegister(PPC::CR0, TRI)))
1432 // This instruction modifies or uses the record condition register after
1433 // the one we want to change. While we could do this transformation, it
1434 // would likely not be profitable. This transformation removes one
1435 // instruction, and so even forcing RA to generate one move probably
1436 // makes it unprofitable.
1439 // Check whether CmpInstr can be made redundant by the current instruction.
1440 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1441 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1442 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1443 ((Instr.getOperand(1).getReg() == SrcReg &&
1444 Instr.getOperand(2).getReg() == SrcReg2) ||
1445 (Instr.getOperand(1).getReg() == SrcReg2 &&
1446 Instr.getOperand(2).getReg() == SrcReg))) {
1452 // The 'and' is below the comparison instruction.
1456 // Return false if no candidates exist.
1460 // The single candidate is called MI.
1464 MIOpC = MI->getOpcode();
1465 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1468 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1469 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1473 // FIXME: On the non-embedded POWER architectures, only some of the record
1474 // forms are fast, and we should use only the fast ones.
1476 // The defining instruction has a record form (or is already a record
1477 // form). It is possible, however, that we'll need to reverse the condition
1478 // code of the users.
1482 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1483 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1485 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1486 // needs to be updated to be based on SUB. Push the condition code
1487 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1488 // condition code of these operands will be modified.
1489 bool ShouldSwap = false;
1491 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1492 Sub->getOperand(2).getReg() == SrcReg;
1494 // The operands to subf are the opposite of sub, so only in the fixed-point
1495 // case, invert the order.
1496 ShouldSwap = !ShouldSwap;
1500 for (MachineRegisterInfo::use_instr_iterator
1501 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1503 MachineInstr *UseMI = &*I;
1504 if (UseMI->getOpcode() == PPC::BCC) {
1505 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1506 assert((!equalityOnly ||
1507 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1508 "Invalid predicate for equality-only optimization");
1509 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1510 PPC::getSwappedPredicate(Pred)));
1511 } else if (UseMI->getOpcode() == PPC::ISEL ||
1512 UseMI->getOpcode() == PPC::ISEL8) {
1513 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1514 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1515 "Invalid CR bit for equality-only optimization");
1517 if (NewSubReg == PPC::sub_lt)
1518 NewSubReg = PPC::sub_gt;
1519 else if (NewSubReg == PPC::sub_gt)
1520 NewSubReg = PPC::sub_lt;
1522 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1524 } else // We need to abort on a user we don't understand.
1528 // Create a new virtual register to hold the value of the CR set by the
1529 // record-form instruction. If the instruction was not previously in
1530 // record form, then set the kill flag on the CR.
1531 CmpInstr->eraseFromParent();
1533 MachineBasicBlock::iterator MII = MI;
1534 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1535 get(TargetOpcode::COPY), CRReg)
1536 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1538 if (MIOpC != NewOpC) {
1539 // We need to be careful here: we're replacing one instruction with
1540 // another, and we need to make sure that we get all of the right
1541 // implicit uses and defs. On the other hand, the caller may be holding
1542 // an iterator to this instruction, and so we can't delete it (this is
1543 // specifically the case if this is the instruction directly after the
1546 const MCInstrDesc &NewDesc = get(NewOpC);
1547 MI->setDesc(NewDesc);
1549 if (NewDesc.ImplicitDefs)
1550 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1551 *ImpDefs; ++ImpDefs)
1552 if (!MI->definesRegister(*ImpDefs))
1553 MI->addOperand(*MI->getParent()->getParent(),
1554 MachineOperand::CreateReg(*ImpDefs, true, true));
1555 if (NewDesc.ImplicitUses)
1556 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1557 *ImpUses; ++ImpUses)
1558 if (!MI->readsRegister(*ImpUses))
1559 MI->addOperand(*MI->getParent()->getParent(),
1560 MachineOperand::CreateReg(*ImpUses, false, true));
1563 // Modify the condition code of operands in OperandsToUpdate.
1564 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1565 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1566 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1567 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1569 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1570 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1575 /// GetInstSize - Return the number of bytes of code the specified
1576 /// instruction may be. This returns the maximum number of bytes.
1578 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1579 unsigned Opcode = MI->getOpcode();
1581 if (Opcode == PPC::INLINEASM) {
1582 const MachineFunction *MF = MI->getParent()->getParent();
1583 const char *AsmStr = MI->getOperand(0).getSymbolName();
1584 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1586 const MCInstrDesc &Desc = get(Opcode);
1587 return Desc.getSize();
1592 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1595 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1596 // (Altivec and scalar floating-point registers), we need to transform the
1597 // copies into subregister copies with other restrictions.
1598 struct PPCVSXFMAMutate : public MachineFunctionPass {
1600 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1601 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1606 const PPCTargetMachine *TM;
1607 const PPCInstrInfo *TII;
1610 bool processBlock(MachineBasicBlock &MBB) {
1611 bool Changed = false;
1613 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1614 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1616 MachineInstr *MI = I;
1618 // The default (A-type) VSX FMA form kills the addend (it is taken from
1619 // the target register, which is then updated to reflect the result of
1620 // the FMA). If the instruction, however, kills one of the registers
1621 // used for the product, then we can use the M-form instruction (which
1622 // will take that value from the to-be-defined register).
1624 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1628 // This pass is run after register coalescing, and so we're looking for
1629 // a situation like this:
1631 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1632 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1633 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1635 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1636 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1638 // Where we can eliminate the copy by changing from the A-type to the
1639 // M-type instruction. Specifically, for this example, this means:
1640 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1641 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1643 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1644 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1645 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1647 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1649 VNInfo *AddendValNo =
1650 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1651 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1653 // The addend and this instruction must be in the same block.
1655 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1658 // The addend must be a full copy within the same register class.
1660 if (!AddendMI->isFullCopy())
1663 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1664 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1665 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1666 MRI.getRegClass(AddendSrcReg))
1669 // If AddendSrcReg is a physical register, make sure the destination
1670 // register class contains it.
1671 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1672 ->contains(AddendSrcReg))
1676 // In theory, there could be other uses of the addend copy before this
1677 // fma. We could deal with this, but that would require additional
1678 // logic below and I suspect it will not occur in any relevant
1680 bool OtherUsers = false;
1681 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1683 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1691 // Find one of the product operands that is killed by this instruction.
1693 unsigned KilledProdOp = 0, OtherProdOp = 0;
1694 if (LIS->getInterval(MI->getOperand(2).getReg())
1695 .Query(FMAIdx).isKill()) {
1698 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1699 .Query(FMAIdx).isKill()) {
1704 // If there are no killed product operands, then this transformation is
1705 // likely not profitable.
1709 // In order to replace the addend here with the source of the copy,
1710 // it must still be live here.
1711 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1714 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1716 unsigned AddReg = AddendMI->getOperand(1).getReg();
1717 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1718 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1720 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1721 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1722 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1724 bool AddRegKill = AddendMI->getOperand(1).isKill();
1725 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1726 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1728 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1729 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1730 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1732 unsigned OldFMAReg = MI->getOperand(0).getReg();
1734 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1735 "Addend copy not tied to old FMA output!");
1737 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1739 MI->getOperand(0).setReg(KilledProdReg);
1740 MI->getOperand(1).setReg(KilledProdReg);
1741 MI->getOperand(3).setReg(AddReg);
1742 MI->getOperand(2).setReg(OtherProdReg);
1744 MI->getOperand(0).setSubReg(KilledProdSubReg);
1745 MI->getOperand(1).setSubReg(KilledProdSubReg);
1746 MI->getOperand(3).setSubReg(AddSubReg);
1747 MI->getOperand(2).setSubReg(OtherProdSubReg);
1749 MI->getOperand(1).setIsKill(KilledProdRegKill);
1750 MI->getOperand(3).setIsKill(AddRegKill);
1751 MI->getOperand(2).setIsKill(OtherProdRegKill);
1753 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1754 MI->getOperand(3).setIsUndef(AddRegUndef);
1755 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1757 MI->setDesc(TII->get(AltOpc));
1759 DEBUG(dbgs() << " -> " << *MI);
1761 // The killed product operand was killed here, so we can reuse it now
1762 // for the result of the fma.
1764 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1765 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1766 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1768 MachineOperand &UseMO = *UI;
1769 MachineInstr *UseMI = UseMO.getParent();
1772 // Don't replace the result register of the copy we're about to erase.
1773 if (UseMI == AddendMI)
1776 UseMO.setReg(KilledProdReg);
1777 UseMO.setSubReg(KilledProdSubReg);
1780 // Extend the live intervals of the killed product operand to hold the
1783 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1784 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1786 // Don't add the segment that corresponds to the original copy.
1787 if (AI->valno == AddendValNo)
1790 VNInfo *NewFMAValNo =
1791 NewFMAInt.getNextValue(AI->start,
1792 LIS->getVNInfoAllocator());
1794 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1797 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1799 FMAInt.removeValNo(FMAValNo);
1800 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1802 // Remove the (now unused) copy.
1804 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1805 LIS->RemoveMachineInstrFromMaps(AddendMI);
1806 AddendMI->eraseFromParent();
1815 bool runOnMachineFunction(MachineFunction &MF) override {
1816 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1817 // If we don't have VSX then go ahead and return without doing
1819 if (!TM->getSubtargetImpl()->hasVSX())
1822 LIS = &getAnalysis<LiveIntervals>();
1824 TII = TM->getInstrInfo();
1826 bool Changed = false;
1828 if (DisableVSXFMAMutate)
1831 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1832 MachineBasicBlock &B = *I++;
1833 if (processBlock(B))
1840 void getAnalysisUsage(AnalysisUsage &AU) const override {
1841 AU.addRequired<LiveIntervals>();
1842 AU.addPreserved<LiveIntervals>();
1843 AU.addRequired<SlotIndexes>();
1844 AU.addPreserved<SlotIndexes>();
1845 MachineFunctionPass::getAnalysisUsage(AU);
1850 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1851 "PowerPC VSX FMA Mutation", false, false)
1852 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1853 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1854 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1855 "PowerPC VSX FMA Mutation", false, false)
1857 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1859 char PPCVSXFMAMutate::ID = 0;
1861 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1864 #define DEBUG_TYPE "ppc-vsx-copy"
1867 void initializePPCVSXCopyPass(PassRegistry&);
1871 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1872 // (Altivec and scalar floating-point registers), we need to transform the
1873 // copies into subregister copies with other restrictions.
1874 struct PPCVSXCopy : public MachineFunctionPass {
1876 PPCVSXCopy() : MachineFunctionPass(ID) {
1877 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1880 const PPCTargetMachine *TM;
1881 const PPCInstrInfo *TII;
1883 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1884 MachineRegisterInfo &MRI) {
1885 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1886 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1887 } else if (RC->contains(Reg)) {
1894 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1895 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1898 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1899 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1902 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1903 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1907 bool processBlock(MachineBasicBlock &MBB) {
1908 bool Changed = false;
1910 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1911 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1913 MachineInstr *MI = I;
1914 if (!MI->isFullCopy())
1917 MachineOperand &DstMO = MI->getOperand(0);
1918 MachineOperand &SrcMO = MI->getOperand(1);
1920 if ( IsVSReg(DstMO.getReg(), MRI) &&
1921 !IsVSReg(SrcMO.getReg(), MRI)) {
1922 // This is a copy *to* a VSX register from a non-VSX register.
1925 const TargetRegisterClass *SrcRC =
1926 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1927 &PPC::VSLRCRegClass;
1928 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1929 IsVRReg(SrcMO.getReg(), MRI)) &&
1930 "Unknown source for a VSX copy");
1932 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1933 BuildMI(MBB, MI, MI->getDebugLoc(),
1934 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1935 .addImm(1) // add 1, not 0, because there is no implicit clearing
1936 // of the high bits.
1938 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1941 // The source of the original copy is now the new virtual register.
1942 SrcMO.setReg(NewVReg);
1943 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1944 IsVSReg(SrcMO.getReg(), MRI)) {
1945 // This is a copy *from* a VSX register to a non-VSX register.
1948 const TargetRegisterClass *DstRC =
1949 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1950 &PPC::VSLRCRegClass;
1951 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1952 IsVRReg(DstMO.getReg(), MRI)) &&
1953 "Unknown destination for a VSX copy");
1955 // Copy the VSX value into a new VSX register of the correct subclass.
1956 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1957 BuildMI(MBB, MI, MI->getDebugLoc(),
1958 TII->get(TargetOpcode::COPY), NewVReg)
1961 // Transform the original copy into a subregister extraction copy.
1962 SrcMO.setReg(NewVReg);
1963 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1972 bool runOnMachineFunction(MachineFunction &MF) override {
1973 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1974 // If we don't have VSX on the subtarget, don't do anything.
1975 if (!TM->getSubtargetImpl()->hasVSX())
1977 TII = TM->getInstrInfo();
1979 bool Changed = false;
1981 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1982 MachineBasicBlock &B = *I++;
1983 if (processBlock(B))
1990 void getAnalysisUsage(AnalysisUsage &AU) const override {
1991 MachineFunctionPass::getAnalysisUsage(AU);
1996 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
1997 "PowerPC VSX Copy Legalization", false, false)
1999 char PPCVSXCopy::ID = 0;
2001 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2004 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2007 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2011 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2012 // registers (mostly because the ABI code still places all values into the
2013 // "traditional" floating-point and vector registers). Remove them here.
2014 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2016 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2017 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2020 const PPCTargetMachine *TM;
2021 const PPCInstrInfo *TII;
2024 bool processBlock(MachineBasicBlock &MBB) {
2025 bool Changed = false;
2027 SmallVector<MachineInstr *, 4> ToDelete;
2028 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2030 MachineInstr *MI = I;
2031 if (MI->getOpcode() == PPC::XXLOR &&
2032 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2033 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2034 ToDelete.push_back(MI);
2037 if (!ToDelete.empty())
2040 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2041 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2042 ToDelete[i]->eraseFromParent();
2049 bool runOnMachineFunction(MachineFunction &MF) override {
2050 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2051 // If we don't have VSX don't bother doing anything here.
2052 if (!TM->getSubtargetImpl()->hasVSX())
2054 TII = TM->getInstrInfo();
2056 bool Changed = false;
2058 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2059 MachineBasicBlock &B = *I++;
2060 if (processBlock(B))
2067 void getAnalysisUsage(AnalysisUsage &AU) const override {
2068 MachineFunctionPass::getAnalysisUsage(AU);
2073 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2074 "PowerPC VSX Copy Cleanup", false, false)
2076 char PPCVSXCopyCleanup::ID = 0;
2078 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2081 #define DEBUG_TYPE "ppc-early-ret"
2082 STATISTIC(NumBCLR, "Number of early conditional returns");
2083 STATISTIC(NumBLR, "Number of early returns");
2086 void initializePPCEarlyReturnPass(PassRegistry&);
2090 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2091 // returns up, and create conditional returns, to avoid unnecessary
2092 // branch-to-blr sequences.
2093 struct PPCEarlyReturn : public MachineFunctionPass {
2095 PPCEarlyReturn() : MachineFunctionPass(ID) {
2096 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2099 const PPCTargetMachine *TM;
2100 const PPCInstrInfo *TII;
2103 bool processBlock(MachineBasicBlock &ReturnMBB) {
2104 bool Changed = false;
2106 MachineBasicBlock::iterator I = ReturnMBB.begin();
2107 I = ReturnMBB.SkipPHIsAndLabels(I);
2109 // The block must be essentially empty except for the blr.
2110 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2111 I != ReturnMBB.getLastNonDebugInstr())
2114 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2115 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2116 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2117 bool OtherReference = false, BlockChanged = false;
2118 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2119 if (J->getOpcode() == PPC::B) {
2120 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2121 // This is an unconditional branch to the return. Replace the
2122 // branch with a blr.
2123 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2124 MachineBasicBlock::iterator K = J--;
2125 K->eraseFromParent();
2126 BlockChanged = true;
2130 } else if (J->getOpcode() == PPC::BCC) {
2131 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2132 // This is a conditional branch to the return. Replace the branch
2134 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2135 .addImm(J->getOperand(0).getImm())
2136 .addReg(J->getOperand(1).getReg());
2137 MachineBasicBlock::iterator K = J--;
2138 K->eraseFromParent();
2139 BlockChanged = true;
2143 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2144 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2145 // This is a conditional branch to the return. Replace the branch
2147 BuildMI(**PI, J, J->getDebugLoc(),
2148 TII->get(J->getOpcode() == PPC::BC ?
2149 PPC::BCLR : PPC::BCLRn))
2150 .addReg(J->getOperand(0).getReg());
2151 MachineBasicBlock::iterator K = J--;
2152 K->eraseFromParent();
2153 BlockChanged = true;
2157 } else if (J->isBranch()) {
2158 if (J->isIndirectBranch()) {
2159 if (ReturnMBB.hasAddressTaken())
2160 OtherReference = true;
2162 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2163 if (J->getOperand(i).isMBB() &&
2164 J->getOperand(i).getMBB() == &ReturnMBB)
2165 OtherReference = true;
2166 } else if (!J->isTerminator() && !J->isDebugValue())
2169 if (J == (*PI)->begin())
2175 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2176 OtherReference = true;
2178 // Predecessors are stored in a vector and can't be removed here.
2179 if (!OtherReference && BlockChanged) {
2180 PredToRemove.push_back(*PI);
2187 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2188 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2190 if (Changed && !ReturnMBB.hasAddressTaken()) {
2191 // We now might be able to merge this blr-only block into its
2192 // by-layout predecessor.
2193 if (ReturnMBB.pred_size() == 1 &&
2194 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2195 // Move the blr into the preceding block.
2196 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2197 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2198 PrevMBB.removeSuccessor(&ReturnMBB);
2201 if (ReturnMBB.pred_empty())
2202 ReturnMBB.eraseFromParent();
2209 bool runOnMachineFunction(MachineFunction &MF) override {
2210 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2211 TII = TM->getInstrInfo();
2213 bool Changed = false;
2215 // If the function does not have at least two blocks, then there is
2220 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2221 MachineBasicBlock &B = *I++;
2222 if (processBlock(B))
2229 void getAnalysisUsage(AnalysisUsage &AU) const override {
2230 MachineFunctionPass::getAnalysisUsage(AU);
2235 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2236 "PowerPC Early-Return Creation", false, false)
2238 char PPCEarlyReturn::ID = 0;
2240 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }