1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
13 //===----------------------------------------------------------------------===//
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 #define DEBUG_TYPE "ppc-codegen"
41 // FIXME: Remove this once the bug has been fixed!
42 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
43 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
46 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
47 cl::desc("use aggressive ppc isel for bit permutations"),
49 static cl::opt<bool> BPermRewriterNoMasking(
50 "ppc-bit-perm-rewriter-stress-rotates",
51 cl::desc("stress rotate selection in aggressive ppc isel for "
56 void initializePPCDAGToDAGISelPass(PassRegistry&);
60 //===--------------------------------------------------------------------===//
61 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
62 /// instructions for SelectionDAG operations.
64 class PPCDAGToDAGISel : public SelectionDAGISel {
65 const PPCTargetMachine &TM;
66 const PPCSubtarget *PPCSubTarget;
67 const PPCTargetLowering *PPCLowering;
68 unsigned GlobalBaseReg;
70 explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
71 : SelectionDAGISel(tm), TM(tm) {
72 initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
75 bool runOnMachineFunction(MachineFunction &MF) override {
76 // Make sure we re-emit a set of the global base reg if necessary
78 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
79 PPCLowering = PPCSubTarget->getTargetLowering();
80 SelectionDAGISel::runOnMachineFunction(MF);
82 if (!PPCSubTarget->isSVR4ABI())
88 void PreprocessISelDAG() override;
89 void PostprocessISelDAG() override;
91 /// getI32Imm - Return a target constant with the specified value, of type
93 inline SDValue getI32Imm(unsigned Imm, SDLoc dl) {
94 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
97 /// getI64Imm - Return a target constant with the specified value, of type
99 inline SDValue getI64Imm(uint64_t Imm, SDLoc dl) {
100 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
103 /// getSmallIPtrImm - Return a target constant of pointer type.
104 inline SDValue getSmallIPtrImm(unsigned Imm, SDLoc dl) {
105 return CurDAG->getTargetConstant(Imm, dl, PPCLowering->getPointerTy());
108 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
109 /// rotate and mask opcode and mask operation.
110 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
111 unsigned &SH, unsigned &MB, unsigned &ME);
113 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
114 /// base register. Return the virtual register that holds this value.
115 SDNode *getGlobalBaseReg();
117 SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
119 // Select - Convert the specified operand from a target-independent to a
120 // target-specific node if it hasn't already been changed.
121 SDNode *Select(SDNode *N) override;
123 SDNode *SelectBitfieldInsert(SDNode *N);
124 SDNode *SelectBitPermutation(SDNode *N);
126 /// SelectCC - Select a comparison of the specified values with the
127 /// specified condition code, returning the CR# of the expression.
128 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
130 /// SelectAddrImm - Returns true if the address N can be represented by
131 /// a base register plus a signed 16-bit displacement [r+imm].
132 bool SelectAddrImm(SDValue N, SDValue &Disp,
134 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
137 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
138 /// immediate field. Note that the operand at this point is already the
139 /// result of a prior SelectAddressRegImm call.
140 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
141 if (N.getOpcode() == ISD::TargetConstant ||
142 N.getOpcode() == ISD::TargetGlobalAddress) {
150 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
151 /// represented as an indexed [r+r] operation. Returns false if it can
152 /// be represented by [r+imm], which are preferred.
153 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
154 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
157 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
158 /// represented as an indexed [r+r] operation.
159 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
160 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
163 /// SelectAddrImmX4 - Returns true if the address N can be represented by
164 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
165 /// Suitable for use by STD and friends.
166 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
167 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
170 // Select an address into a single register.
171 bool SelectAddr(SDValue N, SDValue &Base) {
176 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
177 /// inline asm expressions. It is always correct to compute the value into
178 /// a register. The case of adding a (possibly relocatable) constant to a
179 /// register can be improved, but it is wrong to substitute Reg+Reg for
180 /// Reg in an asm, because the load or store opcode would have to change.
181 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
182 unsigned ConstraintID,
183 std::vector<SDValue> &OutOps) override {
185 switch(ConstraintID) {
187 errs() << "ConstraintID: " << ConstraintID << "\n";
188 llvm_unreachable("Unexpected asm memory constraint");
189 case InlineAsm::Constraint_es:
190 case InlineAsm::Constraint_i:
191 case InlineAsm::Constraint_m:
192 case InlineAsm::Constraint_o:
193 case InlineAsm::Constraint_Q:
194 case InlineAsm::Constraint_Z:
195 case InlineAsm::Constraint_Zy:
196 // We need to make sure that this one operand does not end up in r0
197 // (because we might end up lowering this as 0(%op)).
198 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
199 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
201 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
203 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
204 dl, Op.getValueType(),
207 OutOps.push_back(NewOp);
213 void InsertVRSaveCode(MachineFunction &MF);
215 const char *getPassName() const override {
216 return "PowerPC DAG->DAG Pattern Instruction Selection";
219 // Include the pieces autogenerated from the target description.
220 #include "PPCGenDAGISel.inc"
223 SDNode *SelectSETCC(SDNode *N);
225 void PeepholePPC64();
226 void PeepholePPC64ZExt();
227 void PeepholeCROps();
229 SDValue combineToCMPB(SDNode *N);
230 void foldBoolExts(SDValue &Res, SDNode *&N);
232 bool AllUsersSelectZero(SDNode *N);
233 void SwapAllSelectUsers(SDNode *N);
235 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
239 /// InsertVRSaveCode - Once the entire function has been instruction selected,
240 /// all virtual registers are created and all machine instructions are built,
241 /// check to see if we need to save/restore VRSAVE. If so, do it.
242 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
243 // Check to see if this function uses vector registers, which means we have to
244 // save and restore the VRSAVE register and update it with the regs we use.
246 // In this case, there will be virtual registers of vector type created
247 // by the scheduler. Detect them now.
248 bool HasVectorVReg = false;
249 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
250 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
251 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
252 HasVectorVReg = true;
256 if (!HasVectorVReg) return; // nothing to do.
258 // If we have a vector register, we want to emit code into the entry and exit
259 // blocks to save and restore the VRSAVE register. We do this here (instead
260 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
262 // 1. This (trivially) reduces the load on the register allocator, by not
263 // having to represent the live range of the VRSAVE register.
264 // 2. This (more significantly) allows us to create a temporary virtual
265 // register to hold the saved VRSAVE value, allowing this temporary to be
266 // register allocated, instead of forcing it to be spilled to the stack.
268 // Create two vregs - one to hold the VRSAVE register that is live-in to the
269 // function and one for the value after having bits or'd into it.
270 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
271 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
273 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
274 MachineBasicBlock &EntryBB = *Fn.begin();
276 // Emit the following code into the entry block:
277 // InVRSAVE = MFVRSAVE
278 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
279 // MTVRSAVE UpdatedVRSAVE
280 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
281 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
282 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
283 UpdatedVRSAVE).addReg(InVRSAVE);
284 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
286 // Find all return blocks, outputting a restore in each epilog.
287 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
288 if (!BB->empty() && BB->back().isReturn()) {
289 IP = BB->end(); --IP;
291 // Skip over all terminator instructions, which are part of the return
293 MachineBasicBlock::iterator I2 = IP;
294 while (I2 != BB->begin() && (--I2)->isTerminator())
297 // Emit: MTVRSAVE InVRSave
298 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
304 /// getGlobalBaseReg - Output the instructions required to put the
305 /// base address to use for accessing globals into a register.
307 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
308 if (!GlobalBaseReg) {
309 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
310 // Insert the set of GlobalBaseReg into the first MBB of the function
311 MachineBasicBlock &FirstMBB = MF->front();
312 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
313 const Module *M = MF->getFunction()->getParent();
316 if (PPCLowering->getPointerTy() == MVT::i32) {
317 if (PPCSubTarget->isTargetELF()) {
318 GlobalBaseReg = PPC::R30;
319 if (M->getPICLevel() == PICLevel::Small) {
320 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
321 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
322 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
324 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
325 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
326 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
327 BuildMI(FirstMBB, MBBI, dl,
328 TII.get(PPC::UpdateGBR), GlobalBaseReg)
329 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
330 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
334 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
335 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
336 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
339 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
340 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
341 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
344 return CurDAG->getRegister(GlobalBaseReg,
345 PPCLowering->getPointerTy()).getNode();
348 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
349 /// or 64-bit immediate, and if the value can be accurately represented as a
350 /// sign extension from a 16-bit value. If so, this returns true and the
352 static bool isIntS16Immediate(SDNode *N, short &Imm) {
353 if (N->getOpcode() != ISD::Constant)
356 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
357 if (N->getValueType(0) == MVT::i32)
358 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
360 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
363 static bool isIntS16Immediate(SDValue Op, short &Imm) {
364 return isIntS16Immediate(Op.getNode(), Imm);
368 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
369 /// operand. If so Imm will receive the 32-bit value.
370 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
371 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
372 Imm = cast<ConstantSDNode>(N)->getZExtValue();
378 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
379 /// operand. If so Imm will receive the 64-bit value.
380 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
381 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
382 Imm = cast<ConstantSDNode>(N)->getZExtValue();
388 // isInt32Immediate - This method tests to see if a constant operand.
389 // If so Imm will receive the 32 bit value.
390 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
391 return isInt32Immediate(N.getNode(), Imm);
395 // isOpcWithIntImmediate - This method tests to see if the node is a specific
396 // opcode and that it has a immediate integer right operand.
397 // If so Imm will receive the 32 bit value.
398 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
399 return N->getOpcode() == Opc
400 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
403 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
405 int FI = cast<FrameIndexSDNode>(N)->getIndex();
406 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
407 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
409 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
410 getSmallIPtrImm(Offset, dl));
411 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
412 getSmallIPtrImm(Offset, dl));
415 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
416 bool isShiftMask, unsigned &SH,
417 unsigned &MB, unsigned &ME) {
418 // Don't even go down this path for i64, since different logic will be
419 // necessary for rldicl/rldicr/rldimi.
420 if (N->getValueType(0) != MVT::i32)
424 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
425 unsigned Opcode = N->getOpcode();
426 if (N->getNumOperands() != 2 ||
427 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
430 if (Opcode == ISD::SHL) {
431 // apply shift left to mask if it comes first
432 if (isShiftMask) Mask = Mask << Shift;
433 // determine which bits are made indeterminant by shift
434 Indeterminant = ~(0xFFFFFFFFu << Shift);
435 } else if (Opcode == ISD::SRL) {
436 // apply shift right to mask if it comes first
437 if (isShiftMask) Mask = Mask >> Shift;
438 // determine which bits are made indeterminant by shift
439 Indeterminant = ~(0xFFFFFFFFu >> Shift);
440 // adjust for the left rotate
442 } else if (Opcode == ISD::ROTL) {
448 // if the mask doesn't intersect any Indeterminant bits
449 if (Mask && !(Mask & Indeterminant)) {
451 // make sure the mask is still a mask (wrap arounds may not be)
452 return isRunOfOnes(Mask, MB, ME);
457 /// SelectBitfieldInsert - turn an or of two masked values into
458 /// the rotate left word immediate then mask insert (rlwimi) instruction.
459 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
460 SDValue Op0 = N->getOperand(0);
461 SDValue Op1 = N->getOperand(1);
464 APInt LKZ, LKO, RKZ, RKO;
465 CurDAG->computeKnownBits(Op0, LKZ, LKO);
466 CurDAG->computeKnownBits(Op1, RKZ, RKO);
468 unsigned TargetMask = LKZ.getZExtValue();
469 unsigned InsertMask = RKZ.getZExtValue();
471 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
472 unsigned Op0Opc = Op0.getOpcode();
473 unsigned Op1Opc = Op1.getOpcode();
474 unsigned Value, SH = 0;
475 TargetMask = ~TargetMask;
476 InsertMask = ~InsertMask;
478 // If the LHS has a foldable shift and the RHS does not, then swap it to the
479 // RHS so that we can fold the shift into the insert.
480 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
481 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
482 Op0.getOperand(0).getOpcode() == ISD::SRL) {
483 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
484 Op1.getOperand(0).getOpcode() != ISD::SRL) {
486 std::swap(Op0Opc, Op1Opc);
487 std::swap(TargetMask, InsertMask);
490 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
491 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
492 Op1.getOperand(0).getOpcode() != ISD::SRL) {
494 std::swap(Op0Opc, Op1Opc);
495 std::swap(TargetMask, InsertMask);
500 if (isRunOfOnes(InsertMask, MB, ME)) {
503 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
504 isInt32Immediate(Op1.getOperand(1), Value)) {
505 Op1 = Op1.getOperand(0);
506 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
508 if (Op1Opc == ISD::AND) {
509 // The AND mask might not be a constant, and we need to make sure that
510 // if we're going to fold the masking with the insert, all bits not
511 // know to be zero in the mask are known to be one.
513 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
514 bool CanFoldMask = InsertMask == MKO.getZExtValue();
516 unsigned SHOpc = Op1.getOperand(0).getOpcode();
517 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
518 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
519 // Note that Value must be in range here (less than 32) because
520 // otherwise there would not be any bits set in InsertMask.
521 Op1 = Op1.getOperand(0).getOperand(0);
522 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
527 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
529 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
535 // Predict the number of instructions that would be generated by calling
537 static unsigned SelectInt64CountDirect(int64_t Imm) {
538 // Assume no remaining bits.
539 unsigned Remainder = 0;
540 // Assume no shift required.
543 // If it can't be represented as a 32 bit value.
544 if (!isInt<32>(Imm)) {
545 Shift = countTrailingZeros<uint64_t>(Imm);
546 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
548 // If the shifted value fits 32 bits.
549 if (isInt<32>(ImmSh)) {
550 // Go with the shifted value.
553 // Still stuck with a 64 bit value.
560 // Intermediate operand.
563 // Handle first 32 bits.
564 unsigned Lo = Imm & 0xFFFF;
565 unsigned Hi = (Imm >> 16) & 0xFFFF;
568 if (isInt<16>(Imm)) {
572 // Handle the Hi bits and Lo bits.
579 // If no shift, we're done.
580 if (!Shift) return Result;
582 // Shift for next step if the upper 32-bits were not zero.
586 // Add in the last bits as required.
587 if ((Hi = (Remainder >> 16) & 0xFFFF))
589 if ((Lo = Remainder & 0xFFFF))
595 static uint64_t Rot64(uint64_t Imm, unsigned R) {
596 return (Imm << R) | (Imm >> (64 - R));
599 static unsigned SelectInt64Count(int64_t Imm) {
600 unsigned Count = SelectInt64CountDirect(Imm);
604 for (unsigned r = 1; r < 63; ++r) {
605 uint64_t RImm = Rot64(Imm, r);
606 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
607 Count = std::min(Count, RCount);
609 // See comments in SelectInt64 for an explanation of the logic below.
610 unsigned LS = findLastSet(RImm);
614 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
615 uint64_t RImmWithOnes = RImm | OnesMask;
617 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
618 Count = std::min(Count, RCount);
624 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
625 // (above) needs to be kept in sync with this function.
626 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
627 // Assume no remaining bits.
628 unsigned Remainder = 0;
629 // Assume no shift required.
632 // If it can't be represented as a 32 bit value.
633 if (!isInt<32>(Imm)) {
634 Shift = countTrailingZeros<uint64_t>(Imm);
635 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
637 // If the shifted value fits 32 bits.
638 if (isInt<32>(ImmSh)) {
639 // Go with the shifted value.
642 // Still stuck with a 64 bit value.
649 // Intermediate operand.
652 // Handle first 32 bits.
653 unsigned Lo = Imm & 0xFFFF;
654 unsigned Hi = (Imm >> 16) & 0xFFFF;
656 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
657 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
661 if (isInt<16>(Imm)) {
663 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
665 // Handle the Hi bits.
666 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
667 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
669 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
670 SDValue(Result, 0), getI32Imm(Lo));
673 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
676 // If no shift, we're done.
677 if (!Shift) return Result;
679 // Shift for next step if the upper 32-bits were not zero.
681 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
684 getI32Imm(63 - Shift));
687 // Add in the last bits as required.
688 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
689 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
690 SDValue(Result, 0), getI32Imm(Hi));
692 if ((Lo = Remainder & 0xFFFF)) {
693 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
694 SDValue(Result, 0), getI32Imm(Lo));
700 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
701 unsigned Count = SelectInt64CountDirect(Imm);
703 return SelectInt64Direct(CurDAG, dl, Imm);
710 for (unsigned r = 1; r < 63; ++r) {
711 uint64_t RImm = Rot64(Imm, r);
712 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
713 if (RCount < Count) {
720 // If the immediate to generate has many trailing zeros, it might be
721 // worthwhile to generate a rotated value with too many leading ones
722 // (because that's free with li/lis's sign-extension semantics), and then
723 // mask them off after rotation.
725 unsigned LS = findLastSet(RImm);
726 // We're adding (63-LS) higher-order ones, and we expect to mask them off
727 // after performing the inverse rotation by (64-r). So we need that:
728 // 63-LS == 64-r => LS == r-1
732 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
733 uint64_t RImmWithOnes = RImm | OnesMask;
735 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
736 if (RCount < Count) {
739 MatImm = RImmWithOnes;
745 return SelectInt64Direct(CurDAG, dl, Imm);
747 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
748 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
751 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
752 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
753 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
756 // Select a 64-bit constant.
757 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
761 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
762 return SelectInt64(CurDAG, dl, Imm);
766 class BitPermutationSelector {
770 // The bit number in the value, using a convention where bit 0 is the
779 ValueBit(SDValue V, unsigned I, Kind K = Variable)
780 : V(V), Idx(I), K(K) {}
781 ValueBit(Kind K = Variable)
782 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
784 bool isZero() const {
785 return K == ConstZero;
788 bool hasValue() const {
789 return K == Variable;
792 SDValue getValue() const {
793 assert(hasValue() && "Cannot get the value of a constant bit");
797 unsigned getValueBitIndex() const {
798 assert(hasValue() && "Cannot get the value bit index of a constant bit");
803 // A bit group has the same underlying value and the same rotate factor.
807 unsigned StartIdx, EndIdx;
809 // This rotation amount assumes that the lower 32 bits of the quantity are
810 // replicated in the high 32 bits by the rotation operator (which is done
811 // by rlwinm and friends in 64-bit mode).
813 // Did converting to Repl32 == true change the rotation factor? If it did,
814 // it decreased it by 32.
816 // Was this group coalesced after setting Repl32 to true?
817 bool Repl32Coalesced;
819 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
820 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
821 Repl32Coalesced(false) {
822 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
823 " [" << S << ", " << E << "]\n");
827 // Information on each (Value, RLAmt) pair (like the number of groups
828 // associated with each) used to choose the lowering method.
829 struct ValueRotInfo {
833 unsigned FirstGroupStartIdx;
837 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
840 // For sorting (in reverse order) by NumGroups, and then by
841 // FirstGroupStartIdx.
842 bool operator < (const ValueRotInfo &Other) const {
843 // We need to sort so that the non-Repl32 come first because, when we're
844 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
845 // masking operation.
846 if (Repl32 < Other.Repl32)
848 else if (Repl32 > Other.Repl32)
850 else if (NumGroups > Other.NumGroups)
852 else if (NumGroups < Other.NumGroups)
854 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
860 // Return true if something interesting was deduced, return false if we're
861 // providing only a generic representation of V (or something else likewise
862 // uninteresting for instruction selection).
863 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
864 switch (V.getOpcode()) {
867 if (isa<ConstantSDNode>(V.getOperand(1))) {
868 unsigned RotAmt = V.getConstantOperandVal(1);
870 SmallVector<ValueBit, 64> LHSBits(Bits.size());
871 getValueBits(V.getOperand(0), LHSBits);
873 for (unsigned i = 0; i < Bits.size(); ++i)
874 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
880 if (isa<ConstantSDNode>(V.getOperand(1))) {
881 unsigned ShiftAmt = V.getConstantOperandVal(1);
883 SmallVector<ValueBit, 64> LHSBits(Bits.size());
884 getValueBits(V.getOperand(0), LHSBits);
886 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
887 Bits[i] = LHSBits[i - ShiftAmt];
889 for (unsigned i = 0; i < ShiftAmt; ++i)
890 Bits[i] = ValueBit(ValueBit::ConstZero);
896 if (isa<ConstantSDNode>(V.getOperand(1))) {
897 unsigned ShiftAmt = V.getConstantOperandVal(1);
899 SmallVector<ValueBit, 64> LHSBits(Bits.size());
900 getValueBits(V.getOperand(0), LHSBits);
902 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
903 Bits[i] = LHSBits[i + ShiftAmt];
905 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
906 Bits[i] = ValueBit(ValueBit::ConstZero);
912 if (isa<ConstantSDNode>(V.getOperand(1))) {
913 uint64_t Mask = V.getConstantOperandVal(1);
915 SmallVector<ValueBit, 64> LHSBits(Bits.size());
916 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
918 for (unsigned i = 0; i < Bits.size(); ++i)
919 if (((Mask >> i) & 1) == 1)
920 Bits[i] = LHSBits[i];
922 Bits[i] = ValueBit(ValueBit::ConstZero);
924 // Mark this as interesting, only if the LHS was also interesting. This
925 // prevents the overall procedure from matching a single immediate 'and'
926 // (which is non-optimal because such an and might be folded with other
927 // things if we don't select it here).
932 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
933 getValueBits(V.getOperand(0), LHSBits);
934 getValueBits(V.getOperand(1), RHSBits);
936 bool AllDisjoint = true;
937 for (unsigned i = 0; i < Bits.size(); ++i)
938 if (LHSBits[i].isZero())
939 Bits[i] = RHSBits[i];
940 else if (RHSBits[i].isZero())
941 Bits[i] = LHSBits[i];
954 for (unsigned i = 0; i < Bits.size(); ++i)
955 Bits[i] = ValueBit(V, i);
960 // For each value (except the constant ones), compute the left-rotate amount
961 // to get it from its original to final position.
962 void computeRotationAmounts() {
964 RLAmt.resize(Bits.size());
965 for (unsigned i = 0; i < Bits.size(); ++i)
966 if (Bits[i].hasValue()) {
967 unsigned VBI = Bits[i].getValueBitIndex();
971 RLAmt[i] = Bits.size() - (VBI - i);
972 } else if (Bits[i].isZero()) {
974 RLAmt[i] = UINT32_MAX;
976 llvm_unreachable("Unknown value bit type");
980 // Collect groups of consecutive bits with the same underlying value and
981 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
982 // they break up groups.
983 void collectBitGroups(bool LateMask) {
986 unsigned LastRLAmt = RLAmt[0];
987 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
988 unsigned LastGroupStartIdx = 0;
989 for (unsigned i = 1; i < Bits.size(); ++i) {
990 unsigned ThisRLAmt = RLAmt[i];
991 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
992 if (LateMask && !ThisValue) {
993 ThisValue = LastValue;
994 ThisRLAmt = LastRLAmt;
995 // If we're doing late masking, then the first bit group always starts
996 // at zero (even if the first bits were zero).
997 if (BitGroups.empty())
998 LastGroupStartIdx = 0;
1001 // If this bit has the same underlying value and the same rotate factor as
1002 // the last one, then they're part of the same group.
1003 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1006 if (LastValue.getNode())
1007 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1009 LastRLAmt = ThisRLAmt;
1010 LastValue = ThisValue;
1011 LastGroupStartIdx = i;
1013 if (LastValue.getNode())
1014 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1017 if (BitGroups.empty())
1020 // We might be able to combine the first and last groups.
1021 if (BitGroups.size() > 1) {
1022 // If the first and last groups are the same, then remove the first group
1023 // in favor of the last group, making the ending index of the last group
1024 // equal to the ending index of the to-be-removed first group.
1025 if (BitGroups[0].StartIdx == 0 &&
1026 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1027 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1028 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1029 DEBUG(dbgs() << "\tcombining final bit group with inital one\n");
1030 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1031 BitGroups.erase(BitGroups.begin());
1036 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1037 // associated with each. If there is a degeneracy, pick the one that occurs
1038 // first (in the final value).
1039 void collectValueRotInfo() {
1042 for (auto &BG : BitGroups) {
1043 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1044 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1046 VRI.RLAmt = BG.RLAmt;
1047 VRI.Repl32 = BG.Repl32;
1049 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1052 // Now that we've collected the various ValueRotInfo instances, we need to
1054 ValueRotsVec.clear();
1055 for (auto &I : ValueRots) {
1056 ValueRotsVec.push_back(I.second);
1058 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1061 // In 64-bit mode, rlwinm and friends have a rotation operator that
1062 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1063 // indices of these instructions can only be in the lower 32 bits, so they
1064 // can only represent some 64-bit bit groups. However, when they can be used,
1065 // the 32-bit replication can be used to represent, as a single bit group,
1066 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1067 // groups when possible. Returns true if any of the bit groups were
1069 void assignRepl32BitGroups() {
1070 // If we have bits like this:
1072 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1073 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1074 // Groups: | RLAmt = 8 | RLAmt = 40 |
1076 // But, making use of a 32-bit operation that replicates the low-order 32
1077 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1080 auto IsAllLow32 = [this](BitGroup & BG) {
1081 if (BG.StartIdx <= BG.EndIdx) {
1082 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1083 if (!Bits[i].hasValue())
1085 if (Bits[i].getValueBitIndex() >= 32)
1089 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1090 if (!Bits[i].hasValue())
1092 if (Bits[i].getValueBitIndex() >= 32)
1095 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1096 if (!Bits[i].hasValue())
1098 if (Bits[i].getValueBitIndex() >= 32)
1106 for (auto &BG : BitGroups) {
1107 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1108 if (IsAllLow32(BG)) {
1109 if (BG.RLAmt >= 32) {
1116 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1117 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1118 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1123 // Now walk through the bit groups, consolidating where possible.
1124 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1125 // We might want to remove this bit group by merging it with the previous
1126 // group (which might be the ending group).
1127 auto IP = (I == BitGroups.begin()) ?
1128 std::prev(BitGroups.end()) : std::prev(I);
1129 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1130 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1132 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1133 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1134 " [" << I->StartIdx << ", " << I->EndIdx <<
1135 "] with group with range [" <<
1136 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1138 IP->EndIdx = I->EndIdx;
1139 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1140 IP->Repl32Coalesced = true;
1141 I = BitGroups.erase(I);
1144 // There is a special case worth handling: If there is a single group
1145 // covering the entire upper 32 bits, and it can be merged with both
1146 // the next and previous groups (which might be the same group), then
1147 // do so. If it is the same group (so there will be only one group in
1148 // total), then we need to reverse the order of the range so that it
1149 // covers the entire 64 bits.
1150 if (I->StartIdx == 32 && I->EndIdx == 63) {
1151 assert(std::next(I) == BitGroups.end() &&
1152 "bit group ends at index 63 but there is another?");
1153 auto IN = BitGroups.begin();
1155 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1156 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1157 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1160 DEBUG(dbgs() << "\tcombining bit group for " <<
1161 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1162 " [" << I->StartIdx << ", " << I->EndIdx <<
1163 "] with 32-bit replicated groups with ranges [" <<
1164 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1165 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1168 // There is only one other group; change it to cover the whole
1169 // range (backward, so that it can still be Repl32 but cover the
1170 // whole 64-bit range).
1173 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1174 IP->Repl32Coalesced = true;
1175 I = BitGroups.erase(I);
1177 // There are two separate groups, one before this group and one
1178 // after us (at the beginning). We're going to remove this group,
1179 // but also the group at the very beginning.
1180 IP->EndIdx = IN->EndIdx;
1181 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1182 IP->Repl32Coalesced = true;
1183 I = BitGroups.erase(I);
1184 BitGroups.erase(BitGroups.begin());
1187 // This must be the last group in the vector (and we might have
1188 // just invalidated the iterator above), so break here.
1198 SDValue getI32Imm(unsigned Imm, SDLoc dl) {
1199 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1202 uint64_t getZerosMask() {
1204 for (unsigned i = 0; i < Bits.size(); ++i) {
1205 if (Bits[i].hasValue())
1207 Mask |= (UINT64_C(1) << i);
1213 // Depending on the number of groups for a particular value, it might be
1214 // better to rotate, mask explicitly (using andi/andis), and then or the
1215 // result. Select this part of the result first.
1216 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1217 if (BPermRewriterNoMasking)
1220 for (ValueRotInfo &VRI : ValueRotsVec) {
1222 for (unsigned i = 0; i < Bits.size(); ++i) {
1223 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1225 if (RLAmt[i] != VRI.RLAmt)
1230 // Compute the masks for andi/andis that would be necessary.
1231 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1232 assert((ANDIMask != 0 || ANDISMask != 0) &&
1233 "No set bits in mask for value bit groups");
1234 bool NeedsRotate = VRI.RLAmt != 0;
1236 // We're trying to minimize the number of instructions. If we have one
1237 // group, using one of andi/andis can break even. If we have three
1238 // groups, we can use both andi and andis and break even (to use both
1239 // andi and andis we also need to or the results together). We need four
1240 // groups if we also need to rotate. To use andi/andis we need to do more
1241 // than break even because rotate-and-mask instructions tend to be easier
1244 // FIXME: We've biased here against using andi/andis, which is right for
1245 // POWER cores, but not optimal everywhere. For example, on the A2,
1246 // andi/andis have single-cycle latency whereas the rotate-and-mask
1247 // instructions take two cycles, and it would be better to bias toward
1248 // andi/andis in break-even cases.
1250 unsigned NumAndInsts = (unsigned) NeedsRotate +
1251 (unsigned) (ANDIMask != 0) +
1252 (unsigned) (ANDISMask != 0) +
1253 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1254 (unsigned) (bool) Res;
1256 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1257 " RL: " << VRI.RLAmt << ":" <<
1258 "\n\t\t\tisel using masking: " << NumAndInsts <<
1259 " using rotates: " << VRI.NumGroups << "\n");
1261 if (NumAndInsts >= VRI.NumGroups)
1264 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1266 if (InstCnt) *InstCnt += NumAndInsts;
1271 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1272 getI32Imm(31, dl) };
1273 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1279 SDValue ANDIVal, ANDISVal;
1281 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1282 VRot, getI32Imm(ANDIMask, dl)), 0);
1284 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1285 VRot, getI32Imm(ANDISMask, dl)), 0);
1289 TotalVal = ANDISVal;
1293 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1294 ANDIVal, ANDISVal), 0);
1299 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1302 // Now, remove all groups with this underlying value and rotation
1304 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1305 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1306 I = BitGroups.erase(I);
1313 // Instruction selection for the 32-bit case.
1314 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1318 if (InstCnt) *InstCnt = 0;
1320 // Take care of cases that should use andi/andis first.
1321 SelectAndParts32(dl, Res, InstCnt);
1323 // If we've not yet selected a 'starting' instruction, and we have no zeros
1324 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1325 // number of groups), and start with this rotated value.
1326 if ((!HasZeros || LateMask) && !Res) {
1327 ValueRotInfo &VRI = ValueRotsVec[0];
1329 if (InstCnt) *InstCnt += 1;
1331 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1332 getI32Imm(31, dl) };
1333 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1339 // Now, remove all groups with this underlying value and rotation factor.
1340 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1341 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1342 I = BitGroups.erase(I);
1348 if (InstCnt) *InstCnt += BitGroups.size();
1350 // Insert the other groups (one at a time).
1351 for (auto &BG : BitGroups) {
1354 { BG.V, getI32Imm(BG.RLAmt, dl),
1355 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1356 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1357 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1360 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1361 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1362 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1363 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1368 unsigned Mask = (unsigned) getZerosMask();
1370 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1371 assert((ANDIMask != 0 || ANDISMask != 0) &&
1372 "No set bits in zeros mask?");
1374 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1375 (unsigned) (ANDISMask != 0) +
1376 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1378 SDValue ANDIVal, ANDISVal;
1380 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1381 Res, getI32Imm(ANDIMask, dl)), 0);
1383 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1384 Res, getI32Imm(ANDISMask, dl)), 0);
1391 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1392 ANDIVal, ANDISVal), 0);
1395 return Res.getNode();
1398 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1399 unsigned MaskStart, unsigned MaskEnd,
1401 // In the notation used by the instructions, 'start' and 'end' are reversed
1402 // because bits are counted from high to low order.
1403 unsigned InstMaskStart = 64 - MaskEnd - 1,
1404 InstMaskEnd = 64 - MaskStart - 1;
1409 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1410 InstMaskEnd == 63 - RLAmt)
1416 // For 64-bit values, not all combinations of rotates and masks are
1417 // available. Produce one if it is available.
1418 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1419 unsigned MaskStart, unsigned MaskEnd,
1420 unsigned *InstCnt = nullptr) {
1421 // In the notation used by the instructions, 'start' and 'end' are reversed
1422 // because bits are counted from high to low order.
1423 unsigned InstMaskStart = 64 - MaskEnd - 1,
1424 InstMaskEnd = 64 - MaskStart - 1;
1426 if (InstCnt) *InstCnt += 1;
1429 // This rotation amount assumes that the lower 32 bits of the quantity
1430 // are replicated in the high 32 bits by the rotation operator (which is
1431 // done by rlwinm and friends).
1432 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1433 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1435 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1436 getI32Imm(InstMaskEnd - 32, dl) };
1437 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1441 if (InstMaskEnd == 63) {
1443 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1444 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1447 if (InstMaskStart == 0) {
1449 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1450 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1453 if (InstMaskEnd == 63 - RLAmt) {
1455 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1456 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1459 // We cannot do this with a single instruction, so we'll use two. The
1460 // problem is that we're not free to choose both a rotation amount and mask
1461 // start and end independently. We can choose an arbitrary mask start and
1462 // end, but then the rotation amount is fixed. Rotation, however, can be
1463 // inverted, and so by applying an "inverse" rotation first, we can get the
1465 if (InstCnt) *InstCnt += 1;
1467 // The rotation mask for the second instruction must be MaskStart.
1468 unsigned RLAmt2 = MaskStart;
1469 // The first instruction must rotate V so that the overall rotation amount
1471 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1473 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1474 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1477 // For 64-bit values, not all combinations of rotates and masks are
1478 // available. Produce a rotate-mask-and-insert if one is available.
1479 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1480 bool Repl32, unsigned MaskStart,
1481 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1482 // In the notation used by the instructions, 'start' and 'end' are reversed
1483 // because bits are counted from high to low order.
1484 unsigned InstMaskStart = 64 - MaskEnd - 1,
1485 InstMaskEnd = 64 - MaskStart - 1;
1487 if (InstCnt) *InstCnt += 1;
1490 // This rotation amount assumes that the lower 32 bits of the quantity
1491 // are replicated in the high 32 bits by the rotation operator (which is
1492 // done by rlwinm and friends).
1493 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1494 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1496 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1497 getI32Imm(InstMaskEnd - 32, dl) };
1498 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1502 if (InstMaskEnd == 63 - RLAmt) {
1504 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1505 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1508 // We cannot do this with a single instruction, so we'll use two. The
1509 // problem is that we're not free to choose both a rotation amount and mask
1510 // start and end independently. We can choose an arbitrary mask start and
1511 // end, but then the rotation amount is fixed. Rotation, however, can be
1512 // inverted, and so by applying an "inverse" rotation first, we can get the
1514 if (InstCnt) *InstCnt += 1;
1516 // The rotation mask for the second instruction must be MaskStart.
1517 unsigned RLAmt2 = MaskStart;
1518 // The first instruction must rotate V so that the overall rotation amount
1520 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1522 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1523 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1526 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1527 if (BPermRewriterNoMasking)
1530 // The idea here is the same as in the 32-bit version, but with additional
1531 // complications from the fact that Repl32 might be true. Because we
1532 // aggressively convert bit groups to Repl32 form (which, for small
1533 // rotation factors, involves no other change), and then coalesce, it might
1534 // be the case that a single 64-bit masking operation could handle both
1535 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1536 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1537 // completely capture the new combined bit group.
1539 for (ValueRotInfo &VRI : ValueRotsVec) {
1542 // We need to add to the mask all bits from the associated bit groups.
1543 // If Repl32 is false, we need to add bits from bit groups that have
1544 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1545 // group is trivially convertable if it overlaps only with the lower 32
1546 // bits, and the group has not been coalesced.
1547 auto MatchingBG = [VRI](BitGroup &BG) {
1551 unsigned EffRLAmt = BG.RLAmt;
1552 if (!VRI.Repl32 && BG.Repl32) {
1553 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1554 !BG.Repl32Coalesced) {
1560 } else if (VRI.Repl32 != BG.Repl32) {
1564 if (VRI.RLAmt != EffRLAmt)
1570 for (auto &BG : BitGroups) {
1571 if (!MatchingBG(BG))
1574 if (BG.StartIdx <= BG.EndIdx) {
1575 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1576 Mask |= (UINT64_C(1) << i);
1578 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1579 Mask |= (UINT64_C(1) << i);
1580 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1581 Mask |= (UINT64_C(1) << i);
1585 // We can use the 32-bit andi/andis technique if the mask does not
1586 // require any higher-order bits. This can save an instruction compared
1587 // to always using the general 64-bit technique.
1588 bool Use32BitInsts = isUInt<32>(Mask);
1589 // Compute the masks for andi/andis that would be necessary.
1590 unsigned ANDIMask = (Mask & UINT16_MAX),
1591 ANDISMask = (Mask >> 16) & UINT16_MAX;
1593 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1595 unsigned NumAndInsts = (unsigned) NeedsRotate +
1596 (unsigned) (bool) Res;
1598 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1599 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1601 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1603 unsigned NumRLInsts = 0;
1604 bool FirstBG = true;
1605 for (auto &BG : BitGroups) {
1606 if (!MatchingBG(BG))
1609 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1614 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1615 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1616 "\n\t\t\tisel using masking: " << NumAndInsts <<
1617 " using rotates: " << NumRLInsts << "\n");
1619 // When we'd use andi/andis, we bias toward using the rotates (andi only
1620 // has a record form, and is cracked on POWER cores). However, when using
1621 // general 64-bit constant formation, bias toward the constant form,
1622 // because that exposes more opportunities for CSE.
1623 if (NumAndInsts > NumRLInsts)
1625 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1628 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1630 if (InstCnt) *InstCnt += NumAndInsts;
1633 // We actually need to generate a rotation if we have a non-zero rotation
1634 // factor or, in the Repl32 case, if we care about any of the
1635 // higher-order replicated bits. In the latter case, we generate a mask
1636 // backward so that it actually includes the entire 64 bits.
1637 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1638 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1639 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1644 if (Use32BitInsts) {
1645 assert((ANDIMask != 0 || ANDISMask != 0) &&
1646 "No set bits in mask when using 32-bit ands for 64-bit value");
1648 SDValue ANDIVal, ANDISVal;
1650 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1651 VRot, getI32Imm(ANDIMask, dl)), 0);
1653 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1654 VRot, getI32Imm(ANDISMask, dl)), 0);
1657 TotalVal = ANDISVal;
1661 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1662 ANDIVal, ANDISVal), 0);
1664 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1666 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1667 VRot, TotalVal), 0);
1673 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1676 // Now, remove all groups with this underlying value and rotation
1678 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1680 I = BitGroups.erase(I);
1687 // Instruction selection for the 64-bit case.
1688 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1692 if (InstCnt) *InstCnt = 0;
1694 // Take care of cases that should use andi/andis first.
1695 SelectAndParts64(dl, Res, InstCnt);
1697 // If we've not yet selected a 'starting' instruction, and we have no zeros
1698 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1699 // number of groups), and start with this rotated value.
1700 if ((!HasZeros || LateMask) && !Res) {
1701 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1702 // groups will come first, and so the VRI representing the largest number
1703 // of groups might not be first (it might be the first Repl32 groups).
1704 unsigned MaxGroupsIdx = 0;
1705 if (!ValueRotsVec[0].Repl32) {
1706 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1707 if (ValueRotsVec[i].Repl32) {
1708 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1714 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1715 bool NeedsRotate = false;
1718 } else if (VRI.Repl32) {
1719 for (auto &BG : BitGroups) {
1720 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1721 BG.Repl32 != VRI.Repl32)
1724 // We don't need a rotate if the bit group is confined to the lower
1726 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1735 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1736 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1741 // Now, remove all groups with this underlying value and rotation factor.
1743 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1744 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt && I->Repl32 == VRI.Repl32)
1745 I = BitGroups.erase(I);
1751 // Because 64-bit rotates are more flexible than inserts, we might have a
1752 // preference regarding which one we do first (to save one instruction).
1754 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1755 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1757 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1759 if (I != BitGroups.begin()) {
1762 BitGroups.insert(BitGroups.begin(), BG);
1769 // Insert the other groups (one at a time).
1770 for (auto &BG : BitGroups) {
1772 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1773 BG.EndIdx, InstCnt);
1775 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1776 BG.StartIdx, BG.EndIdx, InstCnt);
1780 uint64_t Mask = getZerosMask();
1782 // We can use the 32-bit andi/andis technique if the mask does not
1783 // require any higher-order bits. This can save an instruction compared
1784 // to always using the general 64-bit technique.
1785 bool Use32BitInsts = isUInt<32>(Mask);
1786 // Compute the masks for andi/andis that would be necessary.
1787 unsigned ANDIMask = (Mask & UINT16_MAX),
1788 ANDISMask = (Mask >> 16) & UINT16_MAX;
1790 if (Use32BitInsts) {
1791 assert((ANDIMask != 0 || ANDISMask != 0) &&
1792 "No set bits in mask when using 32-bit ands for 64-bit value");
1794 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1795 (unsigned) (ANDISMask != 0) +
1796 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1798 SDValue ANDIVal, ANDISVal;
1800 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1801 Res, getI32Imm(ANDIMask, dl)), 0);
1803 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1804 Res, getI32Imm(ANDISMask, dl)), 0);
1811 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1812 ANDIVal, ANDISVal), 0);
1814 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1816 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1818 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1823 return Res.getNode();
1826 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1827 // Fill in BitGroups.
1828 collectBitGroups(LateMask);
1829 if (BitGroups.empty())
1832 // For 64-bit values, figure out when we can use 32-bit instructions.
1833 if (Bits.size() == 64)
1834 assignRepl32BitGroups();
1836 // Fill in ValueRotsVec.
1837 collectValueRotInfo();
1839 if (Bits.size() == 32) {
1840 return Select32(N, LateMask, InstCnt);
1842 assert(Bits.size() == 64 && "Not 64 bits here?");
1843 return Select64(N, LateMask, InstCnt);
1849 SmallVector<ValueBit, 64> Bits;
1852 SmallVector<unsigned, 64> RLAmt;
1854 SmallVector<BitGroup, 16> BitGroups;
1856 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1857 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1859 SelectionDAG *CurDAG;
1862 BitPermutationSelector(SelectionDAG *DAG)
1865 // Here we try to match complex bit permutations into a set of
1866 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1867 // known to produce optimial code for common cases (like i32 byte swapping).
1868 SDNode *Select(SDNode *N) {
1869 Bits.resize(N->getValueType(0).getSizeInBits());
1870 if (!getValueBits(SDValue(N, 0), Bits))
1873 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1874 " selection for: ");
1875 DEBUG(N->dump(CurDAG));
1877 // Fill it RLAmt and set HasZeros.
1878 computeRotationAmounts();
1881 return Select(N, false);
1883 // We currently have two techniques for handling results with zeros: early
1884 // masking (the default) and late masking. Late masking is sometimes more
1885 // efficient, but because the structure of the bit groups is different, it
1886 // is hard to tell without generating both and comparing the results. With
1887 // late masking, we ignore zeros in the resulting value when inserting each
1888 // set of bit groups, and then mask in the zeros at the end. With early
1889 // masking, we only insert the non-zero parts of the result at every step.
1891 unsigned InstCnt, InstCntLateMask;
1892 DEBUG(dbgs() << "\tEarly masking:\n");
1893 SDNode *RN = Select(N, false, &InstCnt);
1894 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1896 DEBUG(dbgs() << "\tLate masking:\n");
1897 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1898 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1901 if (InstCnt <= InstCntLateMask) {
1902 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1906 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1910 } // anonymous namespace
1912 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1913 if (N->getValueType(0) != MVT::i32 &&
1914 N->getValueType(0) != MVT::i64)
1917 if (!UseBitPermRewriter)
1920 switch (N->getOpcode()) {
1927 BitPermutationSelector BPS(CurDAG);
1928 return BPS.Select(N);
1935 /// SelectCC - Select a comparison of the specified values with the specified
1936 /// condition code, returning the CR# of the expression.
1937 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1938 ISD::CondCode CC, SDLoc dl) {
1939 // Always select the LHS.
1942 if (LHS.getValueType() == MVT::i32) {
1944 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1945 if (isInt32Immediate(RHS, Imm)) {
1946 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1947 if (isUInt<16>(Imm))
1948 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1949 getI32Imm(Imm & 0xFFFF, dl)),
1951 // If this is a 16-bit signed immediate, fold it.
1952 if (isInt<16>((int)Imm))
1953 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1954 getI32Imm(Imm & 0xFFFF, dl)),
1957 // For non-equality comparisons, the default code would materialize the
1958 // constant, then compare against it, like this:
1960 // ori r2, r2, 22136
1962 // Since we are just comparing for equality, we can emit this instead:
1963 // xoris r0,r3,0x1234
1964 // cmplwi cr0,r0,0x5678
1966 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1967 getI32Imm(Imm >> 16, dl)), 0);
1968 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1969 getI32Imm(Imm & 0xFFFF, dl)), 0);
1972 } else if (ISD::isUnsignedIntSetCC(CC)) {
1973 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1974 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1975 getI32Imm(Imm & 0xFFFF, dl)), 0);
1979 if (isIntS16Immediate(RHS, SImm))
1980 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1981 getI32Imm((int)SImm & 0xFFFF,
1986 } else if (LHS.getValueType() == MVT::i64) {
1988 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1989 if (isInt64Immediate(RHS.getNode(), Imm)) {
1990 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1991 if (isUInt<16>(Imm))
1992 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1993 getI32Imm(Imm & 0xFFFF, dl)),
1995 // If this is a 16-bit signed immediate, fold it.
1997 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1998 getI32Imm(Imm & 0xFFFF, dl)),
2001 // For non-equality comparisons, the default code would materialize the
2002 // constant, then compare against it, like this:
2004 // ori r2, r2, 22136
2006 // Since we are just comparing for equality, we can emit this instead:
2007 // xoris r0,r3,0x1234
2008 // cmpldi cr0,r0,0x5678
2010 if (isUInt<32>(Imm)) {
2011 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2012 getI64Imm(Imm >> 16, dl)), 0);
2013 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2014 getI64Imm(Imm & 0xFFFF, dl)),
2019 } else if (ISD::isUnsignedIntSetCC(CC)) {
2020 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2021 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2022 getI64Imm(Imm & 0xFFFF, dl)), 0);
2026 if (isIntS16Immediate(RHS, SImm))
2027 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2028 getI64Imm(SImm & 0xFFFF, dl)),
2032 } else if (LHS.getValueType() == MVT::f32) {
2035 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2036 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2038 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2041 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2047 llvm_unreachable("Should be lowered by legalize!");
2048 default: llvm_unreachable("Unknown condition!");
2050 case ISD::SETEQ: return PPC::PRED_EQ;
2052 case ISD::SETNE: return PPC::PRED_NE;
2054 case ISD::SETLT: return PPC::PRED_LT;
2056 case ISD::SETLE: return PPC::PRED_LE;
2058 case ISD::SETGT: return PPC::PRED_GT;
2060 case ISD::SETGE: return PPC::PRED_GE;
2061 case ISD::SETO: return PPC::PRED_NU;
2062 case ISD::SETUO: return PPC::PRED_UN;
2063 // These two are invalid for floating point. Assume we have int.
2064 case ISD::SETULT: return PPC::PRED_LT;
2065 case ISD::SETUGT: return PPC::PRED_GT;
2069 /// getCRIdxForSetCC - Return the index of the condition register field
2070 /// associated with the SetCC condition, and whether or not the field is
2071 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2072 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2075 default: llvm_unreachable("Unknown condition!");
2077 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2079 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2081 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2082 case ISD::SETUO: return 3; // Bit #3 = SETUO
2084 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2086 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2088 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2089 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2094 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2095 // These are invalid for floating point. Assume integer.
2096 case ISD::SETULT: return 0;
2097 case ISD::SETUGT: return 1;
2101 // getVCmpInst: return the vector compare instruction for the specified
2102 // vector type and condition code. Since this is for altivec specific code,
2103 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2104 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2105 bool HasVSX, bool &Swap, bool &Negate) {
2109 if (VecVT.isFloatingPoint()) {
2110 /* Handle some cases by swapping input operands. */
2112 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2113 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2114 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2115 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2116 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2117 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2120 /* Handle some cases by negating the result. */
2122 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2123 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2124 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2125 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2128 /* We have instructions implementing the remaining cases. */
2132 if (VecVT == MVT::v4f32)
2133 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2134 else if (VecVT == MVT::v2f64)
2135 return PPC::XVCMPEQDP;
2139 if (VecVT == MVT::v4f32)
2140 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2141 else if (VecVT == MVT::v2f64)
2142 return PPC::XVCMPGTDP;
2146 if (VecVT == MVT::v4f32)
2147 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2148 else if (VecVT == MVT::v2f64)
2149 return PPC::XVCMPGEDP;
2154 llvm_unreachable("Invalid floating-point vector compare condition");
2156 /* Handle some cases by swapping input operands. */
2158 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2159 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2160 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2161 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2164 /* Handle some cases by negating the result. */
2166 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2167 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2168 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2169 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2172 /* We have instructions implementing the remaining cases. */
2176 if (VecVT == MVT::v16i8)
2177 return PPC::VCMPEQUB;
2178 else if (VecVT == MVT::v8i16)
2179 return PPC::VCMPEQUH;
2180 else if (VecVT == MVT::v4i32)
2181 return PPC::VCMPEQUW;
2182 else if (VecVT == MVT::v2i64)
2183 return PPC::VCMPEQUD;
2186 if (VecVT == MVT::v16i8)
2187 return PPC::VCMPGTSB;
2188 else if (VecVT == MVT::v8i16)
2189 return PPC::VCMPGTSH;
2190 else if (VecVT == MVT::v4i32)
2191 return PPC::VCMPGTSW;
2192 else if (VecVT == MVT::v2i64)
2193 return PPC::VCMPGTSD;
2196 if (VecVT == MVT::v16i8)
2197 return PPC::VCMPGTUB;
2198 else if (VecVT == MVT::v8i16)
2199 return PPC::VCMPGTUH;
2200 else if (VecVT == MVT::v4i32)
2201 return PPC::VCMPGTUW;
2202 else if (VecVT == MVT::v2i64)
2203 return PPC::VCMPGTUD;
2208 llvm_unreachable("Invalid integer vector compare condition");
2212 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2215 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2216 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2217 bool isPPC64 = (PtrVT == MVT::i64);
2219 if (!PPCSubTarget->useCRBits() &&
2220 isInt32Immediate(N->getOperand(1), Imm)) {
2221 // We can codegen setcc op, imm very efficiently compared to a brcond.
2222 // Check for those cases here.
2225 SDValue Op = N->getOperand(0);
2229 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2230 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2231 getI32Imm(31, dl) };
2232 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2237 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2238 Op, getI32Imm(~0U, dl)), 0);
2239 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2243 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2244 getI32Imm(31, dl) };
2245 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2249 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2250 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2251 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2252 getI32Imm(31, dl) };
2253 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2256 } else if (Imm == ~0U) { // setcc op, -1
2257 SDValue Op = N->getOperand(0);
2262 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2263 Op, getI32Imm(1, dl)), 0);
2264 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2265 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2268 0), Op.getValue(1));
2271 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2272 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2273 Op, getI32Imm(~0U, dl));
2274 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2275 Op, SDValue(AD, 1));
2278 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2279 getI32Imm(1, dl)), 0);
2280 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2282 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2283 getI32Imm(31, dl) };
2284 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2287 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2288 getI32Imm(31, dl) };
2289 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2290 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2297 SDValue LHS = N->getOperand(0);
2298 SDValue RHS = N->getOperand(1);
2300 // Altivec Vector compare instructions do not set any CR register by default and
2301 // vector compare operations return the same type as the operands.
2302 if (LHS.getValueType().isVector()) {
2303 if (PPCSubTarget->hasQPX())
2306 EVT VecVT = LHS.getValueType();
2308 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2309 PPCSubTarget->hasVSX(), Swap, Negate);
2311 std::swap(LHS, RHS);
2314 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2315 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2320 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2323 if (PPCSubTarget->useCRBits())
2327 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2328 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2331 // Force the ccreg into CR7.
2332 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2334 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2335 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2336 InFlag).getValue(1);
2338 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2341 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2342 getI32Imm(31, dl), getI32Imm(31, dl) };
2344 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2346 // Get the specified bit.
2348 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2349 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2352 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2353 // Transfer memoperands.
2354 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2355 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2356 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2361 // Select - Convert the specified operand from a target-independent to a
2362 // target-specific node if it hasn't already been changed.
2363 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2365 if (N->isMachineOpcode()) {
2367 return nullptr; // Already selected.
2370 // In case any misguided DAG-level optimizations form an ADD with a
2371 // TargetConstant operand, crash here instead of miscompiling (by selecting
2372 // an r+r add instead of some kind of r+i add).
2373 if (N->getOpcode() == ISD::ADD &&
2374 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2375 llvm_unreachable("Invalid ADD with TargetConstant operand");
2377 // Try matching complex bit permutations before doing anything else.
2378 if (SDNode *NN = SelectBitPermutation(N))
2381 switch (N->getOpcode()) {
2384 case ISD::Constant: {
2385 if (N->getValueType(0) == MVT::i64)
2386 return SelectInt64(CurDAG, N);
2391 SDNode *SN = SelectSETCC(N);
2396 case PPCISD::GlobalBaseReg:
2397 return getGlobalBaseReg();
2399 case ISD::FrameIndex:
2400 return getFrameIndex(N, N);
2402 case PPCISD::MFOCRF: {
2403 SDValue InFlag = N->getOperand(1);
2404 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2405 N->getOperand(0), InFlag);
2408 case PPCISD::READ_TIME_BASE: {
2409 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2410 MVT::Other, N->getOperand(0));
2413 case PPCISD::SRA_ADDZE: {
2414 SDValue N0 = N->getOperand(0);
2416 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2417 getConstantIntValue(), dl,
2418 N->getValueType(0));
2419 if (N->getValueType(0) == MVT::i64) {
2421 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2423 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2424 SDValue(Op, 0), SDValue(Op, 1));
2426 assert(N->getValueType(0) == MVT::i32 &&
2427 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2429 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2431 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2432 SDValue(Op, 0), SDValue(Op, 1));
2437 // Handle preincrement loads.
2438 LoadSDNode *LD = cast<LoadSDNode>(N);
2439 EVT LoadedVT = LD->getMemoryVT();
2441 // Normal loads are handled by code generated from the .td file.
2442 if (LD->getAddressingMode() != ISD::PRE_INC)
2445 SDValue Offset = LD->getOffset();
2446 if (Offset.getOpcode() == ISD::TargetConstant ||
2447 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2450 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2451 if (LD->getValueType(0) != MVT::i64) {
2452 // Handle PPC32 integer and normal FP loads.
2453 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2454 switch (LoadedVT.getSimpleVT().SimpleTy) {
2455 default: llvm_unreachable("Invalid PPC load type!");
2456 case MVT::f64: Opcode = PPC::LFDU; break;
2457 case MVT::f32: Opcode = PPC::LFSU; break;
2458 case MVT::i32: Opcode = PPC::LWZU; break;
2459 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2461 case MVT::i8: Opcode = PPC::LBZU; break;
2464 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2465 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2466 switch (LoadedVT.getSimpleVT().SimpleTy) {
2467 default: llvm_unreachable("Invalid PPC load type!");
2468 case MVT::i64: Opcode = PPC::LDU; break;
2469 case MVT::i32: Opcode = PPC::LWZU8; break;
2470 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2472 case MVT::i8: Opcode = PPC::LBZU8; break;
2476 SDValue Chain = LD->getChain();
2477 SDValue Base = LD->getBasePtr();
2478 SDValue Ops[] = { Offset, Base, Chain };
2479 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2480 LD->getValueType(0),
2481 PPCLowering->getPointerTy(),
2485 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2486 if (LD->getValueType(0) != MVT::i64) {
2487 // Handle PPC32 integer and normal FP loads.
2488 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2489 switch (LoadedVT.getSimpleVT().SimpleTy) {
2490 default: llvm_unreachable("Invalid PPC load type!");
2491 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2492 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2493 case MVT::f64: Opcode = PPC::LFDUX; break;
2494 case MVT::f32: Opcode = PPC::LFSUX; break;
2495 case MVT::i32: Opcode = PPC::LWZUX; break;
2496 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2498 case MVT::i8: Opcode = PPC::LBZUX; break;
2501 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2502 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2503 "Invalid sext update load");
2504 switch (LoadedVT.getSimpleVT().SimpleTy) {
2505 default: llvm_unreachable("Invalid PPC load type!");
2506 case MVT::i64: Opcode = PPC::LDUX; break;
2507 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2508 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2510 case MVT::i8: Opcode = PPC::LBZUX8; break;
2514 SDValue Chain = LD->getChain();
2515 SDValue Base = LD->getBasePtr();
2516 SDValue Ops[] = { Base, Offset, Chain };
2517 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2518 LD->getValueType(0),
2519 PPCLowering->getPointerTy(),
2525 unsigned Imm, Imm2, SH, MB, ME;
2528 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2529 // with a mask, emit rlwinm
2530 if (isInt32Immediate(N->getOperand(1), Imm) &&
2531 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2532 SDValue Val = N->getOperand(0).getOperand(0);
2533 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2534 getI32Imm(ME, dl) };
2535 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2537 // If this is just a masked value where the input is not handled above, and
2538 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2539 if (isInt32Immediate(N->getOperand(1), Imm) &&
2540 isRunOfOnes(Imm, MB, ME) &&
2541 N->getOperand(0).getOpcode() != ISD::ROTL) {
2542 SDValue Val = N->getOperand(0);
2543 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2544 getI32Imm(ME, dl) };
2545 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2547 // If this is a 64-bit zero-extension mask, emit rldicl.
2548 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2550 SDValue Val = N->getOperand(0);
2551 MB = 64 - countTrailingOnes(Imm64);
2554 // If the operand is a logical right shift, we can fold it into this
2555 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2556 // for n <= mb. The right shift is really a left rotate followed by a
2557 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2559 if (Val.getOpcode() == ISD::SRL &&
2560 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2561 assert(Imm < 64 && "Illegal shift amount");
2562 Val = Val.getOperand(0);
2566 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2567 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2569 // AND X, 0 -> 0, not "rlwinm 32".
2570 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2571 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2574 // ISD::OR doesn't get all the bitfield insertion fun.
2575 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2576 if (isInt32Immediate(N->getOperand(1), Imm) &&
2577 N->getOperand(0).getOpcode() == ISD::OR &&
2578 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2581 if (isRunOfOnes(Imm, MB, ME)) {
2582 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2583 N->getOperand(0).getOperand(1),
2584 getI32Imm(0, dl), getI32Imm(MB, dl),
2585 getI32Imm(ME, dl) };
2586 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2590 // Other cases are autogenerated.
2594 if (N->getValueType(0) == MVT::i32)
2595 if (SDNode *I = SelectBitfieldInsert(N))
2599 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2600 isIntS16Immediate(N->getOperand(1), Imm)) {
2601 APInt LHSKnownZero, LHSKnownOne;
2602 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2604 // If this is equivalent to an add, then we can fold it with the
2605 // FrameIndex calculation.
2606 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2607 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2610 // Other cases are autogenerated.
2615 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2616 isIntS16Immediate(N->getOperand(1), Imm))
2617 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2622 unsigned Imm, SH, MB, ME;
2623 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2624 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2625 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2626 getI32Imm(SH, dl), getI32Imm(MB, dl),
2627 getI32Imm(ME, dl) };
2628 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2631 // Other cases are autogenerated.
2635 unsigned Imm, SH, MB, ME;
2636 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2637 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2638 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2639 getI32Imm(SH, dl), getI32Imm(MB, dl),
2640 getI32Imm(ME, dl) };
2641 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2644 // Other cases are autogenerated.
2647 // FIXME: Remove this once the ANDI glue bug is fixed:
2648 case PPCISD::ANDIo_1_EQ_BIT:
2649 case PPCISD::ANDIo_1_GT_BIT: {
2653 EVT InVT = N->getOperand(0).getValueType();
2654 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2655 "Invalid input type for ANDIo_1_EQ_BIT");
2657 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2658 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2660 CurDAG->getTargetConstant(1, dl, InVT)),
2662 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2664 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2665 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2667 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2669 SDValue(AndI.getNode(), 1) /* glue */);
2671 case ISD::SELECT_CC: {
2672 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2673 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2674 bool isPPC64 = (PtrVT == MVT::i64);
2676 // If this is a select of i1 operands, we'll pattern match it.
2677 if (PPCSubTarget->useCRBits() &&
2678 N->getOperand(0).getValueType() == MVT::i1)
2681 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2683 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2684 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2685 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2686 if (N1C->isNullValue() && N3C->isNullValue() &&
2687 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2688 // FIXME: Implement this optzn for PPC64.
2689 N->getValueType(0) == MVT::i32) {
2691 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2692 N->getOperand(0), getI32Imm(~0U, dl));
2693 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2694 SDValue(Tmp, 0), N->getOperand(0),
2698 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2700 if (N->getValueType(0) == MVT::i1) {
2701 // An i1 select is: (c & t) | (!c & f).
2703 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2707 default: llvm_unreachable("Invalid CC index");
2708 case 0: SRI = PPC::sub_lt; break;
2709 case 1: SRI = PPC::sub_gt; break;
2710 case 2: SRI = PPC::sub_eq; break;
2711 case 3: SRI = PPC::sub_un; break;
2714 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2716 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2718 SDValue C = Inv ? NotCCBit : CCBit,
2719 NotC = Inv ? CCBit : NotCCBit;
2721 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2722 C, N->getOperand(2)), 0);
2723 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2724 NotC, N->getOperand(3)), 0);
2726 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2729 unsigned BROpc = getPredicateForSetCC(CC);
2731 unsigned SelectCCOp;
2732 if (N->getValueType(0) == MVT::i32)
2733 SelectCCOp = PPC::SELECT_CC_I4;
2734 else if (N->getValueType(0) == MVT::i64)
2735 SelectCCOp = PPC::SELECT_CC_I8;
2736 else if (N->getValueType(0) == MVT::f32)
2737 if (PPCSubTarget->hasP8Vector())
2738 SelectCCOp = PPC::SELECT_CC_VSSRC;
2740 SelectCCOp = PPC::SELECT_CC_F4;
2741 else if (N->getValueType(0) == MVT::f64)
2742 if (PPCSubTarget->hasVSX())
2743 SelectCCOp = PPC::SELECT_CC_VSFRC;
2745 SelectCCOp = PPC::SELECT_CC_F8;
2746 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2747 SelectCCOp = PPC::SELECT_CC_QFRC;
2748 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2749 SelectCCOp = PPC::SELECT_CC_QSRC;
2750 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2751 SelectCCOp = PPC::SELECT_CC_QBRC;
2752 else if (N->getValueType(0) == MVT::v2f64 ||
2753 N->getValueType(0) == MVT::v2i64)
2754 SelectCCOp = PPC::SELECT_CC_VSRC;
2756 SelectCCOp = PPC::SELECT_CC_VRRC;
2758 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2759 getI32Imm(BROpc, dl) };
2760 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2763 if (PPCSubTarget->hasVSX()) {
2764 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2765 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2769 case ISD::VECTOR_SHUFFLE:
2770 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2771 N->getValueType(0) == MVT::v2i64)) {
2772 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2774 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2775 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2778 for (int i = 0; i < 2; ++i)
2779 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2784 // For little endian, we must swap the input operands and adjust
2785 // the mask elements (reverse and invert them).
2786 if (PPCSubTarget->isLittleEndian()) {
2787 std::swap(Op1, Op2);
2788 unsigned tmp = DM[0];
2793 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2796 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2797 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2798 isa<LoadSDNode>(Op1.getOperand(0))) {
2799 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2800 SDValue Base, Offset;
2802 if (LD->isUnindexed() &&
2803 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2804 SDValue Chain = LD->getChain();
2805 SDValue Ops[] = { Base, Offset, Chain };
2806 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2807 N->getValueType(0), Ops);
2811 SDValue Ops[] = { Op1, Op2, DMV };
2812 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2818 bool IsPPC64 = PPCSubTarget->isPPC64();
2819 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2820 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2821 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2822 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2825 case PPCISD::COND_BRANCH: {
2826 // Op #0 is the Chain.
2827 // Op #1 is the PPC::PRED_* number.
2829 // Op #3 is the Dest MBB
2830 // Op #4 is the Flag.
2831 // Prevent PPC::PRED_* from being selected into LI.
2833 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(), dl);
2834 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2835 N->getOperand(0), N->getOperand(4) };
2836 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2839 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2840 unsigned PCC = getPredicateForSetCC(CC);
2842 if (N->getOperand(2).getValueType() == MVT::i1) {
2846 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2847 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2848 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2849 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2850 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2851 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2852 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2855 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2856 N->getOperand(Swap ? 3 : 2),
2857 N->getOperand(Swap ? 2 : 3)), 0);
2858 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2859 BitComp, N->getOperand(4), N->getOperand(0));
2862 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2863 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
2864 N->getOperand(4), N->getOperand(0) };
2865 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2868 // FIXME: Should custom lower this.
2869 SDValue Chain = N->getOperand(0);
2870 SDValue Target = N->getOperand(1);
2871 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2872 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2873 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2875 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2877 case PPCISD::TOC_ENTRY: {
2878 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2879 "Only supported for 64-bit ABI and 32-bit SVR4");
2880 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2881 SDValue GA = N->getOperand(0);
2882 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2883 MVT::i32, GA, N->getOperand(1)));
2886 // For medium and large code model, we generate two instructions as
2887 // described below. Otherwise we allow SelectCodeCommon to handle this,
2888 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2889 CodeModel::Model CModel = TM.getCodeModel();
2890 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2893 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2894 // If it is an externally defined symbol, a symbol with common linkage,
2895 // a non-local function address, or a jump table address, or if we are
2896 // generating code for large code model, we generate:
2897 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2898 // Otherwise we generate:
2899 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2900 SDValue GA = N->getOperand(0);
2901 SDValue TOCbase = N->getOperand(1);
2902 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2905 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2906 CModel == CodeModel::Large)
2907 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2908 MVT::i64, GA, SDValue(Tmp, 0)));
2910 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2911 const GlobalValue *GValue = G->getGlobal();
2912 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2913 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2914 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2915 GValue->hasAvailableExternallyLinkage())
2916 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2917 MVT::i64, GA, SDValue(Tmp, 0)));
2920 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2921 SDValue(Tmp, 0), GA);
2923 case PPCISD::PPC32_PICGOT: {
2924 // Generate a PIC-safe GOT reference.
2925 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2926 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2927 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2929 case PPCISD::VADD_SPLAT: {
2930 // This expands into one of three sequences, depending on whether
2931 // the first operand is odd or even, positive or negative.
2932 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2933 isa<ConstantSDNode>(N->getOperand(1)) &&
2934 "Invalid operand on VADD_SPLAT!");
2936 int Elt = N->getConstantOperandVal(0);
2937 int EltSize = N->getConstantOperandVal(1);
2938 unsigned Opc1, Opc2, Opc3;
2942 Opc1 = PPC::VSPLTISB;
2943 Opc2 = PPC::VADDUBM;
2944 Opc3 = PPC::VSUBUBM;
2946 } else if (EltSize == 2) {
2947 Opc1 = PPC::VSPLTISH;
2948 Opc2 = PPC::VADDUHM;
2949 Opc3 = PPC::VSUBUHM;
2952 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2953 Opc1 = PPC::VSPLTISW;
2954 Opc2 = PPC::VADDUWM;
2955 Opc3 = PPC::VSUBUWM;
2959 if ((Elt & 1) == 0) {
2960 // Elt is even, in the range [-32,-18] + [16,30].
2962 // Convert: VADD_SPLAT elt, size
2963 // Into: tmp = VSPLTIS[BHW] elt
2964 // VADDU[BHW]M tmp, tmp
2965 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2966 SDValue EltVal = getI32Imm(Elt >> 1, dl);
2967 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2968 SDValue TmpVal = SDValue(Tmp, 0);
2969 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2971 } else if (Elt > 0) {
2972 // Elt is odd and positive, in the range [17,31].
2974 // Convert: VADD_SPLAT elt, size
2975 // Into: tmp1 = VSPLTIS[BHW] elt-16
2976 // tmp2 = VSPLTIS[BHW] -16
2977 // VSUBU[BHW]M tmp1, tmp2
2978 SDValue EltVal = getI32Imm(Elt - 16, dl);
2979 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2980 EltVal = getI32Imm(-16, dl);
2981 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2982 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2986 // Elt is odd and negative, in the range [-31,-17].
2988 // Convert: VADD_SPLAT elt, size
2989 // Into: tmp1 = VSPLTIS[BHW] elt+16
2990 // tmp2 = VSPLTIS[BHW] -16
2991 // VADDU[BHW]M tmp1, tmp2
2992 SDValue EltVal = getI32Imm(Elt + 16, dl);
2993 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2994 EltVal = getI32Imm(-16, dl);
2995 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2996 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3002 return SelectCode(N);
3005 // If the target supports the cmpb instruction, do the idiom recognition here.
3006 // We don't do this as a DAG combine because we don't want to do it as nodes
3007 // are being combined (because we might miss part of the eventual idiom). We
3008 // don't want to do it during instruction selection because we want to reuse
3009 // the logic for lowering the masking operations already part of the
3010 // instruction selector.
3011 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3014 assert(N->getOpcode() == ISD::OR &&
3015 "Only OR nodes are supported for CMPB");
3018 if (!PPCSubTarget->hasCMPB())
3021 if (N->getValueType(0) != MVT::i32 &&
3022 N->getValueType(0) != MVT::i64)
3025 EVT VT = N->getValueType(0);
3028 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3029 uint64_t Mask = 0, Alt = 0;
3031 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3032 uint64_t &Mask, uint64_t &Alt,
3033 SDValue &LHS, SDValue &RHS) {
3034 if (O.getOpcode() != ISD::SELECT_CC)
3036 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3038 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3039 !isa<ConstantSDNode>(O.getOperand(3)))
3042 uint64_t PM = O.getConstantOperandVal(2);
3043 uint64_t PAlt = O.getConstantOperandVal(3);
3044 for (b = 0; b < 8; ++b) {
3045 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3046 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3055 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3056 O.getConstantOperandVal(1) != 0) {
3057 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3058 if (Op0.getOpcode() == ISD::TRUNCATE)
3059 Op0 = Op0.getOperand(0);
3060 if (Op1.getOpcode() == ISD::TRUNCATE)
3061 Op1 = Op1.getOperand(0);
3063 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3064 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3065 isa<ConstantSDNode>(Op0.getOperand(1))) {
3067 unsigned Bits = Op0.getValueType().getSizeInBits();
3070 if (Op0.getConstantOperandVal(1) != Bits-8)
3073 LHS = Op0.getOperand(0);
3074 RHS = Op1.getOperand(0);
3078 // When we have small integers (i16 to be specific), the form present
3079 // post-legalization uses SETULT in the SELECT_CC for the
3080 // higher-order byte, depending on the fact that the
3081 // even-higher-order bytes are known to all be zero, for example:
3082 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3083 // (so when the second byte is the same, because all higher-order
3084 // bits from bytes 3 and 4 are known to be zero, the result of the
3085 // xor can be at most 255)
3086 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3087 isa<ConstantSDNode>(O.getOperand(1))) {
3089 uint64_t ULim = O.getConstantOperandVal(1);
3090 if (ULim != (UINT64_C(1) << b*8))
3093 // Now we need to make sure that the upper bytes are known to be
3095 unsigned Bits = Op0.getValueType().getSizeInBits();
3096 if (!CurDAG->MaskedValueIsZero(Op0,
3097 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3100 LHS = Op0.getOperand(0);
3101 RHS = Op0.getOperand(1);
3108 if (CC != ISD::SETEQ)
3111 SDValue Op = O.getOperand(0);
3112 if (Op.getOpcode() == ISD::AND) {
3113 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3115 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3118 SDValue XOR = Op.getOperand(0);
3119 if (XOR.getOpcode() == ISD::TRUNCATE)
3120 XOR = XOR.getOperand(0);
3121 if (XOR.getOpcode() != ISD::XOR)
3124 LHS = XOR.getOperand(0);
3125 RHS = XOR.getOperand(1);
3127 } else if (Op.getOpcode() == ISD::SRL) {
3128 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3130 unsigned Bits = Op.getValueType().getSizeInBits();
3133 if (Op.getConstantOperandVal(1) != Bits-8)
3136 SDValue XOR = Op.getOperand(0);
3137 if (XOR.getOpcode() == ISD::TRUNCATE)
3138 XOR = XOR.getOperand(0);
3139 if (XOR.getOpcode() != ISD::XOR)
3142 LHS = XOR.getOperand(0);
3143 RHS = XOR.getOperand(1);
3150 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3151 while (!Queue.empty()) {
3152 SDValue V = Queue.pop_back_val();
3154 for (const SDValue &O : V.getNode()->ops()) {
3156 uint64_t M = 0, A = 0;
3158 if (O.getOpcode() == ISD::OR) {
3160 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3164 BytesFound[b] = true;
3167 } else if ((LHS == ORHS && RHS == OLHS) ||
3168 (RHS == ORHS && LHS == OLHS)) {
3169 BytesFound[b] = true;
3181 unsigned LastB = 0, BCnt = 0;
3182 for (unsigned i = 0; i < 8; ++i)
3183 if (BytesFound[LastB]) {
3188 if (!LastB || BCnt < 2)
3191 // Because we'll be zero-extending the output anyway if don't have a specific
3192 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3193 if (LHS.getValueType() != VT) {
3194 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3195 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3198 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3200 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3201 if (NonTrivialMask && !Alt) {
3202 // Res = Mask & CMPB
3203 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3204 CurDAG->getConstant(Mask, dl, VT));
3206 // Res = (CMPB & Mask) | (~CMPB & Alt)
3207 // Which, as suggested here:
3208 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3209 // can be written as:
3210 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3211 // useful because the (Alt ^ Mask) can be pre-computed.
3212 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3213 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3214 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3215 CurDAG->getConstant(Alt, dl, VT));
3221 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3222 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3223 // involves constant materialization of a 0 or a 1 or both. If the result of
3224 // the extension is then operated upon by some operator that can be constant
3225 // folded with a constant 0 or 1, and that constant can be materialized using
3226 // only one instruction (like a zero or one), then we should fold in those
3227 // operations with the select.
3228 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3229 if (!PPCSubTarget->useCRBits())
3232 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3233 N->getOpcode() != ISD::SIGN_EXTEND &&
3234 N->getOpcode() != ISD::ANY_EXTEND)
3237 if (N->getOperand(0).getValueType() != MVT::i1)
3240 if (!N->hasOneUse())
3244 EVT VT = N->getValueType(0);
3245 SDValue Cond = N->getOperand(0);
3247 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3248 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3251 SDNode *User = *N->use_begin();
3252 if (User->getNumOperands() != 2)
3255 auto TryFold = [this, N, User, dl](SDValue Val) {
3256 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3257 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3258 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3260 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3261 User->getValueType(0),
3262 O0.getNode(), O1.getNode());
3265 SDValue TrueRes = TryFold(ConstTrue);
3268 SDValue FalseRes = TryFold(ConstFalse);
3272 // For us to materialize these using one instruction, we must be able to
3273 // represent them as signed 16-bit integers.
3274 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3275 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3276 if (!isInt<16>(True) || !isInt<16>(False))
3279 // We can replace User with a new SELECT node, and try again to see if we
3280 // can fold the select with its user.
3281 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3283 ConstTrue = TrueRes;
3284 ConstFalse = FalseRes;
3285 } while (N->hasOneUse());
3288 void PPCDAGToDAGISel::PreprocessISelDAG() {
3289 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3292 bool MadeChange = false;
3293 while (Position != CurDAG->allnodes_begin()) {
3294 SDNode *N = --Position;
3299 switch (N->getOpcode()) {
3302 Res = combineToCMPB(N);
3307 foldBoolExts(Res, N);
3310 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3311 DEBUG(N->dump(CurDAG));
3312 DEBUG(dbgs() << "\nNew: ");
3313 DEBUG(Res.getNode()->dump(CurDAG));
3314 DEBUG(dbgs() << "\n");
3316 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3322 CurDAG->RemoveDeadNodes();
3325 /// PostprocessISelDAG - Perform some late peephole optimizations
3326 /// on the DAG representation.
3327 void PPCDAGToDAGISel::PostprocessISelDAG() {
3329 // Skip peepholes at -O0.
3330 if (TM.getOptLevel() == CodeGenOpt::None)
3335 PeepholePPC64ZExt();
3338 // Check if all users of this node will become isel where the second operand
3339 // is the constant zero. If this is so, and if we can negate the condition,
3340 // then we can flip the true and false operands. This will allow the zero to
3341 // be folded with the isel so that we don't need to materialize a register
3343 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3344 // If we're not using isel, then this does not matter.
3345 if (!PPCSubTarget->hasISEL())
3348 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3351 if (!User->isMachineOpcode())
3353 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3354 User->getMachineOpcode() != PPC::SELECT_I8)
3357 SDNode *Op2 = User->getOperand(2).getNode();
3358 if (!Op2->isMachineOpcode())
3361 if (Op2->getMachineOpcode() != PPC::LI &&
3362 Op2->getMachineOpcode() != PPC::LI8)
3365 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3369 if (!C->isNullValue())
3376 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3377 SmallVector<SDNode *, 4> ToReplace;
3378 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3381 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3382 User->getMachineOpcode() == PPC::SELECT_I8) &&
3383 "Must have all select users");
3384 ToReplace.push_back(User);
3387 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3388 UE = ToReplace.end(); UI != UE; ++UI) {
3391 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3392 User->getValueType(0), User->getOperand(0),
3393 User->getOperand(2),
3394 User->getOperand(1));
3396 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3397 DEBUG(User->dump(CurDAG));
3398 DEBUG(dbgs() << "\nNew: ");
3399 DEBUG(ResNode->dump(CurDAG));
3400 DEBUG(dbgs() << "\n");
3402 ReplaceUses(User, ResNode);
3406 void PPCDAGToDAGISel::PeepholeCROps() {
3410 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3411 E = CurDAG->allnodes_end(); I != E; ++I) {
3412 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3413 if (!MachineNode || MachineNode->use_empty())
3415 SDNode *ResNode = MachineNode;
3417 bool Op1Set = false, Op1Unset = false,
3419 Op2Set = false, Op2Unset = false,
3422 unsigned Opcode = MachineNode->getMachineOpcode();
3433 SDValue Op = MachineNode->getOperand(1);
3434 if (Op.isMachineOpcode()) {
3435 if (Op.getMachineOpcode() == PPC::CRSET)
3437 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3439 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3440 Op.getOperand(0) == Op.getOperand(1))
3446 case PPC::SELECT_I4:
3447 case PPC::SELECT_I8:
3448 case PPC::SELECT_F4:
3449 case PPC::SELECT_F8:
3450 case PPC::SELECT_QFRC:
3451 case PPC::SELECT_QSRC:
3452 case PPC::SELECT_QBRC:
3453 case PPC::SELECT_VRRC:
3454 case PPC::SELECT_VSFRC:
3455 case PPC::SELECT_VSSRC:
3456 case PPC::SELECT_VSRC: {
3457 SDValue Op = MachineNode->getOperand(0);
3458 if (Op.isMachineOpcode()) {
3459 if (Op.getMachineOpcode() == PPC::CRSET)
3461 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3463 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3464 Op.getOperand(0) == Op.getOperand(1))
3471 bool SelectSwap = false;
3475 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3477 ResNode = MachineNode->getOperand(0).getNode();
3480 ResNode = MachineNode->getOperand(1).getNode();
3483 ResNode = MachineNode->getOperand(0).getNode();
3484 else if (Op1Unset || Op2Unset)
3485 // x & 0 = 0 & y = 0
3486 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3489 // ~x & y = andc(y, x)
3490 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3491 MVT::i1, MachineNode->getOperand(1),
3492 MachineNode->getOperand(0).
3495 // x & ~y = andc(x, y)
3496 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3497 MVT::i1, MachineNode->getOperand(0),
3498 MachineNode->getOperand(1).
3500 else if (AllUsersSelectZero(MachineNode))
3501 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3502 MVT::i1, MachineNode->getOperand(0),
3503 MachineNode->getOperand(1)),
3507 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3508 // nand(x, x) -> nor(x, x)
3509 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3510 MVT::i1, MachineNode->getOperand(0),
3511 MachineNode->getOperand(0));
3513 // nand(1, y) -> nor(y, y)
3514 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3515 MVT::i1, MachineNode->getOperand(1),
3516 MachineNode->getOperand(1));
3518 // nand(x, 1) -> nor(x, x)
3519 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3520 MVT::i1, MachineNode->getOperand(0),
3521 MachineNode->getOperand(0));
3522 else if (Op1Unset || Op2Unset)
3523 // nand(x, 0) = nand(0, y) = 1
3524 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3527 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3528 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3529 MVT::i1, MachineNode->getOperand(0).
3531 MachineNode->getOperand(1));
3533 // nand(x, ~y) = ~x | y = orc(y, x)
3534 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3535 MVT::i1, MachineNode->getOperand(1).
3537 MachineNode->getOperand(0));
3538 else if (AllUsersSelectZero(MachineNode))
3539 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3540 MVT::i1, MachineNode->getOperand(0),
3541 MachineNode->getOperand(1)),
3545 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3547 ResNode = MachineNode->getOperand(0).getNode();
3548 else if (Op1Set || Op2Set)
3549 // x | 1 = 1 | y = 1
3550 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3554 ResNode = MachineNode->getOperand(1).getNode();
3557 ResNode = MachineNode->getOperand(0).getNode();
3559 // ~x | y = orc(y, x)
3560 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3561 MVT::i1, MachineNode->getOperand(1),
3562 MachineNode->getOperand(0).
3565 // x | ~y = orc(x, y)
3566 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3567 MVT::i1, MachineNode->getOperand(0),
3568 MachineNode->getOperand(1).
3570 else if (AllUsersSelectZero(MachineNode))
3571 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3572 MVT::i1, MachineNode->getOperand(0),
3573 MachineNode->getOperand(1)),
3577 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3579 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3582 // xor(1, y) -> nor(y, y)
3583 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3584 MVT::i1, MachineNode->getOperand(1),
3585 MachineNode->getOperand(1));
3587 // xor(x, 1) -> nor(x, x)
3588 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3589 MVT::i1, MachineNode->getOperand(0),
3590 MachineNode->getOperand(0));
3593 ResNode = MachineNode->getOperand(1).getNode();
3596 ResNode = MachineNode->getOperand(0).getNode();
3598 // xor(~x, y) = eqv(x, y)
3599 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3600 MVT::i1, MachineNode->getOperand(0).
3602 MachineNode->getOperand(1));
3604 // xor(x, ~y) = eqv(x, y)
3605 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3606 MVT::i1, MachineNode->getOperand(0),
3607 MachineNode->getOperand(1).
3609 else if (AllUsersSelectZero(MachineNode))
3610 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3611 MVT::i1, MachineNode->getOperand(0),
3612 MachineNode->getOperand(1)),
3616 if (Op1Set || Op2Set)
3618 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3621 // nor(0, y) = ~y -> nor(y, y)
3622 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3623 MVT::i1, MachineNode->getOperand(1),
3624 MachineNode->getOperand(1));
3627 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3628 MVT::i1, MachineNode->getOperand(0),
3629 MachineNode->getOperand(0));
3631 // nor(~x, y) = andc(x, y)
3632 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3633 MVT::i1, MachineNode->getOperand(0).
3635 MachineNode->getOperand(1));
3637 // nor(x, ~y) = andc(y, x)
3638 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3639 MVT::i1, MachineNode->getOperand(1).
3641 MachineNode->getOperand(0));
3642 else if (AllUsersSelectZero(MachineNode))
3643 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3644 MVT::i1, MachineNode->getOperand(0),
3645 MachineNode->getOperand(1)),
3649 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3651 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3655 ResNode = MachineNode->getOperand(1).getNode();
3658 ResNode = MachineNode->getOperand(0).getNode();
3660 // eqv(0, y) = ~y -> nor(y, y)
3661 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3662 MVT::i1, MachineNode->getOperand(1),
3663 MachineNode->getOperand(1));
3666 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3667 MVT::i1, MachineNode->getOperand(0),
3668 MachineNode->getOperand(0));
3670 // eqv(~x, y) = xor(x, y)
3671 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3672 MVT::i1, MachineNode->getOperand(0).
3674 MachineNode->getOperand(1));
3676 // eqv(x, ~y) = xor(x, y)
3677 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3678 MVT::i1, MachineNode->getOperand(0),
3679 MachineNode->getOperand(1).
3681 else if (AllUsersSelectZero(MachineNode))
3682 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3683 MVT::i1, MachineNode->getOperand(0),
3684 MachineNode->getOperand(1)),
3688 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3690 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3694 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3695 MVT::i1, MachineNode->getOperand(1),
3696 MachineNode->getOperand(1));
3697 else if (Op1Unset || Op2Set)
3698 // andc(0, y) = andc(x, 1) = 0
3699 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3703 ResNode = MachineNode->getOperand(0).getNode();
3705 // andc(~x, y) = ~(x | y) = nor(x, y)
3706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3707 MVT::i1, MachineNode->getOperand(0).
3709 MachineNode->getOperand(1));
3711 // andc(x, ~y) = x & y
3712 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3713 MVT::i1, MachineNode->getOperand(0),
3714 MachineNode->getOperand(1).
3716 else if (AllUsersSelectZero(MachineNode))
3717 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3718 MVT::i1, MachineNode->getOperand(1),
3719 MachineNode->getOperand(0)),
3723 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3725 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3727 else if (Op1Set || Op2Unset)
3728 // orc(1, y) = orc(x, 0) = 1
3729 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3733 ResNode = MachineNode->getOperand(0).getNode();
3736 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3737 MVT::i1, MachineNode->getOperand(1),
3738 MachineNode->getOperand(1));
3740 // orc(~x, y) = ~(x & y) = nand(x, y)
3741 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3742 MVT::i1, MachineNode->getOperand(0).
3744 MachineNode->getOperand(1));
3746 // orc(x, ~y) = x | y
3747 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3748 MVT::i1, MachineNode->getOperand(0),
3749 MachineNode->getOperand(1).
3751 else if (AllUsersSelectZero(MachineNode))
3752 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3753 MVT::i1, MachineNode->getOperand(1),
3754 MachineNode->getOperand(0)),
3757 case PPC::SELECT_I4:
3758 case PPC::SELECT_I8:
3759 case PPC::SELECT_F4:
3760 case PPC::SELECT_F8:
3761 case PPC::SELECT_QFRC:
3762 case PPC::SELECT_QSRC:
3763 case PPC::SELECT_QBRC:
3764 case PPC::SELECT_VRRC:
3765 case PPC::SELECT_VSFRC:
3766 case PPC::SELECT_VSSRC:
3767 case PPC::SELECT_VSRC:
3769 ResNode = MachineNode->getOperand(1).getNode();
3771 ResNode = MachineNode->getOperand(2).getNode();
3773 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3775 MachineNode->getValueType(0),
3776 MachineNode->getOperand(0).
3778 MachineNode->getOperand(2),
3779 MachineNode->getOperand(1));
3784 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3788 MachineNode->getOperand(0).
3790 MachineNode->getOperand(1),
3791 MachineNode->getOperand(2));
3792 // FIXME: Handle Op1Set, Op1Unset here too.
3796 // If we're inverting this node because it is used only by selects that
3797 // we'd like to swap, then swap the selects before the node replacement.
3799 SwapAllSelectUsers(MachineNode);
3801 if (ResNode != MachineNode) {
3802 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3803 DEBUG(MachineNode->dump(CurDAG));
3804 DEBUG(dbgs() << "\nNew: ");
3805 DEBUG(ResNode->dump(CurDAG));
3806 DEBUG(dbgs() << "\n");
3808 ReplaceUses(MachineNode, ResNode);
3813 CurDAG->RemoveDeadNodes();
3814 } while (IsModified);
3817 // Gather the set of 32-bit operations that are known to have their
3818 // higher-order 32 bits zero, where ToPromote contains all such operations.
3819 static bool PeepholePPC64ZExtGather(SDValue Op32,
3820 SmallPtrSetImpl<SDNode *> &ToPromote) {
3821 if (!Op32.isMachineOpcode())
3824 // First, check for the "frontier" instructions (those that will clear the
3825 // higher-order 32 bits.
3827 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3828 // around. If it does not, then these instructions will clear the
3829 // higher-order bits.
3830 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3831 Op32.getMachineOpcode() == PPC::RLWNM) &&
3832 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3833 ToPromote.insert(Op32.getNode());
3837 // SLW and SRW always clear the higher-order bits.
3838 if (Op32.getMachineOpcode() == PPC::SLW ||
3839 Op32.getMachineOpcode() == PPC::SRW) {
3840 ToPromote.insert(Op32.getNode());
3844 // For LI and LIS, we need the immediate to be positive (so that it is not
3846 if (Op32.getMachineOpcode() == PPC::LI ||
3847 Op32.getMachineOpcode() == PPC::LIS) {
3848 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3851 ToPromote.insert(Op32.getNode());
3855 // LHBRX and LWBRX always clear the higher-order bits.
3856 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3857 Op32.getMachineOpcode() == PPC::LWBRX) {
3858 ToPromote.insert(Op32.getNode());
3862 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3863 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3864 ToPromote.insert(Op32.getNode());
3868 // Next, check for those instructions we can look through.
3870 // Assuming the mask does not wrap around, then the higher-order bits are
3871 // taken directly from the first operand.
3872 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3873 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3874 SmallPtrSet<SDNode *, 16> ToPromote1;
3875 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3878 ToPromote.insert(Op32.getNode());
3879 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3883 // For OR, the higher-order bits are zero if that is true for both operands.
3884 // For SELECT_I4, the same is true (but the relevant operand numbers are
3886 if (Op32.getMachineOpcode() == PPC::OR ||
3887 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3888 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3889 SmallPtrSet<SDNode *, 16> ToPromote1;
3890 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3892 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3895 ToPromote.insert(Op32.getNode());
3896 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3900 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3901 // zero, and also for the constant to be positive (so that it is not sign
3903 if (Op32.getMachineOpcode() == PPC::ORI ||
3904 Op32.getMachineOpcode() == PPC::ORIS) {
3905 SmallPtrSet<SDNode *, 16> ToPromote1;
3906 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3908 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3911 ToPromote.insert(Op32.getNode());
3912 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3916 // The higher-order bits of AND are zero if that is true for at least one of
3918 if (Op32.getMachineOpcode() == PPC::AND) {
3919 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3921 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3923 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3924 if (!Op0OK && !Op1OK)
3927 ToPromote.insert(Op32.getNode());
3930 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3933 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3938 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3939 // of the first operand, or if the second operand is positive (so that it is
3940 // not sign extended).
3941 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3942 Op32.getMachineOpcode() == PPC::ANDISo) {
3943 SmallPtrSet<SDNode *, 16> ToPromote1;
3945 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3946 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3947 if (!Op0OK && !Op1OK)
3950 ToPromote.insert(Op32.getNode());
3953 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3961 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3962 if (!PPCSubTarget->isPPC64())
3965 // When we zero-extend from i32 to i64, we use a pattern like this:
3966 // def : Pat<(i64 (zext i32:$in)),
3967 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3969 // There are several 32-bit shift/rotate instructions, however, that will
3970 // clear the higher-order bits of their output, rendering the RLDICL
3971 // unnecessary. When that happens, we remove it here, and redefine the
3972 // relevant 32-bit operation to be a 64-bit operation.
3974 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3977 bool MadeChange = false;
3978 while (Position != CurDAG->allnodes_begin()) {
3979 SDNode *N = --Position;
3980 // Skip dead nodes and any non-machine opcodes.
3981 if (N->use_empty() || !N->isMachineOpcode())
3984 if (N->getMachineOpcode() != PPC::RLDICL)
3987 if (N->getConstantOperandVal(1) != 0 ||
3988 N->getConstantOperandVal(2) != 32)
3991 SDValue ISR = N->getOperand(0);
3992 if (!ISR.isMachineOpcode() ||
3993 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3996 if (!ISR.hasOneUse())
3999 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4002 SDValue IDef = ISR.getOperand(0);
4003 if (!IDef.isMachineOpcode() ||
4004 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4007 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4008 // can get rid of it.
4010 SDValue Op32 = ISR->getOperand(1);
4011 if (!Op32.isMachineOpcode())
4014 // There are some 32-bit instructions that always clear the high-order 32
4015 // bits, there are also some instructions (like AND) that we can look
4017 SmallPtrSet<SDNode *, 16> ToPromote;
4018 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4021 // If the ToPromote set contains nodes that have uses outside of the set
4022 // (except for the original INSERT_SUBREG), then abort the transformation.
4023 bool OutsideUse = false;
4024 for (SDNode *PN : ToPromote) {
4025 for (SDNode *UN : PN->uses()) {
4026 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4040 // We now know that this zero extension can be removed by promoting to
4041 // nodes in ToPromote to 64-bit operations, where for operations in the
4042 // frontier of the set, we need to insert INSERT_SUBREGs for their
4044 for (SDNode *PN : ToPromote) {
4046 switch (PN->getMachineOpcode()) {
4048 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4049 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4050 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4051 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4052 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4053 case PPC::LI: NewOpcode = PPC::LI8; break;
4054 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4055 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4056 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4057 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4058 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4059 case PPC::OR: NewOpcode = PPC::OR8; break;
4060 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4061 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4062 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4063 case PPC::AND: NewOpcode = PPC::AND8; break;
4064 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4065 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4068 // Note: During the replacement process, the nodes will be in an
4069 // inconsistent state (some instructions will have operands with values
4070 // of the wrong type). Once done, however, everything should be right
4073 SmallVector<SDValue, 4> Ops;
4074 for (const SDValue &V : PN->ops()) {
4075 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4076 !isa<ConstantSDNode>(V)) {
4077 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4079 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4080 ISR.getNode()->getVTList(), ReplOpOps);
4081 Ops.push_back(SDValue(ReplOp, 0));
4087 // Because all to-be-promoted nodes only have users that are other
4088 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4089 // the i32 result value type with i64.
4091 SmallVector<EVT, 2> NewVTs;
4092 SDVTList VTs = PN->getVTList();
4093 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4094 if (VTs.VTs[i] == MVT::i32)
4095 NewVTs.push_back(MVT::i64);
4097 NewVTs.push_back(VTs.VTs[i]);
4099 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4100 DEBUG(PN->dump(CurDAG));
4102 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4104 DEBUG(dbgs() << "\nNew: ");
4105 DEBUG(PN->dump(CurDAG));
4106 DEBUG(dbgs() << "\n");
4109 // Now we replace the original zero extend and its associated INSERT_SUBREG
4110 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4113 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4114 DEBUG(N->dump(CurDAG));
4115 DEBUG(dbgs() << "\nNew: ");
4116 DEBUG(Op32.getNode()->dump(CurDAG));
4117 DEBUG(dbgs() << "\n");
4119 ReplaceUses(N, Op32.getNode());
4123 CurDAG->RemoveDeadNodes();
4126 void PPCDAGToDAGISel::PeepholePPC64() {
4127 // These optimizations are currently supported only for 64-bit SVR4.
4128 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4131 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4134 while (Position != CurDAG->allnodes_begin()) {
4135 SDNode *N = --Position;
4136 // Skip dead nodes and any non-machine opcodes.
4137 if (N->use_empty() || !N->isMachineOpcode())
4141 unsigned StorageOpcode = N->getMachineOpcode();
4143 switch (StorageOpcode) {
4174 // If this is a load or store with a zero offset, we may be able to
4175 // fold an add-immediate into the memory operation.
4176 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4177 N->getConstantOperandVal(FirstOp) != 0)
4180 SDValue Base = N->getOperand(FirstOp + 1);
4181 if (!Base.isMachineOpcode())
4185 bool ReplaceFlags = true;
4187 // When the feeding operation is an add-immediate of some sort,
4188 // determine whether we need to add relocation information to the
4189 // target flags on the immediate operand when we fold it into the
4190 // load instruction.
4192 // For something like ADDItocL, the relocation information is
4193 // inferred from the opcode; when we process it in the AsmPrinter,
4194 // we add the necessary relocation there. A load, though, can receive
4195 // relocation from various flavors of ADDIxxx, so we need to carry
4196 // the relocation information in the target flags.
4197 switch (Base.getMachineOpcode()) {
4202 // In some cases (such as TLS) the relocation information
4203 // is already in place on the operand, so copying the operand
4205 ReplaceFlags = false;
4206 // For these cases, the immediate may not be divisible by 4, in
4207 // which case the fold is illegal for DS-form instructions. (The
4208 // other cases provide aligned addresses and are always safe.)
4209 if ((StorageOpcode == PPC::LWA ||
4210 StorageOpcode == PPC::LD ||
4211 StorageOpcode == PPC::STD) &&
4212 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4213 Base.getConstantOperandVal(1) % 4 != 0))
4216 case PPC::ADDIdtprelL:
4217 Flags = PPCII::MO_DTPREL_LO;
4219 case PPC::ADDItlsldL:
4220 Flags = PPCII::MO_TLSLD_LO;
4223 Flags = PPCII::MO_TOC_LO;
4227 // We found an opportunity. Reverse the operands from the add
4228 // immediate and substitute them into the load or store. If
4229 // needed, update the target flags for the immediate operand to
4230 // reflect the necessary relocation information.
4231 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4232 DEBUG(Base->dump(CurDAG));
4233 DEBUG(dbgs() << "\nN: ");
4234 DEBUG(N->dump(CurDAG));
4235 DEBUG(dbgs() << "\n");
4237 SDValue ImmOpnd = Base.getOperand(1);
4239 // If the relocation information isn't already present on the
4240 // immediate operand, add it now.
4242 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4244 const GlobalValue *GV = GA->getGlobal();
4245 // We can't perform this optimization for data whose alignment
4246 // is insufficient for the instruction encoding.
4247 if (GV->getAlignment() < 4 &&
4248 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4249 StorageOpcode == PPC::LWA)) {
4250 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4253 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4254 } else if (ConstantPoolSDNode *CP =
4255 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4256 const Constant *C = CP->getConstVal();
4257 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4263 if (FirstOp == 1) // Store
4264 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4265 Base.getOperand(0), N->getOperand(3));
4267 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4270 // The add-immediate may now be dead, in which case remove it.
4271 if (Base.getNode()->use_empty())
4272 CurDAG->RemoveDeadNode(Base.getNode());
4277 /// createPPCISelDag - This pass converts a legalized DAG into a
4278 /// PowerPC-specific DAG, ready for instruction scheduling.
4280 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4281 return new PPCDAGToDAGISel(TM);
4284 static void initializePassOnce(PassRegistry &Registry) {
4285 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4286 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4287 nullptr, false, false);
4288 Registry.registerPass(*PI, true);
4291 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4292 CALL_ONCE_INITIALIZATION(initializePassOnce);