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