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) {
94 return CurDAG->getTargetConstant(Imm, MVT::i32);
97 /// getI64Imm - Return a target constant with the specified value, of type
99 inline SDValue getI64Imm(uint64_t Imm) {
100 return CurDAG->getTargetConstant(Imm, MVT::i64);
103 /// getSmallIPtrImm - Return a target constant of pointer type.
104 inline SDValue getSmallIPtrImm(unsigned Imm) {
105 return CurDAG->getTargetConstant(Imm, 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);
200 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
202 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
203 SDLoc(Op), Op.getValueType(),
206 OutOps.push_back(NewOp);
212 void InsertVRSaveCode(MachineFunction &MF);
214 const char *getPassName() const override {
215 return "PowerPC DAG->DAG Pattern Instruction Selection";
218 // Include the pieces autogenerated from the target description.
219 #include "PPCGenDAGISel.inc"
222 SDNode *SelectSETCC(SDNode *N);
224 void PeepholePPC64();
225 void PeepholePPC64ZExt();
226 void PeepholeCROps();
228 SDValue combineToCMPB(SDNode *N);
229 void foldBoolExts(SDValue &Res, SDNode *&N);
231 bool AllUsersSelectZero(SDNode *N);
232 void SwapAllSelectUsers(SDNode *N);
234 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
238 /// InsertVRSaveCode - Once the entire function has been instruction selected,
239 /// all virtual registers are created and all machine instructions are built,
240 /// check to see if we need to save/restore VRSAVE. If so, do it.
241 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
242 // Check to see if this function uses vector registers, which means we have to
243 // save and restore the VRSAVE register and update it with the regs we use.
245 // In this case, there will be virtual registers of vector type created
246 // by the scheduler. Detect them now.
247 bool HasVectorVReg = false;
248 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
249 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
250 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
251 HasVectorVReg = true;
255 if (!HasVectorVReg) return; // nothing to do.
257 // If we have a vector register, we want to emit code into the entry and exit
258 // blocks to save and restore the VRSAVE register. We do this here (instead
259 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
261 // 1. This (trivially) reduces the load on the register allocator, by not
262 // having to represent the live range of the VRSAVE register.
263 // 2. This (more significantly) allows us to create a temporary virtual
264 // register to hold the saved VRSAVE value, allowing this temporary to be
265 // register allocated, instead of forcing it to be spilled to the stack.
267 // Create two vregs - one to hold the VRSAVE register that is live-in to the
268 // function and one for the value after having bits or'd into it.
269 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
270 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
272 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
273 MachineBasicBlock &EntryBB = *Fn.begin();
275 // Emit the following code into the entry block:
276 // InVRSAVE = MFVRSAVE
277 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
278 // MTVRSAVE UpdatedVRSAVE
279 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
280 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
281 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
282 UpdatedVRSAVE).addReg(InVRSAVE);
283 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
285 // Find all return blocks, outputting a restore in each epilog.
286 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
287 if (!BB->empty() && BB->back().isReturn()) {
288 IP = BB->end(); --IP;
290 // Skip over all terminator instructions, which are part of the return
292 MachineBasicBlock::iterator I2 = IP;
293 while (I2 != BB->begin() && (--I2)->isTerminator())
296 // Emit: MTVRSAVE InVRSave
297 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
303 /// getGlobalBaseReg - Output the instructions required to put the
304 /// base address to use for accessing globals into a register.
306 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
307 if (!GlobalBaseReg) {
308 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
309 // Insert the set of GlobalBaseReg into the first MBB of the function
310 MachineBasicBlock &FirstMBB = MF->front();
311 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
312 const Module *M = MF->getFunction()->getParent();
315 if (PPCLowering->getPointerTy() == MVT::i32) {
316 if (PPCSubTarget->isTargetELF()) {
317 GlobalBaseReg = PPC::R30;
318 if (M->getPICLevel() == PICLevel::Small) {
319 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
320 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
321 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
323 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
324 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
325 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
326 BuildMI(FirstMBB, MBBI, dl,
327 TII.get(PPC::UpdateGBR), GlobalBaseReg)
328 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
329 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
333 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
334 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
335 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
338 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
339 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
340 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
343 return CurDAG->getRegister(GlobalBaseReg,
344 PPCLowering->getPointerTy()).getNode();
347 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
348 /// or 64-bit immediate, and if the value can be accurately represented as a
349 /// sign extension from a 16-bit value. If so, this returns true and the
351 static bool isIntS16Immediate(SDNode *N, short &Imm) {
352 if (N->getOpcode() != ISD::Constant)
355 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
356 if (N->getValueType(0) == MVT::i32)
357 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
359 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
362 static bool isIntS16Immediate(SDValue Op, short &Imm) {
363 return isIntS16Immediate(Op.getNode(), Imm);
367 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
368 /// operand. If so Imm will receive the 32-bit value.
369 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
370 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
371 Imm = cast<ConstantSDNode>(N)->getZExtValue();
377 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
378 /// operand. If so Imm will receive the 64-bit value.
379 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
380 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
381 Imm = cast<ConstantSDNode>(N)->getZExtValue();
387 // isInt32Immediate - This method tests to see if a constant operand.
388 // If so Imm will receive the 32 bit value.
389 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
390 return isInt32Immediate(N.getNode(), Imm);
394 // isOpcWithIntImmediate - This method tests to see if the node is a specific
395 // opcode and that it has a immediate integer right operand.
396 // If so Imm will receive the 32 bit value.
397 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
398 return N->getOpcode() == Opc
399 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
402 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
404 int FI = cast<FrameIndexSDNode>(N)->getIndex();
405 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
406 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
408 return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
409 getSmallIPtrImm(Offset));
410 return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
411 getSmallIPtrImm(Offset));
414 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
415 bool isShiftMask, unsigned &SH,
416 unsigned &MB, unsigned &ME) {
417 // Don't even go down this path for i64, since different logic will be
418 // necessary for rldicl/rldicr/rldimi.
419 if (N->getValueType(0) != MVT::i32)
423 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
424 unsigned Opcode = N->getOpcode();
425 if (N->getNumOperands() != 2 ||
426 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
429 if (Opcode == ISD::SHL) {
430 // apply shift left to mask if it comes first
431 if (isShiftMask) Mask = Mask << Shift;
432 // determine which bits are made indeterminant by shift
433 Indeterminant = ~(0xFFFFFFFFu << Shift);
434 } else if (Opcode == ISD::SRL) {
435 // apply shift right to mask if it comes first
436 if (isShiftMask) Mask = Mask >> Shift;
437 // determine which bits are made indeterminant by shift
438 Indeterminant = ~(0xFFFFFFFFu >> Shift);
439 // adjust for the left rotate
441 } else if (Opcode == ISD::ROTL) {
447 // if the mask doesn't intersect any Indeterminant bits
448 if (Mask && !(Mask & Indeterminant)) {
450 // make sure the mask is still a mask (wrap arounds may not be)
451 return isRunOfOnes(Mask, MB, ME);
456 /// SelectBitfieldInsert - turn an or of two masked values into
457 /// the rotate left word immediate then mask insert (rlwimi) instruction.
458 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
459 SDValue Op0 = N->getOperand(0);
460 SDValue Op1 = N->getOperand(1);
463 APInt LKZ, LKO, RKZ, RKO;
464 CurDAG->computeKnownBits(Op0, LKZ, LKO);
465 CurDAG->computeKnownBits(Op1, RKZ, RKO);
467 unsigned TargetMask = LKZ.getZExtValue();
468 unsigned InsertMask = RKZ.getZExtValue();
470 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
471 unsigned Op0Opc = Op0.getOpcode();
472 unsigned Op1Opc = Op1.getOpcode();
473 unsigned Value, SH = 0;
474 TargetMask = ~TargetMask;
475 InsertMask = ~InsertMask;
477 // If the LHS has a foldable shift and the RHS does not, then swap it to the
478 // RHS so that we can fold the shift into the insert.
479 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
480 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
481 Op0.getOperand(0).getOpcode() == ISD::SRL) {
482 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
483 Op1.getOperand(0).getOpcode() != ISD::SRL) {
485 std::swap(Op0Opc, Op1Opc);
486 std::swap(TargetMask, InsertMask);
489 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
490 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
491 Op1.getOperand(0).getOpcode() != ISD::SRL) {
493 std::swap(Op0Opc, Op1Opc);
494 std::swap(TargetMask, InsertMask);
499 if (isRunOfOnes(InsertMask, MB, ME)) {
502 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
503 isInt32Immediate(Op1.getOperand(1), Value)) {
504 Op1 = Op1.getOperand(0);
505 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
507 if (Op1Opc == ISD::AND) {
508 // The AND mask might not be a constant, and we need to make sure that
509 // if we're going to fold the masking with the insert, all bits not
510 // know to be zero in the mask are known to be one.
512 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
513 bool CanFoldMask = InsertMask == MKO.getZExtValue();
515 unsigned SHOpc = Op1.getOperand(0).getOpcode();
516 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
517 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
518 // Note that Value must be in range here (less than 32) because
519 // otherwise there would not be any bits set in InsertMask.
520 Op1 = Op1.getOperand(0).getOperand(0);
521 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
526 SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
528 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
534 // Predict the number of instructions that would be generated by calling
536 static unsigned SelectInt64CountDirect(int64_t Imm) {
537 // Assume no remaining bits.
538 unsigned Remainder = 0;
539 // Assume no shift required.
542 // If it can't be represented as a 32 bit value.
543 if (!isInt<32>(Imm)) {
544 Shift = countTrailingZeros<uint64_t>(Imm);
545 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
547 // If the shifted value fits 32 bits.
548 if (isInt<32>(ImmSh)) {
549 // Go with the shifted value.
552 // Still stuck with a 64 bit value.
559 // Intermediate operand.
562 // Handle first 32 bits.
563 unsigned Lo = Imm & 0xFFFF;
564 unsigned Hi = (Imm >> 16) & 0xFFFF;
567 if (isInt<16>(Imm)) {
571 // Handle the Hi bits and Lo bits.
578 // If no shift, we're done.
579 if (!Shift) return Result;
581 // Shift for next step if the upper 32-bits were not zero.
585 // Add in the last bits as required.
586 if ((Hi = (Remainder >> 16) & 0xFFFF))
588 if ((Lo = Remainder & 0xFFFF))
594 static uint64_t Rot64(uint64_t Imm, unsigned R) {
595 return (Imm << R) | (Imm >> (64 - R));
598 static unsigned SelectInt64Count(int64_t Imm) {
599 unsigned Count = SelectInt64CountDirect(Imm);
603 for (unsigned r = 1; r < 63; ++r) {
604 uint64_t RImm = Rot64(Imm, r);
605 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
606 Count = std::min(Count, RCount);
608 // See comments in SelectInt64 for an explanation of the logic below.
609 unsigned LS = findLastSet(RImm);
613 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
614 uint64_t RImmWithOnes = RImm | OnesMask;
616 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
617 Count = std::min(Count, RCount);
623 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
624 // (above) needs to be kept in sync with this function.
625 static SDNode *SelectInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
626 // Assume no remaining bits.
627 unsigned Remainder = 0;
628 // Assume no shift required.
631 // If it can't be represented as a 32 bit value.
632 if (!isInt<32>(Imm)) {
633 Shift = countTrailingZeros<uint64_t>(Imm);
634 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
636 // If the shifted value fits 32 bits.
637 if (isInt<32>(ImmSh)) {
638 // Go with the shifted value.
641 // Still stuck with a 64 bit value.
648 // Intermediate operand.
651 // Handle first 32 bits.
652 unsigned Lo = Imm & 0xFFFF;
653 unsigned Hi = (Imm >> 16) & 0xFFFF;
655 auto getI32Imm = [CurDAG](unsigned Imm) {
656 return CurDAG->getTargetConstant(Imm, MVT::i32);
660 if (isInt<16>(Imm)) {
662 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
664 // Handle the Hi bits.
665 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
666 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
668 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
669 SDValue(Result, 0), getI32Imm(Lo));
672 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
675 // If no shift, we're done.
676 if (!Shift) return Result;
678 // Shift for next step if the upper 32-bits were not zero.
680 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
683 getI32Imm(63 - Shift));
686 // Add in the last bits as required.
687 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
688 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
689 SDValue(Result, 0), getI32Imm(Hi));
691 if ((Lo = Remainder & 0xFFFF)) {
692 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
693 SDValue(Result, 0), getI32Imm(Lo));
699 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
700 unsigned Count = SelectInt64CountDirect(Imm);
702 return SelectInt64Direct(CurDAG, dl, Imm);
709 for (unsigned r = 1; r < 63; ++r) {
710 uint64_t RImm = Rot64(Imm, r);
711 unsigned RCount = SelectInt64CountDirect(RImm) + 1;
712 if (RCount < Count) {
719 // If the immediate to generate has many trailing zeros, it might be
720 // worthwhile to generate a rotated value with too many leading ones
721 // (because that's free with li/lis's sign-extension semantics), and then
722 // mask them off after rotation.
724 unsigned LS = findLastSet(RImm);
725 // We're adding (63-LS) higher-order ones, and we expect to mask them off
726 // after performing the inverse rotation by (64-r). So we need that:
727 // 63-LS == 64-r => LS == r-1
731 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
732 uint64_t RImmWithOnes = RImm | OnesMask;
734 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
735 if (RCount < Count) {
738 MatImm = RImmWithOnes;
744 return SelectInt64Direct(CurDAG, dl, Imm);
746 auto getI32Imm = [CurDAG](unsigned Imm) {
747 return CurDAG->getTargetConstant(Imm, MVT::i32);
750 SDValue Val = SDValue(SelectInt64Direct(CurDAG, dl, MatImm), 0);
751 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
752 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
755 // Select a 64-bit constant.
756 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
760 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
761 return SelectInt64(CurDAG, dl, Imm);
765 class BitPermutationSelector {
769 // The bit number in the value, using a convention where bit 0 is the
778 ValueBit(SDValue V, unsigned I, Kind K = Variable)
779 : V(V), Idx(I), K(K) {}
780 ValueBit(Kind K = Variable)
781 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
783 bool isZero() const {
784 return K == ConstZero;
787 bool hasValue() const {
788 return K == Variable;
791 SDValue getValue() const {
792 assert(hasValue() && "Cannot get the value of a constant bit");
796 unsigned getValueBitIndex() const {
797 assert(hasValue() && "Cannot get the value bit index of a constant bit");
802 // A bit group has the same underlying value and the same rotate factor.
806 unsigned StartIdx, EndIdx;
808 // This rotation amount assumes that the lower 32 bits of the quantity are
809 // replicated in the high 32 bits by the rotation operator (which is done
810 // by rlwinm and friends in 64-bit mode).
812 // Did converting to Repl32 == true change the rotation factor? If it did,
813 // it decreased it by 32.
815 // Was this group coalesced after setting Repl32 to true?
816 bool Repl32Coalesced;
818 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
819 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
820 Repl32Coalesced(false) {
821 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
822 " [" << S << ", " << E << "]\n");
826 // Information on each (Value, RLAmt) pair (like the number of groups
827 // associated with each) used to choose the lowering method.
828 struct ValueRotInfo {
832 unsigned FirstGroupStartIdx;
836 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
839 // For sorting (in reverse order) by NumGroups, and then by
840 // FirstGroupStartIdx.
841 bool operator < (const ValueRotInfo &Other) const {
842 // We need to sort so that the non-Repl32 come first because, when we're
843 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
844 // masking operation.
845 if (Repl32 < Other.Repl32)
847 else if (Repl32 > Other.Repl32)
849 else if (NumGroups > Other.NumGroups)
851 else if (NumGroups < Other.NumGroups)
853 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
859 // Return true if something interesting was deduced, return false if we're
860 // providing only a generic representation of V (or something else likewise
861 // uninteresting for instruction selection).
862 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
863 switch (V.getOpcode()) {
866 if (isa<ConstantSDNode>(V.getOperand(1))) {
867 unsigned RotAmt = V.getConstantOperandVal(1);
869 SmallVector<ValueBit, 64> LHSBits(Bits.size());
870 getValueBits(V.getOperand(0), LHSBits);
872 for (unsigned i = 0; i < Bits.size(); ++i)
873 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
879 if (isa<ConstantSDNode>(V.getOperand(1))) {
880 unsigned ShiftAmt = V.getConstantOperandVal(1);
882 SmallVector<ValueBit, 64> LHSBits(Bits.size());
883 getValueBits(V.getOperand(0), LHSBits);
885 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
886 Bits[i] = LHSBits[i - ShiftAmt];
888 for (unsigned i = 0; i < ShiftAmt; ++i)
889 Bits[i] = ValueBit(ValueBit::ConstZero);
895 if (isa<ConstantSDNode>(V.getOperand(1))) {
896 unsigned ShiftAmt = V.getConstantOperandVal(1);
898 SmallVector<ValueBit, 64> LHSBits(Bits.size());
899 getValueBits(V.getOperand(0), LHSBits);
901 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
902 Bits[i] = LHSBits[i + ShiftAmt];
904 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
905 Bits[i] = ValueBit(ValueBit::ConstZero);
911 if (isa<ConstantSDNode>(V.getOperand(1))) {
912 uint64_t Mask = V.getConstantOperandVal(1);
914 SmallVector<ValueBit, 64> LHSBits(Bits.size());
915 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
917 for (unsigned i = 0; i < Bits.size(); ++i)
918 if (((Mask >> i) & 1) == 1)
919 Bits[i] = LHSBits[i];
921 Bits[i] = ValueBit(ValueBit::ConstZero);
923 // Mark this as interesting, only if the LHS was also interesting. This
924 // prevents the overall procedure from matching a single immediate 'and'
925 // (which is non-optimal because such an and might be folded with other
926 // things if we don't select it here).
931 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
932 getValueBits(V.getOperand(0), LHSBits);
933 getValueBits(V.getOperand(1), RHSBits);
935 bool AllDisjoint = true;
936 for (unsigned i = 0; i < Bits.size(); ++i)
937 if (LHSBits[i].isZero())
938 Bits[i] = RHSBits[i];
939 else if (RHSBits[i].isZero())
940 Bits[i] = LHSBits[i];
953 for (unsigned i = 0; i < Bits.size(); ++i)
954 Bits[i] = ValueBit(V, i);
959 // For each value (except the constant ones), compute the left-rotate amount
960 // to get it from its original to final position.
961 void computeRotationAmounts() {
963 RLAmt.resize(Bits.size());
964 for (unsigned i = 0; i < Bits.size(); ++i)
965 if (Bits[i].hasValue()) {
966 unsigned VBI = Bits[i].getValueBitIndex();
970 RLAmt[i] = Bits.size() - (VBI - i);
971 } else if (Bits[i].isZero()) {
973 RLAmt[i] = UINT32_MAX;
975 llvm_unreachable("Unknown value bit type");
979 // Collect groups of consecutive bits with the same underlying value and
980 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
981 // they break up groups.
982 void collectBitGroups(bool LateMask) {
985 unsigned LastRLAmt = RLAmt[0];
986 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
987 unsigned LastGroupStartIdx = 0;
988 for (unsigned i = 1; i < Bits.size(); ++i) {
989 unsigned ThisRLAmt = RLAmt[i];
990 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
991 if (LateMask && !ThisValue) {
992 ThisValue = LastValue;
993 ThisRLAmt = LastRLAmt;
994 // If we're doing late masking, then the first bit group always starts
995 // at zero (even if the first bits were zero).
996 if (BitGroups.empty())
997 LastGroupStartIdx = 0;
1000 // If this bit has the same underlying value and the same rotate factor as
1001 // the last one, then they're part of the same group.
1002 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1005 if (LastValue.getNode())
1006 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1008 LastRLAmt = ThisRLAmt;
1009 LastValue = ThisValue;
1010 LastGroupStartIdx = i;
1012 if (LastValue.getNode())
1013 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1016 if (BitGroups.empty())
1019 // We might be able to combine the first and last groups.
1020 if (BitGroups.size() > 1) {
1021 // If the first and last groups are the same, then remove the first group
1022 // in favor of the last group, making the ending index of the last group
1023 // equal to the ending index of the to-be-removed first group.
1024 if (BitGroups[0].StartIdx == 0 &&
1025 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1026 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1027 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1028 DEBUG(dbgs() << "\tcombining final bit group with inital one\n");
1029 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1030 BitGroups.erase(BitGroups.begin());
1035 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1036 // associated with each. If there is a degeneracy, pick the one that occurs
1037 // first (in the final value).
1038 void collectValueRotInfo() {
1041 for (auto &BG : BitGroups) {
1042 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1043 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1045 VRI.RLAmt = BG.RLAmt;
1046 VRI.Repl32 = BG.Repl32;
1048 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1051 // Now that we've collected the various ValueRotInfo instances, we need to
1053 ValueRotsVec.clear();
1054 for (auto &I : ValueRots) {
1055 ValueRotsVec.push_back(I.second);
1057 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1060 // In 64-bit mode, rlwinm and friends have a rotation operator that
1061 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1062 // indices of these instructions can only be in the lower 32 bits, so they
1063 // can only represent some 64-bit bit groups. However, when they can be used,
1064 // the 32-bit replication can be used to represent, as a single bit group,
1065 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1066 // groups when possible. Returns true if any of the bit groups were
1068 void assignRepl32BitGroups() {
1069 // If we have bits like this:
1071 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1072 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1073 // Groups: | RLAmt = 8 | RLAmt = 40 |
1075 // But, making use of a 32-bit operation that replicates the low-order 32
1076 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1079 auto IsAllLow32 = [this](BitGroup & BG) {
1080 if (BG.StartIdx <= BG.EndIdx) {
1081 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1082 if (!Bits[i].hasValue())
1084 if (Bits[i].getValueBitIndex() >= 32)
1088 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1089 if (!Bits[i].hasValue())
1091 if (Bits[i].getValueBitIndex() >= 32)
1094 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1095 if (!Bits[i].hasValue())
1097 if (Bits[i].getValueBitIndex() >= 32)
1105 for (auto &BG : BitGroups) {
1106 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1107 if (IsAllLow32(BG)) {
1108 if (BG.RLAmt >= 32) {
1115 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1116 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1117 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1122 // Now walk through the bit groups, consolidating where possible.
1123 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1124 // We might want to remove this bit group by merging it with the previous
1125 // group (which might be the ending group).
1126 auto IP = (I == BitGroups.begin()) ?
1127 std::prev(BitGroups.end()) : std::prev(I);
1128 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1129 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1131 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1132 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1133 " [" << I->StartIdx << ", " << I->EndIdx <<
1134 "] with group with range [" <<
1135 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1137 IP->EndIdx = I->EndIdx;
1138 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1139 IP->Repl32Coalesced = true;
1140 I = BitGroups.erase(I);
1143 // There is a special case worth handling: If there is a single group
1144 // covering the entire upper 32 bits, and it can be merged with both
1145 // the next and previous groups (which might be the same group), then
1146 // do so. If it is the same group (so there will be only one group in
1147 // total), then we need to reverse the order of the range so that it
1148 // covers the entire 64 bits.
1149 if (I->StartIdx == 32 && I->EndIdx == 63) {
1150 assert(std::next(I) == BitGroups.end() &&
1151 "bit group ends at index 63 but there is another?");
1152 auto IN = BitGroups.begin();
1154 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1155 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1156 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1159 DEBUG(dbgs() << "\tcombining bit group for " <<
1160 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1161 " [" << I->StartIdx << ", " << I->EndIdx <<
1162 "] with 32-bit replicated groups with ranges [" <<
1163 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1164 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1167 // There is only one other group; change it to cover the whole
1168 // range (backward, so that it can still be Repl32 but cover the
1169 // whole 64-bit range).
1172 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1173 IP->Repl32Coalesced = true;
1174 I = BitGroups.erase(I);
1176 // There are two separate groups, one before this group and one
1177 // after us (at the beginning). We're going to remove this group,
1178 // but also the group at the very beginning.
1179 IP->EndIdx = IN->EndIdx;
1180 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1181 IP->Repl32Coalesced = true;
1182 I = BitGroups.erase(I);
1183 BitGroups.erase(BitGroups.begin());
1186 // This must be the last group in the vector (and we might have
1187 // just invalidated the iterator above), so break here.
1197 SDValue getI32Imm(unsigned Imm) {
1198 return CurDAG->getTargetConstant(Imm, MVT::i32);
1201 uint64_t getZerosMask() {
1203 for (unsigned i = 0; i < Bits.size(); ++i) {
1204 if (Bits[i].hasValue())
1206 Mask |= (UINT64_C(1) << i);
1212 // Depending on the number of groups for a particular value, it might be
1213 // better to rotate, mask explicitly (using andi/andis), and then or the
1214 // result. Select this part of the result first.
1215 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1216 if (BPermRewriterNoMasking)
1219 for (ValueRotInfo &VRI : ValueRotsVec) {
1221 for (unsigned i = 0; i < Bits.size(); ++i) {
1222 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1224 if (RLAmt[i] != VRI.RLAmt)
1229 // Compute the masks for andi/andis that would be necessary.
1230 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1231 assert((ANDIMask != 0 || ANDISMask != 0) &&
1232 "No set bits in mask for value bit groups");
1233 bool NeedsRotate = VRI.RLAmt != 0;
1235 // We're trying to minimize the number of instructions. If we have one
1236 // group, using one of andi/andis can break even. If we have three
1237 // groups, we can use both andi and andis and break even (to use both
1238 // andi and andis we also need to or the results together). We need four
1239 // groups if we also need to rotate. To use andi/andis we need to do more
1240 // than break even because rotate-and-mask instructions tend to be easier
1243 // FIXME: We've biased here against using andi/andis, which is right for
1244 // POWER cores, but not optimal everywhere. For example, on the A2,
1245 // andi/andis have single-cycle latency whereas the rotate-and-mask
1246 // instructions take two cycles, and it would be better to bias toward
1247 // andi/andis in break-even cases.
1249 unsigned NumAndInsts = (unsigned) NeedsRotate +
1250 (unsigned) (ANDIMask != 0) +
1251 (unsigned) (ANDISMask != 0) +
1252 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1253 (unsigned) (bool) Res;
1255 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1256 " RL: " << VRI.RLAmt << ":" <<
1257 "\n\t\t\tisel using masking: " << NumAndInsts <<
1258 " using rotates: " << VRI.NumGroups << "\n");
1260 if (NumAndInsts >= VRI.NumGroups)
1263 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1265 if (InstCnt) *InstCnt += NumAndInsts;
1270 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1271 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1277 SDValue ANDIVal, ANDISVal;
1279 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1280 VRot, getI32Imm(ANDIMask)), 0);
1282 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1283 VRot, getI32Imm(ANDISMask)), 0);
1287 TotalVal = ANDISVal;
1291 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1292 ANDIVal, ANDISVal), 0);
1297 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1300 // Now, remove all groups with this underlying value and rotation
1302 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1303 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1304 I = BitGroups.erase(I);
1311 // Instruction selection for the 32-bit case.
1312 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1316 if (InstCnt) *InstCnt = 0;
1318 // Take care of cases that should use andi/andis first.
1319 SelectAndParts32(dl, Res, InstCnt);
1321 // If we've not yet selected a 'starting' instruction, and we have no zeros
1322 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1323 // number of groups), and start with this rotated value.
1324 if ((!HasZeros || LateMask) && !Res) {
1325 ValueRotInfo &VRI = ValueRotsVec[0];
1327 if (InstCnt) *InstCnt += 1;
1329 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1330 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1335 // Now, remove all groups with this underlying value and rotation factor.
1336 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1337 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1338 I = BitGroups.erase(I);
1344 if (InstCnt) *InstCnt += BitGroups.size();
1346 // Insert the other groups (one at a time).
1347 for (auto &BG : BitGroups) {
1350 { BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1351 getI32Imm(Bits.size() - BG.StartIdx - 1) };
1352 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1355 { Res, BG.V, getI32Imm(BG.RLAmt), getI32Imm(Bits.size() - BG.EndIdx - 1),
1356 getI32Imm(Bits.size() - BG.StartIdx - 1) };
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)), 0);
1377 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1378 Res, getI32Imm(ANDISMask)), 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), getI32Imm(InstMaskStart - 32),
1430 getI32Imm(InstMaskEnd - 32) };
1431 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1435 if (InstMaskEnd == 63) {
1437 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1438 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1441 if (InstMaskStart == 0) {
1443 { V, getI32Imm(RLAmt), getI32Imm(InstMaskEnd) };
1444 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1447 if (InstMaskEnd == 63 - RLAmt) {
1449 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
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), getI32Imm(InstMaskStart - 32),
1491 getI32Imm(InstMaskEnd - 32) };
1492 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1496 if (InstMaskEnd == 63 - RLAmt) {
1498 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
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](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)), 0);
1647 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1648 VRot, getI32Imm(ANDISMask)), 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 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1674 I = BitGroups.erase(I);
1681 // Instruction selection for the 64-bit case.
1682 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1686 if (InstCnt) *InstCnt = 0;
1688 // Take care of cases that should use andi/andis first.
1689 SelectAndParts64(dl, Res, InstCnt);
1691 // If we've not yet selected a 'starting' instruction, and we have no zeros
1692 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1693 // number of groups), and start with this rotated value.
1694 if ((!HasZeros || LateMask) && !Res) {
1695 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1696 // groups will come first, and so the VRI representing the largest number
1697 // of groups might not be first (it might be the first Repl32 groups).
1698 unsigned MaxGroupsIdx = 0;
1699 if (!ValueRotsVec[0].Repl32) {
1700 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1701 if (ValueRotsVec[i].Repl32) {
1702 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1708 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1709 bool NeedsRotate = false;
1712 } else if (VRI.Repl32) {
1713 for (auto &BG : BitGroups) {
1714 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1715 BG.Repl32 != VRI.Repl32)
1718 // We don't need a rotate if the bit group is confined to the lower
1720 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1729 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1730 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1735 // Now, remove all groups with this underlying value and rotation factor.
1737 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1738 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt && I->Repl32 == VRI.Repl32)
1739 I = BitGroups.erase(I);
1745 // Because 64-bit rotates are more flexible than inserts, we might have a
1746 // preference regarding which one we do first (to save one instruction).
1748 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1749 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1751 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1753 if (I != BitGroups.begin()) {
1756 BitGroups.insert(BitGroups.begin(), BG);
1763 // Insert the other groups (one at a time).
1764 for (auto &BG : BitGroups) {
1766 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1767 BG.EndIdx, InstCnt);
1769 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1770 BG.StartIdx, BG.EndIdx, InstCnt);
1774 uint64_t Mask = getZerosMask();
1776 // We can use the 32-bit andi/andis technique if the mask does not
1777 // require any higher-order bits. This can save an instruction compared
1778 // to always using the general 64-bit technique.
1779 bool Use32BitInsts = isUInt<32>(Mask);
1780 // Compute the masks for andi/andis that would be necessary.
1781 unsigned ANDIMask = (Mask & UINT16_MAX),
1782 ANDISMask = (Mask >> 16) & UINT16_MAX;
1784 if (Use32BitInsts) {
1785 assert((ANDIMask != 0 || ANDISMask != 0) &&
1786 "No set bits in mask when using 32-bit ands for 64-bit value");
1788 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1789 (unsigned) (ANDISMask != 0) +
1790 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1792 SDValue ANDIVal, ANDISVal;
1794 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1795 Res, getI32Imm(ANDIMask)), 0);
1797 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1798 Res, getI32Imm(ANDISMask)), 0);
1805 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1806 ANDIVal, ANDISVal), 0);
1808 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1810 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1812 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1817 return Res.getNode();
1820 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1821 // Fill in BitGroups.
1822 collectBitGroups(LateMask);
1823 if (BitGroups.empty())
1826 // For 64-bit values, figure out when we can use 32-bit instructions.
1827 if (Bits.size() == 64)
1828 assignRepl32BitGroups();
1830 // Fill in ValueRotsVec.
1831 collectValueRotInfo();
1833 if (Bits.size() == 32) {
1834 return Select32(N, LateMask, InstCnt);
1836 assert(Bits.size() == 64 && "Not 64 bits here?");
1837 return Select64(N, LateMask, InstCnt);
1843 SmallVector<ValueBit, 64> Bits;
1846 SmallVector<unsigned, 64> RLAmt;
1848 SmallVector<BitGroup, 16> BitGroups;
1850 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1851 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1853 SelectionDAG *CurDAG;
1856 BitPermutationSelector(SelectionDAG *DAG)
1859 // Here we try to match complex bit permutations into a set of
1860 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1861 // known to produce optimial code for common cases (like i32 byte swapping).
1862 SDNode *Select(SDNode *N) {
1863 Bits.resize(N->getValueType(0).getSizeInBits());
1864 if (!getValueBits(SDValue(N, 0), Bits))
1867 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1868 " selection for: ");
1869 DEBUG(N->dump(CurDAG));
1871 // Fill it RLAmt and set HasZeros.
1872 computeRotationAmounts();
1875 return Select(N, false);
1877 // We currently have two techniques for handling results with zeros: early
1878 // masking (the default) and late masking. Late masking is sometimes more
1879 // efficient, but because the structure of the bit groups is different, it
1880 // is hard to tell without generating both and comparing the results. With
1881 // late masking, we ignore zeros in the resulting value when inserting each
1882 // set of bit groups, and then mask in the zeros at the end. With early
1883 // masking, we only insert the non-zero parts of the result at every step.
1885 unsigned InstCnt, InstCntLateMask;
1886 DEBUG(dbgs() << "\tEarly masking:\n");
1887 SDNode *RN = Select(N, false, &InstCnt);
1888 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1890 DEBUG(dbgs() << "\tLate masking:\n");
1891 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1892 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1895 if (InstCnt <= InstCntLateMask) {
1896 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1900 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1904 } // anonymous namespace
1906 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1907 if (N->getValueType(0) != MVT::i32 &&
1908 N->getValueType(0) != MVT::i64)
1911 if (!UseBitPermRewriter)
1914 switch (N->getOpcode()) {
1921 BitPermutationSelector BPS(CurDAG);
1922 return BPS.Select(N);
1929 /// SelectCC - Select a comparison of the specified values with the specified
1930 /// condition code, returning the CR# of the expression.
1931 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1932 ISD::CondCode CC, SDLoc dl) {
1933 // Always select the LHS.
1936 if (LHS.getValueType() == MVT::i32) {
1938 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1939 if (isInt32Immediate(RHS, Imm)) {
1940 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1941 if (isUInt<16>(Imm))
1942 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
1943 getI32Imm(Imm & 0xFFFF)), 0);
1944 // If this is a 16-bit signed immediate, fold it.
1945 if (isInt<16>((int)Imm))
1946 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1947 getI32Imm(Imm & 0xFFFF)), 0);
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)), 0);
1960 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
1961 getI32Imm(Imm & 0xFFFF)), 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)), 0);
1971 if (isIntS16Immediate(RHS, SImm))
1972 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1973 getI32Imm((int)SImm & 0xFFFF)),
1977 } else if (LHS.getValueType() == MVT::i64) {
1979 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1980 if (isInt64Immediate(RHS.getNode(), Imm)) {
1981 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
1982 if (isUInt<16>(Imm))
1983 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
1984 getI32Imm(Imm & 0xFFFF)), 0);
1985 // If this is a 16-bit signed immediate, fold it.
1987 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1988 getI32Imm(Imm & 0xFFFF)), 0);
1990 // For non-equality comparisons, the default code would materialize the
1991 // constant, then compare against it, like this:
1993 // ori r2, r2, 22136
1995 // Since we are just comparing for equality, we can emit this instead:
1996 // xoris r0,r3,0x1234
1997 // cmpldi cr0,r0,0x5678
1999 if (isUInt<32>(Imm)) {
2000 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2001 getI64Imm(Imm >> 16)), 0);
2002 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2003 getI64Imm(Imm & 0xFFFF)), 0);
2007 } else if (ISD::isUnsignedIntSetCC(CC)) {
2008 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2009 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2010 getI64Imm(Imm & 0xFFFF)), 0);
2014 if (isIntS16Immediate(RHS, SImm))
2015 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2016 getI64Imm(SImm & 0xFFFF)),
2020 } else if (LHS.getValueType() == MVT::f32) {
2023 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2024 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2026 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2029 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2035 llvm_unreachable("Should be lowered by legalize!");
2036 default: llvm_unreachable("Unknown condition!");
2038 case ISD::SETEQ: return PPC::PRED_EQ;
2040 case ISD::SETNE: return PPC::PRED_NE;
2042 case ISD::SETLT: return PPC::PRED_LT;
2044 case ISD::SETLE: return PPC::PRED_LE;
2046 case ISD::SETGT: return PPC::PRED_GT;
2048 case ISD::SETGE: return PPC::PRED_GE;
2049 case ISD::SETO: return PPC::PRED_NU;
2050 case ISD::SETUO: return PPC::PRED_UN;
2051 // These two are invalid for floating point. Assume we have int.
2052 case ISD::SETULT: return PPC::PRED_LT;
2053 case ISD::SETUGT: return PPC::PRED_GT;
2057 /// getCRIdxForSetCC - Return the index of the condition register field
2058 /// associated with the SetCC condition, and whether or not the field is
2059 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2060 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2063 default: llvm_unreachable("Unknown condition!");
2065 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2067 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2069 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2070 case ISD::SETUO: return 3; // Bit #3 = SETUO
2072 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2074 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2076 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2077 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2082 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2083 // These are invalid for floating point. Assume integer.
2084 case ISD::SETULT: return 0;
2085 case ISD::SETUGT: return 1;
2089 // getVCmpInst: return the vector compare instruction for the specified
2090 // vector type and condition code. Since this is for altivec specific code,
2091 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2092 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2093 bool HasVSX, bool &Swap, bool &Negate) {
2097 if (VecVT.isFloatingPoint()) {
2098 /* Handle some cases by swapping input operands. */
2100 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2101 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2102 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2103 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2104 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2105 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2108 /* Handle some cases by negating the result. */
2110 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2111 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2112 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2113 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2116 /* We have instructions implementing the remaining cases. */
2120 if (VecVT == MVT::v4f32)
2121 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2122 else if (VecVT == MVT::v2f64)
2123 return PPC::XVCMPEQDP;
2127 if (VecVT == MVT::v4f32)
2128 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2129 else if (VecVT == MVT::v2f64)
2130 return PPC::XVCMPGTDP;
2134 if (VecVT == MVT::v4f32)
2135 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2136 else if (VecVT == MVT::v2f64)
2137 return PPC::XVCMPGEDP;
2142 llvm_unreachable("Invalid floating-point vector compare condition");
2144 /* Handle some cases by swapping input operands. */
2146 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2147 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2148 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2149 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2152 /* Handle some cases by negating the result. */
2154 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2155 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2156 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2157 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2160 /* We have instructions implementing the remaining cases. */
2164 if (VecVT == MVT::v16i8)
2165 return PPC::VCMPEQUB;
2166 else if (VecVT == MVT::v8i16)
2167 return PPC::VCMPEQUH;
2168 else if (VecVT == MVT::v4i32)
2169 return PPC::VCMPEQUW;
2170 else if (VecVT == MVT::v2i64)
2171 return PPC::VCMPEQUD;
2174 if (VecVT == MVT::v16i8)
2175 return PPC::VCMPGTSB;
2176 else if (VecVT == MVT::v8i16)
2177 return PPC::VCMPGTSH;
2178 else if (VecVT == MVT::v4i32)
2179 return PPC::VCMPGTSW;
2180 else if (VecVT == MVT::v2i64)
2181 return PPC::VCMPGTSD;
2184 if (VecVT == MVT::v16i8)
2185 return PPC::VCMPGTUB;
2186 else if (VecVT == MVT::v8i16)
2187 return PPC::VCMPGTUH;
2188 else if (VecVT == MVT::v4i32)
2189 return PPC::VCMPGTUW;
2190 else if (VecVT == MVT::v2i64)
2191 return PPC::VCMPGTUD;
2196 llvm_unreachable("Invalid integer vector compare condition");
2200 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2203 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2204 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2205 bool isPPC64 = (PtrVT == MVT::i64);
2207 if (!PPCSubTarget->useCRBits() &&
2208 isInt32Immediate(N->getOperand(1), Imm)) {
2209 // We can codegen setcc op, imm very efficiently compared to a brcond.
2210 // Check for those cases here.
2213 SDValue Op = N->getOperand(0);
2217 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2218 SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
2219 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2224 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2225 Op, getI32Imm(~0U)), 0);
2226 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
2230 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2231 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2235 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2236 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2237 SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2238 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2241 } else if (Imm == ~0U) { // setcc op, -1
2242 SDValue Op = N->getOperand(0);
2247 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2248 Op, getI32Imm(1)), 0);
2249 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2250 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2256 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2257 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2258 Op, getI32Imm(~0U));
2259 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
2260 Op, SDValue(AD, 1));
2263 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2265 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2267 SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2268 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2271 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2272 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2274 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2281 SDValue LHS = N->getOperand(0);
2282 SDValue RHS = N->getOperand(1);
2284 // Altivec Vector compare instructions do not set any CR register by default and
2285 // vector compare operations return the same type as the operands.
2286 if (LHS.getValueType().isVector()) {
2287 if (PPCSubTarget->hasQPX())
2290 EVT VecVT = LHS.getValueType();
2292 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2293 PPCSubTarget->hasVSX(), Swap, Negate);
2295 std::swap(LHS, RHS);
2298 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2299 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2304 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2307 if (PPCSubTarget->useCRBits())
2311 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2312 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2315 // Force the ccreg into CR7.
2316 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2318 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2319 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2320 InFlag).getValue(1);
2322 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2325 SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2326 getI32Imm(31), getI32Imm(31) };
2328 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2330 // Get the specified bit.
2332 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2333 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2336 SDNode *PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2337 // Transfer memoperands.
2338 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2339 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2340 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2345 // Select - Convert the specified operand from a target-independent to a
2346 // target-specific node if it hasn't already been changed.
2347 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2349 if (N->isMachineOpcode()) {
2351 return nullptr; // Already selected.
2354 // In case any misguided DAG-level optimizations form an ADD with a
2355 // TargetConstant operand, crash here instead of miscompiling (by selecting
2356 // an r+r add instead of some kind of r+i add).
2357 if (N->getOpcode() == ISD::ADD &&
2358 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2359 llvm_unreachable("Invalid ADD with TargetConstant operand");
2361 // Try matching complex bit permutations before doing anything else.
2362 if (SDNode *NN = SelectBitPermutation(N))
2365 switch (N->getOpcode()) {
2368 case ISD::Constant: {
2369 if (N->getValueType(0) == MVT::i64)
2370 return SelectInt64(CurDAG, N);
2375 SDNode *SN = SelectSETCC(N);
2380 case PPCISD::GlobalBaseReg:
2381 return getGlobalBaseReg();
2383 case ISD::FrameIndex:
2384 return getFrameIndex(N, N);
2386 case PPCISD::MFOCRF: {
2387 SDValue InFlag = N->getOperand(1);
2388 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2389 N->getOperand(0), InFlag);
2392 case PPCISD::READ_TIME_BASE: {
2393 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2394 MVT::Other, N->getOperand(0));
2397 case PPCISD::SRA_ADDZE: {
2398 SDValue N0 = N->getOperand(0);
2400 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2401 getConstantIntValue(), N->getValueType(0));
2402 if (N->getValueType(0) == MVT::i64) {
2404 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2406 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2407 SDValue(Op, 0), SDValue(Op, 1));
2409 assert(N->getValueType(0) == MVT::i32 &&
2410 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2412 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2414 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2415 SDValue(Op, 0), SDValue(Op, 1));
2420 // Handle preincrement loads.
2421 LoadSDNode *LD = cast<LoadSDNode>(N);
2422 EVT LoadedVT = LD->getMemoryVT();
2424 // Normal loads are handled by code generated from the .td file.
2425 if (LD->getAddressingMode() != ISD::PRE_INC)
2428 SDValue Offset = LD->getOffset();
2429 if (Offset.getOpcode() == ISD::TargetConstant ||
2430 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2433 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2434 if (LD->getValueType(0) != MVT::i64) {
2435 // Handle PPC32 integer and normal FP loads.
2436 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2437 switch (LoadedVT.getSimpleVT().SimpleTy) {
2438 default: llvm_unreachable("Invalid PPC load type!");
2439 case MVT::f64: Opcode = PPC::LFDU; break;
2440 case MVT::f32: Opcode = PPC::LFSU; break;
2441 case MVT::i32: Opcode = PPC::LWZU; break;
2442 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2444 case MVT::i8: Opcode = PPC::LBZU; break;
2447 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2448 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2449 switch (LoadedVT.getSimpleVT().SimpleTy) {
2450 default: llvm_unreachable("Invalid PPC load type!");
2451 case MVT::i64: Opcode = PPC::LDU; break;
2452 case MVT::i32: Opcode = PPC::LWZU8; break;
2453 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2455 case MVT::i8: Opcode = PPC::LBZU8; break;
2459 SDValue Chain = LD->getChain();
2460 SDValue Base = LD->getBasePtr();
2461 SDValue Ops[] = { Offset, Base, Chain };
2462 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2463 LD->getValueType(0),
2464 PPCLowering->getPointerTy(),
2468 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2469 if (LD->getValueType(0) != MVT::i64) {
2470 // Handle PPC32 integer and normal FP loads.
2471 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2472 switch (LoadedVT.getSimpleVT().SimpleTy) {
2473 default: llvm_unreachable("Invalid PPC load type!");
2474 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2475 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2476 case MVT::f64: Opcode = PPC::LFDUX; break;
2477 case MVT::f32: Opcode = PPC::LFSUX; break;
2478 case MVT::i32: Opcode = PPC::LWZUX; break;
2479 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2481 case MVT::i8: Opcode = PPC::LBZUX; break;
2484 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2485 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2486 "Invalid sext update load");
2487 switch (LoadedVT.getSimpleVT().SimpleTy) {
2488 default: llvm_unreachable("Invalid PPC load type!");
2489 case MVT::i64: Opcode = PPC::LDUX; break;
2490 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2491 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2493 case MVT::i8: Opcode = PPC::LBZUX8; break;
2497 SDValue Chain = LD->getChain();
2498 SDValue Base = LD->getBasePtr();
2499 SDValue Ops[] = { Base, Offset, Chain };
2500 return transferMemOperands(N, CurDAG->getMachineNode(Opcode, dl,
2501 LD->getValueType(0),
2502 PPCLowering->getPointerTy(),
2508 unsigned Imm, Imm2, SH, MB, ME;
2511 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2512 // with a mask, emit rlwinm
2513 if (isInt32Immediate(N->getOperand(1), Imm) &&
2514 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2515 SDValue Val = N->getOperand(0).getOperand(0);
2516 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2517 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2519 // If this is just a masked value where the input is not handled above, and
2520 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2521 if (isInt32Immediate(N->getOperand(1), Imm) &&
2522 isRunOfOnes(Imm, MB, ME) &&
2523 N->getOperand(0).getOpcode() != ISD::ROTL) {
2524 SDValue Val = N->getOperand(0);
2525 SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
2526 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2528 // If this is a 64-bit zero-extension mask, emit rldicl.
2529 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2531 SDValue Val = N->getOperand(0);
2532 MB = 64 - countTrailingOnes(Imm64);
2535 // If the operand is a logical right shift, we can fold it into this
2536 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2537 // for n <= mb. The right shift is really a left rotate followed by a
2538 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2540 if (Val.getOpcode() == ISD::SRL &&
2541 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2542 assert(Imm < 64 && "Illegal shift amount");
2543 Val = Val.getOperand(0);
2547 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2548 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2550 // AND X, 0 -> 0, not "rlwinm 32".
2551 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2552 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2555 // ISD::OR doesn't get all the bitfield insertion fun.
2556 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
2557 if (isInt32Immediate(N->getOperand(1), Imm) &&
2558 N->getOperand(0).getOpcode() == ISD::OR &&
2559 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2562 if (isRunOfOnes(Imm, MB, ME)) {
2563 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2564 N->getOperand(0).getOperand(1),
2565 getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
2566 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
2570 // Other cases are autogenerated.
2574 if (N->getValueType(0) == MVT::i32)
2575 if (SDNode *I = SelectBitfieldInsert(N))
2579 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2580 isIntS16Immediate(N->getOperand(1), Imm)) {
2581 APInt LHSKnownZero, LHSKnownOne;
2582 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2584 // If this is equivalent to an add, then we can fold it with the
2585 // FrameIndex calculation.
2586 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
2587 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2590 // Other cases are autogenerated.
2595 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2596 isIntS16Immediate(N->getOperand(1), Imm))
2597 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2602 unsigned Imm, SH, MB, ME;
2603 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2604 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2605 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2606 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
2607 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2610 // Other cases are autogenerated.
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), getI32Imm(MB), getI32Imm(ME) };
2619 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2622 // Other cases are autogenerated.
2625 // FIXME: Remove this once the ANDI glue bug is fixed:
2626 case PPCISD::ANDIo_1_EQ_BIT:
2627 case PPCISD::ANDIo_1_GT_BIT: {
2631 EVT InVT = N->getOperand(0).getValueType();
2632 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2633 "Invalid input type for ANDIo_1_EQ_BIT");
2635 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2636 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2638 CurDAG->getTargetConstant(1, InVT)), 0);
2639 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2641 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2642 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2644 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2646 SDValue(AndI.getNode(), 1) /* glue */);
2648 case ISD::SELECT_CC: {
2649 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2650 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2651 bool isPPC64 = (PtrVT == MVT::i64);
2653 // If this is a select of i1 operands, we'll pattern match it.
2654 if (PPCSubTarget->useCRBits() &&
2655 N->getOperand(0).getValueType() == MVT::i1)
2658 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2660 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2661 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2662 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2663 if (N1C->isNullValue() && N3C->isNullValue() &&
2664 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2665 // FIXME: Implement this optzn for PPC64.
2666 N->getValueType(0) == MVT::i32) {
2668 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2669 N->getOperand(0), getI32Imm(~0U));
2670 return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
2671 SDValue(Tmp, 0), N->getOperand(0),
2675 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2677 if (N->getValueType(0) == MVT::i1) {
2678 // An i1 select is: (c & t) | (!c & f).
2680 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2684 default: llvm_unreachable("Invalid CC index");
2685 case 0: SRI = PPC::sub_lt; break;
2686 case 1: SRI = PPC::sub_gt; break;
2687 case 2: SRI = PPC::sub_eq; break;
2688 case 3: SRI = PPC::sub_un; break;
2691 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2693 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2695 SDValue C = Inv ? NotCCBit : CCBit,
2696 NotC = Inv ? CCBit : NotCCBit;
2698 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2699 C, N->getOperand(2)), 0);
2700 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2701 NotC, N->getOperand(3)), 0);
2703 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2706 unsigned BROpc = getPredicateForSetCC(CC);
2708 unsigned SelectCCOp;
2709 if (N->getValueType(0) == MVT::i32)
2710 SelectCCOp = PPC::SELECT_CC_I4;
2711 else if (N->getValueType(0) == MVT::i64)
2712 SelectCCOp = PPC::SELECT_CC_I8;
2713 else if (N->getValueType(0) == MVT::f32)
2714 SelectCCOp = PPC::SELECT_CC_F4;
2715 else if (N->getValueType(0) == MVT::f64)
2716 if (PPCSubTarget->hasVSX())
2717 SelectCCOp = PPC::SELECT_CC_VSFRC;
2719 SelectCCOp = PPC::SELECT_CC_F8;
2720 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2721 SelectCCOp = PPC::SELECT_CC_QFRC;
2722 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2723 SelectCCOp = PPC::SELECT_CC_QSRC;
2724 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2725 SelectCCOp = PPC::SELECT_CC_QBRC;
2726 else if (N->getValueType(0) == MVT::v2f64 ||
2727 N->getValueType(0) == MVT::v2i64)
2728 SelectCCOp = PPC::SELECT_CC_VSRC;
2730 SelectCCOp = PPC::SELECT_CC_VRRC;
2732 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2734 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2737 if (PPCSubTarget->hasVSX()) {
2738 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2739 return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2743 case ISD::VECTOR_SHUFFLE:
2744 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2745 N->getValueType(0) == MVT::v2i64)) {
2746 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2748 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2749 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2752 for (int i = 0; i < 2; ++i)
2753 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2758 // For little endian, we must swap the input operands and adjust
2759 // the mask elements (reverse and invert them).
2760 if (PPCSubTarget->isLittleEndian()) {
2761 std::swap(Op1, Op2);
2762 unsigned tmp = DM[0];
2767 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2769 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2770 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2771 isa<LoadSDNode>(Op1.getOperand(0))) {
2772 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2773 SDValue Base, Offset;
2775 if (LD->isUnindexed() &&
2776 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2777 SDValue Chain = LD->getChain();
2778 SDValue Ops[] = { Base, Offset, Chain };
2779 return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2780 N->getValueType(0), Ops);
2784 SDValue Ops[] = { Op1, Op2, DMV };
2785 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2791 bool IsPPC64 = PPCSubTarget->isPPC64();
2792 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2793 return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
2794 (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
2795 (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2798 case PPCISD::COND_BRANCH: {
2799 // Op #0 is the Chain.
2800 // Op #1 is the PPC::PRED_* number.
2802 // Op #3 is the Dest MBB
2803 // Op #4 is the Flag.
2804 // Prevent PPC::PRED_* from being selected into LI.
2806 getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
2807 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2808 N->getOperand(0), N->getOperand(4) };
2809 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2812 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2813 unsigned PCC = getPredicateForSetCC(CC);
2815 if (N->getOperand(2).getValueType() == MVT::i1) {
2819 default: llvm_unreachable("Unexpected Boolean-operand predicate");
2820 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
2821 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
2822 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
2823 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
2824 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2825 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
2828 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2829 N->getOperand(Swap ? 3 : 2),
2830 N->getOperand(Swap ? 2 : 3)), 0);
2831 return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
2832 BitComp, N->getOperand(4), N->getOperand(0));
2835 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
2836 SDValue Ops[] = { getI32Imm(PCC), CondCode,
2837 N->getOperand(4), N->getOperand(0) };
2838 return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2841 // FIXME: Should custom lower this.
2842 SDValue Chain = N->getOperand(0);
2843 SDValue Target = N->getOperand(1);
2844 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
2845 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
2846 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
2848 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2850 case PPCISD::TOC_ENTRY: {
2851 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
2852 "Only supported for 64-bit ABI and 32-bit SVR4");
2853 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
2854 SDValue GA = N->getOperand(0);
2855 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LWZtoc, dl,
2856 MVT::i32, GA, N->getOperand(1)));
2859 // For medium and large code model, we generate two instructions as
2860 // described below. Otherwise we allow SelectCodeCommon to handle this,
2861 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
2862 CodeModel::Model CModel = TM.getCodeModel();
2863 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
2866 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
2867 // If it is an externally defined symbol, a symbol with common linkage,
2868 // a non-local function address, or a jump table address, or if we are
2869 // generating code for large code model, we generate:
2870 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
2871 // Otherwise we generate:
2872 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
2873 SDValue GA = N->getOperand(0);
2874 SDValue TOCbase = N->getOperand(1);
2875 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
2878 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
2879 CModel == CodeModel::Large)
2880 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2881 MVT::i64, GA, SDValue(Tmp, 0)));
2883 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
2884 const GlobalValue *GValue = G->getGlobal();
2885 if ((GValue->getType()->getElementType()->isFunctionTy() &&
2886 (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
2887 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
2888 GValue->hasAvailableExternallyLinkage())
2889 return transferMemOperands(N, CurDAG->getMachineNode(PPC::LDtocL, dl,
2890 MVT::i64, GA, SDValue(Tmp, 0)));
2893 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2894 SDValue(Tmp, 0), GA);
2896 case PPCISD::PPC32_PICGOT: {
2897 // Generate a PIC-safe GOT reference.
2898 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
2899 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
2900 return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(), MVT::i32);
2902 case PPCISD::VADD_SPLAT: {
2903 // This expands into one of three sequences, depending on whether
2904 // the first operand is odd or even, positive or negative.
2905 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
2906 isa<ConstantSDNode>(N->getOperand(1)) &&
2907 "Invalid operand on VADD_SPLAT!");
2909 int Elt = N->getConstantOperandVal(0);
2910 int EltSize = N->getConstantOperandVal(1);
2911 unsigned Opc1, Opc2, Opc3;
2915 Opc1 = PPC::VSPLTISB;
2916 Opc2 = PPC::VADDUBM;
2917 Opc3 = PPC::VSUBUBM;
2919 } else if (EltSize == 2) {
2920 Opc1 = PPC::VSPLTISH;
2921 Opc2 = PPC::VADDUHM;
2922 Opc3 = PPC::VSUBUHM;
2925 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2926 Opc1 = PPC::VSPLTISW;
2927 Opc2 = PPC::VADDUWM;
2928 Opc3 = PPC::VSUBUWM;
2932 if ((Elt & 1) == 0) {
2933 // Elt is even, in the range [-32,-18] + [16,30].
2935 // Convert: VADD_SPLAT elt, size
2936 // Into: tmp = VSPLTIS[BHW] elt
2937 // VADDU[BHW]M tmp, tmp
2938 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
2939 SDValue EltVal = getI32Imm(Elt >> 1);
2940 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2941 SDValue TmpVal = SDValue(Tmp, 0);
2942 return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
2944 } else if (Elt > 0) {
2945 // Elt is odd and positive, in the range [17,31].
2947 // Convert: VADD_SPLAT elt, size
2948 // Into: tmp1 = VSPLTIS[BHW] elt-16
2949 // tmp2 = VSPLTIS[BHW] -16
2950 // VSUBU[BHW]M tmp1, tmp2
2951 SDValue EltVal = getI32Imm(Elt - 16);
2952 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2953 EltVal = getI32Imm(-16);
2954 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2955 return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
2959 // Elt is odd and negative, in the range [-31,-17].
2961 // Convert: VADD_SPLAT elt, size
2962 // Into: tmp1 = VSPLTIS[BHW] elt+16
2963 // tmp2 = VSPLTIS[BHW] -16
2964 // VADDU[BHW]M tmp1, tmp2
2965 SDValue EltVal = getI32Imm(Elt + 16);
2966 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2967 EltVal = getI32Imm(-16);
2968 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
2969 return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
2975 return SelectCode(N);
2978 // If the target supports the cmpb instruction, do the idiom recognition here.
2979 // We don't do this as a DAG combine because we don't want to do it as nodes
2980 // are being combined (because we might miss part of the eventual idiom). We
2981 // don't want to do it during instruction selection because we want to reuse
2982 // the logic for lowering the masking operations already part of the
2983 // instruction selector.
2984 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
2987 assert(N->getOpcode() == ISD::OR &&
2988 "Only OR nodes are supported for CMPB");
2991 if (!PPCSubTarget->hasCMPB())
2994 if (N->getValueType(0) != MVT::i32 &&
2995 N->getValueType(0) != MVT::i64)
2998 EVT VT = N->getValueType(0);
3001 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3002 uint64_t Mask = 0, Alt = 0;
3004 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3005 uint64_t &Mask, uint64_t &Alt,
3006 SDValue &LHS, SDValue &RHS) {
3007 if (O.getOpcode() != ISD::SELECT_CC)
3009 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3011 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3012 !isa<ConstantSDNode>(O.getOperand(3)))
3015 uint64_t PM = O.getConstantOperandVal(2);
3016 uint64_t PAlt = O.getConstantOperandVal(3);
3017 for (b = 0; b < 8; ++b) {
3018 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3019 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3028 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3029 O.getConstantOperandVal(1) != 0) {
3030 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3031 if (Op0.getOpcode() == ISD::TRUNCATE)
3032 Op0 = Op0.getOperand(0);
3033 if (Op1.getOpcode() == ISD::TRUNCATE)
3034 Op1 = Op1.getOperand(0);
3036 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3037 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3038 isa<ConstantSDNode>(Op0.getOperand(1))) {
3040 unsigned Bits = Op0.getValueType().getSizeInBits();
3043 if (Op0.getConstantOperandVal(1) != Bits-8)
3046 LHS = Op0.getOperand(0);
3047 RHS = Op1.getOperand(0);
3051 // When we have small integers (i16 to be specific), the form present
3052 // post-legalization uses SETULT in the SELECT_CC for the
3053 // higher-order byte, depending on the fact that the
3054 // even-higher-order bytes are known to all be zero, for example:
3055 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3056 // (so when the second byte is the same, because all higher-order
3057 // bits from bytes 3 and 4 are known to be zero, the result of the
3058 // xor can be at most 255)
3059 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3060 isa<ConstantSDNode>(O.getOperand(1))) {
3062 uint64_t ULim = O.getConstantOperandVal(1);
3063 if (ULim != (UINT64_C(1) << b*8))
3066 // Now we need to make sure that the upper bytes are known to be
3068 unsigned Bits = Op0.getValueType().getSizeInBits();
3069 if (!CurDAG->MaskedValueIsZero(Op0,
3070 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3073 LHS = Op0.getOperand(0);
3074 RHS = Op0.getOperand(1);
3081 if (CC != ISD::SETEQ)
3084 SDValue Op = O.getOperand(0);
3085 if (Op.getOpcode() == ISD::AND) {
3086 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3088 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3091 SDValue XOR = Op.getOperand(0);
3092 if (XOR.getOpcode() == ISD::TRUNCATE)
3093 XOR = XOR.getOperand(0);
3094 if (XOR.getOpcode() != ISD::XOR)
3097 LHS = XOR.getOperand(0);
3098 RHS = XOR.getOperand(1);
3100 } else if (Op.getOpcode() == ISD::SRL) {
3101 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3103 unsigned Bits = Op.getValueType().getSizeInBits();
3106 if (Op.getConstantOperandVal(1) != Bits-8)
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);
3123 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3124 while (!Queue.empty()) {
3125 SDValue V = Queue.pop_back_val();
3127 for (const SDValue &O : V.getNode()->ops()) {
3129 uint64_t M = 0, A = 0;
3131 if (O.getOpcode() == ISD::OR) {
3133 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3137 BytesFound[b] = true;
3140 } else if ((LHS == ORHS && RHS == OLHS) ||
3141 (RHS == ORHS && LHS == OLHS)) {
3142 BytesFound[b] = true;
3154 unsigned LastB = 0, BCnt = 0;
3155 for (unsigned i = 0; i < 8; ++i)
3156 if (BytesFound[LastB]) {
3161 if (!LastB || BCnt < 2)
3164 // Because we'll be zero-extending the output anyway if don't have a specific
3165 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3166 if (LHS.getValueType() != VT) {
3167 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3168 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3171 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3173 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3174 if (NonTrivialMask && !Alt) {
3175 // Res = Mask & CMPB
3176 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, CurDAG->getConstant(Mask, VT));
3178 // Res = (CMPB & Mask) | (~CMPB & Alt)
3179 // Which, as suggested here:
3180 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3181 // can be written as:
3182 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3183 // useful because the (Alt ^ Mask) can be pre-computed.
3184 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3185 CurDAG->getConstant(Mask ^ Alt, VT));
3186 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, CurDAG->getConstant(Alt, VT));
3192 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3193 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3194 // involves constant materialization of a 0 or a 1 or both. If the result of
3195 // the extension is then operated upon by some operator that can be constant
3196 // folded with a constant 0 or 1, and that constant can be materialized using
3197 // only one instruction (like a zero or one), then we should fold in those
3198 // operations with the select.
3199 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3200 if (!PPCSubTarget->useCRBits())
3203 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3204 N->getOpcode() != ISD::SIGN_EXTEND &&
3205 N->getOpcode() != ISD::ANY_EXTEND)
3208 if (N->getOperand(0).getValueType() != MVT::i1)
3211 if (!N->hasOneUse())
3215 EVT VT = N->getValueType(0);
3216 SDValue Cond = N->getOperand(0);
3218 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, VT);
3219 SDValue ConstFalse = CurDAG->getConstant(0, VT);
3222 SDNode *User = *N->use_begin();
3223 if (User->getNumOperands() != 2)
3226 auto TryFold = [this, N, User](SDValue Val) {
3227 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3228 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3229 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3231 return CurDAG->FoldConstantArithmetic(User->getOpcode(),
3232 User->getValueType(0),
3233 O0.getNode(), O1.getNode());
3236 SDValue TrueRes = TryFold(ConstTrue);
3239 SDValue FalseRes = TryFold(ConstFalse);
3243 // For us to materialize these using one instruction, we must be able to
3244 // represent them as signed 16-bit integers.
3245 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3246 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3247 if (!isInt<16>(True) || !isInt<16>(False))
3250 // We can replace User with a new SELECT node, and try again to see if we
3251 // can fold the select with its user.
3252 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3254 ConstTrue = TrueRes;
3255 ConstFalse = FalseRes;
3256 } while (N->hasOneUse());
3259 void PPCDAGToDAGISel::PreprocessISelDAG() {
3260 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3263 bool MadeChange = false;
3264 while (Position != CurDAG->allnodes_begin()) {
3265 SDNode *N = --Position;
3270 switch (N->getOpcode()) {
3273 Res = combineToCMPB(N);
3278 foldBoolExts(Res, N);
3281 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3282 DEBUG(N->dump(CurDAG));
3283 DEBUG(dbgs() << "\nNew: ");
3284 DEBUG(Res.getNode()->dump(CurDAG));
3285 DEBUG(dbgs() << "\n");
3287 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3293 CurDAG->RemoveDeadNodes();
3296 /// PostprocessISelDAG - Perform some late peephole optimizations
3297 /// on the DAG representation.
3298 void PPCDAGToDAGISel::PostprocessISelDAG() {
3300 // Skip peepholes at -O0.
3301 if (TM.getOptLevel() == CodeGenOpt::None)
3306 PeepholePPC64ZExt();
3309 // Check if all users of this node will become isel where the second operand
3310 // is the constant zero. If this is so, and if we can negate the condition,
3311 // then we can flip the true and false operands. This will allow the zero to
3312 // be folded with the isel so that we don't need to materialize a register
3314 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3315 // If we're not using isel, then this does not matter.
3316 if (!PPCSubTarget->hasISEL())
3319 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3322 if (!User->isMachineOpcode())
3324 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3325 User->getMachineOpcode() != PPC::SELECT_I8)
3328 SDNode *Op2 = User->getOperand(2).getNode();
3329 if (!Op2->isMachineOpcode())
3332 if (Op2->getMachineOpcode() != PPC::LI &&
3333 Op2->getMachineOpcode() != PPC::LI8)
3336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3340 if (!C->isNullValue())
3347 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3348 SmallVector<SDNode *, 4> ToReplace;
3349 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3352 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3353 User->getMachineOpcode() == PPC::SELECT_I8) &&
3354 "Must have all select users");
3355 ToReplace.push_back(User);
3358 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3359 UE = ToReplace.end(); UI != UE; ++UI) {
3362 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3363 User->getValueType(0), User->getOperand(0),
3364 User->getOperand(2),
3365 User->getOperand(1));
3367 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3368 DEBUG(User->dump(CurDAG));
3369 DEBUG(dbgs() << "\nNew: ");
3370 DEBUG(ResNode->dump(CurDAG));
3371 DEBUG(dbgs() << "\n");
3373 ReplaceUses(User, ResNode);
3377 void PPCDAGToDAGISel::PeepholeCROps() {
3381 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
3382 E = CurDAG->allnodes_end(); I != E; ++I) {
3383 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
3384 if (!MachineNode || MachineNode->use_empty())
3386 SDNode *ResNode = MachineNode;
3388 bool Op1Set = false, Op1Unset = false,
3390 Op2Set = false, Op2Unset = false,
3393 unsigned Opcode = MachineNode->getMachineOpcode();
3404 SDValue Op = MachineNode->getOperand(1);
3405 if (Op.isMachineOpcode()) {
3406 if (Op.getMachineOpcode() == PPC::CRSET)
3408 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3410 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3411 Op.getOperand(0) == Op.getOperand(1))
3417 case PPC::SELECT_I4:
3418 case PPC::SELECT_I8:
3419 case PPC::SELECT_F4:
3420 case PPC::SELECT_F8:
3421 case PPC::SELECT_QFRC:
3422 case PPC::SELECT_QSRC:
3423 case PPC::SELECT_QBRC:
3424 case PPC::SELECT_VRRC:
3425 case PPC::SELECT_VSFRC:
3426 case PPC::SELECT_VSRC: {
3427 SDValue Op = MachineNode->getOperand(0);
3428 if (Op.isMachineOpcode()) {
3429 if (Op.getMachineOpcode() == PPC::CRSET)
3431 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3433 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3434 Op.getOperand(0) == Op.getOperand(1))
3441 bool SelectSwap = false;
3445 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3447 ResNode = MachineNode->getOperand(0).getNode();
3450 ResNode = MachineNode->getOperand(1).getNode();
3453 ResNode = MachineNode->getOperand(0).getNode();
3454 else if (Op1Unset || Op2Unset)
3455 // x & 0 = 0 & y = 0
3456 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3459 // ~x & y = andc(y, x)
3460 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3461 MVT::i1, MachineNode->getOperand(1),
3462 MachineNode->getOperand(0).
3465 // x & ~y = andc(x, y)
3466 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3467 MVT::i1, MachineNode->getOperand(0),
3468 MachineNode->getOperand(1).
3470 else if (AllUsersSelectZero(MachineNode))
3471 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3472 MVT::i1, MachineNode->getOperand(0),
3473 MachineNode->getOperand(1)),
3477 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3478 // nand(x, x) -> nor(x, x)
3479 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3480 MVT::i1, MachineNode->getOperand(0),
3481 MachineNode->getOperand(0));
3483 // nand(1, y) -> nor(y, y)
3484 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3485 MVT::i1, MachineNode->getOperand(1),
3486 MachineNode->getOperand(1));
3488 // nand(x, 1) -> nor(x, x)
3489 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3490 MVT::i1, MachineNode->getOperand(0),
3491 MachineNode->getOperand(0));
3492 else if (Op1Unset || Op2Unset)
3493 // nand(x, 0) = nand(0, y) = 1
3494 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3497 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3498 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3499 MVT::i1, MachineNode->getOperand(0).
3501 MachineNode->getOperand(1));
3503 // nand(x, ~y) = ~x | y = orc(y, x)
3504 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3505 MVT::i1, MachineNode->getOperand(1).
3507 MachineNode->getOperand(0));
3508 else if (AllUsersSelectZero(MachineNode))
3509 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3510 MVT::i1, MachineNode->getOperand(0),
3511 MachineNode->getOperand(1)),
3515 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3517 ResNode = MachineNode->getOperand(0).getNode();
3518 else if (Op1Set || Op2Set)
3519 // x | 1 = 1 | y = 1
3520 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3524 ResNode = MachineNode->getOperand(1).getNode();
3527 ResNode = MachineNode->getOperand(0).getNode();
3529 // ~x | y = orc(y, x)
3530 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3531 MVT::i1, MachineNode->getOperand(1),
3532 MachineNode->getOperand(0).
3535 // x | ~y = orc(x, y)
3536 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3537 MVT::i1, MachineNode->getOperand(0),
3538 MachineNode->getOperand(1).
3540 else if (AllUsersSelectZero(MachineNode))
3541 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3542 MVT::i1, MachineNode->getOperand(0),
3543 MachineNode->getOperand(1)),
3547 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3549 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3552 // xor(1, y) -> nor(y, y)
3553 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3554 MVT::i1, MachineNode->getOperand(1),
3555 MachineNode->getOperand(1));
3557 // xor(x, 1) -> nor(x, x)
3558 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3559 MVT::i1, MachineNode->getOperand(0),
3560 MachineNode->getOperand(0));
3563 ResNode = MachineNode->getOperand(1).getNode();
3566 ResNode = MachineNode->getOperand(0).getNode();
3568 // xor(~x, y) = eqv(x, y)
3569 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3570 MVT::i1, MachineNode->getOperand(0).
3572 MachineNode->getOperand(1));
3574 // xor(x, ~y) = eqv(x, y)
3575 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3576 MVT::i1, MachineNode->getOperand(0),
3577 MachineNode->getOperand(1).
3579 else if (AllUsersSelectZero(MachineNode))
3580 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3581 MVT::i1, MachineNode->getOperand(0),
3582 MachineNode->getOperand(1)),
3586 if (Op1Set || Op2Set)
3588 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3591 // nor(0, y) = ~y -> nor(y, y)
3592 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3593 MVT::i1, MachineNode->getOperand(1),
3594 MachineNode->getOperand(1));
3597 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3598 MVT::i1, MachineNode->getOperand(0),
3599 MachineNode->getOperand(0));
3601 // nor(~x, y) = andc(x, y)
3602 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3603 MVT::i1, MachineNode->getOperand(0).
3605 MachineNode->getOperand(1));
3607 // nor(x, ~y) = andc(y, x)
3608 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3609 MVT::i1, MachineNode->getOperand(1).
3611 MachineNode->getOperand(0));
3612 else if (AllUsersSelectZero(MachineNode))
3613 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3614 MVT::i1, MachineNode->getOperand(0),
3615 MachineNode->getOperand(1)),
3619 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3621 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3625 ResNode = MachineNode->getOperand(1).getNode();
3628 ResNode = MachineNode->getOperand(0).getNode();
3630 // eqv(0, y) = ~y -> nor(y, y)
3631 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3632 MVT::i1, MachineNode->getOperand(1),
3633 MachineNode->getOperand(1));
3636 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3637 MVT::i1, MachineNode->getOperand(0),
3638 MachineNode->getOperand(0));
3640 // eqv(~x, y) = xor(x, y)
3641 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3642 MVT::i1, MachineNode->getOperand(0).
3644 MachineNode->getOperand(1));
3646 // eqv(x, ~y) = xor(x, y)
3647 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3648 MVT::i1, MachineNode->getOperand(0),
3649 MachineNode->getOperand(1).
3651 else if (AllUsersSelectZero(MachineNode))
3652 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3653 MVT::i1, MachineNode->getOperand(0),
3654 MachineNode->getOperand(1)),
3658 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3660 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3664 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3665 MVT::i1, MachineNode->getOperand(1),
3666 MachineNode->getOperand(1));
3667 else if (Op1Unset || Op2Set)
3668 // andc(0, y) = andc(x, 1) = 0
3669 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3673 ResNode = MachineNode->getOperand(0).getNode();
3675 // andc(~x, y) = ~(x | y) = nor(x, y)
3676 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3677 MVT::i1, MachineNode->getOperand(0).
3679 MachineNode->getOperand(1));
3681 // andc(x, ~y) = x & y
3682 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3683 MVT::i1, MachineNode->getOperand(0),
3684 MachineNode->getOperand(1).
3686 else if (AllUsersSelectZero(MachineNode))
3687 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3688 MVT::i1, MachineNode->getOperand(1),
3689 MachineNode->getOperand(0)),
3693 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3695 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3697 else if (Op1Set || Op2Unset)
3698 // orc(1, y) = orc(x, 0) = 1
3699 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3703 ResNode = MachineNode->getOperand(0).getNode();
3706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3707 MVT::i1, MachineNode->getOperand(1),
3708 MachineNode->getOperand(1));
3710 // orc(~x, y) = ~(x & y) = nand(x, y)
3711 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3712 MVT::i1, MachineNode->getOperand(0).
3714 MachineNode->getOperand(1));
3716 // orc(x, ~y) = x | y
3717 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3718 MVT::i1, MachineNode->getOperand(0),
3719 MachineNode->getOperand(1).
3721 else if (AllUsersSelectZero(MachineNode))
3722 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3723 MVT::i1, MachineNode->getOperand(1),
3724 MachineNode->getOperand(0)),
3727 case PPC::SELECT_I4:
3728 case PPC::SELECT_I8:
3729 case PPC::SELECT_F4:
3730 case PPC::SELECT_F8:
3731 case PPC::SELECT_QFRC:
3732 case PPC::SELECT_QSRC:
3733 case PPC::SELECT_QBRC:
3734 case PPC::SELECT_VRRC:
3735 case PPC::SELECT_VSFRC:
3736 case PPC::SELECT_VSRC:
3738 ResNode = MachineNode->getOperand(1).getNode();
3740 ResNode = MachineNode->getOperand(2).getNode();
3742 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3744 MachineNode->getValueType(0),
3745 MachineNode->getOperand(0).
3747 MachineNode->getOperand(2),
3748 MachineNode->getOperand(1));
3753 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3757 MachineNode->getOperand(0).
3759 MachineNode->getOperand(1),
3760 MachineNode->getOperand(2));
3761 // FIXME: Handle Op1Set, Op1Unset here too.
3765 // If we're inverting this node because it is used only by selects that
3766 // we'd like to swap, then swap the selects before the node replacement.
3768 SwapAllSelectUsers(MachineNode);
3770 if (ResNode != MachineNode) {
3771 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3772 DEBUG(MachineNode->dump(CurDAG));
3773 DEBUG(dbgs() << "\nNew: ");
3774 DEBUG(ResNode->dump(CurDAG));
3775 DEBUG(dbgs() << "\n");
3777 ReplaceUses(MachineNode, ResNode);
3782 CurDAG->RemoveDeadNodes();
3783 } while (IsModified);
3786 // Gather the set of 32-bit operations that are known to have their
3787 // higher-order 32 bits zero, where ToPromote contains all such operations.
3788 static bool PeepholePPC64ZExtGather(SDValue Op32,
3789 SmallPtrSetImpl<SDNode *> &ToPromote) {
3790 if (!Op32.isMachineOpcode())
3793 // First, check for the "frontier" instructions (those that will clear the
3794 // higher-order 32 bits.
3796 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3797 // around. If it does not, then these instructions will clear the
3798 // higher-order bits.
3799 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3800 Op32.getMachineOpcode() == PPC::RLWNM) &&
3801 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3802 ToPromote.insert(Op32.getNode());
3806 // SLW and SRW always clear the higher-order bits.
3807 if (Op32.getMachineOpcode() == PPC::SLW ||
3808 Op32.getMachineOpcode() == PPC::SRW) {
3809 ToPromote.insert(Op32.getNode());
3813 // For LI and LIS, we need the immediate to be positive (so that it is not
3815 if (Op32.getMachineOpcode() == PPC::LI ||
3816 Op32.getMachineOpcode() == PPC::LIS) {
3817 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3820 ToPromote.insert(Op32.getNode());
3824 // LHBRX and LWBRX always clear the higher-order bits.
3825 if (Op32.getMachineOpcode() == PPC::LHBRX ||
3826 Op32.getMachineOpcode() == PPC::LWBRX) {
3827 ToPromote.insert(Op32.getNode());
3831 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
3832 if (Op32.getMachineOpcode() == PPC::CNTLZW) {
3833 ToPromote.insert(Op32.getNode());
3837 // Next, check for those instructions we can look through.
3839 // Assuming the mask does not wrap around, then the higher-order bits are
3840 // taken directly from the first operand.
3841 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
3842 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
3843 SmallPtrSet<SDNode *, 16> ToPromote1;
3844 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3847 ToPromote.insert(Op32.getNode());
3848 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3852 // For OR, the higher-order bits are zero if that is true for both operands.
3853 // For SELECT_I4, the same is true (but the relevant operand numbers are
3855 if (Op32.getMachineOpcode() == PPC::OR ||
3856 Op32.getMachineOpcode() == PPC::SELECT_I4) {
3857 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
3858 SmallPtrSet<SDNode *, 16> ToPromote1;
3859 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
3861 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3864 ToPromote.insert(Op32.getNode());
3865 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3869 // For ORI and ORIS, we need the higher-order bits of the first operand to be
3870 // zero, and also for the constant to be positive (so that it is not sign
3872 if (Op32.getMachineOpcode() == PPC::ORI ||
3873 Op32.getMachineOpcode() == PPC::ORIS) {
3874 SmallPtrSet<SDNode *, 16> ToPromote1;
3875 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3877 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3880 ToPromote.insert(Op32.getNode());
3881 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3885 // The higher-order bits of AND are zero if that is true for at least one of
3887 if (Op32.getMachineOpcode() == PPC::AND) {
3888 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3890 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3892 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3893 if (!Op0OK && !Op1OK)
3896 ToPromote.insert(Op32.getNode());
3899 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3902 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3907 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
3908 // of the first operand, or if the second operand is positive (so that it is
3909 // not sign extended).
3910 if (Op32.getMachineOpcode() == PPC::ANDIo ||
3911 Op32.getMachineOpcode() == PPC::ANDISo) {
3912 SmallPtrSet<SDNode *, 16> ToPromote1;
3914 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3915 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3916 if (!Op0OK && !Op1OK)
3919 ToPromote.insert(Op32.getNode());
3922 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3930 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3931 if (!PPCSubTarget->isPPC64())
3934 // When we zero-extend from i32 to i64, we use a pattern like this:
3935 // def : Pat<(i64 (zext i32:$in)),
3936 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
3938 // There are several 32-bit shift/rotate instructions, however, that will
3939 // clear the higher-order bits of their output, rendering the RLDICL
3940 // unnecessary. When that happens, we remove it here, and redefine the
3941 // relevant 32-bit operation to be a 64-bit operation.
3943 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3946 bool MadeChange = false;
3947 while (Position != CurDAG->allnodes_begin()) {
3948 SDNode *N = --Position;
3949 // Skip dead nodes and any non-machine opcodes.
3950 if (N->use_empty() || !N->isMachineOpcode())
3953 if (N->getMachineOpcode() != PPC::RLDICL)
3956 if (N->getConstantOperandVal(1) != 0 ||
3957 N->getConstantOperandVal(2) != 32)
3960 SDValue ISR = N->getOperand(0);
3961 if (!ISR.isMachineOpcode() ||
3962 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3965 if (!ISR.hasOneUse())
3968 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3971 SDValue IDef = ISR.getOperand(0);
3972 if (!IDef.isMachineOpcode() ||
3973 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3976 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3977 // can get rid of it.
3979 SDValue Op32 = ISR->getOperand(1);
3980 if (!Op32.isMachineOpcode())
3983 // There are some 32-bit instructions that always clear the high-order 32
3984 // bits, there are also some instructions (like AND) that we can look
3986 SmallPtrSet<SDNode *, 16> ToPromote;
3987 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
3990 // If the ToPromote set contains nodes that have uses outside of the set
3991 // (except for the original INSERT_SUBREG), then abort the transformation.
3992 bool OutsideUse = false;
3993 for (SDNode *PN : ToPromote) {
3994 for (SDNode *UN : PN->uses()) {
3995 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4009 // We now know that this zero extension can be removed by promoting to
4010 // nodes in ToPromote to 64-bit operations, where for operations in the
4011 // frontier of the set, we need to insert INSERT_SUBREGs for their
4013 for (SDNode *PN : ToPromote) {
4015 switch (PN->getMachineOpcode()) {
4017 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4018 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4019 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4020 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4021 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4022 case PPC::LI: NewOpcode = PPC::LI8; break;
4023 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4024 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4025 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4026 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4027 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4028 case PPC::OR: NewOpcode = PPC::OR8; break;
4029 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4030 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4031 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4032 case PPC::AND: NewOpcode = PPC::AND8; break;
4033 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4034 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4037 // Note: During the replacement process, the nodes will be in an
4038 // inconsistent state (some instructions will have operands with values
4039 // of the wrong type). Once done, however, everything should be right
4042 SmallVector<SDValue, 4> Ops;
4043 for (const SDValue &V : PN->ops()) {
4044 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4045 !isa<ConstantSDNode>(V)) {
4046 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4048 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4049 ISR.getNode()->getVTList(), ReplOpOps);
4050 Ops.push_back(SDValue(ReplOp, 0));
4056 // Because all to-be-promoted nodes only have users that are other
4057 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4058 // the i32 result value type with i64.
4060 SmallVector<EVT, 2> NewVTs;
4061 SDVTList VTs = PN->getVTList();
4062 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4063 if (VTs.VTs[i] == MVT::i32)
4064 NewVTs.push_back(MVT::i64);
4066 NewVTs.push_back(VTs.VTs[i]);
4068 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4069 DEBUG(PN->dump(CurDAG));
4071 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4073 DEBUG(dbgs() << "\nNew: ");
4074 DEBUG(PN->dump(CurDAG));
4075 DEBUG(dbgs() << "\n");
4078 // Now we replace the original zero extend and its associated INSERT_SUBREG
4079 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4082 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4083 DEBUG(N->dump(CurDAG));
4084 DEBUG(dbgs() << "\nNew: ");
4085 DEBUG(Op32.getNode()->dump(CurDAG));
4086 DEBUG(dbgs() << "\n");
4088 ReplaceUses(N, Op32.getNode());
4092 CurDAG->RemoveDeadNodes();
4095 void PPCDAGToDAGISel::PeepholePPC64() {
4096 // These optimizations are currently supported only for 64-bit SVR4.
4097 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4100 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4103 while (Position != CurDAG->allnodes_begin()) {
4104 SDNode *N = --Position;
4105 // Skip dead nodes and any non-machine opcodes.
4106 if (N->use_empty() || !N->isMachineOpcode())
4110 unsigned StorageOpcode = N->getMachineOpcode();
4112 switch (StorageOpcode) {
4143 // If this is a load or store with a zero offset, we may be able to
4144 // fold an add-immediate into the memory operation.
4145 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
4146 N->getConstantOperandVal(FirstOp) != 0)
4149 SDValue Base = N->getOperand(FirstOp + 1);
4150 if (!Base.isMachineOpcode())
4154 bool ReplaceFlags = true;
4156 // When the feeding operation is an add-immediate of some sort,
4157 // determine whether we need to add relocation information to the
4158 // target flags on the immediate operand when we fold it into the
4159 // load instruction.
4161 // For something like ADDItocL, the relocation information is
4162 // inferred from the opcode; when we process it in the AsmPrinter,
4163 // we add the necessary relocation there. A load, though, can receive
4164 // relocation from various flavors of ADDIxxx, so we need to carry
4165 // the relocation information in the target flags.
4166 switch (Base.getMachineOpcode()) {
4171 // In some cases (such as TLS) the relocation information
4172 // is already in place on the operand, so copying the operand
4174 ReplaceFlags = false;
4175 // For these cases, the immediate may not be divisible by 4, in
4176 // which case the fold is illegal for DS-form instructions. (The
4177 // other cases provide aligned addresses and are always safe.)
4178 if ((StorageOpcode == PPC::LWA ||
4179 StorageOpcode == PPC::LD ||
4180 StorageOpcode == PPC::STD) &&
4181 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4182 Base.getConstantOperandVal(1) % 4 != 0))
4185 case PPC::ADDIdtprelL:
4186 Flags = PPCII::MO_DTPREL_LO;
4188 case PPC::ADDItlsldL:
4189 Flags = PPCII::MO_TLSLD_LO;
4192 Flags = PPCII::MO_TOC_LO;
4196 // We found an opportunity. Reverse the operands from the add
4197 // immediate and substitute them into the load or store. If
4198 // needed, update the target flags for the immediate operand to
4199 // reflect the necessary relocation information.
4200 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4201 DEBUG(Base->dump(CurDAG));
4202 DEBUG(dbgs() << "\nN: ");
4203 DEBUG(N->dump(CurDAG));
4204 DEBUG(dbgs() << "\n");
4206 SDValue ImmOpnd = Base.getOperand(1);
4208 // If the relocation information isn't already present on the
4209 // immediate operand, add it now.
4211 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4213 const GlobalValue *GV = GA->getGlobal();
4214 // We can't perform this optimization for data whose alignment
4215 // is insufficient for the instruction encoding.
4216 if (GV->getAlignment() < 4 &&
4217 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4218 StorageOpcode == PPC::LWA)) {
4219 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4222 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
4223 } else if (ConstantPoolSDNode *CP =
4224 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4225 const Constant *C = CP->getConstVal();
4226 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4232 if (FirstOp == 1) // Store
4233 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4234 Base.getOperand(0), N->getOperand(3));
4236 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4239 // The add-immediate may now be dead, in which case remove it.
4240 if (Base.getNode()->use_empty())
4241 CurDAG->RemoveDeadNode(Base.getNode());
4246 /// createPPCISelDag - This pass converts a legalized DAG into a
4247 /// PowerPC-specific DAG, ready for instruction scheduling.
4249 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4250 return new PPCDAGToDAGISel(TM);
4253 static void initializePassOnce(PassRegistry &Registry) {
4254 const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
4255 PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
4256 nullptr, false, false);
4257 Registry.registerPass(*PI, true);
4260 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4261 CALL_ONCE_INITIALIZATION(initializePassOnce);