[Codegen] Alter the default promotion for saturating adds and subs
[llvm-complete.git] / lib / Target / PowerPC / PPCInstrInfo.cpp
blob06533fe0de33be4f078989cc436d00edd68d3d9a
1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the PowerPC implementation of the TargetInstrInfo class.
11 //===----------------------------------------------------------------------===//
13 #include "PPCInstrInfo.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCHazardRecognizers.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/LiveIntervals.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/CodeGen/ScheduleDAG.h"
30 #include "llvm/CodeGen/SlotIndexes.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
40 using namespace llvm;
42 #define DEBUG_TYPE "ppc-instr-info"
44 #define GET_INSTRMAP_INFO
45 #define GET_INSTRINFO_CTOR_DTOR
46 #include "PPCGenInstrInfo.inc"
48 STATISTIC(NumStoreSPILLVSRRCAsVec,
49 "Number of spillvsrrc spilled to stack as vec");
50 STATISTIC(NumStoreSPILLVSRRCAsGpr,
51 "Number of spillvsrrc spilled to stack as gpr");
52 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
53 STATISTIC(CmpIselsConverted,
54 "Number of ISELs that depend on comparison of constants converted");
55 STATISTIC(MissedConvertibleImmediateInstrs,
56 "Number of compare-immediate instructions fed by constants");
57 STATISTIC(NumRcRotatesConvertedToRcAnd,
58 "Number of record-form rotates converted to record-form andi");
60 static cl::
61 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
62 cl::desc("Disable analysis for CTR loops"));
64 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
65 cl::desc("Disable compare instruction optimization"), cl::Hidden);
67 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
68 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
69 cl::Hidden);
71 static cl::opt<bool>
72 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
73 cl::desc("Use the old (incorrect) instruction latency calculation"));
75 // Index into the OpcodesForSpill array.
76 enum SpillOpcodeKey {
77 SOK_Int4Spill,
78 SOK_Int8Spill,
79 SOK_Float8Spill,
80 SOK_Float4Spill,
81 SOK_CRSpill,
82 SOK_CRBitSpill,
83 SOK_VRVectorSpill,
84 SOK_VSXVectorSpill,
85 SOK_VectorFloat8Spill,
86 SOK_VectorFloat4Spill,
87 SOK_VRSaveSpill,
88 SOK_QuadFloat8Spill,
89 SOK_QuadFloat4Spill,
90 SOK_QuadBitSpill,
91 SOK_SpillToVSR,
92 SOK_SPESpill,
93 SOK_LastOpcodeSpill // This must be last on the enum.
96 // Pin the vtable to this file.
97 void PPCInstrInfo::anchor() {}
99 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
100 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
101 /* CatchRetOpcode */ -1,
102 STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
103 Subtarget(STI), RI(STI.getTargetMachine()) {}
105 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
106 /// this target when scheduling the DAG.
107 ScheduleHazardRecognizer *
108 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
109 const ScheduleDAG *DAG) const {
110 unsigned Directive =
111 static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
112 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
113 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
114 const InstrItineraryData *II =
115 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
116 return new ScoreboardHazardRecognizer(II, DAG);
119 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
122 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
123 /// to use for this target when scheduling the DAG.
124 ScheduleHazardRecognizer *
125 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
126 const ScheduleDAG *DAG) const {
127 unsigned Directive =
128 DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
130 // FIXME: Leaving this as-is until we have POWER9 scheduling info
131 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
132 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
134 // Most subtargets use a PPC970 recognizer.
135 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
136 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
137 assert(DAG->TII && "No InstrInfo?");
139 return new PPCHazardRecognizer970(*DAG);
142 return new ScoreboardHazardRecognizer(II, DAG);
145 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
146 const MachineInstr &MI,
147 unsigned *PredCost) const {
148 if (!ItinData || UseOldLatencyCalc)
149 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
151 // The default implementation of getInstrLatency calls getStageLatency, but
152 // getStageLatency does not do the right thing for us. While we have
153 // itinerary, most cores are fully pipelined, and so the itineraries only
154 // express the first part of the pipeline, not every stage. Instead, we need
155 // to use the listed output operand cycle number (using operand 0 here, which
156 // is an output).
158 unsigned Latency = 1;
159 unsigned DefClass = MI.getDesc().getSchedClass();
160 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
161 const MachineOperand &MO = MI.getOperand(i);
162 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
163 continue;
165 int Cycle = ItinData->getOperandCycle(DefClass, i);
166 if (Cycle < 0)
167 continue;
169 Latency = std::max(Latency, (unsigned) Cycle);
172 return Latency;
175 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
176 const MachineInstr &DefMI, unsigned DefIdx,
177 const MachineInstr &UseMI,
178 unsigned UseIdx) const {
179 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
180 UseMI, UseIdx);
182 if (!DefMI.getParent())
183 return Latency;
185 const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
186 Register Reg = DefMO.getReg();
188 bool IsRegCR;
189 if (Register::isVirtualRegister(Reg)) {
190 const MachineRegisterInfo *MRI =
191 &DefMI.getParent()->getParent()->getRegInfo();
192 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
193 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
194 } else {
195 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
196 PPC::CRBITRCRegClass.contains(Reg);
199 if (UseMI.isBranch() && IsRegCR) {
200 if (Latency < 0)
201 Latency = getInstrLatency(ItinData, DefMI);
203 // On some cores, there is an additional delay between writing to a condition
204 // register, and using it from a branch.
205 unsigned Directive = Subtarget.getDarwinDirective();
206 switch (Directive) {
207 default: break;
208 case PPC::DIR_7400:
209 case PPC::DIR_750:
210 case PPC::DIR_970:
211 case PPC::DIR_E5500:
212 case PPC::DIR_PWR4:
213 case PPC::DIR_PWR5:
214 case PPC::DIR_PWR5X:
215 case PPC::DIR_PWR6:
216 case PPC::DIR_PWR6X:
217 case PPC::DIR_PWR7:
218 case PPC::DIR_PWR8:
219 // FIXME: Is this needed for POWER9?
220 Latency += 2;
221 break;
225 return Latency;
228 // This function does not list all associative and commutative operations, but
229 // only those worth feeding through the machine combiner in an attempt to
230 // reduce the critical path. Mostly, this means floating-point operations,
231 // because they have high latencies (compared to other operations, such and
232 // and/or, which are also associative and commutative, but have low latencies).
233 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const {
234 switch (Inst.getOpcode()) {
235 // FP Add:
236 case PPC::FADD:
237 case PPC::FADDS:
238 // FP Multiply:
239 case PPC::FMUL:
240 case PPC::FMULS:
241 // Altivec Add:
242 case PPC::VADDFP:
243 // VSX Add:
244 case PPC::XSADDDP:
245 case PPC::XVADDDP:
246 case PPC::XVADDSP:
247 case PPC::XSADDSP:
248 // VSX Multiply:
249 case PPC::XSMULDP:
250 case PPC::XVMULDP:
251 case PPC::XVMULSP:
252 case PPC::XSMULSP:
253 // QPX Add:
254 case PPC::QVFADD:
255 case PPC::QVFADDS:
256 case PPC::QVFADDSs:
257 // QPX Multiply:
258 case PPC::QVFMUL:
259 case PPC::QVFMULS:
260 case PPC::QVFMULSs:
261 return true;
262 default:
263 return false;
267 bool PPCInstrInfo::getMachineCombinerPatterns(
268 MachineInstr &Root,
269 SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
270 // Using the machine combiner in this way is potentially expensive, so
271 // restrict to when aggressive optimizations are desired.
272 if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive)
273 return false;
275 // FP reassociation is only legal when we don't need strict IEEE semantics.
276 if (!Root.getParent()->getParent()->getTarget().Options.UnsafeFPMath)
277 return false;
279 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns);
282 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
283 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
284 unsigned &SrcReg, unsigned &DstReg,
285 unsigned &SubIdx) const {
286 switch (MI.getOpcode()) {
287 default: return false;
288 case PPC::EXTSW:
289 case PPC::EXTSW_32:
290 case PPC::EXTSW_32_64:
291 SrcReg = MI.getOperand(1).getReg();
292 DstReg = MI.getOperand(0).getReg();
293 SubIdx = PPC::sub_32;
294 return true;
298 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
299 int &FrameIndex) const {
300 unsigned Opcode = MI.getOpcode();
301 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
302 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
304 if (End != std::find(OpcodesForSpill, End, Opcode)) {
305 // Check for the operands added by addFrameReference (the immediate is the
306 // offset which defaults to 0).
307 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
308 MI.getOperand(2).isFI()) {
309 FrameIndex = MI.getOperand(2).getIndex();
310 return MI.getOperand(0).getReg();
313 return 0;
316 // For opcodes with the ReMaterializable flag set, this function is called to
317 // verify the instruction is really rematable.
318 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
319 AliasAnalysis *AA) const {
320 switch (MI.getOpcode()) {
321 default:
322 // This function should only be called for opcodes with the ReMaterializable
323 // flag set.
324 llvm_unreachable("Unknown rematerializable operation!");
325 break;
326 case PPC::LI:
327 case PPC::LI8:
328 case PPC::LIS:
329 case PPC::LIS8:
330 case PPC::QVGPCI:
331 case PPC::ADDIStocHA8:
332 case PPC::ADDItocL:
333 case PPC::LOAD_STACK_GUARD:
334 case PPC::XXLXORz:
335 case PPC::XXLXORspz:
336 case PPC::XXLXORdpz:
337 case PPC::XXLEQVOnes:
338 case PPC::V_SET0B:
339 case PPC::V_SET0H:
340 case PPC::V_SET0:
341 case PPC::V_SETALLONESB:
342 case PPC::V_SETALLONESH:
343 case PPC::V_SETALLONES:
344 case PPC::CRSET:
345 case PPC::CRUNSET:
346 return true;
348 return false;
351 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
352 int &FrameIndex) const {
353 unsigned Opcode = MI.getOpcode();
354 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
355 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill;
357 if (End != std::find(OpcodesForSpill, End, Opcode)) {
358 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() &&
359 MI.getOperand(2).isFI()) {
360 FrameIndex = MI.getOperand(2).getIndex();
361 return MI.getOperand(0).getReg();
364 return 0;
367 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
368 unsigned OpIdx1,
369 unsigned OpIdx2) const {
370 MachineFunction &MF = *MI.getParent()->getParent();
372 // Normal instructions can be commuted the obvious way.
373 if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMIo)
374 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
375 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
376 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
377 // changing the relative order of the mask operands might change what happens
378 // to the high-bits of the mask (and, thus, the result).
380 // Cannot commute if it has a non-zero rotate count.
381 if (MI.getOperand(3).getImm() != 0)
382 return nullptr;
384 // If we have a zero rotate count, we have:
385 // M = mask(MB,ME)
386 // Op0 = (Op1 & ~M) | (Op2 & M)
387 // Change this to:
388 // M = mask((ME+1)&31, (MB-1)&31)
389 // Op0 = (Op2 & ~M) | (Op1 & M)
391 // Swap op1/op2
392 assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
393 "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMIo.");
394 Register Reg0 = MI.getOperand(0).getReg();
395 Register Reg1 = MI.getOperand(1).getReg();
396 Register Reg2 = MI.getOperand(2).getReg();
397 unsigned SubReg1 = MI.getOperand(1).getSubReg();
398 unsigned SubReg2 = MI.getOperand(2).getSubReg();
399 bool Reg1IsKill = MI.getOperand(1).isKill();
400 bool Reg2IsKill = MI.getOperand(2).isKill();
401 bool ChangeReg0 = false;
402 // If machine instrs are no longer in two-address forms, update
403 // destination register as well.
404 if (Reg0 == Reg1) {
405 // Must be two address instruction!
406 assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
407 "Expecting a two-address instruction!");
408 assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
409 Reg2IsKill = false;
410 ChangeReg0 = true;
413 // Masks.
414 unsigned MB = MI.getOperand(4).getImm();
415 unsigned ME = MI.getOperand(5).getImm();
417 // We can't commute a trivial mask (there is no way to represent an all-zero
418 // mask).
419 if (MB == 0 && ME == 31)
420 return nullptr;
422 if (NewMI) {
423 // Create a new instruction.
424 Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg();
425 bool Reg0IsDead = MI.getOperand(0).isDead();
426 return BuildMI(MF, MI.getDebugLoc(), MI.getDesc())
427 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
428 .addReg(Reg2, getKillRegState(Reg2IsKill))
429 .addReg(Reg1, getKillRegState(Reg1IsKill))
430 .addImm((ME + 1) & 31)
431 .addImm((MB - 1) & 31);
434 if (ChangeReg0) {
435 MI.getOperand(0).setReg(Reg2);
436 MI.getOperand(0).setSubReg(SubReg2);
438 MI.getOperand(2).setReg(Reg1);
439 MI.getOperand(1).setReg(Reg2);
440 MI.getOperand(2).setSubReg(SubReg1);
441 MI.getOperand(1).setSubReg(SubReg2);
442 MI.getOperand(2).setIsKill(Reg1IsKill);
443 MI.getOperand(1).setIsKill(Reg2IsKill);
445 // Swap the mask around.
446 MI.getOperand(4).setImm((ME + 1) & 31);
447 MI.getOperand(5).setImm((MB - 1) & 31);
448 return &MI;
451 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
452 unsigned &SrcOpIdx1,
453 unsigned &SrcOpIdx2) const {
454 // For VSX A-Type FMA instructions, it is the first two operands that can be
455 // commuted, however, because the non-encoded tied input operand is listed
456 // first, the operands to swap are actually the second and third.
458 int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode());
459 if (AltOpc == -1)
460 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
462 // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
463 // and SrcOpIdx2.
464 return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3);
467 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
468 MachineBasicBlock::iterator MI) const {
469 // This function is used for scheduling, and the nop wanted here is the type
470 // that terminates dispatch groups on the POWER cores.
471 unsigned Directive = Subtarget.getDarwinDirective();
472 unsigned Opcode;
473 switch (Directive) {
474 default: Opcode = PPC::NOP; break;
475 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
476 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
477 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
478 // FIXME: Update when POWER9 scheduling model is ready.
479 case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
482 DebugLoc DL;
483 BuildMI(MBB, MI, DL, get(Opcode));
486 /// Return the noop instruction to use for a noop.
487 void PPCInstrInfo::getNoop(MCInst &NopInst) const {
488 NopInst.setOpcode(PPC::NOP);
491 // Branch analysis.
492 // Note: If the condition register is set to CTR or CTR8 then this is a
493 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
494 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
495 MachineBasicBlock *&TBB,
496 MachineBasicBlock *&FBB,
497 SmallVectorImpl<MachineOperand> &Cond,
498 bool AllowModify) const {
499 bool isPPC64 = Subtarget.isPPC64();
501 // If the block has no terminators, it just falls into the block after it.
502 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
503 if (I == MBB.end())
504 return false;
506 if (!isUnpredicatedTerminator(*I))
507 return false;
509 if (AllowModify) {
510 // If the BB ends with an unconditional branch to the fallthrough BB,
511 // we eliminate the branch instruction.
512 if (I->getOpcode() == PPC::B &&
513 MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
514 I->eraseFromParent();
516 // We update iterator after deleting the last branch.
517 I = MBB.getLastNonDebugInstr();
518 if (I == MBB.end() || !isUnpredicatedTerminator(*I))
519 return false;
523 // Get the last instruction in the block.
524 MachineInstr &LastInst = *I;
526 // If there is only one terminator instruction, process it.
527 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
528 if (LastInst.getOpcode() == PPC::B) {
529 if (!LastInst.getOperand(0).isMBB())
530 return true;
531 TBB = LastInst.getOperand(0).getMBB();
532 return false;
533 } else if (LastInst.getOpcode() == PPC::BCC) {
534 if (!LastInst.getOperand(2).isMBB())
535 return true;
536 // Block ends with fall-through condbranch.
537 TBB = LastInst.getOperand(2).getMBB();
538 Cond.push_back(LastInst.getOperand(0));
539 Cond.push_back(LastInst.getOperand(1));
540 return false;
541 } else if (LastInst.getOpcode() == PPC::BC) {
542 if (!LastInst.getOperand(1).isMBB())
543 return true;
544 // Block ends with fall-through condbranch.
545 TBB = LastInst.getOperand(1).getMBB();
546 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
547 Cond.push_back(LastInst.getOperand(0));
548 return false;
549 } else if (LastInst.getOpcode() == PPC::BCn) {
550 if (!LastInst.getOperand(1).isMBB())
551 return true;
552 // Block ends with fall-through condbranch.
553 TBB = LastInst.getOperand(1).getMBB();
554 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
555 Cond.push_back(LastInst.getOperand(0));
556 return false;
557 } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
558 LastInst.getOpcode() == PPC::BDNZ) {
559 if (!LastInst.getOperand(0).isMBB())
560 return true;
561 if (DisableCTRLoopAnal)
562 return true;
563 TBB = LastInst.getOperand(0).getMBB();
564 Cond.push_back(MachineOperand::CreateImm(1));
565 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
566 true));
567 return false;
568 } else if (LastInst.getOpcode() == PPC::BDZ8 ||
569 LastInst.getOpcode() == PPC::BDZ) {
570 if (!LastInst.getOperand(0).isMBB())
571 return true;
572 if (DisableCTRLoopAnal)
573 return true;
574 TBB = LastInst.getOperand(0).getMBB();
575 Cond.push_back(MachineOperand::CreateImm(0));
576 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
577 true));
578 return false;
581 // Otherwise, don't know what this is.
582 return true;
585 // Get the instruction before it if it's a terminator.
586 MachineInstr &SecondLastInst = *I;
588 // If there are three terminators, we don't know what sort of block this is.
589 if (I != MBB.begin() && isUnpredicatedTerminator(*--I))
590 return true;
592 // If the block ends with PPC::B and PPC:BCC, handle it.
593 if (SecondLastInst.getOpcode() == PPC::BCC &&
594 LastInst.getOpcode() == PPC::B) {
595 if (!SecondLastInst.getOperand(2).isMBB() ||
596 !LastInst.getOperand(0).isMBB())
597 return true;
598 TBB = SecondLastInst.getOperand(2).getMBB();
599 Cond.push_back(SecondLastInst.getOperand(0));
600 Cond.push_back(SecondLastInst.getOperand(1));
601 FBB = LastInst.getOperand(0).getMBB();
602 return false;
603 } else if (SecondLastInst.getOpcode() == PPC::BC &&
604 LastInst.getOpcode() == PPC::B) {
605 if (!SecondLastInst.getOperand(1).isMBB() ||
606 !LastInst.getOperand(0).isMBB())
607 return true;
608 TBB = SecondLastInst.getOperand(1).getMBB();
609 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
610 Cond.push_back(SecondLastInst.getOperand(0));
611 FBB = LastInst.getOperand(0).getMBB();
612 return false;
613 } else if (SecondLastInst.getOpcode() == PPC::BCn &&
614 LastInst.getOpcode() == PPC::B) {
615 if (!SecondLastInst.getOperand(1).isMBB() ||
616 !LastInst.getOperand(0).isMBB())
617 return true;
618 TBB = SecondLastInst.getOperand(1).getMBB();
619 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
620 Cond.push_back(SecondLastInst.getOperand(0));
621 FBB = LastInst.getOperand(0).getMBB();
622 return false;
623 } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
624 SecondLastInst.getOpcode() == PPC::BDNZ) &&
625 LastInst.getOpcode() == PPC::B) {
626 if (!SecondLastInst.getOperand(0).isMBB() ||
627 !LastInst.getOperand(0).isMBB())
628 return true;
629 if (DisableCTRLoopAnal)
630 return true;
631 TBB = SecondLastInst.getOperand(0).getMBB();
632 Cond.push_back(MachineOperand::CreateImm(1));
633 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
634 true));
635 FBB = LastInst.getOperand(0).getMBB();
636 return false;
637 } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
638 SecondLastInst.getOpcode() == PPC::BDZ) &&
639 LastInst.getOpcode() == PPC::B) {
640 if (!SecondLastInst.getOperand(0).isMBB() ||
641 !LastInst.getOperand(0).isMBB())
642 return true;
643 if (DisableCTRLoopAnal)
644 return true;
645 TBB = SecondLastInst.getOperand(0).getMBB();
646 Cond.push_back(MachineOperand::CreateImm(0));
647 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
648 true));
649 FBB = LastInst.getOperand(0).getMBB();
650 return false;
653 // If the block ends with two PPC:Bs, handle it. The second one is not
654 // executed, so remove it.
655 if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
656 if (!SecondLastInst.getOperand(0).isMBB())
657 return true;
658 TBB = SecondLastInst.getOperand(0).getMBB();
659 I = LastInst;
660 if (AllowModify)
661 I->eraseFromParent();
662 return false;
665 // Otherwise, can't handle this.
666 return true;
669 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
670 int *BytesRemoved) const {
671 assert(!BytesRemoved && "code size not handled");
673 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
674 if (I == MBB.end())
675 return 0;
677 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
678 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
679 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
680 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
681 return 0;
683 // Remove the branch.
684 I->eraseFromParent();
686 I = MBB.end();
688 if (I == MBB.begin()) return 1;
689 --I;
690 if (I->getOpcode() != PPC::BCC &&
691 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
692 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
693 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
694 return 1;
696 // Remove the branch.
697 I->eraseFromParent();
698 return 2;
701 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
702 MachineBasicBlock *TBB,
703 MachineBasicBlock *FBB,
704 ArrayRef<MachineOperand> Cond,
705 const DebugLoc &DL,
706 int *BytesAdded) const {
707 // Shouldn't be a fall through.
708 assert(TBB && "insertBranch must not be told to insert a fallthrough");
709 assert((Cond.size() == 2 || Cond.size() == 0) &&
710 "PPC branch conditions have two components!");
711 assert(!BytesAdded && "code size not handled");
713 bool isPPC64 = Subtarget.isPPC64();
715 // One-way branch.
716 if (!FBB) {
717 if (Cond.empty()) // Unconditional branch
718 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
719 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
720 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
721 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
722 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
723 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
724 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
725 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
726 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
727 else // Conditional branch
728 BuildMI(&MBB, DL, get(PPC::BCC))
729 .addImm(Cond[0].getImm())
730 .add(Cond[1])
731 .addMBB(TBB);
732 return 1;
735 // Two-way Conditional Branch.
736 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
737 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
738 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
739 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
740 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
741 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB);
742 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
743 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB);
744 else
745 BuildMI(&MBB, DL, get(PPC::BCC))
746 .addImm(Cond[0].getImm())
747 .add(Cond[1])
748 .addMBB(TBB);
749 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
750 return 2;
753 // Select analysis.
754 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
755 ArrayRef<MachineOperand> Cond,
756 unsigned TrueReg, unsigned FalseReg,
757 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
758 if (Cond.size() != 2)
759 return false;
761 // If this is really a bdnz-like condition, then it cannot be turned into a
762 // select.
763 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
764 return false;
766 // Check register classes.
767 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
768 const TargetRegisterClass *RC =
769 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
770 if (!RC)
771 return false;
773 // isel is for regular integer GPRs only.
774 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
775 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
776 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
777 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
778 return false;
780 // FIXME: These numbers are for the A2, how well they work for other cores is
781 // an open question. On the A2, the isel instruction has a 2-cycle latency
782 // but single-cycle throughput. These numbers are used in combination with
783 // the MispredictPenalty setting from the active SchedMachineModel.
784 CondCycles = 1;
785 TrueCycles = 1;
786 FalseCycles = 1;
788 return true;
791 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
792 MachineBasicBlock::iterator MI,
793 const DebugLoc &dl, unsigned DestReg,
794 ArrayRef<MachineOperand> Cond, unsigned TrueReg,
795 unsigned FalseReg) const {
796 assert(Cond.size() == 2 &&
797 "PPC branch conditions have two components!");
799 // Get the register classes.
800 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
801 const TargetRegisterClass *RC =
802 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
803 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
805 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
806 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
807 assert((Is64Bit ||
808 PPC::GPRCRegClass.hasSubClassEq(RC) ||
809 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
810 "isel is for regular integer GPRs only");
812 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
813 auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
815 unsigned SubIdx = 0;
816 bool SwapOps = false;
817 switch (SelectPred) {
818 case PPC::PRED_EQ:
819 case PPC::PRED_EQ_MINUS:
820 case PPC::PRED_EQ_PLUS:
821 SubIdx = PPC::sub_eq; SwapOps = false; break;
822 case PPC::PRED_NE:
823 case PPC::PRED_NE_MINUS:
824 case PPC::PRED_NE_PLUS:
825 SubIdx = PPC::sub_eq; SwapOps = true; break;
826 case PPC::PRED_LT:
827 case PPC::PRED_LT_MINUS:
828 case PPC::PRED_LT_PLUS:
829 SubIdx = PPC::sub_lt; SwapOps = false; break;
830 case PPC::PRED_GE:
831 case PPC::PRED_GE_MINUS:
832 case PPC::PRED_GE_PLUS:
833 SubIdx = PPC::sub_lt; SwapOps = true; break;
834 case PPC::PRED_GT:
835 case PPC::PRED_GT_MINUS:
836 case PPC::PRED_GT_PLUS:
837 SubIdx = PPC::sub_gt; SwapOps = false; break;
838 case PPC::PRED_LE:
839 case PPC::PRED_LE_MINUS:
840 case PPC::PRED_LE_PLUS:
841 SubIdx = PPC::sub_gt; SwapOps = true; break;
842 case PPC::PRED_UN:
843 case PPC::PRED_UN_MINUS:
844 case PPC::PRED_UN_PLUS:
845 SubIdx = PPC::sub_un; SwapOps = false; break;
846 case PPC::PRED_NU:
847 case PPC::PRED_NU_MINUS:
848 case PPC::PRED_NU_PLUS:
849 SubIdx = PPC::sub_un; SwapOps = true; break;
850 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
851 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
854 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
855 SecondReg = SwapOps ? TrueReg : FalseReg;
857 // The first input register of isel cannot be r0. If it is a member
858 // of a register class that can be r0, then copy it first (the
859 // register allocator should eliminate the copy).
860 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
861 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
862 const TargetRegisterClass *FirstRC =
863 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
864 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
865 unsigned OldFirstReg = FirstReg;
866 FirstReg = MRI.createVirtualRegister(FirstRC);
867 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
868 .addReg(OldFirstReg);
871 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
872 .addReg(FirstReg).addReg(SecondReg)
873 .addReg(Cond[1].getReg(), 0, SubIdx);
876 static unsigned getCRBitValue(unsigned CRBit) {
877 unsigned Ret = 4;
878 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
879 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
880 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
881 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
882 Ret = 3;
883 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
884 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
885 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
886 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
887 Ret = 2;
888 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
889 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
890 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
891 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
892 Ret = 1;
893 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
894 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
895 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
896 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
897 Ret = 0;
899 assert(Ret != 4 && "Invalid CR bit register");
900 return Ret;
903 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
904 MachineBasicBlock::iterator I,
905 const DebugLoc &DL, unsigned DestReg,
906 unsigned SrcReg, bool KillSrc) const {
907 // We can end up with self copies and similar things as a result of VSX copy
908 // legalization. Promote them here.
909 const TargetRegisterInfo *TRI = &getRegisterInfo();
910 if (PPC::F8RCRegClass.contains(DestReg) &&
911 PPC::VSRCRegClass.contains(SrcReg)) {
912 unsigned SuperReg =
913 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
915 if (VSXSelfCopyCrash && SrcReg == SuperReg)
916 llvm_unreachable("nop VSX copy");
918 DestReg = SuperReg;
919 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
920 PPC::VSRCRegClass.contains(DestReg)) {
921 unsigned SuperReg =
922 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
924 if (VSXSelfCopyCrash && DestReg == SuperReg)
925 llvm_unreachable("nop VSX copy");
927 SrcReg = SuperReg;
930 // Different class register copy
931 if (PPC::CRBITRCRegClass.contains(SrcReg) &&
932 PPC::GPRCRegClass.contains(DestReg)) {
933 unsigned CRReg = getCRFromCRBit(SrcReg);
934 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg);
935 getKillRegState(KillSrc);
936 // Rotate the CR bit in the CR fields to be the least significant bit and
937 // then mask with 0x1 (MB = ME = 31).
938 BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
939 .addReg(DestReg, RegState::Kill)
940 .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
941 .addImm(31)
942 .addImm(31);
943 return;
944 } else if (PPC::CRRCRegClass.contains(SrcReg) &&
945 PPC::G8RCRegClass.contains(DestReg)) {
946 BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg);
947 getKillRegState(KillSrc);
948 return;
949 } else if (PPC::CRRCRegClass.contains(SrcReg) &&
950 PPC::GPRCRegClass.contains(DestReg)) {
951 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg);
952 getKillRegState(KillSrc);
953 return;
954 } else if (PPC::G8RCRegClass.contains(SrcReg) &&
955 PPC::VSFRCRegClass.contains(DestReg)) {
956 assert(Subtarget.hasDirectMove() &&
957 "Subtarget doesn't support directmove, don't know how to copy.");
958 BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg);
959 NumGPRtoVSRSpill++;
960 getKillRegState(KillSrc);
961 return;
962 } else if (PPC::VSFRCRegClass.contains(SrcReg) &&
963 PPC::G8RCRegClass.contains(DestReg)) {
964 assert(Subtarget.hasDirectMove() &&
965 "Subtarget doesn't support directmove, don't know how to copy.");
966 BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg);
967 getKillRegState(KillSrc);
968 return;
969 } else if (PPC::SPERCRegClass.contains(SrcReg) &&
970 PPC::GPRCRegClass.contains(DestReg)) {
971 BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg);
972 getKillRegState(KillSrc);
973 return;
974 } else if (PPC::GPRCRegClass.contains(SrcReg) &&
975 PPC::SPERCRegClass.contains(DestReg)) {
976 BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg);
977 getKillRegState(KillSrc);
978 return;
981 unsigned Opc;
982 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
983 Opc = PPC::OR;
984 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
985 Opc = PPC::OR8;
986 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
987 Opc = PPC::FMR;
988 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
989 Opc = PPC::MCRF;
990 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
991 Opc = PPC::VOR;
992 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
993 // There are two different ways this can be done:
994 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
995 // issue in VSU pipeline 0.
996 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
997 // can go to either pipeline.
998 // We'll always use xxlor here, because in practically all cases where
999 // copies are generated, they are close enough to some use that the
1000 // lower-latency form is preferable.
1001 Opc = PPC::XXLOR;
1002 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
1003 PPC::VSSRCRegClass.contains(DestReg, SrcReg))
1004 Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1005 else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
1006 Opc = PPC::QVFMR;
1007 else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
1008 Opc = PPC::QVFMRs;
1009 else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
1010 Opc = PPC::QVFMRb;
1011 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
1012 Opc = PPC::CROR;
1013 else if (PPC::SPERCRegClass.contains(DestReg, SrcReg))
1014 Opc = PPC::EVOR;
1015 else
1016 llvm_unreachable("Impossible reg-to-reg copy");
1018 const MCInstrDesc &MCID = get(Opc);
1019 if (MCID.getNumOperands() == 3)
1020 BuildMI(MBB, I, DL, MCID, DestReg)
1021 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
1022 else
1023 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
1026 unsigned PPCInstrInfo::getStoreOpcodeForSpill(unsigned Reg,
1027 const TargetRegisterClass *RC)
1028 const {
1029 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray();
1030 int OpcodeIndex = 0;
1032 if (RC != nullptr) {
1033 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1034 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1035 OpcodeIndex = SOK_Int4Spill;
1036 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1037 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1038 OpcodeIndex = SOK_Int8Spill;
1039 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1040 OpcodeIndex = SOK_Float8Spill;
1041 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1042 OpcodeIndex = SOK_Float4Spill;
1043 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1044 OpcodeIndex = SOK_SPESpill;
1045 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1046 OpcodeIndex = SOK_CRSpill;
1047 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1048 OpcodeIndex = SOK_CRBitSpill;
1049 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1050 OpcodeIndex = SOK_VRVectorSpill;
1051 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1052 OpcodeIndex = SOK_VSXVectorSpill;
1053 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1054 OpcodeIndex = SOK_VectorFloat8Spill;
1055 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1056 OpcodeIndex = SOK_VectorFloat4Spill;
1057 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1058 OpcodeIndex = SOK_VRSaveSpill;
1059 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1060 OpcodeIndex = SOK_QuadFloat8Spill;
1061 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1062 OpcodeIndex = SOK_QuadFloat4Spill;
1063 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1064 OpcodeIndex = SOK_QuadBitSpill;
1065 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1066 OpcodeIndex = SOK_SpillToVSR;
1067 } else {
1068 llvm_unreachable("Unknown regclass!");
1070 } else {
1071 if (PPC::GPRCRegClass.contains(Reg) ||
1072 PPC::GPRC_NOR0RegClass.contains(Reg)) {
1073 OpcodeIndex = SOK_Int4Spill;
1074 } else if (PPC::G8RCRegClass.contains(Reg) ||
1075 PPC::G8RC_NOX0RegClass.contains(Reg)) {
1076 OpcodeIndex = SOK_Int8Spill;
1077 } else if (PPC::F8RCRegClass.contains(Reg)) {
1078 OpcodeIndex = SOK_Float8Spill;
1079 } else if (PPC::F4RCRegClass.contains(Reg)) {
1080 OpcodeIndex = SOK_Float4Spill;
1081 } else if (PPC::SPERCRegClass.contains(Reg)) {
1082 OpcodeIndex = SOK_SPESpill;
1083 } else if (PPC::CRRCRegClass.contains(Reg)) {
1084 OpcodeIndex = SOK_CRSpill;
1085 } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1086 OpcodeIndex = SOK_CRBitSpill;
1087 } else if (PPC::VRRCRegClass.contains(Reg)) {
1088 OpcodeIndex = SOK_VRVectorSpill;
1089 } else if (PPC::VSRCRegClass.contains(Reg)) {
1090 OpcodeIndex = SOK_VSXVectorSpill;
1091 } else if (PPC::VSFRCRegClass.contains(Reg)) {
1092 OpcodeIndex = SOK_VectorFloat8Spill;
1093 } else if (PPC::VSSRCRegClass.contains(Reg)) {
1094 OpcodeIndex = SOK_VectorFloat4Spill;
1095 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1096 OpcodeIndex = SOK_VRSaveSpill;
1097 } else if (PPC::QFRCRegClass.contains(Reg)) {
1098 OpcodeIndex = SOK_QuadFloat8Spill;
1099 } else if (PPC::QSRCRegClass.contains(Reg)) {
1100 OpcodeIndex = SOK_QuadFloat4Spill;
1101 } else if (PPC::QBRCRegClass.contains(Reg)) {
1102 OpcodeIndex = SOK_QuadBitSpill;
1103 } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1104 OpcodeIndex = SOK_SpillToVSR;
1105 } else {
1106 llvm_unreachable("Unknown regclass!");
1109 return OpcodesForSpill[OpcodeIndex];
1112 unsigned
1113 PPCInstrInfo::getLoadOpcodeForSpill(unsigned Reg,
1114 const TargetRegisterClass *RC) const {
1115 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray();
1116 int OpcodeIndex = 0;
1118 if (RC != nullptr) {
1119 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1120 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1121 OpcodeIndex = SOK_Int4Spill;
1122 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1123 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1124 OpcodeIndex = SOK_Int8Spill;
1125 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1126 OpcodeIndex = SOK_Float8Spill;
1127 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1128 OpcodeIndex = SOK_Float4Spill;
1129 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1130 OpcodeIndex = SOK_SPESpill;
1131 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1132 OpcodeIndex = SOK_CRSpill;
1133 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1134 OpcodeIndex = SOK_CRBitSpill;
1135 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1136 OpcodeIndex = SOK_VRVectorSpill;
1137 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1138 OpcodeIndex = SOK_VSXVectorSpill;
1139 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1140 OpcodeIndex = SOK_VectorFloat8Spill;
1141 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1142 OpcodeIndex = SOK_VectorFloat4Spill;
1143 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1144 OpcodeIndex = SOK_VRSaveSpill;
1145 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1146 OpcodeIndex = SOK_QuadFloat8Spill;
1147 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1148 OpcodeIndex = SOK_QuadFloat4Spill;
1149 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1150 OpcodeIndex = SOK_QuadBitSpill;
1151 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1152 OpcodeIndex = SOK_SpillToVSR;
1153 } else {
1154 llvm_unreachable("Unknown regclass!");
1156 } else {
1157 if (PPC::GPRCRegClass.contains(Reg) ||
1158 PPC::GPRC_NOR0RegClass.contains(Reg)) {
1159 OpcodeIndex = SOK_Int4Spill;
1160 } else if (PPC::G8RCRegClass.contains(Reg) ||
1161 PPC::G8RC_NOX0RegClass.contains(Reg)) {
1162 OpcodeIndex = SOK_Int8Spill;
1163 } else if (PPC::F8RCRegClass.contains(Reg)) {
1164 OpcodeIndex = SOK_Float8Spill;
1165 } else if (PPC::F4RCRegClass.contains(Reg)) {
1166 OpcodeIndex = SOK_Float4Spill;
1167 } else if (PPC::SPERCRegClass.contains(Reg)) {
1168 OpcodeIndex = SOK_SPESpill;
1169 } else if (PPC::CRRCRegClass.contains(Reg)) {
1170 OpcodeIndex = SOK_CRSpill;
1171 } else if (PPC::CRBITRCRegClass.contains(Reg)) {
1172 OpcodeIndex = SOK_CRBitSpill;
1173 } else if (PPC::VRRCRegClass.contains(Reg)) {
1174 OpcodeIndex = SOK_VRVectorSpill;
1175 } else if (PPC::VSRCRegClass.contains(Reg)) {
1176 OpcodeIndex = SOK_VSXVectorSpill;
1177 } else if (PPC::VSFRCRegClass.contains(Reg)) {
1178 OpcodeIndex = SOK_VectorFloat8Spill;
1179 } else if (PPC::VSSRCRegClass.contains(Reg)) {
1180 OpcodeIndex = SOK_VectorFloat4Spill;
1181 } else if (PPC::VRSAVERCRegClass.contains(Reg)) {
1182 OpcodeIndex = SOK_VRSaveSpill;
1183 } else if (PPC::QFRCRegClass.contains(Reg)) {
1184 OpcodeIndex = SOK_QuadFloat8Spill;
1185 } else if (PPC::QSRCRegClass.contains(Reg)) {
1186 OpcodeIndex = SOK_QuadFloat4Spill;
1187 } else if (PPC::QBRCRegClass.contains(Reg)) {
1188 OpcodeIndex = SOK_QuadBitSpill;
1189 } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) {
1190 OpcodeIndex = SOK_SpillToVSR;
1191 } else {
1192 llvm_unreachable("Unknown regclass!");
1195 return OpcodesForSpill[OpcodeIndex];
1198 void PPCInstrInfo::StoreRegToStackSlot(
1199 MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1200 const TargetRegisterClass *RC,
1201 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1202 unsigned Opcode = getStoreOpcodeForSpill(PPC::NoRegister, RC);
1203 DebugLoc DL;
1205 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1206 FuncInfo->setHasSpills();
1208 NewMIs.push_back(addFrameReference(
1209 BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)),
1210 FrameIdx));
1212 if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1213 PPC::CRBITRCRegClass.hasSubClassEq(RC))
1214 FuncInfo->setSpillsCR();
1216 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1217 FuncInfo->setSpillsVRSAVE();
1219 if (isXFormMemOp(Opcode))
1220 FuncInfo->setHasNonRISpills();
1223 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1224 MachineBasicBlock::iterator MI,
1225 unsigned SrcReg, bool isKill,
1226 int FrameIdx,
1227 const TargetRegisterClass *RC,
1228 const TargetRegisterInfo *TRI) const {
1229 MachineFunction &MF = *MBB.getParent();
1230 SmallVector<MachineInstr *, 4> NewMIs;
1232 // We need to avoid a situation in which the value from a VRRC register is
1233 // spilled using an Altivec instruction and reloaded into a VSRC register
1234 // using a VSX instruction. The issue with this is that the VSX
1235 // load/store instructions swap the doublewords in the vector and the Altivec
1236 // ones don't. The register classes on the spill/reload may be different if
1237 // the register is defined using an Altivec instruction and is then used by a
1238 // VSX instruction.
1239 RC = updatedRC(RC);
1241 StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
1243 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1244 MBB.insert(MI, NewMIs[i]);
1246 const MachineFrameInfo &MFI = MF.getFrameInfo();
1247 MachineMemOperand *MMO = MF.getMachineMemOperand(
1248 MachinePointerInfo::getFixedStack(MF, FrameIdx),
1249 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
1250 MFI.getObjectAlignment(FrameIdx));
1251 NewMIs.back()->addMemOperand(MF, MMO);
1254 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
1255 unsigned DestReg, int FrameIdx,
1256 const TargetRegisterClass *RC,
1257 SmallVectorImpl<MachineInstr *> &NewMIs)
1258 const {
1259 unsigned Opcode = getLoadOpcodeForSpill(PPC::NoRegister, RC);
1260 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg),
1261 FrameIdx));
1262 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1264 if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
1265 PPC::CRBITRCRegClass.hasSubClassEq(RC))
1266 FuncInfo->setSpillsCR();
1268 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC))
1269 FuncInfo->setSpillsVRSAVE();
1271 if (isXFormMemOp(Opcode))
1272 FuncInfo->setHasNonRISpills();
1275 void
1276 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1277 MachineBasicBlock::iterator MI,
1278 unsigned DestReg, int FrameIdx,
1279 const TargetRegisterClass *RC,
1280 const TargetRegisterInfo *TRI) const {
1281 MachineFunction &MF = *MBB.getParent();
1282 SmallVector<MachineInstr*, 4> NewMIs;
1283 DebugLoc DL;
1284 if (MI != MBB.end()) DL = MI->getDebugLoc();
1286 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1287 FuncInfo->setHasSpills();
1289 // We need to avoid a situation in which the value from a VRRC register is
1290 // spilled using an Altivec instruction and reloaded into a VSRC register
1291 // using a VSX instruction. The issue with this is that the VSX
1292 // load/store instructions swap the doublewords in the vector and the Altivec
1293 // ones don't. The register classes on the spill/reload may be different if
1294 // the register is defined using an Altivec instruction and is then used by a
1295 // VSX instruction.
1296 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
1297 RC = &PPC::VSRCRegClass;
1299 LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
1301 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1302 MBB.insert(MI, NewMIs[i]);
1304 const MachineFrameInfo &MFI = MF.getFrameInfo();
1305 MachineMemOperand *MMO = MF.getMachineMemOperand(
1306 MachinePointerInfo::getFixedStack(MF, FrameIdx),
1307 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
1308 MFI.getObjectAlignment(FrameIdx));
1309 NewMIs.back()->addMemOperand(MF, MMO);
1312 bool PPCInstrInfo::
1313 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1314 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1315 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1316 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1317 else
1318 // Leave the CR# the same, but invert the condition.
1319 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1320 return false;
1323 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1324 unsigned Reg, MachineRegisterInfo *MRI) const {
1325 // For some instructions, it is legal to fold ZERO into the RA register field.
1326 // A zero immediate should always be loaded with a single li.
1327 unsigned DefOpc = DefMI.getOpcode();
1328 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1329 return false;
1330 if (!DefMI.getOperand(1).isImm())
1331 return false;
1332 if (DefMI.getOperand(1).getImm() != 0)
1333 return false;
1335 // Note that we cannot here invert the arguments of an isel in order to fold
1336 // a ZERO into what is presented as the second argument. All we have here
1337 // is the condition bit, and that might come from a CR-logical bit operation.
1339 const MCInstrDesc &UseMCID = UseMI.getDesc();
1341 // Only fold into real machine instructions.
1342 if (UseMCID.isPseudo())
1343 return false;
1345 unsigned UseIdx;
1346 for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
1347 if (UseMI.getOperand(UseIdx).isReg() &&
1348 UseMI.getOperand(UseIdx).getReg() == Reg)
1349 break;
1351 assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
1352 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1354 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1356 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1357 // register (which might also be specified as a pointer class kind).
1358 if (UseInfo->isLookupPtrRegClass()) {
1359 if (UseInfo->RegClass /* Kind */ != 1)
1360 return false;
1361 } else {
1362 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1363 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1364 return false;
1367 // Make sure this is not tied to an output register (or otherwise
1368 // constrained). This is true for ST?UX registers, for example, which
1369 // are tied to their output registers.
1370 if (UseInfo->Constraints != 0)
1371 return false;
1373 unsigned ZeroReg;
1374 if (UseInfo->isLookupPtrRegClass()) {
1375 bool isPPC64 = Subtarget.isPPC64();
1376 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1377 } else {
1378 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1379 PPC::ZERO8 : PPC::ZERO;
1382 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1383 UseMI.getOperand(UseIdx).setReg(ZeroReg);
1385 if (DeleteDef)
1386 DefMI.eraseFromParent();
1388 return true;
1391 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1392 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1393 I != IE; ++I)
1394 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1395 return true;
1396 return false;
1399 // We should make sure that, if we're going to predicate both sides of a
1400 // condition (a diamond), that both sides don't define the counter register. We
1401 // can predicate counter-decrement-based branches, but while that predicates
1402 // the branching, it does not predicate the counter decrement. If we tried to
1403 // merge the triangle into one predicated block, we'd decrement the counter
1404 // twice.
1405 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1406 unsigned NumT, unsigned ExtraT,
1407 MachineBasicBlock &FMBB,
1408 unsigned NumF, unsigned ExtraF,
1409 BranchProbability Probability) const {
1410 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1414 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
1415 // The predicated branches are identified by their type, not really by the
1416 // explicit presence of a predicate. Furthermore, some of them can be
1417 // predicated more than once. Because if conversion won't try to predicate
1418 // any instruction which already claims to be predicated (by returning true
1419 // here), always return false. In doing so, we let isPredicable() be the
1420 // final word on whether not the instruction can be (further) predicated.
1422 return false;
1425 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
1426 if (!MI.isTerminator())
1427 return false;
1429 // Conditional branch is a special case.
1430 if (MI.isBranch() && !MI.isBarrier())
1431 return true;
1433 return !isPredicated(MI);
1436 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
1437 ArrayRef<MachineOperand> Pred) const {
1438 unsigned OpC = MI.getOpcode();
1439 if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1440 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1441 bool isPPC64 = Subtarget.isPPC64();
1442 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
1443 : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1444 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1445 MI.setDesc(get(PPC::BCLR));
1446 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1447 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1448 MI.setDesc(get(PPC::BCLRn));
1449 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1450 } else {
1451 MI.setDesc(get(PPC::BCCLR));
1452 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1453 .addImm(Pred[0].getImm())
1454 .add(Pred[1]);
1457 return true;
1458 } else if (OpC == PPC::B) {
1459 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1460 bool isPPC64 = Subtarget.isPPC64();
1461 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
1462 : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1463 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1464 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1465 MI.RemoveOperand(0);
1467 MI.setDesc(get(PPC::BC));
1468 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1469 .add(Pred[1])
1470 .addMBB(MBB);
1471 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1472 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1473 MI.RemoveOperand(0);
1475 MI.setDesc(get(PPC::BCn));
1476 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1477 .add(Pred[1])
1478 .addMBB(MBB);
1479 } else {
1480 MachineBasicBlock *MBB = MI.getOperand(0).getMBB();
1481 MI.RemoveOperand(0);
1483 MI.setDesc(get(PPC::BCC));
1484 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1485 .addImm(Pred[0].getImm())
1486 .add(Pred[1])
1487 .addMBB(MBB);
1490 return true;
1491 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
1492 OpC == PPC::BCTRL8) {
1493 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1494 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1496 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1497 bool isPPC64 = Subtarget.isPPC64();
1499 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1500 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
1501 : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1502 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1503 return true;
1504 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1505 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
1506 : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1507 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]);
1508 return true;
1511 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
1512 : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1513 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
1514 .addImm(Pred[0].getImm())
1515 .add(Pred[1]);
1516 return true;
1519 return false;
1522 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1523 ArrayRef<MachineOperand> Pred2) const {
1524 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1525 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1527 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1528 return false;
1529 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1530 return false;
1532 // P1 can only subsume P2 if they test the same condition register.
1533 if (Pred1[1].getReg() != Pred2[1].getReg())
1534 return false;
1536 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1537 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1539 if (P1 == P2)
1540 return true;
1542 // Does P1 subsume P2, e.g. GE subsumes GT.
1543 if (P1 == PPC::PRED_LE &&
1544 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1545 return true;
1546 if (P1 == PPC::PRED_GE &&
1547 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1548 return true;
1550 return false;
1553 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI,
1554 std::vector<MachineOperand> &Pred) const {
1555 // Note: At the present time, the contents of Pred from this function is
1556 // unused by IfConversion. This implementation follows ARM by pushing the
1557 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1558 // predicate, instructions defining CTR or CTR8 are also included as
1559 // predicate-defining instructions.
1561 const TargetRegisterClass *RCs[] =
1562 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1563 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1565 bool Found = false;
1566 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1567 const MachineOperand &MO = MI.getOperand(i);
1568 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1569 const TargetRegisterClass *RC = RCs[c];
1570 if (MO.isReg()) {
1571 if (MO.isDef() && RC->contains(MO.getReg())) {
1572 Pred.push_back(MO);
1573 Found = true;
1575 } else if (MO.isRegMask()) {
1576 for (TargetRegisterClass::iterator I = RC->begin(),
1577 IE = RC->end(); I != IE; ++I)
1578 if (MO.clobbersPhysReg(*I)) {
1579 Pred.push_back(MO);
1580 Found = true;
1586 return Found;
1589 bool PPCInstrInfo::isPredicable(const MachineInstr &MI) const {
1590 unsigned OpC = MI.getOpcode();
1591 switch (OpC) {
1592 default:
1593 return false;
1594 case PPC::B:
1595 case PPC::BLR:
1596 case PPC::BLR8:
1597 case PPC::BCTR:
1598 case PPC::BCTR8:
1599 case PPC::BCTRL:
1600 case PPC::BCTRL8:
1601 return true;
1605 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1606 unsigned &SrcReg2, int &Mask,
1607 int &Value) const {
1608 unsigned Opc = MI.getOpcode();
1610 switch (Opc) {
1611 default: return false;
1612 case PPC::CMPWI:
1613 case PPC::CMPLWI:
1614 case PPC::CMPDI:
1615 case PPC::CMPLDI:
1616 SrcReg = MI.getOperand(1).getReg();
1617 SrcReg2 = 0;
1618 Value = MI.getOperand(2).getImm();
1619 Mask = 0xFFFF;
1620 return true;
1621 case PPC::CMPW:
1622 case PPC::CMPLW:
1623 case PPC::CMPD:
1624 case PPC::CMPLD:
1625 case PPC::FCMPUS:
1626 case PPC::FCMPUD:
1627 SrcReg = MI.getOperand(1).getReg();
1628 SrcReg2 = MI.getOperand(2).getReg();
1629 Value = 0;
1630 Mask = 0;
1631 return true;
1635 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
1636 unsigned SrcReg2, int Mask, int Value,
1637 const MachineRegisterInfo *MRI) const {
1638 if (DisableCmpOpt)
1639 return false;
1641 int OpC = CmpInstr.getOpcode();
1642 Register CRReg = CmpInstr.getOperand(0).getReg();
1644 // FP record forms set CR1 based on the exception status bits, not a
1645 // comparison with zero.
1646 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1647 return false;
1649 const TargetRegisterInfo *TRI = &getRegisterInfo();
1650 // The record forms set the condition register based on a signed comparison
1651 // with zero (so says the ISA manual). This is not as straightforward as it
1652 // seems, however, because this is always a 64-bit comparison on PPC64, even
1653 // for instructions that are 32-bit in nature (like slw for example).
1654 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1655 // for equality checks (as those don't depend on the sign). On PPC64,
1656 // we are restricted to equality for unsigned 64-bit comparisons and for
1657 // signed 32-bit comparisons the applicability is more restricted.
1658 bool isPPC64 = Subtarget.isPPC64();
1659 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1660 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1661 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1663 // Look through copies unless that gets us to a physical register.
1664 unsigned ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI);
1665 if (Register::isVirtualRegister(ActualSrc))
1666 SrcReg = ActualSrc;
1668 // Get the unique definition of SrcReg.
1669 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1670 if (!MI) return false;
1672 bool equalityOnly = false;
1673 bool noSub = false;
1674 if (isPPC64) {
1675 if (is32BitSignedCompare) {
1676 // We can perform this optimization only if MI is sign-extending.
1677 if (isSignExtended(*MI))
1678 noSub = true;
1679 else
1680 return false;
1681 } else if (is32BitUnsignedCompare) {
1682 // We can perform this optimization, equality only, if MI is
1683 // zero-extending.
1684 if (isZeroExtended(*MI)) {
1685 noSub = true;
1686 equalityOnly = true;
1687 } else
1688 return false;
1689 } else
1690 equalityOnly = is64BitUnsignedCompare;
1691 } else
1692 equalityOnly = is32BitUnsignedCompare;
1694 if (equalityOnly) {
1695 // We need to check the uses of the condition register in order to reject
1696 // non-equality comparisons.
1697 for (MachineRegisterInfo::use_instr_iterator
1698 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1699 I != IE; ++I) {
1700 MachineInstr *UseMI = &*I;
1701 if (UseMI->getOpcode() == PPC::BCC) {
1702 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1703 unsigned PredCond = PPC::getPredicateCondition(Pred);
1704 // We ignore hint bits when checking for non-equality comparisons.
1705 if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
1706 return false;
1707 } else if (UseMI->getOpcode() == PPC::ISEL ||
1708 UseMI->getOpcode() == PPC::ISEL8) {
1709 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1710 if (SubIdx != PPC::sub_eq)
1711 return false;
1712 } else
1713 return false;
1717 MachineBasicBlock::iterator I = CmpInstr;
1719 // Scan forward to find the first use of the compare.
1720 for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
1721 ++I) {
1722 bool FoundUse = false;
1723 for (MachineRegisterInfo::use_instr_iterator
1724 J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end();
1725 J != JE; ++J)
1726 if (&*J == &*I) {
1727 FoundUse = true;
1728 break;
1731 if (FoundUse)
1732 break;
1735 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1736 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1738 // There are two possible candidates which can be changed to set CR[01].
1739 // One is MI, the other is a SUB instruction.
1740 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1741 MachineInstr *Sub = nullptr;
1742 if (SrcReg2 != 0)
1743 // MI is not a candidate for CMPrr.
1744 MI = nullptr;
1745 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1746 // same BB as the comparison. This is to allow the check below to avoid calls
1747 // (and other explicit clobbers); instead we should really check for these
1748 // more explicitly (in at least a few predecessors).
1749 else if (MI->getParent() != CmpInstr.getParent())
1750 return false;
1751 else if (Value != 0) {
1752 // The record-form instructions set CR bit based on signed comparison
1753 // against 0. We try to convert a compare against 1 or -1 into a compare
1754 // against 0 to exploit record-form instructions. For example, we change
1755 // the condition "greater than -1" into "greater than or equal to 0"
1756 // and "less than 1" into "less than or equal to 0".
1758 // Since we optimize comparison based on a specific branch condition,
1759 // we don't optimize if condition code is used by more than once.
1760 if (equalityOnly || !MRI->hasOneUse(CRReg))
1761 return false;
1763 MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg);
1764 if (UseMI->getOpcode() != PPC::BCC)
1765 return false;
1767 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm();
1768 unsigned PredCond = PPC::getPredicateCondition(Pred);
1769 unsigned PredHint = PPC::getPredicateHint(Pred);
1770 int16_t Immed = (int16_t)Value;
1772 // When modifying the condition in the predicate, we propagate hint bits
1773 // from the original predicate to the new one.
1774 if (Immed == -1 && PredCond == PPC::PRED_GT)
1775 // We convert "greater than -1" into "greater than or equal to 0",
1776 // since we are assuming signed comparison by !equalityOnly
1777 Pred = PPC::getPredicate(PPC::PRED_GE, PredHint);
1778 else if (Immed == -1 && PredCond == PPC::PRED_LE)
1779 // We convert "less than or equal to -1" into "less than 0".
1780 Pred = PPC::getPredicate(PPC::PRED_LT, PredHint);
1781 else if (Immed == 1 && PredCond == PPC::PRED_LT)
1782 // We convert "less than 1" into "less than or equal to 0".
1783 Pred = PPC::getPredicate(PPC::PRED_LE, PredHint);
1784 else if (Immed == 1 && PredCond == PPC::PRED_GE)
1785 // We convert "greater than or equal to 1" into "greater than 0".
1786 Pred = PPC::getPredicate(PPC::PRED_GT, PredHint);
1787 else
1788 return false;
1790 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred));
1793 // Search for Sub.
1794 --I;
1796 // Get ready to iterate backward from CmpInstr.
1797 MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
1799 for (; I != E && !noSub; --I) {
1800 const MachineInstr &Instr = *I;
1801 unsigned IOpC = Instr.getOpcode();
1803 if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) ||
1804 Instr.readsRegister(PPC::CR0, TRI)))
1805 // This instruction modifies or uses the record condition register after
1806 // the one we want to change. While we could do this transformation, it
1807 // would likely not be profitable. This transformation removes one
1808 // instruction, and so even forcing RA to generate one move probably
1809 // makes it unprofitable.
1810 return false;
1812 // Check whether CmpInstr can be made redundant by the current instruction.
1813 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1814 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1815 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1816 ((Instr.getOperand(1).getReg() == SrcReg &&
1817 Instr.getOperand(2).getReg() == SrcReg2) ||
1818 (Instr.getOperand(1).getReg() == SrcReg2 &&
1819 Instr.getOperand(2).getReg() == SrcReg))) {
1820 Sub = &*I;
1821 break;
1824 if (I == B)
1825 // The 'and' is below the comparison instruction.
1826 return false;
1829 // Return false if no candidates exist.
1830 if (!MI && !Sub)
1831 return false;
1833 // The single candidate is called MI.
1834 if (!MI) MI = Sub;
1836 int NewOpC = -1;
1837 int MIOpC = MI->getOpcode();
1838 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8 ||
1839 MIOpC == PPC::ANDISo || MIOpC == PPC::ANDISo8)
1840 NewOpC = MIOpC;
1841 else {
1842 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1843 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1844 NewOpC = MIOpC;
1847 // FIXME: On the non-embedded POWER architectures, only some of the record
1848 // forms are fast, and we should use only the fast ones.
1850 // The defining instruction has a record form (or is already a record
1851 // form). It is possible, however, that we'll need to reverse the condition
1852 // code of the users.
1853 if (NewOpC == -1)
1854 return false;
1856 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1857 // needs to be updated to be based on SUB. Push the condition code
1858 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1859 // condition code of these operands will be modified.
1860 // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
1861 // comparison against 0, which may modify predicate.
1862 bool ShouldSwap = false;
1863 if (Sub && Value == 0) {
1864 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1865 Sub->getOperand(2).getReg() == SrcReg;
1867 // The operands to subf are the opposite of sub, so only in the fixed-point
1868 // case, invert the order.
1869 ShouldSwap = !ShouldSwap;
1872 if (ShouldSwap)
1873 for (MachineRegisterInfo::use_instr_iterator
1874 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1875 I != IE; ++I) {
1876 MachineInstr *UseMI = &*I;
1877 if (UseMI->getOpcode() == PPC::BCC) {
1878 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1879 unsigned PredCond = PPC::getPredicateCondition(Pred);
1880 assert((!equalityOnly ||
1881 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
1882 "Invalid predicate for equality-only optimization");
1883 (void)PredCond; // To suppress warning in release build.
1884 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1885 PPC::getSwappedPredicate(Pred)));
1886 } else if (UseMI->getOpcode() == PPC::ISEL ||
1887 UseMI->getOpcode() == PPC::ISEL8) {
1888 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1889 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1890 "Invalid CR bit for equality-only optimization");
1892 if (NewSubReg == PPC::sub_lt)
1893 NewSubReg = PPC::sub_gt;
1894 else if (NewSubReg == PPC::sub_gt)
1895 NewSubReg = PPC::sub_lt;
1897 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1898 NewSubReg));
1899 } else // We need to abort on a user we don't understand.
1900 return false;
1902 assert(!(Value != 0 && ShouldSwap) &&
1903 "Non-zero immediate support and ShouldSwap"
1904 "may conflict in updating predicate");
1906 // Create a new virtual register to hold the value of the CR set by the
1907 // record-form instruction. If the instruction was not previously in
1908 // record form, then set the kill flag on the CR.
1909 CmpInstr.eraseFromParent();
1911 MachineBasicBlock::iterator MII = MI;
1912 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1913 get(TargetOpcode::COPY), CRReg)
1914 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1916 // Even if CR0 register were dead before, it is alive now since the
1917 // instruction we just built uses it.
1918 MI->clearRegisterDeads(PPC::CR0);
1920 if (MIOpC != NewOpC) {
1921 // We need to be careful here: we're replacing one instruction with
1922 // another, and we need to make sure that we get all of the right
1923 // implicit uses and defs. On the other hand, the caller may be holding
1924 // an iterator to this instruction, and so we can't delete it (this is
1925 // specifically the case if this is the instruction directly after the
1926 // compare).
1928 // Rotates are expensive instructions. If we're emitting a record-form
1929 // rotate that can just be an andi/andis, we should just emit that.
1930 if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
1931 Register GPRRes = MI->getOperand(0).getReg();
1932 int64_t SH = MI->getOperand(2).getImm();
1933 int64_t MB = MI->getOperand(3).getImm();
1934 int64_t ME = MI->getOperand(4).getImm();
1935 // We can only do this if both the start and end of the mask are in the
1936 // same halfword.
1937 bool MBInLoHWord = MB >= 16;
1938 bool MEInLoHWord = ME >= 16;
1939 uint64_t Mask = ~0LLU;
1941 if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
1942 Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
1943 // The mask value needs to shift right 16 if we're emitting andis.
1944 Mask >>= MBInLoHWord ? 0 : 16;
1945 NewOpC = MIOpC == PPC::RLWINM ?
1946 (MBInLoHWord ? PPC::ANDIo : PPC::ANDISo) :
1947 (MBInLoHWord ? PPC::ANDIo8 :PPC::ANDISo8);
1948 } else if (MRI->use_empty(GPRRes) && (ME == 31) &&
1949 (ME - MB + 1 == SH) && (MB >= 16)) {
1950 // If we are rotating by the exact number of bits as are in the mask
1951 // and the mask is in the least significant bits of the register,
1952 // that's just an andis. (as long as the GPR result has no uses).
1953 Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
1954 Mask >>= 16;
1955 NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDISo :PPC::ANDISo8;
1957 // If we've set the mask, we can transform.
1958 if (Mask != ~0LLU) {
1959 MI->RemoveOperand(4);
1960 MI->RemoveOperand(3);
1961 MI->getOperand(2).setImm(Mask);
1962 NumRcRotatesConvertedToRcAnd++;
1964 } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) {
1965 int64_t MB = MI->getOperand(3).getImm();
1966 if (MB >= 48) {
1967 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
1968 NewOpC = PPC::ANDIo8;
1969 MI->RemoveOperand(3);
1970 MI->getOperand(2).setImm(Mask);
1971 NumRcRotatesConvertedToRcAnd++;
1975 const MCInstrDesc &NewDesc = get(NewOpC);
1976 MI->setDesc(NewDesc);
1978 if (NewDesc.ImplicitDefs)
1979 for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs();
1980 *ImpDefs; ++ImpDefs)
1981 if (!MI->definesRegister(*ImpDefs))
1982 MI->addOperand(*MI->getParent()->getParent(),
1983 MachineOperand::CreateReg(*ImpDefs, true, true));
1984 if (NewDesc.ImplicitUses)
1985 for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses();
1986 *ImpUses; ++ImpUses)
1987 if (!MI->readsRegister(*ImpUses))
1988 MI->addOperand(*MI->getParent()->getParent(),
1989 MachineOperand::CreateReg(*ImpUses, false, true));
1991 assert(MI->definesRegister(PPC::CR0) &&
1992 "Record-form instruction does not define cr0?");
1994 // Modify the condition code of operands in OperandsToUpdate.
1995 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1996 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1997 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1998 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2000 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2001 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2003 return true;
2006 /// GetInstSize - Return the number of bytes of code the specified
2007 /// instruction may be. This returns the maximum number of bytes.
2009 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
2010 unsigned Opcode = MI.getOpcode();
2012 if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) {
2013 const MachineFunction *MF = MI.getParent()->getParent();
2014 const char *AsmStr = MI.getOperand(0).getSymbolName();
2015 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
2016 } else if (Opcode == TargetOpcode::STACKMAP) {
2017 StackMapOpers Opers(&MI);
2018 return Opers.getNumPatchBytes();
2019 } else if (Opcode == TargetOpcode::PATCHPOINT) {
2020 PatchPointOpers Opers(&MI);
2021 return Opers.getNumPatchBytes();
2022 } else {
2023 return get(Opcode).getSize();
2027 std::pair<unsigned, unsigned>
2028 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
2029 const unsigned Mask = PPCII::MO_ACCESS_MASK;
2030 return std::make_pair(TF & Mask, TF & ~Mask);
2033 ArrayRef<std::pair<unsigned, const char *>>
2034 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
2035 using namespace PPCII;
2036 static const std::pair<unsigned, const char *> TargetFlags[] = {
2037 {MO_LO, "ppc-lo"},
2038 {MO_HA, "ppc-ha"},
2039 {MO_TPREL_LO, "ppc-tprel-lo"},
2040 {MO_TPREL_HA, "ppc-tprel-ha"},
2041 {MO_DTPREL_LO, "ppc-dtprel-lo"},
2042 {MO_TLSLD_LO, "ppc-tlsld-lo"},
2043 {MO_TOC_LO, "ppc-toc-lo"},
2044 {MO_TLS, "ppc-tls"}};
2045 return makeArrayRef(TargetFlags);
2048 ArrayRef<std::pair<unsigned, const char *>>
2049 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
2050 using namespace PPCII;
2051 static const std::pair<unsigned, const char *> TargetFlags[] = {
2052 {MO_PLT, "ppc-plt"},
2053 {MO_PIC_FLAG, "ppc-pic"},
2054 {MO_NLP_FLAG, "ppc-nlp"},
2055 {MO_NLP_HIDDEN_FLAG, "ppc-nlp-hidden"}};
2056 return makeArrayRef(TargetFlags);
2059 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
2060 // The VSX versions have the advantage of a full 64-register target whereas
2061 // the FP ones have the advantage of lower latency and higher throughput. So
2062 // what we are after is using the faster instructions in low register pressure
2063 // situations and using the larger register file in high register pressure
2064 // situations.
2065 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
2066 unsigned UpperOpcode, LowerOpcode;
2067 switch (MI.getOpcode()) {
2068 case PPC::DFLOADf32:
2069 UpperOpcode = PPC::LXSSP;
2070 LowerOpcode = PPC::LFS;
2071 break;
2072 case PPC::DFLOADf64:
2073 UpperOpcode = PPC::LXSD;
2074 LowerOpcode = PPC::LFD;
2075 break;
2076 case PPC::DFSTOREf32:
2077 UpperOpcode = PPC::STXSSP;
2078 LowerOpcode = PPC::STFS;
2079 break;
2080 case PPC::DFSTOREf64:
2081 UpperOpcode = PPC::STXSD;
2082 LowerOpcode = PPC::STFD;
2083 break;
2084 case PPC::XFLOADf32:
2085 UpperOpcode = PPC::LXSSPX;
2086 LowerOpcode = PPC::LFSX;
2087 break;
2088 case PPC::XFLOADf64:
2089 UpperOpcode = PPC::LXSDX;
2090 LowerOpcode = PPC::LFDX;
2091 break;
2092 case PPC::XFSTOREf32:
2093 UpperOpcode = PPC::STXSSPX;
2094 LowerOpcode = PPC::STFSX;
2095 break;
2096 case PPC::XFSTOREf64:
2097 UpperOpcode = PPC::STXSDX;
2098 LowerOpcode = PPC::STFDX;
2099 break;
2100 case PPC::LIWAX:
2101 UpperOpcode = PPC::LXSIWAX;
2102 LowerOpcode = PPC::LFIWAX;
2103 break;
2104 case PPC::LIWZX:
2105 UpperOpcode = PPC::LXSIWZX;
2106 LowerOpcode = PPC::LFIWZX;
2107 break;
2108 case PPC::STIWX:
2109 UpperOpcode = PPC::STXSIWX;
2110 LowerOpcode = PPC::STFIWX;
2111 break;
2112 default:
2113 llvm_unreachable("Unknown Operation!");
2116 Register TargetReg = MI.getOperand(0).getReg();
2117 unsigned Opcode;
2118 if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
2119 (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
2120 Opcode = LowerOpcode;
2121 else
2122 Opcode = UpperOpcode;
2123 MI.setDesc(get(Opcode));
2124 return true;
2127 static bool isAnImmediateOperand(const MachineOperand &MO) {
2128 return MO.isCPI() || MO.isGlobal() || MO.isImm();
2131 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2132 auto &MBB = *MI.getParent();
2133 auto DL = MI.getDebugLoc();
2135 switch (MI.getOpcode()) {
2136 case TargetOpcode::LOAD_STACK_GUARD: {
2137 assert(Subtarget.isTargetLinux() &&
2138 "Only Linux target is expected to contain LOAD_STACK_GUARD");
2139 const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
2140 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
2141 MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
2142 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2143 .addImm(Offset)
2144 .addReg(Reg);
2145 return true;
2147 case PPC::DFLOADf32:
2148 case PPC::DFLOADf64:
2149 case PPC::DFSTOREf32:
2150 case PPC::DFSTOREf64: {
2151 assert(Subtarget.hasP9Vector() &&
2152 "Invalid D-Form Pseudo-ops on Pre-P9 target.");
2153 assert(MI.getOperand(2).isReg() &&
2154 isAnImmediateOperand(MI.getOperand(1)) &&
2155 "D-form op must have register and immediate operands");
2156 return expandVSXMemPseudo(MI);
2158 case PPC::XFLOADf32:
2159 case PPC::XFSTOREf32:
2160 case PPC::LIWAX:
2161 case PPC::LIWZX:
2162 case PPC::STIWX: {
2163 assert(Subtarget.hasP8Vector() &&
2164 "Invalid X-Form Pseudo-ops on Pre-P8 target.");
2165 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2166 "X-form op must have register and register operands");
2167 return expandVSXMemPseudo(MI);
2169 case PPC::XFLOADf64:
2170 case PPC::XFSTOREf64: {
2171 assert(Subtarget.hasVSX() &&
2172 "Invalid X-Form Pseudo-ops on target that has no VSX.");
2173 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
2174 "X-form op must have register and register operands");
2175 return expandVSXMemPseudo(MI);
2177 case PPC::SPILLTOVSR_LD: {
2178 Register TargetReg = MI.getOperand(0).getReg();
2179 if (PPC::VSFRCRegClass.contains(TargetReg)) {
2180 MI.setDesc(get(PPC::DFLOADf64));
2181 return expandPostRAPseudo(MI);
2183 else
2184 MI.setDesc(get(PPC::LD));
2185 return true;
2187 case PPC::SPILLTOVSR_ST: {
2188 Register SrcReg = MI.getOperand(0).getReg();
2189 if (PPC::VSFRCRegClass.contains(SrcReg)) {
2190 NumStoreSPILLVSRRCAsVec++;
2191 MI.setDesc(get(PPC::DFSTOREf64));
2192 return expandPostRAPseudo(MI);
2193 } else {
2194 NumStoreSPILLVSRRCAsGpr++;
2195 MI.setDesc(get(PPC::STD));
2197 return true;
2199 case PPC::SPILLTOVSR_LDX: {
2200 Register TargetReg = MI.getOperand(0).getReg();
2201 if (PPC::VSFRCRegClass.contains(TargetReg))
2202 MI.setDesc(get(PPC::LXSDX));
2203 else
2204 MI.setDesc(get(PPC::LDX));
2205 return true;
2207 case PPC::SPILLTOVSR_STX: {
2208 Register SrcReg = MI.getOperand(0).getReg();
2209 if (PPC::VSFRCRegClass.contains(SrcReg)) {
2210 NumStoreSPILLVSRRCAsVec++;
2211 MI.setDesc(get(PPC::STXSDX));
2212 } else {
2213 NumStoreSPILLVSRRCAsGpr++;
2214 MI.setDesc(get(PPC::STDX));
2216 return true;
2219 case PPC::CFENCE8: {
2220 auto Val = MI.getOperand(0).getReg();
2221 BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val);
2222 BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP))
2223 .addImm(PPC::PRED_NE_MINUS)
2224 .addReg(PPC::CR7)
2225 .addImm(1);
2226 MI.setDesc(get(PPC::ISYNC));
2227 MI.RemoveOperand(0);
2228 return true;
2231 return false;
2234 // Essentially a compile-time implementation of a compare->isel sequence.
2235 // It takes two constants to compare, along with the true/false registers
2236 // and the comparison type (as a subreg to a CR field) and returns one
2237 // of the true/false registers, depending on the comparison results.
2238 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
2239 unsigned TrueReg, unsigned FalseReg,
2240 unsigned CRSubReg) {
2241 // Signed comparisons. The immediates are assumed to be sign-extended.
2242 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
2243 switch (CRSubReg) {
2244 default: llvm_unreachable("Unknown integer comparison type.");
2245 case PPC::sub_lt:
2246 return Imm1 < Imm2 ? TrueReg : FalseReg;
2247 case PPC::sub_gt:
2248 return Imm1 > Imm2 ? TrueReg : FalseReg;
2249 case PPC::sub_eq:
2250 return Imm1 == Imm2 ? TrueReg : FalseReg;
2253 // Unsigned comparisons.
2254 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
2255 switch (CRSubReg) {
2256 default: llvm_unreachable("Unknown integer comparison type.");
2257 case PPC::sub_lt:
2258 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
2259 case PPC::sub_gt:
2260 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
2261 case PPC::sub_eq:
2262 return Imm1 == Imm2 ? TrueReg : FalseReg;
2265 return PPC::NoRegister;
2268 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
2269 unsigned OpNo,
2270 int64_t Imm) const {
2271 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
2272 // Replace the REG with the Immediate.
2273 Register InUseReg = MI.getOperand(OpNo).getReg();
2274 MI.getOperand(OpNo).ChangeToImmediate(Imm);
2276 if (MI.implicit_operands().empty())
2277 return;
2279 // We need to make sure that the MI didn't have any implicit use
2280 // of this REG any more.
2281 const TargetRegisterInfo *TRI = &getRegisterInfo();
2282 int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI);
2283 if (UseOpIdx >= 0) {
2284 MachineOperand &MO = MI.getOperand(UseOpIdx);
2285 if (MO.isImplicit())
2286 // The operands must always be in the following order:
2287 // - explicit reg defs,
2288 // - other explicit operands (reg uses, immediates, etc.),
2289 // - implicit reg defs
2290 // - implicit reg uses
2291 // Therefore, removing the implicit operand won't change the explicit
2292 // operands layout.
2293 MI.RemoveOperand(UseOpIdx);
2297 // Replace an instruction with one that materializes a constant (and sets
2298 // CR0 if the original instruction was a record-form instruction).
2299 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
2300 const LoadImmediateInfo &LII) const {
2301 // Remove existing operands.
2302 int OperandToKeep = LII.SetCR ? 1 : 0;
2303 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
2304 MI.RemoveOperand(i);
2306 // Replace the instruction.
2307 if (LII.SetCR) {
2308 MI.setDesc(get(LII.Is64Bit ? PPC::ANDIo8 : PPC::ANDIo));
2309 // Set the immediate.
2310 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2311 .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine);
2312 return;
2314 else
2315 MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI));
2317 // Set the immediate.
2318 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2319 .addImm(LII.Imm);
2322 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
2323 bool &SeenIntermediateUse) const {
2324 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
2325 "Should be called after register allocation.");
2326 const TargetRegisterInfo *TRI = &getRegisterInfo();
2327 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
2328 It++;
2329 SeenIntermediateUse = false;
2330 for (; It != E; ++It) {
2331 if (It->modifiesRegister(Reg, TRI))
2332 return &*It;
2333 if (It->readsRegister(Reg, TRI))
2334 SeenIntermediateUse = true;
2336 return nullptr;
2339 MachineInstr *PPCInstrInfo::getForwardingDefMI(
2340 MachineInstr &MI,
2341 unsigned &OpNoForForwarding,
2342 bool &SeenIntermediateUse) const {
2343 OpNoForForwarding = ~0U;
2344 MachineInstr *DefMI = nullptr;
2345 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
2346 const TargetRegisterInfo *TRI = &getRegisterInfo();
2347 // If we're in SSA, get the defs through the MRI. Otherwise, only look
2348 // within the basic block to see if the register is defined using an LI/LI8.
2349 if (MRI->isSSA()) {
2350 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2351 if (!MI.getOperand(i).isReg())
2352 continue;
2353 Register Reg = MI.getOperand(i).getReg();
2354 if (!Register::isVirtualRegister(Reg))
2355 continue;
2356 unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI);
2357 if (Register::isVirtualRegister(TrueReg)) {
2358 DefMI = MRI->getVRegDef(TrueReg);
2359 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) {
2360 OpNoForForwarding = i;
2361 break;
2365 } else {
2366 // Looking back through the definition for each operand could be expensive,
2367 // so exit early if this isn't an instruction that either has an immediate
2368 // form or is already an immediate form that we can handle.
2369 ImmInstrInfo III;
2370 unsigned Opc = MI.getOpcode();
2371 bool ConvertibleImmForm =
2372 Opc == PPC::CMPWI || Opc == PPC::CMPLWI ||
2373 Opc == PPC::CMPDI || Opc == PPC::CMPLDI ||
2374 Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
2375 Opc == PPC::ORI || Opc == PPC::ORI8 ||
2376 Opc == PPC::XORI || Opc == PPC::XORI8 ||
2377 Opc == PPC::RLDICL || Opc == PPC::RLDICLo ||
2378 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
2379 Opc == PPC::RLWINM || Opc == PPC::RLWINMo ||
2380 Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8o;
2381 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg())
2382 ? isVFRegister(MI.getOperand(0).getReg())
2383 : false;
2384 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true))
2385 return nullptr;
2387 // Don't convert or %X, %Y, %Y since that's just a register move.
2388 if ((Opc == PPC::OR || Opc == PPC::OR8) &&
2389 MI.getOperand(1).getReg() == MI.getOperand(2).getReg())
2390 return nullptr;
2391 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
2392 MachineOperand &MO = MI.getOperand(i);
2393 SeenIntermediateUse = false;
2394 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
2395 Register Reg = MI.getOperand(i).getReg();
2396 // If we see another use of this reg between the def and the MI,
2397 // we want to flat it so the def isn't deleted.
2398 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
2399 if (DefMI) {
2400 // Is this register defined by some form of add-immediate (including
2401 // load-immediate) within this basic block?
2402 switch (DefMI->getOpcode()) {
2403 default:
2404 break;
2405 case PPC::LI:
2406 case PPC::LI8:
2407 case PPC::ADDItocL:
2408 case PPC::ADDI:
2409 case PPC::ADDI8:
2410 OpNoForForwarding = i;
2411 return DefMI;
2417 return OpNoForForwarding == ~0U ? nullptr : DefMI;
2420 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const {
2421 static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2422 // Power 8
2423 {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2424 PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX,
2425 PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2426 PPC::SPILLTOVSR_ST, PPC::EVSTDD},
2427 // Power 9
2428 {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR,
2429 PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32,
2430 PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb,
2431 PPC::SPILLTOVSR_ST}};
2433 return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2436 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const {
2437 static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = {
2438 // Power 8
2439 {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2440 PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX,
2441 PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2442 PPC::SPILLTOVSR_LD, PPC::EVLDD},
2443 // Power 9
2444 {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR,
2445 PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32,
2446 PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb,
2447 PPC::SPILLTOVSR_LD}};
2449 return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0];
2452 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI,
2453 unsigned RegNo) const {
2454 const MachineRegisterInfo &MRI =
2455 StartMI.getParent()->getParent()->getRegInfo();
2456 if (MRI.isSSA())
2457 return;
2459 // Instructions between [StartMI, EndMI] should be in same basic block.
2460 assert((StartMI.getParent() == EndMI.getParent()) &&
2461 "Instructions are not in same basic block");
2463 bool IsKillSet = false;
2465 auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) {
2466 MachineOperand &MO = MI.getOperand(Index);
2467 if (MO.isReg() && MO.isUse() && MO.isKill() &&
2468 getRegisterInfo().regsOverlap(MO.getReg(), RegNo))
2469 MO.setIsKill(false);
2472 // Set killed flag for EndMI.
2473 // No need to do anything if EndMI defines RegNo.
2474 int UseIndex =
2475 EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo());
2476 if (UseIndex != -1) {
2477 EndMI.getOperand(UseIndex).setIsKill(true);
2478 IsKillSet = true;
2479 // Clear killed flag for other EndMI operands related to RegNo. In some
2480 // upexpected cases, killed may be set multiple times for same register
2481 // operand in same MI.
2482 for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i)
2483 if (i != UseIndex)
2484 clearOperandKillInfo(EndMI, i);
2487 // Walking the inst in reverse order (EndMI -> StartMI].
2488 MachineBasicBlock::reverse_iterator It = EndMI;
2489 MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend();
2490 // EndMI has been handled above, skip it here.
2491 It++;
2492 MachineOperand *MO = nullptr;
2493 for (; It != E; ++It) {
2494 // Skip insturctions which could not be a def/use of RegNo.
2495 if (It->isDebugInstr() || It->isPosition())
2496 continue;
2498 // Clear killed flag for all It operands related to RegNo. In some
2499 // upexpected cases, killed may be set multiple times for same register
2500 // operand in same MI.
2501 for (int i = 0, e = It->getNumOperands(); i != e; ++i)
2502 clearOperandKillInfo(*It, i);
2504 // If killed is not set, set killed for its last use or set dead for its def
2505 // if no use found.
2506 if (!IsKillSet) {
2507 if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) {
2508 // Use found, set it killed.
2509 IsKillSet = true;
2510 MO->setIsKill(true);
2511 continue;
2512 } else if ((MO = It->findRegisterDefOperand(RegNo, false, true,
2513 &getRegisterInfo()))) {
2514 // No use found, set dead for its def.
2515 assert(&*It == &StartMI && "No new def between StartMI and EndMI.");
2516 MO->setIsDead(true);
2517 break;
2521 if ((&*It) == &StartMI)
2522 break;
2524 // Ensure RegMo liveness is killed after EndMI.
2525 assert((IsKillSet || (MO && MO->isDead())) &&
2526 "RegNo should be killed or dead");
2529 // If this instruction has an immediate form and one of its operands is a
2530 // result of a load-immediate or an add-immediate, convert it to
2531 // the immediate form if the constant is in range.
2532 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
2533 MachineInstr **KilledDef) const {
2534 MachineFunction *MF = MI.getParent()->getParent();
2535 MachineRegisterInfo *MRI = &MF->getRegInfo();
2536 bool PostRA = !MRI->isSSA();
2537 bool SeenIntermediateUse = true;
2538 unsigned ForwardingOperand = ~0U;
2539 MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand,
2540 SeenIntermediateUse);
2541 if (!DefMI)
2542 return false;
2543 assert(ForwardingOperand < MI.getNumOperands() &&
2544 "The forwarding operand needs to be valid at this point");
2545 bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill();
2546 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
2547 Register ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg();
2548 if (KilledDef && KillFwdDefMI)
2549 *KilledDef = DefMI;
2551 ImmInstrInfo III;
2552 bool IsVFReg = MI.getOperand(0).isReg()
2553 ? isVFRegister(MI.getOperand(0).getReg())
2554 : false;
2555 bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA);
2556 // If this is a reg+reg instruction that has a reg+imm form,
2557 // and one of the operands is produced by an add-immediate,
2558 // try to convert it.
2559 if (HasImmForm &&
2560 transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI,
2561 KillFwdDefMI))
2562 return true;
2564 if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) ||
2565 !DefMI->getOperand(1).isImm())
2566 return false;
2568 int64_t Immediate = DefMI->getOperand(1).getImm();
2569 // Sign-extend to 64-bits.
2570 int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
2571 (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
2573 // If this is a reg+reg instruction that has a reg+imm form,
2574 // and one of the operands is produced by LI, convert it now.
2575 if (HasImmForm)
2576 return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm);
2578 bool ReplaceWithLI = false;
2579 bool Is64BitLI = false;
2580 int64_t NewImm = 0;
2581 bool SetCR = false;
2582 unsigned Opc = MI.getOpcode();
2583 switch (Opc) {
2584 default: return false;
2586 // FIXME: Any branches conditional on such a comparison can be made
2587 // unconditional. At this time, this happens too infrequently to be worth
2588 // the implementation effort, but if that ever changes, we could convert
2589 // such a pattern here.
2590 case PPC::CMPWI:
2591 case PPC::CMPLWI:
2592 case PPC::CMPDI:
2593 case PPC::CMPLDI: {
2594 // Doing this post-RA would require dataflow analysis to reliably find uses
2595 // of the CR register set by the compare.
2596 // No need to fixup killed/dead flag since this transformation is only valid
2597 // before RA.
2598 if (PostRA)
2599 return false;
2600 // If a compare-immediate is fed by an immediate and is itself an input of
2601 // an ISEL (the most common case) into a COPY of the correct register.
2602 bool Changed = false;
2603 Register DefReg = MI.getOperand(0).getReg();
2604 int64_t Comparand = MI.getOperand(2).getImm();
2605 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ?
2606 (Comparand | 0xFFFFFFFFFFFF0000) : Comparand;
2608 for (auto &CompareUseMI : MRI->use_instructions(DefReg)) {
2609 unsigned UseOpc = CompareUseMI.getOpcode();
2610 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
2611 continue;
2612 unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg();
2613 Register TrueReg = CompareUseMI.getOperand(1).getReg();
2614 Register FalseReg = CompareUseMI.getOperand(2).getReg();
2615 unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg,
2616 FalseReg, CRSubReg);
2617 if (RegToCopy == PPC::NoRegister)
2618 continue;
2619 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
2620 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
2621 CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
2622 replaceInstrOperandWithImm(CompareUseMI, 1, 0);
2623 CompareUseMI.RemoveOperand(3);
2624 CompareUseMI.RemoveOperand(2);
2625 continue;
2627 LLVM_DEBUG(
2628 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
2629 LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump());
2630 LLVM_DEBUG(dbgs() << "Is converted to:\n");
2631 // Convert to copy and remove unneeded operands.
2632 CompareUseMI.setDesc(get(PPC::COPY));
2633 CompareUseMI.RemoveOperand(3);
2634 CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1);
2635 CmpIselsConverted++;
2636 Changed = true;
2637 LLVM_DEBUG(CompareUseMI.dump());
2639 if (Changed)
2640 return true;
2641 // This may end up incremented multiple times since this function is called
2642 // during a fixed-point transformation, but it is only meant to indicate the
2643 // presence of this opportunity.
2644 MissedConvertibleImmediateInstrs++;
2645 return false;
2648 // Immediate forms - may simply be convertable to an LI.
2649 case PPC::ADDI:
2650 case PPC::ADDI8: {
2651 // Does the sum fit in a 16-bit signed field?
2652 int64_t Addend = MI.getOperand(2).getImm();
2653 if (isInt<16>(Addend + SExtImm)) {
2654 ReplaceWithLI = true;
2655 Is64BitLI = Opc == PPC::ADDI8;
2656 NewImm = Addend + SExtImm;
2657 break;
2659 return false;
2661 case PPC::RLDICL:
2662 case PPC::RLDICLo:
2663 case PPC::RLDICL_32:
2664 case PPC::RLDICL_32_64: {
2665 // Use APInt's rotate function.
2666 int64_t SH = MI.getOperand(2).getImm();
2667 int64_t MB = MI.getOperand(3).getImm();
2668 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICLo) ?
2669 64 : 32, SExtImm, true);
2670 InVal = InVal.rotl(SH);
2671 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2672 InVal &= Mask;
2673 // Can't replace negative values with an LI as that will sign-extend
2674 // and not clear the left bits. If we're setting the CR bit, we will use
2675 // ANDIo which won't sign extend, so that's safe.
2676 if (isUInt<15>(InVal.getSExtValue()) ||
2677 (Opc == PPC::RLDICLo && isUInt<16>(InVal.getSExtValue()))) {
2678 ReplaceWithLI = true;
2679 Is64BitLI = Opc != PPC::RLDICL_32;
2680 NewImm = InVal.getSExtValue();
2681 SetCR = Opc == PPC::RLDICLo;
2682 break;
2684 return false;
2686 case PPC::RLWINM:
2687 case PPC::RLWINM8:
2688 case PPC::RLWINMo:
2689 case PPC::RLWINM8o: {
2690 int64_t SH = MI.getOperand(2).getImm();
2691 int64_t MB = MI.getOperand(3).getImm();
2692 int64_t ME = MI.getOperand(4).getImm();
2693 APInt InVal(32, SExtImm, true);
2694 InVal = InVal.rotl(SH);
2695 // Set the bits ( MB + 32 ) to ( ME + 32 ).
2696 uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2697 InVal &= Mask;
2698 // Can't replace negative values with an LI as that will sign-extend
2699 // and not clear the left bits. If we're setting the CR bit, we will use
2700 // ANDIo which won't sign extend, so that's safe.
2701 bool ValueFits = isUInt<15>(InVal.getSExtValue());
2702 ValueFits |= ((Opc == PPC::RLWINMo || Opc == PPC::RLWINM8o) &&
2703 isUInt<16>(InVal.getSExtValue()));
2704 if (ValueFits) {
2705 ReplaceWithLI = true;
2706 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8o;
2707 NewImm = InVal.getSExtValue();
2708 SetCR = Opc == PPC::RLWINMo || Opc == PPC::RLWINM8o;
2709 break;
2711 return false;
2713 case PPC::ORI:
2714 case PPC::ORI8:
2715 case PPC::XORI:
2716 case PPC::XORI8: {
2717 int64_t LogicalImm = MI.getOperand(2).getImm();
2718 int64_t Result = 0;
2719 if (Opc == PPC::ORI || Opc == PPC::ORI8)
2720 Result = LogicalImm | SExtImm;
2721 else
2722 Result = LogicalImm ^ SExtImm;
2723 if (isInt<16>(Result)) {
2724 ReplaceWithLI = true;
2725 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
2726 NewImm = Result;
2727 break;
2729 return false;
2733 if (ReplaceWithLI) {
2734 // We need to be careful with CR-setting instructions we're replacing.
2735 if (SetCR) {
2736 // We don't know anything about uses when we're out of SSA, so only
2737 // replace if the new immediate will be reproduced.
2738 bool ImmChanged = (SExtImm & NewImm) != NewImm;
2739 if (PostRA && ImmChanged)
2740 return false;
2742 if (!PostRA) {
2743 // If the defining load-immediate has no other uses, we can just replace
2744 // the immediate with the new immediate.
2745 if (MRI->hasOneUse(DefMI->getOperand(0).getReg()))
2746 DefMI->getOperand(1).setImm(NewImm);
2748 // If we're not using the GPR result of the CR-setting instruction, we
2749 // just need to and with zero/non-zero depending on the new immediate.
2750 else if (MRI->use_empty(MI.getOperand(0).getReg())) {
2751 if (NewImm) {
2752 assert(Immediate && "Transformation converted zero to non-zero?");
2753 NewImm = Immediate;
2756 else if (ImmChanged)
2757 return false;
2761 LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
2762 LLVM_DEBUG(MI.dump());
2763 LLVM_DEBUG(dbgs() << "Fed by:\n");
2764 LLVM_DEBUG(DefMI->dump());
2765 LoadImmediateInfo LII;
2766 LII.Imm = NewImm;
2767 LII.Is64Bit = Is64BitLI;
2768 LII.SetCR = SetCR;
2769 // If we're setting the CR, the original load-immediate must be kept (as an
2770 // operand to ANDIo/ANDI8o).
2771 if (KilledDef && SetCR)
2772 *KilledDef = nullptr;
2773 replaceInstrWithLI(MI, LII);
2775 // Fixup killed/dead flag after transformation.
2776 // Pattern:
2777 // ForwardingOperandReg = LI imm1
2778 // y = op2 imm2, ForwardingOperandReg(killed)
2779 if (IsForwardingOperandKilled)
2780 fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg);
2782 LLVM_DEBUG(dbgs() << "With:\n");
2783 LLVM_DEBUG(MI.dump());
2784 return true;
2786 return false;
2789 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
2790 ImmInstrInfo &III, bool PostRA) const {
2791 // The vast majority of the instructions would need their operand 2 replaced
2792 // with an immediate when switching to the reg+imm form. A marked exception
2793 // are the update form loads/stores for which a constant operand 2 would need
2794 // to turn into a displacement and move operand 1 to the operand 2 position.
2795 III.ImmOpNo = 2;
2796 III.OpNoForForwarding = 2;
2797 III.ImmWidth = 16;
2798 III.ImmMustBeMultipleOf = 1;
2799 III.TruncateImmTo = 0;
2800 III.IsSummingOperands = false;
2801 switch (Opc) {
2802 default: return false;
2803 case PPC::ADD4:
2804 case PPC::ADD8:
2805 III.SignedImm = true;
2806 III.ZeroIsSpecialOrig = 0;
2807 III.ZeroIsSpecialNew = 1;
2808 III.IsCommutative = true;
2809 III.IsSummingOperands = true;
2810 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
2811 break;
2812 case PPC::ADDC:
2813 case PPC::ADDC8:
2814 III.SignedImm = true;
2815 III.ZeroIsSpecialOrig = 0;
2816 III.ZeroIsSpecialNew = 0;
2817 III.IsCommutative = true;
2818 III.IsSummingOperands = true;
2819 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
2820 break;
2821 case PPC::ADDCo:
2822 III.SignedImm = true;
2823 III.ZeroIsSpecialOrig = 0;
2824 III.ZeroIsSpecialNew = 0;
2825 III.IsCommutative = true;
2826 III.IsSummingOperands = true;
2827 III.ImmOpcode = PPC::ADDICo;
2828 break;
2829 case PPC::SUBFC:
2830 case PPC::SUBFC8:
2831 III.SignedImm = true;
2832 III.ZeroIsSpecialOrig = 0;
2833 III.ZeroIsSpecialNew = 0;
2834 III.IsCommutative = false;
2835 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
2836 break;
2837 case PPC::CMPW:
2838 case PPC::CMPD:
2839 III.SignedImm = true;
2840 III.ZeroIsSpecialOrig = 0;
2841 III.ZeroIsSpecialNew = 0;
2842 III.IsCommutative = false;
2843 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
2844 break;
2845 case PPC::CMPLW:
2846 case PPC::CMPLD:
2847 III.SignedImm = false;
2848 III.ZeroIsSpecialOrig = 0;
2849 III.ZeroIsSpecialNew = 0;
2850 III.IsCommutative = false;
2851 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
2852 break;
2853 case PPC::ANDo:
2854 case PPC::AND8o:
2855 case PPC::OR:
2856 case PPC::OR8:
2857 case PPC::XOR:
2858 case PPC::XOR8:
2859 III.SignedImm = false;
2860 III.ZeroIsSpecialOrig = 0;
2861 III.ZeroIsSpecialNew = 0;
2862 III.IsCommutative = true;
2863 switch(Opc) {
2864 default: llvm_unreachable("Unknown opcode");
2865 case PPC::ANDo: III.ImmOpcode = PPC::ANDIo; break;
2866 case PPC::AND8o: III.ImmOpcode = PPC::ANDIo8; break;
2867 case PPC::OR: III.ImmOpcode = PPC::ORI; break;
2868 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
2869 case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
2870 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
2872 break;
2873 case PPC::RLWNM:
2874 case PPC::RLWNM8:
2875 case PPC::RLWNMo:
2876 case PPC::RLWNM8o:
2877 case PPC::SLW:
2878 case PPC::SLW8:
2879 case PPC::SLWo:
2880 case PPC::SLW8o:
2881 case PPC::SRW:
2882 case PPC::SRW8:
2883 case PPC::SRWo:
2884 case PPC::SRW8o:
2885 case PPC::SRAW:
2886 case PPC::SRAWo:
2887 III.SignedImm = false;
2888 III.ZeroIsSpecialOrig = 0;
2889 III.ZeroIsSpecialNew = 0;
2890 III.IsCommutative = false;
2891 // This isn't actually true, but the instructions ignore any of the
2892 // upper bits, so any immediate loaded with an LI is acceptable.
2893 // This does not apply to shift right algebraic because a value
2894 // out of range will produce a -1/0.
2895 III.ImmWidth = 16;
2896 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 ||
2897 Opc == PPC::RLWNMo || Opc == PPC::RLWNM8o)
2898 III.TruncateImmTo = 5;
2899 else
2900 III.TruncateImmTo = 6;
2901 switch(Opc) {
2902 default: llvm_unreachable("Unknown opcode");
2903 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
2904 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
2905 case PPC::RLWNMo: III.ImmOpcode = PPC::RLWINMo; break;
2906 case PPC::RLWNM8o: III.ImmOpcode = PPC::RLWINM8o; break;
2907 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
2908 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
2909 case PPC::SLWo: III.ImmOpcode = PPC::RLWINMo; break;
2910 case PPC::SLW8o: III.ImmOpcode = PPC::RLWINM8o; break;
2911 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
2912 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
2913 case PPC::SRWo: III.ImmOpcode = PPC::RLWINMo; break;
2914 case PPC::SRW8o: III.ImmOpcode = PPC::RLWINM8o; break;
2915 case PPC::SRAW:
2916 III.ImmWidth = 5;
2917 III.TruncateImmTo = 0;
2918 III.ImmOpcode = PPC::SRAWI;
2919 break;
2920 case PPC::SRAWo:
2921 III.ImmWidth = 5;
2922 III.TruncateImmTo = 0;
2923 III.ImmOpcode = PPC::SRAWIo;
2924 break;
2926 break;
2927 case PPC::RLDCL:
2928 case PPC::RLDCLo:
2929 case PPC::RLDCR:
2930 case PPC::RLDCRo:
2931 case PPC::SLD:
2932 case PPC::SLDo:
2933 case PPC::SRD:
2934 case PPC::SRDo:
2935 case PPC::SRAD:
2936 case PPC::SRADo:
2937 III.SignedImm = false;
2938 III.ZeroIsSpecialOrig = 0;
2939 III.ZeroIsSpecialNew = 0;
2940 III.IsCommutative = false;
2941 // This isn't actually true, but the instructions ignore any of the
2942 // upper bits, so any immediate loaded with an LI is acceptable.
2943 // This does not apply to shift right algebraic because a value
2944 // out of range will produce a -1/0.
2945 III.ImmWidth = 16;
2946 if (Opc == PPC::RLDCL || Opc == PPC::RLDCLo ||
2947 Opc == PPC::RLDCR || Opc == PPC::RLDCRo)
2948 III.TruncateImmTo = 6;
2949 else
2950 III.TruncateImmTo = 7;
2951 switch(Opc) {
2952 default: llvm_unreachable("Unknown opcode");
2953 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
2954 case PPC::RLDCLo: III.ImmOpcode = PPC::RLDICLo; break;
2955 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
2956 case PPC::RLDCRo: III.ImmOpcode = PPC::RLDICRo; break;
2957 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
2958 case PPC::SLDo: III.ImmOpcode = PPC::RLDICRo; break;
2959 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
2960 case PPC::SRDo: III.ImmOpcode = PPC::RLDICLo; break;
2961 case PPC::SRAD:
2962 III.ImmWidth = 6;
2963 III.TruncateImmTo = 0;
2964 III.ImmOpcode = PPC::SRADI;
2965 break;
2966 case PPC::SRADo:
2967 III.ImmWidth = 6;
2968 III.TruncateImmTo = 0;
2969 III.ImmOpcode = PPC::SRADIo;
2970 break;
2972 break;
2973 // Loads and stores:
2974 case PPC::LBZX:
2975 case PPC::LBZX8:
2976 case PPC::LHZX:
2977 case PPC::LHZX8:
2978 case PPC::LHAX:
2979 case PPC::LHAX8:
2980 case PPC::LWZX:
2981 case PPC::LWZX8:
2982 case PPC::LWAX:
2983 case PPC::LDX:
2984 case PPC::LFSX:
2985 case PPC::LFDX:
2986 case PPC::STBX:
2987 case PPC::STBX8:
2988 case PPC::STHX:
2989 case PPC::STHX8:
2990 case PPC::STWX:
2991 case PPC::STWX8:
2992 case PPC::STDX:
2993 case PPC::STFSX:
2994 case PPC::STFDX:
2995 III.SignedImm = true;
2996 III.ZeroIsSpecialOrig = 1;
2997 III.ZeroIsSpecialNew = 2;
2998 III.IsCommutative = true;
2999 III.IsSummingOperands = true;
3000 III.ImmOpNo = 1;
3001 III.OpNoForForwarding = 2;
3002 switch(Opc) {
3003 default: llvm_unreachable("Unknown opcode");
3004 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
3005 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
3006 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
3007 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
3008 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
3009 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
3010 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
3011 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
3012 case PPC::LWAX:
3013 III.ImmOpcode = PPC::LWA;
3014 III.ImmMustBeMultipleOf = 4;
3015 break;
3016 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
3017 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
3018 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
3019 case PPC::STBX: III.ImmOpcode = PPC::STB; break;
3020 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
3021 case PPC::STHX: III.ImmOpcode = PPC::STH; break;
3022 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
3023 case PPC::STWX: III.ImmOpcode = PPC::STW; break;
3024 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
3025 case PPC::STDX:
3026 III.ImmOpcode = PPC::STD;
3027 III.ImmMustBeMultipleOf = 4;
3028 break;
3029 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
3030 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
3032 break;
3033 case PPC::LBZUX:
3034 case PPC::LBZUX8:
3035 case PPC::LHZUX:
3036 case PPC::LHZUX8:
3037 case PPC::LHAUX:
3038 case PPC::LHAUX8:
3039 case PPC::LWZUX:
3040 case PPC::LWZUX8:
3041 case PPC::LDUX:
3042 case PPC::LFSUX:
3043 case PPC::LFDUX:
3044 case PPC::STBUX:
3045 case PPC::STBUX8:
3046 case PPC::STHUX:
3047 case PPC::STHUX8:
3048 case PPC::STWUX:
3049 case PPC::STWUX8:
3050 case PPC::STDUX:
3051 case PPC::STFSUX:
3052 case PPC::STFDUX:
3053 III.SignedImm = true;
3054 III.ZeroIsSpecialOrig = 2;
3055 III.ZeroIsSpecialNew = 3;
3056 III.IsCommutative = false;
3057 III.IsSummingOperands = true;
3058 III.ImmOpNo = 2;
3059 III.OpNoForForwarding = 3;
3060 switch(Opc) {
3061 default: llvm_unreachable("Unknown opcode");
3062 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
3063 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
3064 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
3065 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
3066 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
3067 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
3068 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
3069 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
3070 case PPC::LDUX:
3071 III.ImmOpcode = PPC::LDU;
3072 III.ImmMustBeMultipleOf = 4;
3073 break;
3074 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
3075 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
3076 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
3077 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
3078 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
3079 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
3080 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
3081 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
3082 case PPC::STDUX:
3083 III.ImmOpcode = PPC::STDU;
3084 III.ImmMustBeMultipleOf = 4;
3085 break;
3086 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
3087 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
3089 break;
3090 // Power9 and up only. For some of these, the X-Form version has access to all
3091 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
3092 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
3093 // into or stored from is one of the VR registers.
3094 case PPC::LXVX:
3095 case PPC::LXSSPX:
3096 case PPC::LXSDX:
3097 case PPC::STXVX:
3098 case PPC::STXSSPX:
3099 case PPC::STXSDX:
3100 case PPC::XFLOADf32:
3101 case PPC::XFLOADf64:
3102 case PPC::XFSTOREf32:
3103 case PPC::XFSTOREf64:
3104 if (!Subtarget.hasP9Vector())
3105 return false;
3106 III.SignedImm = true;
3107 III.ZeroIsSpecialOrig = 1;
3108 III.ZeroIsSpecialNew = 2;
3109 III.IsCommutative = true;
3110 III.IsSummingOperands = true;
3111 III.ImmOpNo = 1;
3112 III.OpNoForForwarding = 2;
3113 III.ImmMustBeMultipleOf = 4;
3114 switch(Opc) {
3115 default: llvm_unreachable("Unknown opcode");
3116 case PPC::LXVX:
3117 III.ImmOpcode = PPC::LXV;
3118 III.ImmMustBeMultipleOf = 16;
3119 break;
3120 case PPC::LXSSPX:
3121 if (PostRA) {
3122 if (IsVFReg)
3123 III.ImmOpcode = PPC::LXSSP;
3124 else {
3125 III.ImmOpcode = PPC::LFS;
3126 III.ImmMustBeMultipleOf = 1;
3128 break;
3130 LLVM_FALLTHROUGH;
3131 case PPC::XFLOADf32:
3132 III.ImmOpcode = PPC::DFLOADf32;
3133 break;
3134 case PPC::LXSDX:
3135 if (PostRA) {
3136 if (IsVFReg)
3137 III.ImmOpcode = PPC::LXSD;
3138 else {
3139 III.ImmOpcode = PPC::LFD;
3140 III.ImmMustBeMultipleOf = 1;
3142 break;
3144 LLVM_FALLTHROUGH;
3145 case PPC::XFLOADf64:
3146 III.ImmOpcode = PPC::DFLOADf64;
3147 break;
3148 case PPC::STXVX:
3149 III.ImmOpcode = PPC::STXV;
3150 III.ImmMustBeMultipleOf = 16;
3151 break;
3152 case PPC::STXSSPX:
3153 if (PostRA) {
3154 if (IsVFReg)
3155 III.ImmOpcode = PPC::STXSSP;
3156 else {
3157 III.ImmOpcode = PPC::STFS;
3158 III.ImmMustBeMultipleOf = 1;
3160 break;
3162 LLVM_FALLTHROUGH;
3163 case PPC::XFSTOREf32:
3164 III.ImmOpcode = PPC::DFSTOREf32;
3165 break;
3166 case PPC::STXSDX:
3167 if (PostRA) {
3168 if (IsVFReg)
3169 III.ImmOpcode = PPC::STXSD;
3170 else {
3171 III.ImmOpcode = PPC::STFD;
3172 III.ImmMustBeMultipleOf = 1;
3174 break;
3176 LLVM_FALLTHROUGH;
3177 case PPC::XFSTOREf64:
3178 III.ImmOpcode = PPC::DFSTOREf64;
3179 break;
3181 break;
3183 return true;
3186 // Utility function for swaping two arbitrary operands of an instruction.
3187 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
3188 assert(Op1 != Op2 && "Cannot swap operand with itself.");
3190 unsigned MaxOp = std::max(Op1, Op2);
3191 unsigned MinOp = std::min(Op1, Op2);
3192 MachineOperand MOp1 = MI.getOperand(MinOp);
3193 MachineOperand MOp2 = MI.getOperand(MaxOp);
3194 MI.RemoveOperand(std::max(Op1, Op2));
3195 MI.RemoveOperand(std::min(Op1, Op2));
3197 // If the operands we are swapping are the two at the end (the common case)
3198 // we can just remove both and add them in the opposite order.
3199 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
3200 MI.addOperand(MOp2);
3201 MI.addOperand(MOp1);
3202 } else {
3203 // Store all operands in a temporary vector, remove them and re-add in the
3204 // right order.
3205 SmallVector<MachineOperand, 2> MOps;
3206 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
3207 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
3208 MOps.push_back(MI.getOperand(i));
3209 MI.RemoveOperand(i);
3211 // MOp2 needs to be added next.
3212 MI.addOperand(MOp2);
3213 // Now add the rest.
3214 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
3215 if (i == MaxOp)
3216 MI.addOperand(MOp1);
3217 else {
3218 MI.addOperand(MOps.back());
3219 MOps.pop_back();
3225 // Check if the 'MI' that has the index OpNoForForwarding
3226 // meets the requirement described in the ImmInstrInfo.
3227 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
3228 const ImmInstrInfo &III,
3229 unsigned OpNoForForwarding
3230 ) const {
3231 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
3232 // would not work pre-RA, we can only do the check post RA.
3233 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3234 if (MRI.isSSA())
3235 return false;
3237 // Cannot do the transform if MI isn't summing the operands.
3238 if (!III.IsSummingOperands)
3239 return false;
3241 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
3242 if (!III.ZeroIsSpecialOrig)
3243 return false;
3245 // We cannot do the transform if the operand we are trying to replace
3246 // isn't the same as the operand the instruction allows.
3247 if (OpNoForForwarding != III.OpNoForForwarding)
3248 return false;
3250 // Check if the instruction we are trying to transform really has
3251 // the special zero register as its operand.
3252 if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
3253 MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
3254 return false;
3256 // This machine instruction is convertible if it is,
3257 // 1. summing the operands.
3258 // 2. one of the operands is special zero register.
3259 // 3. the operand we are trying to replace is allowed by the MI.
3260 return true;
3263 // Check if the DefMI is the add inst and set the ImmMO and RegMO
3264 // accordingly.
3265 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
3266 const ImmInstrInfo &III,
3267 MachineOperand *&ImmMO,
3268 MachineOperand *&RegMO) const {
3269 unsigned Opc = DefMI.getOpcode();
3270 if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8)
3271 return false;
3273 assert(DefMI.getNumOperands() >= 3 &&
3274 "Add inst must have at least three operands");
3275 RegMO = &DefMI.getOperand(1);
3276 ImmMO = &DefMI.getOperand(2);
3278 // This DefMI is elgible for forwarding if it is:
3279 // 1. add inst
3280 // 2. one of the operands is Imm/CPI/Global.
3281 return isAnImmediateOperand(*ImmMO);
3284 bool PPCInstrInfo::isRegElgibleForForwarding(
3285 const MachineOperand &RegMO, const MachineInstr &DefMI,
3286 const MachineInstr &MI, bool KillDefMI,
3287 bool &IsFwdFeederRegKilled) const {
3288 // x = addi y, imm
3289 // ...
3290 // z = lfdx 0, x -> z = lfd imm(y)
3291 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
3292 // of "y" between the DEF of "x" and "z".
3293 // The query is only valid post RA.
3294 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3295 if (MRI.isSSA())
3296 return false;
3298 Register Reg = RegMO.getReg();
3300 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
3301 MachineBasicBlock::const_reverse_iterator It = MI;
3302 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
3303 It++;
3304 for (; It != E; ++It) {
3305 if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3306 return false;
3307 else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI)
3308 IsFwdFeederRegKilled = true;
3309 // Made it to DefMI without encountering a clobber.
3310 if ((&*It) == &DefMI)
3311 break;
3313 assert((&*It) == &DefMI && "DefMI is missing");
3315 // If DefMI also defines the register to be forwarded, we can only forward it
3316 // if DefMI is being erased.
3317 if (DefMI.modifiesRegister(Reg, &getRegisterInfo()))
3318 return KillDefMI;
3320 return true;
3323 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
3324 const MachineInstr &DefMI,
3325 const ImmInstrInfo &III,
3326 int64_t &Imm) const {
3327 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
3328 if (DefMI.getOpcode() == PPC::ADDItocL) {
3329 // The operand for ADDItocL is CPI, which isn't imm at compiling time,
3330 // However, we know that, it is 16-bit width, and has the alignment of 4.
3331 // Check if the instruction met the requirement.
3332 if (III.ImmMustBeMultipleOf > 4 ||
3333 III.TruncateImmTo || III.ImmWidth != 16)
3334 return false;
3336 // Going from XForm to DForm loads means that the displacement needs to be
3337 // not just an immediate but also a multiple of 4, or 16 depending on the
3338 // load. A DForm load cannot be represented if it is a multiple of say 2.
3339 // XForm loads do not have this restriction.
3340 if (ImmMO.isGlobal() &&
3341 ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf)
3342 return false;
3344 return true;
3347 if (ImmMO.isImm()) {
3348 // It is Imm, we need to check if the Imm fit the range.
3349 int64_t Immediate = ImmMO.getImm();
3350 // Sign-extend to 64-bits.
3351 Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ?
3352 (Immediate | 0xFFFFFFFFFFFF0000) : Immediate;
3354 if (Imm % III.ImmMustBeMultipleOf)
3355 return false;
3356 if (III.TruncateImmTo)
3357 Imm &= ((1 << III.TruncateImmTo) - 1);
3358 if (III.SignedImm) {
3359 APInt ActualValue(64, Imm, true);
3360 if (!ActualValue.isSignedIntN(III.ImmWidth))
3361 return false;
3362 } else {
3363 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3364 if ((uint64_t)Imm > UnsignedMax)
3365 return false;
3368 else
3369 return false;
3371 // This ImmMO is forwarded if it meets the requriement describle
3372 // in ImmInstrInfo
3373 return true;
3376 // If an X-Form instruction is fed by an add-immediate and one of its operands
3377 // is the literal zero, attempt to forward the source of the add-immediate to
3378 // the corresponding D-Form instruction with the displacement coming from
3379 // the immediate being added.
3380 bool PPCInstrInfo::transformToImmFormFedByAdd(
3381 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
3382 MachineInstr &DefMI, bool KillDefMI) const {
3383 // RegMO ImmMO
3384 // | |
3385 // x = addi reg, imm <----- DefMI
3386 // y = op 0 , x <----- MI
3387 // |
3388 // OpNoForForwarding
3389 // Check if the MI meet the requirement described in the III.
3390 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
3391 return false;
3393 // Check if the DefMI meet the requirement
3394 // described in the III. If yes, set the ImmMO and RegMO accordingly.
3395 MachineOperand *ImmMO = nullptr;
3396 MachineOperand *RegMO = nullptr;
3397 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
3398 return false;
3399 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
3401 // As we get the Imm operand now, we need to check if the ImmMO meet
3402 // the requirement described in the III. If yes set the Imm.
3403 int64_t Imm = 0;
3404 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm))
3405 return false;
3407 bool IsFwdFeederRegKilled = false;
3408 // Check if the RegMO can be forwarded to MI.
3409 if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI,
3410 IsFwdFeederRegKilled))
3411 return false;
3413 // Get killed info in case fixup needed after transformation.
3414 unsigned ForwardKilledOperandReg = ~0U;
3415 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3416 bool PostRA = !MRI.isSSA();
3417 if (PostRA && MI.getOperand(OpNoForForwarding).isKill())
3418 ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg();
3420 // We know that, the MI and DefMI both meet the pattern, and
3421 // the Imm also meet the requirement with the new Imm-form.
3422 // It is safe to do the transformation now.
3423 LLVM_DEBUG(dbgs() << "Replacing instruction:\n");
3424 LLVM_DEBUG(MI.dump());
3425 LLVM_DEBUG(dbgs() << "Fed by:\n");
3426 LLVM_DEBUG(DefMI.dump());
3428 // Update the base reg first.
3429 MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(),
3430 false, false,
3431 RegMO->isKill());
3433 // Then, update the imm.
3434 if (ImmMO->isImm()) {
3435 // If the ImmMO is Imm, change the operand that has ZERO to that Imm
3436 // directly.
3437 replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm);
3439 else {
3440 // Otherwise, it is Constant Pool Index(CPI) or Global,
3441 // which is relocation in fact. We need to replace the special zero
3442 // register with ImmMO.
3443 // Before that, we need to fixup the target flags for imm.
3444 // For some reason, we miss to set the flag for the ImmMO if it is CPI.
3445 if (DefMI.getOpcode() == PPC::ADDItocL)
3446 ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
3448 // MI didn't have the interface such as MI.setOperand(i) though
3449 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
3450 // ImmMO, we need to remove ZERO operand and all the operands behind it,
3451 // and, add the ImmMO, then, move back all the operands behind ZERO.
3452 SmallVector<MachineOperand, 2> MOps;
3453 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
3454 MOps.push_back(MI.getOperand(i));
3455 MI.RemoveOperand(i);
3458 // Remove the last MO in the list, which is ZERO operand in fact.
3459 MOps.pop_back();
3460 // Add the imm operand.
3461 MI.addOperand(*ImmMO);
3462 // Now add the rest back.
3463 for (auto &MO : MOps)
3464 MI.addOperand(MO);
3467 // Update the opcode.
3468 MI.setDesc(get(III.ImmOpcode));
3470 // Fix up killed/dead flag after transformation.
3471 // Pattern 1:
3472 // x = ADD KilledFwdFeederReg, imm
3473 // n = opn KilledFwdFeederReg(killed), regn
3474 // y = XOP 0, x
3475 // Pattern 2:
3476 // x = ADD reg(killed), imm
3477 // y = XOP 0, x
3478 if (IsFwdFeederRegKilled || RegMO->isKill())
3479 fixupIsDeadOrKill(DefMI, MI, RegMO->getReg());
3480 // Pattern 3:
3481 // ForwardKilledOperandReg = ADD reg, imm
3482 // y = XOP 0, ForwardKilledOperandReg(killed)
3483 if (ForwardKilledOperandReg != ~0U)
3484 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3486 LLVM_DEBUG(dbgs() << "With:\n");
3487 LLVM_DEBUG(MI.dump());
3489 return true;
3492 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
3493 const ImmInstrInfo &III,
3494 unsigned ConstantOpNo,
3495 MachineInstr &DefMI,
3496 int64_t Imm) const {
3497 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3498 bool PostRA = !MRI.isSSA();
3499 // Exit early if we can't convert this.
3500 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
3501 return false;
3502 if (Imm % III.ImmMustBeMultipleOf)
3503 return false;
3504 if (III.TruncateImmTo)
3505 Imm &= ((1 << III.TruncateImmTo) - 1);
3506 if (III.SignedImm) {
3507 APInt ActualValue(64, Imm, true);
3508 if (!ActualValue.isSignedIntN(III.ImmWidth))
3509 return false;
3510 } else {
3511 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
3512 if ((uint64_t)Imm > UnsignedMax)
3513 return false;
3516 // If we're post-RA, the instructions don't agree on whether register zero is
3517 // special, we can transform this as long as the register operand that will
3518 // end up in the location where zero is special isn't R0.
3519 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3520 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
3521 III.ZeroIsSpecialNew + 1;
3522 Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg();
3523 Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3524 // If R0 is in the operand where zero is special for the new instruction,
3525 // it is unsafe to transform if the constant operand isn't that operand.
3526 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
3527 ConstantOpNo != III.ZeroIsSpecialNew)
3528 return false;
3529 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
3530 ConstantOpNo != PosForOrigZero)
3531 return false;
3534 // Get killed info in case fixup needed after transformation.
3535 unsigned ForwardKilledOperandReg = ~0U;
3536 if (PostRA && MI.getOperand(ConstantOpNo).isKill())
3537 ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg();
3539 unsigned Opc = MI.getOpcode();
3540 bool SpecialShift32 =
3541 Opc == PPC::SLW || Opc == PPC::SLWo || Opc == PPC::SRW || Opc == PPC::SRWo;
3542 bool SpecialShift64 =
3543 Opc == PPC::SLD || Opc == PPC::SLDo || Opc == PPC::SRD || Opc == PPC::SRDo;
3544 bool SetCR = Opc == PPC::SLWo || Opc == PPC::SRWo ||
3545 Opc == PPC::SLDo || Opc == PPC::SRDo;
3546 bool RightShift =
3547 Opc == PPC::SRW || Opc == PPC::SRWo || Opc == PPC::SRD || Opc == PPC::SRDo;
3549 MI.setDesc(get(III.ImmOpcode));
3550 if (ConstantOpNo == III.OpNoForForwarding) {
3551 // Converting shifts to immediate form is a bit tricky since they may do
3552 // one of three things:
3553 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
3554 // 2. If the shift amount is zero, the result is unchanged (save for maybe
3555 // setting CR0)
3556 // 3. If the shift amount is in [1, OpSize), it's just a shift
3557 if (SpecialShift32 || SpecialShift64) {
3558 LoadImmediateInfo LII;
3559 LII.Imm = 0;
3560 LII.SetCR = SetCR;
3561 LII.Is64Bit = SpecialShift64;
3562 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
3563 if (Imm & (SpecialShift32 ? 0x20 : 0x40))
3564 replaceInstrWithLI(MI, LII);
3565 // Shifts by zero don't change the value. If we don't need to set CR0,
3566 // just convert this to a COPY. Can't do this post-RA since we've already
3567 // cleaned up the copies.
3568 else if (!SetCR && ShAmt == 0 && !PostRA) {
3569 MI.RemoveOperand(2);
3570 MI.setDesc(get(PPC::COPY));
3571 } else {
3572 // The 32 bit and 64 bit instructions are quite different.
3573 if (SpecialShift32) {
3574 // Left shifts use (N, 0, 31-N).
3575 // Right shifts use (32-N, N, 31) if 0 < N < 32.
3576 // use (0, 0, 31) if N == 0.
3577 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
3578 uint64_t MB = RightShift ? ShAmt : 0;
3579 uint64_t ME = RightShift ? 31 : 31 - ShAmt;
3580 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3581 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB)
3582 .addImm(ME);
3583 } else {
3584 // Left shifts use (N, 63-N).
3585 // Right shifts use (64-N, N) if 0 < N < 64.
3586 // use (0, 0) if N == 0.
3587 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
3588 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
3589 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH);
3590 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME);
3593 } else
3594 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3596 // Convert commutative instructions (switch the operands and convert the
3597 // desired one to an immediate.
3598 else if (III.IsCommutative) {
3599 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm);
3600 swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding);
3601 } else
3602 llvm_unreachable("Should have exited early!");
3604 // For instructions for which the constant register replaces a different
3605 // operand than where the immediate goes, we need to swap them.
3606 if (III.OpNoForForwarding != III.ImmOpNo)
3607 swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo);
3609 // If the special R0/X0 register index are different for original instruction
3610 // and new instruction, we need to fix up the register class in new
3611 // instruction.
3612 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
3613 if (III.ZeroIsSpecialNew) {
3614 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
3615 // need to fix up register class.
3616 Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg();
3617 if (Register::isVirtualRegister(RegToModify)) {
3618 const TargetRegisterClass *NewRC =
3619 MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ?
3620 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
3621 MRI.setRegClass(RegToModify, NewRC);
3626 // Fix up killed/dead flag after transformation.
3627 // Pattern:
3628 // ForwardKilledOperandReg = LI imm
3629 // y = XOP reg, ForwardKilledOperandReg(killed)
3630 if (ForwardKilledOperandReg != ~0U)
3631 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg);
3632 return true;
3635 const TargetRegisterClass *
3636 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
3637 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
3638 return &PPC::VSRCRegClass;
3639 return RC;
3642 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
3643 return PPC::getRecordFormOpcode(Opcode);
3646 // This function returns true if the machine instruction
3647 // always outputs a value by sign-extending a 32 bit value,
3648 // i.e. 0 to 31-th bits are same as 32-th bit.
3649 static bool isSignExtendingOp(const MachineInstr &MI) {
3650 int Opcode = MI.getOpcode();
3651 if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
3652 Opcode == PPC::LIS || Opcode == PPC::LIS8 ||
3653 Opcode == PPC::SRAW || Opcode == PPC::SRAWo ||
3654 Opcode == PPC::SRAWI || Opcode == PPC::SRAWIo ||
3655 Opcode == PPC::LWA || Opcode == PPC::LWAX ||
3656 Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 ||
3657 Opcode == PPC::LHA || Opcode == PPC::LHAX ||
3658 Opcode == PPC::LHA8 || Opcode == PPC::LHAX8 ||
3659 Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
3660 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
3661 Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
3662 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3663 Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
3664 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
3665 Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
3666 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 ||
3667 Opcode == PPC::EXTSB || Opcode == PPC::EXTSBo ||
3668 Opcode == PPC::EXTSH || Opcode == PPC::EXTSHo ||
3669 Opcode == PPC::EXTSB8 || Opcode == PPC::EXTSH8 ||
3670 Opcode == PPC::EXTSW || Opcode == PPC::EXTSWo ||
3671 Opcode == PPC::SETB || Opcode == PPC::SETB8 ||
3672 Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 ||
3673 Opcode == PPC::EXTSB8_32_64)
3674 return true;
3676 if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33)
3677 return true;
3679 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINMo ||
3680 Opcode == PPC::RLWNM || Opcode == PPC::RLWNMo) &&
3681 MI.getOperand(3).getImm() > 0 &&
3682 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3683 return true;
3685 return false;
3688 // This function returns true if the machine instruction
3689 // always outputs zeros in higher 32 bits.
3690 static bool isZeroExtendingOp(const MachineInstr &MI) {
3691 int Opcode = MI.getOpcode();
3692 // The 16-bit immediate is sign-extended in li/lis.
3693 // If the most significant bit is zero, all higher bits are zero.
3694 if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
3695 Opcode == PPC::LIS || Opcode == PPC::LIS8) {
3696 int64_t Imm = MI.getOperand(1).getImm();
3697 if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
3698 return true;
3701 // We have some variations of rotate-and-mask instructions
3702 // that clear higher 32-bits.
3703 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICLo ||
3704 Opcode == PPC::RLDCL || Opcode == PPC::RLDCLo ||
3705 Opcode == PPC::RLDICL_32_64) &&
3706 MI.getOperand(3).getImm() >= 32)
3707 return true;
3709 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDICo) &&
3710 MI.getOperand(3).getImm() >= 32 &&
3711 MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm())
3712 return true;
3714 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINMo ||
3715 Opcode == PPC::RLWNM || Opcode == PPC::RLWNMo ||
3716 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
3717 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm())
3718 return true;
3720 // There are other instructions that clear higher 32-bits.
3721 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZWo ||
3722 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZWo ||
3723 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 ||
3724 Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZDo ||
3725 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZDo ||
3726 Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW ||
3727 Opcode == PPC::SLW || Opcode == PPC::SLWo ||
3728 Opcode == PPC::SRW || Opcode == PPC::SRWo ||
3729 Opcode == PPC::SLW8 || Opcode == PPC::SRW8 ||
3730 Opcode == PPC::SLWI || Opcode == PPC::SLWIo ||
3731 Opcode == PPC::SRWI || Opcode == PPC::SRWIo ||
3732 Opcode == PPC::LWZ || Opcode == PPC::LWZX ||
3733 Opcode == PPC::LWZU || Opcode == PPC::LWZUX ||
3734 Opcode == PPC::LWBRX || Opcode == PPC::LHBRX ||
3735 Opcode == PPC::LHZ || Opcode == PPC::LHZX ||
3736 Opcode == PPC::LHZU || Opcode == PPC::LHZUX ||
3737 Opcode == PPC::LBZ || Opcode == PPC::LBZX ||
3738 Opcode == PPC::LBZU || Opcode == PPC::LBZUX ||
3739 Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 ||
3740 Opcode == PPC::LWZU8 || Opcode == PPC::LWZUX8 ||
3741 Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 ||
3742 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 ||
3743 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 ||
3744 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 ||
3745 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 ||
3746 Opcode == PPC::ANDIo || Opcode == PPC::ANDISo ||
3747 Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWIo ||
3748 Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWIo ||
3749 Opcode == PPC::MFVSRWZ)
3750 return true;
3752 return false;
3755 // This function returns true if the input MachineInstr is a TOC save
3756 // instruction.
3757 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
3758 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg())
3759 return false;
3760 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
3761 unsigned StackOffset = MI.getOperand(1).getImm();
3762 Register StackReg = MI.getOperand(2).getReg();
3763 if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset)
3764 return true;
3766 return false;
3769 // We limit the max depth to track incoming values of PHIs or binary ops
3770 // (e.g. AND) to avoid excessive cost.
3771 const unsigned MAX_DEPTH = 1;
3773 bool
3774 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt,
3775 const unsigned Depth) const {
3776 const MachineFunction *MF = MI.getParent()->getParent();
3777 const MachineRegisterInfo *MRI = &MF->getRegInfo();
3779 // If we know this instruction returns sign- or zero-extended result,
3780 // return true.
3781 if (SignExt ? isSignExtendingOp(MI):
3782 isZeroExtendingOp(MI))
3783 return true;
3785 switch (MI.getOpcode()) {
3786 case PPC::COPY: {
3787 Register SrcReg = MI.getOperand(1).getReg();
3789 // In both ELFv1 and v2 ABI, method parameters and the return value
3790 // are sign- or zero-extended.
3791 if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
3792 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
3793 // We check the ZExt/SExt flags for a method parameter.
3794 if (MI.getParent()->getBasicBlock() ==
3795 &MF->getFunction().getEntryBlock()) {
3796 Register VReg = MI.getOperand(0).getReg();
3797 if (MF->getRegInfo().isLiveIn(VReg))
3798 return SignExt ? FuncInfo->isLiveInSExt(VReg) :
3799 FuncInfo->isLiveInZExt(VReg);
3802 // For a method return value, we check the ZExt/SExt flags in attribute.
3803 // We assume the following code sequence for method call.
3804 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
3805 // BL8_NOP @func,...
3806 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
3807 // %5 = COPY %x3; G8RC:%5
3808 if (SrcReg == PPC::X3) {
3809 const MachineBasicBlock *MBB = MI.getParent();
3810 MachineBasicBlock::const_instr_iterator II =
3811 MachineBasicBlock::const_instr_iterator(&MI);
3812 if (II != MBB->instr_begin() &&
3813 (--II)->getOpcode() == PPC::ADJCALLSTACKUP) {
3814 const MachineInstr &CallMI = *(--II);
3815 if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) {
3816 const Function *CalleeFn =
3817 dyn_cast<Function>(CallMI.getOperand(0).getGlobal());
3818 if (!CalleeFn)
3819 return false;
3820 const IntegerType *IntTy =
3821 dyn_cast<IntegerType>(CalleeFn->getReturnType());
3822 const AttributeSet &Attrs =
3823 CalleeFn->getAttributes().getRetAttributes();
3824 if (IntTy && IntTy->getBitWidth() <= 32)
3825 return Attrs.hasAttribute(SignExt ? Attribute::SExt :
3826 Attribute::ZExt);
3832 // If this is a copy from another register, we recursively check source.
3833 if (!Register::isVirtualRegister(SrcReg))
3834 return false;
3835 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3836 if (SrcMI != NULL)
3837 return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
3839 return false;
3842 case PPC::ANDIo:
3843 case PPC::ANDISo:
3844 case PPC::ORI:
3845 case PPC::ORIS:
3846 case PPC::XORI:
3847 case PPC::XORIS:
3848 case PPC::ANDIo8:
3849 case PPC::ANDISo8:
3850 case PPC::ORI8:
3851 case PPC::ORIS8:
3852 case PPC::XORI8:
3853 case PPC::XORIS8: {
3854 // logical operation with 16-bit immediate does not change the upper bits.
3855 // So, we track the operand register as we do for register copy.
3856 Register SrcReg = MI.getOperand(1).getReg();
3857 if (!Register::isVirtualRegister(SrcReg))
3858 return false;
3859 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3860 if (SrcMI != NULL)
3861 return isSignOrZeroExtended(*SrcMI, SignExt, Depth);
3863 return false;
3866 // If all incoming values are sign-/zero-extended,
3867 // the output of OR, ISEL or PHI is also sign-/zero-extended.
3868 case PPC::OR:
3869 case PPC::OR8:
3870 case PPC::ISEL:
3871 case PPC::PHI: {
3872 if (Depth >= MAX_DEPTH)
3873 return false;
3875 // The input registers for PHI are operand 1, 3, ...
3876 // The input registers for others are operand 1 and 2.
3877 unsigned E = 3, D = 1;
3878 if (MI.getOpcode() == PPC::PHI) {
3879 E = MI.getNumOperands();
3880 D = 2;
3883 for (unsigned I = 1; I != E; I += D) {
3884 if (MI.getOperand(I).isReg()) {
3885 Register SrcReg = MI.getOperand(I).getReg();
3886 if (!Register::isVirtualRegister(SrcReg))
3887 return false;
3888 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
3889 if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1))
3890 return false;
3892 else
3893 return false;
3895 return true;
3898 // If at least one of the incoming values of an AND is zero extended
3899 // then the output is also zero-extended. If both of the incoming values
3900 // are sign-extended then the output is also sign extended.
3901 case PPC::AND:
3902 case PPC::AND8: {
3903 if (Depth >= MAX_DEPTH)
3904 return false;
3906 assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg());
3908 Register SrcReg1 = MI.getOperand(1).getReg();
3909 Register SrcReg2 = MI.getOperand(2).getReg();
3911 if (!Register::isVirtualRegister(SrcReg1) ||
3912 !Register::isVirtualRegister(SrcReg2))
3913 return false;
3915 const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1);
3916 const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2);
3917 if (!MISrc1 || !MISrc2)
3918 return false;
3920 if(SignExt)
3921 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) &&
3922 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
3923 else
3924 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) ||
3925 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1);
3928 default:
3929 break;
3931 return false;
3934 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
3935 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
3938 namespace {
3939 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
3940 MachineInstr *Loop, *EndLoop, *LoopCount;
3941 MachineFunction *MF;
3942 const TargetInstrInfo *TII;
3943 int64_t TripCount;
3945 public:
3946 PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
3947 MachineInstr *LoopCount)
3948 : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
3949 MF(Loop->getParent()->getParent()),
3950 TII(MF->getSubtarget().getInstrInfo()) {
3951 // Inspect the Loop instruction up-front, as it may be deleted when we call
3952 // createTripCountGreaterCondition.
3953 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
3954 TripCount = LoopCount->getOperand(1).getImm();
3955 else
3956 TripCount = -1;
3959 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
3960 // Only ignore the terminator.
3961 return MI == EndLoop;
3964 Optional<bool>
3965 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
3966 SmallVectorImpl<MachineOperand> &Cond) override {
3967 if (TripCount == -1) {
3968 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
3969 // so we don't need to generate any thing here.
3970 Cond.push_back(MachineOperand::CreateImm(0));
3971 Cond.push_back(MachineOperand::CreateReg(
3972 MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
3973 true));
3974 return {};
3977 return TripCount > TC;
3980 void setPreheader(MachineBasicBlock *NewPreheader) override {
3981 // Do nothing. We want the LOOP setup instruction to stay in the *old*
3982 // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
3985 void adjustTripCount(int TripCountAdjust) override {
3986 // If the loop trip count is a compile-time value, then just change the
3987 // value.
3988 if (LoopCount->getOpcode() == PPC::LI8 ||
3989 LoopCount->getOpcode() == PPC::LI) {
3990 int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust;
3991 LoopCount->getOperand(1).setImm(TripCount);
3992 return;
3995 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
3996 // so we don't need to generate any thing here.
3999 void disposed() override {
4000 Loop->eraseFromParent();
4001 // Ensure the loop setup instruction is deleted too.
4002 LoopCount->eraseFromParent();
4005 } // namespace
4007 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
4008 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
4009 // We really "analyze" only hardware loops right now.
4010 MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
4011 MachineBasicBlock *Preheader = *LoopBB->pred_begin();
4012 if (Preheader == LoopBB)
4013 Preheader = *std::next(LoopBB->pred_begin());
4014 MachineFunction *MF = Preheader->getParent();
4016 if (I != LoopBB->end() && isBDNZ(I->getOpcode())) {
4017 SmallPtrSet<MachineBasicBlock *, 8> Visited;
4018 if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) {
4019 Register LoopCountReg = LoopInst->getOperand(0).getReg();
4020 MachineRegisterInfo &MRI = MF->getRegInfo();
4021 MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg);
4022 return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount);
4025 return nullptr;
4028 MachineInstr *PPCInstrInfo::findLoopInstr(
4029 MachineBasicBlock &PreHeader,
4030 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
4032 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
4034 // The loop set-up instruction should be in preheader
4035 for (auto &I : PreHeader.instrs())
4036 if (I.getOpcode() == LOOPi)
4037 return &I;
4038 return nullptr;
4041 // Return true if get the base operand, byte offset of an instruction and the
4042 // memory width. Width is the size of memory that is being loaded/stored.
4043 bool PPCInstrInfo::getMemOperandWithOffsetWidth(
4044 const MachineInstr &LdSt,
4045 const MachineOperand *&BaseReg,
4046 int64_t &Offset,
4047 unsigned &Width,
4048 const TargetRegisterInfo *TRI) const {
4049 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4051 // Handle only loads/stores with base register followed by immediate offset.
4052 if (LdSt.getNumExplicitOperands() != 3)
4053 return false;
4054 if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg())
4055 return false;
4057 if (!LdSt.hasOneMemOperand())
4058 return false;
4060 Width = (*LdSt.memoperands_begin())->getSize();
4061 Offset = LdSt.getOperand(1).getImm();
4062 BaseReg = &LdSt.getOperand(2);
4063 return true;
4066 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
4067 const MachineInstr &MIa, const MachineInstr &MIb) const {
4068 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
4069 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
4071 if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
4072 MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
4073 return false;
4075 // Retrieve the base register, offset from the base register and width. Width
4076 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If
4077 // base registers are identical, and the offset of a lower memory access +
4078 // the width doesn't overlap the offset of a higher memory access,
4079 // then the memory accesses are different.
4080 const TargetRegisterInfo *TRI = &getRegisterInfo();
4081 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
4082 int64_t OffsetA = 0, OffsetB = 0;
4083 unsigned int WidthA = 0, WidthB = 0;
4084 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) &&
4085 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) {
4086 if (BaseOpA->isIdenticalTo(*BaseOpB)) {
4087 int LowOffset = std::min(OffsetA, OffsetB);
4088 int HighOffset = std::max(OffsetA, OffsetB);
4089 int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
4090 if (LowOffset + LowWidth <= HighOffset)
4091 return true;
4094 return false;