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/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"
38
39 using namespace llvm;
40
41 #define DEBUG_TYPE "ppc-instr-info"
42
43 #define GET_INSTRMAP_INFO
44 #define GET_INSTRINFO_CTOR_DTOR
45 #include "PPCGenInstrInfo.inc"
46
47 static cl::
48 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
49 cl::desc("Disable analysis for CTR loops"));
50
51 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
52 cl::desc("Disable compare instruction optimization"), cl::Hidden);
53
54 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
55 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
56
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"),
59 cl::Hidden);
60
61 // Pin the vtable to this file.
anchor()62 void PPCInstrInfo::anchor() {}
63
PPCInstrInfo(PPCSubtarget & STI)64 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
65 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
66 Subtarget(STI), RI(STI) {}
67
68 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
69 /// this target when scheduling the DAG.
70 ScheduleHazardRecognizer *
CreateTargetHazardRecognizer(const TargetSubtargetInfo * STI,const ScheduleDAG * DAG) const71 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
72 const ScheduleDAG *DAG) const {
73 unsigned Directive =
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);
80 }
81
82 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
83 }
84
85 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
86 /// to use for this target when scheduling the DAG.
CreateTargetPostRAHazardRecognizer(const InstrItineraryData * II,const ScheduleDAG * DAG) const87 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
88 const InstrItineraryData *II,
89 const ScheduleDAG *DAG) const {
90 unsigned Directive =
91 DAG->TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
92
93 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
94 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
95
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?");
100
101 return new PPCHazardRecognizer970(*DAG);
102 }
103
104 return new ScoreboardHazardRecognizer(II, DAG);
105 }
106
107
getOperandLatency(const InstrItineraryData * ItinData,const MachineInstr * DefMI,unsigned DefIdx,const MachineInstr * UseMI,unsigned UseIdx) const108 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,
113 UseMI, UseIdx);
114
115 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
116 unsigned Reg = DefMO.getReg();
117
118 const TargetRegisterInfo *TRI = &getRegisterInfo();
119 bool IsRegCR;
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);
125 } else {
126 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
127 PPC::CRBITRCRegClass.contains(Reg);
128 }
129
130 if (UseMI->isBranch() && IsRegCR) {
131 if (Latency < 0)
132 Latency = getInstrLatency(ItinData, DefMI);
133
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();
137 switch (Directive) {
138 default: break;
139 case PPC::DIR_7400:
140 case PPC::DIR_750:
141 case PPC::DIR_970:
142 case PPC::DIR_E5500:
143 case PPC::DIR_PWR4:
144 case PPC::DIR_PWR5:
145 case PPC::DIR_PWR5X:
146 case PPC::DIR_PWR6:
147 case PPC::DIR_PWR6X:
148 case PPC::DIR_PWR7:
149 case PPC::DIR_PWR8:
150 Latency += 2;
151 break;
152 }
153 }
154
155 return Latency;
156 }
157
158 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
isCoalescableExtInstr(const MachineInstr & MI,unsigned & SrcReg,unsigned & DstReg,unsigned & SubIdx) const159 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
160 unsigned &SrcReg, unsigned &DstReg,
161 unsigned &SubIdx) const {
162 switch (MI.getOpcode()) {
163 default: return false;
164 case PPC::EXTSW:
165 case PPC::EXTSW_32_64:
166 SrcReg = MI.getOperand(1).getReg();
167 DstReg = MI.getOperand(0).getReg();
168 SubIdx = PPC::sub_32;
169 return true;
170 }
171 }
172
isLoadFromStackSlot(const MachineInstr * MI,int & FrameIndex) const173 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
174 int &FrameIndex) const {
175 // Note: This list must be kept consistent with LoadRegFromStackSlot.
176 switch (MI->getOpcode()) {
177 default: break;
178 case PPC::LD:
179 case PPC::LWZ:
180 case PPC::LFS:
181 case PPC::LFD:
182 case PPC::RESTORE_CR:
183 case PPC::RESTORE_CRBIT:
184 case PPC::LVX:
185 case PPC::LXVD2X:
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();
193 }
194 break;
195 }
196 return 0;
197 }
198
isStoreToStackSlot(const MachineInstr * MI,int & FrameIndex) const199 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
200 int &FrameIndex) const {
201 // Note: This list must be kept consistent with StoreRegToStackSlot.
202 switch (MI->getOpcode()) {
203 default: break;
204 case PPC::STD:
205 case PPC::STW:
206 case PPC::STFS:
207 case PPC::STFD:
208 case PPC::SPILL_CR:
209 case PPC::SPILL_CRBIT:
210 case PPC::STVX:
211 case PPC::STXVD2X:
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();
219 }
220 break;
221 }
222 return 0;
223 }
224
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.
227 MachineInstr *
commuteInstruction(MachineInstr * MI,bool NewMI) const228 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
229 MachineFunction &MF = *MI->getParent()->getParent();
230
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);
237
238 // Cannot commute if it has a non-zero rotate count.
239 if (MI->getOperand(3).getImm() != 0)
240 return nullptr;
241
242 // If we have a zero rotate count, we have:
243 // M = mask(MB,ME)
244 // Op0 = (Op1 & ~M) | (Op2 & M)
245 // Change this to:
246 // M = mask((ME+1)&31, (MB-1)&31)
247 // Op0 = (Op2 & ~M) | (Op1 & M)
248
249 // Swap op1/op2
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.
260 if (Reg0 == Reg1) {
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");
265 Reg2IsKill = false;
266 ChangeReg0 = true;
267 }
268
269 // Masks.
270 unsigned MB = MI->getOperand(4).getImm();
271 unsigned ME = MI->getOperand(5).getImm();
272
273 if (NewMI) {
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))
281 .addImm((ME+1) & 31)
282 .addImm((MB-1) & 31);
283 }
284
285 if (ChangeReg0) {
286 MI->getOperand(0).setReg(Reg2);
287 MI->getOperand(0).setSubReg(SubReg2);
288 }
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);
295
296 // Swap the mask around.
297 MI->getOperand(4).setImm((ME+1) & 31);
298 MI->getOperand(5).setImm((MB-1) & 31);
299 return MI;
300 }
301
findCommutedOpIndices(MachineInstr * MI,unsigned & SrcOpIdx1,unsigned & SrcOpIdx2) const302 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.
307
308 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
309 if (AltOpc == -1)
310 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
311
312 SrcOpIdx1 = 2;
313 SrcOpIdx2 = 3;
314 return true;
315 }
316
insertNoop(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI) const317 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();
322 unsigned Opcode;
323 switch (Directive) {
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 */
328 }
329
330 DebugLoc DL;
331 BuildMI(MBB, MI, DL, get(Opcode));
332 }
333
334 // Branch analysis.
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.
AnalyzeBranch(MachineBasicBlock & MBB,MachineBasicBlock * & TBB,MachineBasicBlock * & FBB,SmallVectorImpl<MachineOperand> & Cond,bool AllowModify) const337 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
338 MachineBasicBlock *&FBB,
339 SmallVectorImpl<MachineOperand> &Cond,
340 bool AllowModify) const {
341 bool isPPC64 = Subtarget.isPPC64();
342
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())
346 return false;
347 --I;
348 while (I->isDebugValue()) {
349 if (I == MBB.begin())
350 return false;
351 --I;
352 }
353 if (!isUnpredicatedTerminator(I))
354 return false;
355
356 // Get the last instruction in the block.
357 MachineInstr *LastInst = I;
358
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())
363 return true;
364 TBB = LastInst->getOperand(0).getMBB();
365 return false;
366 } else if (LastInst->getOpcode() == PPC::BCC) {
367 if (!LastInst->getOperand(2).isMBB())
368 return true;
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));
373 return false;
374 } else if (LastInst->getOpcode() == PPC::BC) {
375 if (!LastInst->getOperand(1).isMBB())
376 return true;
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));
381 return false;
382 } else if (LastInst->getOpcode() == PPC::BCn) {
383 if (!LastInst->getOperand(1).isMBB())
384 return true;
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));
389 return false;
390 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
391 LastInst->getOpcode() == PPC::BDNZ) {
392 if (!LastInst->getOperand(0).isMBB())
393 return true;
394 if (DisableCTRLoopAnal)
395 return true;
396 TBB = LastInst->getOperand(0).getMBB();
397 Cond.push_back(MachineOperand::CreateImm(1));
398 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
399 true));
400 return false;
401 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
402 LastInst->getOpcode() == PPC::BDZ) {
403 if (!LastInst->getOperand(0).isMBB())
404 return true;
405 if (DisableCTRLoopAnal)
406 return true;
407 TBB = LastInst->getOperand(0).getMBB();
408 Cond.push_back(MachineOperand::CreateImm(0));
409 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
410 true));
411 return false;
412 }
413
414 // Otherwise, don't know what this is.
415 return true;
416 }
417
418 // Get the instruction before it if it's a terminator.
419 MachineInstr *SecondLastInst = I;
420
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))
424 return true;
425
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())
431 return true;
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();
436 return false;
437 } else if (SecondLastInst->getOpcode() == PPC::BC &&
438 LastInst->getOpcode() == PPC::B) {
439 if (!SecondLastInst->getOperand(1).isMBB() ||
440 !LastInst->getOperand(0).isMBB())
441 return true;
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();
446 return false;
447 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
448 LastInst->getOpcode() == PPC::B) {
449 if (!SecondLastInst->getOperand(1).isMBB() ||
450 !LastInst->getOperand(0).isMBB())
451 return true;
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();
456 return false;
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())
462 return true;
463 if (DisableCTRLoopAnal)
464 return true;
465 TBB = SecondLastInst->getOperand(0).getMBB();
466 Cond.push_back(MachineOperand::CreateImm(1));
467 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
468 true));
469 FBB = LastInst->getOperand(0).getMBB();
470 return false;
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())
476 return true;
477 if (DisableCTRLoopAnal)
478 return true;
479 TBB = SecondLastInst->getOperand(0).getMBB();
480 Cond.push_back(MachineOperand::CreateImm(0));
481 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
482 true));
483 FBB = LastInst->getOperand(0).getMBB();
484 return false;
485 }
486
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())
492 return true;
493 TBB = SecondLastInst->getOperand(0).getMBB();
494 I = LastInst;
495 if (AllowModify)
496 I->eraseFromParent();
497 return false;
498 }
499
500 // Otherwise, can't handle this.
501 return true;
502 }
503
RemoveBranch(MachineBasicBlock & MBB) const504 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
505 MachineBasicBlock::iterator I = MBB.end();
506 if (I == MBB.begin()) return 0;
507 --I;
508 while (I->isDebugValue()) {
509 if (I == MBB.begin())
510 return 0;
511 --I;
512 }
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)
517 return 0;
518
519 // Remove the branch.
520 I->eraseFromParent();
521
522 I = MBB.end();
523
524 if (I == MBB.begin()) return 1;
525 --I;
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)
530 return 1;
531
532 // Remove the branch.
533 I->eraseFromParent();
534 return 2;
535 }
536
537 unsigned
InsertBranch(MachineBasicBlock & MBB,MachineBasicBlock * TBB,MachineBasicBlock * FBB,const SmallVectorImpl<MachineOperand> & Cond,DebugLoc DL) const538 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
539 MachineBasicBlock *FBB,
540 const SmallVectorImpl<MachineOperand> &Cond,
541 DebugLoc DL) const {
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!");
546
547 bool isPPC64 = Subtarget.isPPC64();
548
549 // One-way branch.
550 if (!FBB) {
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);
564 return 1;
565 }
566
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);
576 else
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);
580 return 2;
581 }
582
583 // Select analysis.
canInsertSelect(const MachineBasicBlock & MBB,const SmallVectorImpl<MachineOperand> & Cond,unsigned TrueReg,unsigned FalseReg,int & CondCycles,int & TrueCycles,int & FalseCycles) const584 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())
589 return false;
590
591 if (Cond.size() != 2)
592 return false;
593
594 // If this is really a bdnz-like condition, then it cannot be turned into a
595 // select.
596 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
597 return false;
598
599 // Check register classes.
600 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
601 const TargetRegisterClass *RC =
602 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
603 if (!RC)
604 return false;
605
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))
611 return false;
612
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.
617 CondCycles = 1;
618 TrueCycles = 1;
619 FalseCycles = 1;
620
621 return true;
622 }
623
insertSelect(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,DebugLoc dl,unsigned DestReg,const SmallVectorImpl<MachineOperand> & Cond,unsigned TrueReg,unsigned FalseReg) const624 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
625 MachineBasicBlock::iterator MI, DebugLoc dl,
626 unsigned DestReg,
627 const SmallVectorImpl<MachineOperand> &Cond,
628 unsigned TrueReg, unsigned FalseReg) const {
629 assert(Cond.size() == 2 &&
630 "PPC branch conditions have two components!");
631
632 assert(Subtarget.hasISEL() &&
633 "Cannot insert select on target without ISEL support");
634
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");
640
641 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
642 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
643 assert((Is64Bit ||
644 PPC::GPRCRegClass.hasSubClassEq(RC) ||
645 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
646 "isel is for regular integer GPRs only");
647
648 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
649 unsigned SelectPred = Cond[0].getImm();
650
651 unsigned SubIdx;
652 bool SwapOps;
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;
665 }
666
667 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
668 SecondReg = SwapOps ? TrueReg : FalseReg;
669
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);
682 }
683
684 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
685 .addReg(FirstReg).addReg(SecondReg)
686 .addReg(Cond[1].getReg(), 0, SubIdx);
687 }
688
copyPhysReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,DebugLoc DL,unsigned DestReg,unsigned SrcReg,bool KillSrc) const689 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)) {
698 unsigned SuperReg =
699 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
700
701 if (VSXSelfCopyCrash && SrcReg == SuperReg)
702 llvm_unreachable("nop VSX copy");
703
704 DestReg = SuperReg;
705 } else if (PPC::VRRCRegClass.contains(DestReg) &&
706 PPC::VSHRCRegClass.contains(SrcReg)) {
707 unsigned SuperReg =
708 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
709
710 if (VSXSelfCopyCrash && SrcReg == SuperReg)
711 llvm_unreachable("nop VSX copy");
712
713 DestReg = SuperReg;
714 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
715 PPC::VSLRCRegClass.contains(DestReg)) {
716 unsigned SuperReg =
717 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
718
719 if (VSXSelfCopyCrash && DestReg == SuperReg)
720 llvm_unreachable("nop VSX copy");
721
722 SrcReg = SuperReg;
723 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
724 PPC::VSHRCRegClass.contains(DestReg)) {
725 unsigned SuperReg =
726 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
727
728 if (VSXSelfCopyCrash && DestReg == SuperReg)
729 llvm_unreachable("nop VSX copy");
730
731 SrcReg = SuperReg;
732 }
733
734 unsigned Opc;
735 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
736 Opc = PPC::OR;
737 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
738 Opc = PPC::OR8;
739 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
740 Opc = PPC::FMR;
741 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
742 Opc = PPC::MCRF;
743 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
744 Opc = PPC::VOR;
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.
754 Opc = PPC::XXLOR;
755 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
756 Opc = PPC::XXLORf;
757 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
758 Opc = PPC::CROR;
759 else
760 llvm_unreachable("Impossible reg-to-reg copy");
761
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));
766 else
767 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
768 }
769
770 // This function returns true if a CR spill is necessary and false otherwise.
771 bool
StoreRegToStackSlot(MachineFunction & MF,unsigned SrcReg,bool isKill,int FrameIdx,const TargetRegisterClass * RC,SmallVectorImpl<MachineInstr * > & NewMIs,bool & NonRI,bool & SpillsVRS) const772 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
773 unsigned SrcReg, bool isKill,
774 int FrameIdx,
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.
780
781 DebugLoc DL;
782 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
783 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
784 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
785 .addReg(SrcReg,
786 getKillRegState(isKill)),
787 FrameIdx));
788 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
789 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
790 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
791 .addReg(SrcReg,
792 getKillRegState(isKill)),
793 FrameIdx));
794 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
795 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
796 .addReg(SrcReg,
797 getKillRegState(isKill)),
798 FrameIdx));
799 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
800 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
801 .addReg(SrcReg,
802 getKillRegState(isKill)),
803 FrameIdx));
804 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
805 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
806 .addReg(SrcReg,
807 getKillRegState(isKill)),
808 FrameIdx));
809 return true;
810 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
811 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
812 .addReg(SrcReg,
813 getKillRegState(isKill)),
814 FrameIdx));
815 return true;
816 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
817 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
818 .addReg(SrcReg,
819 getKillRegState(isKill)),
820 FrameIdx));
821 NonRI = true;
822 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
823 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
824 .addReg(SrcReg,
825 getKillRegState(isKill)),
826 FrameIdx));
827 NonRI = true;
828 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
829 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
830 .addReg(SrcReg,
831 getKillRegState(isKill)),
832 FrameIdx));
833 NonRI = true;
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))
838 .addReg(SrcReg,
839 getKillRegState(isKill)),
840 FrameIdx));
841 SpillsVRS = true;
842 } else {
843 llvm_unreachable("Unknown regclass!");
844 }
845
846 return false;
847 }
848
849 void
storeRegToStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned SrcReg,bool isKill,int FrameIdx,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const850 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;
857
858 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
859 FuncInfo->setHasSpills();
860
861 bool NonRI = false, SpillsVRS = false;
862 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
863 NonRI, SpillsVRS))
864 FuncInfo->setSpillsCR();
865
866 if (SpillsVRS)
867 FuncInfo->setSpillsVRSAVE();
868
869 if (NonRI)
870 FuncInfo->setHasNonRISpills();
871
872 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
873 MBB.insert(MI, NewMIs[i]);
874
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);
882 }
883
884 bool
LoadRegFromStackSlot(MachineFunction & MF,DebugLoc DL,unsigned DestReg,int FrameIdx,const TargetRegisterClass * RC,SmallVectorImpl<MachineInstr * > & NewMIs,bool & NonRI,bool & SpillsVRS) const885 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.
892
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),
900 FrameIdx));
901 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
902 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
903 FrameIdx));
904 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
905 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
906 FrameIdx));
907 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
908 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
909 get(PPC::RESTORE_CR), DestReg),
910 FrameIdx));
911 return true;
912 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
913 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
914 get(PPC::RESTORE_CRBIT), DestReg),
915 FrameIdx));
916 return true;
917 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
918 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
919 FrameIdx));
920 NonRI = true;
921 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
922 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
923 FrameIdx));
924 NonRI = true;
925 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
926 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
927 FrameIdx));
928 NonRI = true;
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),
934 DestReg),
935 FrameIdx));
936 SpillsVRS = true;
937 } else {
938 llvm_unreachable("Unknown regclass!");
939 }
940
941 return false;
942 }
943
944 void
loadRegFromStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned DestReg,int FrameIdx,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const945 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;
952 DebugLoc DL;
953 if (MI != MBB.end()) DL = MI->getDebugLoc();
954
955 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
956 FuncInfo->setHasSpills();
957
958 bool NonRI = false, SpillsVRS = false;
959 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
960 NonRI, SpillsVRS))
961 FuncInfo->setSpillsCR();
962
963 if (SpillsVRS)
964 FuncInfo->setSpillsVRSAVE();
965
966 if (NonRI)
967 FuncInfo->setHasNonRISpills();
968
969 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
970 MBB.insert(MI, NewMIs[i]);
971
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);
979 }
980
981 bool PPCInstrInfo::
ReverseBranchCondition(SmallVectorImpl<MachineOperand> & Cond) const982 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);
986 else
987 // Leave the CR# the same, but invert the condition.
988 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
989 return false;
990 }
991
FoldImmediate(MachineInstr * UseMI,MachineInstr * DefMI,unsigned Reg,MachineRegisterInfo * MRI) const992 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)
998 return false;
999 if (!DefMI->getOperand(1).isImm())
1000 return false;
1001 if (DefMI->getOperand(1).getImm() != 0)
1002 return false;
1003
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.
1007
1008 const MCInstrDesc &UseMCID = UseMI->getDesc();
1009
1010 // Only fold into real machine instructions.
1011 if (UseMCID.isPseudo())
1012 return false;
1013
1014 unsigned UseIdx;
1015 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1016 if (UseMI->getOperand(UseIdx).isReg() &&
1017 UseMI->getOperand(UseIdx).getReg() == Reg)
1018 break;
1019
1020 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1021 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1022
1023 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1024
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)
1029 return false;
1030 } else {
1031 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1032 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1033 return false;
1034 }
1035
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)
1040 return false;
1041
1042 unsigned ZeroReg;
1043 if (UseInfo->isLookupPtrRegClass()) {
1044 bool isPPC64 = Subtarget.isPPC64();
1045 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1046 } else {
1047 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1048 PPC::ZERO8 : PPC::ZERO;
1049 }
1050
1051 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1052 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1053
1054 if (DeleteDef)
1055 DefMI->eraseFromParent();
1056
1057 return true;
1058 }
1059
MBBDefinesCTR(MachineBasicBlock & MBB)1060 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1061 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1062 I != IE; ++I)
1063 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1064 return true;
1065 return false;
1066 }
1067
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
1073 // twice.
isProfitableToIfCvt(MachineBasicBlock & TMBB,unsigned NumT,unsigned ExtraT,MachineBasicBlock & FMBB,unsigned NumF,unsigned ExtraF,const BranchProbability & Probability) const1074 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));
1080 }
1081
1082
isPredicated(const MachineInstr * MI) const1083 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.
1090
1091 return false;
1092 }
1093
isUnpredicatedTerminator(const MachineInstr * MI) const1094 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1095 if (!MI->isTerminator())
1096 return false;
1097
1098 // Conditional branch is a special case.
1099 if (MI->isBranch() && !MI->isBarrier())
1100 return true;
1101
1102 return !isPredicated(MI);
1103 }
1104
PredicateInstruction(MachineInstr * MI,const SmallVectorImpl<MachineOperand> & Pred) const1105 bool PPCInstrInfo::PredicateInstruction(
1106 MachineInstr *MI,
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());
1123 } else {
1124 MI->setDesc(get(PPC::BCCLR));
1125 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1126 .addImm(Pred[0].getImm())
1127 .addReg(Pred[1].getReg());
1128 }
1129
1130 return true;
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);
1140
1141 MI->setDesc(get(PPC::BC));
1142 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1143 .addReg(Pred[1].getReg())
1144 .addMBB(MBB);
1145 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1146 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1147 MI->RemoveOperand(0);
1148
1149 MI->setDesc(get(PPC::BCn));
1150 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1151 .addReg(Pred[1].getReg())
1152 .addMBB(MBB);
1153 } else {
1154 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1155 MI->RemoveOperand(0);
1156
1157 MI->setDesc(get(PPC::BCC));
1158 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1159 .addImm(Pred[0].getImm())
1160 .addReg(Pred[1].getReg())
1161 .addMBB(MBB);
1162 }
1163
1164 return true;
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");
1169
1170 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1171 bool isPPC64 = Subtarget.isPPC64();
1172
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());
1178 return true;
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());
1184 return true;
1185 }
1186
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());
1192 return true;
1193 }
1194
1195 return false;
1196 }
1197
SubsumesPredicate(const SmallVectorImpl<MachineOperand> & Pred1,const SmallVectorImpl<MachineOperand> & Pred2) const1198 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");
1203
1204 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1205 return false;
1206 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1207 return false;
1208
1209 // P1 can only subsume P2 if they test the same condition register.
1210 if (Pred1[1].getReg() != Pred2[1].getReg())
1211 return false;
1212
1213 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1214 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1215
1216 if (P1 == P2)
1217 return true;
1218
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))
1222 return true;
1223 if (P1 == PPC::PRED_GE &&
1224 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1225 return true;
1226
1227 return false;
1228 }
1229
DefinesPredicate(MachineInstr * MI,std::vector<MachineOperand> & Pred) const1230 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.
1237
1238 const TargetRegisterClass *RCs[] =
1239 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1240 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1241
1242 bool Found = false;
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];
1247 if (MO.isReg()) {
1248 if (MO.isDef() && RC->contains(MO.getReg())) {
1249 Pred.push_back(MO);
1250 Found = true;
1251 }
1252 } else if (MO.isRegMask()) {
1253 for (TargetRegisterClass::iterator I = RC->begin(),
1254 IE = RC->end(); I != IE; ++I)
1255 if (MO.clobbersPhysReg(*I)) {
1256 Pred.push_back(MO);
1257 Found = true;
1258 }
1259 }
1260 }
1261 }
1262
1263 return Found;
1264 }
1265
isPredicable(MachineInstr * MI) const1266 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1267 unsigned OpC = MI->getOpcode();
1268 switch (OpC) {
1269 default:
1270 return false;
1271 case PPC::B:
1272 case PPC::BLR:
1273 case PPC::BCTR:
1274 case PPC::BCTR8:
1275 case PPC::BCTRL:
1276 case PPC::BCTRL8:
1277 return true;
1278 }
1279 }
1280
analyzeCompare(const MachineInstr * MI,unsigned & SrcReg,unsigned & SrcReg2,int & Mask,int & Value) const1281 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1282 unsigned &SrcReg, unsigned &SrcReg2,
1283 int &Mask, int &Value) const {
1284 unsigned Opc = MI->getOpcode();
1285
1286 switch (Opc) {
1287 default: return false;
1288 case PPC::CMPWI:
1289 case PPC::CMPLWI:
1290 case PPC::CMPDI:
1291 case PPC::CMPLDI:
1292 SrcReg = MI->getOperand(1).getReg();
1293 SrcReg2 = 0;
1294 Value = MI->getOperand(2).getImm();
1295 Mask = 0xFFFF;
1296 return true;
1297 case PPC::CMPW:
1298 case PPC::CMPLW:
1299 case PPC::CMPD:
1300 case PPC::CMPLD:
1301 case PPC::FCMPUS:
1302 case PPC::FCMPUD:
1303 SrcReg = MI->getOperand(1).getReg();
1304 SrcReg2 = MI->getOperand(2).getReg();
1305 return true;
1306 }
1307 }
1308
optimizeCompareInstr(MachineInstr * CmpInstr,unsigned SrcReg,unsigned SrcReg2,int Mask,int Value,const MachineRegisterInfo * MRI) const1309 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1310 unsigned SrcReg, unsigned SrcReg2,
1311 int Mask, int Value,
1312 const MachineRegisterInfo *MRI) const {
1313 if (DisableCmpOpt)
1314 return false;
1315
1316 int OpC = CmpInstr->getOpcode();
1317 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1318
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)
1322 return false;
1323
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;
1336
1337 // Get the unique definition of SrcReg.
1338 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1339 if (!MI) return false;
1340 int MIOpC = MI->getOpcode();
1341
1342 bool equalityOnly = false;
1343 bool noSub = false;
1344 if (isPPC64) {
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) {
1352 noSub = true;
1353 } else
1354 return false;
1355 } else if (is32BitUnsignedCompare) {
1356 // We can perform this optimization, equality only, if MI is
1357 // zero-extending.
1358 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1359 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1360 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1361 noSub = true;
1362 equalityOnly = true;
1363 } else
1364 return false;
1365 } else
1366 equalityOnly = is64BitUnsignedCompare;
1367 } else
1368 equalityOnly = is32BitUnsignedCompare;
1369
1370 if (equalityOnly) {
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)
1379 return false;
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)
1384 return false;
1385 } else
1386 return false;
1387 }
1388 }
1389
1390 MachineBasicBlock::iterator I = CmpInstr;
1391
1392 // Scan forward to find the first use of the compare.
1393 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1394 I != EL; ++I) {
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)
1398 if (&*J == &*I) {
1399 FoundUse = true;
1400 break;
1401 }
1402
1403 if (FoundUse)
1404 break;
1405 }
1406
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;
1411 if (SrcReg2 != 0)
1412 // MI is not a candidate for CMPrr.
1413 MI = nullptr;
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.
1420 return false;
1421 }
1422
1423 // Search for Sub.
1424 const TargetRegisterInfo *TRI = &getRegisterInfo();
1425 --I;
1426
1427 // Get ready to iterate backward from CmpInstr.
1428 MachineBasicBlock::iterator E = MI,
1429 B = CmpInstr->getParent()->begin();
1430
1431 for (; I != E && !noSub; --I) {
1432 const MachineInstr &Instr = *I;
1433 unsigned IOpC = Instr.getOpcode();
1434
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.
1443 return false;
1444
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))) {
1453 Sub = &*I;
1454 break;
1455 }
1456
1457 if (I == B)
1458 // The 'and' is below the comparison instruction.
1459 return false;
1460 }
1461
1462 // Return false if no candidates exist.
1463 if (!MI && !Sub)
1464 return false;
1465
1466 // The single candidate is called MI.
1467 if (!MI) MI = Sub;
1468
1469 int NewOpC = -1;
1470 MIOpC = MI->getOpcode();
1471 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1472 NewOpC = MIOpC;
1473 else {
1474 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1475 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1476 NewOpC = MIOpC;
1477 }
1478
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.
1481
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.
1485 if (NewOpC == -1)
1486 return false;
1487
1488 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1489 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1490
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;
1496 if (Sub) {
1497 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1498 Sub->getOperand(2).getReg() == SrcReg;
1499
1500 // The operands to subf are the opposite of sub, so only in the fixed-point
1501 // case, invert the order.
1502 ShouldSwap = !ShouldSwap;
1503 }
1504
1505 if (ShouldSwap)
1506 for (MachineRegisterInfo::use_instr_iterator
1507 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1508 I != IE; ++I) {
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");
1522
1523 if (NewSubReg == PPC::sub_lt)
1524 NewSubReg = PPC::sub_gt;
1525 else if (NewSubReg == PPC::sub_gt)
1526 NewSubReg = PPC::sub_lt;
1527
1528 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1529 NewSubReg));
1530 } else // We need to abort on a user we don't understand.
1531 return false;
1532 }
1533
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();
1538
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);
1543
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
1550 // compare).
1551
1552 const MCInstrDesc &NewDesc = get(NewOpC);
1553 MI->setDesc(NewDesc);
1554
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));
1567 }
1568
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);
1574
1575 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1576 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1577
1578 return true;
1579 }
1580
1581 /// GetInstSize - Return the number of bytes of code the specified
1582 /// instruction may be. This returns the maximum number of bytes.
1583 ///
GetInstSizeInBytes(const MachineInstr * MI) const1584 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1585 unsigned Opcode = MI->getOpcode();
1586
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());
1591 } else {
1592 const MCInstrDesc &Desc = get(Opcode);
1593 return Desc.getSize();
1594 }
1595 }
1596
1597 #undef DEBUG_TYPE
1598 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1599
1600 namespace {
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 {
1605 static char ID;
PPCVSXFMAMutate__anon93db7c1a0111::PPCVSXFMAMutate1606 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1607 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1608 }
1609
1610 LiveIntervals *LIS;
1611
1612 const PPCTargetMachine *TM;
1613 const PPCInstrInfo *TII;
1614
1615 protected:
processBlock__anon93db7c1a0111::PPCVSXFMAMutate1616 bool processBlock(MachineBasicBlock &MBB) {
1617 bool Changed = false;
1618
1619 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1620 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1621 I != IE; ++I) {
1622 MachineInstr *MI = I;
1623
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).
1629
1630 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1631 if (AltOpc == -1)
1632 continue;
1633
1634 // This pass is run after register coalescing, and so we're looking for
1635 // a situation like this:
1636 // ...
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
1640 // ...
1641 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1642 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1643 // ...
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
1648 // is replaced by:
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
1652
1653 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1654
1655 VNInfo *AddendValNo =
1656 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1657 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1658
1659 // The addend and this instruction must be in the same block.
1660
1661 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1662 continue;
1663
1664 // The addend must be a full copy within the same register class.
1665
1666 if (!AddendMI->isFullCopy())
1667 continue;
1668
1669 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1670 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1671 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1672 MRI.getRegClass(AddendSrcReg))
1673 continue;
1674 } else {
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))
1679 continue;
1680 }
1681
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
1685 // situations.
1686 bool OtherUsers = false;
1687 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1688 J != JE; --J)
1689 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1690 OtherUsers = true;
1691 break;
1692 }
1693
1694 if (OtherUsers)
1695 continue;
1696
1697 // Find one of the product operands that is killed by this instruction.
1698
1699 unsigned KilledProdOp = 0, OtherProdOp = 0;
1700 if (LIS->getInterval(MI->getOperand(2).getReg())
1701 .Query(FMAIdx).isKill()) {
1702 KilledProdOp = 2;
1703 OtherProdOp = 3;
1704 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1705 .Query(FMAIdx).isKill()) {
1706 KilledProdOp = 3;
1707 OtherProdOp = 2;
1708 }
1709
1710 // If there are no killed product operands, then this transformation is
1711 // likely not profitable.
1712 if (!KilledProdOp)
1713 continue;
1714
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))
1718 continue;
1719
1720 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1721
1722 unsigned AddReg = AddendMI->getOperand(1).getReg();
1723 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1724 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1725
1726 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1727 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1728 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1729
1730 bool AddRegKill = AddendMI->getOperand(1).isKill();
1731 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1732 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1733
1734 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1735 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1736 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1737
1738 unsigned OldFMAReg = MI->getOperand(0).getReg();
1739
1740 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1741 "Addend copy not tied to old FMA output!");
1742
1743 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1744
1745 MI->getOperand(0).setReg(KilledProdReg);
1746 MI->getOperand(1).setReg(KilledProdReg);
1747 MI->getOperand(3).setReg(AddReg);
1748 MI->getOperand(2).setReg(OtherProdReg);
1749
1750 MI->getOperand(0).setSubReg(KilledProdSubReg);
1751 MI->getOperand(1).setSubReg(KilledProdSubReg);
1752 MI->getOperand(3).setSubReg(AddSubReg);
1753 MI->getOperand(2).setSubReg(OtherProdSubReg);
1754
1755 MI->getOperand(1).setIsKill(KilledProdRegKill);
1756 MI->getOperand(3).setIsKill(AddRegKill);
1757 MI->getOperand(2).setIsKill(OtherProdRegKill);
1758
1759 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1760 MI->getOperand(3).setIsUndef(AddRegUndef);
1761 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1762
1763 MI->setDesc(TII->get(AltOpc));
1764
1765 DEBUG(dbgs() << " -> " << *MI);
1766
1767 // The killed product operand was killed here, so we can reuse it now
1768 // for the result of the fma.
1769
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();
1773 UI != UE;) {
1774 MachineOperand &UseMO = *UI;
1775 MachineInstr *UseMI = UseMO.getParent();
1776 ++UI;
1777
1778 // Don't replace the result register of the copy we're about to erase.
1779 if (UseMI == AddendMI)
1780 continue;
1781
1782 UseMO.setReg(KilledProdReg);
1783 UseMO.setSubReg(KilledProdSubReg);
1784 }
1785
1786 // Extend the live intervals of the killed product operand to hold the
1787 // fma result.
1788
1789 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1790 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1791 AI != AE; ++AI) {
1792 // Don't add the segment that corresponds to the original copy.
1793 if (AI->valno == AddendValNo)
1794 continue;
1795
1796 VNInfo *NewFMAValNo =
1797 NewFMAInt.getNextValue(AI->start,
1798 LIS->getVNInfoAllocator());
1799
1800 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1801 NewFMAValNo));
1802 }
1803 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1804
1805 FMAInt.removeValNo(FMAValNo);
1806 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1807
1808 // Remove the (now unused) copy.
1809
1810 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1811 LIS->RemoveMachineInstrFromMaps(AddendMI);
1812 AddendMI->eraseFromParent();
1813
1814 Changed = true;
1815 }
1816
1817 return Changed;
1818 }
1819
1820 public:
runOnMachineFunction__anon93db7c1a0111::PPCVSXFMAMutate1821 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
1824 // anything.
1825 if (!TM->getSubtargetImpl()->hasVSX())
1826 return false;
1827
1828 LIS = &getAnalysis<LiveIntervals>();
1829
1830 TII = TM->getInstrInfo();
1831
1832 bool Changed = false;
1833
1834 if (DisableVSXFMAMutate)
1835 return Changed;
1836
1837 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1838 MachineBasicBlock &B = *I++;
1839 if (processBlock(B))
1840 Changed = true;
1841 }
1842
1843 return Changed;
1844 }
1845
getAnalysisUsage__anon93db7c1a0111::PPCVSXFMAMutate1846 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);
1852 }
1853 };
1854 }
1855
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)
1862
1863 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1864
1865 char PPCVSXFMAMutate::ID = 0;
1866 FunctionPass*
createPPCVSXFMAMutatePass()1867 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1868
1869 #undef DEBUG_TYPE
1870 #define DEBUG_TYPE "ppc-vsx-copy"
1871
1872 namespace llvm {
1873 void initializePPCVSXCopyPass(PassRegistry&);
1874 }
1875
1876 namespace {
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 {
1881 static char ID;
PPCVSXCopy__anon93db7c1a0211::PPCVSXCopy1882 PPCVSXCopy() : MachineFunctionPass(ID) {
1883 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1884 }
1885
1886 const PPCTargetMachine *TM;
1887 const PPCInstrInfo *TII;
1888
IsRegInClass__anon93db7c1a0211::PPCVSXCopy1889 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)) {
1894 return true;
1895 }
1896
1897 return false;
1898 }
1899
IsVSReg__anon93db7c1a0211::PPCVSXCopy1900 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1901 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1902 }
1903
IsVRReg__anon93db7c1a0211::PPCVSXCopy1904 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1905 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1906 }
1907
IsF8Reg__anon93db7c1a0211::PPCVSXCopy1908 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1909 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1910 }
1911
1912 protected:
processBlock__anon93db7c1a0211::PPCVSXCopy1913 bool processBlock(MachineBasicBlock &MBB) {
1914 bool Changed = false;
1915
1916 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1917 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1918 I != IE; ++I) {
1919 MachineInstr *MI = I;
1920 if (!MI->isFullCopy())
1921 continue;
1922
1923 MachineOperand &DstMO = MI->getOperand(0);
1924 MachineOperand &SrcMO = MI->getOperand(1);
1925
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.
1929 Changed = true;
1930
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");
1937
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.
1943 .addOperand(SrcMO)
1944 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1945 PPC::sub_64);
1946
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.
1952 Changed = true;
1953
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");
1960
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)
1965 .addOperand(SrcMO);
1966
1967 // Transform the original copy into a subregister extraction copy.
1968 SrcMO.setReg(NewVReg);
1969 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1970 PPC::sub_64);
1971 }
1972 }
1973
1974 return Changed;
1975 }
1976
1977 public:
runOnMachineFunction__anon93db7c1a0211::PPCVSXCopy1978 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())
1982 return false;
1983 TII = TM->getInstrInfo();
1984
1985 bool Changed = false;
1986
1987 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1988 MachineBasicBlock &B = *I++;
1989 if (processBlock(B))
1990 Changed = true;
1991 }
1992
1993 return Changed;
1994 }
1995
getAnalysisUsage__anon93db7c1a0211::PPCVSXCopy1996 void getAnalysisUsage(AnalysisUsage &AU) const override {
1997 MachineFunctionPass::getAnalysisUsage(AU);
1998 }
1999 };
2000 }
2001
2002 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2003 "PowerPC VSX Copy Legalization", false, false)
2004
2005 char PPCVSXCopy::ID = 0;
2006 FunctionPass*
createPPCVSXCopyPass()2007 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2008
2009 #undef DEBUG_TYPE
2010 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2011
2012 namespace llvm {
2013 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2014 }
2015
2016 namespace {
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 {
2021 static char ID;
PPCVSXCopyCleanup__anon93db7c1a0311::PPCVSXCopyCleanup2022 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2023 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2024 }
2025
2026 const PPCTargetMachine *TM;
2027 const PPCInstrInfo *TII;
2028
2029 protected:
processBlock__anon93db7c1a0311::PPCVSXCopyCleanup2030 bool processBlock(MachineBasicBlock &MBB) {
2031 bool Changed = false;
2032
2033 SmallVector<MachineInstr *, 4> ToDelete;
2034 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2035 I != IE; ++I) {
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);
2041 }
2042
2043 if (!ToDelete.empty())
2044 Changed = true;
2045
2046 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2047 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2048 ToDelete[i]->eraseFromParent();
2049 }
2050
2051 return Changed;
2052 }
2053
2054 public:
runOnMachineFunction__anon93db7c1a0311::PPCVSXCopyCleanup2055 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())
2059 return false;
2060 TII = TM->getInstrInfo();
2061
2062 bool Changed = false;
2063
2064 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2065 MachineBasicBlock &B = *I++;
2066 if (processBlock(B))
2067 Changed = true;
2068 }
2069
2070 return Changed;
2071 }
2072
getAnalysisUsage__anon93db7c1a0311::PPCVSXCopyCleanup2073 void getAnalysisUsage(AnalysisUsage &AU) const override {
2074 MachineFunctionPass::getAnalysisUsage(AU);
2075 }
2076 };
2077 }
2078
2079 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2080 "PowerPC VSX Copy Cleanup", false, false)
2081
2082 char PPCVSXCopyCleanup::ID = 0;
2083 FunctionPass*
createPPCVSXCopyCleanupPass()2084 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2085
2086 #undef DEBUG_TYPE
2087 #define DEBUG_TYPE "ppc-early-ret"
2088 STATISTIC(NumBCLR, "Number of early conditional returns");
2089 STATISTIC(NumBLR, "Number of early returns");
2090
2091 namespace llvm {
2092 void initializePPCEarlyReturnPass(PassRegistry&);
2093 }
2094
2095 namespace {
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 {
2100 static char ID;
PPCEarlyReturn__anon93db7c1a0411::PPCEarlyReturn2101 PPCEarlyReturn() : MachineFunctionPass(ID) {
2102 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2103 }
2104
2105 const PPCTargetMachine *TM;
2106 const PPCInstrInfo *TII;
2107
2108 protected:
processBlock__anon93db7c1a0411::PPCEarlyReturn2109 bool processBlock(MachineBasicBlock &ReturnMBB) {
2110 bool Changed = false;
2111
2112 MachineBasicBlock::iterator I = ReturnMBB.begin();
2113 I = ReturnMBB.SkipPHIsAndLabels(I);
2114
2115 // The block must be essentially empty except for the blr.
2116 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2117 I != ReturnMBB.getLastNonDebugInstr())
2118 return Changed;
2119
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;
2133 ++NumBLR;
2134 continue;
2135 }
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
2139 // with a bclr.
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;
2146 ++NumBCLR;
2147 continue;
2148 }
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
2152 // with a bclr.
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;
2160 ++NumBCLR;
2161 continue;
2162 }
2163 } else if (J->isBranch()) {
2164 if (J->isIndirectBranch()) {
2165 if (ReturnMBB.hasAddressTaken())
2166 OtherReference = true;
2167 } else
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())
2173 break;
2174
2175 if (J == (*PI)->begin())
2176 break;
2177
2178 --J;
2179 }
2180
2181 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2182 OtherReference = true;
2183
2184 // Predecessors are stored in a vector and can't be removed here.
2185 if (!OtherReference && BlockChanged) {
2186 PredToRemove.push_back(*PI);
2187 }
2188
2189 if (BlockChanged)
2190 Changed = true;
2191 }
2192
2193 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2194 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2195
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);
2205 }
2206
2207 if (ReturnMBB.pred_empty())
2208 ReturnMBB.eraseFromParent();
2209 }
2210
2211 return Changed;
2212 }
2213
2214 public:
runOnMachineFunction__anon93db7c1a0411::PPCEarlyReturn2215 bool runOnMachineFunction(MachineFunction &MF) override {
2216 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2217 TII = TM->getInstrInfo();
2218
2219 bool Changed = false;
2220
2221 // If the function does not have at least two blocks, then there is
2222 // nothing to do.
2223 if (MF.size() < 2)
2224 return Changed;
2225
2226 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2227 MachineBasicBlock &B = *I++;
2228 if (processBlock(B))
2229 Changed = true;
2230 }
2231
2232 return Changed;
2233 }
2234
getAnalysisUsage__anon93db7c1a0411::PPCEarlyReturn2235 void getAnalysisUsage(AnalysisUsage &AU) const override {
2236 MachineFunctionPass::getAnalysisUsage(AU);
2237 }
2238 };
2239 }
2240
2241 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2242 "PowerPC Early-Return Creation", false, false)
2243
2244 char PPCEarlyReturn::ID = 0;
2245 FunctionPass*
createPPCEarlyReturnPass()2246 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }
2247