1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the PowerPC implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.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/CodeGen/StackMaps.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "ppc-instr-info"
44
45 #define GET_INSTRMAP_INFO
46 #define GET_INSTRINFO_CTOR_DTOR
47 #include "PPCGenInstrInfo.inc"
48
49 static cl::
50 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
51 cl::desc("Disable analysis for CTR loops"));
52
53 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
54 cl::desc("Disable compare instruction optimization"), cl::Hidden);
55
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"),
58 cl::Hidden);
59
60 static cl::opt<bool>
61 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
62 cl::desc("Use the old (incorrect) instruction latency calculation"));
63
64 // Pin the vtable to this file.
anchor()65 void PPCInstrInfo::anchor() {}
66
PPCInstrInfo(PPCSubtarget & STI)67 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
68 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
69 Subtarget(STI), RI(STI.getTargetMachine()) {}
70
71 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
72 /// this target when scheduling the DAG.
73 ScheduleHazardRecognizer *
CreateTargetHazardRecognizer(const TargetSubtargetInfo * STI,const ScheduleDAG * DAG) const74 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
75 const ScheduleDAG *DAG) const {
76 unsigned Directive =
77 static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
78 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
79 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
80 const InstrItineraryData *II =
81 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
82 return new ScoreboardHazardRecognizer(II, DAG);
83 }
84
85 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
86 }
87
88 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
89 /// to use for this target when scheduling the DAG.
90 ScheduleHazardRecognizer *
CreateTargetPostRAHazardRecognizer(const InstrItineraryData * II,const ScheduleDAG * DAG) const91 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
92 const ScheduleDAG *DAG) const {
93 unsigned Directive =
94 DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
95
96 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
97 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
98
99 // Most subtargets use a PPC970 recognizer.
100 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
101 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
102 assert(DAG->TII && "No InstrInfo?");
103
104 return new PPCHazardRecognizer970(*DAG);
105 }
106
107 return new ScoreboardHazardRecognizer(II, DAG);
108 }
109
getInstrLatency(const InstrItineraryData * ItinData,const MachineInstr * MI,unsigned * PredCost) const110 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
111 const MachineInstr *MI,
112 unsigned *PredCost) const {
113 if (!ItinData || UseOldLatencyCalc)
114 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
115
116 // The default implementation of getInstrLatency calls getStageLatency, but
117 // getStageLatency does not do the right thing for us. While we have
118 // itinerary, most cores are fully pipelined, and so the itineraries only
119 // express the first part of the pipeline, not every stage. Instead, we need
120 // to use the listed output operand cycle number (using operand 0 here, which
121 // is an output).
122
123 unsigned Latency = 1;
124 unsigned DefClass = MI->getDesc().getSchedClass();
125 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
126 const MachineOperand &MO = MI->getOperand(i);
127 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
128 continue;
129
130 int Cycle = ItinData->getOperandCycle(DefClass, i);
131 if (Cycle < 0)
132 continue;
133
134 Latency = std::max(Latency, (unsigned) Cycle);
135 }
136
137 return Latency;
138 }
139
getOperandLatency(const InstrItineraryData * ItinData,const MachineInstr * DefMI,unsigned DefIdx,const MachineInstr * UseMI,unsigned UseIdx) const140 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
141 const MachineInstr *DefMI, unsigned DefIdx,
142 const MachineInstr *UseMI,
143 unsigned UseIdx) const {
144 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
145 UseMI, UseIdx);
146
147 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
148 unsigned Reg = DefMO.getReg();
149
150 bool IsRegCR;
151 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
152 const MachineRegisterInfo *MRI =
153 &DefMI->getParent()->getParent()->getRegInfo();
154 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
155 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
156 } else {
157 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
158 PPC::CRBITRCRegClass.contains(Reg);
159 }
160
161 if (UseMI->isBranch() && IsRegCR) {
162 if (Latency < 0)
163 Latency = getInstrLatency(ItinData, DefMI);
164
165 // On some cores, there is an additional delay between writing to a condition
166 // register, and using it from a branch.
167 unsigned Directive = Subtarget.getDarwinDirective();
168 switch (Directive) {
169 default: break;
170 case PPC::DIR_7400:
171 case PPC::DIR_750:
172 case PPC::DIR_970:
173 case PPC::DIR_E5500:
174 case PPC::DIR_PWR4:
175 case PPC::DIR_PWR5:
176 case PPC::DIR_PWR5X:
177 case PPC::DIR_PWR6:
178 case PPC::DIR_PWR6X:
179 case PPC::DIR_PWR7:
180 case PPC::DIR_PWR8:
181 Latency += 2;
182 break;
183 }
184 }
185
186 return Latency;
187 }
188
189 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
isCoalescableExtInstr(const MachineInstr & MI,unsigned & SrcReg,unsigned & DstReg,unsigned & SubIdx) const190 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
191 unsigned &SrcReg, unsigned &DstReg,
192 unsigned &SubIdx) const {
193 switch (MI.getOpcode()) {
194 default: return false;
195 case PPC::EXTSW:
196 case PPC::EXTSW_32_64:
197 SrcReg = MI.getOperand(1).getReg();
198 DstReg = MI.getOperand(0).getReg();
199 SubIdx = PPC::sub_32;
200 return true;
201 }
202 }
203
isLoadFromStackSlot(const MachineInstr * MI,int & FrameIndex) const204 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
205 int &FrameIndex) const {
206 // Note: This list must be kept consistent with LoadRegFromStackSlot.
207 switch (MI->getOpcode()) {
208 default: break;
209 case PPC::LD:
210 case PPC::LWZ:
211 case PPC::LFS:
212 case PPC::LFD:
213 case PPC::RESTORE_CR:
214 case PPC::RESTORE_CRBIT:
215 case PPC::LVX:
216 case PPC::LXVD2X:
217 case PPC::QVLFDX:
218 case PPC::QVLFSXs:
219 case PPC::QVLFDXb:
220 case PPC::RESTORE_VRSAVE:
221 // Check for the operands added by addFrameReference (the immediate is the
222 // offset which defaults to 0).
223 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
224 MI->getOperand(2).isFI()) {
225 FrameIndex = MI->getOperand(2).getIndex();
226 return MI->getOperand(0).getReg();
227 }
228 break;
229 }
230 return 0;
231 }
232
isStoreToStackSlot(const MachineInstr * MI,int & FrameIndex) const233 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
234 int &FrameIndex) const {
235 // Note: This list must be kept consistent with StoreRegToStackSlot.
236 switch (MI->getOpcode()) {
237 default: break;
238 case PPC::STD:
239 case PPC::STW:
240 case PPC::STFS:
241 case PPC::STFD:
242 case PPC::SPILL_CR:
243 case PPC::SPILL_CRBIT:
244 case PPC::STVX:
245 case PPC::STXVD2X:
246 case PPC::QVSTFDX:
247 case PPC::QVSTFSXs:
248 case PPC::QVSTFDXb:
249 case PPC::SPILL_VRSAVE:
250 // Check for the operands added by addFrameReference (the immediate is the
251 // offset which defaults to 0).
252 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
253 MI->getOperand(2).isFI()) {
254 FrameIndex = MI->getOperand(2).getIndex();
255 return MI->getOperand(0).getReg();
256 }
257 break;
258 }
259 return 0;
260 }
261
262 // commuteInstruction - We can commute rlwimi instructions, but only if the
263 // rotate amt is zero. We also have to munge the immediates a bit.
264 MachineInstr *
commuteInstruction(MachineInstr * MI,bool NewMI) const265 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
266 MachineFunction &MF = *MI->getParent()->getParent();
267
268 // Normal instructions can be commuted the obvious way.
269 if (MI->getOpcode() != PPC::RLWIMI &&
270 MI->getOpcode() != PPC::RLWIMIo)
271 return TargetInstrInfo::commuteInstruction(MI, NewMI);
272 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
273 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
274 // changing the relative order of the mask operands might change what happens
275 // to the high-bits of the mask (and, thus, the result).
276
277 // Cannot commute if it has a non-zero rotate count.
278 if (MI->getOperand(3).getImm() != 0)
279 return nullptr;
280
281 // If we have a zero rotate count, we have:
282 // M = mask(MB,ME)
283 // Op0 = (Op1 & ~M) | (Op2 & M)
284 // Change this to:
285 // M = mask((ME+1)&31, (MB-1)&31)
286 // Op0 = (Op2 & ~M) | (Op1 & M)
287
288 // Swap op1/op2
289 unsigned Reg0 = MI->getOperand(0).getReg();
290 unsigned Reg1 = MI->getOperand(1).getReg();
291 unsigned Reg2 = MI->getOperand(2).getReg();
292 unsigned SubReg1 = MI->getOperand(1).getSubReg();
293 unsigned SubReg2 = MI->getOperand(2).getSubReg();
294 bool Reg1IsKill = MI->getOperand(1).isKill();
295 bool Reg2IsKill = MI->getOperand(2).isKill();
296 bool ChangeReg0 = false;
297 // If machine instrs are no longer in two-address forms, update
298 // destination register as well.
299 if (Reg0 == Reg1) {
300 // Must be two address instruction!
301 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
302 "Expecting a two-address instruction!");
303 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
304 Reg2IsKill = false;
305 ChangeReg0 = true;
306 }
307
308 // Masks.
309 unsigned MB = MI->getOperand(4).getImm();
310 unsigned ME = MI->getOperand(5).getImm();
311
312 // We can't commute a trivial mask (there is no way to represent an all-zero
313 // mask).
314 if (MB == 0 && ME == 31)
315 return nullptr;
316
317 if (NewMI) {
318 // Create a new instruction.
319 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
320 bool Reg0IsDead = MI->getOperand(0).isDead();
321 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
322 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
323 .addReg(Reg2, getKillRegState(Reg2IsKill))
324 .addReg(Reg1, getKillRegState(Reg1IsKill))
325 .addImm((ME+1) & 31)
326 .addImm((MB-1) & 31);
327 }
328
329 if (ChangeReg0) {
330 MI->getOperand(0).setReg(Reg2);
331 MI->getOperand(0).setSubReg(SubReg2);
332 }
333 MI->getOperand(2).setReg(Reg1);
334 MI->getOperand(1).setReg(Reg2);
335 MI->getOperand(2).setSubReg(SubReg1);
336 MI->getOperand(1).setSubReg(SubReg2);
337 MI->getOperand(2).setIsKill(Reg1IsKill);
338 MI->getOperand(1).setIsKill(Reg2IsKill);
339
340 // Swap the mask around.
341 MI->getOperand(4).setImm((ME+1) & 31);
342 MI->getOperand(5).setImm((MB-1) & 31);
343 return MI;
344 }
345
findCommutedOpIndices(MachineInstr * MI,unsigned & SrcOpIdx1,unsigned & SrcOpIdx2) const346 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
347 unsigned &SrcOpIdx2) const {
348 // For VSX A-Type FMA instructions, it is the first two operands that can be
349 // commuted, however, because the non-encoded tied input operand is listed
350 // first, the operands to swap are actually the second and third.
351
352 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
353 if (AltOpc == -1)
354 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
355
356 SrcOpIdx1 = 2;
357 SrcOpIdx2 = 3;
358 return true;
359 }
360
insertNoop(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI) const361 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
362 MachineBasicBlock::iterator MI) const {
363 // This function is used for scheduling, and the nop wanted here is the type
364 // that terminates dispatch groups on the POWER cores.
365 unsigned Directive = Subtarget.getDarwinDirective();
366 unsigned Opcode;
367 switch (Directive) {
368 default: Opcode = PPC::NOP; break;
369 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
370 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
371 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
372 }
373
374 DebugLoc DL;
375 BuildMI(MBB, MI, DL, get(Opcode));
376 }
377
378 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
getNoopForMachoTarget(MCInst & NopInst) const379 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
380 NopInst.setOpcode(PPC::NOP);
381 }
382
383 // Branch analysis.
384 // Note: If the condition register is set to CTR or CTR8 then this is a
385 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
AnalyzeBranch(MachineBasicBlock & MBB,MachineBasicBlock * & TBB,MachineBasicBlock * & FBB,SmallVectorImpl<MachineOperand> & Cond,bool AllowModify) const386 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
387 MachineBasicBlock *&FBB,
388 SmallVectorImpl<MachineOperand> &Cond,
389 bool AllowModify) const {
390 bool isPPC64 = Subtarget.isPPC64();
391
392 // If the block has no terminators, it just falls into the block after it.
393 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
394 if (I == MBB.end())
395 return false;
396
397 if (!isUnpredicatedTerminator(I))
398 return false;
399
400 // Get the last instruction in the block.
401 MachineInstr *LastInst = I;
402
403 // If there is only one terminator instruction, process it.
404 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
405 if (LastInst->getOpcode() == PPC::B) {
406 if (!LastInst->getOperand(0).isMBB())
407 return true;
408 TBB = LastInst->getOperand(0).getMBB();
409 return false;
410 } else if (LastInst->getOpcode() == PPC::BCC) {
411 if (!LastInst->getOperand(2).isMBB())
412 return true;
413 // Block ends with fall-through condbranch.
414 TBB = LastInst->getOperand(2).getMBB();
415 Cond.push_back(LastInst->getOperand(0));
416 Cond.push_back(LastInst->getOperand(1));
417 return false;
418 } else if (LastInst->getOpcode() == PPC::BC) {
419 if (!LastInst->getOperand(1).isMBB())
420 return true;
421 // Block ends with fall-through condbranch.
422 TBB = LastInst->getOperand(1).getMBB();
423 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
424 Cond.push_back(LastInst->getOperand(0));
425 return false;
426 } else if (LastInst->getOpcode() == PPC::BCn) {
427 if (!LastInst->getOperand(1).isMBB())
428 return true;
429 // Block ends with fall-through condbranch.
430 TBB = LastInst->getOperand(1).getMBB();
431 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
432 Cond.push_back(LastInst->getOperand(0));
433 return false;
434 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
435 LastInst->getOpcode() == PPC::BDNZ) {
436 if (!LastInst->getOperand(0).isMBB())
437 return true;
438 if (DisableCTRLoopAnal)
439 return true;
440 TBB = LastInst->getOperand(0).getMBB();
441 Cond.push_back(MachineOperand::CreateImm(1));
442 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
443 true));
444 return false;
445 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
446 LastInst->getOpcode() == PPC::BDZ) {
447 if (!LastInst->getOperand(0).isMBB())
448 return true;
449 if (DisableCTRLoopAnal)
450 return true;
451 TBB = LastInst->getOperand(0).getMBB();
452 Cond.push_back(MachineOperand::CreateImm(0));
453 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
454 true));
455 return false;
456 }
457
458 // Otherwise, don't know what this is.
459 return true;
460 }
461
462 // Get the instruction before it if it's a terminator.
463 MachineInstr *SecondLastInst = I;
464
465 // If there are three terminators, we don't know what sort of block this is.
466 if (SecondLastInst && I != MBB.begin() &&
467 isUnpredicatedTerminator(--I))
468 return true;
469
470 // If the block ends with PPC::B and PPC:BCC, handle it.
471 if (SecondLastInst->getOpcode() == PPC::BCC &&
472 LastInst->getOpcode() == PPC::B) {
473 if (!SecondLastInst->getOperand(2).isMBB() ||
474 !LastInst->getOperand(0).isMBB())
475 return true;
476 TBB = SecondLastInst->getOperand(2).getMBB();
477 Cond.push_back(SecondLastInst->getOperand(0));
478 Cond.push_back(SecondLastInst->getOperand(1));
479 FBB = LastInst->getOperand(0).getMBB();
480 return false;
481 } else if (SecondLastInst->getOpcode() == PPC::BC &&
482 LastInst->getOpcode() == PPC::B) {
483 if (!SecondLastInst->getOperand(1).isMBB() ||
484 !LastInst->getOperand(0).isMBB())
485 return true;
486 TBB = SecondLastInst->getOperand(1).getMBB();
487 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
488 Cond.push_back(SecondLastInst->getOperand(0));
489 FBB = LastInst->getOperand(0).getMBB();
490 return false;
491 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
492 LastInst->getOpcode() == PPC::B) {
493 if (!SecondLastInst->getOperand(1).isMBB() ||
494 !LastInst->getOperand(0).isMBB())
495 return true;
496 TBB = SecondLastInst->getOperand(1).getMBB();
497 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
498 Cond.push_back(SecondLastInst->getOperand(0));
499 FBB = LastInst->getOperand(0).getMBB();
500 return false;
501 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
502 SecondLastInst->getOpcode() == PPC::BDNZ) &&
503 LastInst->getOpcode() == PPC::B) {
504 if (!SecondLastInst->getOperand(0).isMBB() ||
505 !LastInst->getOperand(0).isMBB())
506 return true;
507 if (DisableCTRLoopAnal)
508 return true;
509 TBB = SecondLastInst->getOperand(0).getMBB();
510 Cond.push_back(MachineOperand::CreateImm(1));
511 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
512 true));
513 FBB = LastInst->getOperand(0).getMBB();
514 return false;
515 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
516 SecondLastInst->getOpcode() == PPC::BDZ) &&
517 LastInst->getOpcode() == PPC::B) {
518 if (!SecondLastInst->getOperand(0).isMBB() ||
519 !LastInst->getOperand(0).isMBB())
520 return true;
521 if (DisableCTRLoopAnal)
522 return true;
523 TBB = SecondLastInst->getOperand(0).getMBB();
524 Cond.push_back(MachineOperand::CreateImm(0));
525 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
526 true));
527 FBB = LastInst->getOperand(0).getMBB();
528 return false;
529 }
530
531 // If the block ends with two PPC:Bs, handle it. The second one is not
532 // executed, so remove it.
533 if (SecondLastInst->getOpcode() == PPC::B &&
534 LastInst->getOpcode() == PPC::B) {
535 if (!SecondLastInst->getOperand(0).isMBB())
536 return true;
537 TBB = SecondLastInst->getOperand(0).getMBB();
538 I = LastInst;
539 if (AllowModify)
540 I->eraseFromParent();
541 return false;
542 }
543
544 // Otherwise, can't handle this.
545 return true;
546 }
547
RemoveBranch(MachineBasicBlock & MBB) const548 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
549 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
550 if (I == MBB.end())
551 return 0;
552
553 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
554 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
555 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
556 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
557 return 0;
558
559 // Remove the branch.
560 I->eraseFromParent();
561
562 I = MBB.end();
563
564 if (I == MBB.begin()) return 1;
565 --I;
566 if (I->getOpcode() != PPC::BCC &&
567 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
568 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
569 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
570 return 1;
571
572 // Remove the branch.
573 I->eraseFromParent();
574 return 2;
575 }
576
577 unsigned
InsertBranch(MachineBasicBlock & MBB,MachineBasicBlock * TBB,MachineBasicBlock * FBB,ArrayRef<MachineOperand> Cond,DebugLoc DL) const578 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
579 MachineBasicBlock *FBB,
580 ArrayRef<MachineOperand> Cond,
581 DebugLoc DL) const {
582 // Shouldn't be a fall through.
583 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
584 assert((Cond.size() == 2 || Cond.size() == 0) &&
585 "PPC branch conditions have two components!");
586
587 bool isPPC64 = Subtarget.isPPC64();
588
589 // One-way branch.
590 if (!FBB) {
591 if (Cond.empty()) // Unconditional branch
592 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
593 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
594 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
595 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
596 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
597 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
598 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
599 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
600 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
601 else // Conditional branch
602 BuildMI(&MBB, DL, get(PPC::BCC))
603 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
604 return 1;
605 }
606
607 // Two-way Conditional Branch.
608 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
609 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
610 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
611 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
612 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
613 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
614 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
615 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
616 else
617 BuildMI(&MBB, DL, get(PPC::BCC))
618 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
619 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
620 return 2;
621 }
622
623 // Select analysis.
canInsertSelect(const MachineBasicBlock & MBB,ArrayRef<MachineOperand> Cond,unsigned TrueReg,unsigned FalseReg,int & CondCycles,int & TrueCycles,int & FalseCycles) const624 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
625 ArrayRef<MachineOperand> Cond,
626 unsigned TrueReg, unsigned FalseReg,
627 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
628 if (!Subtarget.hasISEL())
629 return false;
630
631 if (Cond.size() != 2)
632 return false;
633
634 // If this is really a bdnz-like condition, then it cannot be turned into a
635 // select.
636 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
637 return false;
638
639 // Check register classes.
640 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
641 const TargetRegisterClass *RC =
642 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
643 if (!RC)
644 return false;
645
646 // isel is for regular integer GPRs only.
647 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
648 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
649 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
650 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
651 return false;
652
653 // FIXME: These numbers are for the A2, how well they work for other cores is
654 // an open question. On the A2, the isel instruction has a 2-cycle latency
655 // but single-cycle throughput. These numbers are used in combination with
656 // the MispredictPenalty setting from the active SchedMachineModel.
657 CondCycles = 1;
658 TrueCycles = 1;
659 FalseCycles = 1;
660
661 return true;
662 }
663
insertSelect(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,DebugLoc dl,unsigned DestReg,ArrayRef<MachineOperand> Cond,unsigned TrueReg,unsigned FalseReg) const664 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
665 MachineBasicBlock::iterator MI, DebugLoc dl,
666 unsigned DestReg, ArrayRef<MachineOperand> Cond,
667 unsigned TrueReg, unsigned FalseReg) const {
668 assert(Cond.size() == 2 &&
669 "PPC branch conditions have two components!");
670
671 assert(Subtarget.hasISEL() &&
672 "Cannot insert select on target without ISEL support");
673
674 // Get the register classes.
675 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
676 const TargetRegisterClass *RC =
677 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
678 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
679
680 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
681 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
682 assert((Is64Bit ||
683 PPC::GPRCRegClass.hasSubClassEq(RC) ||
684 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
685 "isel is for regular integer GPRs only");
686
687 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
688 unsigned SelectPred = Cond[0].getImm();
689
690 unsigned SubIdx;
691 bool SwapOps;
692 switch (SelectPred) {
693 default: llvm_unreachable("invalid predicate for isel");
694 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
695 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
696 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
697 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
698 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
699 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
700 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
701 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
702 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
703 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
704 }
705
706 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
707 SecondReg = SwapOps ? TrueReg : FalseReg;
708
709 // The first input register of isel cannot be r0. If it is a member
710 // of a register class that can be r0, then copy it first (the
711 // register allocator should eliminate the copy).
712 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
713 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
714 const TargetRegisterClass *FirstRC =
715 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
716 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
717 unsigned OldFirstReg = FirstReg;
718 FirstReg = MRI.createVirtualRegister(FirstRC);
719 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
720 .addReg(OldFirstReg);
721 }
722
723 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
724 .addReg(FirstReg).addReg(SecondReg)
725 .addReg(Cond[1].getReg(), 0, SubIdx);
726 }
727
getCRBitValue(unsigned CRBit)728 static unsigned getCRBitValue(unsigned CRBit) {
729 unsigned Ret = 4;
730 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
731 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
732 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
733 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
734 Ret = 3;
735 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
736 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
737 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
738 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
739 Ret = 2;
740 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
741 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
742 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
743 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
744 Ret = 1;
745 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
746 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
747 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
748 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
749 Ret = 0;
750
751 assert(Ret != 4 && "Invalid CR bit register");
752 return Ret;
753 }
754
copyPhysReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,DebugLoc DL,unsigned DestReg,unsigned SrcReg,bool KillSrc) const755 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
756 MachineBasicBlock::iterator I, DebugLoc DL,
757 unsigned DestReg, unsigned SrcReg,
758 bool KillSrc) const {
759 // We can end up with self copies and similar things as a result of VSX copy
760 // legalization. Promote them here.
761 const TargetRegisterInfo *TRI = &getRegisterInfo();
762 if (PPC::F8RCRegClass.contains(DestReg) &&
763 PPC::VSRCRegClass.contains(SrcReg)) {
764 unsigned SuperReg =
765 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
766
767 if (VSXSelfCopyCrash && SrcReg == SuperReg)
768 llvm_unreachable("nop VSX copy");
769
770 DestReg = SuperReg;
771 } else if (PPC::VRRCRegClass.contains(DestReg) &&
772 PPC::VSRCRegClass.contains(SrcReg)) {
773 unsigned SuperReg =
774 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
775
776 if (VSXSelfCopyCrash && SrcReg == SuperReg)
777 llvm_unreachable("nop VSX copy");
778
779 DestReg = SuperReg;
780 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
781 PPC::VSRCRegClass.contains(DestReg)) {
782 unsigned SuperReg =
783 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
784
785 if (VSXSelfCopyCrash && DestReg == SuperReg)
786 llvm_unreachable("nop VSX copy");
787
788 SrcReg = SuperReg;
789 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
790 PPC::VSRCRegClass.contains(DestReg)) {
791 unsigned SuperReg =
792 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
793
794 if (VSXSelfCopyCrash && DestReg == SuperReg)
795 llvm_unreachable("nop VSX copy");
796
797 SrcReg = SuperReg;
798 }
799
800 // Different class register copy
801 if (PPC::CRBITRCRegClass.contains(SrcReg) &&
802 PPC::GPRCRegClass.contains(DestReg)) {
803 unsigned CRReg = getCRFromCRBit(SrcReg);
804 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
805 .addReg(CRReg), getKillRegState(KillSrc);
806 // Rotate the CR bit in the CR fields to be the least significant bit and
807 // then mask with 0x1 (MB = ME = 31).
808 BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
809 .addReg(DestReg, RegState::Kill)
810 .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
811 .addImm(31)
812 .addImm(31);
813 return;
814 } else if (PPC::CRRCRegClass.contains(SrcReg) &&
815 PPC::G8RCRegClass.contains(DestReg)) {
816 BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg)
817 .addReg(SrcReg), getKillRegState(KillSrc);
818 return;
819 } else if (PPC::CRRCRegClass.contains(SrcReg) &&
820 PPC::GPRCRegClass.contains(DestReg)) {
821 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
822 .addReg(SrcReg), getKillRegState(KillSrc);
823 return;
824 }
825
826 unsigned Opc;
827 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
828 Opc = PPC::OR;
829 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
830 Opc = PPC::OR8;
831 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
832 Opc = PPC::FMR;
833 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
834 Opc = PPC::MCRF;
835 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
836 Opc = PPC::VOR;
837 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
838 // There are two different ways this can be done:
839 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
840 // issue in VSU pipeline 0.
841 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
842 // can go to either pipeline.
843 // We'll always use xxlor here, because in practically all cases where
844 // copies are generated, they are close enough to some use that the
845 // lower-latency form is preferable.
846 Opc = PPC::XXLOR;
847 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
848 PPC::VSSRCRegClass.contains(DestReg, SrcReg))
849 Opc = PPC::XXLORf;
850 else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
851 Opc = PPC::QVFMR;
852 else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
853 Opc = PPC::QVFMRs;
854 else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
855 Opc = PPC::QVFMRb;
856 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
857 Opc = PPC::CROR;
858 else
859 llvm_unreachable("Impossible reg-to-reg copy");
860
861 const MCInstrDesc &MCID = get(Opc);
862 if (MCID.getNumOperands() == 3)
863 BuildMI(MBB, I, DL, MCID, DestReg)
864 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
865 else
866 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
867 }
868
869 // This function returns true if a CR spill is necessary and false otherwise.
870 bool
StoreRegToStackSlot(MachineFunction & MF,unsigned SrcReg,bool isKill,int FrameIdx,const TargetRegisterClass * RC,SmallVectorImpl<MachineInstr * > & NewMIs,bool & NonRI,bool & SpillsVRS) const871 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
872 unsigned SrcReg, bool isKill,
873 int FrameIdx,
874 const TargetRegisterClass *RC,
875 SmallVectorImpl<MachineInstr*> &NewMIs,
876 bool &NonRI, bool &SpillsVRS) const{
877 // Note: If additional store instructions are added here,
878 // update isStoreToStackSlot.
879
880 DebugLoc DL;
881 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
882 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
883 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
884 .addReg(SrcReg,
885 getKillRegState(isKill)),
886 FrameIdx));
887 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
888 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
889 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
890 .addReg(SrcReg,
891 getKillRegState(isKill)),
892 FrameIdx));
893 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
894 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
895 .addReg(SrcReg,
896 getKillRegState(isKill)),
897 FrameIdx));
898 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
899 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
900 .addReg(SrcReg,
901 getKillRegState(isKill)),
902 FrameIdx));
903 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
904 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
905 .addReg(SrcReg,
906 getKillRegState(isKill)),
907 FrameIdx));
908 return true;
909 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
910 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
911 .addReg(SrcReg,
912 getKillRegState(isKill)),
913 FrameIdx));
914 return true;
915 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
916 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
917 .addReg(SrcReg,
918 getKillRegState(isKill)),
919 FrameIdx));
920 NonRI = true;
921 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
922 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
923 .addReg(SrcReg,
924 getKillRegState(isKill)),
925 FrameIdx));
926 NonRI = true;
927 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
928 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
929 .addReg(SrcReg,
930 getKillRegState(isKill)),
931 FrameIdx));
932 NonRI = true;
933 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
934 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSSPX))
935 .addReg(SrcReg,
936 getKillRegState(isKill)),
937 FrameIdx));
938 NonRI = true;
939 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
940 assert(Subtarget.isDarwin() &&
941 "VRSAVE only needs spill/restore on Darwin");
942 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
943 .addReg(SrcReg,
944 getKillRegState(isKill)),
945 FrameIdx));
946 SpillsVRS = true;
947 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
948 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
949 .addReg(SrcReg,
950 getKillRegState(isKill)),
951 FrameIdx));
952 NonRI = true;
953 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
954 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
955 .addReg(SrcReg,
956 getKillRegState(isKill)),
957 FrameIdx));
958 NonRI = true;
959 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
960 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
961 .addReg(SrcReg,
962 getKillRegState(isKill)),
963 FrameIdx));
964 NonRI = true;
965 } else {
966 llvm_unreachable("Unknown regclass!");
967 }
968
969 return false;
970 }
971
972 void
storeRegToStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned SrcReg,bool isKill,int FrameIdx,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const973 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
974 MachineBasicBlock::iterator MI,
975 unsigned SrcReg, bool isKill, int FrameIdx,
976 const TargetRegisterClass *RC,
977 const TargetRegisterInfo *TRI) const {
978 MachineFunction &MF = *MBB.getParent();
979 SmallVector<MachineInstr*, 4> NewMIs;
980
981 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
982 FuncInfo->setHasSpills();
983
984 bool NonRI = false, SpillsVRS = false;
985 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
986 NonRI, SpillsVRS))
987 FuncInfo->setSpillsCR();
988
989 if (SpillsVRS)
990 FuncInfo->setSpillsVRSAVE();
991
992 if (NonRI)
993 FuncInfo->setHasNonRISpills();
994
995 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
996 MBB.insert(MI, NewMIs[i]);
997
998 const MachineFrameInfo &MFI = *MF.getFrameInfo();
999 MachineMemOperand *MMO =
1000 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
1001 MachineMemOperand::MOStore,
1002 MFI.getObjectSize(FrameIdx),
1003 MFI.getObjectAlignment(FrameIdx));
1004 NewMIs.back()->addMemOperand(MF, MMO);
1005 }
1006
1007 bool
LoadRegFromStackSlot(MachineFunction & MF,DebugLoc DL,unsigned DestReg,int FrameIdx,const TargetRegisterClass * RC,SmallVectorImpl<MachineInstr * > & NewMIs,bool & NonRI,bool & SpillsVRS) const1008 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
1009 unsigned DestReg, int FrameIdx,
1010 const TargetRegisterClass *RC,
1011 SmallVectorImpl<MachineInstr*> &NewMIs,
1012 bool &NonRI, bool &SpillsVRS) const{
1013 // Note: If additional load instructions are added here,
1014 // update isLoadFromStackSlot.
1015
1016 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1017 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1018 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
1019 DestReg), FrameIdx));
1020 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1021 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1022 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
1023 FrameIdx));
1024 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1025 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
1026 FrameIdx));
1027 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1028 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
1029 FrameIdx));
1030 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1031 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1032 get(PPC::RESTORE_CR), DestReg),
1033 FrameIdx));
1034 return true;
1035 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1036 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1037 get(PPC::RESTORE_CRBIT), DestReg),
1038 FrameIdx));
1039 return true;
1040 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1041 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
1042 FrameIdx));
1043 NonRI = true;
1044 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1045 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
1046 FrameIdx));
1047 NonRI = true;
1048 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1049 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
1050 FrameIdx));
1051 NonRI = true;
1052 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1053 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSSPX), DestReg),
1054 FrameIdx));
1055 NonRI = true;
1056 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1057 assert(Subtarget.isDarwin() &&
1058 "VRSAVE only needs spill/restore on Darwin");
1059 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1060 get(PPC::RESTORE_VRSAVE),
1061 DestReg),
1062 FrameIdx));
1063 SpillsVRS = true;
1064 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1065 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
1066 FrameIdx));
1067 NonRI = true;
1068 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1069 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
1070 FrameIdx));
1071 NonRI = true;
1072 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1073 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
1074 FrameIdx));
1075 NonRI = true;
1076 } else {
1077 llvm_unreachable("Unknown regclass!");
1078 }
1079
1080 return false;
1081 }
1082
1083 void
loadRegFromStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned DestReg,int FrameIdx,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const1084 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1085 MachineBasicBlock::iterator MI,
1086 unsigned DestReg, int FrameIdx,
1087 const TargetRegisterClass *RC,
1088 const TargetRegisterInfo *TRI) const {
1089 MachineFunction &MF = *MBB.getParent();
1090 SmallVector<MachineInstr*, 4> NewMIs;
1091 DebugLoc DL;
1092 if (MI != MBB.end()) DL = MI->getDebugLoc();
1093
1094 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1095 FuncInfo->setHasSpills();
1096
1097 bool NonRI = false, SpillsVRS = false;
1098 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
1099 NonRI, SpillsVRS))
1100 FuncInfo->setSpillsCR();
1101
1102 if (SpillsVRS)
1103 FuncInfo->setSpillsVRSAVE();
1104
1105 if (NonRI)
1106 FuncInfo->setHasNonRISpills();
1107
1108 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1109 MBB.insert(MI, NewMIs[i]);
1110
1111 const MachineFrameInfo &MFI = *MF.getFrameInfo();
1112 MachineMemOperand *MMO =
1113 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
1114 MachineMemOperand::MOLoad,
1115 MFI.getObjectSize(FrameIdx),
1116 MFI.getObjectAlignment(FrameIdx));
1117 NewMIs.back()->addMemOperand(MF, MMO);
1118 }
1119
1120 bool PPCInstrInfo::
ReverseBranchCondition(SmallVectorImpl<MachineOperand> & Cond) const1121 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1122 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1123 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1124 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1125 else
1126 // Leave the CR# the same, but invert the condition.
1127 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1128 return false;
1129 }
1130
FoldImmediate(MachineInstr * UseMI,MachineInstr * DefMI,unsigned Reg,MachineRegisterInfo * MRI) const1131 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
1132 unsigned Reg, MachineRegisterInfo *MRI) const {
1133 // For some instructions, it is legal to fold ZERO into the RA register field.
1134 // A zero immediate should always be loaded with a single li.
1135 unsigned DefOpc = DefMI->getOpcode();
1136 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1137 return false;
1138 if (!DefMI->getOperand(1).isImm())
1139 return false;
1140 if (DefMI->getOperand(1).getImm() != 0)
1141 return false;
1142
1143 // Note that we cannot here invert the arguments of an isel in order to fold
1144 // a ZERO into what is presented as the second argument. All we have here
1145 // is the condition bit, and that might come from a CR-logical bit operation.
1146
1147 const MCInstrDesc &UseMCID = UseMI->getDesc();
1148
1149 // Only fold into real machine instructions.
1150 if (UseMCID.isPseudo())
1151 return false;
1152
1153 unsigned UseIdx;
1154 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1155 if (UseMI->getOperand(UseIdx).isReg() &&
1156 UseMI->getOperand(UseIdx).getReg() == Reg)
1157 break;
1158
1159 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1160 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1161
1162 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1163
1164 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1165 // register (which might also be specified as a pointer class kind).
1166 if (UseInfo->isLookupPtrRegClass()) {
1167 if (UseInfo->RegClass /* Kind */ != 1)
1168 return false;
1169 } else {
1170 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1171 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1172 return false;
1173 }
1174
1175 // Make sure this is not tied to an output register (or otherwise
1176 // constrained). This is true for ST?UX registers, for example, which
1177 // are tied to their output registers.
1178 if (UseInfo->Constraints != 0)
1179 return false;
1180
1181 unsigned ZeroReg;
1182 if (UseInfo->isLookupPtrRegClass()) {
1183 bool isPPC64 = Subtarget.isPPC64();
1184 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1185 } else {
1186 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1187 PPC::ZERO8 : PPC::ZERO;
1188 }
1189
1190 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1191 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1192
1193 if (DeleteDef)
1194 DefMI->eraseFromParent();
1195
1196 return true;
1197 }
1198
MBBDefinesCTR(MachineBasicBlock & MBB)1199 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1200 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1201 I != IE; ++I)
1202 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1203 return true;
1204 return false;
1205 }
1206
1207 // We should make sure that, if we're going to predicate both sides of a
1208 // condition (a diamond), that both sides don't define the counter register. We
1209 // can predicate counter-decrement-based branches, but while that predicates
1210 // the branching, it does not predicate the counter decrement. If we tried to
1211 // merge the triangle into one predicated block, we'd decrement the counter
1212 // twice.
isProfitableToIfCvt(MachineBasicBlock & TMBB,unsigned NumT,unsigned ExtraT,MachineBasicBlock & FMBB,unsigned NumF,unsigned ExtraF,const BranchProbability & Probability) const1213 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1214 unsigned NumT, unsigned ExtraT,
1215 MachineBasicBlock &FMBB,
1216 unsigned NumF, unsigned ExtraF,
1217 const BranchProbability &Probability) const {
1218 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1219 }
1220
1221
isPredicated(const MachineInstr * MI) const1222 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1223 // The predicated branches are identified by their type, not really by the
1224 // explicit presence of a predicate. Furthermore, some of them can be
1225 // predicated more than once. Because if conversion won't try to predicate
1226 // any instruction which already claims to be predicated (by returning true
1227 // here), always return false. In doing so, we let isPredicable() be the
1228 // final word on whether not the instruction can be (further) predicated.
1229
1230 return false;
1231 }
1232
isUnpredicatedTerminator(const MachineInstr * MI) const1233 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1234 if (!MI->isTerminator())
1235 return false;
1236
1237 // Conditional branch is a special case.
1238 if (MI->isBranch() && !MI->isBarrier())
1239 return true;
1240
1241 return !isPredicated(MI);
1242 }
1243
PredicateInstruction(MachineInstr * MI,ArrayRef<MachineOperand> Pred) const1244 bool PPCInstrInfo::PredicateInstruction(MachineInstr *MI,
1245 ArrayRef<MachineOperand> Pred) const {
1246 unsigned OpC = MI->getOpcode();
1247 if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1248 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1249 bool isPPC64 = Subtarget.isPPC64();
1250 MI->setDesc(get(Pred[0].getImm() ?
1251 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1252 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1253 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1254 MI->setDesc(get(PPC::BCLR));
1255 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1256 .addReg(Pred[1].getReg());
1257 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1258 MI->setDesc(get(PPC::BCLRn));
1259 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1260 .addReg(Pred[1].getReg());
1261 } else {
1262 MI->setDesc(get(PPC::BCCLR));
1263 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1264 .addImm(Pred[0].getImm())
1265 .addReg(Pred[1].getReg());
1266 }
1267
1268 return true;
1269 } else if (OpC == PPC::B) {
1270 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1271 bool isPPC64 = Subtarget.isPPC64();
1272 MI->setDesc(get(Pred[0].getImm() ?
1273 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1274 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1275 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1276 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1277 MI->RemoveOperand(0);
1278
1279 MI->setDesc(get(PPC::BC));
1280 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1281 .addReg(Pred[1].getReg())
1282 .addMBB(MBB);
1283 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1284 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1285 MI->RemoveOperand(0);
1286
1287 MI->setDesc(get(PPC::BCn));
1288 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1289 .addReg(Pred[1].getReg())
1290 .addMBB(MBB);
1291 } else {
1292 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1293 MI->RemoveOperand(0);
1294
1295 MI->setDesc(get(PPC::BCC));
1296 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1297 .addImm(Pred[0].getImm())
1298 .addReg(Pred[1].getReg())
1299 .addMBB(MBB);
1300 }
1301
1302 return true;
1303 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1304 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1305 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1306 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1307
1308 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1309 bool isPPC64 = Subtarget.isPPC64();
1310
1311 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1312 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1313 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1314 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1315 .addReg(Pred[1].getReg());
1316 return true;
1317 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1318 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1319 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1320 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1321 .addReg(Pred[1].getReg());
1322 return true;
1323 }
1324
1325 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1326 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1327 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1328 .addImm(Pred[0].getImm())
1329 .addReg(Pred[1].getReg());
1330 return true;
1331 }
1332
1333 return false;
1334 }
1335
SubsumesPredicate(ArrayRef<MachineOperand> Pred1,ArrayRef<MachineOperand> Pred2) const1336 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1337 ArrayRef<MachineOperand> Pred2) const {
1338 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1339 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1340
1341 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1342 return false;
1343 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1344 return false;
1345
1346 // P1 can only subsume P2 if they test the same condition register.
1347 if (Pred1[1].getReg() != Pred2[1].getReg())
1348 return false;
1349
1350 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1351 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1352
1353 if (P1 == P2)
1354 return true;
1355
1356 // Does P1 subsume P2, e.g. GE subsumes GT.
1357 if (P1 == PPC::PRED_LE &&
1358 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1359 return true;
1360 if (P1 == PPC::PRED_GE &&
1361 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1362 return true;
1363
1364 return false;
1365 }
1366
DefinesPredicate(MachineInstr * MI,std::vector<MachineOperand> & Pred) const1367 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1368 std::vector<MachineOperand> &Pred) const {
1369 // Note: At the present time, the contents of Pred from this function is
1370 // unused by IfConversion. This implementation follows ARM by pushing the
1371 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1372 // predicate, instructions defining CTR or CTR8 are also included as
1373 // predicate-defining instructions.
1374
1375 const TargetRegisterClass *RCs[] =
1376 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1377 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1378
1379 bool Found = false;
1380 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1381 const MachineOperand &MO = MI->getOperand(i);
1382 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1383 const TargetRegisterClass *RC = RCs[c];
1384 if (MO.isReg()) {
1385 if (MO.isDef() && RC->contains(MO.getReg())) {
1386 Pred.push_back(MO);
1387 Found = true;
1388 }
1389 } else if (MO.isRegMask()) {
1390 for (TargetRegisterClass::iterator I = RC->begin(),
1391 IE = RC->end(); I != IE; ++I)
1392 if (MO.clobbersPhysReg(*I)) {
1393 Pred.push_back(MO);
1394 Found = true;
1395 }
1396 }
1397 }
1398 }
1399
1400 return Found;
1401 }
1402
isPredicable(MachineInstr * MI) const1403 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1404 unsigned OpC = MI->getOpcode();
1405 switch (OpC) {
1406 default:
1407 return false;
1408 case PPC::B:
1409 case PPC::BLR:
1410 case PPC::BLR8:
1411 case PPC::BCTR:
1412 case PPC::BCTR8:
1413 case PPC::BCTRL:
1414 case PPC::BCTRL8:
1415 return true;
1416 }
1417 }
1418
analyzeCompare(const MachineInstr * MI,unsigned & SrcReg,unsigned & SrcReg2,int & Mask,int & Value) const1419 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1420 unsigned &SrcReg, unsigned &SrcReg2,
1421 int &Mask, int &Value) const {
1422 unsigned Opc = MI->getOpcode();
1423
1424 switch (Opc) {
1425 default: return false;
1426 case PPC::CMPWI:
1427 case PPC::CMPLWI:
1428 case PPC::CMPDI:
1429 case PPC::CMPLDI:
1430 SrcReg = MI->getOperand(1).getReg();
1431 SrcReg2 = 0;
1432 Value = MI->getOperand(2).getImm();
1433 Mask = 0xFFFF;
1434 return true;
1435 case PPC::CMPW:
1436 case PPC::CMPLW:
1437 case PPC::CMPD:
1438 case PPC::CMPLD:
1439 case PPC::FCMPUS:
1440 case PPC::FCMPUD:
1441 SrcReg = MI->getOperand(1).getReg();
1442 SrcReg2 = MI->getOperand(2).getReg();
1443 return true;
1444 }
1445 }
1446
optimizeCompareInstr(MachineInstr * CmpInstr,unsigned SrcReg,unsigned SrcReg2,int Mask,int Value,const MachineRegisterInfo * MRI) const1447 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1448 unsigned SrcReg, unsigned SrcReg2,
1449 int Mask, int Value,
1450 const MachineRegisterInfo *MRI) const {
1451 if (DisableCmpOpt)
1452 return false;
1453
1454 int OpC = CmpInstr->getOpcode();
1455 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1456
1457 // FP record forms set CR1 based on the execption status bits, not a
1458 // comparison with zero.
1459 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1460 return false;
1461
1462 // The record forms set the condition register based on a signed comparison
1463 // with zero (so says the ISA manual). This is not as straightforward as it
1464 // seems, however, because this is always a 64-bit comparison on PPC64, even
1465 // for instructions that are 32-bit in nature (like slw for example).
1466 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1467 // for equality checks (as those don't depend on the sign). On PPC64,
1468 // we are restricted to equality for unsigned 64-bit comparisons and for
1469 // signed 32-bit comparisons the applicability is more restricted.
1470 bool isPPC64 = Subtarget.isPPC64();
1471 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1472 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1473 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1474
1475 // Get the unique definition of SrcReg.
1476 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1477 if (!MI) return false;
1478 int MIOpC = MI->getOpcode();
1479
1480 bool equalityOnly = false;
1481 bool noSub = false;
1482 if (isPPC64) {
1483 if (is32BitSignedCompare) {
1484 // We can perform this optimization only if MI is sign-extending.
1485 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1486 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1487 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1488 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1489 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1490 noSub = true;
1491 } else
1492 return false;
1493 } else if (is32BitUnsignedCompare) {
1494 // We can perform this optimization, equality only, if MI is
1495 // zero-extending.
1496 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1497 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1498 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1499 noSub = true;
1500 equalityOnly = true;
1501 } else
1502 return false;
1503 } else
1504 equalityOnly = is64BitUnsignedCompare;
1505 } else
1506 equalityOnly = is32BitUnsignedCompare;
1507
1508 if (equalityOnly) {
1509 // We need to check the uses of the condition register in order to reject
1510 // non-equality comparisons.
1511 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1512 IE = MRI->use_instr_end(); I != IE; ++I) {
1513 MachineInstr *UseMI = &*I;
1514 if (UseMI->getOpcode() == PPC::BCC) {
1515 unsigned Pred = UseMI->getOperand(0).getImm();
1516 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1517 return false;
1518 } else if (UseMI->getOpcode() == PPC::ISEL ||
1519 UseMI->getOpcode() == PPC::ISEL8) {
1520 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1521 if (SubIdx != PPC::sub_eq)
1522 return false;
1523 } else
1524 return false;
1525 }
1526 }
1527
1528 MachineBasicBlock::iterator I = CmpInstr;
1529
1530 // Scan forward to find the first use of the compare.
1531 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1532 I != EL; ++I) {
1533 bool FoundUse = false;
1534 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1535 JE = MRI->use_instr_end(); J != JE; ++J)
1536 if (&*J == &*I) {
1537 FoundUse = true;
1538 break;
1539 }
1540
1541 if (FoundUse)
1542 break;
1543 }
1544
1545 // There are two possible candidates which can be changed to set CR[01].
1546 // One is MI, the other is a SUB instruction.
1547 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1548 MachineInstr *Sub = nullptr;
1549 if (SrcReg2 != 0)
1550 // MI is not a candidate for CMPrr.
1551 MI = nullptr;
1552 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1553 // same BB as the comparison. This is to allow the check below to avoid calls
1554 // (and other explicit clobbers); instead we should really check for these
1555 // more explicitly (in at least a few predecessors).
1556 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1557 // PPC does not have a record-form SUBri.
1558 return false;
1559 }
1560
1561 // Search for Sub.
1562 const TargetRegisterInfo *TRI = &getRegisterInfo();
1563 --I;
1564
1565 // Get ready to iterate backward from CmpInstr.
1566 MachineBasicBlock::iterator E = MI,
1567 B = CmpInstr->getParent()->begin();
1568
1569 for (; I != E && !noSub; --I) {
1570 const MachineInstr &Instr = *I;
1571 unsigned IOpC = Instr.getOpcode();
1572
1573 if (&*I != CmpInstr && (
1574 Instr.modifiesRegister(PPC::CR0, TRI) ||
1575 Instr.readsRegister(PPC::CR0, TRI)))
1576 // This instruction modifies or uses the record condition register after
1577 // the one we want to change. While we could do this transformation, it
1578 // would likely not be profitable. This transformation removes one
1579 // instruction, and so even forcing RA to generate one move probably
1580 // makes it unprofitable.
1581 return false;
1582
1583 // Check whether CmpInstr can be made redundant by the current instruction.
1584 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1585 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1586 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1587 ((Instr.getOperand(1).getReg() == SrcReg &&
1588 Instr.getOperand(2).getReg() == SrcReg2) ||
1589 (Instr.getOperand(1).getReg() == SrcReg2 &&
1590 Instr.getOperand(2).getReg() == SrcReg))) {
1591 Sub = &*I;
1592 break;
1593 }
1594
1595 if (I == B)
1596 // The 'and' is below the comparison instruction.
1597 return false;
1598 }
1599
1600 // Return false if no candidates exist.
1601 if (!MI && !Sub)
1602 return false;
1603
1604 // The single candidate is called MI.
1605 if (!MI) MI = Sub;
1606
1607 int NewOpC = -1;
1608 MIOpC = MI->getOpcode();
1609 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1610 NewOpC = MIOpC;
1611 else {
1612 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1613 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1614 NewOpC = MIOpC;
1615 }
1616
1617 // FIXME: On the non-embedded POWER architectures, only some of the record
1618 // forms are fast, and we should use only the fast ones.
1619
1620 // The defining instruction has a record form (or is already a record
1621 // form). It is possible, however, that we'll need to reverse the condition
1622 // code of the users.
1623 if (NewOpC == -1)
1624 return false;
1625
1626 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1627 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1628
1629 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1630 // needs to be updated to be based on SUB. Push the condition code
1631 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1632 // condition code of these operands will be modified.
1633 bool ShouldSwap = false;
1634 if (Sub) {
1635 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1636 Sub->getOperand(2).getReg() == SrcReg;
1637
1638 // The operands to subf are the opposite of sub, so only in the fixed-point
1639 // case, invert the order.
1640 ShouldSwap = !ShouldSwap;
1641 }
1642
1643 if (ShouldSwap)
1644 for (MachineRegisterInfo::use_instr_iterator
1645 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1646 I != IE; ++I) {
1647 MachineInstr *UseMI = &*I;
1648 if (UseMI->getOpcode() == PPC::BCC) {
1649 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1650 assert((!equalityOnly ||
1651 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1652 "Invalid predicate for equality-only optimization");
1653 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1654 PPC::getSwappedPredicate(Pred)));
1655 } else if (UseMI->getOpcode() == PPC::ISEL ||
1656 UseMI->getOpcode() == PPC::ISEL8) {
1657 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1658 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1659 "Invalid CR bit for equality-only optimization");
1660
1661 if (NewSubReg == PPC::sub_lt)
1662 NewSubReg = PPC::sub_gt;
1663 else if (NewSubReg == PPC::sub_gt)
1664 NewSubReg = PPC::sub_lt;
1665
1666 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1667 NewSubReg));
1668 } else // We need to abort on a user we don't understand.
1669 return false;
1670 }
1671
1672 // Create a new virtual register to hold the value of the CR set by the
1673 // record-form instruction. If the instruction was not previously in
1674 // record form, then set the kill flag on the CR.
1675 CmpInstr->eraseFromParent();
1676
1677 MachineBasicBlock::iterator MII = MI;
1678 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1679 get(TargetOpcode::COPY), CRReg)
1680 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1681
1682 if (MIOpC != NewOpC) {
1683 // We need to be careful here: we're replacing one instruction with
1684 // another, and we need to make sure that we get all of the right
1685 // implicit uses and defs. On the other hand, the caller may be holding
1686 // an iterator to this instruction, and so we can't delete it (this is
1687 // specifically the case if this is the instruction directly after the
1688 // compare).
1689
1690 const MCInstrDesc &NewDesc = get(NewOpC);
1691 MI->setDesc(NewDesc);
1692
1693 if (NewDesc.ImplicitDefs)
1694 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1695 *ImpDefs; ++ImpDefs)
1696 if (!MI->definesRegister(*ImpDefs))
1697 MI->addOperand(*MI->getParent()->getParent(),
1698 MachineOperand::CreateReg(*ImpDefs, true, true));
1699 if (NewDesc.ImplicitUses)
1700 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1701 *ImpUses; ++ImpUses)
1702 if (!MI->readsRegister(*ImpUses))
1703 MI->addOperand(*MI->getParent()->getParent(),
1704 MachineOperand::CreateReg(*ImpUses, false, true));
1705 }
1706
1707 // Modify the condition code of operands in OperandsToUpdate.
1708 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1709 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1710 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1711 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1712
1713 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1714 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1715
1716 return true;
1717 }
1718
1719 /// GetInstSize - Return the number of bytes of code the specified
1720 /// instruction may be. This returns the maximum number of bytes.
1721 ///
GetInstSizeInBytes(const MachineInstr * MI) const1722 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1723 unsigned Opcode = MI->getOpcode();
1724
1725 if (Opcode == PPC::INLINEASM) {
1726 const MachineFunction *MF = MI->getParent()->getParent();
1727 const char *AsmStr = MI->getOperand(0).getSymbolName();
1728 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1729 } else if (Opcode == TargetOpcode::STACKMAP) {
1730 return MI->getOperand(1).getImm();
1731 } else if (Opcode == TargetOpcode::PATCHPOINT) {
1732 PatchPointOpers Opers(MI);
1733 return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
1734 } else {
1735 const MCInstrDesc &Desc = get(Opcode);
1736 return Desc.getSize();
1737 }
1738 }
1739
1740