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 || Directive == PPC::DIR_PWR8)
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();
158 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
159 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
160 unsigned &SrcReg, unsigned &DstReg,
161 unsigned &SubIdx) const {
162 switch (MI.getOpcode()) {
163 default: return false;
165 case PPC::EXTSW_32_64:
166 SrcReg = MI.getOperand(1).getReg();
167 DstReg = MI.getOperand(0).getReg();
168 SubIdx = PPC::sub_32;
173 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
174 int &FrameIndex) const {
175 // Note: This list must be kept consistent with LoadRegFromStackSlot.
176 switch (MI->getOpcode()) {
182 case PPC::RESTORE_CR:
183 case PPC::RESTORE_CRBIT:
186 case PPC::RESTORE_VRSAVE:
187 // Check for the operands added by addFrameReference (the immediate is the
188 // offset which defaults to 0).
189 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
190 MI->getOperand(2).isFI()) {
191 FrameIndex = MI->getOperand(2).getIndex();
192 return MI->getOperand(0).getReg();
199 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
200 int &FrameIndex) const {
201 // Note: This list must be kept consistent with StoreRegToStackSlot.
202 switch (MI->getOpcode()) {
209 case PPC::SPILL_CRBIT:
212 case PPC::SPILL_VRSAVE:
213 // Check for the operands added by addFrameReference (the immediate is the
214 // offset which defaults to 0).
215 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
216 MI->getOperand(2).isFI()) {
217 FrameIndex = MI->getOperand(2).getIndex();
218 return MI->getOperand(0).getReg();
225 // commuteInstruction - We can commute rlwimi instructions, but only if the
226 // rotate amt is zero. We also have to munge the immediates a bit.
228 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
229 MachineFunction &MF = *MI->getParent()->getParent();
231 // Normal instructions can be commuted the obvious way.
232 if (MI->getOpcode() != PPC::RLWIMI &&
233 MI->getOpcode() != PPC::RLWIMIo &&
234 MI->getOpcode() != PPC::RLWIMI8 &&
235 MI->getOpcode() != PPC::RLWIMI8o)
236 return TargetInstrInfo::commuteInstruction(MI, NewMI);
238 // Cannot commute if it has a non-zero rotate count.
239 if (MI->getOperand(3).getImm() != 0)
242 // If we have a zero rotate count, we have:
244 // Op0 = (Op1 & ~M) | (Op2 & M)
246 // M = mask((ME+1)&31, (MB-1)&31)
247 // Op0 = (Op2 & ~M) | (Op1 & M)
250 unsigned Reg0 = MI->getOperand(0).getReg();
251 unsigned Reg1 = MI->getOperand(1).getReg();
252 unsigned Reg2 = MI->getOperand(2).getReg();
253 unsigned SubReg1 = MI->getOperand(1).getSubReg();
254 unsigned SubReg2 = MI->getOperand(2).getSubReg();
255 bool Reg1IsKill = MI->getOperand(1).isKill();
256 bool Reg2IsKill = MI->getOperand(2).isKill();
257 bool ChangeReg0 = false;
258 // If machine instrs are no longer in two-address forms, update
259 // destination register as well.
261 // Must be two address instruction!
262 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
263 "Expecting a two-address instruction!");
264 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
270 unsigned MB = MI->getOperand(4).getImm();
271 unsigned ME = MI->getOperand(5).getImm();
274 // Create a new instruction.
275 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
276 bool Reg0IsDead = MI->getOperand(0).isDead();
277 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
278 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
279 .addReg(Reg2, getKillRegState(Reg2IsKill))
280 .addReg(Reg1, getKillRegState(Reg1IsKill))
282 .addImm((MB-1) & 31);
286 MI->getOperand(0).setReg(Reg2);
287 MI->getOperand(0).setSubReg(SubReg2);
289 MI->getOperand(2).setReg(Reg1);
290 MI->getOperand(1).setReg(Reg2);
291 MI->getOperand(2).setSubReg(SubReg1);
292 MI->getOperand(1).setSubReg(SubReg2);
293 MI->getOperand(2).setIsKill(Reg1IsKill);
294 MI->getOperand(1).setIsKill(Reg2IsKill);
296 // Swap the mask around.
297 MI->getOperand(4).setImm((ME+1) & 31);
298 MI->getOperand(5).setImm((MB-1) & 31);
302 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
303 unsigned &SrcOpIdx2) const {
304 // For VSX A-Type FMA instructions, it is the first two operands that can be
305 // commuted, however, because the non-encoded tied input operand is listed
306 // first, the operands to swap are actually the second and third.
308 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
310 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
317 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
318 MachineBasicBlock::iterator MI) const {
319 // This function is used for scheduling, and the nop wanted here is the type
320 // that terminates dispatch groups on the POWER cores.
321 unsigned Directive = Subtarget.getDarwinDirective();
324 default: Opcode = PPC::NOP; break;
325 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
326 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
327 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
331 BuildMI(MBB, MI, DL, get(Opcode));
335 // Note: If the condition register is set to CTR or CTR8 then this is a
336 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
337 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
338 MachineBasicBlock *&FBB,
339 SmallVectorImpl<MachineOperand> &Cond,
340 bool AllowModify) const {
341 bool isPPC64 = Subtarget.isPPC64();
343 // If the block has no terminators, it just falls into the block after it.
344 MachineBasicBlock::iterator I = MBB.end();
345 if (I == MBB.begin())
348 while (I->isDebugValue()) {
349 if (I == MBB.begin())
353 if (!isUnpredicatedTerminator(I))
356 // Get the last instruction in the block.
357 MachineInstr *LastInst = I;
359 // If there is only one terminator instruction, process it.
360 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
361 if (LastInst->getOpcode() == PPC::B) {
362 if (!LastInst->getOperand(0).isMBB())
364 TBB = LastInst->getOperand(0).getMBB();
366 } else if (LastInst->getOpcode() == PPC::BCC) {
367 if (!LastInst->getOperand(2).isMBB())
369 // Block ends with fall-through condbranch.
370 TBB = LastInst->getOperand(2).getMBB();
371 Cond.push_back(LastInst->getOperand(0));
372 Cond.push_back(LastInst->getOperand(1));
374 } else if (LastInst->getOpcode() == PPC::BC) {
375 if (!LastInst->getOperand(1).isMBB())
377 // Block ends with fall-through condbranch.
378 TBB = LastInst->getOperand(1).getMBB();
379 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
380 Cond.push_back(LastInst->getOperand(0));
382 } else if (LastInst->getOpcode() == PPC::BCn) {
383 if (!LastInst->getOperand(1).isMBB())
385 // Block ends with fall-through condbranch.
386 TBB = LastInst->getOperand(1).getMBB();
387 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
388 Cond.push_back(LastInst->getOperand(0));
390 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
391 LastInst->getOpcode() == PPC::BDNZ) {
392 if (!LastInst->getOperand(0).isMBB())
394 if (DisableCTRLoopAnal)
396 TBB = LastInst->getOperand(0).getMBB();
397 Cond.push_back(MachineOperand::CreateImm(1));
398 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
401 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
402 LastInst->getOpcode() == PPC::BDZ) {
403 if (!LastInst->getOperand(0).isMBB())
405 if (DisableCTRLoopAnal)
407 TBB = LastInst->getOperand(0).getMBB();
408 Cond.push_back(MachineOperand::CreateImm(0));
409 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
414 // Otherwise, don't know what this is.
418 // Get the instruction before it if it's a terminator.
419 MachineInstr *SecondLastInst = I;
421 // If there are three terminators, we don't know what sort of block this is.
422 if (SecondLastInst && I != MBB.begin() &&
423 isUnpredicatedTerminator(--I))
426 // If the block ends with PPC::B and PPC:BCC, handle it.
427 if (SecondLastInst->getOpcode() == PPC::BCC &&
428 LastInst->getOpcode() == PPC::B) {
429 if (!SecondLastInst->getOperand(2).isMBB() ||
430 !LastInst->getOperand(0).isMBB())
432 TBB = SecondLastInst->getOperand(2).getMBB();
433 Cond.push_back(SecondLastInst->getOperand(0));
434 Cond.push_back(SecondLastInst->getOperand(1));
435 FBB = LastInst->getOperand(0).getMBB();
437 } else if (SecondLastInst->getOpcode() == PPC::BC &&
438 LastInst->getOpcode() == PPC::B) {
439 if (!SecondLastInst->getOperand(1).isMBB() ||
440 !LastInst->getOperand(0).isMBB())
442 TBB = SecondLastInst->getOperand(1).getMBB();
443 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
444 Cond.push_back(SecondLastInst->getOperand(0));
445 FBB = LastInst->getOperand(0).getMBB();
447 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
448 LastInst->getOpcode() == PPC::B) {
449 if (!SecondLastInst->getOperand(1).isMBB() ||
450 !LastInst->getOperand(0).isMBB())
452 TBB = SecondLastInst->getOperand(1).getMBB();
453 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
454 Cond.push_back(SecondLastInst->getOperand(0));
455 FBB = LastInst->getOperand(0).getMBB();
457 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
458 SecondLastInst->getOpcode() == PPC::BDNZ) &&
459 LastInst->getOpcode() == PPC::B) {
460 if (!SecondLastInst->getOperand(0).isMBB() ||
461 !LastInst->getOperand(0).isMBB())
463 if (DisableCTRLoopAnal)
465 TBB = SecondLastInst->getOperand(0).getMBB();
466 Cond.push_back(MachineOperand::CreateImm(1));
467 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
469 FBB = LastInst->getOperand(0).getMBB();
471 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
472 SecondLastInst->getOpcode() == PPC::BDZ) &&
473 LastInst->getOpcode() == PPC::B) {
474 if (!SecondLastInst->getOperand(0).isMBB() ||
475 !LastInst->getOperand(0).isMBB())
477 if (DisableCTRLoopAnal)
479 TBB = SecondLastInst->getOperand(0).getMBB();
480 Cond.push_back(MachineOperand::CreateImm(0));
481 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
483 FBB = LastInst->getOperand(0).getMBB();
487 // If the block ends with two PPC:Bs, handle it. The second one is not
488 // executed, so remove it.
489 if (SecondLastInst->getOpcode() == PPC::B &&
490 LastInst->getOpcode() == PPC::B) {
491 if (!SecondLastInst->getOperand(0).isMBB())
493 TBB = SecondLastInst->getOperand(0).getMBB();
496 I->eraseFromParent();
500 // Otherwise, can't handle this.
504 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
505 MachineBasicBlock::iterator I = MBB.end();
506 if (I == MBB.begin()) return 0;
508 while (I->isDebugValue()) {
509 if (I == MBB.begin())
513 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
514 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
515 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
516 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
519 // Remove the branch.
520 I->eraseFromParent();
524 if (I == MBB.begin()) return 1;
526 if (I->getOpcode() != PPC::BCC &&
527 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
528 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
529 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
532 // Remove the branch.
533 I->eraseFromParent();
538 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
539 MachineBasicBlock *FBB,
540 const SmallVectorImpl<MachineOperand> &Cond,
542 // Shouldn't be a fall through.
543 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
544 assert((Cond.size() == 2 || Cond.size() == 0) &&
545 "PPC branch conditions have two components!");
547 bool isPPC64 = Subtarget.isPPC64();
551 if (Cond.empty()) // Unconditional branch
552 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
553 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
554 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
555 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
556 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
557 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
558 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
559 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
560 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
561 else // Conditional branch
562 BuildMI(&MBB, DL, get(PPC::BCC))
563 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
567 // Two-way Conditional Branch.
568 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
569 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
570 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
571 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
572 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
573 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
574 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
575 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
577 BuildMI(&MBB, DL, get(PPC::BCC))
578 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
579 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
584 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
585 const SmallVectorImpl<MachineOperand> &Cond,
586 unsigned TrueReg, unsigned FalseReg,
587 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
588 if (!Subtarget.hasISEL())
591 if (Cond.size() != 2)
594 // If this is really a bdnz-like condition, then it cannot be turned into a
596 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
599 // Check register classes.
600 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
601 const TargetRegisterClass *RC =
602 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
606 // isel is for regular integer GPRs only.
607 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
608 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
609 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
610 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
613 // FIXME: These numbers are for the A2, how well they work for other cores is
614 // an open question. On the A2, the isel instruction has a 2-cycle latency
615 // but single-cycle throughput. These numbers are used in combination with
616 // the MispredictPenalty setting from the active SchedMachineModel.
624 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
625 MachineBasicBlock::iterator MI, DebugLoc dl,
627 const SmallVectorImpl<MachineOperand> &Cond,
628 unsigned TrueReg, unsigned FalseReg) const {
629 assert(Cond.size() == 2 &&
630 "PPC branch conditions have two components!");
632 assert(Subtarget.hasISEL() &&
633 "Cannot insert select on target without ISEL support");
635 // Get the register classes.
636 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
637 const TargetRegisterClass *RC =
638 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
639 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
641 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
642 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
644 PPC::GPRCRegClass.hasSubClassEq(RC) ||
645 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
646 "isel is for regular integer GPRs only");
648 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
649 unsigned SelectPred = Cond[0].getImm();
653 switch (SelectPred) {
654 default: llvm_unreachable("invalid predicate for isel");
655 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
656 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
657 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
658 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
659 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
660 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
661 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
662 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
663 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
664 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
667 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
668 SecondReg = SwapOps ? TrueReg : FalseReg;
670 // The first input register of isel cannot be r0. If it is a member
671 // of a register class that can be r0, then copy it first (the
672 // register allocator should eliminate the copy).
673 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
674 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
675 const TargetRegisterClass *FirstRC =
676 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
677 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
678 unsigned OldFirstReg = FirstReg;
679 FirstReg = MRI.createVirtualRegister(FirstRC);
680 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
681 .addReg(OldFirstReg);
684 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
685 .addReg(FirstReg).addReg(SecondReg)
686 .addReg(Cond[1].getReg(), 0, SubIdx);
689 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
690 MachineBasicBlock::iterator I, DebugLoc DL,
691 unsigned DestReg, unsigned SrcReg,
692 bool KillSrc) const {
693 // We can end up with self copies and similar things as a result of VSX copy
694 // legalization. Promote them here.
695 const TargetRegisterInfo *TRI = &getRegisterInfo();
696 if (PPC::F8RCRegClass.contains(DestReg) &&
697 PPC::VSLRCRegClass.contains(SrcReg)) {
699 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
701 if (VSXSelfCopyCrash && SrcReg == SuperReg)
702 llvm_unreachable("nop VSX copy");
705 } else if (PPC::VRRCRegClass.contains(DestReg) &&
706 PPC::VSHRCRegClass.contains(SrcReg)) {
708 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
710 if (VSXSelfCopyCrash && SrcReg == SuperReg)
711 llvm_unreachable("nop VSX copy");
714 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
715 PPC::VSLRCRegClass.contains(DestReg)) {
717 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
719 if (VSXSelfCopyCrash && DestReg == SuperReg)
720 llvm_unreachable("nop VSX copy");
723 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
724 PPC::VSHRCRegClass.contains(DestReg)) {
726 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
728 if (VSXSelfCopyCrash && DestReg == SuperReg)
729 llvm_unreachable("nop VSX copy");
735 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
737 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
739 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
741 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
743 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
745 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
746 // There are two different ways this can be done:
747 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
748 // issue in VSU pipeline 0.
749 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
750 // can go to either pipeline.
751 // We'll always use xxlor here, because in practically all cases where
752 // copies are generated, they are close enough to some use that the
753 // lower-latency form is preferable.
755 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
757 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
760 llvm_unreachable("Impossible reg-to-reg copy");
762 const MCInstrDesc &MCID = get(Opc);
763 if (MCID.getNumOperands() == 3)
764 BuildMI(MBB, I, DL, MCID, DestReg)
765 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
767 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
770 // This function returns true if a CR spill is necessary and false otherwise.
772 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
773 unsigned SrcReg, bool isKill,
775 const TargetRegisterClass *RC,
776 SmallVectorImpl<MachineInstr*> &NewMIs,
777 bool &NonRI, bool &SpillsVRS) const{
778 // Note: If additional store instructions are added here,
779 // update isStoreToStackSlot.
782 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
783 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
784 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
786 getKillRegState(isKill)),
788 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
789 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
790 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
792 getKillRegState(isKill)),
794 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
795 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
797 getKillRegState(isKill)),
799 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
800 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
802 getKillRegState(isKill)),
804 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
805 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
807 getKillRegState(isKill)),
810 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
811 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
813 getKillRegState(isKill)),
816 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
817 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
819 getKillRegState(isKill)),
822 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
823 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
825 getKillRegState(isKill)),
828 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
829 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
831 getKillRegState(isKill)),
834 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
835 assert(Subtarget.isDarwin() &&
836 "VRSAVE only needs spill/restore on Darwin");
837 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
839 getKillRegState(isKill)),
843 llvm_unreachable("Unknown regclass!");
850 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
851 MachineBasicBlock::iterator MI,
852 unsigned SrcReg, bool isKill, int FrameIdx,
853 const TargetRegisterClass *RC,
854 const TargetRegisterInfo *TRI) const {
855 MachineFunction &MF = *MBB.getParent();
856 SmallVector<MachineInstr*, 4> NewMIs;
858 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
859 FuncInfo->setHasSpills();
861 bool NonRI = false, SpillsVRS = false;
862 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
864 FuncInfo->setSpillsCR();
867 FuncInfo->setSpillsVRSAVE();
870 FuncInfo->setHasNonRISpills();
872 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
873 MBB.insert(MI, NewMIs[i]);
875 const MachineFrameInfo &MFI = *MF.getFrameInfo();
876 MachineMemOperand *MMO =
877 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
878 MachineMemOperand::MOStore,
879 MFI.getObjectSize(FrameIdx),
880 MFI.getObjectAlignment(FrameIdx));
881 NewMIs.back()->addMemOperand(MF, MMO);
885 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
886 unsigned DestReg, int FrameIdx,
887 const TargetRegisterClass *RC,
888 SmallVectorImpl<MachineInstr*> &NewMIs,
889 bool &NonRI, bool &SpillsVRS) const{
890 // Note: If additional load instructions are added here,
891 // update isLoadFromStackSlot.
893 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
894 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
895 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
896 DestReg), FrameIdx));
897 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
898 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
899 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
901 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
902 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
904 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
905 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
907 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
908 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
909 get(PPC::RESTORE_CR), DestReg),
912 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
913 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
914 get(PPC::RESTORE_CRBIT), DestReg),
917 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
918 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
921 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
922 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
925 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
926 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
929 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
930 assert(Subtarget.isDarwin() &&
931 "VRSAVE only needs spill/restore on Darwin");
932 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
933 get(PPC::RESTORE_VRSAVE),
938 llvm_unreachable("Unknown regclass!");
945 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
946 MachineBasicBlock::iterator MI,
947 unsigned DestReg, int FrameIdx,
948 const TargetRegisterClass *RC,
949 const TargetRegisterInfo *TRI) const {
950 MachineFunction &MF = *MBB.getParent();
951 SmallVector<MachineInstr*, 4> NewMIs;
953 if (MI != MBB.end()) DL = MI->getDebugLoc();
955 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
956 FuncInfo->setHasSpills();
958 bool NonRI = false, SpillsVRS = false;
959 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
961 FuncInfo->setSpillsCR();
964 FuncInfo->setSpillsVRSAVE();
967 FuncInfo->setHasNonRISpills();
969 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
970 MBB.insert(MI, NewMIs[i]);
972 const MachineFrameInfo &MFI = *MF.getFrameInfo();
973 MachineMemOperand *MMO =
974 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
975 MachineMemOperand::MOLoad,
976 MFI.getObjectSize(FrameIdx),
977 MFI.getObjectAlignment(FrameIdx));
978 NewMIs.back()->addMemOperand(MF, MMO);
982 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
983 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
984 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
985 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
987 // Leave the CR# the same, but invert the condition.
988 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
992 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
993 unsigned Reg, MachineRegisterInfo *MRI) const {
994 // For some instructions, it is legal to fold ZERO into the RA register field.
995 // A zero immediate should always be loaded with a single li.
996 unsigned DefOpc = DefMI->getOpcode();
997 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
999 if (!DefMI->getOperand(1).isImm())
1001 if (DefMI->getOperand(1).getImm() != 0)
1004 // Note that we cannot here invert the arguments of an isel in order to fold
1005 // a ZERO into what is presented as the second argument. All we have here
1006 // is the condition bit, and that might come from a CR-logical bit operation.
1008 const MCInstrDesc &UseMCID = UseMI->getDesc();
1010 // Only fold into real machine instructions.
1011 if (UseMCID.isPseudo())
1015 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1016 if (UseMI->getOperand(UseIdx).isReg() &&
1017 UseMI->getOperand(UseIdx).getReg() == Reg)
1020 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1021 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1023 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1025 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1026 // register (which might also be specified as a pointer class kind).
1027 if (UseInfo->isLookupPtrRegClass()) {
1028 if (UseInfo->RegClass /* Kind */ != 1)
1031 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1032 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1036 // Make sure this is not tied to an output register (or otherwise
1037 // constrained). This is true for ST?UX registers, for example, which
1038 // are tied to their output registers.
1039 if (UseInfo->Constraints != 0)
1043 if (UseInfo->isLookupPtrRegClass()) {
1044 bool isPPC64 = Subtarget.isPPC64();
1045 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1047 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1048 PPC::ZERO8 : PPC::ZERO;
1051 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1052 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1055 DefMI->eraseFromParent();
1060 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1061 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1063 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1068 // We should make sure that, if we're going to predicate both sides of a
1069 // condition (a diamond), that both sides don't define the counter register. We
1070 // can predicate counter-decrement-based branches, but while that predicates
1071 // the branching, it does not predicate the counter decrement. If we tried to
1072 // merge the triangle into one predicated block, we'd decrement the counter
1074 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1075 unsigned NumT, unsigned ExtraT,
1076 MachineBasicBlock &FMBB,
1077 unsigned NumF, unsigned ExtraF,
1078 const BranchProbability &Probability) const {
1079 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1083 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1084 // The predicated branches are identified by their type, not really by the
1085 // explicit presence of a predicate. Furthermore, some of them can be
1086 // predicated more than once. Because if conversion won't try to predicate
1087 // any instruction which already claims to be predicated (by returning true
1088 // here), always return false. In doing so, we let isPredicable() be the
1089 // final word on whether not the instruction can be (further) predicated.
1094 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1095 if (!MI->isTerminator())
1098 // Conditional branch is a special case.
1099 if (MI->isBranch() && !MI->isBarrier())
1102 return !isPredicated(MI);
1105 bool PPCInstrInfo::PredicateInstruction(
1107 const SmallVectorImpl<MachineOperand> &Pred) const {
1108 unsigned OpC = MI->getOpcode();
1109 if (OpC == PPC::BLR) {
1110 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1111 bool isPPC64 = Subtarget.isPPC64();
1112 MI->setDesc(get(Pred[0].getImm() ?
1113 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1114 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1115 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1116 MI->setDesc(get(PPC::BCLR));
1117 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1118 .addReg(Pred[1].getReg());
1119 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1120 MI->setDesc(get(PPC::BCLRn));
1121 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1122 .addReg(Pred[1].getReg());
1124 MI->setDesc(get(PPC::BCCLR));
1125 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1126 .addImm(Pred[0].getImm())
1127 .addReg(Pred[1].getReg());
1131 } else if (OpC == PPC::B) {
1132 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1133 bool isPPC64 = Subtarget.isPPC64();
1134 MI->setDesc(get(Pred[0].getImm() ?
1135 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1136 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1137 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1138 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1139 MI->RemoveOperand(0);
1141 MI->setDesc(get(PPC::BC));
1142 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1143 .addReg(Pred[1].getReg())
1145 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1146 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1147 MI->RemoveOperand(0);
1149 MI->setDesc(get(PPC::BCn));
1150 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1151 .addReg(Pred[1].getReg())
1154 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1155 MI->RemoveOperand(0);
1157 MI->setDesc(get(PPC::BCC));
1158 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1159 .addImm(Pred[0].getImm())
1160 .addReg(Pred[1].getReg())
1165 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1166 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1167 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1168 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1170 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1171 bool isPPC64 = Subtarget.isPPC64();
1173 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1174 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1175 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1176 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1177 .addReg(Pred[1].getReg());
1179 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1180 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1181 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1182 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1183 .addReg(Pred[1].getReg());
1187 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1188 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1189 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1190 .addImm(Pred[0].getImm())
1191 .addReg(Pred[1].getReg());
1198 bool PPCInstrInfo::SubsumesPredicate(
1199 const SmallVectorImpl<MachineOperand> &Pred1,
1200 const SmallVectorImpl<MachineOperand> &Pred2) const {
1201 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1202 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1204 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1206 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1209 // P1 can only subsume P2 if they test the same condition register.
1210 if (Pred1[1].getReg() != Pred2[1].getReg())
1213 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1214 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1219 // Does P1 subsume P2, e.g. GE subsumes GT.
1220 if (P1 == PPC::PRED_LE &&
1221 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1223 if (P1 == PPC::PRED_GE &&
1224 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1230 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1231 std::vector<MachineOperand> &Pred) const {
1232 // Note: At the present time, the contents of Pred from this function is
1233 // unused by IfConversion. This implementation follows ARM by pushing the
1234 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1235 // predicate, instructions defining CTR or CTR8 are also included as
1236 // predicate-defining instructions.
1238 const TargetRegisterClass *RCs[] =
1239 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1240 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1243 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1244 const MachineOperand &MO = MI->getOperand(i);
1245 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1246 const TargetRegisterClass *RC = RCs[c];
1248 if (MO.isDef() && RC->contains(MO.getReg())) {
1252 } else if (MO.isRegMask()) {
1253 for (TargetRegisterClass::iterator I = RC->begin(),
1254 IE = RC->end(); I != IE; ++I)
1255 if (MO.clobbersPhysReg(*I)) {
1266 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1267 unsigned OpC = MI->getOpcode();
1281 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1282 unsigned &SrcReg, unsigned &SrcReg2,
1283 int &Mask, int &Value) const {
1284 unsigned Opc = MI->getOpcode();
1287 default: return false;
1292 SrcReg = MI->getOperand(1).getReg();
1294 Value = MI->getOperand(2).getImm();
1303 SrcReg = MI->getOperand(1).getReg();
1304 SrcReg2 = MI->getOperand(2).getReg();
1309 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1310 unsigned SrcReg, unsigned SrcReg2,
1311 int Mask, int Value,
1312 const MachineRegisterInfo *MRI) const {
1316 int OpC = CmpInstr->getOpcode();
1317 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1319 // FP record forms set CR1 based on the execption status bits, not a
1320 // comparison with zero.
1321 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1324 // The record forms set the condition register based on a signed comparison
1325 // with zero (so says the ISA manual). This is not as straightforward as it
1326 // seems, however, because this is always a 64-bit comparison on PPC64, even
1327 // for instructions that are 32-bit in nature (like slw for example).
1328 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1329 // for equality checks (as those don't depend on the sign). On PPC64,
1330 // we are restricted to equality for unsigned 64-bit comparisons and for
1331 // signed 32-bit comparisons the applicability is more restricted.
1332 bool isPPC64 = Subtarget.isPPC64();
1333 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1334 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1335 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1337 // Get the unique definition of SrcReg.
1338 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1339 if (!MI) return false;
1340 int MIOpC = MI->getOpcode();
1342 bool equalityOnly = false;
1345 if (is32BitSignedCompare) {
1346 // We can perform this optimization only if MI is sign-extending.
1347 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1348 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1349 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1350 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1351 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1355 } else if (is32BitUnsignedCompare) {
1356 // We can perform this optimization, equality only, if MI is
1358 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1359 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1360 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1362 equalityOnly = true;
1366 equalityOnly = is64BitUnsignedCompare;
1368 equalityOnly = is32BitUnsignedCompare;
1371 // We need to check the uses of the condition register in order to reject
1372 // non-equality comparisons.
1373 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1374 IE = MRI->use_instr_end(); I != IE; ++I) {
1375 MachineInstr *UseMI = &*I;
1376 if (UseMI->getOpcode() == PPC::BCC) {
1377 unsigned Pred = UseMI->getOperand(0).getImm();
1378 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1380 } else if (UseMI->getOpcode() == PPC::ISEL ||
1381 UseMI->getOpcode() == PPC::ISEL8) {
1382 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1383 if (SubIdx != PPC::sub_eq)
1390 MachineBasicBlock::iterator I = CmpInstr;
1392 // Scan forward to find the first use of the compare.
1393 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1395 bool FoundUse = false;
1396 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1397 JE = MRI->use_instr_end(); J != JE; ++J)
1407 // There are two possible candidates which can be changed to set CR[01].
1408 // One is MI, the other is a SUB instruction.
1409 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1410 MachineInstr *Sub = nullptr;
1412 // MI is not a candidate for CMPrr.
1414 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1415 // same BB as the comparison. This is to allow the check below to avoid calls
1416 // (and other explicit clobbers); instead we should really check for these
1417 // more explicitly (in at least a few predecessors).
1418 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1419 // PPC does not have a record-form SUBri.
1424 const TargetRegisterInfo *TRI = &getRegisterInfo();
1427 // Get ready to iterate backward from CmpInstr.
1428 MachineBasicBlock::iterator E = MI,
1429 B = CmpInstr->getParent()->begin();
1431 for (; I != E && !noSub; --I) {
1432 const MachineInstr &Instr = *I;
1433 unsigned IOpC = Instr.getOpcode();
1435 if (&*I != CmpInstr && (
1436 Instr.modifiesRegister(PPC::CR0, TRI) ||
1437 Instr.readsRegister(PPC::CR0, TRI)))
1438 // This instruction modifies or uses the record condition register after
1439 // the one we want to change. While we could do this transformation, it
1440 // would likely not be profitable. This transformation removes one
1441 // instruction, and so even forcing RA to generate one move probably
1442 // makes it unprofitable.
1445 // Check whether CmpInstr can be made redundant by the current instruction.
1446 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1447 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1448 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1449 ((Instr.getOperand(1).getReg() == SrcReg &&
1450 Instr.getOperand(2).getReg() == SrcReg2) ||
1451 (Instr.getOperand(1).getReg() == SrcReg2 &&
1452 Instr.getOperand(2).getReg() == SrcReg))) {
1458 // The 'and' is below the comparison instruction.
1462 // Return false if no candidates exist.
1466 // The single candidate is called MI.
1470 MIOpC = MI->getOpcode();
1471 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1474 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1475 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1479 // FIXME: On the non-embedded POWER architectures, only some of the record
1480 // forms are fast, and we should use only the fast ones.
1482 // The defining instruction has a record form (or is already a record
1483 // form). It is possible, however, that we'll need to reverse the condition
1484 // code of the users.
1488 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1489 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1491 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1492 // needs to be updated to be based on SUB. Push the condition code
1493 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1494 // condition code of these operands will be modified.
1495 bool ShouldSwap = false;
1497 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1498 Sub->getOperand(2).getReg() == SrcReg;
1500 // The operands to subf are the opposite of sub, so only in the fixed-point
1501 // case, invert the order.
1502 ShouldSwap = !ShouldSwap;
1506 for (MachineRegisterInfo::use_instr_iterator
1507 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1509 MachineInstr *UseMI = &*I;
1510 if (UseMI->getOpcode() == PPC::BCC) {
1511 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1512 assert((!equalityOnly ||
1513 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1514 "Invalid predicate for equality-only optimization");
1515 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1516 PPC::getSwappedPredicate(Pred)));
1517 } else if (UseMI->getOpcode() == PPC::ISEL ||
1518 UseMI->getOpcode() == PPC::ISEL8) {
1519 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1520 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1521 "Invalid CR bit for equality-only optimization");
1523 if (NewSubReg == PPC::sub_lt)
1524 NewSubReg = PPC::sub_gt;
1525 else if (NewSubReg == PPC::sub_gt)
1526 NewSubReg = PPC::sub_lt;
1528 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1530 } else // We need to abort on a user we don't understand.
1534 // Create a new virtual register to hold the value of the CR set by the
1535 // record-form instruction. If the instruction was not previously in
1536 // record form, then set the kill flag on the CR.
1537 CmpInstr->eraseFromParent();
1539 MachineBasicBlock::iterator MII = MI;
1540 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1541 get(TargetOpcode::COPY), CRReg)
1542 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1544 if (MIOpC != NewOpC) {
1545 // We need to be careful here: we're replacing one instruction with
1546 // another, and we need to make sure that we get all of the right
1547 // implicit uses and defs. On the other hand, the caller may be holding
1548 // an iterator to this instruction, and so we can't delete it (this is
1549 // specifically the case if this is the instruction directly after the
1552 const MCInstrDesc &NewDesc = get(NewOpC);
1553 MI->setDesc(NewDesc);
1555 if (NewDesc.ImplicitDefs)
1556 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1557 *ImpDefs; ++ImpDefs)
1558 if (!MI->definesRegister(*ImpDefs))
1559 MI->addOperand(*MI->getParent()->getParent(),
1560 MachineOperand::CreateReg(*ImpDefs, true, true));
1561 if (NewDesc.ImplicitUses)
1562 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1563 *ImpUses; ++ImpUses)
1564 if (!MI->readsRegister(*ImpUses))
1565 MI->addOperand(*MI->getParent()->getParent(),
1566 MachineOperand::CreateReg(*ImpUses, false, true));
1569 // Modify the condition code of operands in OperandsToUpdate.
1570 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1571 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1572 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1573 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1575 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1576 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1581 /// GetInstSize - Return the number of bytes of code the specified
1582 /// instruction may be. This returns the maximum number of bytes.
1584 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1585 unsigned Opcode = MI->getOpcode();
1587 if (Opcode == PPC::INLINEASM) {
1588 const MachineFunction *MF = MI->getParent()->getParent();
1589 const char *AsmStr = MI->getOperand(0).getSymbolName();
1590 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1592 const MCInstrDesc &Desc = get(Opcode);
1593 return Desc.getSize();
1598 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1601 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1602 // (Altivec and scalar floating-point registers), we need to transform the
1603 // copies into subregister copies with other restrictions.
1604 struct PPCVSXFMAMutate : public MachineFunctionPass {
1606 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1607 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1612 const PPCTargetMachine *TM;
1613 const PPCInstrInfo *TII;
1616 bool processBlock(MachineBasicBlock &MBB) {
1617 bool Changed = false;
1619 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1620 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1622 MachineInstr *MI = I;
1624 // The default (A-type) VSX FMA form kills the addend (it is taken from
1625 // the target register, which is then updated to reflect the result of
1626 // the FMA). If the instruction, however, kills one of the registers
1627 // used for the product, then we can use the M-form instruction (which
1628 // will take that value from the to-be-defined register).
1630 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1634 // This pass is run after register coalescing, and so we're looking for
1635 // a situation like this:
1637 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1638 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1639 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1641 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1642 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1644 // Where we can eliminate the copy by changing from the A-type to the
1645 // M-type instruction. Specifically, for this example, this means:
1646 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1647 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1649 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1650 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1651 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1653 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1655 VNInfo *AddendValNo =
1656 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1657 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1659 // The addend and this instruction must be in the same block.
1661 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1664 // The addend must be a full copy within the same register class.
1666 if (!AddendMI->isFullCopy())
1669 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1670 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1671 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1672 MRI.getRegClass(AddendSrcReg))
1675 // If AddendSrcReg is a physical register, make sure the destination
1676 // register class contains it.
1677 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1678 ->contains(AddendSrcReg))
1682 // In theory, there could be other uses of the addend copy before this
1683 // fma. We could deal with this, but that would require additional
1684 // logic below and I suspect it will not occur in any relevant
1686 bool OtherUsers = false;
1687 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1689 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1697 // Find one of the product operands that is killed by this instruction.
1699 unsigned KilledProdOp = 0, OtherProdOp = 0;
1700 if (LIS->getInterval(MI->getOperand(2).getReg())
1701 .Query(FMAIdx).isKill()) {
1704 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1705 .Query(FMAIdx).isKill()) {
1710 // If there are no killed product operands, then this transformation is
1711 // likely not profitable.
1715 // In order to replace the addend here with the source of the copy,
1716 // it must still be live here.
1717 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1720 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1722 unsigned AddReg = AddendMI->getOperand(1).getReg();
1723 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1724 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1726 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1727 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1728 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1730 bool AddRegKill = AddendMI->getOperand(1).isKill();
1731 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1732 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1734 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1735 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1736 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1738 unsigned OldFMAReg = MI->getOperand(0).getReg();
1740 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1741 "Addend copy not tied to old FMA output!");
1743 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1745 MI->getOperand(0).setReg(KilledProdReg);
1746 MI->getOperand(1).setReg(KilledProdReg);
1747 MI->getOperand(3).setReg(AddReg);
1748 MI->getOperand(2).setReg(OtherProdReg);
1750 MI->getOperand(0).setSubReg(KilledProdSubReg);
1751 MI->getOperand(1).setSubReg(KilledProdSubReg);
1752 MI->getOperand(3).setSubReg(AddSubReg);
1753 MI->getOperand(2).setSubReg(OtherProdSubReg);
1755 MI->getOperand(1).setIsKill(KilledProdRegKill);
1756 MI->getOperand(3).setIsKill(AddRegKill);
1757 MI->getOperand(2).setIsKill(OtherProdRegKill);
1759 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1760 MI->getOperand(3).setIsUndef(AddRegUndef);
1761 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1763 MI->setDesc(TII->get(AltOpc));
1765 DEBUG(dbgs() << " -> " << *MI);
1767 // The killed product operand was killed here, so we can reuse it now
1768 // for the result of the fma.
1770 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1771 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1772 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1774 MachineOperand &UseMO = *UI;
1775 MachineInstr *UseMI = UseMO.getParent();
1778 // Don't replace the result register of the copy we're about to erase.
1779 if (UseMI == AddendMI)
1782 UseMO.setReg(KilledProdReg);
1783 UseMO.setSubReg(KilledProdSubReg);
1786 // Extend the live intervals of the killed product operand to hold the
1789 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1790 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1792 // Don't add the segment that corresponds to the original copy.
1793 if (AI->valno == AddendValNo)
1796 VNInfo *NewFMAValNo =
1797 NewFMAInt.getNextValue(AI->start,
1798 LIS->getVNInfoAllocator());
1800 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1803 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1805 FMAInt.removeValNo(FMAValNo);
1806 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1808 // Remove the (now unused) copy.
1810 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1811 LIS->RemoveMachineInstrFromMaps(AddendMI);
1812 AddendMI->eraseFromParent();
1821 bool runOnMachineFunction(MachineFunction &MF) override {
1822 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1823 // If we don't have VSX then go ahead and return without doing
1825 if (!TM->getSubtargetImpl()->hasVSX())
1828 LIS = &getAnalysis<LiveIntervals>();
1830 TII = TM->getInstrInfo();
1832 bool Changed = false;
1834 if (DisableVSXFMAMutate)
1837 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1838 MachineBasicBlock &B = *I++;
1839 if (processBlock(B))
1846 void getAnalysisUsage(AnalysisUsage &AU) const override {
1847 AU.addRequired<LiveIntervals>();
1848 AU.addPreserved<LiveIntervals>();
1849 AU.addRequired<SlotIndexes>();
1850 AU.addPreserved<SlotIndexes>();
1851 MachineFunctionPass::getAnalysisUsage(AU);
1856 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1857 "PowerPC VSX FMA Mutation", false, false)
1858 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1859 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1860 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1861 "PowerPC VSX FMA Mutation", false, false)
1863 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1865 char PPCVSXFMAMutate::ID = 0;
1867 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1870 #define DEBUG_TYPE "ppc-vsx-copy"
1873 void initializePPCVSXCopyPass(PassRegistry&);
1877 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1878 // (Altivec and scalar floating-point registers), we need to transform the
1879 // copies into subregister copies with other restrictions.
1880 struct PPCVSXCopy : public MachineFunctionPass {
1882 PPCVSXCopy() : MachineFunctionPass(ID) {
1883 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1886 const PPCTargetMachine *TM;
1887 const PPCInstrInfo *TII;
1889 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1890 MachineRegisterInfo &MRI) {
1891 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1892 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1893 } else if (RC->contains(Reg)) {
1900 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1901 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1904 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1905 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1908 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1909 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1913 bool processBlock(MachineBasicBlock &MBB) {
1914 bool Changed = false;
1916 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1917 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1919 MachineInstr *MI = I;
1920 if (!MI->isFullCopy())
1923 MachineOperand &DstMO = MI->getOperand(0);
1924 MachineOperand &SrcMO = MI->getOperand(1);
1926 if ( IsVSReg(DstMO.getReg(), MRI) &&
1927 !IsVSReg(SrcMO.getReg(), MRI)) {
1928 // This is a copy *to* a VSX register from a non-VSX register.
1931 const TargetRegisterClass *SrcRC =
1932 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1933 &PPC::VSLRCRegClass;
1934 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1935 IsVRReg(SrcMO.getReg(), MRI)) &&
1936 "Unknown source for a VSX copy");
1938 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1939 BuildMI(MBB, MI, MI->getDebugLoc(),
1940 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1941 .addImm(1) // add 1, not 0, because there is no implicit clearing
1942 // of the high bits.
1944 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1947 // The source of the original copy is now the new virtual register.
1948 SrcMO.setReg(NewVReg);
1949 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1950 IsVSReg(SrcMO.getReg(), MRI)) {
1951 // This is a copy *from* a VSX register to a non-VSX register.
1954 const TargetRegisterClass *DstRC =
1955 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1956 &PPC::VSLRCRegClass;
1957 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1958 IsVRReg(DstMO.getReg(), MRI)) &&
1959 "Unknown destination for a VSX copy");
1961 // Copy the VSX value into a new VSX register of the correct subclass.
1962 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1963 BuildMI(MBB, MI, MI->getDebugLoc(),
1964 TII->get(TargetOpcode::COPY), NewVReg)
1967 // Transform the original copy into a subregister extraction copy.
1968 SrcMO.setReg(NewVReg);
1969 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1978 bool runOnMachineFunction(MachineFunction &MF) override {
1979 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1980 // If we don't have VSX on the subtarget, don't do anything.
1981 if (!TM->getSubtargetImpl()->hasVSX())
1983 TII = TM->getInstrInfo();
1985 bool Changed = false;
1987 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1988 MachineBasicBlock &B = *I++;
1989 if (processBlock(B))
1996 void getAnalysisUsage(AnalysisUsage &AU) const override {
1997 MachineFunctionPass::getAnalysisUsage(AU);
2002 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2003 "PowerPC VSX Copy Legalization", false, false)
2005 char PPCVSXCopy::ID = 0;
2007 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2010 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2013 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2017 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2018 // registers (mostly because the ABI code still places all values into the
2019 // "traditional" floating-point and vector registers). Remove them here.
2020 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2022 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2023 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2026 const PPCTargetMachine *TM;
2027 const PPCInstrInfo *TII;
2030 bool processBlock(MachineBasicBlock &MBB) {
2031 bool Changed = false;
2033 SmallVector<MachineInstr *, 4> ToDelete;
2034 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2036 MachineInstr *MI = I;
2037 if (MI->getOpcode() == PPC::XXLOR &&
2038 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2039 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2040 ToDelete.push_back(MI);
2043 if (!ToDelete.empty())
2046 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2047 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2048 ToDelete[i]->eraseFromParent();
2055 bool runOnMachineFunction(MachineFunction &MF) override {
2056 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2057 // If we don't have VSX don't bother doing anything here.
2058 if (!TM->getSubtargetImpl()->hasVSX())
2060 TII = TM->getInstrInfo();
2062 bool Changed = false;
2064 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2065 MachineBasicBlock &B = *I++;
2066 if (processBlock(B))
2073 void getAnalysisUsage(AnalysisUsage &AU) const override {
2074 MachineFunctionPass::getAnalysisUsage(AU);
2079 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2080 "PowerPC VSX Copy Cleanup", false, false)
2082 char PPCVSXCopyCleanup::ID = 0;
2084 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2087 #define DEBUG_TYPE "ppc-early-ret"
2088 STATISTIC(NumBCLR, "Number of early conditional returns");
2089 STATISTIC(NumBLR, "Number of early returns");
2092 void initializePPCEarlyReturnPass(PassRegistry&);
2096 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2097 // returns up, and create conditional returns, to avoid unnecessary
2098 // branch-to-blr sequences.
2099 struct PPCEarlyReturn : public MachineFunctionPass {
2101 PPCEarlyReturn() : MachineFunctionPass(ID) {
2102 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2105 const PPCTargetMachine *TM;
2106 const PPCInstrInfo *TII;
2109 bool processBlock(MachineBasicBlock &ReturnMBB) {
2110 bool Changed = false;
2112 MachineBasicBlock::iterator I = ReturnMBB.begin();
2113 I = ReturnMBB.SkipPHIsAndLabels(I);
2115 // The block must be essentially empty except for the blr.
2116 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2117 I != ReturnMBB.getLastNonDebugInstr())
2120 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2121 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2122 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2123 bool OtherReference = false, BlockChanged = false;
2124 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2125 if (J->getOpcode() == PPC::B) {
2126 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2127 // This is an unconditional branch to the return. Replace the
2128 // branch with a blr.
2129 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2130 MachineBasicBlock::iterator K = J--;
2131 K->eraseFromParent();
2132 BlockChanged = true;
2136 } else if (J->getOpcode() == PPC::BCC) {
2137 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2138 // This is a conditional branch to the return. Replace the branch
2140 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2141 .addImm(J->getOperand(0).getImm())
2142 .addReg(J->getOperand(1).getReg());
2143 MachineBasicBlock::iterator K = J--;
2144 K->eraseFromParent();
2145 BlockChanged = true;
2149 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2150 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2151 // This is a conditional branch to the return. Replace the branch
2153 BuildMI(**PI, J, J->getDebugLoc(),
2154 TII->get(J->getOpcode() == PPC::BC ?
2155 PPC::BCLR : PPC::BCLRn))
2156 .addReg(J->getOperand(0).getReg());
2157 MachineBasicBlock::iterator K = J--;
2158 K->eraseFromParent();
2159 BlockChanged = true;
2163 } else if (J->isBranch()) {
2164 if (J->isIndirectBranch()) {
2165 if (ReturnMBB.hasAddressTaken())
2166 OtherReference = true;
2168 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2169 if (J->getOperand(i).isMBB() &&
2170 J->getOperand(i).getMBB() == &ReturnMBB)
2171 OtherReference = true;
2172 } else if (!J->isTerminator() && !J->isDebugValue())
2175 if (J == (*PI)->begin())
2181 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2182 OtherReference = true;
2184 // Predecessors are stored in a vector and can't be removed here.
2185 if (!OtherReference && BlockChanged) {
2186 PredToRemove.push_back(*PI);
2193 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2194 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2196 if (Changed && !ReturnMBB.hasAddressTaken()) {
2197 // We now might be able to merge this blr-only block into its
2198 // by-layout predecessor.
2199 if (ReturnMBB.pred_size() == 1 &&
2200 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2201 // Move the blr into the preceding block.
2202 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2203 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2204 PrevMBB.removeSuccessor(&ReturnMBB);
2207 if (ReturnMBB.pred_empty())
2208 ReturnMBB.eraseFromParent();
2215 bool runOnMachineFunction(MachineFunction &MF) override {
2216 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2217 TII = TM->getInstrInfo();
2219 bool Changed = false;
2221 // If the function does not have at least two blocks, then there is
2226 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2227 MachineBasicBlock &B = *I++;
2228 if (processBlock(B))
2235 void getAnalysisUsage(AnalysisUsage &AU) const override {
2236 MachineFunctionPass::getAnalysisUsage(AU);
2241 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2242 "PowerPC Early-Return Creation", false, false)
2244 char PPCEarlyReturn::ID = 0;
2246 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }