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