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