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.
10//
11//===----------------------------------------------------------------------===//
12
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/LivePhysRegs.h"
24#include "llvm/CodeGen/MachineCombinerPattern.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineMemOperand.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/PseudoSourceValue.h"
31#include "llvm/CodeGen/RegisterClassInfo.h"
32#include "llvm/CodeGen/RegisterPressure.h"
33#include "llvm/CodeGen/RegisterScavenging.h"
34#include "llvm/CodeGen/ScheduleDAG.h"
35#include "llvm/CodeGen/SlotIndexes.h"
36#include "llvm/CodeGen/StackMaps.h"
37#include "llvm/IR/Module.h"
38#include "llvm/MC/MCInst.h"
39#include "llvm/MC/TargetRegistry.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
44
45using namespace llvm;
46
47#define DEBUG_TYPE "ppc-instr-info"
48
49#define GET_INSTRMAP_INFO
50#define GET_INSTRINFO_CTOR_DTOR
51#include "PPCGenInstrInfo.inc"
52
53STATISTIC(NumStoreSPILLVSRRCAsVec,
54 "Number of spillvsrrc spilled to stack as vec");
55STATISTIC(NumStoreSPILLVSRRCAsGpr,
56 "Number of spillvsrrc spilled to stack as gpr");
57STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc");
58STATISTIC(CmpIselsConverted,
59 "Number of ISELs that depend on comparison of constants converted");
60STATISTIC(MissedConvertibleImmediateInstrs,
61 "Number of compare-immediate instructions fed by constants");
62STATISTIC(NumRcRotatesConvertedToRcAnd,
63 "Number of record-form rotates converted to record-form andi");
64
65static cl::
66opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
67 cl::desc("Disable analysis for CTR loops"));
68
69static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
70cl::desc("Disable compare instruction optimization"), cl::Hidden);
71
72static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
73cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
74cl::Hidden);
75
76static cl::opt<bool>
77UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden,
78 cl::desc("Use the old (incorrect) instruction latency calculation"));
79
80static cl::opt<float>
81 FMARPFactor("ppc-fma-rp-factor", cl::Hidden, cl::init(Val: 1.5),
82 cl::desc("register pressure factor for the transformations."));
83
84static cl::opt<bool> EnableFMARegPressureReduction(
85 "ppc-fma-rp-reduction", cl::Hidden, cl::init(Val: true),
86 cl::desc("enable register pressure reduce in machine combiner pass."));
87
88// Pin the vtable to this file.
89void PPCInstrInfo::anchor() {}
90
91PPCInstrInfo::PPCInstrInfo(const PPCSubtarget &STI)
92 : PPCGenInstrInfo(STI, RI, PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP,
93 /* CatchRetOpcode */ -1,
94 STI.isPPC64() ? PPC::BLR8 : PPC::BLR),
95 Subtarget(STI), RI(STI.getTargetMachine()) {}
96
97const TargetRegisterClass *PPCInstrInfo::getInlineAsmMemoryOperandRegClass(
98 InlineAsm::ConstraintCode C) const {
99 return Subtarget.isPPC64() ? &PPC::G8RC_NOX0RegClass
100 : &PPC::GPRC_NOR0RegClass;
101}
102
103/// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
104/// this target when scheduling the DAG.
105ScheduleHazardRecognizer *
106PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
107 const ScheduleDAG *DAG) const {
108 unsigned Directive =
109 static_cast<const PPCSubtarget *>(STI)->getCPUDirective();
110 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
111 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
112 const InstrItineraryData *II =
113 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
114 return new ScoreboardHazardRecognizer(II, DAG);
115 }
116
117 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
118}
119
120/// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
121/// to use for this target when scheduling the DAG.
122ScheduleHazardRecognizer *
123PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
124 const ScheduleDAG *DAG) const {
125 unsigned Directive =
126 DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective();
127
128 // FIXME: Leaving this as-is until we have POWER9 scheduling info
129 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
130 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
131
132 // Most subtargets use a PPC970 recognizer.
133 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
134 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
135 assert(DAG->TII && "No InstrInfo?");
136
137 return new PPCHazardRecognizer970(*DAG);
138 }
139
140 return new ScoreboardHazardRecognizer(II, DAG);
141}
142
143unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
144 const MachineInstr &MI,
145 unsigned *PredCost) const {
146 if (!ItinData || UseOldLatencyCalc)
147 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost);
148
149 // The default implementation of getInstrLatency calls getStageLatency, but
150 // getStageLatency does not do the right thing for us. While we have
151 // itinerary, most cores are fully pipelined, and so the itineraries only
152 // express the first part of the pipeline, not every stage. Instead, we need
153 // to use the listed output operand cycle number (using operand 0 here, which
154 // is an output).
155
156 unsigned Latency = 1;
157 unsigned DefClass = MI.getDesc().getSchedClass();
158 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
159 const MachineOperand &MO = MI.getOperand(i);
160 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
161 continue;
162
163 std::optional<unsigned> Cycle = ItinData->getOperandCycle(ItinClassIndx: DefClass, OperandIdx: i);
164 if (!Cycle)
165 continue;
166
167 Latency = std::max(a: Latency, b: *Cycle);
168 }
169
170 return Latency;
171}
172
173std::optional<unsigned> PPCInstrInfo::getOperandLatency(
174 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
175 unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const {
176 std::optional<unsigned> Latency = PPCGenInstrInfo::getOperandLatency(
177 ItinData, DefMI, DefIdx, UseMI, UseIdx);
178
179 if (!DefMI.getParent())
180 return Latency;
181
182 const MachineOperand &DefMO = DefMI.getOperand(i: DefIdx);
183 Register Reg = DefMO.getReg();
184
185 bool IsRegCR;
186 if (Reg.isVirtual()) {
187 const MachineRegisterInfo *MRI =
188 &DefMI.getParent()->getParent()->getRegInfo();
189 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(RC: &PPC::CRRCRegClass) ||
190 MRI->getRegClass(Reg)->hasSuperClassEq(RC: &PPC::CRBITRCRegClass);
191 } else {
192 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
193 PPC::CRBITRCRegClass.contains(Reg);
194 }
195
196 if (UseMI.isBranch() && IsRegCR) {
197 if (!Latency)
198 Latency = getInstrLatency(ItinData, MI: DefMI);
199
200 // On some cores, there is an additional delay between writing to a condition
201 // register, and using it from a branch.
202 unsigned Directive = Subtarget.getCPUDirective();
203 switch (Directive) {
204 default: break;
205 case PPC::DIR_7400:
206 case PPC::DIR_750:
207 case PPC::DIR_970:
208 case PPC::DIR_E5500:
209 case PPC::DIR_PWR4:
210 case PPC::DIR_PWR5:
211 case PPC::DIR_PWR5X:
212 case PPC::DIR_PWR6:
213 case PPC::DIR_PWR6X:
214 case PPC::DIR_PWR7:
215 case PPC::DIR_PWR8:
216 // FIXME: Is this needed for POWER9?
217 Latency = *Latency + 2;
218 break;
219 }
220 }
221
222 return Latency;
223}
224
225void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &MI,
226 uint32_t Flags) const {
227 MI.setFlags(Flags);
228 MI.clearFlag(Flag: MachineInstr::MIFlag::NoSWrap);
229 MI.clearFlag(Flag: MachineInstr::MIFlag::NoUWrap);
230 MI.clearFlag(Flag: MachineInstr::MIFlag::IsExact);
231}
232
233// This function does not list all associative and commutative operations, but
234// only those worth feeding through the machine combiner in an attempt to
235// reduce the critical path. Mostly, this means floating-point operations,
236// because they have high latencies(>=5) (compared to other operations, such as
237// and/or, which are also associative and commutative, but have low latencies).
238bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
239 bool Invert) const {
240 if (Invert)
241 return false;
242 switch (Inst.getOpcode()) {
243 // Floating point:
244 // FP Add:
245 case PPC::FADD:
246 case PPC::FADDS:
247 // FP Multiply:
248 case PPC::FMUL:
249 case PPC::FMULS:
250 // Altivec Add:
251 case PPC::VADDFP:
252 // VSX Add:
253 case PPC::XSADDDP:
254 case PPC::XVADDDP:
255 case PPC::XVADDSP:
256 case PPC::XSADDSP:
257 // VSX Multiply:
258 case PPC::XSMULDP:
259 case PPC::XVMULDP:
260 case PPC::XVMULSP:
261 case PPC::XSMULSP:
262 return Inst.getFlag(Flag: MachineInstr::MIFlag::FmReassoc) &&
263 Inst.getFlag(Flag: MachineInstr::MIFlag::FmNsz);
264 // Fixed point:
265 // Multiply:
266 case PPC::MULHD:
267 case PPC::MULLD:
268 case PPC::MULHW:
269 case PPC::MULLW:
270 return true;
271 default:
272 return false;
273 }
274}
275
276#define InfoArrayIdxFMAInst 0
277#define InfoArrayIdxFAddInst 1
278#define InfoArrayIdxFMULInst 2
279#define InfoArrayIdxAddOpIdx 3
280#define InfoArrayIdxMULOpIdx 4
281#define InfoArrayIdxFSubInst 5
282// Array keeps info for FMA instructions:
283// Index 0(InfoArrayIdxFMAInst): FMA instruction;
284// Index 1(InfoArrayIdxFAddInst): ADD instruction associated with FMA;
285// Index 2(InfoArrayIdxFMULInst): MUL instruction associated with FMA;
286// Index 3(InfoArrayIdxAddOpIdx): ADD operand index in FMA operands;
287// Index 4(InfoArrayIdxMULOpIdx): first MUL operand index in FMA operands;
288// second MUL operand index is plus 1;
289// Index 5(InfoArrayIdxFSubInst): SUB instruction associated with FMA.
290static const uint16_t FMAOpIdxInfo[][6] = {
291 // FIXME: Add more FMA instructions like XSNMADDADP and so on.
292 {PPC::XSMADDADP, PPC::XSADDDP, PPC::XSMULDP, 1, 2, PPC::XSSUBDP},
293 {PPC::XSMADDASP, PPC::XSADDSP, PPC::XSMULSP, 1, 2, PPC::XSSUBSP},
294 {PPC::XVMADDADP, PPC::XVADDDP, PPC::XVMULDP, 1, 2, PPC::XVSUBDP},
295 {PPC::XVMADDASP, PPC::XVADDSP, PPC::XVMULSP, 1, 2, PPC::XVSUBSP},
296 {PPC::FMADD, PPC::FADD, PPC::FMUL, 3, 1, PPC::FSUB},
297 {PPC::FMADDS, PPC::FADDS, PPC::FMULS, 3, 1, PPC::FSUBS}};
298
299// Check if an opcode is a FMA instruction. If it is, return the index in array
300// FMAOpIdxInfo. Otherwise, return -1.
301int16_t PPCInstrInfo::getFMAOpIdxInfo(unsigned Opcode) const {
302 for (unsigned I = 0; I < std::size(FMAOpIdxInfo); I++)
303 if (FMAOpIdxInfo[I][InfoArrayIdxFMAInst] == Opcode)
304 return I;
305 return -1;
306}
307
308// On PowerPC target, we have two kinds of patterns related to FMA:
309// 1: Improve ILP.
310// Try to reassociate FMA chains like below:
311//
312// Pattern 1:
313// A = FADD X, Y (Leaf)
314// B = FMA A, M21, M22 (Prev)
315// C = FMA B, M31, M32 (Root)
316// -->
317// A = FMA X, M21, M22
318// B = FMA Y, M31, M32
319// C = FADD A, B
320//
321// Pattern 2:
322// A = FMA X, M11, M12 (Leaf)
323// B = FMA A, M21, M22 (Prev)
324// C = FMA B, M31, M32 (Root)
325// -->
326// A = FMUL M11, M12
327// B = FMA X, M21, M22
328// D = FMA A, M31, M32
329// C = FADD B, D
330//
331// breaking the dependency between A and B, allowing FMA to be executed in
332// parallel (or back-to-back in a pipeline) instead of depending on each other.
333//
334// 2: Reduce register pressure.
335// Try to reassociate FMA with FSUB and a constant like below:
336// C is a floating point const.
337//
338// Pattern 1:
339// A = FSUB X, Y (Leaf)
340// D = FMA B, C, A (Root)
341// -->
342// A = FMA B, Y, -C
343// D = FMA A, X, C
344//
345// Pattern 2:
346// A = FSUB X, Y (Leaf)
347// D = FMA B, A, C (Root)
348// -->
349// A = FMA B, Y, -C
350// D = FMA A, X, C
351//
352// Before the transformation, A must be assigned with different hardware
353// register with D. After the transformation, A and D must be assigned with
354// same hardware register due to TIE attribute of FMA instructions.
355//
356bool PPCInstrInfo::getFMAPatterns(MachineInstr &Root,
357 SmallVectorImpl<unsigned> &Patterns,
358 bool DoRegPressureReduce) const {
359 MachineBasicBlock *MBB = Root.getParent();
360 const MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
361
362 auto IsAllOpsVirtualReg = [](const MachineInstr &Instr) {
363 for (const auto &MO : Instr.explicit_operands())
364 if (!(MO.isReg() && MO.getReg().isVirtual()))
365 return false;
366 return true;
367 };
368
369 auto IsReassociableAddOrSub = [&](const MachineInstr &Instr,
370 unsigned OpType) {
371 if (Instr.getOpcode() !=
372 FMAOpIdxInfo[getFMAOpIdxInfo(Opcode: Root.getOpcode())][OpType])
373 return false;
374
375 // Instruction can be reassociated.
376 // fast math flags may prohibit reassociation.
377 if (!(Instr.getFlag(Flag: MachineInstr::MIFlag::FmReassoc) &&
378 Instr.getFlag(Flag: MachineInstr::MIFlag::FmNsz)))
379 return false;
380
381 // Instruction operands are virtual registers for reassociation.
382 if (!IsAllOpsVirtualReg(Instr))
383 return false;
384
385 // For register pressure reassociation, the FSub must have only one use as
386 // we want to delete the sub to save its def.
387 if (OpType == InfoArrayIdxFSubInst &&
388 !MRI->hasOneNonDBGUse(RegNo: Instr.getOperand(i: 0).getReg()))
389 return false;
390
391 return true;
392 };
393
394 auto IsReassociableFMA = [&](const MachineInstr &Instr, int16_t &AddOpIdx,
395 int16_t &MulOpIdx, bool IsLeaf) {
396 int16_t Idx = getFMAOpIdxInfo(Opcode: Instr.getOpcode());
397 if (Idx < 0)
398 return false;
399
400 // Instruction can be reassociated.
401 // fast math flags may prohibit reassociation.
402 if (!(Instr.getFlag(Flag: MachineInstr::MIFlag::FmReassoc) &&
403 Instr.getFlag(Flag: MachineInstr::MIFlag::FmNsz)))
404 return false;
405
406 // Instruction operands are virtual registers for reassociation.
407 if (!IsAllOpsVirtualReg(Instr))
408 return false;
409
410 MulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
411 if (IsLeaf)
412 return true;
413
414 AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
415
416 const MachineOperand &OpAdd = Instr.getOperand(i: AddOpIdx);
417 MachineInstr *MIAdd = MRI->getUniqueVRegDef(Reg: OpAdd.getReg());
418 // If 'add' operand's def is not in current block, don't do ILP related opt.
419 if (!MIAdd || MIAdd->getParent() != MBB)
420 return false;
421
422 // If this is not Leaf FMA Instr, its 'add' operand should only have one use
423 // as this fma will be changed later.
424 return MRI->hasOneNonDBGUse(RegNo: OpAdd.getReg());
425 };
426
427 int16_t AddOpIdx = -1;
428 int16_t MulOpIdx = -1;
429
430 bool IsUsedOnceL = false;
431 bool IsUsedOnceR = false;
432 MachineInstr *MULInstrL = nullptr;
433 MachineInstr *MULInstrR = nullptr;
434
435 auto IsRPReductionCandidate = [&]() {
436 // Currently, we only support float and double.
437 // FIXME: add support for other types.
438 unsigned Opcode = Root.getOpcode();
439 if (Opcode != PPC::XSMADDASP && Opcode != PPC::XSMADDADP)
440 return false;
441
442 // Root must be a valid FMA like instruction.
443 // Treat it as leaf as we don't care its add operand.
444 if (IsReassociableFMA(Root, AddOpIdx, MulOpIdx, true)) {
445 assert((MulOpIdx >= 0) && "mul operand index not right!");
446 Register MULRegL = RI.lookThruSingleUseCopyChain(
447 SrcReg: Root.getOperand(i: MulOpIdx).getReg(), MRI);
448 Register MULRegR = RI.lookThruSingleUseCopyChain(
449 SrcReg: Root.getOperand(i: MulOpIdx + 1).getReg(), MRI);
450 if (!MULRegL && !MULRegR)
451 return false;
452
453 if (MULRegL && !MULRegR) {
454 MULRegR =
455 RI.lookThruCopyLike(SrcReg: Root.getOperand(i: MulOpIdx + 1).getReg(), MRI);
456 IsUsedOnceL = true;
457 } else if (!MULRegL && MULRegR) {
458 MULRegL = RI.lookThruCopyLike(SrcReg: Root.getOperand(i: MulOpIdx).getReg(), MRI);
459 IsUsedOnceR = true;
460 } else {
461 IsUsedOnceL = true;
462 IsUsedOnceR = true;
463 }
464
465 if (!MULRegL.isVirtual() || !MULRegR.isVirtual())
466 return false;
467
468 MULInstrL = MRI->getVRegDef(Reg: MULRegL);
469 MULInstrR = MRI->getVRegDef(Reg: MULRegR);
470 return MULInstrL && MULInstrR;
471 }
472 return false;
473 };
474
475 // Register pressure fma reassociation patterns.
476 if (DoRegPressureReduce && IsRPReductionCandidate()) {
477 assert((MULInstrL && MULInstrR) && "wrong register preduction candidate!");
478 // Register pressure pattern 1
479 if (isLoadFromConstantPool(I: MULInstrL) && IsUsedOnceR &&
480 IsReassociableAddOrSub(*MULInstrR, InfoArrayIdxFSubInst)) {
481 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BCA\n");
482 Patterns.push_back(Elt: PPCMachineCombinerPattern::REASSOC_XY_BCA);
483 return true;
484 }
485
486 // Register pressure pattern 2
487 if ((isLoadFromConstantPool(I: MULInstrR) && IsUsedOnceL &&
488 IsReassociableAddOrSub(*MULInstrL, InfoArrayIdxFSubInst))) {
489 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_BAC\n");
490 Patterns.push_back(Elt: PPCMachineCombinerPattern::REASSOC_XY_BAC);
491 return true;
492 }
493 }
494
495 // ILP fma reassociation patterns.
496 // Root must be a valid FMA like instruction.
497 AddOpIdx = -1;
498 if (!IsReassociableFMA(Root, AddOpIdx, MulOpIdx, false))
499 return false;
500
501 assert((AddOpIdx >= 0) && "add operand index not right!");
502
503 Register RegB = Root.getOperand(i: AddOpIdx).getReg();
504 MachineInstr *Prev = MRI->getUniqueVRegDef(Reg: RegB);
505
506 // Prev must be a valid FMA like instruction.
507 AddOpIdx = -1;
508 if (!IsReassociableFMA(*Prev, AddOpIdx, MulOpIdx, false))
509 return false;
510
511 assert((AddOpIdx >= 0) && "add operand index not right!");
512
513 Register RegA = Prev->getOperand(i: AddOpIdx).getReg();
514 MachineInstr *Leaf = MRI->getUniqueVRegDef(Reg: RegA);
515 AddOpIdx = -1;
516 if (IsReassociableFMA(*Leaf, AddOpIdx, MulOpIdx, true)) {
517 Patterns.push_back(Elt: PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM);
518 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XMM_AMM_BMM\n");
519 return true;
520 }
521 if (IsReassociableAddOrSub(*Leaf, InfoArrayIdxFAddInst)) {
522 Patterns.push_back(Elt: PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM);
523 LLVM_DEBUG(dbgs() << "add pattern REASSOC_XY_AMM_BMM\n");
524 return true;
525 }
526 return false;
527}
528
529void PPCInstrInfo::finalizeInsInstrs(
530 MachineInstr &Root, unsigned &Pattern,
531 SmallVectorImpl<MachineInstr *> &InsInstrs) const {
532 assert(!InsInstrs.empty() && "Instructions set to be inserted is empty!");
533
534 MachineFunction *MF = Root.getMF();
535 MachineRegisterInfo *MRI = &MF->getRegInfo();
536 MachineConstantPool *MCP = MF->getConstantPool();
537
538 int16_t Idx = getFMAOpIdxInfo(Opcode: Root.getOpcode());
539 if (Idx < 0)
540 return;
541
542 uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
543
544 // For now we only need to fix up placeholder for register pressure reduce
545 // patterns.
546 Register ConstReg = 0;
547 switch (Pattern) {
548 case PPCMachineCombinerPattern::REASSOC_XY_BCA:
549 ConstReg =
550 RI.lookThruCopyLike(SrcReg: Root.getOperand(i: FirstMulOpIdx).getReg(), MRI);
551 break;
552 case PPCMachineCombinerPattern::REASSOC_XY_BAC:
553 ConstReg =
554 RI.lookThruCopyLike(SrcReg: Root.getOperand(i: FirstMulOpIdx + 1).getReg(), MRI);
555 break;
556 default:
557 // Not register pressure reduce patterns.
558 return;
559 }
560
561 MachineInstr *ConstDefInstr = MRI->getVRegDef(Reg: ConstReg);
562 // Get const value from const pool.
563 const Constant *C = getConstantFromConstantPool(I: ConstDefInstr);
564 assert(isa<llvm::ConstantFP>(C) && "not a valid constant!");
565
566 // Get negative fp const.
567 APFloat F1((dyn_cast<ConstantFP>(Val: C))->getValueAPF());
568 F1.changeSign();
569 Constant *NegC = ConstantFP::get(Context&: dyn_cast<ConstantFP>(Val: C)->getContext(), V: F1);
570 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: C->getType());
571
572 // Put negative fp const into constant pool.
573 unsigned ConstPoolIdx = MCP->getConstantPoolIndex(C: NegC, Alignment);
574
575 MachineOperand *Placeholder = nullptr;
576 // Record the placeholder PPC::ZERO8 we add in reassociateFMA.
577 for (auto *Inst : InsInstrs) {
578 for (MachineOperand &Operand : Inst->explicit_operands()) {
579 assert(Operand.isReg() && "Invalid instruction in InsInstrs!");
580 if (Operand.getReg() == PPC::ZERO8) {
581 Placeholder = &Operand;
582 break;
583 }
584 }
585 }
586
587 assert(Placeholder && "Placeholder does not exist!");
588
589 // Generate instructions to load the const fp from constant pool.
590 // We only support PPC64 and medium code model.
591 Register LoadNewConst =
592 generateLoadForNewConst(Idx: ConstPoolIdx, MI: &Root, Ty: C->getType(), InsInstrs);
593
594 // Fill the placeholder with the new load from constant pool.
595 Placeholder->setReg(LoadNewConst);
596}
597
598bool PPCInstrInfo::shouldReduceRegisterPressure(
599 const MachineBasicBlock *MBB, const RegisterClassInfo *RegClassInfo) const {
600
601 if (!EnableFMARegPressureReduction)
602 return false;
603
604 // Currently, we only enable register pressure reducing in machine combiner
605 // for: 1: PPC64; 2: Code Model is Medium; 3: Power9 which also has vector
606 // support.
607 //
608 // So we need following instructions to access a TOC entry:
609 //
610 // %6:g8rc_and_g8rc_nox0 = ADDIStocHA8 $x2, %const.0
611 // %7:vssrc = DFLOADf32 target-flags(ppc-toc-lo) %const.0,
612 // killed %6:g8rc_and_g8rc_nox0, implicit $x2 :: (load 4 from constant-pool)
613 //
614 // FIXME: add more supported targets, like Small and Large code model, PPC32,
615 // AIX.
616 if (!(Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
617 Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium))
618 return false;
619
620 const MachineFunction *MF = MBB->getParent();
621 const MachineRegisterInfo *MRI = &MF->getRegInfo();
622
623 auto GetMBBPressure =
624 [&](const MachineBasicBlock *MBB) -> std::vector<unsigned> {
625 RegionPressure Pressure;
626 RegPressureTracker RPTracker(Pressure);
627
628 // Initialize the register pressure tracker.
629 RPTracker.init(mf: MBB->getParent(), rci: RegClassInfo, lis: nullptr, mbb: MBB, pos: MBB->end(),
630 /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
631
632 for (const auto &MI : reverse(C: *MBB)) {
633 if (MI.isDebugValue() || MI.isDebugLabel())
634 continue;
635 RegisterOperands RegOpers;
636 RegOpers.collect(MI, TRI: RI, MRI: *MRI, TrackLaneMasks: false, IgnoreDead: false);
637 RPTracker.recedeSkipDebugValues();
638 assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
639 RPTracker.recede(RegOpers);
640 }
641
642 // Close the RPTracker to finalize live ins.
643 RPTracker.closeRegion();
644
645 return RPTracker.getPressure().MaxSetPressure;
646 };
647
648 // For now we only care about float and double type fma.
649 unsigned VSSRCLimit =
650 RegClassInfo->getRegPressureSetLimit(Idx: PPC::RegisterPressureSets::VSSRC);
651
652 // Only reduce register pressure when pressure is high.
653 return GetMBBPressure(MBB)[PPC::RegisterPressureSets::VSSRC] >
654 (float)VSSRCLimit * FMARPFactor;
655}
656
657bool PPCInstrInfo::isLoadFromConstantPool(MachineInstr *I) const {
658 // I has only one memory operand which is load from constant pool.
659 if (!I->hasOneMemOperand())
660 return false;
661
662 MachineMemOperand *Op = I->memoperands()[0];
663 return Op->isLoad() && Op->getPseudoValue() &&
664 Op->getPseudoValue()->kind() == PseudoSourceValue::ConstantPool;
665}
666
667Register PPCInstrInfo::generateLoadForNewConst(
668 unsigned Idx, MachineInstr *MI, Type *Ty,
669 SmallVectorImpl<MachineInstr *> &InsInstrs) const {
670 // Now we only support PPC64, Medium code model and P9 with vector.
671 // We have immutable pattern to access const pool. See function
672 // shouldReduceRegisterPressure.
673 assert((Subtarget.isPPC64() && Subtarget.hasP9Vector() &&
674 Subtarget.getTargetMachine().getCodeModel() == CodeModel::Medium) &&
675 "Target not supported!\n");
676
677 MachineFunction *MF = MI->getMF();
678 MachineRegisterInfo *MRI = &MF->getRegInfo();
679
680 // Generate ADDIStocHA8
681 Register VReg1 = MRI->createVirtualRegister(RegClass: &PPC::G8RC_and_G8RC_NOX0RegClass);
682 MachineInstrBuilder TOCOffset =
683 BuildMI(MF&: *MF, MIMD: MI->getDebugLoc(), MCID: get(Opcode: PPC::ADDIStocHA8), DestReg: VReg1)
684 .addReg(RegNo: PPC::X2)
685 .addConstantPoolIndex(Idx);
686
687 assert((Ty->isFloatTy() || Ty->isDoubleTy()) &&
688 "Only float and double are supported!");
689
690 unsigned LoadOpcode;
691 // Should be float type or double type.
692 if (Ty->isFloatTy())
693 LoadOpcode = PPC::DFLOADf32;
694 else
695 LoadOpcode = PPC::DFLOADf64;
696
697 const TargetRegisterClass *RC = MRI->getRegClass(Reg: MI->getOperand(i: 0).getReg());
698 Register VReg2 = MRI->createVirtualRegister(RegClass: RC);
699 MachineMemOperand *MMO = MF->getMachineMemOperand(
700 PtrInfo: MachinePointerInfo::getConstantPool(MF&: *MF), F: MachineMemOperand::MOLoad,
701 Size: Ty->getScalarSizeInBits() / 8, BaseAlignment: MF->getDataLayout().getPrefTypeAlign(Ty));
702
703 // Generate Load from constant pool.
704 MachineInstrBuilder Load =
705 BuildMI(MF&: *MF, MIMD: MI->getDebugLoc(), MCID: get(Opcode: LoadOpcode), DestReg: VReg2)
706 .addConstantPoolIndex(Idx)
707 .addReg(RegNo: VReg1, Flags: getKillRegState(B: true))
708 .addMemOperand(MMO);
709
710 Load->getOperand(i: 1).setTargetFlags(PPCII::MO_TOC_LO);
711
712 // Insert the toc load instructions into InsInstrs.
713 InsInstrs.insert(I: InsInstrs.begin(), Elt: Load);
714 InsInstrs.insert(I: InsInstrs.begin(), Elt: TOCOffset);
715 return VReg2;
716}
717
718// This function returns the const value in constant pool if the \p I is a load
719// from constant pool.
720const Constant *
721PPCInstrInfo::getConstantFromConstantPool(MachineInstr *I) const {
722 MachineFunction *MF = I->getMF();
723 MachineRegisterInfo *MRI = &MF->getRegInfo();
724 MachineConstantPool *MCP = MF->getConstantPool();
725 assert(I->mayLoad() && "Should be a load instruction.\n");
726 for (auto MO : I->uses()) {
727 if (!MO.isReg())
728 continue;
729 Register Reg = MO.getReg();
730 if (Reg == 0 || !Reg.isVirtual())
731 continue;
732 // Find the toc address.
733 MachineInstr *DefMI = MRI->getVRegDef(Reg);
734 for (auto MO2 : DefMI->uses())
735 if (MO2.isCPI())
736 return (MCP->getConstants())[MO2.getIndex()].Val.ConstVal;
737 }
738 return nullptr;
739}
740
741CombinerObjective PPCInstrInfo::getCombinerObjective(unsigned Pattern) const {
742 switch (Pattern) {
743 case PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM:
744 case PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM:
745 return CombinerObjective::MustReduceDepth;
746 case PPCMachineCombinerPattern::REASSOC_XY_BCA:
747 case PPCMachineCombinerPattern::REASSOC_XY_BAC:
748 return CombinerObjective::MustReduceRegisterPressure;
749 default:
750 return TargetInstrInfo::getCombinerObjective(Pattern);
751 }
752}
753
754bool PPCInstrInfo::getMachineCombinerPatterns(
755 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
756 bool DoRegPressureReduce) const {
757 // Using the machine combiner in this way is potentially expensive, so
758 // restrict to when aggressive optimizations are desired.
759 if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOptLevel::Aggressive)
760 return false;
761
762 if (getFMAPatterns(Root, Patterns, DoRegPressureReduce))
763 return true;
764
765 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
766 DoRegPressureReduce);
767}
768
769void PPCInstrInfo::genAlternativeCodeSequence(
770 MachineInstr &Root, unsigned Pattern,
771 SmallVectorImpl<MachineInstr *> &InsInstrs,
772 SmallVectorImpl<MachineInstr *> &DelInstrs,
773 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
774 switch (Pattern) {
775 case PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM:
776 case PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM:
777 case PPCMachineCombinerPattern::REASSOC_XY_BCA:
778 case PPCMachineCombinerPattern::REASSOC_XY_BAC:
779 reassociateFMA(Root, Pattern, InsInstrs, DelInstrs, InstrIdxForVirtReg);
780 break;
781 default:
782 // Reassociate default patterns.
783 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
784 DelInstrs, InstIdxForVirtReg&: InstrIdxForVirtReg);
785 break;
786 }
787}
788
789void PPCInstrInfo::reassociateFMA(
790 MachineInstr &Root, unsigned Pattern,
791 SmallVectorImpl<MachineInstr *> &InsInstrs,
792 SmallVectorImpl<MachineInstr *> &DelInstrs,
793 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
794 MachineFunction *MF = Root.getMF();
795 MachineRegisterInfo &MRI = MF->getRegInfo();
796 MachineOperand &OpC = Root.getOperand(i: 0);
797 Register RegC = OpC.getReg();
798 const TargetRegisterClass *RC = MRI.getRegClass(Reg: RegC);
799 MRI.constrainRegClass(Reg: RegC, RC);
800
801 unsigned FmaOp = Root.getOpcode();
802 int16_t Idx = getFMAOpIdxInfo(Opcode: FmaOp);
803 assert(Idx >= 0 && "Root must be a FMA instruction");
804
805 bool IsILPReassociate =
806 (Pattern == PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM) ||
807 (Pattern == PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM);
808
809 uint16_t AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx];
810 uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx];
811
812 MachineInstr *Prev = nullptr;
813 MachineInstr *Leaf = nullptr;
814 switch (Pattern) {
815 default:
816 llvm_unreachable("not recognized pattern!");
817 case PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM:
818 case PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM:
819 Prev = MRI.getUniqueVRegDef(Reg: Root.getOperand(i: AddOpIdx).getReg());
820 Leaf = MRI.getUniqueVRegDef(Reg: Prev->getOperand(i: AddOpIdx).getReg());
821 break;
822 case PPCMachineCombinerPattern::REASSOC_XY_BAC: {
823 Register MULReg =
824 RI.lookThruCopyLike(SrcReg: Root.getOperand(i: FirstMulOpIdx).getReg(), MRI: &MRI);
825 Leaf = MRI.getVRegDef(Reg: MULReg);
826 break;
827 }
828 case PPCMachineCombinerPattern::REASSOC_XY_BCA: {
829 Register MULReg =
830 RI.lookThruCopyLike(SrcReg: Root.getOperand(i: FirstMulOpIdx + 1).getReg(), MRI: &MRI);
831 Leaf = MRI.getVRegDef(Reg: MULReg);
832 break;
833 }
834 }
835
836 uint32_t IntersectedFlags = 0;
837 if (IsILPReassociate)
838 IntersectedFlags = Root.getFlags() & Prev->getFlags() & Leaf->getFlags();
839 else
840 IntersectedFlags = Root.getFlags() & Leaf->getFlags();
841
842 auto GetOperandInfo = [&](const MachineOperand &Operand, Register &Reg,
843 bool &KillFlag) {
844 Reg = Operand.getReg();
845 MRI.constrainRegClass(Reg, RC);
846 KillFlag = Operand.isKill();
847 };
848
849 auto GetFMAInstrInfo = [&](const MachineInstr &Instr, Register &MulOp1,
850 Register &MulOp2, Register &AddOp,
851 bool &MulOp1KillFlag, bool &MulOp2KillFlag,
852 bool &AddOpKillFlag) {
853 GetOperandInfo(Instr.getOperand(i: FirstMulOpIdx), MulOp1, MulOp1KillFlag);
854 GetOperandInfo(Instr.getOperand(i: FirstMulOpIdx + 1), MulOp2, MulOp2KillFlag);
855 GetOperandInfo(Instr.getOperand(i: AddOpIdx), AddOp, AddOpKillFlag);
856 };
857
858 Register RegM11, RegM12, RegX, RegY, RegM21, RegM22, RegM31, RegM32, RegA11,
859 RegA21, RegB;
860 bool KillX = false, KillY = false, KillM11 = false, KillM12 = false,
861 KillM21 = false, KillM22 = false, KillM31 = false, KillM32 = false,
862 KillA11 = false, KillA21 = false, KillB = false;
863
864 GetFMAInstrInfo(Root, RegM31, RegM32, RegB, KillM31, KillM32, KillB);
865
866 if (IsILPReassociate)
867 GetFMAInstrInfo(*Prev, RegM21, RegM22, RegA21, KillM21, KillM22, KillA21);
868
869 if (Pattern == PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
870 GetFMAInstrInfo(*Leaf, RegM11, RegM12, RegA11, KillM11, KillM12, KillA11);
871 GetOperandInfo(Leaf->getOperand(i: AddOpIdx), RegX, KillX);
872 } else if (Pattern == PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM) {
873 GetOperandInfo(Leaf->getOperand(i: 1), RegX, KillX);
874 GetOperandInfo(Leaf->getOperand(i: 2), RegY, KillY);
875 } else {
876 // Get FSUB instruction info.
877 GetOperandInfo(Leaf->getOperand(i: 1), RegX, KillX);
878 GetOperandInfo(Leaf->getOperand(i: 2), RegY, KillY);
879 }
880
881 // Create new virtual registers for the new results instead of
882 // recycling legacy ones because the MachineCombiner's computation of the
883 // critical path requires a new register definition rather than an existing
884 // one.
885 // For register pressure reassociation, we only need create one virtual
886 // register for the new fma.
887 Register NewVRA = MRI.createVirtualRegister(RegClass: RC);
888 InstrIdxForVirtReg.insert(KV: std::make_pair(x&: NewVRA, y: 0));
889
890 Register NewVRB = 0;
891 if (IsILPReassociate) {
892 NewVRB = MRI.createVirtualRegister(RegClass: RC);
893 InstrIdxForVirtReg.insert(KV: std::make_pair(x&: NewVRB, y: 1));
894 }
895
896 Register NewVRD = 0;
897 if (Pattern == PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM) {
898 NewVRD = MRI.createVirtualRegister(RegClass: RC);
899 InstrIdxForVirtReg.insert(KV: std::make_pair(x&: NewVRD, y: 2));
900 }
901
902 auto AdjustOperandOrder = [&](MachineInstr *MI, Register RegAdd, bool KillAdd,
903 Register RegMul1, bool KillRegMul1,
904 Register RegMul2, bool KillRegMul2) {
905 MI->getOperand(i: AddOpIdx).setReg(RegAdd);
906 MI->getOperand(i: AddOpIdx).setIsKill(KillAdd);
907 MI->getOperand(i: FirstMulOpIdx).setReg(RegMul1);
908 MI->getOperand(i: FirstMulOpIdx).setIsKill(KillRegMul1);
909 MI->getOperand(i: FirstMulOpIdx + 1).setReg(RegMul2);
910 MI->getOperand(i: FirstMulOpIdx + 1).setIsKill(KillRegMul2);
911 };
912
913 MachineInstrBuilder NewARegPressure, NewCRegPressure;
914 switch (Pattern) {
915 default:
916 llvm_unreachable("not recognized pattern!");
917 case PPCMachineCombinerPattern::REASSOC_XY_AMM_BMM: {
918 // Create new instructions for insertion.
919 MachineInstrBuilder MINewB =
920 BuildMI(MF&: *MF, MIMD: Prev->getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: NewVRB)
921 .addReg(RegNo: RegX, Flags: getKillRegState(B: KillX))
922 .addReg(RegNo: RegM21, Flags: getKillRegState(B: KillM21))
923 .addReg(RegNo: RegM22, Flags: getKillRegState(B: KillM22));
924 MachineInstrBuilder MINewA =
925 BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: NewVRA)
926 .addReg(RegNo: RegY, Flags: getKillRegState(B: KillY))
927 .addReg(RegNo: RegM31, Flags: getKillRegState(B: KillM31))
928 .addReg(RegNo: RegM32, Flags: getKillRegState(B: KillM32));
929 // If AddOpIdx is not 1, adjust the order.
930 if (AddOpIdx != 1) {
931 AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
932 AdjustOperandOrder(MINewA, RegY, KillY, RegM31, KillM31, RegM32, KillM32);
933 }
934
935 MachineInstrBuilder MINewC =
936 BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(),
937 MCID: get(Opcode: FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), DestReg: RegC)
938 .addReg(RegNo: NewVRB, Flags: getKillRegState(B: true))
939 .addReg(RegNo: NewVRA, Flags: getKillRegState(B: true));
940
941 // Update flags for newly created instructions.
942 setSpecialOperandAttr(MI&: *MINewA, Flags: IntersectedFlags);
943 setSpecialOperandAttr(MI&: *MINewB, Flags: IntersectedFlags);
944 setSpecialOperandAttr(MI&: *MINewC, Flags: IntersectedFlags);
945
946 // Record new instructions for insertion.
947 InsInstrs.push_back(Elt: MINewA);
948 InsInstrs.push_back(Elt: MINewB);
949 InsInstrs.push_back(Elt: MINewC);
950 break;
951 }
952 case PPCMachineCombinerPattern::REASSOC_XMM_AMM_BMM: {
953 assert(NewVRD && "new FMA register not created!");
954 // Create new instructions for insertion.
955 MachineInstrBuilder MINewA =
956 BuildMI(MF&: *MF, MIMD: Leaf->getDebugLoc(),
957 MCID: get(Opcode: FMAOpIdxInfo[Idx][InfoArrayIdxFMULInst]), DestReg: NewVRA)
958 .addReg(RegNo: RegM11, Flags: getKillRegState(B: KillM11))
959 .addReg(RegNo: RegM12, Flags: getKillRegState(B: KillM12));
960 MachineInstrBuilder MINewB =
961 BuildMI(MF&: *MF, MIMD: Prev->getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: NewVRB)
962 .addReg(RegNo: RegX, Flags: getKillRegState(B: KillX))
963 .addReg(RegNo: RegM21, Flags: getKillRegState(B: KillM21))
964 .addReg(RegNo: RegM22, Flags: getKillRegState(B: KillM22));
965 MachineInstrBuilder MINewD =
966 BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: NewVRD)
967 .addReg(RegNo: NewVRA, Flags: getKillRegState(B: true))
968 .addReg(RegNo: RegM31, Flags: getKillRegState(B: KillM31))
969 .addReg(RegNo: RegM32, Flags: getKillRegState(B: KillM32));
970 // If AddOpIdx is not 1, adjust the order.
971 if (AddOpIdx != 1) {
972 AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22);
973 AdjustOperandOrder(MINewD, NewVRA, true, RegM31, KillM31, RegM32,
974 KillM32);
975 }
976
977 MachineInstrBuilder MINewC =
978 BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(),
979 MCID: get(Opcode: FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), DestReg: RegC)
980 .addReg(RegNo: NewVRB, Flags: getKillRegState(B: true))
981 .addReg(RegNo: NewVRD, Flags: getKillRegState(B: true));
982
983 // Update flags for newly created instructions.
984 setSpecialOperandAttr(MI&: *MINewA, Flags: IntersectedFlags);
985 setSpecialOperandAttr(MI&: *MINewB, Flags: IntersectedFlags);
986 setSpecialOperandAttr(MI&: *MINewD, Flags: IntersectedFlags);
987 setSpecialOperandAttr(MI&: *MINewC, Flags: IntersectedFlags);
988
989 // Record new instructions for insertion.
990 InsInstrs.push_back(Elt: MINewA);
991 InsInstrs.push_back(Elt: MINewB);
992 InsInstrs.push_back(Elt: MINewD);
993 InsInstrs.push_back(Elt: MINewC);
994 break;
995 }
996 case PPCMachineCombinerPattern::REASSOC_XY_BAC:
997 case PPCMachineCombinerPattern::REASSOC_XY_BCA: {
998 Register VarReg;
999 bool KillVarReg = false;
1000 if (Pattern == PPCMachineCombinerPattern::REASSOC_XY_BCA) {
1001 VarReg = RegM31;
1002 KillVarReg = KillM31;
1003 } else {
1004 VarReg = RegM32;
1005 KillVarReg = KillM32;
1006 }
1007 // We don't want to get negative const from memory pool too early, as the
1008 // created entry will not be deleted even if it has no users. Since all
1009 // operand of Leaf and Root are virtual register, we use zero register
1010 // here as a placeholder. When the InsInstrs is selected in
1011 // MachineCombiner, we call finalizeInsInstrs to replace the zero register
1012 // with a virtual register which is a load from constant pool.
1013 NewARegPressure = BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: NewVRA)
1014 .addReg(RegNo: RegB, Flags: getKillRegState(B: RegB))
1015 .addReg(RegNo: RegY, Flags: getKillRegState(B: KillY))
1016 .addReg(RegNo: PPC::ZERO8);
1017 NewCRegPressure = BuildMI(MF&: *MF, MIMD: Root.getDebugLoc(), MCID: get(Opcode: FmaOp), DestReg: RegC)
1018 .addReg(RegNo: NewVRA, Flags: getKillRegState(B: true))
1019 .addReg(RegNo: RegX, Flags: getKillRegState(B: KillX))
1020 .addReg(RegNo: VarReg, Flags: getKillRegState(B: KillVarReg));
1021 // For now, we only support xsmaddadp/xsmaddasp, their add operand are
1022 // both at index 1, no need to adjust.
1023 // FIXME: when add more fma instructions support, like fma/fmas, adjust
1024 // the operand index here.
1025 break;
1026 }
1027 }
1028
1029 if (!IsILPReassociate) {
1030 setSpecialOperandAttr(MI&: *NewARegPressure, Flags: IntersectedFlags);
1031 setSpecialOperandAttr(MI&: *NewCRegPressure, Flags: IntersectedFlags);
1032
1033 InsInstrs.push_back(Elt: NewARegPressure);
1034 InsInstrs.push_back(Elt: NewCRegPressure);
1035 }
1036
1037 assert(!InsInstrs.empty() &&
1038 "Insertion instructions set should not be empty!");
1039
1040 // Record old instructions for deletion.
1041 DelInstrs.push_back(Elt: Leaf);
1042 if (IsILPReassociate)
1043 DelInstrs.push_back(Elt: Prev);
1044 DelInstrs.push_back(Elt: &Root);
1045}
1046
1047// Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
1048bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
1049 Register &SrcReg, Register &DstReg,
1050 unsigned &SubIdx) const {
1051 switch (MI.getOpcode()) {
1052 default: return false;
1053 case PPC::EXTSW:
1054 case PPC::EXTSW_32:
1055 case PPC::EXTSW_32_64:
1056 SrcReg = MI.getOperand(i: 1).getReg();
1057 DstReg = MI.getOperand(i: 0).getReg();
1058 SubIdx = PPC::sub_32;
1059 return true;
1060 }
1061}
1062
1063Register PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
1064 int &FrameIndex) const {
1065 if (llvm::is_contained(Range: getLoadOpcodesForSpillArray(), Element: MI.getOpcode())) {
1066 // Check for the operands added by addFrameReference (the immediate is the
1067 // offset which defaults to 0).
1068 if (MI.getOperand(i: 1).isImm() && !MI.getOperand(i: 1).getImm() &&
1069 MI.getOperand(i: 2).isFI()) {
1070 FrameIndex = MI.getOperand(i: 2).getIndex();
1071 return MI.getOperand(i: 0).getReg();
1072 }
1073 }
1074 return 0;
1075}
1076
1077// For opcodes with the ReMaterializable flag set, this function is called to
1078// verify the instruction is really rematable.
1079bool PPCInstrInfo::isReMaterializableImpl(
1080 const MachineInstr &MI) const {
1081 switch (MI.getOpcode()) {
1082 default:
1083 // Let base implementaion decide.
1084 break;
1085 case PPC::LI:
1086 case PPC::LI8:
1087 case PPC::PLI:
1088 case PPC::PLI8:
1089 case PPC::LIS:
1090 case PPC::LIS8:
1091 case PPC::ADDIStocHA:
1092 case PPC::ADDIStocHA8:
1093 case PPC::ADDItocL:
1094 case PPC::ADDItocL8:
1095 case PPC::LOAD_STACK_GUARD:
1096 case PPC::PPCLdFixedAddr:
1097 case PPC::XXLXORz:
1098 case PPC::XXLXORspz:
1099 case PPC::XXLXORdpz:
1100 case PPC::XXLEQVOnes:
1101 case PPC::XXSPLTI32DX:
1102 case PPC::XXSPLTIW:
1103 case PPC::XXSPLTIDP:
1104 case PPC::V_SET0B:
1105 case PPC::V_SET0H:
1106 case PPC::V_SET0:
1107 case PPC::V_SETALLONESB:
1108 case PPC::V_SETALLONESH:
1109 case PPC::V_SETALLONES:
1110 case PPC::CRSET:
1111 case PPC::CRUNSET:
1112 case PPC::XXSETACCZ:
1113 case PPC::DMXXSETACCZ:
1114 return true;
1115 }
1116 return TargetInstrInfo::isReMaterializableImpl(MI);
1117}
1118
1119Register PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
1120 int &FrameIndex) const {
1121 if (llvm::is_contained(Range: getStoreOpcodesForSpillArray(), Element: MI.getOpcode())) {
1122 if (MI.getOperand(i: 1).isImm() && !MI.getOperand(i: 1).getImm() &&
1123 MI.getOperand(i: 2).isFI()) {
1124 FrameIndex = MI.getOperand(i: 2).getIndex();
1125 return MI.getOperand(i: 0).getReg();
1126 }
1127 }
1128 return 0;
1129}
1130
1131MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1132 unsigned OpIdx1,
1133 unsigned OpIdx2) const {
1134 MachineFunction &MF = *MI.getParent()->getParent();
1135
1136 // Normal instructions can be commuted the obvious way.
1137 if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec)
1138 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1139 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
1140 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
1141 // changing the relative order of the mask operands might change what happens
1142 // to the high-bits of the mask (and, thus, the result).
1143
1144 // Cannot commute if it has a non-zero rotate count.
1145 if (MI.getOperand(i: 3).getImm() != 0)
1146 return nullptr;
1147
1148 // If we have a zero rotate count, we have:
1149 // M = mask(MB,ME)
1150 // Op0 = (Op1 & ~M) | (Op2 & M)
1151 // Change this to:
1152 // M = mask((ME+1)&31, (MB-1)&31)
1153 // Op0 = (Op2 & ~M) | (Op1 & M)
1154
1155 // Swap op1/op2
1156 assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) &&
1157 "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec.");
1158 Register Reg0 = MI.getOperand(i: 0).getReg();
1159 Register Reg1 = MI.getOperand(i: 1).getReg();
1160 Register Reg2 = MI.getOperand(i: 2).getReg();
1161 unsigned SubReg1 = MI.getOperand(i: 1).getSubReg();
1162 unsigned SubReg2 = MI.getOperand(i: 2).getSubReg();
1163 bool Reg1IsKill = MI.getOperand(i: 1).isKill();
1164 bool Reg2IsKill = MI.getOperand(i: 2).isKill();
1165 bool ChangeReg0 = false;
1166 // If machine instrs are no longer in two-address forms, update
1167 // destination register as well.
1168 if (Reg0 == Reg1) {
1169 // Must be two address instruction (i.e. op1 is tied to op0).
1170 assert(MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) == 0 &&
1171 "Expecting a two-address instruction!");
1172 assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
1173 Reg2IsKill = false;
1174 ChangeReg0 = true;
1175 }
1176
1177 // Masks.
1178 unsigned MB = MI.getOperand(i: 4).getImm();
1179 unsigned ME = MI.getOperand(i: 5).getImm();
1180
1181 // We can't commute a trivial mask (there is no way to represent an all-zero
1182 // mask).
1183 if (MB == 0 && ME == 31)
1184 return nullptr;
1185
1186 if (NewMI) {
1187 // Create a new instruction.
1188 Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(i: 0).getReg();
1189 bool Reg0IsDead = MI.getOperand(i: 0).isDead();
1190 return BuildMI(MF, MIMD: MI.getDebugLoc(), MCID: MI.getDesc())
1191 .addReg(RegNo: Reg0, Flags: RegState::Define | getDeadRegState(B: Reg0IsDead))
1192 .addReg(RegNo: Reg2, Flags: getKillRegState(B: Reg2IsKill))
1193 .addReg(RegNo: Reg1, Flags: getKillRegState(B: Reg1IsKill))
1194 .addImm(Val: (ME + 1) & 31)
1195 .addImm(Val: (MB - 1) & 31);
1196 }
1197
1198 if (ChangeReg0) {
1199 MI.getOperand(i: 0).setReg(Reg2);
1200 MI.getOperand(i: 0).setSubReg(SubReg2);
1201 }
1202 MI.getOperand(i: 2).setReg(Reg1);
1203 MI.getOperand(i: 1).setReg(Reg2);
1204 MI.getOperand(i: 2).setSubReg(SubReg1);
1205 MI.getOperand(i: 1).setSubReg(SubReg2);
1206 MI.getOperand(i: 2).setIsKill(Reg1IsKill);
1207 MI.getOperand(i: 1).setIsKill(Reg2IsKill);
1208
1209 // Swap the mask around.
1210 MI.getOperand(i: 4).setImm((ME + 1) & 31);
1211 MI.getOperand(i: 5).setImm((MB - 1) & 31);
1212 return &MI;
1213}
1214
1215bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
1216 unsigned &SrcOpIdx1,
1217 unsigned &SrcOpIdx2) const {
1218 // For VSX A-Type FMA instructions, it is the first two operands that can be
1219 // commuted, however, because the non-encoded tied input operand is listed
1220 // first, the operands to swap are actually the second and third.
1221
1222 int AltOpc = PPC::getAltVSXFMAOpcode(Opcode: MI.getOpcode());
1223 if (AltOpc == -1)
1224 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
1225
1226 // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1
1227 // and SrcOpIdx2.
1228 return fixCommutedOpIndices(ResultIdx1&: SrcOpIdx1, ResultIdx2&: SrcOpIdx2, CommutableOpIdx1: 2, CommutableOpIdx2: 3);
1229}
1230
1231void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
1232 MachineBasicBlock::iterator MI) const {
1233 // This function is used for scheduling, and the nop wanted here is the type
1234 // that terminates dispatch groups on the POWER cores.
1235 unsigned Directive = Subtarget.getCPUDirective();
1236 unsigned Opcode;
1237 switch (Directive) {
1238 default: Opcode = PPC::NOP; break;
1239 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
1240 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
1241 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
1242 // FIXME: Update when POWER9 scheduling model is ready.
1243 case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break;
1244 }
1245
1246 DebugLoc DL;
1247 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: get(Opcode));
1248}
1249
1250/// Return the noop instruction to use for a noop.
1251MCInst PPCInstrInfo::getNop() const {
1252 MCInst Nop;
1253 Nop.setOpcode(PPC::NOP);
1254 return Nop;
1255}
1256
1257// Branch analysis.
1258// Note: If the condition register is set to CTR or CTR8 then this is a
1259// BDNZ (imm == 1) or BDZ (imm == 0) branch.
1260bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
1261 MachineBasicBlock *&TBB,
1262 MachineBasicBlock *&FBB,
1263 SmallVectorImpl<MachineOperand> &Cond,
1264 bool AllowModify) const {
1265 bool isPPC64 = Subtarget.isPPC64();
1266
1267 // If the block has no terminators, it just falls into the block after it.
1268 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1269 if (I == MBB.end())
1270 return false;
1271
1272 if (!isUnpredicatedTerminator(MI: *I))
1273 return false;
1274
1275 if (AllowModify) {
1276 // If the BB ends with an unconditional branch to the fallthrough BB,
1277 // we eliminate the branch instruction.
1278 if (I->getOpcode() == PPC::B &&
1279 MBB.isLayoutSuccessor(MBB: I->getOperand(i: 0).getMBB())) {
1280 I->eraseFromParent();
1281
1282 // We update iterator after deleting the last branch.
1283 I = MBB.getLastNonDebugInstr();
1284 if (I == MBB.end() || !isUnpredicatedTerminator(MI: *I))
1285 return false;
1286 }
1287 }
1288
1289 // Get the last instruction in the block.
1290 MachineInstr &LastInst = *I;
1291
1292 // If there is only one terminator instruction, process it.
1293 if (I == MBB.begin() || !isUnpredicatedTerminator(MI: *--I)) {
1294 if (LastInst.getOpcode() == PPC::B) {
1295 if (!LastInst.getOperand(i: 0).isMBB())
1296 return true;
1297 TBB = LastInst.getOperand(i: 0).getMBB();
1298 return false;
1299 } else if (LastInst.getOpcode() == PPC::BCC) {
1300 if (!LastInst.getOperand(i: 2).isMBB())
1301 return true;
1302 // Block ends with fall-through condbranch.
1303 TBB = LastInst.getOperand(i: 2).getMBB();
1304 Cond.push_back(Elt: LastInst.getOperand(i: 0));
1305 Cond.push_back(Elt: LastInst.getOperand(i: 1));
1306 return false;
1307 } else if (LastInst.getOpcode() == PPC::BC) {
1308 if (!LastInst.getOperand(i: 1).isMBB())
1309 return true;
1310 // Block ends with fall-through condbranch.
1311 TBB = LastInst.getOperand(i: 1).getMBB();
1312 Cond.push_back(Elt: MachineOperand::CreateImm(Val: PPC::PRED_BIT_SET));
1313 Cond.push_back(Elt: LastInst.getOperand(i: 0));
1314 return false;
1315 } else if (LastInst.getOpcode() == PPC::BCn) {
1316 if (!LastInst.getOperand(i: 1).isMBB())
1317 return true;
1318 // Block ends with fall-through condbranch.
1319 TBB = LastInst.getOperand(i: 1).getMBB();
1320 Cond.push_back(Elt: MachineOperand::CreateImm(Val: PPC::PRED_BIT_UNSET));
1321 Cond.push_back(Elt: LastInst.getOperand(i: 0));
1322 return false;
1323 } else if (LastInst.getOpcode() == PPC::BDNZ8 ||
1324 LastInst.getOpcode() == PPC::BDNZ) {
1325 if (!LastInst.getOperand(i: 0).isMBB())
1326 return true;
1327 if (DisableCTRLoopAnal)
1328 return true;
1329 TBB = LastInst.getOperand(i: 0).getMBB();
1330 Cond.push_back(Elt: MachineOperand::CreateImm(Val: 1));
1331 Cond.push_back(Elt: MachineOperand::CreateReg(Reg: isPPC64 ? PPC::CTR8 : PPC::CTR,
1332 isDef: true));
1333 return false;
1334 } else if (LastInst.getOpcode() == PPC::BDZ8 ||
1335 LastInst.getOpcode() == PPC::BDZ) {
1336 if (!LastInst.getOperand(i: 0).isMBB())
1337 return true;
1338 if (DisableCTRLoopAnal)
1339 return true;
1340 TBB = LastInst.getOperand(i: 0).getMBB();
1341 Cond.push_back(Elt: MachineOperand::CreateImm(Val: 0));
1342 Cond.push_back(Elt: MachineOperand::CreateReg(Reg: isPPC64 ? PPC::CTR8 : PPC::CTR,
1343 isDef: true));
1344 return false;
1345 }
1346
1347 // Otherwise, don't know what this is.
1348 return true;
1349 }
1350
1351 // Get the instruction before it if it's a terminator.
1352 MachineInstr &SecondLastInst = *I;
1353
1354 // If there are three terminators, we don't know what sort of block this is.
1355 if (I != MBB.begin() && isUnpredicatedTerminator(MI: *--I))
1356 return true;
1357
1358 // If the block ends with PPC::B and PPC:BCC, handle it.
1359 if (SecondLastInst.getOpcode() == PPC::BCC &&
1360 LastInst.getOpcode() == PPC::B) {
1361 if (!SecondLastInst.getOperand(i: 2).isMBB() ||
1362 !LastInst.getOperand(i: 0).isMBB())
1363 return true;
1364 TBB = SecondLastInst.getOperand(i: 2).getMBB();
1365 Cond.push_back(Elt: SecondLastInst.getOperand(i: 0));
1366 Cond.push_back(Elt: SecondLastInst.getOperand(i: 1));
1367 FBB = LastInst.getOperand(i: 0).getMBB();
1368 return false;
1369 } else if (SecondLastInst.getOpcode() == PPC::BC &&
1370 LastInst.getOpcode() == PPC::B) {
1371 if (!SecondLastInst.getOperand(i: 1).isMBB() ||
1372 !LastInst.getOperand(i: 0).isMBB())
1373 return true;
1374 TBB = SecondLastInst.getOperand(i: 1).getMBB();
1375 Cond.push_back(Elt: MachineOperand::CreateImm(Val: PPC::PRED_BIT_SET));
1376 Cond.push_back(Elt: SecondLastInst.getOperand(i: 0));
1377 FBB = LastInst.getOperand(i: 0).getMBB();
1378 return false;
1379 } else if (SecondLastInst.getOpcode() == PPC::BCn &&
1380 LastInst.getOpcode() == PPC::B) {
1381 if (!SecondLastInst.getOperand(i: 1).isMBB() ||
1382 !LastInst.getOperand(i: 0).isMBB())
1383 return true;
1384 TBB = SecondLastInst.getOperand(i: 1).getMBB();
1385 Cond.push_back(Elt: MachineOperand::CreateImm(Val: PPC::PRED_BIT_UNSET));
1386 Cond.push_back(Elt: SecondLastInst.getOperand(i: 0));
1387 FBB = LastInst.getOperand(i: 0).getMBB();
1388 return false;
1389 } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 ||
1390 SecondLastInst.getOpcode() == PPC::BDNZ) &&
1391 LastInst.getOpcode() == PPC::B) {
1392 if (!SecondLastInst.getOperand(i: 0).isMBB() ||
1393 !LastInst.getOperand(i: 0).isMBB())
1394 return true;
1395 if (DisableCTRLoopAnal)
1396 return true;
1397 TBB = SecondLastInst.getOperand(i: 0).getMBB();
1398 Cond.push_back(Elt: MachineOperand::CreateImm(Val: 1));
1399 Cond.push_back(Elt: MachineOperand::CreateReg(Reg: isPPC64 ? PPC::CTR8 : PPC::CTR,
1400 isDef: true));
1401 FBB = LastInst.getOperand(i: 0).getMBB();
1402 return false;
1403 } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 ||
1404 SecondLastInst.getOpcode() == PPC::BDZ) &&
1405 LastInst.getOpcode() == PPC::B) {
1406 if (!SecondLastInst.getOperand(i: 0).isMBB() ||
1407 !LastInst.getOperand(i: 0).isMBB())
1408 return true;
1409 if (DisableCTRLoopAnal)
1410 return true;
1411 TBB = SecondLastInst.getOperand(i: 0).getMBB();
1412 Cond.push_back(Elt: MachineOperand::CreateImm(Val: 0));
1413 Cond.push_back(Elt: MachineOperand::CreateReg(Reg: isPPC64 ? PPC::CTR8 : PPC::CTR,
1414 isDef: true));
1415 FBB = LastInst.getOperand(i: 0).getMBB();
1416 return false;
1417 }
1418
1419 // If the block ends with two PPC:Bs, handle it. The second one is not
1420 // executed, so remove it.
1421 if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) {
1422 if (!SecondLastInst.getOperand(i: 0).isMBB())
1423 return true;
1424 TBB = SecondLastInst.getOperand(i: 0).getMBB();
1425 I = LastInst;
1426 if (AllowModify)
1427 I->eraseFromParent();
1428 return false;
1429 }
1430
1431 // Otherwise, can't handle this.
1432 return true;
1433}
1434
1435unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB,
1436 int *BytesRemoved) const {
1437 assert(!BytesRemoved && "code size not handled");
1438
1439 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1440 if (I == MBB.end())
1441 return 0;
1442
1443 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
1444 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1445 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1446 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
1447 return 0;
1448
1449 // Remove the branch.
1450 I->eraseFromParent();
1451
1452 I = MBB.end();
1453
1454 if (I == MBB.begin()) return 1;
1455 --I;
1456 if (I->getOpcode() != PPC::BCC &&
1457 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
1458 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
1459 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
1460 return 1;
1461
1462 // Remove the branch.
1463 I->eraseFromParent();
1464 return 2;
1465}
1466
1467unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB,
1468 MachineBasicBlock *TBB,
1469 MachineBasicBlock *FBB,
1470 ArrayRef<MachineOperand> Cond,
1471 const DebugLoc &DL,
1472 int *BytesAdded) const {
1473 // Shouldn't be a fall through.
1474 assert(TBB && "insertBranch must not be told to insert a fallthrough");
1475 assert((Cond.size() == 2 || Cond.size() == 0) &&
1476 "PPC branch conditions have two components!");
1477 assert(!BytesAdded && "code size not handled");
1478
1479 bool isPPC64 = Subtarget.isPPC64();
1480
1481 // One-way branch.
1482 if (!FBB) {
1483 if (Cond.empty()) // Unconditional branch
1484 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::B)).addMBB(MBB: TBB);
1485 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1486 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: Cond[0].getImm() ?
1487 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1488 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(MBB: TBB);
1489 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1490 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BC)).add(MO: Cond[1]).addMBB(MBB: TBB);
1491 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1492 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BCn)).add(MO: Cond[1]).addMBB(MBB: TBB);
1493 else // Conditional branch
1494 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BCC))
1495 .addImm(Val: Cond[0].getImm())
1496 .add(MO: Cond[1])
1497 .addMBB(MBB: TBB);
1498 return 1;
1499 }
1500
1501 // Two-way Conditional Branch.
1502 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1503 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: Cond[0].getImm() ?
1504 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1505 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(MBB: TBB);
1506 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
1507 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BC)).add(MO: Cond[1]).addMBB(MBB: TBB);
1508 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
1509 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BCn)).add(MO: Cond[1]).addMBB(MBB: TBB);
1510 else
1511 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::BCC))
1512 .addImm(Val: Cond[0].getImm())
1513 .add(MO: Cond[1])
1514 .addMBB(MBB: TBB);
1515 BuildMI(BB: &MBB, MIMD: DL, MCID: get(Opcode: PPC::B)).addMBB(MBB: FBB);
1516 return 2;
1517}
1518
1519// Select analysis.
1520bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1521 ArrayRef<MachineOperand> Cond,
1522 Register DstReg, Register TrueReg,
1523 Register FalseReg, int &CondCycles,
1524 int &TrueCycles, int &FalseCycles) const {
1525 if (!Subtarget.hasISEL())
1526 return false;
1527
1528 if (Cond.size() != 2)
1529 return false;
1530
1531 // If this is really a bdnz-like condition, then it cannot be turned into a
1532 // select.
1533 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
1534 return false;
1535
1536 // If the conditional branch uses a physical register, then it cannot be
1537 // turned into a select.
1538 if (Cond[1].getReg().isPhysical())
1539 return false;
1540
1541 // Check register classes.
1542 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1543 const TargetRegisterClass *RC =
1544 RI.getCommonSubClass(A: MRI.getRegClass(Reg: TrueReg), B: MRI.getRegClass(Reg: FalseReg));
1545 if (!RC)
1546 return false;
1547
1548 // isel is for regular integer GPRs only.
1549 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
1550 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
1551 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
1552 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
1553 return false;
1554
1555 // FIXME: These numbers are for the A2, how well they work for other cores is
1556 // an open question. On the A2, the isel instruction has a 2-cycle latency
1557 // but single-cycle throughput. These numbers are used in combination with
1558 // the MispredictPenalty setting from the active SchedMachineModel.
1559 CondCycles = 1;
1560 TrueCycles = 1;
1561 FalseCycles = 1;
1562
1563 return true;
1564}
1565
1566void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
1567 MachineBasicBlock::iterator MI,
1568 const DebugLoc &dl, Register DestReg,
1569 ArrayRef<MachineOperand> Cond, Register TrueReg,
1570 Register FalseReg) const {
1571 assert(Cond.size() == 2 &&
1572 "PPC branch conditions have two components!");
1573
1574 // Get the register classes.
1575 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1576 const TargetRegisterClass *RC =
1577 RI.getCommonSubClass(A: MRI.getRegClass(Reg: TrueReg), B: MRI.getRegClass(Reg: FalseReg));
1578 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
1579
1580 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
1581 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
1582 assert((Is64Bit ||
1583 PPC::GPRCRegClass.hasSubClassEq(RC) ||
1584 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
1585 "isel is for regular integer GPRs only");
1586
1587 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
1588 auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm());
1589
1590 unsigned SubIdx = 0;
1591 bool SwapOps = false;
1592 switch (SelectPred) {
1593 case PPC::PRED_EQ:
1594 case PPC::PRED_EQ_MINUS:
1595 case PPC::PRED_EQ_PLUS:
1596 SubIdx = PPC::sub_eq; SwapOps = false; break;
1597 case PPC::PRED_NE:
1598 case PPC::PRED_NE_MINUS:
1599 case PPC::PRED_NE_PLUS:
1600 SubIdx = PPC::sub_eq; SwapOps = true; break;
1601 case PPC::PRED_LT:
1602 case PPC::PRED_LT_MINUS:
1603 case PPC::PRED_LT_PLUS:
1604 SubIdx = PPC::sub_lt; SwapOps = false; break;
1605 case PPC::PRED_GE:
1606 case PPC::PRED_GE_MINUS:
1607 case PPC::PRED_GE_PLUS:
1608 SubIdx = PPC::sub_lt; SwapOps = true; break;
1609 case PPC::PRED_GT:
1610 case PPC::PRED_GT_MINUS:
1611 case PPC::PRED_GT_PLUS:
1612 SubIdx = PPC::sub_gt; SwapOps = false; break;
1613 case PPC::PRED_LE:
1614 case PPC::PRED_LE_MINUS:
1615 case PPC::PRED_LE_PLUS:
1616 SubIdx = PPC::sub_gt; SwapOps = true; break;
1617 case PPC::PRED_UN:
1618 case PPC::PRED_UN_MINUS:
1619 case PPC::PRED_UN_PLUS:
1620 SubIdx = PPC::sub_un; SwapOps = false; break;
1621 case PPC::PRED_NU:
1622 case PPC::PRED_NU_MINUS:
1623 case PPC::PRED_NU_PLUS:
1624 SubIdx = PPC::sub_un; SwapOps = true; break;
1625 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
1626 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
1627 }
1628
1629 Register FirstReg = SwapOps ? FalseReg : TrueReg,
1630 SecondReg = SwapOps ? TrueReg : FalseReg;
1631
1632 // The first input register of isel cannot be r0. If it is a member
1633 // of a register class that can be r0, then copy it first (the
1634 // register allocator should eliminate the copy).
1635 if (MRI.getRegClass(Reg: FirstReg)->contains(Reg: PPC::R0) ||
1636 MRI.getRegClass(Reg: FirstReg)->contains(Reg: PPC::X0)) {
1637 const TargetRegisterClass *FirstRC =
1638 MRI.getRegClass(Reg: FirstReg)->contains(Reg: PPC::X0) ?
1639 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
1640 Register OldFirstReg = FirstReg;
1641 FirstReg = MRI.createVirtualRegister(RegClass: FirstRC);
1642 BuildMI(BB&: MBB, I: MI, MIMD: dl, MCID: get(Opcode: TargetOpcode::COPY), DestReg: FirstReg)
1643 .addReg(RegNo: OldFirstReg);
1644 }
1645
1646 BuildMI(BB&: MBB, I: MI, MIMD: dl, MCID: get(Opcode: OpCode), DestReg)
1647 .addReg(RegNo: FirstReg)
1648 .addReg(RegNo: SecondReg)
1649 .addReg(RegNo: Cond[1].getReg(), Flags: {}, SubReg: SubIdx);
1650}
1651
1652static unsigned getCRBitValue(unsigned CRBit) {
1653 unsigned Ret = 4;
1654 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
1655 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
1656 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
1657 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
1658 Ret = 3;
1659 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
1660 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
1661 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
1662 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
1663 Ret = 2;
1664 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
1665 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
1666 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
1667 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
1668 Ret = 1;
1669 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
1670 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
1671 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
1672 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
1673 Ret = 0;
1674
1675 assert(Ret != 4 && "Invalid CR bit register");
1676 return Ret;
1677}
1678
1679void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
1680 MachineBasicBlock::iterator I,
1681 const DebugLoc &DL, Register DestReg,
1682 Register SrcReg, bool KillSrc,
1683 bool RenamableDest, bool RenamableSrc) const {
1684 // We can end up with self copies and similar things as a result of VSX copy
1685 // legalization. Promote them here.
1686 if (PPC::F8RCRegClass.contains(Reg: DestReg) &&
1687 PPC::VSRCRegClass.contains(Reg: SrcReg)) {
1688 MCRegister SuperReg =
1689 RI.getMatchingSuperReg(Reg: DestReg, SubIdx: PPC::sub_64, RC: &PPC::VSRCRegClass);
1690
1691 if (VSXSelfCopyCrash && SrcReg == SuperReg)
1692 llvm_unreachable("nop VSX copy");
1693
1694 DestReg = SuperReg;
1695 } else if (PPC::F8RCRegClass.contains(Reg: SrcReg) &&
1696 PPC::VSRCRegClass.contains(Reg: DestReg)) {
1697 MCRegister SuperReg =
1698 RI.getMatchingSuperReg(Reg: SrcReg, SubIdx: PPC::sub_64, RC: &PPC::VSRCRegClass);
1699
1700 if (VSXSelfCopyCrash && DestReg == SuperReg)
1701 llvm_unreachable("nop VSX copy");
1702
1703 SrcReg = SuperReg;
1704 }
1705
1706 // Different class register copy
1707 if (PPC::CRBITRCRegClass.contains(Reg: SrcReg) &&
1708 PPC::GPRCRegClass.contains(Reg: DestReg)) {
1709 MCRegister CRReg = getCRFromCRBit(SrcReg);
1710 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::MFOCRF), DestReg).addReg(RegNo: CRReg);
1711 getKillRegState(B: KillSrc);
1712 // Rotate the CR bit in the CR fields to be the least significant bit and
1713 // then mask with 0x1 (MB = ME = 31).
1714 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::RLWINM), DestReg)
1715 .addReg(RegNo: DestReg, Flags: RegState::Kill)
1716 .addImm(Val: RI.getEncodingValue(Reg: CRReg) * 4 + (4 - getCRBitValue(CRBit: SrcReg)))
1717 .addImm(Val: 31)
1718 .addImm(Val: 31);
1719 return;
1720 } else if (PPC::CRRCRegClass.contains(Reg: SrcReg) &&
1721 (PPC::G8RCRegClass.contains(Reg: DestReg) ||
1722 PPC::GPRCRegClass.contains(Reg: DestReg))) {
1723 bool Is64Bit = PPC::G8RCRegClass.contains(Reg: DestReg);
1724 unsigned MvCode = Is64Bit ? PPC::MFOCRF8 : PPC::MFOCRF;
1725 unsigned ShCode = Is64Bit ? PPC::RLWINM8 : PPC::RLWINM;
1726 unsigned CRNum = RI.getEncodingValue(Reg: SrcReg);
1727 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: MvCode), DestReg).addReg(RegNo: SrcReg);
1728 getKillRegState(B: KillSrc);
1729 if (CRNum == 7)
1730 return;
1731 // Shift the CR bits to make the CR field in the lowest 4 bits of GRC.
1732 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: ShCode), DestReg)
1733 .addReg(RegNo: DestReg, Flags: RegState::Kill)
1734 .addImm(Val: CRNum * 4 + 4)
1735 .addImm(Val: 28)
1736 .addImm(Val: 31);
1737 return;
1738 } else if (PPC::G8RCRegClass.contains(Reg: SrcReg) &&
1739 PPC::VSFRCRegClass.contains(Reg: DestReg)) {
1740 assert(Subtarget.hasDirectMove() &&
1741 "Subtarget doesn't support directmove, don't know how to copy.");
1742 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::MTVSRD), DestReg).addReg(RegNo: SrcReg);
1743 NumGPRtoVSRSpill++;
1744 getKillRegState(B: KillSrc);
1745 return;
1746 } else if (PPC::VSFRCRegClass.contains(Reg: SrcReg) &&
1747 PPC::G8RCRegClass.contains(Reg: DestReg)) {
1748 assert(Subtarget.hasDirectMove() &&
1749 "Subtarget doesn't support directmove, don't know how to copy.");
1750 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::MFVSRD), DestReg).addReg(RegNo: SrcReg);
1751 getKillRegState(B: KillSrc);
1752 return;
1753 } else if (PPC::SPERCRegClass.contains(Reg: SrcReg) &&
1754 PPC::GPRCRegClass.contains(Reg: DestReg)) {
1755 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::EFSCFD), DestReg).addReg(RegNo: SrcReg);
1756 getKillRegState(B: KillSrc);
1757 return;
1758 } else if (PPC::GPRCRegClass.contains(Reg: SrcReg) &&
1759 PPC::SPERCRegClass.contains(Reg: DestReg)) {
1760 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::EFDCFS), DestReg).addReg(RegNo: SrcReg);
1761 getKillRegState(B: KillSrc);
1762 return;
1763 } else if ((PPC::G8RCRegClass.contains(Reg: DestReg) ||
1764 PPC::GPRCRegClass.contains(Reg: DestReg)) &&
1765 SrcReg == PPC::CARRY) {
1766 bool Is64Bit = PPC::G8RCRegClass.contains(Reg: DestReg);
1767 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: Is64Bit ? PPC::MFSPR8 : PPC::MFSPR), DestReg)
1768 .addImm(Val: 1)
1769 .addReg(RegNo: PPC::CARRY, Flags: RegState::Implicit);
1770 return;
1771 } else if ((PPC::G8RCRegClass.contains(Reg: SrcReg) ||
1772 PPC::GPRCRegClass.contains(Reg: SrcReg)) &&
1773 DestReg == PPC::CARRY) {
1774 bool Is64Bit = PPC::G8RCRegClass.contains(Reg: SrcReg);
1775 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: Is64Bit ? PPC::MTSPR8 : PPC::MTSPR))
1776 .addImm(Val: 1)
1777 .addReg(RegNo: SrcReg)
1778 .addReg(RegNo: PPC::CARRY, Flags: RegState::ImplicitDefine);
1779 return;
1780 }
1781
1782 unsigned Opc;
1783 if (PPC::GPRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1784 Opc = PPC::OR;
1785 else if (PPC::G8RCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1786 Opc = PPC::OR8;
1787 else if (PPC::F4RCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1788 Opc = PPC::FMR;
1789 else if (PPC::CRRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1790 Opc = PPC::MCRF;
1791 else if (PPC::VRRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1792 Opc = PPC::VOR;
1793 else if (PPC::VSRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1794 // There are two different ways this can be done:
1795 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
1796 // issue in VSU pipeline 0.
1797 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
1798 // can go to either pipeline.
1799 // We'll always use xxlor here, because in practically all cases where
1800 // copies are generated, they are close enough to some use that the
1801 // lower-latency form is preferable.
1802 Opc = PPC::XXLOR;
1803 else if (PPC::VSFRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg) ||
1804 PPC::VSSRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1805 Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf;
1806 else if (Subtarget.pairedVectorMemops() &&
1807 PPC::VSRpRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg)) {
1808 if (SrcReg > PPC::VSRp15)
1809 SrcReg = PPC::V0 + (SrcReg - PPC::VSRp16) * 2;
1810 else
1811 SrcReg = PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1812 if (DestReg > PPC::VSRp15)
1813 DestReg = PPC::V0 + (DestReg - PPC::VSRp16) * 2;
1814 else
1815 DestReg = PPC::VSL0 + (DestReg - PPC::VSRp0) * 2;
1816 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXLOR), DestReg).
1817 addReg(RegNo: SrcReg).addReg(RegNo: SrcReg, Flags: getKillRegState(B: KillSrc));
1818 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXLOR), DestReg: DestReg + 1).
1819 addReg(RegNo: SrcReg + 1).addReg(RegNo: SrcReg + 1, Flags: getKillRegState(B: KillSrc));
1820 return;
1821 }
1822 else if (PPC::CRBITRCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1823 Opc = PPC::CROR;
1824 else if (PPC::SPERCRegClass.contains(Reg1: DestReg, Reg2: SrcReg))
1825 Opc = PPC::EVOR;
1826 else if ((PPC::ACCRCRegClass.contains(Reg: DestReg) ||
1827 PPC::UACCRCRegClass.contains(Reg: DestReg)) &&
1828 (PPC::ACCRCRegClass.contains(Reg: SrcReg) ||
1829 PPC::UACCRCRegClass.contains(Reg: SrcReg))) {
1830 // If primed, de-prime the source register, copy the individual registers
1831 // and prime the destination if needed. The vector subregisters are
1832 // vs[(u)acc * 4] - vs[(u)acc * 4 + 3]. If the copy is not a kill and the
1833 // source is primed, we need to re-prime it after the copy as well.
1834 PPCRegisterInfo::emitAccCopyInfo(MBB, DestReg, SrcReg);
1835 bool DestPrimed = PPC::ACCRCRegClass.contains(Reg: DestReg);
1836 bool SrcPrimed = PPC::ACCRCRegClass.contains(Reg: SrcReg);
1837 MCRegister VSLSrcReg =
1838 PPC::VSL0 + (SrcReg - (SrcPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1839 MCRegister VSLDestReg =
1840 PPC::VSL0 + (DestReg - (DestPrimed ? PPC::ACC0 : PPC::UACC0)) * 4;
1841 if (SrcPrimed)
1842 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXMFACC), DestReg: SrcReg).addReg(RegNo: SrcReg);
1843 for (unsigned Idx = 0; Idx < 4; Idx++)
1844 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXLOR), DestReg: VSLDestReg + Idx)
1845 .addReg(RegNo: VSLSrcReg + Idx)
1846 .addReg(RegNo: VSLSrcReg + Idx, Flags: getKillRegState(B: KillSrc));
1847 if (DestPrimed)
1848 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXMTACC), DestReg).addReg(RegNo: DestReg);
1849 if (SrcPrimed && !KillSrc)
1850 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::XXMTACC), DestReg: SrcReg).addReg(RegNo: SrcReg);
1851 return;
1852 } else if (PPC::G8pRCRegClass.contains(Reg: DestReg) &&
1853 PPC::G8pRCRegClass.contains(Reg: SrcReg)) {
1854 // TODO: Handle G8RC to G8pRC (and vice versa) copy.
1855 unsigned DestRegIdx = DestReg - PPC::G8p0;
1856 MCRegister DestRegSub0 = PPC::X0 + 2 * DestRegIdx;
1857 MCRegister DestRegSub1 = PPC::X0 + 2 * DestRegIdx + 1;
1858 unsigned SrcRegIdx = SrcReg - PPC::G8p0;
1859 MCRegister SrcRegSub0 = PPC::X0 + 2 * SrcRegIdx;
1860 MCRegister SrcRegSub1 = PPC::X0 + 2 * SrcRegIdx + 1;
1861 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::OR8), DestReg: DestRegSub0)
1862 .addReg(RegNo: SrcRegSub0)
1863 .addReg(RegNo: SrcRegSub0, Flags: getKillRegState(B: KillSrc));
1864 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::OR8), DestReg: DestRegSub1)
1865 .addReg(RegNo: SrcRegSub1)
1866 .addReg(RegNo: SrcRegSub1, Flags: getKillRegState(B: KillSrc));
1867 return;
1868 } else if ((PPC::WACCRCRegClass.contains(Reg: DestReg) ||
1869 PPC::WACC_HIRCRegClass.contains(Reg: DestReg)) &&
1870 (PPC::WACCRCRegClass.contains(Reg: SrcReg) ||
1871 PPC::WACC_HIRCRegClass.contains(Reg: SrcReg))) {
1872
1873 Opc = PPC::WACCRCRegClass.contains(Reg: SrcReg) ? PPC::DMXXEXTFDMR512
1874 : PPC::DMXXEXTFDMR512_HI;
1875
1876 RegScavenger RS;
1877 RS.enterBasicBlockEnd(MBB);
1878 RS.backward(I: std::next(x: I));
1879
1880 Register TmpReg1 = RS.scavengeRegisterBackwards(RC: PPC::VSRpRCRegClass, To: I,
1881 /* RestoreAfter */ false, SPAdj: 0,
1882 /* AllowSpill */ false);
1883
1884 RS.setRegUsed(Reg: TmpReg1);
1885 Register TmpReg2 = RS.scavengeRegisterBackwards(RC: PPC::VSRpRCRegClass, To: I,
1886 /* RestoreAfter */ false, SPAdj: 0,
1887 /* AllowSpill */ false);
1888
1889 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: Opc))
1890 .addReg(RegNo: TmpReg1, Flags: RegState::Define)
1891 .addReg(RegNo: TmpReg2, Flags: RegState::Define)
1892 .addReg(RegNo: SrcReg, Flags: getKillRegState(B: KillSrc));
1893
1894 Opc = PPC::WACCRCRegClass.contains(Reg: DestReg) ? PPC::DMXXINSTDMR512
1895 : PPC::DMXXINSTDMR512_HI;
1896
1897 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: Opc), DestReg)
1898 .addReg(RegNo: TmpReg1, Flags: RegState::Kill)
1899 .addReg(RegNo: TmpReg2, Flags: RegState::Kill);
1900
1901 return;
1902 } else if (PPC::DMRRCRegClass.contains(Reg: DestReg) &&
1903 PPC::DMRRCRegClass.contains(Reg: SrcReg)) {
1904
1905 BuildMI(BB&: MBB, I, MIMD: DL, MCID: get(Opcode: PPC::DMMR), DestReg)
1906 .addReg(RegNo: SrcReg, Flags: getKillRegState(B: KillSrc));
1907
1908 return;
1909
1910 } else
1911 llvm_unreachable("Impossible reg-to-reg copy");
1912
1913 const MCInstrDesc &MCID = get(Opcode: Opc);
1914 if (MCID.getNumOperands() == 3)
1915 BuildMI(BB&: MBB, I, MIMD: DL, MCID, DestReg)
1916 .addReg(RegNo: SrcReg).addReg(RegNo: SrcReg, Flags: getKillRegState(B: KillSrc));
1917 else
1918 BuildMI(BB&: MBB, I, MIMD: DL, MCID, DestReg).addReg(RegNo: SrcReg, Flags: getKillRegState(B: KillSrc));
1919}
1920
1921unsigned PPCInstrInfo::getSpillIndex(const TargetRegisterClass *RC) const {
1922 int OpcodeIndex = 0;
1923
1924 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
1925 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
1926 OpcodeIndex = SOK_Int4Spill;
1927 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
1928 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
1929 OpcodeIndex = SOK_Int8Spill;
1930 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
1931 OpcodeIndex = SOK_Float8Spill;
1932 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
1933 OpcodeIndex = SOK_Float4Spill;
1934 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) {
1935 OpcodeIndex = SOK_SPESpill;
1936 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1937 OpcodeIndex = SOK_CRSpill;
1938 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1939 OpcodeIndex = SOK_CRBitSpill;
1940 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1941 OpcodeIndex = SOK_VRVectorSpill;
1942 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1943 OpcodeIndex = SOK_VSXVectorSpill;
1944 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1945 OpcodeIndex = SOK_VectorFloat8Spill;
1946 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1947 OpcodeIndex = SOK_VectorFloat4Spill;
1948 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) {
1949 OpcodeIndex = SOK_SpillToVSR;
1950 } else if (PPC::ACCRCRegClass.hasSubClassEq(RC)) {
1951 assert(Subtarget.pairedVectorMemops() &&
1952 "Register unexpected when paired memops are disabled.");
1953 OpcodeIndex = SOK_AccumulatorSpill;
1954 } else if (PPC::UACCRCRegClass.hasSubClassEq(RC)) {
1955 assert(Subtarget.pairedVectorMemops() &&
1956 "Register unexpected when paired memops are disabled.");
1957 OpcodeIndex = SOK_UAccumulatorSpill;
1958 } else if (PPC::WACCRCRegClass.hasSubClassEq(RC)) {
1959 assert(Subtarget.pairedVectorMemops() &&
1960 "Register unexpected when paired memops are disabled.");
1961 OpcodeIndex = SOK_WAccumulatorSpill;
1962 } else if (PPC::VSRpRCRegClass.hasSubClassEq(RC)) {
1963 assert(Subtarget.pairedVectorMemops() &&
1964 "Register unexpected when paired memops are disabled.");
1965 OpcodeIndex = SOK_PairedVecSpill;
1966 } else if (PPC::G8pRCRegClass.hasSubClassEq(RC)) {
1967 OpcodeIndex = SOK_PairedG8Spill;
1968 } else if (PPC::DMRROWRCRegClass.hasSubClassEq(RC)) {
1969 llvm_unreachable("TODO: Implement spill DMRROW regclass!");
1970 } else if (PPC::DMRROWpRCRegClass.hasSubClassEq(RC)) {
1971 llvm_unreachable("TODO: Implement spill DMRROWp regclass!");
1972 } else if (PPC::DMRpRCRegClass.hasSubClassEq(RC)) {
1973 OpcodeIndex = SOK_DMRpSpill;
1974 } else if (PPC::DMRRCRegClass.hasSubClassEq(RC)) {
1975 OpcodeIndex = SOK_DMRSpill;
1976 } else {
1977 llvm_unreachable("Unknown regclass!");
1978 }
1979 return OpcodeIndex;
1980}
1981
1982unsigned
1983PPCInstrInfo::getStoreOpcodeForSpill(const TargetRegisterClass *RC) const {
1984 ArrayRef<unsigned> OpcodesForSpill = getStoreOpcodesForSpillArray();
1985 return OpcodesForSpill[getSpillIndex(RC)];
1986}
1987
1988unsigned
1989PPCInstrInfo::getLoadOpcodeForSpill(const TargetRegisterClass *RC) const {
1990 ArrayRef<unsigned> OpcodesForSpill = getLoadOpcodesForSpillArray();
1991 return OpcodesForSpill[getSpillIndex(RC)];
1992}
1993
1994void PPCInstrInfo::StoreRegToStackSlot(
1995 MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx,
1996 const TargetRegisterClass *RC,
1997 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1998 unsigned Opcode = getStoreOpcodeForSpill(RC);
1999 DebugLoc DL;
2000
2001 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2002 FuncInfo->setHasSpills();
2003
2004 NewMIs.push_back(Elt: addFrameReference(
2005 MIB: BuildMI(MF, MIMD: DL, MCID: get(Opcode)).addReg(RegNo: SrcReg, Flags: getKillRegState(B: isKill)),
2006 FI: FrameIdx));
2007
2008 if (PPC::CRRCRegClass.hasSubClassEq(RC) ||
2009 PPC::CRBITRCRegClass.hasSubClassEq(RC))
2010 FuncInfo->setSpillsCR();
2011
2012 if (isXFormMemOp(Opcode))
2013 FuncInfo->setHasNonRISpills();
2014}
2015
2016void PPCInstrInfo::storeRegToStackSlotNoUpd(
2017 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg,
2018 bool isKill, int FrameIdx, const TargetRegisterClass *RC) const {
2019 MachineFunction &MF = *MBB.getParent();
2020 SmallVector<MachineInstr *, 4> NewMIs;
2021
2022 StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs);
2023
2024 for (MachineInstr *NewMI : NewMIs)
2025 MBB.insert(I: MI, MI: NewMI);
2026
2027 const MachineFrameInfo &MFI = MF.getFrameInfo();
2028 MachineMemOperand *MMO = MF.getMachineMemOperand(
2029 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: FrameIdx),
2030 F: MachineMemOperand::MOStore, Size: MFI.getObjectSize(ObjectIdx: FrameIdx),
2031 BaseAlignment: MFI.getObjectAlign(ObjectIdx: FrameIdx));
2032 NewMIs.back()->addMemOperand(MF, MO: MMO);
2033}
2034
2035void PPCInstrInfo::storeRegToStackSlot(
2036 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
2037 bool isKill, int FrameIdx, const TargetRegisterClass *RC, Register VReg,
2038 MachineInstr::MIFlag Flags) const {
2039 // We need to avoid a situation in which the value from a VRRC register is
2040 // spilled using an Altivec instruction and reloaded into a VSRC register
2041 // using a VSX instruction. The issue with this is that the VSX
2042 // load/store instructions swap the doublewords in the vector and the Altivec
2043 // ones don't. The register classes on the spill/reload may be different if
2044 // the register is defined using an Altivec instruction and is then used by a
2045 // VSX instruction.
2046 RC = updatedRC(RC);
2047 storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC);
2048}
2049
2050void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL,
2051 unsigned DestReg, int FrameIdx,
2052 const TargetRegisterClass *RC,
2053 SmallVectorImpl<MachineInstr *> &NewMIs)
2054 const {
2055 unsigned Opcode = getLoadOpcodeForSpill(RC);
2056 NewMIs.push_back(Elt: addFrameReference(MIB: BuildMI(MF, MIMD: DL, MCID: get(Opcode), DestReg),
2057 FI: FrameIdx));
2058}
2059
2060void PPCInstrInfo::loadRegFromStackSlotNoUpd(
2061 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg,
2062 int FrameIdx, const TargetRegisterClass *RC) const {
2063 MachineFunction &MF = *MBB.getParent();
2064 SmallVector<MachineInstr*, 4> NewMIs;
2065 DebugLoc DL;
2066 if (MI != MBB.end()) DL = MI->getDebugLoc();
2067
2068 LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
2069
2070 for (MachineInstr *NewMI : NewMIs)
2071 MBB.insert(I: MI, MI: NewMI);
2072
2073 const MachineFrameInfo &MFI = MF.getFrameInfo();
2074 MachineMemOperand *MMO = MF.getMachineMemOperand(
2075 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI: FrameIdx),
2076 F: MachineMemOperand::MOLoad, Size: MFI.getObjectSize(ObjectIdx: FrameIdx),
2077 BaseAlignment: MFI.getObjectAlign(ObjectIdx: FrameIdx));
2078 NewMIs.back()->addMemOperand(MF, MO: MMO);
2079}
2080
2081void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
2082 MachineBasicBlock::iterator MI,
2083 Register DestReg, int FrameIdx,
2084 const TargetRegisterClass *RC,
2085 Register VReg, unsigned SubReg,
2086 MachineInstr::MIFlag Flags) const {
2087 // We need to avoid a situation in which the value from a VRRC register is
2088 // spilled using an Altivec instruction and reloaded into a VSRC register
2089 // using a VSX instruction. The issue with this is that the VSX
2090 // load/store instructions swap the doublewords in the vector and the Altivec
2091 // ones don't. The register classes on the spill/reload may be different if
2092 // the register is defined using an Altivec instruction and is then used by a
2093 // VSX instruction.
2094 RC = updatedRC(RC);
2095
2096 loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC);
2097}
2098
2099bool PPCInstrInfo::
2100reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
2101 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
2102 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
2103 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
2104 else
2105 // Leave the CR# the same, but invert the condition.
2106 Cond[0].setImm(PPC::InvertPredicate(Opcode: (PPC::Predicate)Cond[0].getImm()));
2107 return false;
2108}
2109
2110// For some instructions, it is legal to fold ZERO into the RA register field.
2111// This function performs that fold by replacing the operand with PPC::ZERO,
2112// it does not consider whether the load immediate zero is no longer in use.
2113bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2114 Register Reg) const {
2115 // A zero immediate should always be loaded with a single li.
2116 unsigned DefOpc = DefMI.getOpcode();
2117 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
2118 return false;
2119 if (!DefMI.getOperand(i: 1).isImm())
2120 return false;
2121 if (DefMI.getOperand(i: 1).getImm() != 0)
2122 return false;
2123
2124 // Note that we cannot here invert the arguments of an isel in order to fold
2125 // a ZERO into what is presented as the second argument. All we have here
2126 // is the condition bit, and that might come from a CR-logical bit operation.
2127
2128 const MCInstrDesc &UseMCID = UseMI.getDesc();
2129
2130 // Only fold into real machine instructions.
2131 if (UseMCID.isPseudo())
2132 return false;
2133
2134 // We need to find which of the User's operands is to be folded, that will be
2135 // the operand that matches the given register ID.
2136 unsigned UseIdx;
2137 for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx)
2138 if (UseMI.getOperand(i: UseIdx).isReg() &&
2139 UseMI.getOperand(i: UseIdx).getReg() == Reg)
2140 break;
2141
2142 assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI");
2143 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
2144
2145 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
2146 // register (which might also be specified as a pointer class kind).
2147
2148 const MCOperandInfo &UseInfo = UseMCID.operands()[UseIdx];
2149 int16_t RegClass = getOpRegClassID(OpInfo: UseInfo);
2150 if (UseInfo.RegClass != PPC::GPRC_NOR0RegClassID &&
2151 UseInfo.RegClass != PPC::G8RC_NOX0RegClassID)
2152 return false;
2153
2154 // Make sure this is not tied to an output register (or otherwise
2155 // constrained). This is true for ST?UX registers, for example, which
2156 // are tied to their output registers.
2157 if (UseInfo.Constraints != 0)
2158 return false;
2159
2160 MCRegister ZeroReg =
2161 RegClass == PPC::G8RC_NOX0RegClassID ? PPC::ZERO8 : PPC::ZERO;
2162
2163 LLVM_DEBUG(dbgs() << "Folded immediate zero for: ");
2164 LLVM_DEBUG(UseMI.dump());
2165 UseMI.getOperand(i: UseIdx).setReg(ZeroReg);
2166 LLVM_DEBUG(dbgs() << "Into: ");
2167 LLVM_DEBUG(UseMI.dump());
2168 return true;
2169}
2170
2171// Folds zero into instructions which have a load immediate zero as an operand
2172// but also recognize zero as immediate zero. If the definition of the load
2173// has no more users it is deleted.
2174bool PPCInstrInfo::foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2175 Register Reg, MachineRegisterInfo *MRI) const {
2176 bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg);
2177 if (MRI->use_nodbg_empty(RegNo: Reg))
2178 DefMI.eraseFromParent();
2179 return Changed;
2180}
2181
2182static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
2183 for (MachineInstr &MI : MBB)
2184 if (MI.definesRegister(Reg: PPC::CTR, /*TRI=*/nullptr) ||
2185 MI.definesRegister(Reg: PPC::CTR8, /*TRI=*/nullptr))
2186 return true;
2187 return false;
2188}
2189
2190// We should make sure that, if we're going to predicate both sides of a
2191// condition (a diamond), that both sides don't define the counter register. We
2192// can predicate counter-decrement-based branches, but while that predicates
2193// the branching, it does not predicate the counter decrement. If we tried to
2194// merge the triangle into one predicated block, we'd decrement the counter
2195// twice.
2196bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
2197 unsigned NumT, unsigned ExtraT,
2198 MachineBasicBlock &FMBB,
2199 unsigned NumF, unsigned ExtraF,
2200 BranchProbability Probability) const {
2201 return !(MBBDefinesCTR(MBB&: TMBB) && MBBDefinesCTR(MBB&: FMBB));
2202}
2203
2204
2205bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const {
2206 // The predicated branches are identified by their type, not really by the
2207 // explicit presence of a predicate. Furthermore, some of them can be
2208 // predicated more than once. Because if conversion won't try to predicate
2209 // any instruction which already claims to be predicated (by returning true
2210 // here), always return false. In doing so, we let isPredicable() be the
2211 // final word on whether not the instruction can be (further) predicated.
2212
2213 return false;
2214}
2215
2216bool PPCInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2217 const MachineBasicBlock *MBB,
2218 const MachineFunction &MF) const {
2219 switch (MI.getOpcode()) {
2220 default:
2221 break;
2222 // Set MFFS and MTFSF as scheduling boundary to avoid unexpected code motion
2223 // across them, since some FP operations may change content of FPSCR.
2224 // TODO: Model FPSCR in PPC instruction definitions and remove the workaround
2225 case PPC::MFFS:
2226 case PPC::MTFSF:
2227 case PPC::FENCE:
2228 return true;
2229 }
2230 return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF);
2231}
2232
2233bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI,
2234 ArrayRef<MachineOperand> Pred) const {
2235 unsigned OpC = MI.getOpcode();
2236 if (OpC == PPC::BLR || OpC == PPC::BLR8) {
2237 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2238 bool isPPC64 = Subtarget.isPPC64();
2239 MI.setDesc(get(Opcode: Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR)
2240 : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
2241 // Need add Def and Use for CTR implicit operand.
2242 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2243 .addReg(RegNo: Pred[1].getReg(), Flags: RegState::Implicit)
2244 .addReg(RegNo: Pred[1].getReg(), Flags: RegState::ImplicitDefine);
2245 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2246 MI.setDesc(get(Opcode: PPC::BCLR));
2247 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(MO: Pred[1]);
2248 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2249 MI.setDesc(get(Opcode: PPC::BCLRn));
2250 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(MO: Pred[1]);
2251 } else {
2252 MI.setDesc(get(Opcode: PPC::BCCLR));
2253 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2254 .addImm(Val: Pred[0].getImm())
2255 .add(MO: Pred[1]);
2256 }
2257
2258 return true;
2259 } else if (OpC == PPC::B) {
2260 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
2261 bool isPPC64 = Subtarget.isPPC64();
2262 MI.setDesc(get(Opcode: Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
2263 : (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
2264 // Need add Def and Use for CTR implicit operand.
2265 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2266 .addReg(RegNo: Pred[1].getReg(), Flags: RegState::Implicit)
2267 .addReg(RegNo: Pred[1].getReg(), Flags: RegState::ImplicitDefine);
2268 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2269 MachineBasicBlock *MBB = MI.getOperand(i: 0).getMBB();
2270 MI.removeOperand(OpNo: 0);
2271
2272 MI.setDesc(get(Opcode: PPC::BC));
2273 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2274 .add(MO: Pred[1])
2275 .addMBB(MBB);
2276 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2277 MachineBasicBlock *MBB = MI.getOperand(i: 0).getMBB();
2278 MI.removeOperand(OpNo: 0);
2279
2280 MI.setDesc(get(Opcode: PPC::BCn));
2281 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2282 .add(MO: Pred[1])
2283 .addMBB(MBB);
2284 } else {
2285 MachineBasicBlock *MBB = MI.getOperand(i: 0).getMBB();
2286 MI.removeOperand(OpNo: 0);
2287
2288 MI.setDesc(get(Opcode: PPC::BCC));
2289 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2290 .addImm(Val: Pred[0].getImm())
2291 .add(MO: Pred[1])
2292 .addMBB(MBB);
2293 }
2294
2295 return true;
2296 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL ||
2297 OpC == PPC::BCTRL8 || OpC == PPC::BCTRL_RM ||
2298 OpC == PPC::BCTRL8_RM) {
2299 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
2300 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
2301
2302 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8 ||
2303 OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM;
2304 bool isPPC64 = Subtarget.isPPC64();
2305
2306 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
2307 MI.setDesc(get(Opcode: isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8)
2308 : (setLR ? PPC::BCCTRL : PPC::BCCTR)));
2309 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(MO: Pred[1]);
2310 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
2311 MI.setDesc(get(Opcode: isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n)
2312 : (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
2313 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(MO: Pred[1]);
2314 } else {
2315 MI.setDesc(get(Opcode: isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8)
2316 : (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
2317 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2318 .addImm(Val: Pred[0].getImm())
2319 .add(MO: Pred[1]);
2320 }
2321
2322 // Need add Def and Use for LR implicit operand.
2323 if (setLR)
2324 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2325 .addReg(RegNo: isPPC64 ? PPC::LR8 : PPC::LR, Flags: RegState::Implicit)
2326 .addReg(RegNo: isPPC64 ? PPC::LR8 : PPC::LR, Flags: RegState::ImplicitDefine);
2327 if (OpC == PPC::BCTRL_RM || OpC == PPC::BCTRL8_RM)
2328 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
2329 .addReg(RegNo: PPC::RM, Flags: RegState::ImplicitDefine);
2330
2331 return true;
2332 }
2333
2334 return false;
2335}
2336
2337bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
2338 ArrayRef<MachineOperand> Pred2) const {
2339 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
2340 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
2341
2342 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
2343 return false;
2344 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
2345 return false;
2346
2347 // P1 can only subsume P2 if they test the same condition register.
2348 if (Pred1[1].getReg() != Pred2[1].getReg())
2349 return false;
2350
2351 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
2352 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
2353
2354 if (P1 == P2)
2355 return true;
2356
2357 // Does P1 subsume P2, e.g. GE subsumes GT.
2358 if (P1 == PPC::PRED_LE &&
2359 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
2360 return true;
2361 if (P1 == PPC::PRED_GE &&
2362 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
2363 return true;
2364
2365 return false;
2366}
2367
2368bool PPCInstrInfo::ClobbersPredicate(MachineInstr &MI,
2369 std::vector<MachineOperand> &Pred,
2370 bool SkipDead) const {
2371 // Note: At the present time, the contents of Pred from this function is
2372 // unused by IfConversion. This implementation follows ARM by pushing the
2373 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
2374 // predicate, instructions defining CTR or CTR8 are also included as
2375 // predicate-defining instructions.
2376
2377 const TargetRegisterClass *RCs[] =
2378 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
2379 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
2380
2381 bool Found = false;
2382 for (const MachineOperand &MO : MI.operands()) {
2383 for (unsigned c = 0; c < std::size(RCs) && !Found; ++c) {
2384 const TargetRegisterClass *RC = RCs[c];
2385 if (MO.isReg()) {
2386 if (MO.isDef() && RC->contains(Reg: MO.getReg())) {
2387 Pred.push_back(x: MO);
2388 Found = true;
2389 }
2390 } else if (MO.isRegMask()) {
2391 for (MCPhysReg R : *RC)
2392 if (MO.clobbersPhysReg(PhysReg: R)) {
2393 Pred.push_back(x: MO);
2394 Found = true;
2395 }
2396 }
2397 }
2398 }
2399
2400 return Found;
2401}
2402
2403bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
2404 Register &SrcReg2, int64_t &Mask,
2405 int64_t &Value) const {
2406 unsigned Opc = MI.getOpcode();
2407
2408 switch (Opc) {
2409 default: return false;
2410 case PPC::CMPWI:
2411 case PPC::CMPLWI:
2412 case PPC::CMPDI:
2413 case PPC::CMPLDI:
2414 SrcReg = MI.getOperand(i: 1).getReg();
2415 SrcReg2 = 0;
2416 Value = MI.getOperand(i: 2).getImm();
2417 Mask = 0xFFFF;
2418 return true;
2419 case PPC::CMPW:
2420 case PPC::CMPLW:
2421 case PPC::CMPD:
2422 case PPC::CMPLD:
2423 case PPC::FCMPUS:
2424 case PPC::FCMPUD:
2425 SrcReg = MI.getOperand(i: 1).getReg();
2426 SrcReg2 = MI.getOperand(i: 2).getReg();
2427 Value = 0;
2428 Mask = 0;
2429 return true;
2430 }
2431}
2432
2433bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
2434 Register SrcReg2, int64_t Mask,
2435 int64_t Value,
2436 const MachineRegisterInfo *MRI) const {
2437 if (DisableCmpOpt)
2438 return false;
2439
2440 int OpC = CmpInstr.getOpcode();
2441 Register CRReg = CmpInstr.getOperand(i: 0).getReg();
2442
2443 // FP record forms set CR1 based on the exception status bits, not a
2444 // comparison with zero.
2445 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
2446 return false;
2447
2448 // The record forms set the condition register based on a signed comparison
2449 // with zero (so says the ISA manual). This is not as straightforward as it
2450 // seems, however, because this is always a 64-bit comparison on PPC64, even
2451 // for instructions that are 32-bit in nature (like slw for example).
2452 // So, on PPC32, for unsigned comparisons, we can use the record forms only
2453 // for equality checks (as those don't depend on the sign). On PPC64,
2454 // we are restricted to equality for unsigned 64-bit comparisons and for
2455 // signed 32-bit comparisons the applicability is more restricted.
2456 bool isPPC64 = Subtarget.isPPC64();
2457 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
2458 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
2459 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
2460
2461 // Look through copies unless that gets us to a physical register.
2462 Register ActualSrc = RI.lookThruCopyLike(SrcReg, MRI);
2463 if (ActualSrc.isVirtual())
2464 SrcReg = ActualSrc;
2465
2466 // Get the unique definition of SrcReg.
2467 MachineInstr *MI = MRI->getUniqueVRegDef(Reg: SrcReg);
2468 if (!MI) return false;
2469
2470 bool equalityOnly = false;
2471 bool noSub = false;
2472 if (isPPC64) {
2473 if (is32BitSignedCompare) {
2474 // We can perform this optimization only if SrcReg is sign-extending.
2475 if (isSignExtended(Reg: SrcReg, MRI))
2476 noSub = true;
2477 else
2478 return false;
2479 } else if (is32BitUnsignedCompare) {
2480 // We can perform this optimization, equality only, if SrcReg is
2481 // zero-extending.
2482 if (isZeroExtended(Reg: SrcReg, MRI)) {
2483 noSub = true;
2484 equalityOnly = true;
2485 } else
2486 return false;
2487 } else
2488 equalityOnly = is64BitUnsignedCompare;
2489 } else
2490 equalityOnly = is32BitUnsignedCompare;
2491
2492 if (equalityOnly) {
2493 // We need to check the uses of the condition register in order to reject
2494 // non-equality comparisons.
2495 for (MachineRegisterInfo::use_instr_iterator
2496 I = MRI->use_instr_begin(RegNo: CRReg), IE = MRI->use_instr_end();
2497 I != IE; ++I) {
2498 MachineInstr *UseMI = &*I;
2499 if (UseMI->getOpcode() == PPC::BCC) {
2500 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(i: 0).getImm();
2501 unsigned PredCond = PPC::getPredicateCondition(Opcode: Pred);
2502 // We ignore hint bits when checking for non-equality comparisons.
2503 if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE)
2504 return false;
2505 } else if (UseMI->getOpcode() == PPC::ISEL ||
2506 UseMI->getOpcode() == PPC::ISEL8) {
2507 unsigned SubIdx = UseMI->getOperand(i: 3).getSubReg();
2508 if (SubIdx != PPC::sub_eq)
2509 return false;
2510 } else
2511 return false;
2512 }
2513 }
2514
2515 MachineBasicBlock::iterator I = CmpInstr;
2516
2517 // Scan forward to find the first use of the compare.
2518 for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL;
2519 ++I) {
2520 bool FoundUse = false;
2521 for (MachineRegisterInfo::use_instr_iterator
2522 J = MRI->use_instr_begin(RegNo: CRReg), JE = MRI->use_instr_end();
2523 J != JE; ++J)
2524 if (&*J == &*I) {
2525 FoundUse = true;
2526 break;
2527 }
2528
2529 if (FoundUse)
2530 break;
2531 }
2532
2533 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
2534 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
2535
2536 // There are two possible candidates which can be changed to set CR[01].
2537 // One is MI, the other is a SUB instruction.
2538 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2539 MachineInstr *Sub = nullptr;
2540 if (SrcReg2 != 0)
2541 // MI is not a candidate for CMPrr.
2542 MI = nullptr;
2543 // FIXME: Conservatively refuse to convert an instruction which isn't in the
2544 // same BB as the comparison. This is to allow the check below to avoid calls
2545 // (and other explicit clobbers); instead we should really check for these
2546 // more explicitly (in at least a few predecessors).
2547 else if (MI->getParent() != CmpInstr.getParent())
2548 return false;
2549 else if (Value != 0) {
2550 // The record-form instructions set CR bit based on signed comparison
2551 // against 0. We try to convert a compare against 1 or -1 into a compare
2552 // against 0 to exploit record-form instructions. For example, we change
2553 // the condition "greater than -1" into "greater than or equal to 0"
2554 // and "less than 1" into "less than or equal to 0".
2555
2556 // Since we optimize comparison based on a specific branch condition,
2557 // we don't optimize if condition code is used by more than once.
2558 if (equalityOnly || !MRI->hasOneUse(RegNo: CRReg))
2559 return false;
2560
2561 MachineInstr *UseMI = &*MRI->use_instr_begin(RegNo: CRReg);
2562 if (UseMI->getOpcode() != PPC::BCC)
2563 return false;
2564
2565 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(i: 0).getImm();
2566 unsigned PredCond = PPC::getPredicateCondition(Opcode: Pred);
2567 unsigned PredHint = PPC::getPredicateHint(Opcode: Pred);
2568 int16_t Immed = (int16_t)Value;
2569
2570 // When modifying the condition in the predicate, we propagate hint bits
2571 // from the original predicate to the new one.
2572 if (Immed == -1 && PredCond == PPC::PRED_GT)
2573 // We convert "greater than -1" into "greater than or equal to 0",
2574 // since we are assuming signed comparison by !equalityOnly
2575 Pred = PPC::getPredicate(Condition: PPC::PRED_GE, Hint: PredHint);
2576 else if (Immed == -1 && PredCond == PPC::PRED_LE)
2577 // We convert "less than or equal to -1" into "less than 0".
2578 Pred = PPC::getPredicate(Condition: PPC::PRED_LT, Hint: PredHint);
2579 else if (Immed == 1 && PredCond == PPC::PRED_LT)
2580 // We convert "less than 1" into "less than or equal to 0".
2581 Pred = PPC::getPredicate(Condition: PPC::PRED_LE, Hint: PredHint);
2582 else if (Immed == 1 && PredCond == PPC::PRED_GE)
2583 // We convert "greater than or equal to 1" into "greater than 0".
2584 Pred = PPC::getPredicate(Condition: PPC::PRED_GT, Hint: PredHint);
2585 else
2586 return false;
2587
2588 // Convert the comparison and its user to a compare against zero with the
2589 // appropriate predicate on the branch. Zero comparison might provide
2590 // optimization opportunities post-RA (see optimization in
2591 // PPCPreEmitPeephole.cpp).
2592 UseMI->getOperand(i: 0).setImm(Pred);
2593 CmpInstr.getOperand(i: 2).setImm(0);
2594 }
2595
2596 // Search for Sub.
2597 --I;
2598
2599 // Get ready to iterate backward from CmpInstr.
2600 MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin();
2601
2602 for (; I != E && !noSub; --I) {
2603 const MachineInstr &Instr = *I;
2604 unsigned IOpC = Instr.getOpcode();
2605
2606 if (&*I != &CmpInstr && (Instr.modifiesRegister(Reg: PPC::CR0, TRI: &RI) ||
2607 Instr.readsRegister(Reg: PPC::CR0, TRI: &RI)))
2608 // This instruction modifies or uses the record condition register after
2609 // the one we want to change. While we could do this transformation, it
2610 // would likely not be profitable. This transformation removes one
2611 // instruction, and so even forcing RA to generate one move probably
2612 // makes it unprofitable.
2613 return false;
2614
2615 // Check whether CmpInstr can be made redundant by the current instruction.
2616 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
2617 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
2618 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
2619 ((Instr.getOperand(i: 1).getReg() == SrcReg &&
2620 Instr.getOperand(i: 2).getReg() == SrcReg2) ||
2621 (Instr.getOperand(i: 1).getReg() == SrcReg2 &&
2622 Instr.getOperand(i: 2).getReg() == SrcReg))) {
2623 Sub = &*I;
2624 break;
2625 }
2626
2627 if (I == B)
2628 // The 'and' is below the comparison instruction.
2629 return false;
2630 }
2631
2632 // Return false if no candidates exist.
2633 if (!MI && !Sub)
2634 return false;
2635
2636 // The single candidate is called MI.
2637 if (!MI) MI = Sub;
2638
2639 int NewOpC = -1;
2640 int MIOpC = MI->getOpcode();
2641 if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec ||
2642 MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec)
2643 NewOpC = MIOpC;
2644 else {
2645 NewOpC = PPC::getRecordFormOpcode(Opcode: MIOpC);
2646 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(Opcode: MIOpC) != -1)
2647 NewOpC = MIOpC;
2648 }
2649
2650 // FIXME: On the non-embedded POWER architectures, only some of the record
2651 // forms are fast, and we should use only the fast ones.
2652
2653 // The defining instruction has a record form (or is already a record
2654 // form). It is possible, however, that we'll need to reverse the condition
2655 // code of the users.
2656 if (NewOpC == -1)
2657 return false;
2658
2659 // This transformation should not be performed if `nsw` is missing and is not
2660 // `equalityOnly` comparison. Since if there is overflow, sub_lt, sub_gt in
2661 // CRReg do not reflect correct order. If `equalityOnly` is true, sub_eq in
2662 // CRReg can reflect if compared values are equal, this optz is still valid.
2663 if (!equalityOnly && (NewOpC == PPC::SUBF_rec || NewOpC == PPC::SUBF8_rec) &&
2664 Sub && !Sub->getFlag(Flag: MachineInstr::NoSWrap))
2665 return false;
2666
2667 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
2668 // needs to be updated to be based on SUB. Push the condition code
2669 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
2670 // condition code of these operands will be modified.
2671 // Here, Value == 0 means we haven't converted comparison against 1 or -1 to
2672 // comparison against 0, which may modify predicate.
2673 bool ShouldSwap = false;
2674 if (Sub && Value == 0) {
2675 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(i: 1).getReg() == SrcReg2 &&
2676 Sub->getOperand(i: 2).getReg() == SrcReg;
2677
2678 // The operands to subf are the opposite of sub, so only in the fixed-point
2679 // case, invert the order.
2680 ShouldSwap = !ShouldSwap;
2681 }
2682
2683 if (ShouldSwap)
2684 for (MachineRegisterInfo::use_instr_iterator
2685 I = MRI->use_instr_begin(RegNo: CRReg), IE = MRI->use_instr_end();
2686 I != IE; ++I) {
2687 MachineInstr *UseMI = &*I;
2688 if (UseMI->getOpcode() == PPC::BCC) {
2689 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(i: 0).getImm();
2690 unsigned PredCond = PPC::getPredicateCondition(Opcode: Pred);
2691 assert((!equalityOnly ||
2692 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) &&
2693 "Invalid predicate for equality-only optimization");
2694 (void)PredCond; // To suppress warning in release build.
2695 PredsToUpdate.push_back(Elt: std::make_pair(x: &(UseMI->getOperand(i: 0)),
2696 y: PPC::getSwappedPredicate(Opcode: Pred)));
2697 } else if (UseMI->getOpcode() == PPC::ISEL ||
2698 UseMI->getOpcode() == PPC::ISEL8) {
2699 unsigned NewSubReg = UseMI->getOperand(i: 3).getSubReg();
2700 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
2701 "Invalid CR bit for equality-only optimization");
2702
2703 if (NewSubReg == PPC::sub_lt)
2704 NewSubReg = PPC::sub_gt;
2705 else if (NewSubReg == PPC::sub_gt)
2706 NewSubReg = PPC::sub_lt;
2707
2708 SubRegsToUpdate.push_back(Elt: std::make_pair(x: &(UseMI->getOperand(i: 3)),
2709 y&: NewSubReg));
2710 } else // We need to abort on a user we don't understand.
2711 return false;
2712 }
2713 assert(!(Value != 0 && ShouldSwap) &&
2714 "Non-zero immediate support and ShouldSwap"
2715 "may conflict in updating predicate");
2716
2717 // Create a new virtual register to hold the value of the CR set by the
2718 // record-form instruction. If the instruction was not previously in
2719 // record form, then set the kill flag on the CR.
2720 CmpInstr.eraseFromParent();
2721
2722 MachineBasicBlock::iterator MII = MI;
2723 BuildMI(BB&: *MI->getParent(), I: std::next(x: MII), MIMD: MI->getDebugLoc(),
2724 MCID: get(Opcode: TargetOpcode::COPY), DestReg: CRReg)
2725 .addReg(RegNo: PPC::CR0, Flags: getKillRegState(B: MIOpC != NewOpC));
2726
2727 // Even if CR0 register were dead before, it is alive now since the
2728 // instruction we just built uses it.
2729 MI->clearRegisterDeads(Reg: PPC::CR0);
2730
2731 if (MIOpC != NewOpC) {
2732 // We need to be careful here: we're replacing one instruction with
2733 // another, and we need to make sure that we get all of the right
2734 // implicit uses and defs. On the other hand, the caller may be holding
2735 // an iterator to this instruction, and so we can't delete it (this is
2736 // specifically the case if this is the instruction directly after the
2737 // compare).
2738
2739 // Rotates are expensive instructions. If we're emitting a record-form
2740 // rotate that can just be an andi/andis, we should just emit that.
2741 if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) {
2742 Register GPRRes = MI->getOperand(i: 0).getReg();
2743 int64_t SH = MI->getOperand(i: 2).getImm();
2744 int64_t MB = MI->getOperand(i: 3).getImm();
2745 int64_t ME = MI->getOperand(i: 4).getImm();
2746 // We can only do this if both the start and end of the mask are in the
2747 // same halfword.
2748 bool MBInLoHWord = MB >= 16;
2749 bool MEInLoHWord = ME >= 16;
2750 uint64_t Mask = ~0LLU;
2751
2752 if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) {
2753 Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1);
2754 // The mask value needs to shift right 16 if we're emitting andis.
2755 Mask >>= MBInLoHWord ? 0 : 16;
2756 NewOpC = MIOpC == PPC::RLWINM
2757 ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec)
2758 : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec);
2759 } else if (MRI->use_empty(RegNo: GPRRes) && (ME == 31) &&
2760 (ME - MB + 1 == SH) && (MB >= 16)) {
2761 // If we are rotating by the exact number of bits as are in the mask
2762 // and the mask is in the least significant bits of the register,
2763 // that's just an andis. (as long as the GPR result has no uses).
2764 Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1);
2765 Mask >>= 16;
2766 NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec;
2767 }
2768 // If we've set the mask, we can transform.
2769 if (Mask != ~0LLU) {
2770 MI->removeOperand(OpNo: 4);
2771 MI->removeOperand(OpNo: 3);
2772 MI->getOperand(i: 2).setImm(Mask);
2773 NumRcRotatesConvertedToRcAnd++;
2774 }
2775 } else if (MIOpC == PPC::RLDICL && MI->getOperand(i: 2).getImm() == 0) {
2776 int64_t MB = MI->getOperand(i: 3).getImm();
2777 if (MB >= 48) {
2778 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1;
2779 NewOpC = PPC::ANDI8_rec;
2780 MI->removeOperand(OpNo: 3);
2781 MI->getOperand(i: 2).setImm(Mask);
2782 NumRcRotatesConvertedToRcAnd++;
2783 }
2784 }
2785
2786 const MCInstrDesc &NewDesc = get(Opcode: NewOpC);
2787 MI->setDesc(NewDesc);
2788
2789 for (MCPhysReg ImpDef : NewDesc.implicit_defs()) {
2790 if (!MI->definesRegister(Reg: ImpDef, /*TRI=*/nullptr)) {
2791 MI->addOperand(MF&: *MI->getParent()->getParent(),
2792 Op: MachineOperand::CreateReg(Reg: ImpDef, isDef: true, isImp: true));
2793 }
2794 }
2795 for (MCPhysReg ImpUse : NewDesc.implicit_uses()) {
2796 if (!MI->readsRegister(Reg: ImpUse, /*TRI=*/nullptr)) {
2797 MI->addOperand(MF&: *MI->getParent()->getParent(),
2798 Op: MachineOperand::CreateReg(Reg: ImpUse, isDef: false, isImp: true));
2799 }
2800 }
2801 }
2802 assert(MI->definesRegister(PPC::CR0, /*TRI=*/nullptr) &&
2803 "Record-form instruction does not define cr0?");
2804
2805 // Modify the condition code of operands in OperandsToUpdate.
2806 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2807 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2808 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
2809 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
2810
2811 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
2812 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
2813
2814 return true;
2815}
2816
2817bool PPCInstrInfo::optimizeCmpPostRA(MachineInstr &CmpMI) const {
2818 MachineRegisterInfo *MRI = &CmpMI.getParent()->getParent()->getRegInfo();
2819 if (MRI->isSSA())
2820 return false;
2821
2822 Register SrcReg, SrcReg2;
2823 int64_t CmpMask, CmpValue;
2824 if (!analyzeCompare(MI: CmpMI, SrcReg, SrcReg2, Mask&: CmpMask, Value&: CmpValue))
2825 return false;
2826
2827 // Try to optimize the comparison against 0.
2828 if (CmpValue || !CmpMask || SrcReg2)
2829 return false;
2830
2831 // The record forms set the condition register based on a signed comparison
2832 // with zero (see comments in optimizeCompareInstr). Since we can't do the
2833 // equality checks in post-RA, we are more restricted on a unsigned
2834 // comparison.
2835 unsigned Opc = CmpMI.getOpcode();
2836 if (Opc == PPC::CMPLWI || Opc == PPC::CMPLDI)
2837 return false;
2838
2839 // The record forms are always based on a 64-bit comparison on PPC64
2840 // (similary, a 32-bit comparison on PPC32), while the CMPWI is a 32-bit
2841 // comparison. Since we can't do the equality checks in post-RA, we bail out
2842 // the case.
2843 if (Subtarget.isPPC64() && Opc == PPC::CMPWI)
2844 return false;
2845
2846 // CmpMI can't be deleted if it has implicit def.
2847 if (CmpMI.hasImplicitDef())
2848 return false;
2849
2850 bool SrcRegHasOtherUse = false;
2851 MachineInstr *SrcMI = getDefMIPostRA(Reg: SrcReg, MI&: CmpMI, SeenIntermediateUse&: SrcRegHasOtherUse);
2852 if (!SrcMI || !SrcMI->definesRegister(Reg: SrcReg, /*TRI=*/nullptr))
2853 return false;
2854
2855 MachineOperand RegMO = CmpMI.getOperand(i: 0);
2856 Register CRReg = RegMO.getReg();
2857 if (CRReg != PPC::CR0)
2858 return false;
2859
2860 // Make sure there is no def/use of CRReg between SrcMI and CmpMI.
2861 bool SeenUseOfCRReg = false;
2862 bool IsCRRegKilled = false;
2863 if (!isRegElgibleForForwarding(RegMO, DefMI: *SrcMI, MI: CmpMI, KillDefMI: false, IsFwdFeederRegKilled&: IsCRRegKilled,
2864 SeenIntermediateUse&: SeenUseOfCRReg) ||
2865 SrcMI->definesRegister(Reg: CRReg, /*TRI=*/nullptr) || SeenUseOfCRReg)
2866 return false;
2867
2868 int SrcMIOpc = SrcMI->getOpcode();
2869 int NewOpC = PPC::getRecordFormOpcode(Opcode: SrcMIOpc);
2870 if (NewOpC == -1)
2871 return false;
2872
2873 LLVM_DEBUG(dbgs() << "Replace Instr: ");
2874 LLVM_DEBUG(SrcMI->dump());
2875
2876 const MCInstrDesc &NewDesc = get(Opcode: NewOpC);
2877 SrcMI->setDesc(NewDesc);
2878 MachineInstrBuilder(*SrcMI->getParent()->getParent(), SrcMI)
2879 .addReg(RegNo: CRReg, Flags: RegState::ImplicitDefine);
2880 SrcMI->clearRegisterDeads(Reg: CRReg);
2881
2882 assert(SrcMI->definesRegister(PPC::CR0, /*TRI=*/nullptr) &&
2883 "Record-form instruction does not define cr0?");
2884
2885 LLVM_DEBUG(dbgs() << "with: ");
2886 LLVM_DEBUG(SrcMI->dump());
2887 LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
2888 LLVM_DEBUG(CmpMI.dump());
2889 return true;
2890}
2891
2892bool PPCInstrInfo::getMemOperandsWithOffsetWidth(
2893 const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2894 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
2895 const TargetRegisterInfo *TRI) const {
2896 const MachineOperand *BaseOp;
2897 OffsetIsScalable = false;
2898 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, Width, TRI))
2899 return false;
2900 BaseOps.push_back(Elt: BaseOp);
2901 return true;
2902}
2903
2904static bool isLdStSafeToCluster(const MachineInstr &LdSt,
2905 const TargetRegisterInfo *TRI) {
2906 // If this is a volatile load/store, don't mess with it.
2907 if (LdSt.hasOrderedMemoryRef() || LdSt.getNumExplicitOperands() != 3)
2908 return false;
2909
2910 if (LdSt.getOperand(i: 2).isFI())
2911 return true;
2912
2913 assert(LdSt.getOperand(2).isReg() && "Expected a reg operand.");
2914 // Can't cluster if the instruction modifies the base register
2915 // or it is update form. e.g. ld r2,3(r2)
2916 if (LdSt.modifiesRegister(Reg: LdSt.getOperand(i: 2).getReg(), TRI))
2917 return false;
2918
2919 return true;
2920}
2921
2922// Only cluster instruction pair that have the same opcode, and they are
2923// clusterable according to PowerPC specification.
2924static bool isClusterableLdStOpcPair(unsigned FirstOpc, unsigned SecondOpc,
2925 const PPCSubtarget &Subtarget) {
2926 switch (FirstOpc) {
2927 default:
2928 return false;
2929 case PPC::STD:
2930 case PPC::STFD:
2931 case PPC::STXSD:
2932 case PPC::DFSTOREf64:
2933 return FirstOpc == SecondOpc;
2934 // PowerPC backend has opcode STW/STW8 for instruction "stw" to deal with
2935 // 32bit and 64bit instruction selection. They are clusterable pair though
2936 // they are different opcode.
2937 case PPC::STW:
2938 case PPC::STW8:
2939 return SecondOpc == PPC::STW || SecondOpc == PPC::STW8;
2940 }
2941}
2942
2943bool PPCInstrInfo::shouldClusterMemOps(
2944 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
2945 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
2946 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
2947 unsigned NumBytes) const {
2948
2949 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
2950 const MachineOperand &BaseOp1 = *BaseOps1.front();
2951 const MachineOperand &BaseOp2 = *BaseOps2.front();
2952 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
2953 "Only base registers and frame indices are supported.");
2954
2955 // ClusterSize means the number of memory operations that will have been
2956 // clustered if this hook returns true.
2957 // Don't cluster memory op if there are already two ops clustered at least.
2958 if (ClusterSize > 2)
2959 return false;
2960
2961 // Cluster the load/store only when they have the same base
2962 // register or FI.
2963 if ((BaseOp1.isReg() != BaseOp2.isReg()) ||
2964 (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) ||
2965 (BaseOp1.isFI() && BaseOp1.getIndex() != BaseOp2.getIndex()))
2966 return false;
2967
2968 // Check if the load/store are clusterable according to the PowerPC
2969 // specification.
2970 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
2971 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
2972 unsigned FirstOpc = FirstLdSt.getOpcode();
2973 unsigned SecondOpc = SecondLdSt.getOpcode();
2974 // Cluster the load/store only when they have the same opcode, and they are
2975 // clusterable opcode according to PowerPC specification.
2976 if (!isClusterableLdStOpcPair(FirstOpc, SecondOpc, Subtarget))
2977 return false;
2978
2979 // Can't cluster load/store that have ordered or volatile memory reference.
2980 if (!isLdStSafeToCluster(LdSt: FirstLdSt, TRI: &RI) ||
2981 !isLdStSafeToCluster(LdSt: SecondLdSt, TRI: &RI))
2982 return false;
2983
2984 int64_t Offset1 = 0, Offset2 = 0;
2985 LocationSize Width1 = LocationSize::precise(Value: 0),
2986 Width2 = LocationSize::precise(Value: 0);
2987 const MachineOperand *Base1 = nullptr, *Base2 = nullptr;
2988 if (!getMemOperandWithOffsetWidth(LdSt: FirstLdSt, BaseOp&: Base1, Offset&: Offset1, Width&: Width1, TRI: &RI) ||
2989 !getMemOperandWithOffsetWidth(LdSt: SecondLdSt, BaseOp&: Base2, Offset&: Offset2, Width&: Width2, TRI: &RI) ||
2990 Width1 != Width2)
2991 return false;
2992
2993 assert(Base1 == &BaseOp1 && Base2 == &BaseOp2 &&
2994 "getMemOperandWithOffsetWidth return incorrect base op");
2995 // The caller should already have ordered FirstMemOp/SecondMemOp by offset.
2996 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
2997 return Offset1 + (int64_t)Width1.getValue() == Offset2;
2998}
2999
3000/// GetInstSize - Return the number of bytes of code the specified
3001/// instruction may be. This returns the maximum number of bytes.
3002///
3003unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
3004 unsigned Opcode = MI.getOpcode();
3005
3006 switch (Opcode) {
3007 case PPC::INLINEASM:
3008 case PPC::INLINEASM_BR: {
3009 const MachineFunction *MF = MI.getParent()->getParent();
3010 const char *AsmStr = MI.getOperand(i: 0).getSymbolName();
3011 return getInlineAsmLength(Str: AsmStr, MAI: MF->getTarget().getMCAsmInfo());
3012 }
3013 case TargetOpcode::STACKMAP: {
3014 StackMapOpers Opers(&MI);
3015 return Opers.getNumPatchBytes();
3016 }
3017 case TargetOpcode::PATCHPOINT: {
3018 PatchPointOpers Opers(&MI);
3019 return Opers.getNumPatchBytes();
3020 }
3021 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
3022 const MachineFunction *MF = MI.getParent()->getParent();
3023 const Function &F = MF->getFunction();
3024 unsigned Num = F.getFnAttributeAsParsedInteger(Kind: "patchable-function-entry");
3025 if (Num || MF->getTarget().getTargetTriple().isOSAIX() ||
3026 !MF->getTarget().getTargetTriple().isLittleEndian())
3027 return Num * 4;
3028 // Size of xray sled.
3029 return 7 * 4;
3030 }
3031 case TargetOpcode::PATCHABLE_RET: {
3032 // Size of xray sled.
3033 unsigned RetOpcode = MI.getOperand(i: 0).getImm();
3034 bool IsConditional = RetOpcode == PPC::BCCLR;
3035 return (8 + IsConditional) * 4;
3036 }
3037 case TargetOpcode::BUNDLE:
3038 return getInstBundleSize(MI);
3039 default:
3040 return get(Opcode).getSize();
3041 }
3042}
3043
3044TargetInstrInfo::InstSizeVerifyMode
3045PPCInstrInfo::getInstSizeVerifyMode(const MachineInstr &MI) const {
3046 // FIXME: The size of STACKMAP is currently over-estimated.
3047 return MI.getOpcode() == TargetOpcode::STACKMAP
3048 ? InstSizeVerifyMode::AllowOverEstimate
3049 : InstSizeVerifyMode::ExactSize;
3050}
3051
3052std::pair<unsigned, unsigned>
3053PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
3054 // PPC always uses a direct mask.
3055 return std::make_pair(x&: TF, y: 0u);
3056}
3057
3058ArrayRef<std::pair<unsigned, const char *>>
3059PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
3060 using namespace PPCII;
3061 static const std::pair<unsigned, const char *> TargetFlags[] = {
3062 {MO_PLT, "ppc-plt"},
3063 {MO_PIC_FLAG, "ppc-pic"},
3064 {MO_PCREL_FLAG, "ppc-pcrel"},
3065 {MO_GOT_FLAG, "ppc-got"},
3066 {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"},
3067 {MO_TLSGD_FLAG, "ppc-tlsgd"},
3068 {MO_TPREL_FLAG, "ppc-tprel"},
3069 {MO_TLSLDM_FLAG, "ppc-tlsldm"},
3070 {MO_TLSLD_FLAG, "ppc-tlsld"},
3071 {MO_TLSGDM_FLAG, "ppc-tlsgdm"},
3072 {MO_GOT_TLSGD_PCREL_FLAG, "ppc-got-tlsgd-pcrel"},
3073 {MO_GOT_TLSLD_PCREL_FLAG, "ppc-got-tlsld-pcrel"},
3074 {MO_GOT_TPREL_PCREL_FLAG, "ppc-got-tprel-pcrel"},
3075 {MO_LO, "ppc-lo"},
3076 {MO_HA, "ppc-ha"},
3077 {MO_TPREL_LO, "ppc-tprel-lo"},
3078 {MO_TPREL_HA, "ppc-tprel-ha"},
3079 {MO_DTPREL_LO, "ppc-dtprel-lo"},
3080 {MO_TLSLD_LO, "ppc-tlsld-lo"},
3081 {MO_TOC_LO, "ppc-toc-lo"},
3082 {MO_TLS, "ppc-tls"},
3083 {MO_PIC_HA_FLAG, "ppc-ha-pic"},
3084 {MO_PIC_LO_FLAG, "ppc-lo-pic"},
3085 {MO_TPREL_PCREL_FLAG, "ppc-tprel-pcrel"},
3086 {MO_TLS_PCREL_FLAG, "ppc-tls-pcrel"},
3087 {MO_GOT_PCREL_FLAG, "ppc-got-pcrel"},
3088 };
3089 return ArrayRef(TargetFlags);
3090}
3091
3092// Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction.
3093// The VSX versions have the advantage of a full 64-register target whereas
3094// the FP ones have the advantage of lower latency and higher throughput. So
3095// what we are after is using the faster instructions in low register pressure
3096// situations and using the larger register file in high register pressure
3097// situations.
3098bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const {
3099 unsigned UpperOpcode, LowerOpcode;
3100 switch (MI.getOpcode()) {
3101 case PPC::DFLOADf32:
3102 UpperOpcode = PPC::LXSSP;
3103 LowerOpcode = PPC::LFS;
3104 break;
3105 case PPC::DFLOADf64:
3106 UpperOpcode = PPC::LXSD;
3107 LowerOpcode = PPC::LFD;
3108 break;
3109 case PPC::DFSTOREf32:
3110 UpperOpcode = PPC::STXSSP;
3111 LowerOpcode = PPC::STFS;
3112 break;
3113 case PPC::DFSTOREf64:
3114 UpperOpcode = PPC::STXSD;
3115 LowerOpcode = PPC::STFD;
3116 break;
3117 case PPC::XFLOADf32:
3118 UpperOpcode = PPC::LXSSPX;
3119 LowerOpcode = PPC::LFSX;
3120 break;
3121 case PPC::XFLOADf64:
3122 UpperOpcode = PPC::LXSDX;
3123 LowerOpcode = PPC::LFDX;
3124 break;
3125 case PPC::XFSTOREf32:
3126 UpperOpcode = PPC::STXSSPX;
3127 LowerOpcode = PPC::STFSX;
3128 break;
3129 case PPC::XFSTOREf64:
3130 UpperOpcode = PPC::STXSDX;
3131 LowerOpcode = PPC::STFDX;
3132 break;
3133 case PPC::LIWAX:
3134 UpperOpcode = PPC::LXSIWAX;
3135 LowerOpcode = PPC::LFIWAX;
3136 break;
3137 case PPC::LIWZX:
3138 UpperOpcode = PPC::LXSIWZX;
3139 LowerOpcode = PPC::LFIWZX;
3140 break;
3141 case PPC::STIWX:
3142 UpperOpcode = PPC::STXSIWX;
3143 LowerOpcode = PPC::STFIWX;
3144 break;
3145 default:
3146 llvm_unreachable("Unknown Operation!");
3147 }
3148
3149 Register TargetReg = MI.getOperand(i: 0).getReg();
3150 unsigned Opcode;
3151 if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) ||
3152 (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31))
3153 Opcode = LowerOpcode;
3154 else
3155 Opcode = UpperOpcode;
3156 MI.setDesc(get(Opcode));
3157 return true;
3158}
3159
3160static bool isAnImmediateOperand(const MachineOperand &MO) {
3161 return MO.isCPI() || MO.isGlobal() || MO.isImm();
3162}
3163
3164bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
3165 auto &MBB = *MI.getParent();
3166 auto DL = MI.getDebugLoc();
3167
3168 switch (MI.getOpcode()) {
3169 case PPC::BUILD_UACC: {
3170 MCRegister ACC = MI.getOperand(i: 0).getReg();
3171 MCRegister UACC = MI.getOperand(i: 1).getReg();
3172 if (ACC - PPC::ACC0 != UACC - PPC::UACC0) {
3173 MCRegister SrcVSR = PPC::VSL0 + (UACC - PPC::UACC0) * 4;
3174 MCRegister DstVSR = PPC::VSL0 + (ACC - PPC::ACC0) * 4;
3175 // FIXME: This can easily be improved to look up to the top of the MBB
3176 // to see if the inputs are XXLOR's. If they are and SrcReg is killed,
3177 // we can just re-target any such XXLOR's to DstVSR + offset.
3178 for (int VecNo = 0; VecNo < 4; VecNo++)
3179 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: PPC::XXLOR), DestReg: DstVSR + VecNo)
3180 .addReg(RegNo: SrcVSR + VecNo)
3181 .addReg(RegNo: SrcVSR + VecNo);
3182 }
3183 // BUILD_UACC is expanded to 4 copies of the underlying vsx registers.
3184 // So after building the 4 copies, we can replace the BUILD_UACC instruction
3185 // with a NOP.
3186 [[fallthrough]];
3187 }
3188 case PPC::KILL_PAIR: {
3189 MI.setDesc(get(Opcode: PPC::UNENCODED_NOP));
3190 MI.removeOperand(OpNo: 1);
3191 MI.removeOperand(OpNo: 0);
3192 return true;
3193 }
3194 case TargetOpcode::LOAD_STACK_GUARD: {
3195 auto M = MBB.getParent()->getFunction().getParent();
3196 assert(
3197 (Subtarget.isTargetLinux() || M->getStackProtectorGuard() == "tls") &&
3198 "Only Linux target or tls mode are expected to contain "
3199 "LOAD_STACK_GUARD");
3200 int64_t Offset;
3201 if (M->getStackProtectorGuard() == "tls")
3202 Offset = M->getStackProtectorGuardOffset();
3203 else
3204 Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008;
3205 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
3206 MI.setDesc(get(Opcode: Subtarget.isPPC64() ? PPC::LD : PPC::LWZ));
3207 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3208 .addImm(Val: Offset)
3209 .addReg(RegNo: Reg);
3210 return true;
3211 }
3212 case PPC::PPCLdFixedAddr: {
3213 assert((Subtarget.getTargetTriple().isOSGlibc() ||
3214 Subtarget.getTargetTriple().isMusl()) &&
3215 "Only targets with Glibc expected to contain PPCLdFixedAddr");
3216 int64_t Offset = 0;
3217 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2;
3218 MI.setDesc(get(Opcode: PPC::LWZ));
3219 uint64_t FAType = MI.getOperand(i: 1).getImm();
3220#undef PPC_LNX_FEATURE
3221#undef PPC_CPU
3222#define PPC_LNX_DEFINE_OFFSETS
3223#include "llvm/TargetParser/PPCTargetParser.def"
3224 bool IsLE = Subtarget.isLittleEndian();
3225 bool Is64 = Subtarget.isPPC64();
3226 if (FAType == PPC_FAWORD_HWCAP) {
3227 if (IsLE)
3228 Offset = Is64 ? PPC_HWCAP_OFFSET_LE64 : PPC_HWCAP_OFFSET_LE32;
3229 else
3230 Offset = Is64 ? PPC_HWCAP_OFFSET_BE64 : PPC_HWCAP_OFFSET_BE32;
3231 } else if (FAType == PPC_FAWORD_HWCAP2) {
3232 if (IsLE)
3233 Offset = Is64 ? PPC_HWCAP2_OFFSET_LE64 : PPC_HWCAP2_OFFSET_LE32;
3234 else
3235 Offset = Is64 ? PPC_HWCAP2_OFFSET_BE64 : PPC_HWCAP2_OFFSET_BE32;
3236 } else if (FAType == PPC_FAWORD_CPUID) {
3237 if (IsLE)
3238 Offset = Is64 ? PPC_CPUID_OFFSET_LE64 : PPC_CPUID_OFFSET_LE32;
3239 else
3240 Offset = Is64 ? PPC_CPUID_OFFSET_BE64 : PPC_CPUID_OFFSET_BE32;
3241 }
3242 assert(Offset && "Do not know the offset for this fixed addr load");
3243 MI.removeOperand(OpNo: 1);
3244 Subtarget.getTargetMachine().setGlibcHWCAPAccess();
3245 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3246 .addImm(Val: Offset)
3247 .addReg(RegNo: Reg);
3248 return true;
3249#define PPC_TGT_PARSER_UNDEF_MACROS
3250#include "llvm/TargetParser/PPCTargetParser.def"
3251#undef PPC_TGT_PARSER_UNDEF_MACROS
3252 }
3253 case PPC::DFLOADf32:
3254 case PPC::DFLOADf64:
3255 case PPC::DFSTOREf32:
3256 case PPC::DFSTOREf64: {
3257 assert(Subtarget.hasP9Vector() &&
3258 "Invalid D-Form Pseudo-ops on Pre-P9 target.");
3259 assert(MI.getOperand(2).isReg() &&
3260 isAnImmediateOperand(MI.getOperand(1)) &&
3261 "D-form op must have register and immediate operands");
3262 return expandVSXMemPseudo(MI);
3263 }
3264 case PPC::XFLOADf32:
3265 case PPC::XFSTOREf32:
3266 case PPC::LIWAX:
3267 case PPC::LIWZX:
3268 case PPC::STIWX: {
3269 assert(Subtarget.hasP8Vector() &&
3270 "Invalid X-Form Pseudo-ops on Pre-P8 target.");
3271 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3272 "X-form op must have register and register operands");
3273 return expandVSXMemPseudo(MI);
3274 }
3275 case PPC::XFLOADf64:
3276 case PPC::XFSTOREf64: {
3277 assert(Subtarget.hasVSX() &&
3278 "Invalid X-Form Pseudo-ops on target that has no VSX.");
3279 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() &&
3280 "X-form op must have register and register operands");
3281 return expandVSXMemPseudo(MI);
3282 }
3283 case PPC::SPILLTOVSR_LD: {
3284 Register TargetReg = MI.getOperand(i: 0).getReg();
3285 if (PPC::VSFRCRegClass.contains(Reg: TargetReg)) {
3286 MI.setDesc(get(Opcode: PPC::DFLOADf64));
3287 return expandPostRAPseudo(MI);
3288 }
3289 else
3290 MI.setDesc(get(Opcode: PPC::LD));
3291 return true;
3292 }
3293 case PPC::SPILLTOVSR_ST: {
3294 Register SrcReg = MI.getOperand(i: 0).getReg();
3295 if (PPC::VSFRCRegClass.contains(Reg: SrcReg)) {
3296 NumStoreSPILLVSRRCAsVec++;
3297 MI.setDesc(get(Opcode: PPC::DFSTOREf64));
3298 return expandPostRAPseudo(MI);
3299 } else {
3300 NumStoreSPILLVSRRCAsGpr++;
3301 MI.setDesc(get(Opcode: PPC::STD));
3302 }
3303 return true;
3304 }
3305 case PPC::SPILLTOVSR_LDX: {
3306 Register TargetReg = MI.getOperand(i: 0).getReg();
3307 if (PPC::VSFRCRegClass.contains(Reg: TargetReg))
3308 MI.setDesc(get(Opcode: PPC::LXSDX));
3309 else
3310 MI.setDesc(get(Opcode: PPC::LDX));
3311 return true;
3312 }
3313 case PPC::SPILLTOVSR_STX: {
3314 Register SrcReg = MI.getOperand(i: 0).getReg();
3315 if (PPC::VSFRCRegClass.contains(Reg: SrcReg)) {
3316 NumStoreSPILLVSRRCAsVec++;
3317 MI.setDesc(get(Opcode: PPC::STXSDX));
3318 } else {
3319 NumStoreSPILLVSRRCAsGpr++;
3320 MI.setDesc(get(Opcode: PPC::STDX));
3321 }
3322 return true;
3323 }
3324
3325 // FIXME: Maybe we can expand it in 'PowerPC Expand Atomic' pass.
3326 case PPC::CFENCE:
3327 case PPC::CFENCE8: {
3328 auto Val = MI.getOperand(i: 0).getReg();
3329 unsigned CmpOp = Subtarget.isPPC64() ? PPC::CMPD : PPC::CMPW;
3330 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: CmpOp), DestReg: PPC::CR7).addReg(RegNo: Val).addReg(RegNo: Val);
3331 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: PPC::CTRL_DEP))
3332 .addImm(Val: PPC::PRED_NE_MINUS)
3333 .addReg(RegNo: PPC::CR7)
3334 .addImm(Val: 1);
3335 MI.setDesc(get(Opcode: PPC::ISYNC));
3336 MI.removeOperand(OpNo: 0);
3337 return true;
3338 }
3339 case PPC::LWAT_CSNE_PSEUDO:
3340 case PPC::LDAT_CSNE_PSEUDO:
3341 return expandAMOCSNEPseudo(MI);
3342 }
3343 return false;
3344}
3345
3346// Essentially a compile-time implementation of a compare->isel sequence.
3347// It takes two constants to compare, along with the true/false registers
3348// and the comparison type (as a subreg to a CR field) and returns one
3349// of the true/false registers, depending on the comparison results.
3350static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc,
3351 unsigned TrueReg, unsigned FalseReg,
3352 unsigned CRSubReg) {
3353 // Signed comparisons. The immediates are assumed to be sign-extended.
3354 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) {
3355 switch (CRSubReg) {
3356 default: llvm_unreachable("Unknown integer comparison type.");
3357 case PPC::sub_lt:
3358 return Imm1 < Imm2 ? TrueReg : FalseReg;
3359 case PPC::sub_gt:
3360 return Imm1 > Imm2 ? TrueReg : FalseReg;
3361 case PPC::sub_eq:
3362 return Imm1 == Imm2 ? TrueReg : FalseReg;
3363 }
3364 }
3365 // Unsigned comparisons.
3366 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) {
3367 switch (CRSubReg) {
3368 default: llvm_unreachable("Unknown integer comparison type.");
3369 case PPC::sub_lt:
3370 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg;
3371 case PPC::sub_gt:
3372 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg;
3373 case PPC::sub_eq:
3374 return Imm1 == Imm2 ? TrueReg : FalseReg;
3375 }
3376 }
3377 return PPC::NoRegister;
3378}
3379
3380void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI,
3381 unsigned OpNo,
3382 int64_t Imm) const {
3383 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG");
3384 // Replace the REG with the Immediate.
3385 Register InUseReg = MI.getOperand(i: OpNo).getReg();
3386 MI.getOperand(i: OpNo).ChangeToImmediate(ImmVal: Imm);
3387
3388 // We need to make sure that the MI didn't have any implicit use
3389 // of this REG any more. We don't call MI.implicit_operands().empty() to
3390 // return early, since MI's MCID might be changed in calling context, as a
3391 // result its number of explicit operands may be changed, thus the begin of
3392 // implicit operand is changed.
3393 int UseOpIdx = MI.findRegisterUseOperandIdx(Reg: InUseReg, TRI: &RI, isKill: false);
3394 if (UseOpIdx >= 0) {
3395 MachineOperand &MO = MI.getOperand(i: UseOpIdx);
3396 if (MO.isImplicit())
3397 // The operands must always be in the following order:
3398 // - explicit reg defs,
3399 // - other explicit operands (reg uses, immediates, etc.),
3400 // - implicit reg defs
3401 // - implicit reg uses
3402 // Therefore, removing the implicit operand won't change the explicit
3403 // operands layout.
3404 MI.removeOperand(OpNo: UseOpIdx);
3405 }
3406}
3407
3408// Replace an instruction with one that materializes a constant (and sets
3409// CR0 if the original instruction was a record-form instruction).
3410void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI,
3411 const LoadImmediateInfo &LII) const {
3412 // Remove existing operands.
3413 int OperandToKeep = LII.SetCR ? 1 : 0;
3414 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--)
3415 MI.removeOperand(OpNo: i);
3416
3417 // Replace the instruction.
3418 if (LII.SetCR) {
3419 MI.setDesc(get(Opcode: LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3420 // Set the immediate.
3421 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3422 .addImm(Val: LII.Imm).addReg(RegNo: PPC::CR0, Flags: RegState::ImplicitDefine);
3423 return;
3424 }
3425 else
3426 MI.setDesc(get(Opcode: LII.Is64Bit ? PPC::LI8 : PPC::LI));
3427
3428 // Set the immediate.
3429 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
3430 .addImm(Val: LII.Imm);
3431}
3432
3433MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI,
3434 bool &SeenIntermediateUse) const {
3435 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() &&
3436 "Should be called after register allocation.");
3437 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI;
3438 It++;
3439 SeenIntermediateUse = false;
3440 for (; It != E; ++It) {
3441 if (It->modifiesRegister(Reg, TRI: &RI))
3442 return &*It;
3443 if (It->readsRegister(Reg, TRI: &RI))
3444 SeenIntermediateUse = true;
3445 }
3446 return nullptr;
3447}
3448
3449void PPCInstrInfo::materializeImmPostRA(MachineBasicBlock &MBB,
3450 MachineBasicBlock::iterator MBBI,
3451 const DebugLoc &DL, Register Reg,
3452 int64_t Imm) const {
3453 assert(!MBB.getParent()->getRegInfo().isSSA() &&
3454 "Register should be in non-SSA form after RA");
3455 bool isPPC64 = Subtarget.isPPC64();
3456 // FIXME: Materialization here is not optimal.
3457 // For some special bit patterns we can use less instructions.
3458 // See `selectI64ImmDirect` in PPCISelDAGToDAG.cpp.
3459 if (isInt<16>(x: Imm)) {
3460 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: isPPC64 ? PPC::LI8 : PPC::LI), DestReg: Reg).addImm(Val: Imm);
3461 } else if (isInt<32>(x: Imm)) {
3462 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: isPPC64 ? PPC::LIS8 : PPC::LIS), DestReg: Reg)
3463 .addImm(Val: Imm >> 16);
3464 if (Imm & 0xFFFF)
3465 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: isPPC64 ? PPC::ORI8 : PPC::ORI), DestReg: Reg)
3466 .addReg(RegNo: Reg, Flags: RegState::Kill)
3467 .addImm(Val: Imm & 0xFFFF);
3468 } else {
3469 assert(isPPC64 && "Materializing 64-bit immediate to single register is "
3470 "only supported in PPC64");
3471 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: PPC::LIS8), DestReg: Reg).addImm(Val: Imm >> 48);
3472 if ((Imm >> 32) & 0xFFFF)
3473 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: PPC::ORI8), DestReg: Reg)
3474 .addReg(RegNo: Reg, Flags: RegState::Kill)
3475 .addImm(Val: (Imm >> 32) & 0xFFFF);
3476 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: PPC::RLDICR), DestReg: Reg)
3477 .addReg(RegNo: Reg, Flags: RegState::Kill)
3478 .addImm(Val: 32)
3479 .addImm(Val: 31);
3480 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: PPC::ORIS8), DestReg: Reg)
3481 .addReg(RegNo: Reg, Flags: RegState::Kill)
3482 .addImm(Val: (Imm >> 16) & 0xFFFF);
3483 if (Imm & 0xFFFF)
3484 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: get(Opcode: PPC::ORI8), DestReg: Reg)
3485 .addReg(RegNo: Reg, Flags: RegState::Kill)
3486 .addImm(Val: Imm & 0xFFFF);
3487 }
3488}
3489
3490MachineInstr *PPCInstrInfo::getForwardingDefMI(
3491 MachineInstr &MI,
3492 unsigned &OpNoForForwarding,
3493 bool &SeenIntermediateUse) const {
3494 OpNoForForwarding = ~0U;
3495 MachineInstr *DefMI = nullptr;
3496 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3497 // If we're in SSA, get the defs through the MRI. Otherwise, only look
3498 // within the basic block to see if the register is defined using an
3499 // LI/LI8/ADDI/ADDI8.
3500 if (MRI->isSSA()) {
3501 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3502 if (!MI.getOperand(i).isReg())
3503 continue;
3504 Register Reg = MI.getOperand(i).getReg();
3505 if (!Reg.isVirtual())
3506 continue;
3507 Register TrueReg = RI.lookThruCopyLike(SrcReg: Reg, MRI);
3508 if (TrueReg.isVirtual()) {
3509 MachineInstr *DefMIForTrueReg = MRI->getVRegDef(Reg: TrueReg);
3510 if (!DefMIForTrueReg)
3511 continue;
3512 if (DefMIForTrueReg->getOpcode() == PPC::LI ||
3513 DefMIForTrueReg->getOpcode() == PPC::LI8 ||
3514 DefMIForTrueReg->getOpcode() == PPC::ADDI ||
3515 DefMIForTrueReg->getOpcode() == PPC::ADDI8) {
3516 OpNoForForwarding = i;
3517 DefMI = DefMIForTrueReg;
3518 // The ADDI and LI operand maybe exist in one instruction at same
3519 // time. we prefer to fold LI operand as LI only has one Imm operand
3520 // and is more possible to be converted. So if current DefMI is
3521 // ADDI/ADDI8, we continue to find possible LI/LI8.
3522 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8)
3523 break;
3524 }
3525 }
3526 }
3527 } else {
3528 // Looking back through the definition for each operand could be expensive,
3529 // so exit early if this isn't an instruction that either has an immediate
3530 // form or is already an immediate form that we can handle.
3531 ImmInstrInfo III;
3532 unsigned Opc = MI.getOpcode();
3533 bool ConvertibleImmForm =
3534 Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI ||
3535 Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 ||
3536 Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI ||
3537 Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec ||
3538 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 ||
3539 Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 ||
3540 Opc == PPC::RLWINM8_rec;
3541 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(i: 0).isReg())
3542 ? PPC::isVFRegister(Reg: MI.getOperand(i: 0).getReg())
3543 : false;
3544 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, PostRA: true))
3545 return nullptr;
3546
3547 // Don't convert or %X, %Y, %Y since that's just a register move.
3548 if ((Opc == PPC::OR || Opc == PPC::OR8) &&
3549 MI.getOperand(i: 1).getReg() == MI.getOperand(i: 2).getReg())
3550 return nullptr;
3551 for (int i = 1, e = MI.getNumOperands(); i < e; i++) {
3552 MachineOperand &MO = MI.getOperand(i);
3553 SeenIntermediateUse = false;
3554 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) {
3555 Register Reg = MI.getOperand(i).getReg();
3556 // If we see another use of this reg between the def and the MI,
3557 // we want to flag it so the def isn't deleted.
3558 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse);
3559 if (DefMI) {
3560 // Is this register defined by some form of add-immediate (including
3561 // load-immediate) within this basic block?
3562 switch (DefMI->getOpcode()) {
3563 default:
3564 break;
3565 case PPC::LI:
3566 case PPC::LI8:
3567 case PPC::ADDItocL8:
3568 case PPC::ADDI:
3569 case PPC::ADDI8:
3570 OpNoForForwarding = i;
3571 return DefMI;
3572 }
3573 }
3574 }
3575 }
3576 }
3577 return OpNoForForwarding == ~0U ? nullptr : DefMI;
3578}
3579
3580unsigned PPCInstrInfo::getSpillTarget() const {
3581 // With P10, we may need to spill paired vector registers or accumulator
3582 // registers. MMA implies paired vectors, so we can just check that.
3583 bool IsP10Variant = Subtarget.isISA3_1() || Subtarget.pairedVectorMemops();
3584 // P11 uses the P10 target.
3585 return Subtarget.isISAFuture() ? 3 : IsP10Variant ?
3586 2 : Subtarget.hasP9Vector() ?
3587 1 : 0;
3588}
3589
3590ArrayRef<unsigned> PPCInstrInfo::getStoreOpcodesForSpillArray() const {
3591 return {StoreSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3592}
3593
3594ArrayRef<unsigned> PPCInstrInfo::getLoadOpcodesForSpillArray() const {
3595 return {LoadSpillOpcodesArray[getSpillTarget()], SOK_LastOpcodeSpill};
3596}
3597
3598// This opt tries to convert the following imm form to an index form to save an
3599// add for stack variables.
3600// Return false if no such pattern found.
3601//
3602// ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3603// ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg
3604// Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed)
3605//
3606// can be converted to:
3607//
3608// new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm)
3609// Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed)
3610//
3611// In order to eliminate ADD instr, make sure that:
3612// 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in
3613// new ADDI instr and ADDI can only take int16 Imm.
3614// 2: ToBeChangedReg must be killed in ADD instr and there is no other use
3615// between ADDI and ADD instr since its original def in ADDI will be changed
3616// in new ADDI instr. And also there should be no new def for it between
3617// ADD and Imm instr as ToBeChangedReg will be used in Index instr.
3618// 3: ToBeDeletedReg must be killed in Imm instr and there is no other use
3619// between ADD and Imm instr since ADD instr will be eliminated.
3620// 4: ScaleReg must not be redefined between ADD and Imm instr since it will be
3621// moved to Index instr.
3622bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const {
3623 MachineFunction *MF = MI.getParent()->getParent();
3624 MachineRegisterInfo *MRI = &MF->getRegInfo();
3625 bool PostRA = !MRI->isSSA();
3626 // Do this opt after PEI which is after RA. The reason is stack slot expansion
3627 // in PEI may expose such opportunities since in PEI, stack slot offsets to
3628 // frame base(OffsetAddi) are determined.
3629 if (!PostRA)
3630 return false;
3631 unsigned ToBeDeletedReg = 0;
3632 int64_t OffsetImm = 0;
3633 unsigned XFormOpcode = 0;
3634 ImmInstrInfo III;
3635
3636 // Check if Imm instr meets requirement.
3637 if (!isImmInstrEligibleForFolding(MI, BaseReg&: ToBeDeletedReg, XFormOpcode, OffsetOfImmInstr&: OffsetImm,
3638 III))
3639 return false;
3640
3641 bool OtherIntermediateUse = false;
3642 MachineInstr *ADDMI = getDefMIPostRA(Reg: ToBeDeletedReg, MI, SeenIntermediateUse&: OtherIntermediateUse);
3643
3644 // Exit if there is other use between ADD and Imm instr or no def found.
3645 if (OtherIntermediateUse || !ADDMI)
3646 return false;
3647
3648 // Check if ADD instr meets requirement.
3649 if (!isADDInstrEligibleForFolding(ADDMI&: *ADDMI))
3650 return false;
3651
3652 unsigned ScaleRegIdx = 0;
3653 int64_t OffsetAddi = 0;
3654 MachineInstr *ADDIMI = nullptr;
3655
3656 // Check if there is a valid ToBeChangedReg in ADDMI.
3657 // 1: It must be killed.
3658 // 2: Its definition must be a valid ADDIMI.
3659 // 3: It must satify int16 offset requirement.
3660 if (isValidToBeChangedReg(ADDMI, Index: 1, ADDIMI, OffsetAddi, OffsetImm))
3661 ScaleRegIdx = 2;
3662 else if (isValidToBeChangedReg(ADDMI, Index: 2, ADDIMI, OffsetAddi, OffsetImm))
3663 ScaleRegIdx = 1;
3664 else
3665 return false;
3666
3667 assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg.");
3668 Register ToBeChangedReg = ADDIMI->getOperand(i: 0).getReg();
3669 Register ScaleReg = ADDMI->getOperand(i: ScaleRegIdx).getReg();
3670 auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start,
3671 MachineBasicBlock::iterator End) {
3672 for (auto It = ++Start; It != End; It++)
3673 if (It->modifiesRegister(Reg, TRI: &getRegisterInfo()))
3674 return true;
3675 return false;
3676 };
3677
3678 // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is
3679 // treated as special zero when ScaleReg is R0/X0 register.
3680 if (III.ZeroIsSpecialOrig == III.ImmOpNo &&
3681 (ScaleReg == PPC::R0 || ScaleReg == PPC::X0))
3682 return false;
3683
3684 // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr
3685 // and Imm Instr.
3686 if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI))
3687 return false;
3688
3689 // Now start to do the transformation.
3690 LLVM_DEBUG(dbgs() << "Replace instruction: "
3691 << "\n");
3692 LLVM_DEBUG(ADDIMI->dump());
3693 LLVM_DEBUG(ADDMI->dump());
3694 LLVM_DEBUG(MI.dump());
3695 LLVM_DEBUG(dbgs() << "with: "
3696 << "\n");
3697
3698 // Update ADDI instr.
3699 ADDIMI->getOperand(i: 2).setImm(OffsetAddi + OffsetImm);
3700
3701 // Update Imm instr.
3702 MI.setDesc(get(Opcode: XFormOpcode));
3703 MI.getOperand(i: III.ImmOpNo)
3704 .ChangeToRegister(Reg: ScaleReg, isDef: false, isImp: false,
3705 isKill: ADDMI->getOperand(i: ScaleRegIdx).isKill());
3706
3707 MI.getOperand(i: III.OpNoForForwarding)
3708 .ChangeToRegister(Reg: ToBeChangedReg, isDef: false, isImp: false, isKill: true);
3709
3710 // Eliminate ADD instr.
3711 ADDMI->eraseFromParent();
3712
3713 LLVM_DEBUG(ADDIMI->dump());
3714 LLVM_DEBUG(MI.dump());
3715
3716 return true;
3717}
3718
3719bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI,
3720 int64_t &Imm) const {
3721 unsigned Opc = ADDIMI.getOpcode();
3722
3723 // Exit if the instruction is not ADDI.
3724 if (Opc != PPC::ADDI && Opc != PPC::ADDI8)
3725 return false;
3726
3727 // The operand may not necessarily be an immediate - it could be a relocation.
3728 if (!ADDIMI.getOperand(i: 2).isImm())
3729 return false;
3730
3731 Imm = ADDIMI.getOperand(i: 2).getImm();
3732
3733 return true;
3734}
3735
3736bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const {
3737 unsigned Opc = ADDMI.getOpcode();
3738
3739 // Exit if the instruction is not ADD.
3740 return Opc == PPC::ADD4 || Opc == PPC::ADD8;
3741}
3742
3743bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI,
3744 unsigned &ToBeDeletedReg,
3745 unsigned &XFormOpcode,
3746 int64_t &OffsetImm,
3747 ImmInstrInfo &III) const {
3748 // Only handle load/store.
3749 if (!MI.mayLoadOrStore())
3750 return false;
3751
3752 unsigned Opc = MI.getOpcode();
3753
3754 XFormOpcode = RI.getMappedIdxOpcForImmOpc(ImmOpcode: Opc);
3755
3756 // Exit if instruction has no index form.
3757 if (XFormOpcode == PPC::INSTRUCTION_LIST_END)
3758 return false;
3759
3760 // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap.
3761 if (!instrHasImmForm(Opc: XFormOpcode,
3762 IsVFReg: PPC::isVFRegister(Reg: MI.getOperand(i: 0).getReg()), III, PostRA: true))
3763 return false;
3764
3765 if (!III.IsSummingOperands)
3766 return false;
3767
3768 MachineOperand ImmOperand = MI.getOperand(i: III.ImmOpNo);
3769 MachineOperand RegOperand = MI.getOperand(i: III.OpNoForForwarding);
3770 // Only support imm operands, not relocation slots or others.
3771 if (!ImmOperand.isImm())
3772 return false;
3773
3774 assert(RegOperand.isReg() && "Instruction format is not right");
3775
3776 // There are other use for ToBeDeletedReg after Imm instr, can not delete it.
3777 if (!RegOperand.isKill())
3778 return false;
3779
3780 ToBeDeletedReg = RegOperand.getReg();
3781 OffsetImm = ImmOperand.getImm();
3782
3783 return true;
3784}
3785
3786bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index,
3787 MachineInstr *&ADDIMI,
3788 int64_t &OffsetAddi,
3789 int64_t OffsetImm) const {
3790 assert((Index == 1 || Index == 2) && "Invalid operand index for add.");
3791 MachineOperand &MO = ADDMI->getOperand(i: Index);
3792
3793 if (!MO.isKill())
3794 return false;
3795
3796 bool OtherIntermediateUse = false;
3797
3798 ADDIMI = getDefMIPostRA(Reg: MO.getReg(), MI&: *ADDMI, SeenIntermediateUse&: OtherIntermediateUse);
3799 // Currently handle only one "add + Imminstr" pair case, exit if other
3800 // intermediate use for ToBeChangedReg found.
3801 // TODO: handle the cases where there are other "add + Imminstr" pairs
3802 // with same offset in Imminstr which is like:
3803 //
3804 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi
3805 // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1
3806 // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed)
3807 // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2
3808 // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed)
3809 //
3810 // can be converted to:
3811 //
3812 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg,
3813 // (OffsetAddi + OffsetImm)
3814 // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg
3815 // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed)
3816
3817 if (OtherIntermediateUse || !ADDIMI)
3818 return false;
3819 // Check if ADDI instr meets requirement.
3820 if (!isADDIInstrEligibleForFolding(ADDIMI&: *ADDIMI, Imm&: OffsetAddi))
3821 return false;
3822
3823 if (isInt<16>(x: OffsetAddi + OffsetImm))
3824 return true;
3825 return false;
3826}
3827
3828// If this instruction has an immediate form and one of its operands is a
3829// result of a load-immediate or an add-immediate, convert it to
3830// the immediate form if the constant is in range.
3831bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI,
3832 SmallSet<Register, 4> &RegsToUpdate,
3833 MachineInstr **KilledDef) const {
3834 MachineFunction *MF = MI.getParent()->getParent();
3835 MachineRegisterInfo *MRI = &MF->getRegInfo();
3836 bool PostRA = !MRI->isSSA();
3837 bool SeenIntermediateUse = true;
3838 unsigned ForwardingOperand = ~0U;
3839 MachineInstr *DefMI = getForwardingDefMI(MI, OpNoForForwarding&: ForwardingOperand,
3840 SeenIntermediateUse);
3841 if (!DefMI)
3842 return false;
3843 assert(ForwardingOperand < MI.getNumOperands() &&
3844 "The forwarding operand needs to be valid at this point");
3845 bool IsForwardingOperandKilled = MI.getOperand(i: ForwardingOperand).isKill();
3846 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled;
3847 if (KilledDef && KillFwdDefMI)
3848 *KilledDef = DefMI;
3849
3850 // Conservatively add defs from DefMI and defs/uses from MI to the set of
3851 // registers that need their kill flags updated.
3852 for (const MachineOperand &MO : DefMI->operands())
3853 if (MO.isReg() && MO.isDef())
3854 RegsToUpdate.insert(V: MO.getReg());
3855 for (const MachineOperand &MO : MI.operands())
3856 if (MO.isReg())
3857 RegsToUpdate.insert(V: MO.getReg());
3858
3859 // If this is a imm instruction and its register operands is produced by ADDI,
3860 // put the imm into imm inst directly.
3861 if (RI.getMappedIdxOpcForImmOpc(ImmOpcode: MI.getOpcode()) !=
3862 PPC::INSTRUCTION_LIST_END &&
3863 transformToNewImmFormFedByAdd(MI, DefMI&: *DefMI, OpNoForForwarding: ForwardingOperand))
3864 return true;
3865
3866 ImmInstrInfo III;
3867 bool IsVFReg = MI.getOperand(i: 0).isReg() &&
3868 MI.getOperand(i: 0).getReg().isPhysical() &&
3869 PPC::isVFRegister(Reg: MI.getOperand(i: 0).getReg());
3870 bool HasImmForm = instrHasImmForm(Opc: MI.getOpcode(), IsVFReg, III, PostRA);
3871 // If this is a reg+reg instruction that has a reg+imm form,
3872 // and one of the operands is produced by an add-immediate,
3873 // try to convert it.
3874 if (HasImmForm &&
3875 transformToImmFormFedByAdd(MI, III, ConstantOpNo: ForwardingOperand, DefMI&: *DefMI,
3876 KillDefMI: KillFwdDefMI))
3877 return true;
3878
3879 // If this is a reg+reg instruction that has a reg+imm form,
3880 // and one of the operands is produced by LI, convert it now.
3881 if (HasImmForm &&
3882 transformToImmFormFedByLI(MI, III, ConstantOpNo: ForwardingOperand, DefMI&: *DefMI))
3883 return true;
3884
3885 // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI
3886 // can be simpified to LI.
3887 if (!HasImmForm &&
3888 simplifyToLI(MI, DefMI&: *DefMI, OpNoForForwarding: ForwardingOperand, KilledDef, RegsToUpdate: &RegsToUpdate))
3889 return true;
3890
3891 return false;
3892}
3893
3894bool PPCInstrInfo::combineRLWINM(MachineInstr &MI,
3895 MachineInstr **ToErase) const {
3896 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
3897 Register FoldingReg = MI.getOperand(i: 1).getReg();
3898 if (!FoldingReg.isVirtual())
3899 return false;
3900 MachineInstr *SrcMI = MRI->getVRegDef(Reg: FoldingReg);
3901 if (!SrcMI)
3902 return false;
3903 if (SrcMI->getOpcode() != PPC::RLWINM &&
3904 SrcMI->getOpcode() != PPC::RLWINM_rec &&
3905 SrcMI->getOpcode() != PPC::RLWINM8 &&
3906 SrcMI->getOpcode() != PPC::RLWINM8_rec)
3907 return false;
3908 assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() &&
3909 MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() &&
3910 SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) &&
3911 "Invalid PPC::RLWINM Instruction!");
3912 uint64_t SHSrc = SrcMI->getOperand(i: 2).getImm();
3913 uint64_t SHMI = MI.getOperand(i: 2).getImm();
3914 uint64_t MBSrc = SrcMI->getOperand(i: 3).getImm();
3915 uint64_t MBMI = MI.getOperand(i: 3).getImm();
3916 uint64_t MESrc = SrcMI->getOperand(i: 4).getImm();
3917 uint64_t MEMI = MI.getOperand(i: 4).getImm();
3918
3919 assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) &&
3920 "Invalid PPC::RLWINM Instruction!");
3921 // If MBMI is bigger than MEMI, we always can not get run of ones.
3922 // RotatedSrcMask non-wrap:
3923 // 0........31|32........63
3924 // RotatedSrcMask: B---E B---E
3925 // MaskMI: -----------|--E B------
3926 // Result: ----- --- (Bad candidate)
3927 //
3928 // RotatedSrcMask wrap:
3929 // 0........31|32........63
3930 // RotatedSrcMask: --E B----|--E B----
3931 // MaskMI: -----------|--E B------
3932 // Result: --- -----|--- ----- (Bad candidate)
3933 //
3934 // One special case is RotatedSrcMask is a full set mask.
3935 // RotatedSrcMask full:
3936 // 0........31|32........63
3937 // RotatedSrcMask: ------EB---|-------EB---
3938 // MaskMI: -----------|--E B------
3939 // Result: -----------|--- ------- (Good candidate)
3940
3941 // Mark special case.
3942 bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31);
3943
3944 // For other MBMI > MEMI cases, just return.
3945 if ((MBMI > MEMI) && !SrcMaskFull)
3946 return false;
3947
3948 // Handle MBMI <= MEMI cases.
3949 APInt MaskMI = APInt::getBitsSetWithWrap(numBits: 32, loBit: 32 - MEMI - 1, hiBit: 32 - MBMI);
3950 // In MI, we only need low 32 bits of SrcMI, just consider about low 32
3951 // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0,
3952 // while in PowerPC ISA, lowerest bit is at index 63.
3953 APInt MaskSrc = APInt::getBitsSetWithWrap(numBits: 32, loBit: 32 - MESrc - 1, hiBit: 32 - MBSrc);
3954
3955 APInt RotatedSrcMask = MaskSrc.rotl(rotateAmt: SHMI);
3956 APInt FinalMask = RotatedSrcMask & MaskMI;
3957 uint32_t NewMB, NewME;
3958 bool Simplified = false;
3959
3960 // If final mask is 0, MI result should be 0 too.
3961 if (FinalMask.isZero()) {
3962 bool Is64Bit =
3963 (MI.getOpcode() == PPC::RLWINM8 || MI.getOpcode() == PPC::RLWINM8_rec);
3964 Simplified = true;
3965 LLVM_DEBUG(dbgs() << "Replace Instr: ");
3966 LLVM_DEBUG(MI.dump());
3967
3968 if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) {
3969 // Replace MI with "LI 0"
3970 MI.removeOperand(OpNo: 4);
3971 MI.removeOperand(OpNo: 3);
3972 MI.removeOperand(OpNo: 2);
3973 MI.getOperand(i: 1).ChangeToImmediate(ImmVal: 0);
3974 MI.setDesc(get(Opcode: Is64Bit ? PPC::LI8 : PPC::LI));
3975 } else {
3976 // Replace MI with "ANDI_rec reg, 0"
3977 MI.removeOperand(OpNo: 4);
3978 MI.removeOperand(OpNo: 3);
3979 MI.getOperand(i: 2).setImm(0);
3980 MI.setDesc(get(Opcode: Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec));
3981 MI.getOperand(i: 1).setReg(SrcMI->getOperand(i: 1).getReg());
3982 if (SrcMI->getOperand(i: 1).isKill()) {
3983 MI.getOperand(i: 1).setIsKill(true);
3984 SrcMI->getOperand(i: 1).setIsKill(false);
3985 } else
3986 // About to replace MI.getOperand(1), clear its kill flag.
3987 MI.getOperand(i: 1).setIsKill(false);
3988 }
3989
3990 LLVM_DEBUG(dbgs() << "With: ");
3991 LLVM_DEBUG(MI.dump());
3992
3993 } else if ((isRunOfOnes(Val: (unsigned)(FinalMask.getZExtValue()), MB&: NewMB, ME&: NewME) &&
3994 NewMB <= NewME) ||
3995 SrcMaskFull) {
3996 // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger
3997 // than NewME. Otherwise we get a 64 bit value after folding, but MI
3998 // return a 32 bit value.
3999 Simplified = true;
4000 LLVM_DEBUG(dbgs() << "Converting Instr: ");
4001 LLVM_DEBUG(MI.dump());
4002
4003 uint16_t NewSH = (SHSrc + SHMI) % 32;
4004 MI.getOperand(i: 2).setImm(NewSH);
4005 // If SrcMI mask is full, no need to update MBMI and MEMI.
4006 if (!SrcMaskFull) {
4007 MI.getOperand(i: 3).setImm(NewMB);
4008 MI.getOperand(i: 4).setImm(NewME);
4009 }
4010 MI.getOperand(i: 1).setReg(SrcMI->getOperand(i: 1).getReg());
4011 if (SrcMI->getOperand(i: 1).isKill()) {
4012 MI.getOperand(i: 1).setIsKill(true);
4013 SrcMI->getOperand(i: 1).setIsKill(false);
4014 } else
4015 // About to replace MI.getOperand(1), clear its kill flag.
4016 MI.getOperand(i: 1).setIsKill(false);
4017
4018 LLVM_DEBUG(dbgs() << "To: ");
4019 LLVM_DEBUG(MI.dump());
4020 }
4021 if (Simplified & MRI->use_nodbg_empty(RegNo: FoldingReg) &&
4022 !SrcMI->hasImplicitDef()) {
4023 // If FoldingReg has no non-debug use and it has no implicit def (it
4024 // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI.
4025 // Otherwise keep it.
4026 *ToErase = SrcMI;
4027 LLVM_DEBUG(dbgs() << "Delete dead instruction: ");
4028 LLVM_DEBUG(SrcMI->dump());
4029 }
4030 return Simplified;
4031}
4032
4033bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg,
4034 ImmInstrInfo &III, bool PostRA) const {
4035 // The vast majority of the instructions would need their operand 2 replaced
4036 // with an immediate when switching to the reg+imm form. A marked exception
4037 // are the update form loads/stores for which a constant operand 2 would need
4038 // to turn into a displacement and move operand 1 to the operand 2 position.
4039 III.ImmOpNo = 2;
4040 III.OpNoForForwarding = 2;
4041 III.ImmWidth = 16;
4042 III.ImmMustBeMultipleOf = 1;
4043 III.TruncateImmTo = 0;
4044 III.IsSummingOperands = false;
4045 switch (Opc) {
4046 default: return false;
4047 case PPC::ADD4:
4048 case PPC::ADD8:
4049 III.SignedImm = true;
4050 III.ZeroIsSpecialOrig = 0;
4051 III.ZeroIsSpecialNew = 1;
4052 III.IsCommutative = true;
4053 III.IsSummingOperands = true;
4054 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8;
4055 break;
4056 case PPC::ADDC:
4057 case PPC::ADDC8:
4058 III.SignedImm = true;
4059 III.ZeroIsSpecialOrig = 0;
4060 III.ZeroIsSpecialNew = 0;
4061 III.IsCommutative = true;
4062 III.IsSummingOperands = true;
4063 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8;
4064 break;
4065 case PPC::ADDC_rec:
4066 III.SignedImm = true;
4067 III.ZeroIsSpecialOrig = 0;
4068 III.ZeroIsSpecialNew = 0;
4069 III.IsCommutative = true;
4070 III.IsSummingOperands = true;
4071 III.ImmOpcode = PPC::ADDIC_rec;
4072 break;
4073 case PPC::SUBFC:
4074 case PPC::SUBFC8:
4075 III.SignedImm = true;
4076 III.ZeroIsSpecialOrig = 0;
4077 III.ZeroIsSpecialNew = 0;
4078 III.IsCommutative = false;
4079 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8;
4080 break;
4081 case PPC::CMPW:
4082 case PPC::CMPD:
4083 III.SignedImm = true;
4084 III.ZeroIsSpecialOrig = 0;
4085 III.ZeroIsSpecialNew = 0;
4086 III.IsCommutative = false;
4087 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI;
4088 break;
4089 case PPC::CMPLW:
4090 case PPC::CMPLD:
4091 III.SignedImm = false;
4092 III.ZeroIsSpecialOrig = 0;
4093 III.ZeroIsSpecialNew = 0;
4094 III.IsCommutative = false;
4095 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI;
4096 break;
4097 case PPC::AND_rec:
4098 case PPC::AND8_rec:
4099 case PPC::OR:
4100 case PPC::OR8:
4101 case PPC::XOR:
4102 case PPC::XOR8:
4103 III.SignedImm = false;
4104 III.ZeroIsSpecialOrig = 0;
4105 III.ZeroIsSpecialNew = 0;
4106 III.IsCommutative = true;
4107 switch(Opc) {
4108 default: llvm_unreachable("Unknown opcode");
4109 case PPC::AND_rec:
4110 III.ImmOpcode = PPC::ANDI_rec;
4111 break;
4112 case PPC::AND8_rec:
4113 III.ImmOpcode = PPC::ANDI8_rec;
4114 break;
4115 case PPC::OR: III.ImmOpcode = PPC::ORI; break;
4116 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break;
4117 case PPC::XOR: III.ImmOpcode = PPC::XORI; break;
4118 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break;
4119 }
4120 break;
4121 case PPC::RLWNM:
4122 case PPC::RLWNM8:
4123 case PPC::RLWNM_rec:
4124 case PPC::RLWNM8_rec:
4125 case PPC::SLW:
4126 case PPC::SLW8:
4127 case PPC::SLW_rec:
4128 case PPC::SLW8_rec:
4129 case PPC::SRW:
4130 case PPC::SRW8:
4131 case PPC::SRW_rec:
4132 case PPC::SRW8_rec:
4133 case PPC::SRAW:
4134 case PPC::SRAW_rec:
4135 III.SignedImm = false;
4136 III.ZeroIsSpecialOrig = 0;
4137 III.ZeroIsSpecialNew = 0;
4138 III.IsCommutative = false;
4139 // This isn't actually true, but the instructions ignore any of the
4140 // upper bits, so any immediate loaded with an LI is acceptable.
4141 // This does not apply to shift right algebraic because a value
4142 // out of range will produce a -1/0.
4143 III.ImmWidth = 16;
4144 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec ||
4145 Opc == PPC::RLWNM8_rec)
4146 III.TruncateImmTo = 5;
4147 else
4148 III.TruncateImmTo = 6;
4149 switch(Opc) {
4150 default: llvm_unreachable("Unknown opcode");
4151 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break;
4152 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break;
4153 case PPC::RLWNM_rec:
4154 III.ImmOpcode = PPC::RLWINM_rec;
4155 break;
4156 case PPC::RLWNM8_rec:
4157 III.ImmOpcode = PPC::RLWINM8_rec;
4158 break;
4159 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break;
4160 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break;
4161 case PPC::SLW_rec:
4162 III.ImmOpcode = PPC::RLWINM_rec;
4163 break;
4164 case PPC::SLW8_rec:
4165 III.ImmOpcode = PPC::RLWINM8_rec;
4166 break;
4167 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break;
4168 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break;
4169 case PPC::SRW_rec:
4170 III.ImmOpcode = PPC::RLWINM_rec;
4171 break;
4172 case PPC::SRW8_rec:
4173 III.ImmOpcode = PPC::RLWINM8_rec;
4174 break;
4175 case PPC::SRAW:
4176 III.ImmWidth = 5;
4177 III.TruncateImmTo = 0;
4178 III.ImmOpcode = PPC::SRAWI;
4179 break;
4180 case PPC::SRAW_rec:
4181 III.ImmWidth = 5;
4182 III.TruncateImmTo = 0;
4183 III.ImmOpcode = PPC::SRAWI_rec;
4184 break;
4185 }
4186 break;
4187 case PPC::RLDCL:
4188 case PPC::RLDCL_rec:
4189 case PPC::RLDCR:
4190 case PPC::RLDCR_rec:
4191 case PPC::SLD:
4192 case PPC::SLD_rec:
4193 case PPC::SRD:
4194 case PPC::SRD_rec:
4195 case PPC::SRAD:
4196 case PPC::SRAD_rec:
4197 III.SignedImm = false;
4198 III.ZeroIsSpecialOrig = 0;
4199 III.ZeroIsSpecialNew = 0;
4200 III.IsCommutative = false;
4201 // This isn't actually true, but the instructions ignore any of the
4202 // upper bits, so any immediate loaded with an LI is acceptable.
4203 // This does not apply to shift right algebraic because a value
4204 // out of range will produce a -1/0.
4205 III.ImmWidth = 16;
4206 if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR ||
4207 Opc == PPC::RLDCR_rec)
4208 III.TruncateImmTo = 6;
4209 else
4210 III.TruncateImmTo = 7;
4211 switch(Opc) {
4212 default: llvm_unreachable("Unknown opcode");
4213 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break;
4214 case PPC::RLDCL_rec:
4215 III.ImmOpcode = PPC::RLDICL_rec;
4216 break;
4217 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break;
4218 case PPC::RLDCR_rec:
4219 III.ImmOpcode = PPC::RLDICR_rec;
4220 break;
4221 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break;
4222 case PPC::SLD_rec:
4223 III.ImmOpcode = PPC::RLDICR_rec;
4224 break;
4225 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break;
4226 case PPC::SRD_rec:
4227 III.ImmOpcode = PPC::RLDICL_rec;
4228 break;
4229 case PPC::SRAD:
4230 III.ImmWidth = 6;
4231 III.TruncateImmTo = 0;
4232 III.ImmOpcode = PPC::SRADI;
4233 break;
4234 case PPC::SRAD_rec:
4235 III.ImmWidth = 6;
4236 III.TruncateImmTo = 0;
4237 III.ImmOpcode = PPC::SRADI_rec;
4238 break;
4239 }
4240 break;
4241 // Loads and stores:
4242 case PPC::LBZX:
4243 case PPC::LBZX8:
4244 case PPC::LHZX:
4245 case PPC::LHZX8:
4246 case PPC::LHAX:
4247 case PPC::LHAX8:
4248 case PPC::LWZX:
4249 case PPC::LWZX8:
4250 case PPC::LWAX:
4251 case PPC::LDX:
4252 case PPC::LFSX:
4253 case PPC::LFDX:
4254 case PPC::STBX:
4255 case PPC::STBX8:
4256 case PPC::STHX:
4257 case PPC::STHX8:
4258 case PPC::STWX:
4259 case PPC::STWX8:
4260 case PPC::STDX:
4261 case PPC::STFSX:
4262 case PPC::STFDX:
4263 III.SignedImm = true;
4264 III.ZeroIsSpecialOrig = 1;
4265 III.ZeroIsSpecialNew = 2;
4266 III.IsCommutative = true;
4267 III.IsSummingOperands = true;
4268 III.ImmOpNo = 1;
4269 III.OpNoForForwarding = 2;
4270 switch(Opc) {
4271 default: llvm_unreachable("Unknown opcode");
4272 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break;
4273 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break;
4274 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break;
4275 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break;
4276 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break;
4277 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break;
4278 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break;
4279 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break;
4280 case PPC::LWAX:
4281 III.ImmOpcode = PPC::LWA;
4282 III.ImmMustBeMultipleOf = 4;
4283 break;
4284 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break;
4285 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break;
4286 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break;
4287 case PPC::STBX: III.ImmOpcode = PPC::STB; break;
4288 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break;
4289 case PPC::STHX: III.ImmOpcode = PPC::STH; break;
4290 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break;
4291 case PPC::STWX: III.ImmOpcode = PPC::STW; break;
4292 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break;
4293 case PPC::STDX:
4294 III.ImmOpcode = PPC::STD;
4295 III.ImmMustBeMultipleOf = 4;
4296 break;
4297 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break;
4298 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break;
4299 }
4300 break;
4301 case PPC::LBZUX:
4302 case PPC::LBZUX8:
4303 case PPC::LHZUX:
4304 case PPC::LHZUX8:
4305 case PPC::LHAUX:
4306 case PPC::LHAUX8:
4307 case PPC::LWZUX:
4308 case PPC::LWZUX8:
4309 case PPC::LDUX:
4310 case PPC::LFSUX:
4311 case PPC::LFDUX:
4312 case PPC::STBUX:
4313 case PPC::STBUX8:
4314 case PPC::STHUX:
4315 case PPC::STHUX8:
4316 case PPC::STWUX:
4317 case PPC::STWUX8:
4318 case PPC::STDUX:
4319 case PPC::STFSUX:
4320 case PPC::STFDUX:
4321 III.SignedImm = true;
4322 III.ZeroIsSpecialOrig = 2;
4323 III.ZeroIsSpecialNew = 3;
4324 III.IsCommutative = false;
4325 III.IsSummingOperands = true;
4326 III.ImmOpNo = 2;
4327 III.OpNoForForwarding = 3;
4328 switch(Opc) {
4329 default: llvm_unreachable("Unknown opcode");
4330 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break;
4331 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break;
4332 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break;
4333 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break;
4334 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break;
4335 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break;
4336 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break;
4337 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break;
4338 case PPC::LDUX:
4339 III.ImmOpcode = PPC::LDU;
4340 III.ImmMustBeMultipleOf = 4;
4341 break;
4342 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break;
4343 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break;
4344 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break;
4345 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break;
4346 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break;
4347 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break;
4348 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break;
4349 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break;
4350 case PPC::STDUX:
4351 III.ImmOpcode = PPC::STDU;
4352 III.ImmMustBeMultipleOf = 4;
4353 break;
4354 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break;
4355 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break;
4356 }
4357 break;
4358 // Power9 and up only. For some of these, the X-Form version has access to all
4359 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those
4360 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded
4361 // into or stored from is one of the VR registers.
4362 case PPC::LXVX:
4363 case PPC::LXSSPX:
4364 case PPC::LXSDX:
4365 case PPC::STXVX:
4366 case PPC::STXSSPX:
4367 case PPC::STXSDX:
4368 case PPC::XFLOADf32:
4369 case PPC::XFLOADf64:
4370 case PPC::XFSTOREf32:
4371 case PPC::XFSTOREf64:
4372 if (!Subtarget.hasP9Vector())
4373 return false;
4374 III.SignedImm = true;
4375 III.ZeroIsSpecialOrig = 1;
4376 III.ZeroIsSpecialNew = 2;
4377 III.IsCommutative = true;
4378 III.IsSummingOperands = true;
4379 III.ImmOpNo = 1;
4380 III.OpNoForForwarding = 2;
4381 III.ImmMustBeMultipleOf = 4;
4382 switch(Opc) {
4383 default: llvm_unreachable("Unknown opcode");
4384 case PPC::LXVX:
4385 III.ImmOpcode = PPC::LXV;
4386 III.ImmMustBeMultipleOf = 16;
4387 break;
4388 case PPC::LXSSPX:
4389 if (PostRA) {
4390 if (IsVFReg)
4391 III.ImmOpcode = PPC::LXSSP;
4392 else {
4393 III.ImmOpcode = PPC::LFS;
4394 III.ImmMustBeMultipleOf = 1;
4395 }
4396 break;
4397 }
4398 [[fallthrough]];
4399 case PPC::XFLOADf32:
4400 III.ImmOpcode = PPC::DFLOADf32;
4401 break;
4402 case PPC::LXSDX:
4403 if (PostRA) {
4404 if (IsVFReg)
4405 III.ImmOpcode = PPC::LXSD;
4406 else {
4407 III.ImmOpcode = PPC::LFD;
4408 III.ImmMustBeMultipleOf = 1;
4409 }
4410 break;
4411 }
4412 [[fallthrough]];
4413 case PPC::XFLOADf64:
4414 III.ImmOpcode = PPC::DFLOADf64;
4415 break;
4416 case PPC::STXVX:
4417 III.ImmOpcode = PPC::STXV;
4418 III.ImmMustBeMultipleOf = 16;
4419 break;
4420 case PPC::STXSSPX:
4421 if (PostRA) {
4422 if (IsVFReg)
4423 III.ImmOpcode = PPC::STXSSP;
4424 else {
4425 III.ImmOpcode = PPC::STFS;
4426 III.ImmMustBeMultipleOf = 1;
4427 }
4428 break;
4429 }
4430 [[fallthrough]];
4431 case PPC::XFSTOREf32:
4432 III.ImmOpcode = PPC::DFSTOREf32;
4433 break;
4434 case PPC::STXSDX:
4435 if (PostRA) {
4436 if (IsVFReg)
4437 III.ImmOpcode = PPC::STXSD;
4438 else {
4439 III.ImmOpcode = PPC::STFD;
4440 III.ImmMustBeMultipleOf = 1;
4441 }
4442 break;
4443 }
4444 [[fallthrough]];
4445 case PPC::XFSTOREf64:
4446 III.ImmOpcode = PPC::DFSTOREf64;
4447 break;
4448 }
4449 break;
4450 }
4451 return true;
4452}
4453
4454// Utility function for swaping two arbitrary operands of an instruction.
4455static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) {
4456 assert(Op1 != Op2 && "Cannot swap operand with itself.");
4457
4458 unsigned MaxOp = std::max(a: Op1, b: Op2);
4459 unsigned MinOp = std::min(a: Op1, b: Op2);
4460 MachineOperand MOp1 = MI.getOperand(i: MinOp);
4461 MachineOperand MOp2 = MI.getOperand(i: MaxOp);
4462 MI.removeOperand(OpNo: std::max(a: Op1, b: Op2));
4463 MI.removeOperand(OpNo: std::min(a: Op1, b: Op2));
4464
4465 // If the operands we are swapping are the two at the end (the common case)
4466 // we can just remove both and add them in the opposite order.
4467 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) {
4468 MI.addOperand(Op: MOp2);
4469 MI.addOperand(Op: MOp1);
4470 } else {
4471 // Store all operands in a temporary vector, remove them and re-add in the
4472 // right order.
4473 SmallVector<MachineOperand, 2> MOps;
4474 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops.
4475 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) {
4476 MOps.push_back(Elt: MI.getOperand(i));
4477 MI.removeOperand(OpNo: i);
4478 }
4479 // MOp2 needs to be added next.
4480 MI.addOperand(Op: MOp2);
4481 // Now add the rest.
4482 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) {
4483 if (i == MaxOp)
4484 MI.addOperand(Op: MOp1);
4485 else {
4486 MI.addOperand(Op: MOps.back());
4487 MOps.pop_back();
4488 }
4489 }
4490 }
4491}
4492
4493// Check if the 'MI' that has the index OpNoForForwarding
4494// meets the requirement described in the ImmInstrInfo.
4495bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI,
4496 const ImmInstrInfo &III,
4497 unsigned OpNoForForwarding
4498 ) const {
4499 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8
4500 // would not work pre-RA, we can only do the check post RA.
4501 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4502 if (MRI.isSSA())
4503 return false;
4504
4505 // Cannot do the transform if MI isn't summing the operands.
4506 if (!III.IsSummingOperands)
4507 return false;
4508
4509 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set.
4510 if (!III.ZeroIsSpecialOrig)
4511 return false;
4512
4513 // We cannot do the transform if the operand we are trying to replace
4514 // isn't the same as the operand the instruction allows.
4515 if (OpNoForForwarding != III.OpNoForForwarding)
4516 return false;
4517
4518 // Check if the instruction we are trying to transform really has
4519 // the special zero register as its operand.
4520 if (MI.getOperand(i: III.ZeroIsSpecialOrig).getReg() != PPC::ZERO &&
4521 MI.getOperand(i: III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8)
4522 return false;
4523
4524 // This machine instruction is convertible if it is,
4525 // 1. summing the operands.
4526 // 2. one of the operands is special zero register.
4527 // 3. the operand we are trying to replace is allowed by the MI.
4528 return true;
4529}
4530
4531// Check if the DefMI is the add inst and set the ImmMO and RegMO
4532// accordingly.
4533bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI,
4534 const ImmInstrInfo &III,
4535 MachineOperand *&ImmMO,
4536 MachineOperand *&RegMO) const {
4537 unsigned Opc = DefMI.getOpcode();
4538 if (Opc != PPC::ADDItocL8 && Opc != PPC::ADDI && Opc != PPC::ADDI8)
4539 return false;
4540
4541 // Skip the optimization of transformTo[NewImm|Imm]FormFedByAdd for ADDItocL8
4542 // on AIX which is used for toc-data access. TODO: Follow up to see if it can
4543 // apply for AIX toc-data as well.
4544 if (Opc == PPC::ADDItocL8 && Subtarget.isAIX())
4545 return false;
4546
4547 assert(DefMI.getNumOperands() >= 3 &&
4548 "Add inst must have at least three operands");
4549 RegMO = &DefMI.getOperand(i: 1);
4550 ImmMO = &DefMI.getOperand(i: 2);
4551
4552 // Before RA, ADDI first operand could be a frame index.
4553 if (!RegMO->isReg())
4554 return false;
4555
4556 // This DefMI is elgible for forwarding if it is:
4557 // 1. add inst
4558 // 2. one of the operands is Imm/CPI/Global.
4559 return isAnImmediateOperand(MO: *ImmMO);
4560}
4561
4562bool PPCInstrInfo::isRegElgibleForForwarding(
4563 const MachineOperand &RegMO, const MachineInstr &DefMI,
4564 const MachineInstr &MI, bool KillDefMI,
4565 bool &IsFwdFeederRegKilled, bool &SeenIntermediateUse) const {
4566 // x = addi y, imm
4567 // ...
4568 // z = lfdx 0, x -> z = lfd imm(y)
4569 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF
4570 // of "y" between the DEF of "x" and "z".
4571 // The query is only valid post RA.
4572 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4573 if (MRI.isSSA())
4574 return false;
4575
4576 Register Reg = RegMO.getReg();
4577
4578 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg.
4579 MachineBasicBlock::const_reverse_iterator It = MI;
4580 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend();
4581 It++;
4582 for (; It != E; ++It) {
4583 if (It->modifiesRegister(Reg, TRI: &getRegisterInfo()) && (&*It) != &DefMI)
4584 return false;
4585 else if (It->killsRegister(Reg, TRI: &getRegisterInfo()) && (&*It) != &DefMI)
4586 IsFwdFeederRegKilled = true;
4587 if (It->readsRegister(Reg, TRI: &getRegisterInfo()) && (&*It) != &DefMI)
4588 SeenIntermediateUse = true;
4589 // Made it to DefMI without encountering a clobber.
4590 if ((&*It) == &DefMI)
4591 break;
4592 }
4593 assert((&*It) == &DefMI && "DefMI is missing");
4594
4595 // If DefMI also defines the register to be forwarded, we can only forward it
4596 // if DefMI is being erased.
4597 if (DefMI.modifiesRegister(Reg, TRI: &getRegisterInfo()))
4598 return KillDefMI;
4599
4600 return true;
4601}
4602
4603bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO,
4604 const MachineInstr &DefMI,
4605 const ImmInstrInfo &III,
4606 int64_t &Imm,
4607 int64_t BaseImm) const {
4608 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate");
4609 if (DefMI.getOpcode() == PPC::ADDItocL8) {
4610 // The operand for ADDItocL8 is CPI, which isn't imm at compiling time,
4611 // However, we know that, it is 16-bit width, and has the alignment of 4.
4612 // Check if the instruction met the requirement.
4613 if (III.ImmMustBeMultipleOf > 4 ||
4614 III.TruncateImmTo || III.ImmWidth != 16)
4615 return false;
4616
4617 // Going from XForm to DForm loads means that the displacement needs to be
4618 // not just an immediate but also a multiple of 4, or 16 depending on the
4619 // load. A DForm load cannot be represented if it is a multiple of say 2.
4620 // XForm loads do not have this restriction.
4621 if (ImmMO.isGlobal()) {
4622 const DataLayout &DL = ImmMO.getGlobal()->getDataLayout();
4623 if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf)
4624 return false;
4625 }
4626
4627 return true;
4628 }
4629
4630 if (ImmMO.isImm()) {
4631 // It is Imm, we need to check if the Imm fit the range.
4632 // Sign-extend to 64-bits.
4633 // DefMI may be folded with another imm form instruction, the result Imm is
4634 // the sum of Imm of DefMI and BaseImm which is from imm form instruction.
4635 APInt ActualValue(64, ImmMO.getImm() + BaseImm, true);
4636 if (III.SignedImm && !ActualValue.isSignedIntN(N: III.ImmWidth))
4637 return false;
4638 if (!III.SignedImm && !ActualValue.isIntN(N: III.ImmWidth))
4639 return false;
4640 Imm = SignExtend64<16>(x: ImmMO.getImm() + BaseImm);
4641
4642 if (Imm % III.ImmMustBeMultipleOf)
4643 return false;
4644 if (III.TruncateImmTo)
4645 Imm &= ((1 << III.TruncateImmTo) - 1);
4646 }
4647 else
4648 return false;
4649
4650 // This ImmMO is forwarded if it meets the requriement describle
4651 // in ImmInstrInfo
4652 return true;
4653}
4654
4655bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI,
4656 unsigned OpNoForForwarding,
4657 MachineInstr **KilledDef,
4658 SmallSet<Register, 4> *RegsToUpdate) const {
4659 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
4660 !DefMI.getOperand(i: 1).isImm())
4661 return false;
4662
4663 MachineFunction *MF = MI.getParent()->getParent();
4664 MachineRegisterInfo *MRI = &MF->getRegInfo();
4665 bool PostRA = !MRI->isSSA();
4666
4667 int64_t Immediate = DefMI.getOperand(i: 1).getImm();
4668 // Sign-extend to 64-bits.
4669 int64_t SExtImm = SignExtend64<16>(x: Immediate);
4670
4671 bool ReplaceWithLI = false;
4672 bool Is64BitLI = false;
4673 int64_t NewImm = 0;
4674 bool SetCR = false;
4675 unsigned Opc = MI.getOpcode();
4676 switch (Opc) {
4677 default:
4678 return false;
4679
4680 // FIXME: Any branches conditional on such a comparison can be made
4681 // unconditional. At this time, this happens too infrequently to be worth
4682 // the implementation effort, but if that ever changes, we could convert
4683 // such a pattern here.
4684 case PPC::CMPWI:
4685 case PPC::CMPLWI:
4686 case PPC::CMPDI:
4687 case PPC::CMPLDI: {
4688 // Doing this post-RA would require dataflow analysis to reliably find uses
4689 // of the CR register set by the compare.
4690 // No need to fixup killed/dead flag since this transformation is only valid
4691 // before RA.
4692 if (PostRA)
4693 return false;
4694 // If a compare-immediate is fed by an immediate and is itself an input of
4695 // an ISEL (the most common case) into a COPY of the correct register.
4696 bool Changed = false;
4697 Register DefReg = MI.getOperand(i: 0).getReg();
4698 int64_t Comparand = MI.getOperand(i: 2).getImm();
4699 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0
4700 ? (Comparand | 0xFFFFFFFFFFFF0000)
4701 : Comparand;
4702
4703 for (auto &CompareUseMI : MRI->use_instructions(Reg: DefReg)) {
4704 unsigned UseOpc = CompareUseMI.getOpcode();
4705 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8)
4706 continue;
4707 unsigned CRSubReg = CompareUseMI.getOperand(i: 3).getSubReg();
4708 Register TrueReg = CompareUseMI.getOperand(i: 1).getReg();
4709 Register FalseReg = CompareUseMI.getOperand(i: 2).getReg();
4710 unsigned RegToCopy =
4711 selectReg(Imm1: SExtImm, Imm2: SExtComparand, CompareOpc: Opc, TrueReg, FalseReg, CRSubReg);
4712 if (RegToCopy == PPC::NoRegister)
4713 continue;
4714 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0.
4715 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) {
4716 CompareUseMI.setDesc(get(Opcode: UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI));
4717 replaceInstrOperandWithImm(MI&: CompareUseMI, OpNo: 1, Imm: 0);
4718 CompareUseMI.removeOperand(OpNo: 3);
4719 CompareUseMI.removeOperand(OpNo: 2);
4720 continue;
4721 }
4722 LLVM_DEBUG(
4723 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n");
4724 LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump());
4725 LLVM_DEBUG(dbgs() << "Is converted to:\n");
4726 if (RegsToUpdate) {
4727 for (const MachineOperand &MO : CompareUseMI.operands())
4728 if (MO.isReg())
4729 RegsToUpdate->insert(V: MO.getReg());
4730 }
4731 // Convert to copy and remove unneeded operands.
4732 CompareUseMI.setDesc(get(Opcode: PPC::COPY));
4733 CompareUseMI.removeOperand(OpNo: 3);
4734 CompareUseMI.removeOperand(OpNo: RegToCopy == TrueReg ? 2 : 1);
4735 CmpIselsConverted++;
4736 Changed = true;
4737 LLVM_DEBUG(CompareUseMI.dump());
4738 }
4739 if (Changed)
4740 return true;
4741 // This may end up incremented multiple times since this function is called
4742 // during a fixed-point transformation, but it is only meant to indicate the
4743 // presence of this opportunity.
4744 MissedConvertibleImmediateInstrs++;
4745 return false;
4746 }
4747
4748 // Immediate forms - may simply be convertable to an LI.
4749 case PPC::ADDI:
4750 case PPC::ADDI8: {
4751 // Does the sum fit in a 16-bit signed field?
4752 int64_t Addend = MI.getOperand(i: 2).getImm();
4753 if (isInt<16>(x: Addend + SExtImm)) {
4754 ReplaceWithLI = true;
4755 Is64BitLI = Opc == PPC::ADDI8;
4756 NewImm = Addend + SExtImm;
4757 break;
4758 }
4759 return false;
4760 }
4761 case PPC::SUBFIC:
4762 case PPC::SUBFIC8: {
4763 // Only transform this if the CARRY implicit operand is dead.
4764 if (MI.getNumOperands() > 3 && !MI.getOperand(i: 3).isDead())
4765 return false;
4766 int64_t Minuend = MI.getOperand(i: 2).getImm();
4767 if (isInt<16>(x: Minuend - SExtImm)) {
4768 ReplaceWithLI = true;
4769 Is64BitLI = Opc == PPC::SUBFIC8;
4770 NewImm = Minuend - SExtImm;
4771 break;
4772 }
4773 return false;
4774 }
4775 case PPC::RLDICL:
4776 case PPC::RLDICL_rec:
4777 case PPC::RLDICL_32:
4778 case PPC::RLDICL_32_64: {
4779 // Use APInt's rotate function.
4780 int64_t SH = MI.getOperand(i: 2).getImm();
4781 int64_t MB = MI.getOperand(i: 3).getImm();
4782 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32,
4783 SExtImm, true);
4784 InVal = InVal.rotl(rotateAmt: SH);
4785 uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1;
4786 InVal &= Mask;
4787 // Can't replace negative values with an LI as that will sign-extend
4788 // and not clear the left bits. If we're setting the CR bit, we will use
4789 // ANDI_rec which won't sign extend, so that's safe.
4790 if (isUInt<15>(x: InVal.getSExtValue()) ||
4791 (Opc == PPC::RLDICL_rec && isUInt<16>(x: InVal.getSExtValue()))) {
4792 ReplaceWithLI = true;
4793 Is64BitLI = Opc != PPC::RLDICL_32;
4794 NewImm = InVal.getSExtValue();
4795 SetCR = Opc == PPC::RLDICL_rec;
4796 break;
4797 }
4798 return false;
4799 }
4800 case PPC::RLWINM:
4801 case PPC::RLWINM8:
4802 case PPC::RLWINM_rec:
4803 case PPC::RLWINM8_rec: {
4804 int64_t SH = MI.getOperand(i: 2).getImm();
4805 int64_t MB = MI.getOperand(i: 3).getImm();
4806 int64_t ME = MI.getOperand(i: 4).getImm();
4807 APInt InVal(32, SExtImm, true);
4808 InVal = InVal.rotl(rotateAmt: SH);
4809 APInt Mask = APInt::getBitsSetWithWrap(numBits: 32, loBit: 32 - ME - 1, hiBit: 32 - MB);
4810 InVal &= Mask;
4811 // Can't replace negative values with an LI as that will sign-extend
4812 // and not clear the left bits. If we're setting the CR bit, we will use
4813 // ANDI_rec which won't sign extend, so that's safe.
4814 bool ValueFits = isUInt<15>(x: InVal.getSExtValue());
4815 ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) &&
4816 isUInt<16>(x: InVal.getSExtValue()));
4817 if (ValueFits) {
4818 ReplaceWithLI = true;
4819 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec;
4820 NewImm = InVal.getSExtValue();
4821 SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec;
4822 break;
4823 }
4824 return false;
4825 }
4826 case PPC::ORI:
4827 case PPC::ORI8:
4828 case PPC::XORI:
4829 case PPC::XORI8: {
4830 int64_t LogicalImm = MI.getOperand(i: 2).getImm();
4831 int64_t Result = 0;
4832 if (Opc == PPC::ORI || Opc == PPC::ORI8)
4833 Result = LogicalImm | SExtImm;
4834 else
4835 Result = LogicalImm ^ SExtImm;
4836 if (isInt<16>(x: Result)) {
4837 ReplaceWithLI = true;
4838 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8;
4839 NewImm = Result;
4840 break;
4841 }
4842 return false;
4843 }
4844 }
4845
4846 if (ReplaceWithLI) {
4847 // We need to be careful with CR-setting instructions we're replacing.
4848 if (SetCR) {
4849 // We don't know anything about uses when we're out of SSA, so only
4850 // replace if the new immediate will be reproduced.
4851 bool ImmChanged = (SExtImm & NewImm) != NewImm;
4852 if (PostRA && ImmChanged)
4853 return false;
4854
4855 if (!PostRA) {
4856 // If the defining load-immediate has no other uses, we can just replace
4857 // the immediate with the new immediate.
4858 if (MRI->hasOneUse(RegNo: DefMI.getOperand(i: 0).getReg()))
4859 DefMI.getOperand(i: 1).setImm(NewImm);
4860
4861 // If we're not using the GPR result of the CR-setting instruction, we
4862 // just need to and with zero/non-zero depending on the new immediate.
4863 else if (MRI->use_empty(RegNo: MI.getOperand(i: 0).getReg())) {
4864 if (NewImm) {
4865 assert(Immediate && "Transformation converted zero to non-zero?");
4866 NewImm = Immediate;
4867 }
4868 } else if (ImmChanged)
4869 return false;
4870 }
4871 }
4872
4873 LLVM_DEBUG(dbgs() << "Replacing constant instruction:\n");
4874 LLVM_DEBUG(MI.dump());
4875 LLVM_DEBUG(dbgs() << "Fed by:\n");
4876 LLVM_DEBUG(DefMI.dump());
4877 LoadImmediateInfo LII;
4878 LII.Imm = NewImm;
4879 LII.Is64Bit = Is64BitLI;
4880 LII.SetCR = SetCR;
4881 // If we're setting the CR, the original load-immediate must be kept (as an
4882 // operand to ANDI_rec/ANDI8_rec).
4883 if (KilledDef && SetCR)
4884 *KilledDef = nullptr;
4885 replaceInstrWithLI(MI, LII);
4886
4887 if (PostRA)
4888 recomputeLivenessFlags(MBB&: *MI.getParent());
4889
4890 LLVM_DEBUG(dbgs() << "With:\n");
4891 LLVM_DEBUG(MI.dump());
4892 return true;
4893 }
4894 return false;
4895}
4896
4897bool PPCInstrInfo::transformToNewImmFormFedByAdd(
4898 MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const {
4899 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo();
4900 bool PostRA = !MRI->isSSA();
4901 // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI
4902 // for post-ra.
4903 if (PostRA)
4904 return false;
4905
4906 // Only handle load/store.
4907 if (!MI.mayLoadOrStore())
4908 return false;
4909
4910 unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(ImmOpcode: MI.getOpcode());
4911
4912 assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) &&
4913 "MI must have x-form opcode");
4914
4915 // get Imm Form info.
4916 ImmInstrInfo III;
4917 bool IsVFReg = MI.getOperand(i: 0).isReg() &&
4918 MI.getOperand(i: 0).getReg().isPhysical() &&
4919 PPC::isVFRegister(Reg: MI.getOperand(i: 0).getReg());
4920
4921 if (!instrHasImmForm(Opc: XFormOpcode, IsVFReg, III, PostRA))
4922 return false;
4923
4924 if (!III.IsSummingOperands)
4925 return false;
4926
4927 if (OpNoForForwarding != III.OpNoForForwarding)
4928 return false;
4929
4930 MachineOperand ImmOperandMI = MI.getOperand(i: III.ImmOpNo);
4931 if (!ImmOperandMI.isImm())
4932 return false;
4933
4934 // Check DefMI.
4935 MachineOperand *ImmMO = nullptr;
4936 MachineOperand *RegMO = nullptr;
4937 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4938 return false;
4939 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4940
4941 // Check Imm.
4942 // Set ImmBase from imm instruction as base and get new Imm inside
4943 // isImmElgibleForForwarding.
4944 int64_t ImmBase = ImmOperandMI.getImm();
4945 int64_t Imm = 0;
4946 if (!isImmElgibleForForwarding(ImmMO: *ImmMO, DefMI, III, Imm, BaseImm: ImmBase))
4947 return false;
4948
4949 // Do the transform
4950 LLVM_DEBUG(dbgs() << "Replacing existing reg+imm instruction:\n");
4951 LLVM_DEBUG(MI.dump());
4952 LLVM_DEBUG(dbgs() << "Fed by:\n");
4953 LLVM_DEBUG(DefMI.dump());
4954
4955 MI.getOperand(i: III.OpNoForForwarding).setReg(RegMO->getReg());
4956 MI.getOperand(i: III.ImmOpNo).setImm(Imm);
4957
4958 LLVM_DEBUG(dbgs() << "With:\n");
4959 LLVM_DEBUG(MI.dump());
4960 return true;
4961}
4962
4963// If an X-Form instruction is fed by an add-immediate and one of its operands
4964// is the literal zero, attempt to forward the source of the add-immediate to
4965// the corresponding D-Form instruction with the displacement coming from
4966// the immediate being added.
4967bool PPCInstrInfo::transformToImmFormFedByAdd(
4968 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding,
4969 MachineInstr &DefMI, bool KillDefMI) const {
4970 // RegMO ImmMO
4971 // | |
4972 // x = addi reg, imm <----- DefMI
4973 // y = op 0 , x <----- MI
4974 // |
4975 // OpNoForForwarding
4976 // Check if the MI meet the requirement described in the III.
4977 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding))
4978 return false;
4979
4980 // Check if the DefMI meet the requirement
4981 // described in the III. If yes, set the ImmMO and RegMO accordingly.
4982 MachineOperand *ImmMO = nullptr;
4983 MachineOperand *RegMO = nullptr;
4984 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO))
4985 return false;
4986 assert(ImmMO && RegMO && "Imm and Reg operand must have been set");
4987
4988 // As we get the Imm operand now, we need to check if the ImmMO meet
4989 // the requirement described in the III. If yes set the Imm.
4990 int64_t Imm = 0;
4991 if (!isImmElgibleForForwarding(ImmMO: *ImmMO, DefMI, III, Imm))
4992 return false;
4993
4994 bool IsFwdFeederRegKilled = false;
4995 bool SeenIntermediateUse = false;
4996 // Check if the RegMO can be forwarded to MI.
4997 if (!isRegElgibleForForwarding(RegMO: *RegMO, DefMI, MI, KillDefMI,
4998 IsFwdFeederRegKilled, SeenIntermediateUse))
4999 return false;
5000
5001 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5002 bool PostRA = !MRI.isSSA();
5003
5004 // We know that, the MI and DefMI both meet the pattern, and
5005 // the Imm also meet the requirement with the new Imm-form.
5006 // It is safe to do the transformation now.
5007 LLVM_DEBUG(dbgs() << "Replacing indexed instruction:\n");
5008 LLVM_DEBUG(MI.dump());
5009 LLVM_DEBUG(dbgs() << "Fed by:\n");
5010 LLVM_DEBUG(DefMI.dump());
5011
5012 // Update the base reg first.
5013 MI.getOperand(i: III.OpNoForForwarding).ChangeToRegister(Reg: RegMO->getReg(),
5014 isDef: false, isImp: false,
5015 isKill: RegMO->isKill());
5016
5017 // Then, update the imm.
5018 if (ImmMO->isImm()) {
5019 // If the ImmMO is Imm, change the operand that has ZERO to that Imm
5020 // directly.
5021 replaceInstrOperandWithImm(MI, OpNo: III.ZeroIsSpecialOrig, Imm);
5022 }
5023 else {
5024 // Otherwise, it is Constant Pool Index(CPI) or Global,
5025 // which is relocation in fact. We need to replace the special zero
5026 // register with ImmMO.
5027 // Before that, we need to fixup the target flags for imm.
5028 // For some reason, we miss to set the flag for the ImmMO if it is CPI.
5029 if (DefMI.getOpcode() == PPC::ADDItocL8)
5030 ImmMO->setTargetFlags(PPCII::MO_TOC_LO);
5031
5032 // MI didn't have the interface such as MI.setOperand(i) though
5033 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with
5034 // ImmMO, we need to remove ZERO operand and all the operands behind it,
5035 // and, add the ImmMO, then, move back all the operands behind ZERO.
5036 SmallVector<MachineOperand, 2> MOps;
5037 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) {
5038 MOps.push_back(Elt: MI.getOperand(i));
5039 MI.removeOperand(OpNo: i);
5040 }
5041
5042 // Remove the last MO in the list, which is ZERO operand in fact.
5043 MOps.pop_back();
5044 // Add the imm operand.
5045 MI.addOperand(Op: *ImmMO);
5046 // Now add the rest back.
5047 for (auto &MO : MOps)
5048 MI.addOperand(Op: MO);
5049 }
5050
5051 // Update the opcode.
5052 MI.setDesc(get(Opcode: III.ImmOpcode));
5053
5054 if (PostRA)
5055 recomputeLivenessFlags(MBB&: *MI.getParent());
5056 LLVM_DEBUG(dbgs() << "With:\n");
5057 LLVM_DEBUG(MI.dump());
5058
5059 return true;
5060}
5061
5062bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI,
5063 const ImmInstrInfo &III,
5064 unsigned ConstantOpNo,
5065 MachineInstr &DefMI) const {
5066 // DefMI must be LI or LI8.
5067 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) ||
5068 !DefMI.getOperand(i: 1).isImm())
5069 return false;
5070
5071 // Get Imm operand and Sign-extend to 64-bits.
5072 int64_t Imm = SignExtend64<16>(x: DefMI.getOperand(i: 1).getImm());
5073
5074 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5075 bool PostRA = !MRI.isSSA();
5076 // Exit early if we can't convert this.
5077 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative)
5078 return false;
5079 if (Imm % III.ImmMustBeMultipleOf)
5080 return false;
5081 if (III.TruncateImmTo)
5082 Imm &= ((1 << III.TruncateImmTo) - 1);
5083 if (III.SignedImm) {
5084 APInt ActualValue(64, Imm, true);
5085 if (!ActualValue.isSignedIntN(N: III.ImmWidth))
5086 return false;
5087 } else {
5088 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1;
5089 if ((uint64_t)Imm > UnsignedMax)
5090 return false;
5091 }
5092
5093 // If we're post-RA, the instructions don't agree on whether register zero is
5094 // special, we can transform this as long as the register operand that will
5095 // end up in the location where zero is special isn't R0.
5096 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5097 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig :
5098 III.ZeroIsSpecialNew + 1;
5099 Register OrigZeroReg = MI.getOperand(i: PosForOrigZero).getReg();
5100 Register NewZeroReg = MI.getOperand(i: III.ZeroIsSpecialNew).getReg();
5101 // If R0 is in the operand where zero is special for the new instruction,
5102 // it is unsafe to transform if the constant operand isn't that operand.
5103 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) &&
5104 ConstantOpNo != III.ZeroIsSpecialNew)
5105 return false;
5106 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) &&
5107 ConstantOpNo != PosForOrigZero)
5108 return false;
5109 }
5110
5111 unsigned Opc = MI.getOpcode();
5112 bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec ||
5113 Opc == PPC::SRW || Opc == PPC::SRW_rec ||
5114 Opc == PPC::SLW8 || Opc == PPC::SLW8_rec ||
5115 Opc == PPC::SRW8 || Opc == PPC::SRW8_rec;
5116 bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec ||
5117 Opc == PPC::SRD || Opc == PPC::SRD_rec;
5118 bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec ||
5119 Opc == PPC::SLD_rec || Opc == PPC::SRD_rec;
5120 bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD ||
5121 Opc == PPC::SRD_rec;
5122
5123 LLVM_DEBUG(dbgs() << "Replacing reg+reg instruction: ");
5124 LLVM_DEBUG(MI.dump());
5125 LLVM_DEBUG(dbgs() << "Fed by load-immediate: ");
5126 LLVM_DEBUG(DefMI.dump());
5127 MI.setDesc(get(Opcode: III.ImmOpcode));
5128 if (ConstantOpNo == III.OpNoForForwarding) {
5129 // Converting shifts to immediate form is a bit tricky since they may do
5130 // one of three things:
5131 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero
5132 // 2. If the shift amount is zero, the result is unchanged (save for maybe
5133 // setting CR0)
5134 // 3. If the shift amount is in [1, OpSize), it's just a shift
5135 if (SpecialShift32 || SpecialShift64) {
5136 LoadImmediateInfo LII;
5137 LII.Imm = 0;
5138 LII.SetCR = SetCR;
5139 LII.Is64Bit = SpecialShift64;
5140 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F);
5141 if (Imm & (SpecialShift32 ? 0x20 : 0x40))
5142 replaceInstrWithLI(MI, LII);
5143 // Shifts by zero don't change the value. If we don't need to set CR0,
5144 // just convert this to a COPY. Can't do this post-RA since we've already
5145 // cleaned up the copies.
5146 else if (!SetCR && ShAmt == 0 && !PostRA) {
5147 MI.removeOperand(OpNo: 2);
5148 MI.setDesc(get(Opcode: PPC::COPY));
5149 } else {
5150 // The 32 bit and 64 bit instructions are quite different.
5151 if (SpecialShift32) {
5152 // Left shifts use (N, 0, 31-N).
5153 // Right shifts use (32-N, N, 31) if 0 < N < 32.
5154 // use (0, 0, 31) if N == 0.
5155 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt;
5156 uint64_t MB = RightShift ? ShAmt : 0;
5157 uint64_t ME = RightShift ? 31 : 31 - ShAmt;
5158 replaceInstrOperandWithImm(MI, OpNo: III.OpNoForForwarding, Imm: SH);
5159 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(Val: MB)
5160 .addImm(Val: ME);
5161 } else {
5162 // Left shifts use (N, 63-N).
5163 // Right shifts use (64-N, N) if 0 < N < 64.
5164 // use (0, 0) if N == 0.
5165 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt;
5166 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt;
5167 replaceInstrOperandWithImm(MI, OpNo: III.OpNoForForwarding, Imm: SH);
5168 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(Val: ME);
5169 }
5170 }
5171 } else
5172 replaceInstrOperandWithImm(MI, OpNo: ConstantOpNo, Imm);
5173 }
5174 // Convert commutative instructions (switch the operands and convert the
5175 // desired one to an immediate.
5176 else if (III.IsCommutative) {
5177 replaceInstrOperandWithImm(MI, OpNo: ConstantOpNo, Imm);
5178 swapMIOperands(MI, Op1: ConstantOpNo, Op2: III.OpNoForForwarding);
5179 } else
5180 llvm_unreachable("Should have exited early!");
5181
5182 // For instructions for which the constant register replaces a different
5183 // operand than where the immediate goes, we need to swap them.
5184 if (III.OpNoForForwarding != III.ImmOpNo)
5185 swapMIOperands(MI, Op1: III.OpNoForForwarding, Op2: III.ImmOpNo);
5186
5187 // If the special R0/X0 register index are different for original instruction
5188 // and new instruction, we need to fix up the register class in new
5189 // instruction.
5190 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) {
5191 if (III.ZeroIsSpecialNew) {
5192 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no
5193 // need to fix up register class.
5194 Register RegToModify = MI.getOperand(i: III.ZeroIsSpecialNew).getReg();
5195 if (RegToModify.isVirtual()) {
5196 const TargetRegisterClass *NewRC =
5197 MRI.getRegClass(Reg: RegToModify)->hasSuperClassEq(RC: &PPC::GPRCRegClass) ?
5198 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass;
5199 MRI.setRegClass(Reg: RegToModify, RC: NewRC);
5200 }
5201 }
5202 }
5203
5204 if (PostRA)
5205 recomputeLivenessFlags(MBB&: *MI.getParent());
5206
5207 LLVM_DEBUG(dbgs() << "With: ");
5208 LLVM_DEBUG(MI.dump());
5209 LLVM_DEBUG(dbgs() << "\n");
5210 return true;
5211}
5212
5213const TargetRegisterClass *
5214PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const {
5215 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass)
5216 return &PPC::VSRCRegClass;
5217 return RC;
5218}
5219
5220int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) {
5221 return PPC::getRecordFormOpcode(Opcode);
5222}
5223
5224static bool isOpZeroOfSubwordPreincLoad(int Opcode) {
5225 return (Opcode == PPC::LBZU || Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 ||
5226 Opcode == PPC::LBZUX8 || Opcode == PPC::LHZU ||
5227 Opcode == PPC::LHZUX || Opcode == PPC::LHZU8 ||
5228 Opcode == PPC::LHZUX8);
5229}
5230
5231// This function checks for sign extension from 32 bits to 64 bits.
5232static bool definedBySignExtendingOp(const PPCInstrInfo &TII,
5233 const unsigned Reg,
5234 const MachineRegisterInfo *MRI) {
5235 if (!Register::isVirtualRegister(Reg))
5236 return false;
5237
5238 MachineInstr *MI = MRI->getVRegDef(Reg);
5239 if (!MI)
5240 return false;
5241
5242 int Opcode = MI->getOpcode();
5243 if (TII.isSExt32To64(Opcode))
5244 return true;
5245
5246 // The first def of LBZU/LHZU is sign extended.
5247 if (isOpZeroOfSubwordPreincLoad(Opcode) && MI->getOperand(i: 0).getReg() == Reg)
5248 return true;
5249
5250 // RLDICL generates sign-extended output if it clears at least
5251 // 33 bits from the left (MSB).
5252 if (Opcode == PPC::RLDICL && MI->getOperand(i: 3).getImm() >= 33)
5253 return true;
5254
5255 // If at least one bit from left in a lower word is masked out,
5256 // all of 0 to 32-th bits of the output are cleared.
5257 // Hence the output is already sign extended.
5258 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5259 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) &&
5260 MI->getOperand(i: 3).getImm() > 0 &&
5261 MI->getOperand(i: 3).getImm() <= MI->getOperand(i: 4).getImm())
5262 return true;
5263
5264 // If the most significant bit of immediate in ANDIS is zero,
5265 // all of 0 to 32-th bits are cleared.
5266 if (Opcode == PPC::ANDIS_rec || Opcode == PPC::ANDIS8_rec) {
5267 uint16_t Imm = MI->getOperand(i: 2).getImm();
5268 if ((Imm & 0x8000) == 0)
5269 return true;
5270 }
5271
5272 return false;
5273}
5274
5275// This function checks the machine instruction that defines the input register
5276// Reg. If that machine instruction always outputs a value that has only zeros
5277// in the higher 32 bits then this function will return true.
5278static bool definedByZeroExtendingOp(const PPCInstrInfo &TII,
5279 const unsigned Reg,
5280 const MachineRegisterInfo *MRI) {
5281 if (!Register::isVirtualRegister(Reg))
5282 return false;
5283
5284 MachineInstr *MI = MRI->getVRegDef(Reg);
5285 if (!MI)
5286 return false;
5287
5288 int Opcode = MI->getOpcode();
5289 if (TII.isZExt32To64(Opcode))
5290 return true;
5291
5292 // The first def of LBZU/LHZU/LWZU are zero extended.
5293 if ((isOpZeroOfSubwordPreincLoad(Opcode) || Opcode == PPC::LWZU ||
5294 Opcode == PPC::LWZUX || Opcode == PPC::LWZU8 || Opcode == PPC::LWZUX8) &&
5295 MI->getOperand(i: 0).getReg() == Reg)
5296 return true;
5297
5298 // The 16-bit immediate is sign-extended in li/lis.
5299 // If the most significant bit is zero, all higher bits are zero.
5300 if (Opcode == PPC::LI || Opcode == PPC::LI8 ||
5301 Opcode == PPC::LIS || Opcode == PPC::LIS8) {
5302 int64_t Imm = MI->getOperand(i: 1).getImm();
5303 if (((uint64_t)Imm & ~0x7FFFuLL) == 0)
5304 return true;
5305 }
5306
5307 // We have some variations of rotate-and-mask instructions
5308 // that clear higher 32-bits.
5309 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec ||
5310 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec ||
5311 Opcode == PPC::RLDICL_32_64) &&
5312 MI->getOperand(i: 3).getImm() >= 32)
5313 return true;
5314
5315 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) &&
5316 MI->getOperand(i: 3).getImm() >= 32 &&
5317 MI->getOperand(i: 3).getImm() <= 63 - MI->getOperand(i: 2).getImm())
5318 return true;
5319
5320 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec ||
5321 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec ||
5322 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) &&
5323 MI->getOperand(i: 3).getImm() <= MI->getOperand(i: 4).getImm())
5324 return true;
5325
5326 return false;
5327}
5328
5329// This function returns true if the input MachineInstr is a TOC save
5330// instruction.
5331bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const {
5332 if (!MI.getOperand(i: 1).isImm() || !MI.getOperand(i: 2).isReg())
5333 return false;
5334 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5335 unsigned StackOffset = MI.getOperand(i: 1).getImm();
5336 Register StackReg = MI.getOperand(i: 2).getReg();
5337 Register SPReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
5338 if (StackReg == SPReg && StackOffset == TOCSaveOffset)
5339 return true;
5340
5341 return false;
5342}
5343
5344// We limit the max depth to track incoming values of PHIs or binary ops
5345// (e.g. AND) to avoid excessive cost.
5346const unsigned MAX_BINOP_DEPTH = 1;
5347
5348// This function will promote the instruction which defines the register `Reg`
5349// in the parameter from a 32-bit to a 64-bit instruction if needed. The logic
5350// used to check whether an instruction needs to be promoted or not is similar
5351// to the logic used to check whether or not a defined register is sign or zero
5352// extended within the function PPCInstrInfo::isSignOrZeroExtended.
5353// Additionally, the `promoteInstr32To64ForElimEXTSW` function is recursive.
5354// BinOpDepth does not count all of the recursions. The parameter BinOpDepth is
5355// incremented only when `promoteInstr32To64ForElimEXTSW` calls itself more
5356// than once. This is done to prevent exponential recursion.
5357void PPCInstrInfo::promoteInstr32To64ForElimEXTSW(const Register &Reg,
5358 MachineRegisterInfo *MRI,
5359 unsigned BinOpDepth,
5360 LiveVariables *LV) const {
5361 if (!Reg.isVirtual())
5362 return;
5363
5364 MachineInstr *MI = MRI->getVRegDef(Reg);
5365 if (!MI)
5366 return;
5367
5368 unsigned Opcode = MI->getOpcode();
5369
5370 switch (Opcode) {
5371 case PPC::OR:
5372 case PPC::ISEL:
5373 case PPC::OR8:
5374 case PPC::PHI: {
5375 if (BinOpDepth >= MAX_BINOP_DEPTH)
5376 break;
5377 unsigned OperandEnd = 3, OperandStride = 1;
5378 if (Opcode == PPC::PHI) {
5379 OperandEnd = MI->getNumOperands();
5380 OperandStride = 2;
5381 }
5382
5383 for (unsigned I = 1; I < OperandEnd; I += OperandStride) {
5384 assert(MI->getOperand(I).isReg() && "Operand must be register");
5385 promoteInstr32To64ForElimEXTSW(Reg: MI->getOperand(i: I).getReg(), MRI,
5386 BinOpDepth: BinOpDepth + 1, LV);
5387 }
5388
5389 break;
5390 }
5391 case PPC::COPY: {
5392 // Refers to the logic of the `case PPC::COPY` statement in the function
5393 // PPCInstrInfo::isSignOrZeroExtended().
5394
5395 Register SrcReg = MI->getOperand(i: 1).getReg();
5396 // In both ELFv1 and v2 ABI, method parameters and the return value
5397 // are sign- or zero-extended.
5398 const MachineFunction *MF = MI->getMF();
5399 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5400 // If this is a copy from another register, we recursively promote the
5401 // source.
5402 promoteInstr32To64ForElimEXTSW(Reg: SrcReg, MRI, BinOpDepth, LV);
5403 return;
5404 }
5405
5406 // From here on everything is SVR4ABI. COPY will be eliminated in the other
5407 // pass, we do not need promote the COPY pseudo opcode.
5408
5409 if (SrcReg != PPC::X3)
5410 // If this is a copy from another register, we recursively promote the
5411 // source.
5412 promoteInstr32To64ForElimEXTSW(Reg: SrcReg, MRI, BinOpDepth, LV);
5413 return;
5414 }
5415 case PPC::ORI:
5416 case PPC::XORI:
5417 case PPC::ORIS:
5418 case PPC::XORIS:
5419 case PPC::ORI8:
5420 case PPC::XORI8:
5421 case PPC::ORIS8:
5422 case PPC::XORIS8:
5423 promoteInstr32To64ForElimEXTSW(Reg: MI->getOperand(i: 1).getReg(), MRI, BinOpDepth,
5424 LV);
5425 break;
5426 case PPC::AND:
5427 case PPC::AND8:
5428 if (BinOpDepth >= MAX_BINOP_DEPTH)
5429 break;
5430
5431 promoteInstr32To64ForElimEXTSW(Reg: MI->getOperand(i: 1).getReg(), MRI,
5432 BinOpDepth: BinOpDepth + 1, LV);
5433 promoteInstr32To64ForElimEXTSW(Reg: MI->getOperand(i: 2).getReg(), MRI,
5434 BinOpDepth: BinOpDepth + 1, LV);
5435 break;
5436 }
5437
5438 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
5439 if (RC == &PPC::G8RCRegClass || RC == &PPC::G8RC_and_G8RC_NOX0RegClass)
5440 return;
5441
5442 // Map the 32bit to 64bit opcodes for instructions that are not signed or zero
5443 // extended themselves, but may have operands who's destination registers of
5444 // signed or zero extended instructions.
5445 DenseMap<unsigned, unsigned> OpcodeMap = {
5446 {PPC::OR, PPC::OR8}, {PPC::ISEL, PPC::ISEL8},
5447 {PPC::ORI, PPC::ORI8}, {PPC::XORI, PPC::XORI8},
5448 {PPC::ORIS, PPC::ORIS8}, {PPC::XORIS, PPC::XORIS8},
5449 {PPC::AND, PPC::AND8}};
5450
5451 int NewOpcode = -1;
5452 auto It = OpcodeMap.find(Val: Opcode);
5453 if (It != OpcodeMap.end()) {
5454 // Set the new opcode to the mapped 64-bit version.
5455 NewOpcode = It->second;
5456 } else {
5457 if (!isSExt32To64(Opcode))
5458 return;
5459
5460 // The TableGen function `get64BitInstrFromSignedExt32BitInstr` is used to
5461 // map the 32-bit instruction with the `SExt32To64` flag to the 64-bit
5462 // instruction with the same opcode.
5463 NewOpcode = PPC::get64BitInstrFromSignedExt32BitInstr(Opcode);
5464 }
5465
5466 assert(NewOpcode != -1 &&
5467 "Must have a 64-bit opcode to map the 32-bit opcode!");
5468
5469 const MCInstrDesc &MCID = get(Opcode: NewOpcode);
5470 const TargetRegisterClass *NewRC =
5471 RI.getRegClass(i: MCID.operands()[0].RegClass);
5472
5473 Register SrcReg = MI->getOperand(i: 0).getReg();
5474 const TargetRegisterClass *SrcRC = MRI->getRegClass(Reg: SrcReg);
5475
5476 // If the register class of the defined register in the 32-bit instruction
5477 // is the same as the register class of the defined register in the promoted
5478 // 64-bit instruction, we do not need to promote the instruction.
5479 if (NewRC == SrcRC)
5480 return;
5481
5482 DebugLoc DL = MI->getDebugLoc();
5483 auto MBB = MI->getParent();
5484
5485 // Since the pseudo-opcode of the instruction is promoted from 32-bit to
5486 // 64-bit, if the source reg class of the original instruction belongs to
5487 // PPC::GRCRegClass or PPC::GPRC_and_GPRC_NOR0RegClass, we need to promote
5488 // the operand to PPC::G8CRegClass or PPC::G8RC_and_G8RC_NOR0RegClass,
5489 // respectively.
5490 SmallVector<Register> PromoteRegs(MI->getNumOperands());
5491 for (unsigned i = 1; i < MI->getNumOperands(); i++) {
5492 MachineOperand &Operand = MI->getOperand(i);
5493 if (!Operand.isReg())
5494 continue;
5495
5496 Register OperandReg = Operand.getReg();
5497 if (!OperandReg.isVirtual())
5498 continue;
5499
5500 const TargetRegisterClass *NewUsedRegRC =
5501 RI.getRegClass(i: MCID.operands()[i].RegClass);
5502 const TargetRegisterClass *OrgRC = MRI->getRegClass(Reg: OperandReg);
5503 if (NewUsedRegRC != OrgRC && (OrgRC == &PPC::GPRCRegClass ||
5504 OrgRC == &PPC::GPRC_and_GPRC_NOR0RegClass)) {
5505 // Promote the used 32-bit register to 64-bit register.
5506 Register TmpReg = MRI->createVirtualRegister(RegClass: NewUsedRegRC);
5507 Register DstTmpReg = MRI->createVirtualRegister(RegClass: NewUsedRegRC);
5508 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: get(Opcode: PPC::IMPLICIT_DEF), DestReg: TmpReg);
5509 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: get(Opcode: PPC::INSERT_SUBREG), DestReg: DstTmpReg)
5510 .addReg(RegNo: TmpReg)
5511 .addReg(RegNo: OperandReg)
5512 .addImm(Val: PPC::sub_32);
5513 PromoteRegs[i] = DstTmpReg;
5514 }
5515 }
5516
5517 Register NewDefinedReg = MRI->createVirtualRegister(RegClass: NewRC);
5518
5519 BuildMI(BB&: *MBB, I: MI, MIMD: DL, MCID: get(Opcode: NewOpcode), DestReg: NewDefinedReg);
5520 MachineBasicBlock::instr_iterator Iter(MI);
5521 --Iter;
5522 MachineInstrBuilder MIBuilder(*Iter->getMF(), Iter);
5523 for (unsigned i = 1; i < MI->getNumOperands(); i++) {
5524 if (PromoteRegs[i])
5525 MIBuilder.addReg(RegNo: PromoteRegs[i], Flags: RegState::Kill);
5526 else
5527 Iter->addOperand(Op: MI->getOperand(i));
5528 }
5529
5530 for (unsigned i = 1; i < Iter->getNumOperands(); i++) {
5531 MachineOperand &Operand = Iter->getOperand(i);
5532 if (!Operand.isReg())
5533 continue;
5534 Register OperandReg = Operand.getReg();
5535 if (!OperandReg.isVirtual())
5536 continue;
5537 LV->recomputeForSingleDefVirtReg(Reg: OperandReg);
5538 }
5539
5540 MI->eraseFromParent();
5541
5542 // A defined register may be used by other instructions that are 32-bit.
5543 // After the defined register is promoted to 64-bit for the promoted
5544 // instruction, we need to demote the 64-bit defined register back to a
5545 // 32-bit register
5546 BuildMI(BB&: *MBB, I: ++Iter, MIMD: DL, MCID: get(Opcode: PPC::COPY), DestReg: SrcReg)
5547 .addReg(RegNo: NewDefinedReg, Flags: RegState::Kill, SubReg: PPC::sub_32);
5548 LV->recomputeForSingleDefVirtReg(Reg: NewDefinedReg);
5549}
5550
5551// The isSignOrZeroExtended function is recursive. The parameter BinOpDepth
5552// does not count all of the recursions. The parameter BinOpDepth is incremented
5553// only when isSignOrZeroExtended calls itself more than once. This is done to
5554// prevent expontential recursion. There is no parameter to track linear
5555// recursion.
5556std::pair<bool, bool>
5557PPCInstrInfo::isSignOrZeroExtended(const unsigned Reg,
5558 const unsigned BinOpDepth,
5559 const MachineRegisterInfo *MRI) const {
5560 if (!Register::isVirtualRegister(Reg))
5561 return std::pair<bool, bool>(false, false);
5562
5563 MachineInstr *MI = MRI->getVRegDef(Reg);
5564 if (!MI)
5565 return std::pair<bool, bool>(false, false);
5566
5567 bool IsSExt = definedBySignExtendingOp(TII: *this, Reg, MRI);
5568 bool IsZExt = definedByZeroExtendingOp(TII: *this, Reg, MRI);
5569
5570 // If we know the instruction always returns sign- and zero-extended result,
5571 // return here.
5572 if (IsSExt && IsZExt)
5573 return std::pair<bool, bool>(IsSExt, IsZExt);
5574
5575 switch (MI->getOpcode()) {
5576 case PPC::COPY: {
5577 Register SrcReg = MI->getOperand(i: 1).getReg();
5578
5579 // In both ELFv1 and v2 ABI, method parameters and the return value
5580 // are sign- or zero-extended.
5581 const MachineFunction *MF = MI->getMF();
5582
5583 if (!MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) {
5584 // If this is a copy from another register, we recursively check source.
5585 auto SrcExt = isSignOrZeroExtended(Reg: SrcReg, BinOpDepth, MRI);
5586 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5587 SrcExt.second || IsZExt);
5588 }
5589
5590 // From here on everything is SVR4ABI
5591 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
5592 // We check the ZExt/SExt flags for a method parameter.
5593 if (MI->getParent()->getBasicBlock() ==
5594 &MF->getFunction().getEntryBlock()) {
5595 Register VReg = MI->getOperand(i: 0).getReg();
5596 if (MF->getRegInfo().isLiveIn(Reg: VReg)) {
5597 IsSExt |= FuncInfo->isLiveInSExt(VReg);
5598 IsZExt |= FuncInfo->isLiveInZExt(VReg);
5599 return std::pair<bool, bool>(IsSExt, IsZExt);
5600 }
5601 }
5602
5603 if (SrcReg != PPC::X3) {
5604 // If this is a copy from another register, we recursively check source.
5605 auto SrcExt = isSignOrZeroExtended(Reg: SrcReg, BinOpDepth, MRI);
5606 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5607 SrcExt.second || IsZExt);
5608 }
5609
5610 // For a method return value, we check the ZExt/SExt flags in attribute.
5611 // We assume the following code sequence for method call.
5612 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1
5613 // BL8_NOP @func,...
5614 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1
5615 // %5 = COPY %x3; G8RC:%5
5616 const MachineBasicBlock *MBB = MI->getParent();
5617 std::pair<bool, bool> IsExtendPair = std::pair<bool, bool>(IsSExt, IsZExt);
5618 MachineBasicBlock::const_instr_iterator II =
5619 MachineBasicBlock::const_instr_iterator(MI);
5620 if (II == MBB->instr_begin() || (--II)->getOpcode() != PPC::ADJCALLSTACKUP)
5621 return IsExtendPair;
5622
5623 const MachineInstr &CallMI = *(--II);
5624 if (!CallMI.isCall() || !CallMI.getOperand(i: 0).isGlobal())
5625 return IsExtendPair;
5626
5627 const Function *CalleeFn =
5628 dyn_cast_if_present<Function>(Val: CallMI.getOperand(i: 0).getGlobal());
5629 if (!CalleeFn)
5630 return IsExtendPair;
5631 const IntegerType *IntTy = dyn_cast<IntegerType>(Val: CalleeFn->getReturnType());
5632 if (IntTy && IntTy->getBitWidth() <= 32) {
5633 const AttributeSet &Attrs = CalleeFn->getAttributes().getRetAttrs();
5634 IsSExt |= Attrs.hasAttribute(Kind: Attribute::SExt);
5635 IsZExt |= Attrs.hasAttribute(Kind: Attribute::ZExt);
5636 return std::pair<bool, bool>(IsSExt, IsZExt);
5637 }
5638
5639 return IsExtendPair;
5640 }
5641
5642 // OR, XOR with 16-bit immediate does not change the upper 48 bits.
5643 // So, we track the operand register as we do for register copy.
5644 case PPC::ORI:
5645 case PPC::XORI:
5646 case PPC::ORI8:
5647 case PPC::XORI8: {
5648 Register SrcReg = MI->getOperand(i: 1).getReg();
5649 auto SrcExt = isSignOrZeroExtended(Reg: SrcReg, BinOpDepth, MRI);
5650 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5651 SrcExt.second || IsZExt);
5652 }
5653
5654 // OR, XOR with shifted 16-bit immediate does not change the upper
5655 // 32 bits. So, we track the operand register for zero extension.
5656 // For sign extension when the MSB of the immediate is zero, we also
5657 // track the operand register since the upper 33 bits are unchanged.
5658 case PPC::ORIS:
5659 case PPC::XORIS:
5660 case PPC::ORIS8:
5661 case PPC::XORIS8: {
5662 Register SrcReg = MI->getOperand(i: 1).getReg();
5663 auto SrcExt = isSignOrZeroExtended(Reg: SrcReg, BinOpDepth, MRI);
5664 uint16_t Imm = MI->getOperand(i: 2).getImm();
5665 if (Imm & 0x8000)
5666 return std::pair<bool, bool>(false, SrcExt.second || IsZExt);
5667 else
5668 return std::pair<bool, bool>(SrcExt.first || IsSExt,
5669 SrcExt.second || IsZExt);
5670 }
5671
5672 // If all incoming values are sign-/zero-extended,
5673 // the output of OR, ISEL or PHI is also sign-/zero-extended.
5674 case PPC::OR:
5675 case PPC::OR8:
5676 case PPC::ISEL:
5677 case PPC::PHI: {
5678 if (BinOpDepth >= MAX_BINOP_DEPTH)
5679 return std::pair<bool, bool>(false, false);
5680
5681 // The input registers for PHI are operand 1, 3, ...
5682 // The input registers for others are operand 1 and 2.
5683 unsigned OperandEnd = 3, OperandStride = 1;
5684 if (MI->getOpcode() == PPC::PHI) {
5685 OperandEnd = MI->getNumOperands();
5686 OperandStride = 2;
5687 }
5688
5689 IsSExt = true;
5690 IsZExt = true;
5691 for (unsigned I = 1; I != OperandEnd; I += OperandStride) {
5692 if (!MI->getOperand(i: I).isReg())
5693 return std::pair<bool, bool>(false, false);
5694
5695 Register SrcReg = MI->getOperand(i: I).getReg();
5696 auto SrcExt = isSignOrZeroExtended(Reg: SrcReg, BinOpDepth: BinOpDepth + 1, MRI);
5697 IsSExt &= SrcExt.first;
5698 IsZExt &= SrcExt.second;
5699 }
5700 return std::pair<bool, bool>(IsSExt, IsZExt);
5701 }
5702
5703 // If at least one of the incoming values of an AND is zero extended
5704 // then the output is also zero-extended. If both of the incoming values
5705 // are sign-extended then the output is also sign extended.
5706 case PPC::AND:
5707 case PPC::AND8: {
5708 if (BinOpDepth >= MAX_BINOP_DEPTH)
5709 return std::pair<bool, bool>(false, false);
5710
5711 Register SrcReg1 = MI->getOperand(i: 1).getReg();
5712 Register SrcReg2 = MI->getOperand(i: 2).getReg();
5713 auto Src1Ext = isSignOrZeroExtended(Reg: SrcReg1, BinOpDepth: BinOpDepth + 1, MRI);
5714 auto Src2Ext = isSignOrZeroExtended(Reg: SrcReg2, BinOpDepth: BinOpDepth + 1, MRI);
5715 return std::pair<bool, bool>(Src1Ext.first && Src2Ext.first,
5716 Src1Ext.second || Src2Ext.second);
5717 }
5718
5719 default:
5720 break;
5721 }
5722 return std::pair<bool, bool>(IsSExt, IsZExt);
5723}
5724
5725bool PPCInstrInfo::isBDNZ(unsigned Opcode) const {
5726 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ));
5727}
5728
5729namespace {
5730class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
5731 MachineInstr *Loop, *EndLoop, *LoopCount;
5732 MachineFunction *MF;
5733 const TargetInstrInfo *TII;
5734 int64_t TripCount;
5735
5736public:
5737 PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop,
5738 MachineInstr *LoopCount)
5739 : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount),
5740 MF(Loop->getParent()->getParent()),
5741 TII(MF->getSubtarget().getInstrInfo()) {
5742 // Inspect the Loop instruction up-front, as it may be deleted when we call
5743 // createTripCountGreaterCondition.
5744 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI)
5745 TripCount = LoopCount->getOperand(i: 1).getImm();
5746 else
5747 TripCount = -1;
5748 }
5749
5750 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
5751 // Only ignore the terminator.
5752 return MI == EndLoop;
5753 }
5754
5755 std::optional<bool> createTripCountGreaterCondition(
5756 int TC, MachineBasicBlock &MBB,
5757 SmallVectorImpl<MachineOperand> &Cond) override {
5758 if (TripCount == -1) {
5759 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5760 // so we don't need to generate any thing here.
5761 Cond.push_back(Elt: MachineOperand::CreateImm(Val: 0));
5762 Cond.push_back(Elt: MachineOperand::CreateReg(
5763 Reg: MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR,
5764 isDef: true));
5765 return {};
5766 }
5767
5768 return TripCount > TC;
5769 }
5770
5771 void setPreheader(MachineBasicBlock *NewPreheader) override {
5772 // Do nothing. We want the LOOP setup instruction to stay in the *old*
5773 // preheader, so we can use BDZ in the prologs to adapt the loop trip count.
5774 }
5775
5776 void adjustTripCount(int TripCountAdjust) override {
5777 // If the loop trip count is a compile-time value, then just change the
5778 // value.
5779 if (LoopCount->getOpcode() == PPC::LI8 ||
5780 LoopCount->getOpcode() == PPC::LI) {
5781 int64_t TripCount = LoopCount->getOperand(i: 1).getImm() + TripCountAdjust;
5782 LoopCount->getOperand(i: 1).setImm(TripCount);
5783 return;
5784 }
5785
5786 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1,
5787 // so we don't need to generate any thing here.
5788 }
5789
5790 void disposed(LiveIntervals *LIS) override {
5791 if (LIS) {
5792 LIS->RemoveMachineInstrFromMaps(MI&: *Loop);
5793 LIS->RemoveMachineInstrFromMaps(MI&: *LoopCount);
5794 }
5795 Loop->eraseFromParent();
5796 // Ensure the loop setup instruction is deleted too.
5797 LoopCount->eraseFromParent();
5798 }
5799};
5800} // namespace
5801
5802std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
5803PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
5804 // We really "analyze" only hardware loops right now.
5805 MachineBasicBlock::iterator I = LoopBB->getFirstTerminator();
5806 MachineBasicBlock *Preheader = *LoopBB->pred_begin();
5807 if (Preheader == LoopBB)
5808 Preheader = *std::next(x: LoopBB->pred_begin());
5809 MachineFunction *MF = Preheader->getParent();
5810
5811 if (I != LoopBB->end() && isBDNZ(Opcode: I->getOpcode())) {
5812 SmallPtrSet<MachineBasicBlock *, 8> Visited;
5813 if (MachineInstr *LoopInst = findLoopInstr(PreHeader&: *Preheader, Visited)) {
5814 Register LoopCountReg = LoopInst->getOperand(i: 0).getReg();
5815 MachineRegisterInfo &MRI = MF->getRegInfo();
5816 MachineInstr *LoopCount = MRI.getUniqueVRegDef(Reg: LoopCountReg);
5817 return std::make_unique<PPCPipelinerLoopInfo>(args&: LoopInst, args: &*I, args&: LoopCount);
5818 }
5819 }
5820 return nullptr;
5821}
5822
5823MachineInstr *PPCInstrInfo::findLoopInstr(
5824 MachineBasicBlock &PreHeader,
5825 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const {
5826
5827 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop);
5828
5829 // The loop set-up instruction should be in preheader
5830 for (auto &I : PreHeader.instrs())
5831 if (I.getOpcode() == LOOPi)
5832 return &I;
5833 return nullptr;
5834}
5835
5836// Return true if get the base operand, byte offset of an instruction and the
5837// memory width. Width is the size of memory that is being loaded/stored.
5838bool PPCInstrInfo::getMemOperandWithOffsetWidth(
5839 const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset,
5840 LocationSize &Width, const TargetRegisterInfo *TRI) const {
5841 if (!LdSt.mayLoadOrStore() || LdSt.getNumExplicitOperands() != 3)
5842 return false;
5843
5844 // Handle only loads/stores with base register followed by immediate offset.
5845 if (!LdSt.getOperand(i: 1).isImm() ||
5846 (!LdSt.getOperand(i: 2).isReg() && !LdSt.getOperand(i: 2).isFI()))
5847 return false;
5848
5849 if (!LdSt.hasOneMemOperand())
5850 return false;
5851
5852 Width = (*LdSt.memoperands_begin())->getSize();
5853 Offset = LdSt.getOperand(i: 1).getImm();
5854 BaseReg = &LdSt.getOperand(i: 2);
5855 return true;
5856}
5857
5858bool PPCInstrInfo::areMemAccessesTriviallyDisjoint(
5859 const MachineInstr &MIa, const MachineInstr &MIb) const {
5860 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
5861 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
5862
5863 if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
5864 MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
5865 return false;
5866
5867 // Retrieve the base register, offset from the base register and width. Width
5868 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If
5869 // base registers are identical, and the offset of a lower memory access +
5870 // the width doesn't overlap the offset of a higher memory access,
5871 // then the memory accesses are different.
5872 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
5873 int64_t OffsetA = 0, OffsetB = 0;
5874 LocationSize WidthA = LocationSize::precise(Value: 0),
5875 WidthB = LocationSize::precise(Value: 0);
5876 if (getMemOperandWithOffsetWidth(LdSt: MIa, BaseReg&: BaseOpA, Offset&: OffsetA, Width&: WidthA, TRI: &RI) &&
5877 getMemOperandWithOffsetWidth(LdSt: MIb, BaseReg&: BaseOpB, Offset&: OffsetB, Width&: WidthB, TRI: &RI)) {
5878 if (BaseOpA->isIdenticalTo(Other: *BaseOpB)) {
5879 int LowOffset = std::min(a: OffsetA, b: OffsetB);
5880 int HighOffset = std::max(a: OffsetA, b: OffsetB);
5881 LocationSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
5882 if (LowWidth.hasValue() &&
5883 LowOffset + (int)LowWidth.getValue() <= HighOffset)
5884 return true;
5885 }
5886 }
5887 return false;
5888}
5889
5890// Expands LWAT_CSNE_PSEUDO/LDAT_CSNE_PSEUDO post register allocation.
5891// lwat/ldat FC=16 requires 3 consecutive registers. X8/X9/X10 are
5892// hardcoded post-RA to satisfy this constraint without a dedicated
5893// register class.
5894bool PPCInstrInfo::expandAMOCSNEPseudo(MachineInstr &MI) const {
5895 MachineBasicBlock &MBB = *MI.getParent();
5896 DebugLoc DL = MI.getDebugLoc();
5897 bool IsLDAT = MI.getOpcode() == PPC::LDAT_CSNE_PSEUDO;
5898
5899 Register DstReg = MI.getOperand(i: 0).getReg();
5900 Register PtrReg = MI.getOperand(i: 1).getReg();
5901
5902 Register ScratchReg = PtrReg;
5903 if (PtrReg == PPC::X8 || PtrReg == PPC::X9 || PtrReg == PPC::X10) {
5904 // If ptr is in X8/X9/X10, use $dst as scratch to move ptr away from
5905 // X8/X9/X10 since lwat FC=16 always writes its result to X8. After lwat
5906 // copy X8 into $dst.
5907 Register DstReg64 = IsLDAT ? DstReg
5908 : Register(RI.getMatchingSuperReg(
5909 Reg: DstReg, SubIdx: PPC::sub_32, RC: &PPC::G8RCRegClass));
5910 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: PPC::OR8), DestReg: DstReg64).addReg(RegNo: PtrReg).addReg(RegNo: PtrReg);
5911 ScratchReg = DstReg64;
5912 }
5913
5914 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: IsLDAT ? PPC::LDAT_CSNE : PPC::LWAT_CSNE), DestReg: PPC::X8)
5915 .addReg(RegNo: ScratchReg)
5916 .addReg(RegNo: PPC::X9, Flags: RegState::Implicit)
5917 .addReg(RegNo: PPC::X10, Flags: RegState::Implicit);
5918
5919 if (DstReg != (IsLDAT ? PPC::X8 : PPC::R8)) {
5920 BuildMI(BB&: MBB, I&: MI, MIMD: DL, MCID: get(Opcode: IsLDAT ? PPC::OR8 : PPC::OR), DestReg: DstReg)
5921 .addReg(RegNo: IsLDAT ? PPC::X8 : PPC::R8)
5922 .addReg(RegNo: IsLDAT ? PPC::X8 : PPC::R8);
5923 }
5924 MI.eraseFromParent();
5925 return true;
5926}
5927