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 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1305 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1310 // Instruction selection for the 32-bit case.
1311 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1315 if (InstCnt) *InstCnt = 0;
1317 // Take care of cases that should use andi/andis first.
1318 SelectAndParts32(dl, Res, InstCnt);
1320 // If we've not yet selected a 'starting' instruction, and we have no zeros
1321 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1322 // number of groups), and start with this rotated value.
1323 if ((!HasZeros || LateMask) && !Res) {
1324 ValueRotInfo &VRI = ValueRotsVec[0];
1326 if (InstCnt) *InstCnt += 1;
1328 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1329 getI32Imm(31, dl) };
1330 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1336 // Now, remove all groups with this underlying value and rotation factor.
1337 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1338 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1342 if (InstCnt) *InstCnt += BitGroups.size();
1344 // Insert the other groups (one at a time).
1345 for (auto &BG : BitGroups) {
1348 { BG.V, getI32Imm(BG.RLAmt, dl),
1349 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1350 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1351 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1354 { Res, 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::RLWIMI, dl, MVT::i32, Ops), 0);
1362 unsigned Mask = (unsigned) getZerosMask();
1364 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1365 assert((ANDIMask != 0 || ANDISMask != 0) &&
1366 "No set bits in zeros mask?");
1368 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1369 (unsigned) (ANDISMask != 0) +
1370 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1372 SDValue ANDIVal, ANDISVal;
1374 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1375 Res, getI32Imm(ANDIMask, dl)), 0);
1377 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1378 Res, getI32Imm(ANDISMask, dl)), 0);
1385 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1386 ANDIVal, ANDISVal), 0);
1389 return Res.getNode();
1392 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1393 unsigned MaskStart, unsigned MaskEnd,
1395 // In the notation used by the instructions, 'start' and 'end' are reversed
1396 // because bits are counted from high to low order.
1397 unsigned InstMaskStart = 64 - MaskEnd - 1,
1398 InstMaskEnd = 64 - MaskStart - 1;
1403 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1404 InstMaskEnd == 63 - RLAmt)
1410 // For 64-bit values, not all combinations of rotates and masks are
1411 // available. Produce one if it is available.
1412 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32,
1413 unsigned MaskStart, unsigned MaskEnd,
1414 unsigned *InstCnt = nullptr) {
1415 // In the notation used by the instructions, 'start' and 'end' are reversed
1416 // because bits are counted from high to low order.
1417 unsigned InstMaskStart = 64 - MaskEnd - 1,
1418 InstMaskEnd = 64 - MaskStart - 1;
1420 if (InstCnt) *InstCnt += 1;
1423 // This rotation amount assumes that the lower 32 bits of the quantity
1424 // are replicated in the high 32 bits by the rotation operator (which is
1425 // done by rlwinm and friends).
1426 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1427 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1429 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1430 getI32Imm(InstMaskEnd - 32, dl) };
1431 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1435 if (InstMaskEnd == 63) {
1437 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1438 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1441 if (InstMaskStart == 0) {
1443 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1444 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1447 if (InstMaskEnd == 63 - RLAmt) {
1449 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1450 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1453 // We cannot do this with a single instruction, so we'll use two. The
1454 // problem is that we're not free to choose both a rotation amount and mask
1455 // start and end independently. We can choose an arbitrary mask start and
1456 // end, but then the rotation amount is fixed. Rotation, however, can be
1457 // inverted, and so by applying an "inverse" rotation first, we can get the
1459 if (InstCnt) *InstCnt += 1;
1461 // The rotation mask for the second instruction must be MaskStart.
1462 unsigned RLAmt2 = MaskStart;
1463 // The first instruction must rotate V so that the overall rotation amount
1465 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1467 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1468 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1471 // For 64-bit values, not all combinations of rotates and masks are
1472 // available. Produce a rotate-mask-and-insert if one is available.
1473 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt,
1474 bool Repl32, unsigned MaskStart,
1475 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1476 // In the notation used by the instructions, 'start' and 'end' are reversed
1477 // because bits are counted from high to low order.
1478 unsigned InstMaskStart = 64 - MaskEnd - 1,
1479 InstMaskEnd = 64 - MaskStart - 1;
1481 if (InstCnt) *InstCnt += 1;
1484 // This rotation amount assumes that the lower 32 bits of the quantity
1485 // are replicated in the high 32 bits by the rotation operator (which is
1486 // done by rlwinm and friends).
1487 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1488 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1490 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1491 getI32Imm(InstMaskEnd - 32, dl) };
1492 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1496 if (InstMaskEnd == 63 - RLAmt) {
1498 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1499 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1502 // We cannot do this with a single instruction, so we'll use two. The
1503 // problem is that we're not free to choose both a rotation amount and mask
1504 // start and end independently. We can choose an arbitrary mask start and
1505 // end, but then the rotation amount is fixed. Rotation, however, can be
1506 // inverted, and so by applying an "inverse" rotation first, we can get the
1508 if (InstCnt) *InstCnt += 1;
1510 // The rotation mask for the second instruction must be MaskStart.
1511 unsigned RLAmt2 = MaskStart;
1512 // The first instruction must rotate V so that the overall rotation amount
1514 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1516 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1517 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1520 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1521 if (BPermRewriterNoMasking)
1524 // The idea here is the same as in the 32-bit version, but with additional
1525 // complications from the fact that Repl32 might be true. Because we
1526 // aggressively convert bit groups to Repl32 form (which, for small
1527 // rotation factors, involves no other change), and then coalesce, it might
1528 // be the case that a single 64-bit masking operation could handle both
1529 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1530 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1531 // completely capture the new combined bit group.
1533 for (ValueRotInfo &VRI : ValueRotsVec) {
1536 // We need to add to the mask all bits from the associated bit groups.
1537 // If Repl32 is false, we need to add bits from bit groups that have
1538 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1539 // group is trivially convertable if it overlaps only with the lower 32
1540 // bits, and the group has not been coalesced.
1541 auto MatchingBG = [VRI](const BitGroup &BG) {
1545 unsigned EffRLAmt = BG.RLAmt;
1546 if (!VRI.Repl32 && BG.Repl32) {
1547 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1548 !BG.Repl32Coalesced) {
1554 } else if (VRI.Repl32 != BG.Repl32) {
1558 if (VRI.RLAmt != EffRLAmt)
1564 for (auto &BG : BitGroups) {
1565 if (!MatchingBG(BG))
1568 if (BG.StartIdx <= BG.EndIdx) {
1569 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1570 Mask |= (UINT64_C(1) << i);
1572 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1573 Mask |= (UINT64_C(1) << i);
1574 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1575 Mask |= (UINT64_C(1) << i);
1579 // We can use the 32-bit andi/andis technique if the mask does not
1580 // require any higher-order bits. This can save an instruction compared
1581 // to always using the general 64-bit technique.
1582 bool Use32BitInsts = isUInt<32>(Mask);
1583 // Compute the masks for andi/andis that would be necessary.
1584 unsigned ANDIMask = (Mask & UINT16_MAX),
1585 ANDISMask = (Mask >> 16) & UINT16_MAX;
1587 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1589 unsigned NumAndInsts = (unsigned) NeedsRotate +
1590 (unsigned) (bool) Res;
1592 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1593 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1595 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1597 unsigned NumRLInsts = 0;
1598 bool FirstBG = true;
1599 for (auto &BG : BitGroups) {
1600 if (!MatchingBG(BG))
1603 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1608 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1609 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1610 "\n\t\t\tisel using masking: " << NumAndInsts <<
1611 " using rotates: " << NumRLInsts << "\n");
1613 // When we'd use andi/andis, we bias toward using the rotates (andi only
1614 // has a record form, and is cracked on POWER cores). However, when using
1615 // general 64-bit constant formation, bias toward the constant form,
1616 // because that exposes more opportunities for CSE.
1617 if (NumAndInsts > NumRLInsts)
1619 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1622 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1624 if (InstCnt) *InstCnt += NumAndInsts;
1627 // We actually need to generate a rotation if we have a non-zero rotation
1628 // factor or, in the Repl32 case, if we care about any of the
1629 // higher-order replicated bits. In the latter case, we generate a mask
1630 // backward so that it actually includes the entire 64 bits.
1631 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1632 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1633 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1638 if (Use32BitInsts) {
1639 assert((ANDIMask != 0 || ANDISMask != 0) &&
1640 "No set bits in mask when using 32-bit ands for 64-bit value");
1642 SDValue ANDIVal, ANDISVal;
1644 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1645 VRot, getI32Imm(ANDIMask, dl)), 0);
1647 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1648 VRot, getI32Imm(ANDISMask, dl)), 0);
1651 TotalVal = ANDISVal;
1655 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1656 ANDIVal, ANDISVal), 0);
1658 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1660 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1661 VRot, TotalVal), 0);
1667 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1670 // Now, remove all groups with this underlying value and rotation
1672 eraseMatchingBitGroups(MatchingBG);
1676 // Instruction selection for the 64-bit case.
1677 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1681 if (InstCnt) *InstCnt = 0;
1683 // Take care of cases that should use andi/andis first.
1684 SelectAndParts64(dl, Res, InstCnt);
1686 // If we've not yet selected a 'starting' instruction, and we have no zeros
1687 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1688 // number of groups), and start with this rotated value.
1689 if ((!HasZeros || LateMask) && !Res) {
1690 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1691 // groups will come first, and so the VRI representing the largest number
1692 // of groups might not be first (it might be the first Repl32 groups).
1693 unsigned MaxGroupsIdx = 0;
1694 if (!ValueRotsVec[0].Repl32) {
1695 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1696 if (ValueRotsVec[i].Repl32) {
1697 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1703 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1704 bool NeedsRotate = false;
1707 } else if (VRI.Repl32) {
1708 for (auto &BG : BitGroups) {
1709 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1710 BG.Repl32 != VRI.Repl32)
1713 // We don't need a rotate if the bit group is confined to the lower
1715 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1724 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1725 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1730 // Now, remove all groups with this underlying value and rotation factor.
1732 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1733 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1734 BG.Repl32 == VRI.Repl32;
1738 // Because 64-bit rotates are more flexible than inserts, we might have a
1739 // preference regarding which one we do first (to save one instruction).
1741 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1742 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1744 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1746 if (I != BitGroups.begin()) {
1749 BitGroups.insert(BitGroups.begin(), BG);
1756 // Insert the other groups (one at a time).
1757 for (auto &BG : BitGroups) {
1759 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1760 BG.EndIdx, InstCnt);
1762 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1763 BG.StartIdx, BG.EndIdx, InstCnt);
1767 uint64_t Mask = getZerosMask();
1769 // We can use the 32-bit andi/andis technique if the mask does not
1770 // require any higher-order bits. This can save an instruction compared
1771 // to always using the general 64-bit technique.
1772 bool Use32BitInsts = isUInt<32>(Mask);
1773 // Compute the masks for andi/andis that would be necessary.
1774 unsigned ANDIMask = (Mask & UINT16_MAX),
1775 ANDISMask = (Mask >> 16) & UINT16_MAX;
1777 if (Use32BitInsts) {
1778 assert((ANDIMask != 0 || ANDISMask != 0) &&
1779 "No set bits in mask when using 32-bit ands for 64-bit value");
1781 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1782 (unsigned) (ANDISMask != 0) +
1783 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1785 SDValue ANDIVal, ANDISVal;
1787 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1788 Res, getI32Imm(ANDIMask, dl)), 0);
1790 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1791 Res, getI32Imm(ANDISMask, dl)), 0);
1798 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1799 ANDIVal, ANDISVal), 0);
1801 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1803 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1805 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1810 return Res.getNode();
1813 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1814 // Fill in BitGroups.
1815 collectBitGroups(LateMask);
1816 if (BitGroups.empty())
1819 // For 64-bit values, figure out when we can use 32-bit instructions.
1820 if (Bits.size() == 64)
1821 assignRepl32BitGroups();
1823 // Fill in ValueRotsVec.
1824 collectValueRotInfo();
1826 if (Bits.size() == 32) {
1827 return Select32(N, LateMask, InstCnt);
1829 assert(Bits.size() == 64 && "Not 64 bits here?");
1830 return Select64(N, LateMask, InstCnt);
1836 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1837 BitGroups.erase(std::remove_if(BitGroups.begin(), BitGroups.end(), F),
1841 SmallVector<ValueBit, 64> Bits;
1844 SmallVector<unsigned, 64> RLAmt;
1846 SmallVector<BitGroup, 16> BitGroups;
1848 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1849 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1851 SelectionDAG *CurDAG;
1854 BitPermutationSelector(SelectionDAG *DAG)
1857 // Here we try to match complex bit permutations into a set of
1858 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1859 // known to produce optimial code for common cases (like i32 byte swapping).
1860 SDNode *Select(SDNode *N) {
1861 Bits.resize(N->getValueType(0).getSizeInBits());
1862 if (!getValueBits(SDValue(N, 0), Bits))
1865 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1866 " selection for: ");
1867 DEBUG(N->dump(CurDAG));
1869 // Fill it RLAmt and set HasZeros.
1870 computeRotationAmounts();
1873 return Select(N, false);
1875 // We currently have two techniques for handling results with zeros: early
1876 // masking (the default) and late masking. Late masking is sometimes more
1877 // efficient, but because the structure of the bit groups is different, it
1878 // is hard to tell without generating both and comparing the results. With
1879 // late masking, we ignore zeros in the resulting value when inserting each
1880 // set of bit groups, and then mask in the zeros at the end. With early
1881 // masking, we only insert the non-zero parts of the result at every step.
1883 unsigned InstCnt, InstCntLateMask;
1884 DEBUG(dbgs() << "\tEarly masking:\n");
1885 SDNode *RN = Select(N, false, &InstCnt);
1886 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1888 DEBUG(dbgs() << "\tLate masking:\n");
1889 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1890 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1893 if (InstCnt <= InstCntLateMask) {
1894 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1898 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1902 } // anonymous namespace
1904 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1905 if (N->getValueType(0) != MVT::i32 &&
1906 N->getValueType(0) != MVT::i64)
1909 if (!UseBitPermRewriter)
1912 switch (N->getOpcode()) {
1919 BitPermutationSelector BPS(CurDAG);
1920 return BPS.Select(N);
1927 /// SelectCC - Select a comparison of the specified values with the specified
1928 /// condition code, returning the CR# of the expression.
1929 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1930 ISD::CondCode CC, SDLoc dl) {
1931 // Always select the LHS.
1934 if (LHS.getValueType() == MVT::i32) {
1936 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1937 if (isInt32Immediate(RHS, Imm)) {
1938 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1939 if (isUInt<16>(Imm))
1940 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1941 getI32Imm(Imm & 0xFFFF, dl)),
1943 // If this is a 16-bit signed immediate, fold it.
1944 if (isInt<16>((int)Imm))
1945 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1946 getI32Imm(Imm & 0xFFFF, dl)),
1949 // For non-equality comparisons, the default code would materialize the
1950 // constant, then compare against it, like this:
1952 // ori r2, r2, 22136
1954 // Since we are just comparing for equality, we can emit this instead:
1955 // xoris r0,r3,0x1234
1956 // cmplwi cr0,r0,0x5678
1958 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
1959 getI32Imm(Imm >> 16, dl)), 0);
1960 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1961 getI32Imm(Imm & 0xFFFF, dl)), 0);
1964 } else if (ISD::isUnsignedIntSetCC(CC)) {
1965 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
1966 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1967 getI32Imm(Imm & 0xFFFF, dl)), 0);
1971 if (isIntS16Immediate(RHS, SImm))
1972 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1973 getI32Imm((int)SImm & 0xFFFF,
1978 } else if (LHS.getValueType() == MVT::i64) {
1980 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1981 if (isInt64Immediate(RHS.getNode(), Imm)) {
1982 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1983 if (isUInt<16>(Imm))
1984 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1985 getI32Imm(Imm & 0xFFFF, dl)),
1987 // If this is a 16-bit signed immediate, fold it.
1989 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1990 getI32Imm(Imm & 0xFFFF, dl)),
1993 // For non-equality comparisons, the default code would materialize the
1994 // constant, then compare against it, like this:
1996 // ori r2, r2, 22136
1998 // Since we are just comparing for equality, we can emit this instead:
1999 // xoris r0,r3,0x1234
2000 // cmpldi cr0,r0,0x5678
2002 if (isUInt<32>(Imm)) {
2003 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2004 getI64Imm(Imm >> 16, dl)), 0);
2005 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2006 getI64Imm(Imm & 0xFFFF, dl)),
2011 } else if (ISD::isUnsignedIntSetCC(CC)) {
2012 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2013 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2014 getI64Imm(Imm & 0xFFFF, dl)), 0);
2018 if (isIntS16Immediate(RHS, SImm))
2019 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2020 getI64Imm(SImm & 0xFFFF, dl)),
2024 } else if (LHS.getValueType() == MVT::f32) {
2027 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2028 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2030 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2033 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2039 llvm_unreachable("Should be lowered by legalize!");
2040 default: llvm_unreachable("Unknown condition!");
2042 case ISD::SETEQ: return PPC::PRED_EQ;
2044 case ISD::SETNE: return PPC::PRED_NE;
2046 case ISD::SETLT: return PPC::PRED_LT;
2048 case ISD::SETLE: return PPC::PRED_LE;
2050 case ISD::SETGT: return PPC::PRED_GT;
2052 case ISD::SETGE: return PPC::PRED_GE;
2053 case ISD::SETO: return PPC::PRED_NU;
2054 case ISD::SETUO: return PPC::PRED_UN;
2055 // These two are invalid for floating point. Assume we have int.
2056 case ISD::SETULT: return PPC::PRED_LT;
2057 case ISD::SETUGT: return PPC::PRED_GT;
2061 /// getCRIdxForSetCC - Return the index of the condition register field
2062 /// associated with the SetCC condition, and whether or not the field is
2063 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2064 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2067 default: llvm_unreachable("Unknown condition!");
2069 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2071 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2073 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2074 case ISD::SETUO: return 3; // Bit #3 = SETUO
2076 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2078 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2080 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2081 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2086 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2087 // These are invalid for floating point. Assume integer.
2088 case ISD::SETULT: return 0;
2089 case ISD::SETUGT: return 1;
2093 // getVCmpInst: return the vector compare instruction for the specified
2094 // vector type and condition code. Since this is for altivec specific code,
2095 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2096 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2097 bool HasVSX, bool &Swap, bool &Negate) {
2101 if (VecVT.isFloatingPoint()) {
2102 /* Handle some cases by swapping input operands. */
2104 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2105 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2106 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2107 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2108 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2109 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2112 /* Handle some cases by negating the result. */
2114 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2115 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2116 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2117 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2120 /* We have instructions implementing the remaining cases. */
2124 if (VecVT == MVT::v4f32)
2125 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2126 else if (VecVT == MVT::v2f64)
2127 return PPC::XVCMPEQDP;
2131 if (VecVT == MVT::v4f32)
2132 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2133 else if (VecVT == MVT::v2f64)
2134 return PPC::XVCMPGTDP;
2138 if (VecVT == MVT::v4f32)
2139 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2140 else if (VecVT == MVT::v2f64)
2141 return PPC::XVCMPGEDP;
2146 llvm_unreachable("Invalid floating-point vector compare condition");
2148 /* Handle some cases by swapping input operands. */
2150 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2151 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2152 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2153 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2156 /* Handle some cases by negating the result. */
2158 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2159 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2160 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2161 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2164 /* We have instructions implementing the remaining cases. */
2168 if (VecVT == MVT::v16i8)
2169 return PPC::VCMPEQUB;
2170 else if (VecVT == MVT::v8i16)
2171 return PPC::VCMPEQUH;
2172 else if (VecVT == MVT::v4i32)
2173 return PPC::VCMPEQUW;
2174 else if (VecVT == MVT::v2i64)
2175 return PPC::VCMPEQUD;
2178 if (VecVT == MVT::v16i8)
2179 return PPC::VCMPGTSB;
2180 else if (VecVT == MVT::v8i16)
2181 return PPC::VCMPGTSH;
2182 else if (VecVT == MVT::v4i32)
2183 return PPC::VCMPGTSW;
2184 else if (VecVT == MVT::v2i64)
2185 return PPC::VCMPGTSD;
2188 if (VecVT == MVT::v16i8)
2189 return PPC::VCMPGTUB;
2190 else if (VecVT == MVT::v8i16)
2191 return PPC::VCMPGTUH;
2192 else if (VecVT == MVT::v4i32)
2193 return PPC::VCMPGTUW;
2194 else if (VecVT == MVT::v2i64)
2195 return PPC::VCMPGTUD;
2200 llvm_unreachable("Invalid integer vector compare condition");
2204 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2207 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2208 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2209 bool isPPC64 = (PtrVT == MVT::i64);
2211 if (!PPCSubTarget->useCRBits() &&
2212 isInt32Immediate(N->getOperand(1), Imm)) {
2213 // We can codegen setcc op, imm very efficiently compared to a brcond.
2214 // Check for those cases here.
2217 SDValue Op = N->getOperand(0);
2221 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2222 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2223 getI32Imm(31, dl) };
2224 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2229 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2230 Op, getI32Imm(~0U, dl)), 0);
2231 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2235 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2236 getI32Imm(31, dl) };
2237 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2241 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2242 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2243 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2244 getI32Imm(31, dl) };
2245 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2248 } else if (Imm == ~0U) { // setcc op, -1
2249 SDValue Op = N->getOperand(0);
2254 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2255 Op, getI32Imm(1, dl)), 0);
2256 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2257 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2260 0), Op.getValue(1));
2263 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2264 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2265 Op, getI32Imm(~0U, dl));
2266 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2267 Op, SDValue(AD, 1));
2270 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2271 getI32Imm(1, dl)), 0);
2272 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2274 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2275 getI32Imm(31, dl) };
2276 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2279 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2280 getI32Imm(31, dl) };
2281 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2282 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2289 SDValue LHS = N->getOperand(0);
2290 SDValue RHS = N->getOperand(1);
2292 // Altivec Vector compare instructions do not set any CR register by default and
2293 // vector compare operations return the same type as the operands.
2294 if (LHS.getValueType().isVector()) {
2295 if (PPCSubTarget->hasQPX())
2298 EVT VecVT = LHS.getValueType();
2300 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2301 PPCSubTarget->hasVSX(), Swap, Negate);
2303 std::swap(LHS, RHS);
2306 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2307 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2312 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2315 if (PPCSubTarget->useCRBits())
2319 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2320 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2323 // Force the ccreg into CR7.
2324 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2326 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2327 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2328 InFlag).getValue(1);
2330 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2333 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2334 getI32Imm(31, dl), getI32Imm(31, dl) };
2336 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2338 // Get the specified bit.
2340 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2341 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2344 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2345 // Transfer memoperands.
2346 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2347 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2348 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2353 // Select - Convert the specified operand from a target-independent to a
2354 // target-specific node if it hasn't already been changed.
2355 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2357 if (N->isMachineOpcode()) {
2359 return nullptr; // Already selected.
2362 // In case any misguided DAG-level optimizations form an ADD with a
2363 // TargetConstant operand, crash here instead of miscompiling (by selecting
2364 // an r+r add instead of some kind of r+i add).
2365 if (N->getOpcode() == ISD::ADD &&
2366 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2367 llvm_unreachable("Invalid ADD with TargetConstant operand");
2369 // Try matching complex bit permutations before doing anything else.
2370 if (SDNode *NN = SelectBitPermutation(N))
2373 switch (N->getOpcode()) {
2376 case ISD::Constant: {
2377 if (N->getValueType(0) == MVT::i64)
2378 return SelectInt64(CurDAG, N);
2383 SDNode *SN = SelectSETCC(N);
2388 case PPCISD::GlobalBaseReg:
2389 return getGlobalBaseReg();
2391 case ISD::FrameIndex:
2392 return getFrameIndex(N, N);
2394 case PPCISD::MFOCRF: {
2395 SDValue InFlag = N->getOperand(1);
2396 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2397 N->getOperand(0), InFlag);
2400 case PPCISD::READ_TIME_BASE: {
2401 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2402 MVT::Other, N->getOperand(0));
2405 case PPCISD::SRA_ADDZE: {
2406 SDValue N0 = N->getOperand(0);
2408 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2409 getConstantIntValue(), dl,
2410 N->getValueType(0));
2411 if (N->getValueType(0) == MVT::i64) {
2413 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2415 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2416 SDValue(Op, 0), SDValue(Op, 1));
2418 assert(N->getValueType(0) == MVT::i32 &&
2419 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2421 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2423 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2424 SDValue(Op, 0), SDValue(Op, 1));
2429 // Handle preincrement loads.
2430 LoadSDNode *LD = cast<LoadSDNode>(N);
2431 EVT LoadedVT = LD->getMemoryVT();
2433 // Normal loads are handled by code generated from the .td file.
2434 if (LD->getAddressingMode() != ISD::PRE_INC)
2437 SDValue Offset = LD->getOffset();
2438 if (Offset.getOpcode() == ISD::TargetConstant ||
2439 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2442 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2443 if (LD->getValueType(0) != MVT::i64) {
2444 // Handle PPC32 integer and normal FP loads.
2445 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2446 switch (LoadedVT.getSimpleVT().SimpleTy) {
2447 default: llvm_unreachable("Invalid PPC load type!");
2448 case MVT::f64: Opcode = PPC::LFDU; break;
2449 case MVT::f32: Opcode = PPC::LFSU; break;
2450 case MVT::i32: Opcode = PPC::LWZU; break;
2451 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2453 case MVT::i8: Opcode = PPC::LBZU; break;
2456 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2457 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2458 switch (LoadedVT.getSimpleVT().SimpleTy) {
2459 default: llvm_unreachable("Invalid PPC load type!");
2460 case MVT::i64: Opcode = PPC::LDU; break;
2461 case MVT::i32: Opcode = PPC::LWZU8; break;
2462 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2464 case MVT::i8: Opcode = PPC::LBZU8; break;
2468 SDValue Chain = LD->getChain();
2469 SDValue Base = LD->getBasePtr();
2470 SDValue Ops[] = { Offset, Base, Chain };
2471 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2472 LD->getValueType(0),
2473 PPCLowering->getPointerTy(),
2477 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2478 if (LD->getValueType(0) != MVT::i64) {
2479 // Handle PPC32 integer and normal FP loads.
2480 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2481 switch (LoadedVT.getSimpleVT().SimpleTy) {
2482 default: llvm_unreachable("Invalid PPC load type!");
2483 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2484 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2485 case MVT::f64: Opcode = PPC::LFDUX; break;
2486 case MVT::f32: Opcode = PPC::LFSUX; break;
2487 case MVT::i32: Opcode = PPC::LWZUX; break;
2488 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2490 case MVT::i8: Opcode = PPC::LBZUX; break;
2493 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2494 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2495 "Invalid sext update load");
2496 switch (LoadedVT.getSimpleVT().SimpleTy) {
2497 default: llvm_unreachable("Invalid PPC load type!");
2498 case MVT::i64: Opcode = PPC::LDUX; break;
2499 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2500 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2502 case MVT::i8: Opcode = PPC::LBZUX8; break;
2506 SDValue Chain = LD->getChain();
2507 SDValue Base = LD->getBasePtr();
2508 SDValue Ops[] = { Base, Offset, Chain };
2509 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2510 LD->getValueType(0),
2511 PPCLowering->getPointerTy(),
2517 unsigned Imm, Imm2, SH, MB, ME;
2520 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2521 // with a mask, emit rlwinm
2522 if (isInt32Immediate(N->getOperand(1), Imm) &&
2523 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2524 SDValue Val = N->getOperand(0).getOperand(0);
2525 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2526 getI32Imm(ME, dl) };
2527 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2529 // If this is just a masked value where the input is not handled above, and
2530 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2531 if (isInt32Immediate(N->getOperand(1), Imm) &&
2532 isRunOfOnes(Imm, MB, ME) &&
2533 N->getOperand(0).getOpcode() != ISD::ROTL) {
2534 SDValue Val = N->getOperand(0);
2535 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2536 getI32Imm(ME, dl) };
2537 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2539 // If this is a 64-bit zero-extension mask, emit rldicl.
2540 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2542 SDValue Val = N->getOperand(0);
2543 MB = 64 - countTrailingOnes(Imm64);
2546 // If the operand is a logical right shift, we can fold it into this
2547 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2548 // for n <= mb. The right shift is really a left rotate followed by a
2549 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2551 if (Val.getOpcode() == ISD::SRL &&
2552 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2553 assert(Imm < 64 && "Illegal shift amount");
2554 Val = Val.getOperand(0);
2558 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2559 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2561 // AND X, 0 -> 0, not "rlwinm 32".
2562 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2563 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2566 // ISD::OR doesn't get all the bitfield insertion fun.
2567 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2568 if (isInt32Immediate(N->getOperand(1), Imm) &&
2569 N->getOperand(0).getOpcode() == ISD::OR &&
2570 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2573 if (isRunOfOnes(Imm, MB, ME)) {
2574 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2575 N->getOperand(0).getOperand(1),
2576 getI32Imm(0, dl), getI32Imm(MB, dl),
2577 getI32Imm(ME, dl) };
2578 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2582 // Other cases are autogenerated.
2586 if (N->getValueType(0) == MVT::i32)
2587 if (SDNode *I = SelectBitfieldInsert(N))
2591 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2592 isIntS16Immediate(N->getOperand(1), Imm)) {
2593 APInt LHSKnownZero, LHSKnownOne;
2594 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2596 // If this is equivalent to an add, then we can fold it with the
2597 // FrameIndex calculation.
2598 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2599 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2602 // Other cases are autogenerated.
2607 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2608 isIntS16Immediate(N->getOperand(1), Imm))
2609 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2614 unsigned Imm, SH, MB, ME;
2615 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2616 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2617 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2618 getI32Imm(SH, dl), getI32Imm(MB, dl),
2619 getI32Imm(ME, dl) };
2620 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2623 // Other cases are autogenerated.
2627 unsigned Imm, SH, MB, ME;
2628 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2629 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2630 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2631 getI32Imm(SH, dl), getI32Imm(MB, dl),
2632 getI32Imm(ME, dl) };
2633 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2636 // Other cases are autogenerated.
2639 // FIXME: Remove this once the ANDI glue bug is fixed:
2640 case PPCISD::ANDIo_1_EQ_BIT:
2641 case PPCISD::ANDIo_1_GT_BIT: {
2645 EVT InVT = N->getOperand(0).getValueType();
2646 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2647 "Invalid input type for ANDIo_1_EQ_BIT");
2649 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2650 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2652 CurDAG->getTargetConstant(1, dl, InVT)),
2654 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2656 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2657 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2659 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2661 SDValue(AndI.getNode(), 1) /* glue */);
2663 case ISD::SELECT_CC: {
2664 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2665 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2666 bool isPPC64 = (PtrVT == MVT::i64);
2668 // If this is a select of i1 operands, we'll pattern match it.
2669 if (PPCSubTarget->useCRBits() &&
2670 N->getOperand(0).getValueType() == MVT::i1)
2673 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2675 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2676 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2677 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2678 if (N1C->isNullValue() && N3C->isNullValue() &&
2679 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2680 // FIXME: Implement this optzn for PPC64.
2681 N->getValueType(0) == MVT::i32) {
2683 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2684 N->getOperand(0), getI32Imm(~0U, dl));
2685 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2686 SDValue(Tmp, 0), N->getOperand(0),
2690 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2692 if (N->getValueType(0) == MVT::i1) {
2693 // An i1 select is: (c & t) | (!c & f).
2695 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2699 default: llvm_unreachable("Invalid CC index");
2700 case 0: SRI = PPC::sub_lt; break;
2701 case 1: SRI = PPC::sub_gt; break;
2702 case 2: SRI = PPC::sub_eq; break;
2703 case 3: SRI = PPC::sub_un; break;
2706 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2708 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2710 SDValue C = Inv ? NotCCBit : CCBit,
2711 NotC = Inv ? CCBit : NotCCBit;
2713 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2714 C, N->getOperand(2)), 0);
2715 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2716 NotC, N->getOperand(3)), 0);
2718 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2721 unsigned BROpc = getPredicateForSetCC(CC);
2723 unsigned SelectCCOp;
2724 if (N->getValueType(0) == MVT::i32)
2725 SelectCCOp = PPC::SELECT_CC_I4;
2726 else if (N->getValueType(0) == MVT::i64)
2727 SelectCCOp = PPC::SELECT_CC_I8;
2728 else if (N->getValueType(0) == MVT::f32)
2729 if (PPCSubTarget->hasP8Vector())
2730 SelectCCOp = PPC::SELECT_CC_VSSRC;
2732 SelectCCOp = PPC::SELECT_CC_F4;
2733 else if (N->getValueType(0) == MVT::f64)
2734 if (PPCSubTarget->hasVSX())
2735 SelectCCOp = PPC::SELECT_CC_VSFRC;
2737 SelectCCOp = PPC::SELECT_CC_F8;
2738 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2739 SelectCCOp = PPC::SELECT_CC_QFRC;
2740 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2741 SelectCCOp = PPC::SELECT_CC_QSRC;
2742 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2743 SelectCCOp = PPC::SELECT_CC_QBRC;
2744 else if (N->getValueType(0) == MVT::v2f64 ||
2745 N->getValueType(0) == MVT::v2i64)
2746 SelectCCOp = PPC::SELECT_CC_VSRC;
2748 SelectCCOp = PPC::SELECT_CC_VRRC;
2750 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2751 getI32Imm(BROpc, dl) };
2752 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2755 if (PPCSubTarget->hasVSX()) {
2756 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2757 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2761 case ISD::VECTOR_SHUFFLE:
2762 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2763 N->getValueType(0) == MVT::v2i64)) {
2764 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2766 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2767 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2770 for (int i = 0; i < 2; ++i)
2771 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2776 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2777 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2778 isa<LoadSDNode>(Op1.getOperand(0))) {
2779 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2780 SDValue Base, Offset;
2782 if (LD->isUnindexed() &&
2783 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2784 SDValue Chain = LD->getChain();
2785 SDValue Ops[] = { Base, Offset, Chain };
2786 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2787 N->getValueType(0), Ops);
2791 // For little endian, we must swap the input operands and adjust
2792 // the mask elements (reverse and invert them).
2793 if (PPCSubTarget->isLittleEndian()) {
2794 std::swap(Op1, Op2);
2795 unsigned tmp = DM[0];
2800 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2802 SDValue Ops[] = { Op1, Op2, DMV };
2803 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2809 bool IsPPC64 = PPCSubTarget->isPPC64();
2810 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2811 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2812 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2813 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2816 case PPCISD::COND_BRANCH: {
2817 // Op #0 is the Chain.
2818 // Op #1 is the PPC::PRED_* number.
2820 // Op #3 is the Dest MBB
2821 // Op #4 is the Flag.
2822 // Prevent PPC::PRED_* from being selected into LI.
2824 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(), dl);
2825 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2826 N->getOperand(0), N->getOperand(4) };
2827 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2830 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2831 unsigned PCC = getPredicateForSetCC(CC);
2833 if (N->getOperand(2).getValueType() == MVT::i1) {
2837 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2838 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2839 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2840 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2841 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2842 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2843 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2846 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2847 N->getOperand(Swap ? 3 : 2),
2848 N->getOperand(Swap ? 2 : 3)), 0);
2849 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2850 BitComp, N->getOperand(4), N->getOperand(0));
2853 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2854 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
2855 N->getOperand(4), N->getOperand(0) };
2856 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2859 // FIXME: Should custom lower this.
2860 SDValue Chain = N->getOperand(0);
2861 SDValue Target = N->getOperand(1);
2862 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2863 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2864 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2866 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2868 case PPCISD::TOC_ENTRY: {
2869 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2870 "Only supported for 64-bit ABI and 32-bit SVR4");
2871 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2872 SDValue GA = N->getOperand(0);
2873 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2874 MVT::i32, GA, N->getOperand(1)));
2877 // For medium and large code model, we generate two instructions as
2878 // described below. Otherwise we allow SelectCodeCommon to handle this,
2879 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2880 CodeModel::Model CModel = TM.getCodeModel();
2881 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2884 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2885 // If it is an externally defined symbol, a symbol with common linkage,
2886 // a non-local function address, or a jump table address, or if we are
2887 // generating code for large code model, we generate:
2888 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2889 // Otherwise we generate:
2890 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2891 SDValue GA = N->getOperand(0);
2892 SDValue TOCbase = N->getOperand(1);
2893 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2896 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2897 CModel == CodeModel::Large)
2898 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2899 MVT::i64, GA, SDValue(Tmp, 0)));
2901 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2902 const GlobalValue *GValue = G->getGlobal();
2903 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2904 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2905 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2906 GValue->hasAvailableExternallyLinkage())
2907 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2908 MVT::i64, GA, SDValue(Tmp, 0)));
2911 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2912 SDValue(Tmp, 0), GA);
2914 case PPCISD::PPC32_PICGOT: {
2915 // Generate a PIC-safe GOT reference.
2916 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2917 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2918 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2920 case PPCISD::VADD_SPLAT: {
2921 // This expands into one of three sequences, depending on whether
2922 // the first operand is odd or even, positive or negative.
2923 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2924 isa<ConstantSDNode>(N->getOperand(1)) &&
2925 "Invalid operand on VADD_SPLAT!");
2927 int Elt = N->getConstantOperandVal(0);
2928 int EltSize = N->getConstantOperandVal(1);
2929 unsigned Opc1, Opc2, Opc3;
2933 Opc1 = PPC::VSPLTISB;
2934 Opc2 = PPC::VADDUBM;
2935 Opc3 = PPC::VSUBUBM;
2937 } else if (EltSize == 2) {
2938 Opc1 = PPC::VSPLTISH;
2939 Opc2 = PPC::VADDUHM;
2940 Opc3 = PPC::VSUBUHM;
2943 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2944 Opc1 = PPC::VSPLTISW;
2945 Opc2 = PPC::VADDUWM;
2946 Opc3 = PPC::VSUBUWM;
2950 if ((Elt & 1) == 0) {
2951 // Elt is even, in the range [-32,-18] + [16,30].
2953 // Convert: VADD_SPLAT elt, size
2954 // Into: tmp = VSPLTIS[BHW] elt
2955 // VADDU[BHW]M tmp, tmp
2956 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2957 SDValue EltVal = getI32Imm(Elt >> 1, dl);
2958 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2959 SDValue TmpVal = SDValue(Tmp, 0);
2960 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2962 } else if (Elt > 0) {
2963 // Elt is odd and positive, in the range [17,31].
2965 // Convert: VADD_SPLAT elt, size
2966 // Into: tmp1 = VSPLTIS[BHW] elt-16
2967 // tmp2 = VSPLTIS[BHW] -16
2968 // VSUBU[BHW]M tmp1, tmp2
2969 SDValue EltVal = getI32Imm(Elt - 16, dl);
2970 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2971 EltVal = getI32Imm(-16, dl);
2972 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2973 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2977 // Elt is odd and negative, in the range [-31,-17].
2979 // Convert: VADD_SPLAT elt, size
2980 // Into: tmp1 = VSPLTIS[BHW] elt+16
2981 // tmp2 = VSPLTIS[BHW] -16
2982 // VADDU[BHW]M tmp1, tmp2
2983 SDValue EltVal = getI32Imm(Elt + 16, dl);
2984 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2985 EltVal = getI32Imm(-16, dl);
2986 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2987 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
2993 return SelectCode(N);
2996 // If the target supports the cmpb instruction, do the idiom recognition here.
2997 // We don't do this as a DAG combine because we don't want to do it as nodes
2998 // are being combined (because we might miss part of the eventual idiom). We
2999 // don't want to do it during instruction selection because we want to reuse
3000 // the logic for lowering the masking operations already part of the
3001 // instruction selector.
3002 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3005 assert(N->getOpcode() == ISD::OR &&
3006 "Only OR nodes are supported for CMPB");
3009 if (!PPCSubTarget->hasCMPB())
3012 if (N->getValueType(0) != MVT::i32 &&
3013 N->getValueType(0) != MVT::i64)
3016 EVT VT = N->getValueType(0);
3019 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3020 uint64_t Mask = 0, Alt = 0;
3022 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3023 uint64_t &Mask, uint64_t &Alt,
3024 SDValue &LHS, SDValue &RHS) {
3025 if (O.getOpcode() != ISD::SELECT_CC)
3027 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3029 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3030 !isa<ConstantSDNode>(O.getOperand(3)))
3033 uint64_t PM = O.getConstantOperandVal(2);
3034 uint64_t PAlt = O.getConstantOperandVal(3);
3035 for (b = 0; b < 8; ++b) {
3036 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3037 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3046 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3047 O.getConstantOperandVal(1) != 0) {
3048 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3049 if (Op0.getOpcode() == ISD::TRUNCATE)
3050 Op0 = Op0.getOperand(0);
3051 if (Op1.getOpcode() == ISD::TRUNCATE)
3052 Op1 = Op1.getOperand(0);
3054 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3055 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3056 isa<ConstantSDNode>(Op0.getOperand(1))) {
3058 unsigned Bits = Op0.getValueType().getSizeInBits();
3061 if (Op0.getConstantOperandVal(1) != Bits-8)
3064 LHS = Op0.getOperand(0);
3065 RHS = Op1.getOperand(0);
3069 // When we have small integers (i16 to be specific), the form present
3070 // post-legalization uses SETULT in the SELECT_CC for the
3071 // higher-order byte, depending on the fact that the
3072 // even-higher-order bytes are known to all be zero, for example:
3073 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3074 // (so when the second byte is the same, because all higher-order
3075 // bits from bytes 3 and 4 are known to be zero, the result of the
3076 // xor can be at most 255)
3077 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3078 isa<ConstantSDNode>(O.getOperand(1))) {
3080 uint64_t ULim = O.getConstantOperandVal(1);
3081 if (ULim != (UINT64_C(1) << b*8))
3084 // Now we need to make sure that the upper bytes are known to be
3086 unsigned Bits = Op0.getValueType().getSizeInBits();
3087 if (!CurDAG->MaskedValueIsZero(Op0,
3088 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3091 LHS = Op0.getOperand(0);
3092 RHS = Op0.getOperand(1);
3099 if (CC != ISD::SETEQ)
3102 SDValue Op = O.getOperand(0);
3103 if (Op.getOpcode() == ISD::AND) {
3104 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3106 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3109 SDValue XOR = Op.getOperand(0);
3110 if (XOR.getOpcode() == ISD::TRUNCATE)
3111 XOR = XOR.getOperand(0);
3112 if (XOR.getOpcode() != ISD::XOR)
3115 LHS = XOR.getOperand(0);
3116 RHS = XOR.getOperand(1);
3118 } else if (Op.getOpcode() == ISD::SRL) {
3119 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3121 unsigned Bits = Op.getValueType().getSizeInBits();
3124 if (Op.getConstantOperandVal(1) != Bits-8)
3127 SDValue XOR = Op.getOperand(0);
3128 if (XOR.getOpcode() == ISD::TRUNCATE)
3129 XOR = XOR.getOperand(0);
3130 if (XOR.getOpcode() != ISD::XOR)
3133 LHS = XOR.getOperand(0);
3134 RHS = XOR.getOperand(1);
3141 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3142 while (!Queue.empty()) {
3143 SDValue V = Queue.pop_back_val();
3145 for (const SDValue &O : V.getNode()->ops()) {
3147 uint64_t M = 0, A = 0;
3149 if (O.getOpcode() == ISD::OR) {
3151 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3155 BytesFound[b] = true;
3158 } else if ((LHS == ORHS && RHS == OLHS) ||
3159 (RHS == ORHS && LHS == OLHS)) {
3160 BytesFound[b] = true;
3172 unsigned LastB = 0, BCnt = 0;
3173 for (unsigned i = 0; i < 8; ++i)
3174 if (BytesFound[LastB]) {
3179 if (!LastB || BCnt < 2)
3182 // Because we'll be zero-extending the output anyway if don't have a specific
3183 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3184 if (LHS.getValueType() != VT) {
3185 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3186 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3189 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3191 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3192 if (NonTrivialMask && !Alt) {
3193 // Res = Mask & CMPB
3194 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3195 CurDAG->getConstant(Mask, dl, VT));
3197 // Res = (CMPB & Mask) | (~CMPB & Alt)
3198 // Which, as suggested here:
3199 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3200 // can be written as:
3201 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3202 // useful because the (Alt ^ Mask) can be pre-computed.
3203 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3204 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3205 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3206 CurDAG->getConstant(Alt, dl, VT));
3212 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3213 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3214 // involves constant materialization of a 0 or a 1 or both. If the result of
3215 // the extension is then operated upon by some operator that can be constant
3216 // folded with a constant 0 or 1, and that constant can be materialized using
3217 // only one instruction (like a zero or one), then we should fold in those
3218 // operations with the select.
3219 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3220 if (!PPCSubTarget->useCRBits())
3223 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3224 N->getOpcode() != ISD::SIGN_EXTEND &&
3225 N->getOpcode() != ISD::ANY_EXTEND)
3228 if (N->getOperand(0).getValueType() != MVT::i1)
3231 if (!N->hasOneUse())
3235 EVT VT = N->getValueType(0);
3236 SDValue Cond = N->getOperand(0);
3238 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3239 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3242 SDNode *User = *N->use_begin();
3243 if (User->getNumOperands() != 2)
3246 auto TryFold = [this, N, User, dl](SDValue Val) {
3247 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3248 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3249 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3251 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3252 User->getValueType(0),
3253 O0.getNode(), O1.getNode());
3256 SDValue TrueRes = TryFold(ConstTrue);
3259 SDValue FalseRes = TryFold(ConstFalse);
3263 // For us to materialize these using one instruction, we must be able to
3264 // represent them as signed 16-bit integers.
3265 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3266 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3267 if (!isInt<16>(True) || !isInt<16>(False))
3270 // We can replace User with a new SELECT node, and try again to see if we
3271 // can fold the select with its user.
3272 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3274 ConstTrue = TrueRes;
3275 ConstFalse = FalseRes;
3276 } while (N->hasOneUse());
3279 void PPCDAGToDAGISel::PreprocessISelDAG() {
3280 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3283 bool MadeChange = false;
3284 while (Position != CurDAG->allnodes_begin()) {
3285 SDNode *N = --Position;
3290 switch (N->getOpcode()) {
3293 Res = combineToCMPB(N);
3298 foldBoolExts(Res, N);
3301 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3302 DEBUG(N->dump(CurDAG));
3303 DEBUG(dbgs() << "\nNew: ");
3304 DEBUG(Res.getNode()->dump(CurDAG));
3305 DEBUG(dbgs() << "\n");
3307 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3313 CurDAG->RemoveDeadNodes();
3316 /// PostprocessISelDAG - Perform some late peephole optimizations
3317 /// on the DAG representation.
3318 void PPCDAGToDAGISel::PostprocessISelDAG() {
3320 // Skip peepholes at -O0.
3321 if (TM.getOptLevel() == CodeGenOpt::None)
3326 PeepholePPC64ZExt();
3329 // Check if all users of this node will become isel where the second operand
3330 // is the constant zero. If this is so, and if we can negate the condition,
3331 // then we can flip the true and false operands. This will allow the zero to
3332 // be folded with the isel so that we don't need to materialize a register
3334 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3335 // If we're not using isel, then this does not matter.
3336 if (!PPCSubTarget->hasISEL())
3339 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3342 if (!User->isMachineOpcode())
3344 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3345 User->getMachineOpcode() != PPC::SELECT_I8)
3348 SDNode *Op2 = User->getOperand(2).getNode();
3349 if (!Op2->isMachineOpcode())
3352 if (Op2->getMachineOpcode() != PPC::LI &&
3353 Op2->getMachineOpcode() != PPC::LI8)
3356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3360 if (!C->isNullValue())
3367 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3368 SmallVector<SDNode *, 4> ToReplace;
3369 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3372 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3373 User->getMachineOpcode() == PPC::SELECT_I8) &&
3374 "Must have all select users");
3375 ToReplace.push_back(User);
3378 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3379 UE = ToReplace.end(); UI != UE; ++UI) {
3382 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3383 User->getValueType(0), User->getOperand(0),
3384 User->getOperand(2),
3385 User->getOperand(1));
3387 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3388 DEBUG(User->dump(CurDAG));
3389 DEBUG(dbgs() << "\nNew: ");
3390 DEBUG(ResNode->dump(CurDAG));
3391 DEBUG(dbgs() << "\n");
3393 ReplaceUses(User, ResNode);
3397 void PPCDAGToDAGISel::PeepholeCROps() {
3401 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3402 E = CurDAG->allnodes_end(); I != E; ++I) {
3403 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3404 if (!MachineNode || MachineNode->use_empty())
3406 SDNode *ResNode = MachineNode;
3408 bool Op1Set = false, Op1Unset = false,
3410 Op2Set = false, Op2Unset = false,
3413 unsigned Opcode = MachineNode->getMachineOpcode();
3424 SDValue Op = MachineNode->getOperand(1);
3425 if (Op.isMachineOpcode()) {
3426 if (Op.getMachineOpcode() == PPC::CRSET)
3428 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3430 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3431 Op.getOperand(0) == Op.getOperand(1))
3437 case PPC::SELECT_I4:
3438 case PPC::SELECT_I8:
3439 case PPC::SELECT_F4:
3440 case PPC::SELECT_F8:
3441 case PPC::SELECT_QFRC:
3442 case PPC::SELECT_QSRC:
3443 case PPC::SELECT_QBRC:
3444 case PPC::SELECT_VRRC:
3445 case PPC::SELECT_VSFRC:
3446 case PPC::SELECT_VSSRC:
3447 case PPC::SELECT_VSRC: {
3448 SDValue Op = MachineNode->getOperand(0);
3449 if (Op.isMachineOpcode()) {
3450 if (Op.getMachineOpcode() == PPC::CRSET)
3452 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3454 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3455 Op.getOperand(0) == Op.getOperand(1))
3462 bool SelectSwap = false;
3466 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3468 ResNode = MachineNode->getOperand(0).getNode();
3471 ResNode = MachineNode->getOperand(1).getNode();
3474 ResNode = MachineNode->getOperand(0).getNode();
3475 else if (Op1Unset || Op2Unset)
3476 // x & 0 = 0 & y = 0
3477 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3480 // ~x & y = andc(y, x)
3481 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3482 MVT::i1, MachineNode->getOperand(1),
3483 MachineNode->getOperand(0).
3486 // x & ~y = andc(x, y)
3487 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3488 MVT::i1, MachineNode->getOperand(0),
3489 MachineNode->getOperand(1).
3491 else if (AllUsersSelectZero(MachineNode))
3492 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3493 MVT::i1, MachineNode->getOperand(0),
3494 MachineNode->getOperand(1)),
3498 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3499 // nand(x, x) -> nor(x, x)
3500 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3501 MVT::i1, MachineNode->getOperand(0),
3502 MachineNode->getOperand(0));
3504 // nand(1, y) -> nor(y, y)
3505 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3506 MVT::i1, MachineNode->getOperand(1),
3507 MachineNode->getOperand(1));
3509 // nand(x, 1) -> nor(x, x)
3510 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3511 MVT::i1, MachineNode->getOperand(0),
3512 MachineNode->getOperand(0));
3513 else if (Op1Unset || Op2Unset)
3514 // nand(x, 0) = nand(0, y) = 1
3515 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3518 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3519 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3520 MVT::i1, MachineNode->getOperand(0).
3522 MachineNode->getOperand(1));
3524 // nand(x, ~y) = ~x | y = orc(y, x)
3525 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3526 MVT::i1, MachineNode->getOperand(1).
3528 MachineNode->getOperand(0));
3529 else if (AllUsersSelectZero(MachineNode))
3530 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3531 MVT::i1, MachineNode->getOperand(0),
3532 MachineNode->getOperand(1)),
3536 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3538 ResNode = MachineNode->getOperand(0).getNode();
3539 else if (Op1Set || Op2Set)
3540 // x | 1 = 1 | y = 1
3541 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3545 ResNode = MachineNode->getOperand(1).getNode();
3548 ResNode = MachineNode->getOperand(0).getNode();
3550 // ~x | y = orc(y, x)
3551 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3552 MVT::i1, MachineNode->getOperand(1),
3553 MachineNode->getOperand(0).
3556 // x | ~y = orc(x, y)
3557 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3558 MVT::i1, MachineNode->getOperand(0),
3559 MachineNode->getOperand(1).
3561 else if (AllUsersSelectZero(MachineNode))
3562 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3563 MVT::i1, MachineNode->getOperand(0),
3564 MachineNode->getOperand(1)),
3568 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3570 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3573 // xor(1, y) -> nor(y, y)
3574 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3575 MVT::i1, MachineNode->getOperand(1),
3576 MachineNode->getOperand(1));
3578 // xor(x, 1) -> nor(x, x)
3579 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3580 MVT::i1, MachineNode->getOperand(0),
3581 MachineNode->getOperand(0));
3584 ResNode = MachineNode->getOperand(1).getNode();
3587 ResNode = MachineNode->getOperand(0).getNode();
3589 // xor(~x, y) = eqv(x, y)
3590 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3591 MVT::i1, MachineNode->getOperand(0).
3593 MachineNode->getOperand(1));
3595 // xor(x, ~y) = eqv(x, y)
3596 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3597 MVT::i1, MachineNode->getOperand(0),
3598 MachineNode->getOperand(1).
3600 else if (AllUsersSelectZero(MachineNode))
3601 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3602 MVT::i1, MachineNode->getOperand(0),
3603 MachineNode->getOperand(1)),
3607 if (Op1Set || Op2Set)
3609 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3612 // nor(0, y) = ~y -> nor(y, y)
3613 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3614 MVT::i1, MachineNode->getOperand(1),
3615 MachineNode->getOperand(1));
3618 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3619 MVT::i1, MachineNode->getOperand(0),
3620 MachineNode->getOperand(0));
3622 // nor(~x, y) = andc(x, y)
3623 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3624 MVT::i1, MachineNode->getOperand(0).
3626 MachineNode->getOperand(1));
3628 // nor(x, ~y) = andc(y, x)
3629 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3630 MVT::i1, MachineNode->getOperand(1).
3632 MachineNode->getOperand(0));
3633 else if (AllUsersSelectZero(MachineNode))
3634 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3635 MVT::i1, MachineNode->getOperand(0),
3636 MachineNode->getOperand(1)),
3640 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3642 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3646 ResNode = MachineNode->getOperand(1).getNode();
3649 ResNode = MachineNode->getOperand(0).getNode();
3651 // eqv(0, y) = ~y -> nor(y, y)
3652 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3653 MVT::i1, MachineNode->getOperand(1),
3654 MachineNode->getOperand(1));
3657 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3658 MVT::i1, MachineNode->getOperand(0),
3659 MachineNode->getOperand(0));
3661 // eqv(~x, y) = xor(x, y)
3662 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3663 MVT::i1, MachineNode->getOperand(0).
3665 MachineNode->getOperand(1));
3667 // eqv(x, ~y) = xor(x, y)
3668 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3669 MVT::i1, MachineNode->getOperand(0),
3670 MachineNode->getOperand(1).
3672 else if (AllUsersSelectZero(MachineNode))
3673 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3674 MVT::i1, MachineNode->getOperand(0),
3675 MachineNode->getOperand(1)),
3679 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3681 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3685 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3686 MVT::i1, MachineNode->getOperand(1),
3687 MachineNode->getOperand(1));
3688 else if (Op1Unset || Op2Set)
3689 // andc(0, y) = andc(x, 1) = 0
3690 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3694 ResNode = MachineNode->getOperand(0).getNode();
3696 // andc(~x, y) = ~(x | y) = nor(x, y)
3697 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3698 MVT::i1, MachineNode->getOperand(0).
3700 MachineNode->getOperand(1));
3702 // andc(x, ~y) = x & y
3703 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3704 MVT::i1, MachineNode->getOperand(0),
3705 MachineNode->getOperand(1).
3707 else if (AllUsersSelectZero(MachineNode))
3708 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3709 MVT::i1, MachineNode->getOperand(1),
3710 MachineNode->getOperand(0)),
3714 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3716 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3718 else if (Op1Set || Op2Unset)
3719 // orc(1, y) = orc(x, 0) = 1
3720 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3724 ResNode = MachineNode->getOperand(0).getNode();
3727 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3728 MVT::i1, MachineNode->getOperand(1),
3729 MachineNode->getOperand(1));
3731 // orc(~x, y) = ~(x & y) = nand(x, y)
3732 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3733 MVT::i1, MachineNode->getOperand(0).
3735 MachineNode->getOperand(1));
3737 // orc(x, ~y) = x | y
3738 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3739 MVT::i1, MachineNode->getOperand(0),
3740 MachineNode->getOperand(1).
3742 else if (AllUsersSelectZero(MachineNode))
3743 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3744 MVT::i1, MachineNode->getOperand(1),
3745 MachineNode->getOperand(0)),
3748 case PPC::SELECT_I4:
3749 case PPC::SELECT_I8:
3750 case PPC::SELECT_F4:
3751 case PPC::SELECT_F8:
3752 case PPC::SELECT_QFRC:
3753 case PPC::SELECT_QSRC:
3754 case PPC::SELECT_QBRC:
3755 case PPC::SELECT_VRRC:
3756 case PPC::SELECT_VSFRC:
3757 case PPC::SELECT_VSSRC:
3758 case PPC::SELECT_VSRC:
3760 ResNode = MachineNode->getOperand(1).getNode();
3762 ResNode = MachineNode->getOperand(2).getNode();
3764 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3766 MachineNode->getValueType(0),
3767 MachineNode->getOperand(0).
3769 MachineNode->getOperand(2),
3770 MachineNode->getOperand(1));
3775 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3779 MachineNode->getOperand(0).
3781 MachineNode->getOperand(1),
3782 MachineNode->getOperand(2));
3783 // FIXME: Handle Op1Set, Op1Unset here too.
3787 // If we're inverting this node because it is used only by selects that
3788 // we'd like to swap, then swap the selects before the node replacement.
3790 SwapAllSelectUsers(MachineNode);
3792 if (ResNode != MachineNode) {
3793 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3794 DEBUG(MachineNode->dump(CurDAG));
3795 DEBUG(dbgs() << "\nNew: ");
3796 DEBUG(ResNode->dump(CurDAG));
3797 DEBUG(dbgs() << "\n");
3799 ReplaceUses(MachineNode, ResNode);
3804 CurDAG->RemoveDeadNodes();
3805 } while (IsModified);
3808 // Gather the set of 32-bit operations that are known to have their
3809 // higher-order 32 bits zero, where ToPromote contains all such operations.
3810 static bool PeepholePPC64ZExtGather(SDValue Op32,
3811 SmallPtrSetImpl<SDNode *> &ToPromote) {
3812 if (!Op32.isMachineOpcode())
3815 // First, check for the "frontier" instructions (those that will clear the
3816 // higher-order 32 bits.
3818 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3819 // around. If it does not, then these instructions will clear the
3820 // higher-order bits.
3821 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3822 Op32.getMachineOpcode() == PPC::RLWNM) &&
3823 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3824 ToPromote.insert(Op32.getNode());
3828 // SLW and SRW always clear the higher-order bits.
3829 if (Op32.getMachineOpcode() == PPC::SLW ||
3830 Op32.getMachineOpcode() == PPC::SRW) {
3831 ToPromote.insert(Op32.getNode());
3835 // For LI and LIS, we need the immediate to be positive (so that it is not
3837 if (Op32.getMachineOpcode() == PPC::LI ||
3838 Op32.getMachineOpcode() == PPC::LIS) {
3839 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3842 ToPromote.insert(Op32.getNode());
3846 // LHBRX and LWBRX always clear the higher-order bits.
3847 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3848 Op32.getMachineOpcode() == PPC::LWBRX) {
3849 ToPromote.insert(Op32.getNode());
3853 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3854 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3855 ToPromote.insert(Op32.getNode());
3859 // Next, check for those instructions we can look through.
3861 // Assuming the mask does not wrap around, then the higher-order bits are
3862 // taken directly from the first operand.
3863 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3864 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3865 SmallPtrSet<SDNode *, 16> ToPromote1;
3866 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3869 ToPromote.insert(Op32.getNode());
3870 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3874 // For OR, the higher-order bits are zero if that is true for both operands.
3875 // For SELECT_I4, the same is true (but the relevant operand numbers are
3877 if (Op32.getMachineOpcode() == PPC::OR ||
3878 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3879 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3880 SmallPtrSet<SDNode *, 16> ToPromote1;
3881 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3883 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3886 ToPromote.insert(Op32.getNode());
3887 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3891 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3892 // zero, and also for the constant to be positive (so that it is not sign
3894 if (Op32.getMachineOpcode() == PPC::ORI ||
3895 Op32.getMachineOpcode() == PPC::ORIS) {
3896 SmallPtrSet<SDNode *, 16> ToPromote1;
3897 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3899 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3902 ToPromote.insert(Op32.getNode());
3903 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3907 // The higher-order bits of AND are zero if that is true for at least one of
3909 if (Op32.getMachineOpcode() == PPC::AND) {
3910 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3912 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3914 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3915 if (!Op0OK && !Op1OK)
3918 ToPromote.insert(Op32.getNode());
3921 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3924 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3929 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3930 // of the first operand, or if the second operand is positive (so that it is
3931 // not sign extended).
3932 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3933 Op32.getMachineOpcode() == PPC::ANDISo) {
3934 SmallPtrSet<SDNode *, 16> ToPromote1;
3936 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3937 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3938 if (!Op0OK && !Op1OK)
3941 ToPromote.insert(Op32.getNode());
3944 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3952 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3953 if (!PPCSubTarget->isPPC64())
3956 // When we zero-extend from i32 to i64, we use a pattern like this:
3957 // def : Pat<(i64 (zext i32:$in)),
3958 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3960 // There are several 32-bit shift/rotate instructions, however, that will
3961 // clear the higher-order bits of their output, rendering the RLDICL
3962 // unnecessary. When that happens, we remove it here, and redefine the
3963 // relevant 32-bit operation to be a 64-bit operation.
3965 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3968 bool MadeChange = false;
3969 while (Position != CurDAG->allnodes_begin()) {
3970 SDNode *N = --Position;
3971 // Skip dead nodes and any non-machine opcodes.
3972 if (N->use_empty() || !N->isMachineOpcode())
3975 if (N->getMachineOpcode() != PPC::RLDICL)
3978 if (N->getConstantOperandVal(1) != 0 ||
3979 N->getConstantOperandVal(2) != 32)
3982 SDValue ISR = N->getOperand(0);
3983 if (!ISR.isMachineOpcode() ||
3984 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3987 if (!ISR.hasOneUse())
3990 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3993 SDValue IDef = ISR.getOperand(0);
3994 if (!IDef.isMachineOpcode() ||
3995 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3998 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3999 // can get rid of it.
4001 SDValue Op32 = ISR->getOperand(1);
4002 if (!Op32.isMachineOpcode())
4005 // There are some 32-bit instructions that always clear the high-order 32
4006 // bits, there are also some instructions (like AND) that we can look
4008 SmallPtrSet<SDNode *, 16> ToPromote;
4009 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4012 // If the ToPromote set contains nodes that have uses outside of the set
4013 // (except for the original INSERT_SUBREG), then abort the transformation.
4014 bool OutsideUse = false;
4015 for (SDNode *PN : ToPromote) {
4016 for (SDNode *UN : PN->uses()) {
4017 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4031 // We now know that this zero extension can be removed by promoting to
4032 // nodes in ToPromote to 64-bit operations, where for operations in the
4033 // frontier of the set, we need to insert INSERT_SUBREGs for their
4035 for (SDNode *PN : ToPromote) {
4037 switch (PN->getMachineOpcode()) {
4039 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4040 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4041 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4042 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4043 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4044 case PPC::LI: NewOpcode = PPC::LI8; break;
4045 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4046 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4047 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4048 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4049 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4050 case PPC::OR: NewOpcode = PPC::OR8; break;
4051 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4052 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4053 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4054 case PPC::AND: NewOpcode = PPC::AND8; break;
4055 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4056 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4059 // Note: During the replacement process, the nodes will be in an
4060 // inconsistent state (some instructions will have operands with values
4061 // of the wrong type). Once done, however, everything should be right
4064 SmallVector<SDValue, 4> Ops;
4065 for (const SDValue &V : PN->ops()) {
4066 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4067 !isa<ConstantSDNode>(V)) {
4068 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4070 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4071 ISR.getNode()->getVTList(), ReplOpOps);
4072 Ops.push_back(SDValue(ReplOp, 0));
4078 // Because all to-be-promoted nodes only have users that are other
4079 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4080 // the i32 result value type with i64.
4082 SmallVector<EVT, 2> NewVTs;
4083 SDVTList VTs = PN->getVTList();
4084 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4085 if (VTs.VTs[i] == MVT::i32)
4086 NewVTs.push_back(MVT::i64);
4088 NewVTs.push_back(VTs.VTs[i]);
4090 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4091 DEBUG(PN->dump(CurDAG));
4093 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4095 DEBUG(dbgs() << "\nNew: ");
4096 DEBUG(PN->dump(CurDAG));
4097 DEBUG(dbgs() << "\n");
4100 // Now we replace the original zero extend and its associated INSERT_SUBREG
4101 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4104 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4105 DEBUG(N->dump(CurDAG));
4106 DEBUG(dbgs() << "\nNew: ");
4107 DEBUG(Op32.getNode()->dump(CurDAG));
4108 DEBUG(dbgs() << "\n");
4110 ReplaceUses(N, Op32.getNode());
4114 CurDAG->RemoveDeadNodes();
4117 void PPCDAGToDAGISel::PeepholePPC64() {
4118 // These optimizations are currently supported only for 64-bit SVR4.
4119 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4122 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4125 while (Position != CurDAG->allnodes_begin()) {
4126 SDNode *N = --Position;
4127 // Skip dead nodes and any non-machine opcodes.
4128 if (N->use_empty() || !N->isMachineOpcode())
4132 unsigned StorageOpcode = N->getMachineOpcode();
4134 switch (StorageOpcode) {
4165 // If this is a load or store with a zero offset, we may be able to
4166 // fold an add-immediate into the memory operation.
4167 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4168 N->getConstantOperandVal(FirstOp) != 0)
4171 SDValue Base = N->getOperand(FirstOp + 1);
4172 if (!Base.isMachineOpcode())
4176 bool ReplaceFlags = true;
4178 // When the feeding operation is an add-immediate of some sort,
4179 // determine whether we need to add relocation information to the
4180 // target flags on the immediate operand when we fold it into the
4181 // load instruction.
4183 // For something like ADDItocL, the relocation information is
4184 // inferred from the opcode; when we process it in the AsmPrinter,
4185 // we add the necessary relocation there. A load, though, can receive
4186 // relocation from various flavors of ADDIxxx, so we need to carry
4187 // the relocation information in the target flags.
4188 switch (Base.getMachineOpcode()) {
4193 // In some cases (such as TLS) the relocation information
4194 // is already in place on the operand, so copying the operand
4196 ReplaceFlags = false;
4197 // For these cases, the immediate may not be divisible by 4, in
4198 // which case the fold is illegal for DS-form instructions. (The
4199 // other cases provide aligned addresses and are always safe.)
4200 if ((StorageOpcode == PPC::LWA ||
4201 StorageOpcode == PPC::LD ||
4202 StorageOpcode == PPC::STD) &&
4203 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4204 Base.getConstantOperandVal(1) % 4 != 0))
4207 case PPC::ADDIdtprelL:
4208 Flags = PPCII::MO_DTPREL_LO;
4210 case PPC::ADDItlsldL:
4211 Flags = PPCII::MO_TLSLD_LO;
4214 Flags = PPCII::MO_TOC_LO;
4218 // We found an opportunity. Reverse the operands from the add
4219 // immediate and substitute them into the load or store. If
4220 // needed, update the target flags for the immediate operand to
4221 // reflect the necessary relocation information.
4222 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4223 DEBUG(Base->dump(CurDAG));
4224 DEBUG(dbgs() << "\nN: ");
4225 DEBUG(N->dump(CurDAG));
4226 DEBUG(dbgs() << "\n");
4228 SDValue ImmOpnd = Base.getOperand(1);
4230 // If the relocation information isn't already present on the
4231 // immediate operand, add it now.
4233 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4235 const GlobalValue *GV = GA->getGlobal();
4236 // We can't perform this optimization for data whose alignment
4237 // is insufficient for the instruction encoding.
4238 if (GV->getAlignment() < 4 &&
4239 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4240 StorageOpcode == PPC::LWA)) {
4241 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4244 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4245 } else if (ConstantPoolSDNode *CP =
4246 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4247 const Constant *C = CP->getConstVal();
4248 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4254 if (FirstOp == 1) // Store
4255 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4256 Base.getOperand(0), N->getOperand(3));
4258 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4261 // The add-immediate may now be dead, in which case remove it.
4262 if (Base.getNode()->use_empty())
4263 CurDAG->RemoveDeadNode(Base.getNode());
4268 /// createPPCISelDag - This pass converts a legalized DAG into a
4269 /// PowerPC-specific DAG, ready for instruction scheduling.
4271 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4272 return new PPCDAGToDAGISel(TM);
4275 static void initializePassOnce(PassRegistry &Registry) {
4276 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4277 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4278 nullptr, false, false);
4279 Registry.registerPass(*PI, true);
4282 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4283 CALL_ONCE_INITIALIZATION(initializePassOnce);