1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
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"
37 using namespace llvm;
38
39 #define DEBUG_TYPE "ppc-codegen"
40
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);
44
45 static cl::opt<bool>
46 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
47 cl::desc("use aggressive ppc isel for bit permutations"),
48 cl::Hidden);
49 static cl::opt<bool> BPermRewriterNoMasking(
50 "ppc-bit-perm-rewriter-stress-rotates",
51 cl::desc("stress rotate selection in aggressive ppc isel for "
52 "bit permutations"),
53 cl::Hidden);
54
55 namespace llvm {
56 void initializePPCDAGToDAGISelPass(PassRegistry&);
57 }
58
59 namespace {
60 //===--------------------------------------------------------------------===//
61 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
62 /// instructions for SelectionDAG operations.
63 ///
64 class PPCDAGToDAGISel : public SelectionDAGISel {
65 const PPCTargetMachine &TM;
66 const PPCSubtarget *PPCSubTarget;
67 const PPCTargetLowering *PPCLowering;
68 unsigned GlobalBaseReg;
69 public:
PPCDAGToDAGISel(PPCTargetMachine & tm)70 explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
71 : SelectionDAGISel(tm), TM(tm) {
72 initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
73 }
74
runOnMachineFunction(MachineFunction & MF)75 bool runOnMachineFunction(MachineFunction &MF) override {
76 // Make sure we re-emit a set of the global base reg if necessary
77 GlobalBaseReg = 0;
78 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
79 PPCLowering = PPCSubTarget->getTargetLowering();
80 SelectionDAGISel::runOnMachineFunction(MF);
81
82 if (!PPCSubTarget->isSVR4ABI())
83 InsertVRSaveCode(MF);
84
85 return true;
86 }
87
88 void PreprocessISelDAG() override;
89 void PostprocessISelDAG() override;
90
91 /// getI32Imm - Return a target constant with the specified value, of type
92 /// i32.
getI32Imm(unsigned Imm)93 inline SDValue getI32Imm(unsigned Imm) {
94 return CurDAG->getTargetConstant(Imm, MVT::i32);
95 }
96
97 /// getI64Imm - Return a target constant with the specified value, of type
98 /// i64.
getI64Imm(uint64_t Imm)99 inline SDValue getI64Imm(uint64_t Imm) {
100 return CurDAG->getTargetConstant(Imm, MVT::i64);
101 }
102
103 /// getSmallIPtrImm - Return a target constant of pointer type.
getSmallIPtrImm(unsigned Imm)104 inline SDValue getSmallIPtrImm(unsigned Imm) {
105 return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
106 }
107
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);
112
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();
116
117 SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
118
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;
122
123 SDNode *SelectBitfieldInsert(SDNode *N);
124 SDNode *SelectBitPermutation(SDNode *N);
125
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);
129
130 /// SelectAddrImm - Returns true if the address N can be represented by
131 /// a base register plus a signed 16-bit displacement [r+imm].
SelectAddrImm(SDValue N,SDValue & Disp,SDValue & Base)132 bool SelectAddrImm(SDValue N, SDValue &Disp,
133 SDValue &Base) {
134 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
135 }
136
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.
SelectAddrImmOffs(SDValue N,SDValue & Out) const140 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
141 if (N.getOpcode() == ISD::TargetConstant ||
142 N.getOpcode() == ISD::TargetGlobalAddress) {
143 Out = N;
144 return true;
145 }
146
147 return false;
148 }
149
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.
SelectAddrIdx(SDValue N,SDValue & Base,SDValue & Index)153 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
154 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
155 }
156
157 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
158 /// represented as an indexed [r+r] operation.
SelectAddrIdxOnly(SDValue N,SDValue & Base,SDValue & Index)159 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
160 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
161 }
162
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.
SelectAddrImmX4(SDValue N,SDValue & Disp,SDValue & Base)166 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
167 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
168 }
169
170 // Select an address into a single register.
SelectAddr(SDValue N,SDValue & Base)171 bool SelectAddr(SDValue N, SDValue &Base) {
172 Base = N;
173 return true;
174 }
175
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.
SelectInlineAsmMemoryOperand(const SDValue & Op,unsigned ConstraintID,std::vector<SDValue> & OutOps)181 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
182 unsigned ConstraintID,
183 std::vector<SDValue> &OutOps) override {
184
185 switch(ConstraintID) {
186 default:
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);
201 SDValue NewOp =
202 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
203 SDLoc(Op), Op.getValueType(),
204 Op, RC), 0);
205
206 OutOps.push_back(NewOp);
207 return false;
208 }
209 return true;
210 }
211
212 void InsertVRSaveCode(MachineFunction &MF);
213
getPassName() const214 const char *getPassName() const override {
215 return "PowerPC DAG->DAG Pattern Instruction Selection";
216 }
217
218 // Include the pieces autogenerated from the target description.
219 #include "PPCGenDAGISel.inc"
220
221 private:
222 SDNode *SelectSETCC(SDNode *N);
223
224 void PeepholePPC64();
225 void PeepholePPC64ZExt();
226 void PeepholeCROps();
227
228 SDValue combineToCMPB(SDNode *N);
229 void foldBoolExts(SDValue &Res, SDNode *&N);
230
231 bool AllUsersSelectZero(SDNode *N);
232 void SwapAllSelectUsers(SDNode *N);
233
234 SDNode *transferMemOperands(SDNode *N, SDNode *Result);
235 };
236 }
237
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.
InsertVRSaveCode(MachineFunction & Fn)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.
244 //
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;
252 break;
253 }
254 }
255 if (!HasVectorVReg) return; // nothing to do.
256
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:
260 //
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.
266
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);
271
272 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
273 MachineBasicBlock &EntryBB = *Fn.begin();
274 DebugLoc dl;
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);
284
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;
289
290 // Skip over all terminator instructions, which are part of the return
291 // sequence.
292 MachineBasicBlock::iterator I2 = IP;
293 while (I2 != BB->begin() && (--I2)->isTerminator())
294 IP = I2;
295
296 // Emit: MTVRSAVE InVRSave
297 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
298 }
299 }
300 }
301
302
303 /// getGlobalBaseReg - Output the instructions required to put the
304 /// base address to use for accessing globals into a register.
305 ///
getGlobalBaseReg()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();
313 DebugLoc dl;
314
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);
322 } else {
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);
330 }
331 } else {
332 GlobalBaseReg =
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);
336 }
337 } else {
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);
341 }
342 }
343 return CurDAG->getRegister(GlobalBaseReg,
344 PPCLowering->getPointerTy()).getNode();
345 }
346
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
350 /// immediate.
isIntS16Immediate(SDNode * N,short & Imm)351 static bool isIntS16Immediate(SDNode *N, short &Imm) {
352 if (N->getOpcode() != ISD::Constant)
353 return false;
354
355 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
356 if (N->getValueType(0) == MVT::i32)
357 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
358 else
359 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
360 }
361
isIntS16Immediate(SDValue Op,short & Imm)362 static bool isIntS16Immediate(SDValue Op, short &Imm) {
363 return isIntS16Immediate(Op.getNode(), Imm);
364 }
365
366
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.
isInt32Immediate(SDNode * N,unsigned & Imm)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();
372 return true;
373 }
374 return false;
375 }
376
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.
isInt64Immediate(SDNode * N,uint64_t & Imm)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();
382 return true;
383 }
384 return false;
385 }
386
387 // isInt32Immediate - This method tests to see if a constant operand.
388 // If so Imm will receive the 32 bit value.
isInt32Immediate(SDValue N,unsigned & Imm)389 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
390 return isInt32Immediate(N.getNode(), Imm);
391 }
392
393
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.
isOpcWithIntImmediate(SDNode * N,unsigned Opc,unsigned & Imm)397 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
398 return N->getOpcode() == Opc
399 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
400 }
401
getFrameIndex(SDNode * SN,SDNode * N,unsigned Offset)402 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
403 SDLoc dl(SN);
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;
407 if (SN->hasOneUse())
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));
412 }
413
isRotateAndMask(SDNode * N,unsigned Mask,bool isShiftMask,unsigned & SH,unsigned & MB,unsigned & ME)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)
420 return false;
421
422 unsigned Shift = 32;
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))
427 return false;
428
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
440 Shift = 32 - Shift;
441 } else if (Opcode == ISD::ROTL) {
442 Indeterminant = 0;
443 } else {
444 return false;
445 }
446
447 // if the mask doesn't intersect any Indeterminant bits
448 if (Mask && !(Mask & Indeterminant)) {
449 SH = Shift & 31;
450 // make sure the mask is still a mask (wrap arounds may not be)
451 return isRunOfOnes(Mask, MB, ME);
452 }
453 return false;
454 }
455
456 /// SelectBitfieldInsert - turn an or of two masked values into
457 /// the rotate left word immediate then mask insert (rlwimi) instruction.
SelectBitfieldInsert(SDNode * N)458 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
459 SDValue Op0 = N->getOperand(0);
460 SDValue Op1 = N->getOperand(1);
461 SDLoc dl(N);
462
463 APInt LKZ, LKO, RKZ, RKO;
464 CurDAG->computeKnownBits(Op0, LKZ, LKO);
465 CurDAG->computeKnownBits(Op1, RKZ, RKO);
466
467 unsigned TargetMask = LKZ.getZExtValue();
468 unsigned InsertMask = RKZ.getZExtValue();
469
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;
476
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) {
484 std::swap(Op0, Op1);
485 std::swap(Op0Opc, Op1Opc);
486 std::swap(TargetMask, InsertMask);
487 }
488 }
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) {
492 std::swap(Op0, Op1);
493 std::swap(Op0Opc, Op1Opc);
494 std::swap(TargetMask, InsertMask);
495 }
496 }
497
498 unsigned MB, ME;
499 if (isRunOfOnes(InsertMask, MB, ME)) {
500 SDValue Tmp1, Tmp2;
501
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;
506 }
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.
511 APInt MKZ, MKO;
512 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
513 bool CanFoldMask = InsertMask == MKO.getZExtValue();
514
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;
522 }
523 }
524
525 SH &= 31;
526 SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
527 getI32Imm(ME) };
528 return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
529 }
530 }
531 return nullptr;
532 }
533
534 // Predict the number of instructions that would be generated by calling
535 // SelectInt64(N).
SelectInt64CountDirect(int64_t Imm)536 static unsigned SelectInt64CountDirect(int64_t Imm) {
537 // Assume no remaining bits.
538 unsigned Remainder = 0;
539 // Assume no shift required.
540 unsigned Shift = 0;
541
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;
546
547 // If the shifted value fits 32 bits.
548 if (isInt<32>(ImmSh)) {
549 // Go with the shifted value.
550 Imm = ImmSh;
551 } else {
552 // Still stuck with a 64 bit value.
553 Remainder = Imm;
554 Shift = 32;
555 Imm >>= 32;
556 }
557 }
558
559 // Intermediate operand.
560 unsigned Result = 0;
561
562 // Handle first 32 bits.
563 unsigned Lo = Imm & 0xFFFF;
564 unsigned Hi = (Imm >> 16) & 0xFFFF;
565
566 // Simple value.
567 if (isInt<16>(Imm)) {
568 // Just the Lo bits.
569 ++Result;
570 } else if (Lo) {
571 // Handle the Hi bits and Lo bits.
572 Result += 2;
573 } else {
574 // Just the Hi bits.
575 ++Result;
576 }
577
578 // If no shift, we're done.
579 if (!Shift) return Result;
580
581 // Shift for next step if the upper 32-bits were not zero.
582 if (Imm)
583 ++Result;
584
585 // Add in the last bits as required.
586 if ((Hi = (Remainder >> 16) & 0xFFFF))
587 ++Result;
588 if ((Lo = Remainder & 0xFFFF))
589 ++Result;
590
591 return Result;
592 }
593
Rot64(uint64_t Imm,unsigned R)594 static uint64_t Rot64(uint64_t Imm, unsigned R) {
595 return (Imm << R) | (Imm >> (64 - R));
596 }
597
SelectInt64Count(int64_t Imm)598 static unsigned SelectInt64Count(int64_t Imm) {
599 unsigned Count = SelectInt64CountDirect(Imm);
600 if (Count == 1)
601 return Count;
602
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);
607
608 // See comments in SelectInt64 for an explanation of the logic below.
609 unsigned LS = findLastSet(RImm);
610 if (LS != r-1)
611 continue;
612
613 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
614 uint64_t RImmWithOnes = RImm | OnesMask;
615
616 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
617 Count = std::min(Count, RCount);
618 }
619
620 return Count;
621 }
622
623 // Select a 64-bit constant. For cost-modeling purposes, SelectInt64Count
624 // (above) needs to be kept in sync with this function.
SelectInt64Direct(SelectionDAG * CurDAG,SDLoc dl,int64_t Imm)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.
629 unsigned Shift = 0;
630
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;
635
636 // If the shifted value fits 32 bits.
637 if (isInt<32>(ImmSh)) {
638 // Go with the shifted value.
639 Imm = ImmSh;
640 } else {
641 // Still stuck with a 64 bit value.
642 Remainder = Imm;
643 Shift = 32;
644 Imm >>= 32;
645 }
646 }
647
648 // Intermediate operand.
649 SDNode *Result;
650
651 // Handle first 32 bits.
652 unsigned Lo = Imm & 0xFFFF;
653 unsigned Hi = (Imm >> 16) & 0xFFFF;
654
655 auto getI32Imm = [CurDAG](unsigned Imm) {
656 return CurDAG->getTargetConstant(Imm, MVT::i32);
657 };
658
659 // Simple value.
660 if (isInt<16>(Imm)) {
661 // Just the Lo bits.
662 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
663 } else if (Lo) {
664 // Handle the Hi bits.
665 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
666 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
667 // And Lo bits.
668 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
669 SDValue(Result, 0), getI32Imm(Lo));
670 } else {
671 // Just the Hi bits.
672 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
673 }
674
675 // If no shift, we're done.
676 if (!Shift) return Result;
677
678 // Shift for next step if the upper 32-bits were not zero.
679 if (Imm) {
680 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
681 SDValue(Result, 0),
682 getI32Imm(Shift),
683 getI32Imm(63 - Shift));
684 }
685
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));
690 }
691 if ((Lo = Remainder & 0xFFFF)) {
692 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
693 SDValue(Result, 0), getI32Imm(Lo));
694 }
695
696 return Result;
697 }
698
SelectInt64(SelectionDAG * CurDAG,SDLoc dl,int64_t Imm)699 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) {
700 unsigned Count = SelectInt64CountDirect(Imm);
701 if (Count == 1)
702 return SelectInt64Direct(CurDAG, dl, Imm);
703
704 unsigned RMin = 0;
705
706 int64_t MatImm;
707 unsigned MaskEnd;
708
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) {
713 Count = RCount;
714 RMin = r;
715 MatImm = RImm;
716 MaskEnd = 63;
717 }
718
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.
723
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
728 if (LS != r-1)
729 continue;
730
731 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
732 uint64_t RImmWithOnes = RImm | OnesMask;
733
734 RCount = SelectInt64CountDirect(RImmWithOnes) + 1;
735 if (RCount < Count) {
736 Count = RCount;
737 RMin = r;
738 MatImm = RImmWithOnes;
739 MaskEnd = LS;
740 }
741 }
742
743 if (!RMin)
744 return SelectInt64Direct(CurDAG, dl, Imm);
745
746 auto getI32Imm = [CurDAG](unsigned Imm) {
747 return CurDAG->getTargetConstant(Imm, MVT::i32);
748 };
749
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));
753 }
754
755 // Select a 64-bit constant.
SelectInt64(SelectionDAG * CurDAG,SDNode * N)756 static SDNode *SelectInt64(SelectionDAG *CurDAG, SDNode *N) {
757 SDLoc dl(N);
758
759 // Get 64 bit value.
760 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
761 return SelectInt64(CurDAG, dl, Imm);
762 }
763
764 namespace {
765 class BitPermutationSelector {
766 struct ValueBit {
767 SDValue V;
768
769 // The bit number in the value, using a convention where bit 0 is the
770 // lowest-order bit.
771 unsigned Idx;
772
773 enum Kind {
774 ConstZero,
775 Variable
776 } K;
777
ValueBit__anon7bd595e20411::BitPermutationSelector::ValueBit778 ValueBit(SDValue V, unsigned I, Kind K = Variable)
779 : V(V), Idx(I), K(K) {}
ValueBit__anon7bd595e20411::BitPermutationSelector::ValueBit780 ValueBit(Kind K = Variable)
781 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
782
isZero__anon7bd595e20411::BitPermutationSelector::ValueBit783 bool isZero() const {
784 return K == ConstZero;
785 }
786
hasValue__anon7bd595e20411::BitPermutationSelector::ValueBit787 bool hasValue() const {
788 return K == Variable;
789 }
790
getValue__anon7bd595e20411::BitPermutationSelector::ValueBit791 SDValue getValue() const {
792 assert(hasValue() && "Cannot get the value of a constant bit");
793 return V;
794 }
795
getValueBitIndex__anon7bd595e20411::BitPermutationSelector::ValueBit796 unsigned getValueBitIndex() const {
797 assert(hasValue() && "Cannot get the value bit index of a constant bit");
798 return Idx;
799 }
800 };
801
802 // A bit group has the same underlying value and the same rotate factor.
803 struct BitGroup {
804 SDValue V;
805 unsigned RLAmt;
806 unsigned StartIdx, EndIdx;
807
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).
811 bool Repl32;
812 // Did converting to Repl32 == true change the rotation factor? If it did,
813 // it decreased it by 32.
814 bool Repl32CR;
815 // Was this group coalesced after setting Repl32 to true?
816 bool Repl32Coalesced;
817
BitGroup__anon7bd595e20411::BitPermutationSelector::BitGroup818 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");
823 }
824 };
825
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 {
829 SDValue V;
830 unsigned RLAmt;
831 unsigned NumGroups;
832 unsigned FirstGroupStartIdx;
833 bool Repl32;
834
ValueRotInfo__anon7bd595e20411::BitPermutationSelector::ValueRotInfo835 ValueRotInfo()
836 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
837 Repl32(false) {}
838
839 // For sorting (in reverse order) by NumGroups, and then by
840 // FirstGroupStartIdx.
operator <__anon7bd595e20411::BitPermutationSelector::ValueRotInfo841 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)
846 return true;
847 else if (Repl32 > Other.Repl32)
848 return false;
849 else if (NumGroups > Other.NumGroups)
850 return true;
851 else if (NumGroups < Other.NumGroups)
852 return false;
853 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
854 return true;
855 return false;
856 }
857 };
858
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).
getValueBits(SDValue V,SmallVector<ValueBit,64> & Bits)862 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) {
863 switch (V.getOpcode()) {
864 default: break;
865 case ISD::ROTL:
866 if (isa<ConstantSDNode>(V.getOperand(1))) {
867 unsigned RotAmt = V.getConstantOperandVal(1);
868
869 SmallVector<ValueBit, 64> LHSBits(Bits.size());
870 getValueBits(V.getOperand(0), LHSBits);
871
872 for (unsigned i = 0; i < Bits.size(); ++i)
873 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt];
874
875 return true;
876 }
877 break;
878 case ISD::SHL:
879 if (isa<ConstantSDNode>(V.getOperand(1))) {
880 unsigned ShiftAmt = V.getConstantOperandVal(1);
881
882 SmallVector<ValueBit, 64> LHSBits(Bits.size());
883 getValueBits(V.getOperand(0), LHSBits);
884
885 for (unsigned i = ShiftAmt; i < Bits.size(); ++i)
886 Bits[i] = LHSBits[i - ShiftAmt];
887
888 for (unsigned i = 0; i < ShiftAmt; ++i)
889 Bits[i] = ValueBit(ValueBit::ConstZero);
890
891 return true;
892 }
893 break;
894 case ISD::SRL:
895 if (isa<ConstantSDNode>(V.getOperand(1))) {
896 unsigned ShiftAmt = V.getConstantOperandVal(1);
897
898 SmallVector<ValueBit, 64> LHSBits(Bits.size());
899 getValueBits(V.getOperand(0), LHSBits);
900
901 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i)
902 Bits[i] = LHSBits[i + ShiftAmt];
903
904 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i)
905 Bits[i] = ValueBit(ValueBit::ConstZero);
906
907 return true;
908 }
909 break;
910 case ISD::AND:
911 if (isa<ConstantSDNode>(V.getOperand(1))) {
912 uint64_t Mask = V.getConstantOperandVal(1);
913
914 SmallVector<ValueBit, 64> LHSBits(Bits.size());
915 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits);
916
917 for (unsigned i = 0; i < Bits.size(); ++i)
918 if (((Mask >> i) & 1) == 1)
919 Bits[i] = LHSBits[i];
920 else
921 Bits[i] = ValueBit(ValueBit::ConstZero);
922
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).
927 return LHSTrivial;
928 }
929 break;
930 case ISD::OR: {
931 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size());
932 getValueBits(V.getOperand(0), LHSBits);
933 getValueBits(V.getOperand(1), RHSBits);
934
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];
941 else {
942 AllDisjoint = false;
943 break;
944 }
945
946 if (!AllDisjoint)
947 break;
948
949 return true;
950 }
951 }
952
953 for (unsigned i = 0; i < Bits.size(); ++i)
954 Bits[i] = ValueBit(V, i);
955
956 return false;
957 }
958
959 // For each value (except the constant ones), compute the left-rotate amount
960 // to get it from its original to final position.
computeRotationAmounts()961 void computeRotationAmounts() {
962 HasZeros = false;
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();
967 if (i >= VBI)
968 RLAmt[i] = i - VBI;
969 else
970 RLAmt[i] = Bits.size() - (VBI - i);
971 } else if (Bits[i].isZero()) {
972 HasZeros = true;
973 RLAmt[i] = UINT32_MAX;
974 } else {
975 llvm_unreachable("Unknown value bit type");
976 }
977 }
978
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.
collectBitGroups(bool LateMask)982 void collectBitGroups(bool LateMask) {
983 BitGroups.clear();
984
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;
998 }
999
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)
1003 continue;
1004
1005 if (LastValue.getNode())
1006 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1007 i-1));
1008 LastRLAmt = ThisRLAmt;
1009 LastValue = ThisValue;
1010 LastGroupStartIdx = i;
1011 }
1012 if (LastValue.getNode())
1013 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1014 Bits.size()-1));
1015
1016 if (BitGroups.empty())
1017 return;
1018
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());
1031 }
1032 }
1033 }
1034
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).
collectValueRotInfo()1038 void collectValueRotInfo() {
1039 ValueRots.clear();
1040
1041 for (auto &BG : BitGroups) {
1042 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1043 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1044 VRI.V = BG.V;
1045 VRI.RLAmt = BG.RLAmt;
1046 VRI.Repl32 = BG.Repl32;
1047 VRI.NumGroups += 1;
1048 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1049 }
1050
1051 // Now that we've collected the various ValueRotInfo instances, we need to
1052 // sort them.
1053 ValueRotsVec.clear();
1054 for (auto &I : ValueRots) {
1055 ValueRotsVec.push_back(I.second);
1056 }
1057 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1058 }
1059
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
1067 // converted.
assignRepl32BitGroups()1068 void assignRepl32BitGroups() {
1069 // If we have bits like this:
1070 //
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 |
1074 //
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
1077 // of 8.
1078
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())
1083 continue;
1084 if (Bits[i].getValueBitIndex() >= 32)
1085 return false;
1086 }
1087 } else {
1088 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1089 if (!Bits[i].hasValue())
1090 continue;
1091 if (Bits[i].getValueBitIndex() >= 32)
1092 return false;
1093 }
1094 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1095 if (!Bits[i].hasValue())
1096 continue;
1097 if (Bits[i].getValueBitIndex() >= 32)
1098 return false;
1099 }
1100 }
1101
1102 return true;
1103 };
1104
1105 for (auto &BG : BitGroups) {
1106 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1107 if (IsAllLow32(BG)) {
1108 if (BG.RLAmt >= 32) {
1109 BG.RLAmt -= 32;
1110 BG.Repl32CR = true;
1111 }
1112
1113 BG.Repl32 = true;
1114
1115 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1116 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1117 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1118 }
1119 }
1120 }
1121
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) {
1130
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");
1136
1137 IP->EndIdx = I->EndIdx;
1138 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1139 IP->Repl32Coalesced = true;
1140 I = BitGroups.erase(I);
1141 continue;
1142 } else {
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();
1153
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 &&
1157 IsAllLow32(*I)) {
1158
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");
1165
1166 if (IP == IN) {
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).
1170 IP->StartIdx = 31;
1171 IP->EndIdx = 30;
1172 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1173 IP->Repl32Coalesced = true;
1174 I = BitGroups.erase(I);
1175 } else {
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());
1184 }
1185
1186 // This must be the last group in the vector (and we might have
1187 // just invalidated the iterator above), so break here.
1188 break;
1189 }
1190 }
1191 }
1192
1193 ++I;
1194 }
1195 }
1196
getI32Imm(unsigned Imm)1197 SDValue getI32Imm(unsigned Imm) {
1198 return CurDAG->getTargetConstant(Imm, MVT::i32);
1199 }
1200
getZerosMask()1201 uint64_t getZerosMask() {
1202 uint64_t Mask = 0;
1203 for (unsigned i = 0; i < Bits.size(); ++i) {
1204 if (Bits[i].hasValue())
1205 continue;
1206 Mask |= (UINT64_C(1) << i);
1207 }
1208
1209 return ~Mask;
1210 }
1211
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.
SelectAndParts32(SDLoc dl,SDValue & Res,unsigned * InstCnt)1215 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1216 if (BPermRewriterNoMasking)
1217 return;
1218
1219 for (ValueRotInfo &VRI : ValueRotsVec) {
1220 unsigned Mask = 0;
1221 for (unsigned i = 0; i < Bits.size(); ++i) {
1222 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1223 continue;
1224 if (RLAmt[i] != VRI.RLAmt)
1225 continue;
1226 Mask |= (1u << i);
1227 }
1228
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;
1234
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
1241 // to schedule.
1242
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.
1248
1249 unsigned NumAndInsts = (unsigned) NeedsRotate +
1250 (unsigned) (ANDIMask != 0) +
1251 (unsigned) (ANDISMask != 0) +
1252 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1253 (unsigned) (bool) Res;
1254
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");
1259
1260 if (NumAndInsts >= VRI.NumGroups)
1261 continue;
1262
1263 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1264
1265 if (InstCnt) *InstCnt += NumAndInsts;
1266
1267 SDValue VRot;
1268 if (VRI.RLAmt) {
1269 SDValue Ops[] =
1270 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1271 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1272 Ops), 0);
1273 } else {
1274 VRot = VRI.V;
1275 }
1276
1277 SDValue ANDIVal, ANDISVal;
1278 if (ANDIMask != 0)
1279 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1280 VRot, getI32Imm(ANDIMask)), 0);
1281 if (ANDISMask != 0)
1282 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1283 VRot, getI32Imm(ANDISMask)), 0);
1284
1285 SDValue TotalVal;
1286 if (!ANDIVal)
1287 TotalVal = ANDISVal;
1288 else if (!ANDISVal)
1289 TotalVal = ANDIVal;
1290 else
1291 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1292 ANDIVal, ANDISVal), 0);
1293
1294 if (!Res)
1295 Res = TotalVal;
1296 else
1297 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1298 Res, TotalVal), 0);
1299
1300 // Now, remove all groups with this underlying value and rotation
1301 // factor.
1302 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1303 if (I->V == VRI.V && I->RLAmt == VRI.RLAmt)
1304 I = BitGroups.erase(I);
1305 else
1306 ++I;
1307 }
1308 }
1309 }
1310
1311 // Instruction selection for the 32-bit case.
Select32(SDNode * N,bool LateMask,unsigned * InstCnt)1312 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1313 SDLoc dl(N);
1314 SDValue Res;
1315
1316 if (InstCnt) *InstCnt = 0;
1317
1318 // Take care of cases that should use andi/andis first.
1319 SelectAndParts32(dl, Res, InstCnt);
1320
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];
1326 if (VRI.RLAmt) {
1327 if (InstCnt) *InstCnt += 1;
1328 SDValue Ops[] =
1329 { VRI.V, getI32Imm(VRI.RLAmt), getI32Imm(0), getI32Imm(31) };
1330 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1331 } else {
1332 Res = VRI.V;
1333 }
1334
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);
1339 else
1340 ++I;
1341 }
1342 }
1343
1344 if (InstCnt) *InstCnt += BitGroups.size();
1345
1346 // Insert the other groups (one at a time).
1347 for (auto &BG : BitGroups) {
1348 if (!Res) {
1349 SDValue Ops[] =
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);
1353 } else {
1354 SDValue Ops[] =
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);
1358 }
1359 }
1360
1361 if (LateMask) {
1362 unsigned Mask = (unsigned) getZerosMask();
1363
1364 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1365 assert((ANDIMask != 0 || ANDISMask != 0) &&
1366 "No set bits in zeros mask?");
1367
1368 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1369 (unsigned) (ANDISMask != 0) +
1370 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1371
1372 SDValue ANDIVal, ANDISVal;
1373 if (ANDIMask != 0)
1374 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1375 Res, getI32Imm(ANDIMask)), 0);
1376 if (ANDISMask != 0)
1377 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1378 Res, getI32Imm(ANDISMask)), 0);
1379
1380 if (!ANDIVal)
1381 Res = ANDISVal;
1382 else if (!ANDISVal)
1383 Res = ANDIVal;
1384 else
1385 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1386 ANDIVal, ANDISVal), 0);
1387 }
1388
1389 return Res.getNode();
1390 }
1391
SelectRotMask64Count(unsigned RLAmt,bool Repl32,unsigned MaskStart,unsigned MaskEnd,bool IsIns)1392 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1393 unsigned MaskStart, unsigned MaskEnd,
1394 bool IsIns) {
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;
1399
1400 if (Repl32)
1401 return 1;
1402
1403 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1404 InstMaskEnd == 63 - RLAmt)
1405 return 1;
1406
1407 return 2;
1408 }
1409
1410 // For 64-bit values, not all combinations of rotates and masks are
1411 // available. Produce one if it is available.
SelectRotMask64(SDValue V,SDLoc dl,unsigned RLAmt,bool Repl32,unsigned MaskStart,unsigned MaskEnd,unsigned * InstCnt=nullptr)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;
1419
1420 if (InstCnt) *InstCnt += 1;
1421
1422 if (Repl32) {
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");
1428 SDValue Ops[] =
1429 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1430 getI32Imm(InstMaskEnd - 32) };
1431 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1432 Ops), 0);
1433 }
1434
1435 if (InstMaskEnd == 63) {
1436 SDValue Ops[] =
1437 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1438 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1439 }
1440
1441 if (InstMaskStart == 0) {
1442 SDValue Ops[] =
1443 { V, getI32Imm(RLAmt), getI32Imm(InstMaskEnd) };
1444 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1445 }
1446
1447 if (InstMaskEnd == 63 - RLAmt) {
1448 SDValue Ops[] =
1449 { V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1450 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1451 }
1452
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
1458 // desired result.
1459 if (InstCnt) *InstCnt += 1;
1460
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
1464 // is RLAmt.
1465 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1466 if (RLAmt1)
1467 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1468 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1469 }
1470
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.
SelectRotMaskIns64(SDValue Base,SDValue V,SDLoc dl,unsigned RLAmt,bool Repl32,unsigned MaskStart,unsigned MaskEnd,unsigned * InstCnt=nullptr)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;
1480
1481 if (InstCnt) *InstCnt += 1;
1482
1483 if (Repl32) {
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");
1489 SDValue Ops[] =
1490 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart - 32),
1491 getI32Imm(InstMaskEnd - 32) };
1492 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1493 Ops), 0);
1494 }
1495
1496 if (InstMaskEnd == 63 - RLAmt) {
1497 SDValue Ops[] =
1498 { Base, V, getI32Imm(RLAmt), getI32Imm(InstMaskStart) };
1499 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1500 }
1501
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
1507 // desired result.
1508 if (InstCnt) *InstCnt += 1;
1509
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
1513 // is RLAmt.
1514 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1515 if (RLAmt1)
1516 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1517 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1518 }
1519
SelectAndParts64(SDLoc dl,SDValue & Res,unsigned * InstCnt)1520 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) {
1521 if (BPermRewriterNoMasking)
1522 return;
1523
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.
1532
1533 for (ValueRotInfo &VRI : ValueRotsVec) {
1534 uint64_t Mask = 0;
1535
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) {
1542 if (VRI.V != BG.V)
1543 return false;
1544
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) {
1549 if (BG.Repl32CR)
1550 EffRLAmt += 32;
1551 } else {
1552 return false;
1553 }
1554 } else if (VRI.Repl32 != BG.Repl32) {
1555 return false;
1556 }
1557
1558 if (VRI.RLAmt != EffRLAmt)
1559 return false;
1560
1561 return true;
1562 };
1563
1564 for (auto &BG : BitGroups) {
1565 if (!MatchingBG(BG))
1566 continue;
1567
1568 if (BG.StartIdx <= BG.EndIdx) {
1569 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1570 Mask |= (UINT64_C(1) << i);
1571 } else {
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);
1576 }
1577 }
1578
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;
1586
1587 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1588
1589 unsigned NumAndInsts = (unsigned) NeedsRotate +
1590 (unsigned) (bool) Res;
1591 if (Use32BitInsts)
1592 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1593 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1594 else
1595 NumAndInsts += SelectInt64Count(Mask) + /* and */ 1;
1596
1597 unsigned NumRLInsts = 0;
1598 bool FirstBG = true;
1599 for (auto &BG : BitGroups) {
1600 if (!MatchingBG(BG))
1601 continue;
1602 NumRLInsts +=
1603 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1604 !FirstBG);
1605 FirstBG = false;
1606 }
1607
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");
1612
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)
1618 continue;
1619 if (Use32BitInsts && NumAndInsts == NumRLInsts)
1620 continue;
1621
1622 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1623
1624 if (InstCnt) *InstCnt += NumAndInsts;
1625
1626 SDValue VRot;
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);
1634 else
1635 VRot = VRI.V;
1636
1637 SDValue TotalVal;
1638 if (Use32BitInsts) {
1639 assert((ANDIMask != 0 || ANDISMask != 0) &&
1640 "No set bits in mask when using 32-bit ands for 64-bit value");
1641
1642 SDValue ANDIVal, ANDISVal;
1643 if (ANDIMask != 0)
1644 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1645 VRot, getI32Imm(ANDIMask)), 0);
1646 if (ANDISMask != 0)
1647 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1648 VRot, getI32Imm(ANDISMask)), 0);
1649
1650 if (!ANDIVal)
1651 TotalVal = ANDISVal;
1652 else if (!ANDISVal)
1653 TotalVal = ANDIVal;
1654 else
1655 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1656 ANDIVal, ANDISVal), 0);
1657 } else {
1658 TotalVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1659 TotalVal =
1660 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1661 VRot, TotalVal), 0);
1662 }
1663
1664 if (!Res)
1665 Res = TotalVal;
1666 else
1667 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1668 Res, TotalVal), 0);
1669
1670 // Now, remove all groups with this underlying value and rotation
1671 // factor.
1672 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1673 if (MatchingBG(*I))
1674 I = BitGroups.erase(I);
1675 else
1676 ++I;
1677 }
1678 }
1679 }
1680
1681 // Instruction selection for the 64-bit case.
Select64(SDNode * N,bool LateMask,unsigned * InstCnt)1682 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1683 SDLoc dl(N);
1684 SDValue Res;
1685
1686 if (InstCnt) *InstCnt = 0;
1687
1688 // Take care of cases that should use andi/andis first.
1689 SelectAndParts64(dl, Res, InstCnt);
1690
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)
1703 MaxGroupsIdx = i;
1704 break;
1705 }
1706 }
1707
1708 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1709 bool NeedsRotate = false;
1710 if (VRI.RLAmt) {
1711 NeedsRotate = true;
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)
1716 continue;
1717
1718 // We don't need a rotate if the bit group is confined to the lower
1719 // 32 bits.
1720 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1721 continue;
1722
1723 NeedsRotate = true;
1724 break;
1725 }
1726 }
1727
1728 if (NeedsRotate)
1729 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1730 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1731 InstCnt);
1732 else
1733 Res = VRI.V;
1734
1735 // Now, remove all groups with this underlying value and rotation factor.
1736 if (Res)
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);
1740 else
1741 ++I;
1742 }
1743 }
1744
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).
1747 if (!Res)
1748 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1749 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1750 false) <
1751 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1752 true)) {
1753 if (I != BitGroups.begin()) {
1754 BitGroup BG = *I;
1755 BitGroups.erase(I);
1756 BitGroups.insert(BitGroups.begin(), BG);
1757 }
1758
1759 break;
1760 }
1761 }
1762
1763 // Insert the other groups (one at a time).
1764 for (auto &BG : BitGroups) {
1765 if (!Res)
1766 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1767 BG.EndIdx, InstCnt);
1768 else
1769 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1770 BG.StartIdx, BG.EndIdx, InstCnt);
1771 }
1772
1773 if (LateMask) {
1774 uint64_t Mask = getZerosMask();
1775
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;
1783
1784 if (Use32BitInsts) {
1785 assert((ANDIMask != 0 || ANDISMask != 0) &&
1786 "No set bits in mask when using 32-bit ands for 64-bit value");
1787
1788 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1789 (unsigned) (ANDISMask != 0) +
1790 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1791
1792 SDValue ANDIVal, ANDISVal;
1793 if (ANDIMask != 0)
1794 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1795 Res, getI32Imm(ANDIMask)), 0);
1796 if (ANDISMask != 0)
1797 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1798 Res, getI32Imm(ANDISMask)), 0);
1799
1800 if (!ANDIVal)
1801 Res = ANDISVal;
1802 else if (!ANDISVal)
1803 Res = ANDIVal;
1804 else
1805 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1806 ANDIVal, ANDISVal), 0);
1807 } else {
1808 if (InstCnt) *InstCnt += SelectInt64Count(Mask) + /* and */ 1;
1809
1810 SDValue MaskVal = SDValue(SelectInt64(CurDAG, dl, Mask), 0);
1811 Res =
1812 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1813 Res, MaskVal), 0);
1814 }
1815 }
1816
1817 return Res.getNode();
1818 }
1819
Select(SDNode * N,bool LateMask,unsigned * InstCnt=nullptr)1820 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1821 // Fill in BitGroups.
1822 collectBitGroups(LateMask);
1823 if (BitGroups.empty())
1824 return nullptr;
1825
1826 // For 64-bit values, figure out when we can use 32-bit instructions.
1827 if (Bits.size() == 64)
1828 assignRepl32BitGroups();
1829
1830 // Fill in ValueRotsVec.
1831 collectValueRotInfo();
1832
1833 if (Bits.size() == 32) {
1834 return Select32(N, LateMask, InstCnt);
1835 } else {
1836 assert(Bits.size() == 64 && "Not 64 bits here?");
1837 return Select64(N, LateMask, InstCnt);
1838 }
1839
1840 return nullptr;
1841 }
1842
1843 SmallVector<ValueBit, 64> Bits;
1844
1845 bool HasZeros;
1846 SmallVector<unsigned, 64> RLAmt;
1847
1848 SmallVector<BitGroup, 16> BitGroups;
1849
1850 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1851 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1852
1853 SelectionDAG *CurDAG;
1854
1855 public:
BitPermutationSelector(SelectionDAG * DAG)1856 BitPermutationSelector(SelectionDAG *DAG)
1857 : CurDAG(DAG) {}
1858
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).
Select(SDNode * N)1862 SDNode *Select(SDNode *N) {
1863 Bits.resize(N->getValueType(0).getSizeInBits());
1864 if (!getValueBits(SDValue(N, 0), Bits))
1865 return nullptr;
1866
1867 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1868 " selection for: ");
1869 DEBUG(N->dump(CurDAG));
1870
1871 // Fill it RLAmt and set HasZeros.
1872 computeRotationAmounts();
1873
1874 if (!HasZeros)
1875 return Select(N, false);
1876
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.
1884
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");
1889
1890 DEBUG(dbgs() << "\tLate masking:\n");
1891 SDNode *RNLM = Select(N, true, &InstCntLateMask);
1892 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1893 " instructions\n");
1894
1895 if (InstCnt <= InstCntLateMask) {
1896 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1897 return RN;
1898 }
1899
1900 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1901 return RNLM;
1902 }
1903 };
1904 } // anonymous namespace
1905
SelectBitPermutation(SDNode * N)1906 SDNode *PPCDAGToDAGISel::SelectBitPermutation(SDNode *N) {
1907 if (N->getValueType(0) != MVT::i32 &&
1908 N->getValueType(0) != MVT::i64)
1909 return nullptr;
1910
1911 if (!UseBitPermRewriter)
1912 return nullptr;
1913
1914 switch (N->getOpcode()) {
1915 default: break;
1916 case ISD::ROTL:
1917 case ISD::SHL:
1918 case ISD::SRL:
1919 case ISD::AND:
1920 case ISD::OR: {
1921 BitPermutationSelector BPS(CurDAG);
1922 return BPS.Select(N);
1923 }
1924 }
1925
1926 return nullptr;
1927 }
1928
1929 /// SelectCC - Select a comparison of the specified values with the specified
1930 /// condition code, returning the CR# of the expression.
SelectCC(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDLoc dl)1931 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
1932 ISD::CondCode CC, SDLoc dl) {
1933 // Always select the LHS.
1934 unsigned Opc;
1935
1936 if (LHS.getValueType() == MVT::i32) {
1937 unsigned Imm;
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);
1948
1949 // For non-equality comparisons, the default code would materialize the
1950 // constant, then compare against it, like this:
1951 // lis r2, 4660
1952 // ori r2, r2, 22136
1953 // cmpw cr0, r3, r2
1954 // Since we are just comparing for equality, we can emit this instead:
1955 // xoris r0,r3,0x1234
1956 // cmplwi cr0,r0,0x5678
1957 // beq cr0,L6
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);
1962 }
1963 Opc = PPC::CMPLW;
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);
1968 Opc = PPC::CMPLW;
1969 } else {
1970 short SImm;
1971 if (isIntS16Immediate(RHS, SImm))
1972 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
1973 getI32Imm((int)SImm & 0xFFFF)),
1974 0);
1975 Opc = PPC::CMPW;
1976 }
1977 } else if (LHS.getValueType() == MVT::i64) {
1978 uint64_t Imm;
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.
1986 if (isInt<16>(Imm))
1987 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
1988 getI32Imm(Imm & 0xFFFF)), 0);
1989
1990 // For non-equality comparisons, the default code would materialize the
1991 // constant, then compare against it, like this:
1992 // lis r2, 4660
1993 // ori r2, r2, 22136
1994 // cmpd cr0, r3, r2
1995 // Since we are just comparing for equality, we can emit this instead:
1996 // xoris r0,r3,0x1234
1997 // cmpldi cr0,r0,0x5678
1998 // beq cr0,L6
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);
2004 }
2005 }
2006 Opc = PPC::CMPLD;
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);
2011 Opc = PPC::CMPLD;
2012 } else {
2013 short SImm;
2014 if (isIntS16Immediate(RHS, SImm))
2015 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2016 getI64Imm(SImm & 0xFFFF)),
2017 0);
2018 Opc = PPC::CMPD;
2019 }
2020 } else if (LHS.getValueType() == MVT::f32) {
2021 Opc = PPC::FCMPUS;
2022 } else {
2023 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2024 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2025 }
2026 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2027 }
2028
getPredicateForSetCC(ISD::CondCode CC)2029 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2030 switch (CC) {
2031 case ISD::SETUEQ:
2032 case ISD::SETONE:
2033 case ISD::SETOLE:
2034 case ISD::SETOGE:
2035 llvm_unreachable("Should be lowered by legalize!");
2036 default: llvm_unreachable("Unknown condition!");
2037 case ISD::SETOEQ:
2038 case ISD::SETEQ: return PPC::PRED_EQ;
2039 case ISD::SETUNE:
2040 case ISD::SETNE: return PPC::PRED_NE;
2041 case ISD::SETOLT:
2042 case ISD::SETLT: return PPC::PRED_LT;
2043 case ISD::SETULE:
2044 case ISD::SETLE: return PPC::PRED_LE;
2045 case ISD::SETOGT:
2046 case ISD::SETGT: return PPC::PRED_GT;
2047 case ISD::SETUGE:
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;
2054 }
2055 }
2056
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.
getCRIdxForSetCC(ISD::CondCode CC,bool & Invert)2060 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2061 Invert = false;
2062 switch (CC) {
2063 default: llvm_unreachable("Unknown condition!");
2064 case ISD::SETOLT:
2065 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2066 case ISD::SETOGT:
2067 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2068 case ISD::SETOEQ:
2069 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2070 case ISD::SETUO: return 3; // Bit #3 = SETUO
2071 case ISD::SETUGE:
2072 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2073 case ISD::SETULE:
2074 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2075 case ISD::SETUNE:
2076 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2077 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2078 case ISD::SETUEQ:
2079 case ISD::SETOGE:
2080 case ISD::SETOLE:
2081 case ISD::SETONE:
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;
2086 }
2087 }
2088
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).
getVCmpInst(MVT VecVT,ISD::CondCode CC,bool HasVSX,bool & Swap,bool & Negate)2092 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2093 bool HasVSX, bool &Swap, bool &Negate) {
2094 Swap = false;
2095 Negate = false;
2096
2097 if (VecVT.isFloatingPoint()) {
2098 /* Handle some cases by swapping input operands. */
2099 switch (CC) {
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;
2106 default: break;
2107 }
2108 /* Handle some cases by negating the result. */
2109 switch (CC) {
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;
2114 default: break;
2115 }
2116 /* We have instructions implementing the remaining cases. */
2117 switch (CC) {
2118 case ISD::SETEQ:
2119 case ISD::SETOEQ:
2120 if (VecVT == MVT::v4f32)
2121 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2122 else if (VecVT == MVT::v2f64)
2123 return PPC::XVCMPEQDP;
2124 break;
2125 case ISD::SETGT:
2126 case ISD::SETOGT:
2127 if (VecVT == MVT::v4f32)
2128 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2129 else if (VecVT == MVT::v2f64)
2130 return PPC::XVCMPGTDP;
2131 break;
2132 case ISD::SETGE:
2133 case ISD::SETOGE:
2134 if (VecVT == MVT::v4f32)
2135 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2136 else if (VecVT == MVT::v2f64)
2137 return PPC::XVCMPGEDP;
2138 break;
2139 default:
2140 break;
2141 }
2142 llvm_unreachable("Invalid floating-point vector compare condition");
2143 } else {
2144 /* Handle some cases by swapping input operands. */
2145 switch (CC) {
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;
2150 default: break;
2151 }
2152 /* Handle some cases by negating the result. */
2153 switch (CC) {
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;
2158 default: break;
2159 }
2160 /* We have instructions implementing the remaining cases. */
2161 switch (CC) {
2162 case ISD::SETEQ:
2163 case ISD::SETUEQ:
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;
2172 break;
2173 case ISD::SETGT:
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;
2182 break;
2183 case ISD::SETUGT:
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;
2192 break;
2193 default:
2194 break;
2195 }
2196 llvm_unreachable("Invalid integer vector compare condition");
2197 }
2198 }
2199
SelectSETCC(SDNode * N)2200 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
2201 SDLoc dl(N);
2202 unsigned Imm;
2203 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2204 EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
2205 bool isPPC64 = (PtrVT == MVT::i64);
2206
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.
2211 // setcc op, 0
2212 if (Imm == 0) {
2213 SDValue Op = N->getOperand(0);
2214 switch (CC) {
2215 default: break;
2216 case ISD::SETEQ: {
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);
2220 }
2221 case ISD::SETNE: {
2222 if (isPPC64) break;
2223 SDValue AD =
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,
2227 AD.getValue(1));
2228 }
2229 case ISD::SETLT: {
2230 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2231 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2232 }
2233 case ISD::SETGT: {
2234 SDValue T =
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);
2239 }
2240 }
2241 } else if (Imm == ~0U) { // setcc op, -1
2242 SDValue Op = N->getOperand(0);
2243 switch (CC) {
2244 default: break;
2245 case ISD::SETEQ:
2246 if (isPPC64) break;
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,
2251 MVT::i32,
2252 getI32Imm(0)), 0),
2253 Op.getValue(1));
2254 case ISD::SETNE: {
2255 if (isPPC64) break;
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));
2261 }
2262 case ISD::SETLT: {
2263 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2264 getI32Imm(1)), 0);
2265 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2266 Op), 0);
2267 SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2268 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2269 }
2270 case ISD::SETGT: {
2271 SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
2272 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2273 0);
2274 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
2275 getI32Imm(1));
2276 }
2277 }
2278 }
2279 }
2280
2281 SDValue LHS = N->getOperand(0);
2282 SDValue RHS = N->getOperand(1);
2283
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())
2288 return nullptr;
2289
2290 EVT VecVT = LHS.getValueType();
2291 bool Swap, Negate;
2292 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2293 PPCSubTarget->hasVSX(), Swap, Negate);
2294 if (Swap)
2295 std::swap(LHS, RHS);
2296
2297 if (Negate) {
2298 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
2299 return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
2300 PPC::VNOR,
2301 VecVT, VCmp, VCmp);
2302 }
2303
2304 return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
2305 }
2306
2307 if (PPCSubTarget->useCRBits())
2308 return nullptr;
2309
2310 bool Inv;
2311 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2312 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2313 SDValue IntCR;
2314
2315 // Force the ccreg into CR7.
2316 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2317
2318 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2319 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2320 InFlag).getValue(1);
2321
2322 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2323 CCReg), 0);
2324
2325 SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
2326 getI32Imm(31), getI32Imm(31) };
2327 if (!Inv)
2328 return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2329
2330 // Get the specified bit.
2331 SDValue Tmp =
2332 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2333 return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
2334 }
2335
transferMemOperands(SDNode * N,SDNode * Result)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);
2341 return Result;
2342 }
2343
2344
2345 // Select - Convert the specified operand from a target-independent to a
2346 // target-specific node if it hasn't already been changed.
Select(SDNode * N)2347 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
2348 SDLoc dl(N);
2349 if (N->isMachineOpcode()) {
2350 N->setNodeId(-1);
2351 return nullptr; // Already selected.
2352 }
2353
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");
2360
2361 // Try matching complex bit permutations before doing anything else.
2362 if (SDNode *NN = SelectBitPermutation(N))
2363 return NN;
2364
2365 switch (N->getOpcode()) {
2366 default: break;
2367
2368 case ISD::Constant: {
2369 if (N->getValueType(0) == MVT::i64)
2370 return SelectInt64(CurDAG, N);
2371 break;
2372 }
2373
2374 case ISD::SETCC: {
2375 SDNode *SN = SelectSETCC(N);
2376 if (SN)
2377 return SN;
2378 break;
2379 }
2380 case PPCISD::GlobalBaseReg:
2381 return getGlobalBaseReg();
2382
2383 case ISD::FrameIndex:
2384 return getFrameIndex(N, N);
2385
2386 case PPCISD::MFOCRF: {
2387 SDValue InFlag = N->getOperand(1);
2388 return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2389 N->getOperand(0), InFlag);
2390 }
2391
2392 case PPCISD::READ_TIME_BASE: {
2393 return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2394 MVT::Other, N->getOperand(0));
2395 }
2396
2397 case PPCISD::SRA_ADDZE: {
2398 SDValue N0 = N->getOperand(0);
2399 SDValue ShiftAmt =
2400 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2401 getConstantIntValue(), N->getValueType(0));
2402 if (N->getValueType(0) == MVT::i64) {
2403 SDNode *Op =
2404 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2405 N0, ShiftAmt);
2406 return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
2407 SDValue(Op, 0), SDValue(Op, 1));
2408 } else {
2409 assert(N->getValueType(0) == MVT::i32 &&
2410 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2411 SDNode *Op =
2412 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2413 N0, ShiftAmt);
2414 return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2415 SDValue(Op, 0), SDValue(Op, 1));
2416 }
2417 }
2418
2419 case ISD::LOAD: {
2420 // Handle preincrement loads.
2421 LoadSDNode *LD = cast<LoadSDNode>(N);
2422 EVT LoadedVT = LD->getMemoryVT();
2423
2424 // Normal loads are handled by code generated from the .td file.
2425 if (LD->getAddressingMode() != ISD::PRE_INC)
2426 break;
2427
2428 SDValue Offset = LD->getOffset();
2429 if (Offset.getOpcode() == ISD::TargetConstant ||
2430 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2431
2432 unsigned Opcode;
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;
2443 case MVT::i1:
2444 case MVT::i8: Opcode = PPC::LBZU; break;
2445 }
2446 } else {
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;
2454 case MVT::i1:
2455 case MVT::i8: Opcode = PPC::LBZU8; break;
2456 }
2457 }
2458
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(),
2465 MVT::Other, Ops));
2466 } else {
2467 unsigned Opcode;
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;
2480 case MVT::i1:
2481 case MVT::i8: Opcode = PPC::LBZUX; break;
2482 }
2483 } else {
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;
2492 case MVT::i1:
2493 case MVT::i8: Opcode = PPC::LBZUX8; break;
2494 }
2495 }
2496
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(),
2503 MVT::Other, Ops));
2504 }
2505 }
2506
2507 case ISD::AND: {
2508 unsigned Imm, Imm2, SH, MB, ME;
2509 uint64_t Imm64;
2510
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);
2518 }
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);
2527 }
2528 // If this is a 64-bit zero-extension mask, emit rldicl.
2529 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2530 isMask_64(Imm64)) {
2531 SDValue Val = N->getOperand(0);
2532 MB = 64 - countTrailingOnes(Imm64);
2533 SH = 0;
2534
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
2539 // by the shift.
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);
2544 SH = 64 - Imm;
2545 }
2546
2547 SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
2548 return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2549 }
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));
2553 return nullptr;
2554 }
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)) {
2560 unsigned MB, ME;
2561 Imm = ~(Imm^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);
2567 }
2568 }
2569
2570 // Other cases are autogenerated.
2571 break;
2572 }
2573 case ISD::OR: {
2574 if (N->getValueType(0) == MVT::i32)
2575 if (SDNode *I = SelectBitfieldInsert(N))
2576 return I;
2577
2578 short Imm;
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);
2583
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);
2588 }
2589
2590 // Other cases are autogenerated.
2591 break;
2592 }
2593 case ISD::ADD: {
2594 short Imm;
2595 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2596 isIntS16Immediate(N->getOperand(1), Imm))
2597 return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2598
2599 break;
2600 }
2601 case ISD::SHL: {
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);
2608 }
2609
2610 // Other cases are autogenerated.
2611 break;
2612 }
2613 case ISD::SRL: {
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);
2620 }
2621
2622 // Other cases are autogenerated.
2623 break;
2624 }
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: {
2628 if (!ANDIGlueBug)
2629 break;
2630
2631 EVT InVT = N->getOperand(0).getValueType();
2632 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2633 "Invalid input type for ANDIo_1_EQ_BIT");
2634
2635 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2636 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2637 N->getOperand(0),
2638 CurDAG->getTargetConstant(1, InVT)), 0);
2639 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2640 SDValue SRIdxVal =
2641 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2642 PPC::sub_eq : PPC::sub_gt, MVT::i32);
2643
2644 return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
2645 CR0Reg, SRIdxVal,
2646 SDValue(AndI.getNode(), 1) /* glue */);
2647 }
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);
2652
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)
2656 break;
2657
2658 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2659 if (!isPPC64)
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) {
2667 SDNode *Tmp =
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),
2672 SDValue(Tmp, 1));
2673 }
2674
2675 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2676
2677 if (N->getValueType(0) == MVT::i1) {
2678 // An i1 select is: (c & t) | (!c & f).
2679 bool Inv;
2680 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2681
2682 unsigned SRI;
2683 switch (Idx) {
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;
2689 }
2690
2691 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2692
2693 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2694 CCBit, CCBit), 0);
2695 SDValue C = Inv ? NotCCBit : CCBit,
2696 NotC = Inv ? CCBit : NotCCBit;
2697
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);
2702
2703 return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2704 }
2705
2706 unsigned BROpc = getPredicateForSetCC(CC);
2707
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;
2718 else
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;
2729 else
2730 SelectCCOp = PPC::SELECT_CC_VRRC;
2731
2732 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2733 getI32Imm(BROpc) };
2734 return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2735 }
2736 case ISD::VSELECT:
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);
2740 }
2741
2742 break;
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);
2747
2748 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2749 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2750 unsigned DM[2];
2751
2752 for (int i = 0; i < 2; ++i)
2753 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2754 DM[i] = 0;
2755 else
2756 DM[i] = 1;
2757
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];
2763 DM[0] = 1 - DM[1];
2764 DM[1] = 1 - tmp;
2765 }
2766
2767 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
2768
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;
2774
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);
2781 }
2782 }
2783
2784 SDValue Ops[] = { Op1, Op2, DMV };
2785 return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2786 }
2787
2788 break;
2789 case PPCISD::BDNZ:
2790 case PPCISD::BDZ: {
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),
2796 MVT::Other, Ops);
2797 }
2798 case PPCISD::COND_BRANCH: {
2799 // Op #0 is the Chain.
2800 // Op #1 is the PPC::PRED_* number.
2801 // Op #2 is the CR#
2802 // Op #3 is the Dest MBB
2803 // Op #4 is the Flag.
2804 // Prevent PPC::PRED_* from being selected into LI.
2805 SDValue Pred =
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);
2810 }
2811 case ISD::BR_CC: {
2812 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2813 unsigned PCC = getPredicateForSetCC(CC);
2814
2815 if (N->getOperand(2).getValueType() == MVT::i1) {
2816 unsigned Opc;
2817 bool Swap;
2818 switch (PCC) {
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;
2826 }
2827
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));
2833 }
2834
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);
2839 }
2840 case ISD::BRIND: {
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,
2847 Chain), 0);
2848 return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
2849 }
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)));
2857 }
2858
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)
2864 break;
2865
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,
2876 TOCbase, GA);
2877
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)));
2882
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)));
2891 }
2892
2893 return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
2894 SDValue(Tmp, 0), GA);
2895 }
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);
2901 }
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!");
2908
2909 int Elt = N->getConstantOperandVal(0);
2910 int EltSize = N->getConstantOperandVal(1);
2911 unsigned Opc1, Opc2, Opc3;
2912 EVT VT;
2913
2914 if (EltSize == 1) {
2915 Opc1 = PPC::VSPLTISB;
2916 Opc2 = PPC::VADDUBM;
2917 Opc3 = PPC::VSUBUBM;
2918 VT = MVT::v16i8;
2919 } else if (EltSize == 2) {
2920 Opc1 = PPC::VSPLTISH;
2921 Opc2 = PPC::VADDUHM;
2922 Opc3 = PPC::VSUBUHM;
2923 VT = MVT::v8i16;
2924 } else {
2925 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
2926 Opc1 = PPC::VSPLTISW;
2927 Opc2 = PPC::VADDUWM;
2928 Opc3 = PPC::VSUBUWM;
2929 VT = MVT::v4i32;
2930 }
2931
2932 if ((Elt & 1) == 0) {
2933 // Elt is even, in the range [-32,-18] + [16,30].
2934 //
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);
2943
2944 } else if (Elt > 0) {
2945 // Elt is odd and positive, in the range [17,31].
2946 //
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),
2956 SDValue(Tmp2, 0));
2957
2958 } else {
2959 // Elt is odd and negative, in the range [-31,-17].
2960 //
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),
2970 SDValue(Tmp2, 0));
2971 }
2972 }
2973 }
2974
2975 return SelectCode(N);
2976 }
2977
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.
combineToCMPB(SDNode * N)2984 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
2985 SDLoc dl(N);
2986
2987 assert(N->getOpcode() == ISD::OR &&
2988 "Only OR nodes are supported for CMPB");
2989
2990 SDValue Res;
2991 if (!PPCSubTarget->hasCMPB())
2992 return Res;
2993
2994 if (N->getValueType(0) != MVT::i32 &&
2995 N->getValueType(0) != MVT::i64)
2996 return Res;
2997
2998 EVT VT = N->getValueType(0);
2999
3000 SDValue RHS, LHS;
3001 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3002 uint64_t Mask = 0, Alt = 0;
3003
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)
3008 return false;
3009 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3010
3011 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3012 !isa<ConstantSDNode>(O.getOperand(3)))
3013 return false;
3014
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)
3020 break;
3021 }
3022
3023 if (b == 8)
3024 return false;
3025 Mask |= PM;
3026 Alt |= PAlt;
3027
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);
3035
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))) {
3039
3040 unsigned Bits = Op0.getValueType().getSizeInBits();
3041 if (b != Bits/8-1)
3042 return false;
3043 if (Op0.getConstantOperandVal(1) != Bits-8)
3044 return false;
3045
3046 LHS = Op0.getOperand(0);
3047 RHS = Op1.getOperand(0);
3048 return true;
3049 }
3050
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))) {
3061
3062 uint64_t ULim = O.getConstantOperandVal(1);
3063 if (ULim != (UINT64_C(1) << b*8))
3064 return false;
3065
3066 // Now we need to make sure that the upper bytes are known to be
3067 // zero.
3068 unsigned Bits = Op0.getValueType().getSizeInBits();
3069 if (!CurDAG->MaskedValueIsZero(Op0,
3070 APInt::getHighBitsSet(Bits, Bits - (b+1)*8)))
3071 return false;
3072
3073 LHS = Op0.getOperand(0);
3074 RHS = Op0.getOperand(1);
3075 return true;
3076 }
3077
3078 return false;
3079 }
3080
3081 if (CC != ISD::SETEQ)
3082 return false;
3083
3084 SDValue Op = O.getOperand(0);
3085 if (Op.getOpcode() == ISD::AND) {
3086 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3087 return false;
3088 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3089 return false;
3090
3091 SDValue XOR = Op.getOperand(0);
3092 if (XOR.getOpcode() == ISD::TRUNCATE)
3093 XOR = XOR.getOperand(0);
3094 if (XOR.getOpcode() != ISD::XOR)
3095 return false;
3096
3097 LHS = XOR.getOperand(0);
3098 RHS = XOR.getOperand(1);
3099 return true;
3100 } else if (Op.getOpcode() == ISD::SRL) {
3101 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3102 return false;
3103 unsigned Bits = Op.getValueType().getSizeInBits();
3104 if (b != Bits/8-1)
3105 return false;
3106 if (Op.getConstantOperandVal(1) != Bits-8)
3107 return false;
3108
3109 SDValue XOR = Op.getOperand(0);
3110 if (XOR.getOpcode() == ISD::TRUNCATE)
3111 XOR = XOR.getOperand(0);
3112 if (XOR.getOpcode() != ISD::XOR)
3113 return false;
3114
3115 LHS = XOR.getOperand(0);
3116 RHS = XOR.getOperand(1);
3117 return true;
3118 }
3119
3120 return false;
3121 };
3122
3123 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3124 while (!Queue.empty()) {
3125 SDValue V = Queue.pop_back_val();
3126
3127 for (const SDValue &O : V.getNode()->ops()) {
3128 unsigned b;
3129 uint64_t M = 0, A = 0;
3130 SDValue OLHS, ORHS;
3131 if (O.getOpcode() == ISD::OR) {
3132 Queue.push_back(O);
3133 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3134 if (!LHS) {
3135 LHS = OLHS;
3136 RHS = ORHS;
3137 BytesFound[b] = true;
3138 Mask |= M;
3139 Alt |= A;
3140 } else if ((LHS == ORHS && RHS == OLHS) ||
3141 (RHS == ORHS && LHS == OLHS)) {
3142 BytesFound[b] = true;
3143 Mask |= M;
3144 Alt |= A;
3145 } else {
3146 return Res;
3147 }
3148 } else {
3149 return Res;
3150 }
3151 }
3152 }
3153
3154 unsigned LastB = 0, BCnt = 0;
3155 for (unsigned i = 0; i < 8; ++i)
3156 if (BytesFound[LastB]) {
3157 ++BCnt;
3158 LastB = i;
3159 }
3160
3161 if (!LastB || BCnt < 2)
3162 return Res;
3163
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);
3169 }
3170
3171 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3172
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));
3177 } else if (Alt) {
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));
3187 }
3188
3189 return Res;
3190 }
3191
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.
foldBoolExts(SDValue & Res,SDNode * & N)3199 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3200 if (!PPCSubTarget->useCRBits())
3201 return;
3202
3203 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3204 N->getOpcode() != ISD::SIGN_EXTEND &&
3205 N->getOpcode() != ISD::ANY_EXTEND)
3206 return;
3207
3208 if (N->getOperand(0).getValueType() != MVT::i1)
3209 return;
3210
3211 if (!N->hasOneUse())
3212 return;
3213
3214 SDLoc dl(N);
3215 EVT VT = N->getValueType(0);
3216 SDValue Cond = N->getOperand(0);
3217 SDValue ConstTrue =
3218 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, VT);
3219 SDValue ConstFalse = CurDAG->getConstant(0, VT);
3220
3221 do {
3222 SDNode *User = *N->use_begin();
3223 if (User->getNumOperands() != 2)
3224 break;
3225
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;
3230
3231 return CurDAG->FoldConstantArithmetic(User->getOpcode(),
3232 User->getValueType(0),
3233 O0.getNode(), O1.getNode());
3234 };
3235
3236 SDValue TrueRes = TryFold(ConstTrue);
3237 if (!TrueRes)
3238 break;
3239 SDValue FalseRes = TryFold(ConstFalse);
3240 if (!FalseRes)
3241 break;
3242
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))
3248 break;
3249
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);
3253 N = User;
3254 ConstTrue = TrueRes;
3255 ConstFalse = FalseRes;
3256 } while (N->hasOneUse());
3257 }
3258
PreprocessISelDAG()3259 void PPCDAGToDAGISel::PreprocessISelDAG() {
3260 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3261 ++Position;
3262
3263 bool MadeChange = false;
3264 while (Position != CurDAG->allnodes_begin()) {
3265 SDNode *N = --Position;
3266 if (N->use_empty())
3267 continue;
3268
3269 SDValue Res;
3270 switch (N->getOpcode()) {
3271 default: break;
3272 case ISD::OR:
3273 Res = combineToCMPB(N);
3274 break;
3275 }
3276
3277 if (!Res)
3278 foldBoolExts(Res, N);
3279
3280 if (Res) {
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");
3286
3287 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3288 MadeChange = true;
3289 }
3290 }
3291
3292 if (MadeChange)
3293 CurDAG->RemoveDeadNodes();
3294 }
3295
3296 /// PostprocessISelDAG - Perform some late peephole optimizations
3297 /// on the DAG representation.
PostprocessISelDAG()3298 void PPCDAGToDAGISel::PostprocessISelDAG() {
3299
3300 // Skip peepholes at -O0.
3301 if (TM.getOptLevel() == CodeGenOpt::None)
3302 return;
3303
3304 PeepholePPC64();
3305 PeepholeCROps();
3306 PeepholePPC64ZExt();
3307 }
3308
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
3313 // containing zero.
AllUsersSelectZero(SDNode * N)3314 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3315 // If we're not using isel, then this does not matter.
3316 if (!PPCSubTarget->hasISEL())
3317 return false;
3318
3319 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3320 UI != UE; ++UI) {
3321 SDNode *User = *UI;
3322 if (!User->isMachineOpcode())
3323 return false;
3324 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3325 User->getMachineOpcode() != PPC::SELECT_I8)
3326 return false;
3327
3328 SDNode *Op2 = User->getOperand(2).getNode();
3329 if (!Op2->isMachineOpcode())
3330 return false;
3331
3332 if (Op2->getMachineOpcode() != PPC::LI &&
3333 Op2->getMachineOpcode() != PPC::LI8)
3334 return false;
3335
3336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3337 if (!C)
3338 return false;
3339
3340 if (!C->isNullValue())
3341 return false;
3342 }
3343
3344 return true;
3345 }
3346
SwapAllSelectUsers(SDNode * N)3347 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3348 SmallVector<SDNode *, 4> ToReplace;
3349 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3350 UI != UE; ++UI) {
3351 SDNode *User = *UI;
3352 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3353 User->getMachineOpcode() == PPC::SELECT_I8) &&
3354 "Must have all select users");
3355 ToReplace.push_back(User);
3356 }
3357
3358 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3359 UE = ToReplace.end(); UI != UE; ++UI) {
3360 SDNode *User = *UI;
3361 SDNode *ResNode =
3362 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3363 User->getValueType(0), User->getOperand(0),
3364 User->getOperand(2),
3365 User->getOperand(1));
3366
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");
3372
3373 ReplaceUses(User, ResNode);
3374 }
3375 }
3376
PeepholeCROps()3377 void PPCDAGToDAGISel::PeepholeCROps() {
3378 bool IsModified;
3379 do {
3380 IsModified = false;
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())
3385 continue;
3386 SDNode *ResNode = MachineNode;
3387
3388 bool Op1Set = false, Op1Unset = false,
3389 Op1Not = false,
3390 Op2Set = false, Op2Unset = false,
3391 Op2Not = false;
3392
3393 unsigned Opcode = MachineNode->getMachineOpcode();
3394 switch (Opcode) {
3395 default: break;
3396 case PPC::CRAND:
3397 case PPC::CRNAND:
3398 case PPC::CROR:
3399 case PPC::CRXOR:
3400 case PPC::CRNOR:
3401 case PPC::CREQV:
3402 case PPC::CRANDC:
3403 case PPC::CRORC: {
3404 SDValue Op = MachineNode->getOperand(1);
3405 if (Op.isMachineOpcode()) {
3406 if (Op.getMachineOpcode() == PPC::CRSET)
3407 Op2Set = true;
3408 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3409 Op2Unset = true;
3410 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3411 Op.getOperand(0) == Op.getOperand(1))
3412 Op2Not = true;
3413 }
3414 } // fallthrough
3415 case PPC::BC:
3416 case PPC::BCn:
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)
3430 Op1Set = true;
3431 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3432 Op1Unset = true;
3433 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3434 Op.getOperand(0) == Op.getOperand(1))
3435 Op1Not = true;
3436 }
3437 }
3438 break;
3439 }
3440
3441 bool SelectSwap = false;
3442 switch (Opcode) {
3443 default: break;
3444 case PPC::CRAND:
3445 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3446 // x & x = x
3447 ResNode = MachineNode->getOperand(0).getNode();
3448 else if (Op1Set)
3449 // 1 & y = y
3450 ResNode = MachineNode->getOperand(1).getNode();
3451 else if (Op2Set)
3452 // x & 1 = x
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),
3457 MVT::i1);
3458 else if (Op1Not)
3459 // ~x & y = andc(y, x)
3460 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3461 MVT::i1, MachineNode->getOperand(1),
3462 MachineNode->getOperand(0).
3463 getOperand(0));
3464 else if (Op2Not)
3465 // x & ~y = andc(x, y)
3466 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3467 MVT::i1, MachineNode->getOperand(0),
3468 MachineNode->getOperand(1).
3469 getOperand(0));
3470 else if (AllUsersSelectZero(MachineNode))
3471 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3472 MVT::i1, MachineNode->getOperand(0),
3473 MachineNode->getOperand(1)),
3474 SelectSwap = true;
3475 break;
3476 case PPC::CRNAND:
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));
3482 else if (Op1Set)
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));
3487 else if (Op2Set)
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),
3495 MVT::i1);
3496 else if (Op1Not)
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).
3500 getOperand(0),
3501 MachineNode->getOperand(1));
3502 else if (Op2Not)
3503 // nand(x, ~y) = ~x | y = orc(y, x)
3504 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3505 MVT::i1, MachineNode->getOperand(1).
3506 getOperand(0),
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)),
3512 SelectSwap = true;
3513 break;
3514 case PPC::CROR:
3515 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3516 // x | x = x
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),
3521 MVT::i1);
3522 else if (Op1Unset)
3523 // 0 | y = y
3524 ResNode = MachineNode->getOperand(1).getNode();
3525 else if (Op2Unset)
3526 // x | 0 = x
3527 ResNode = MachineNode->getOperand(0).getNode();
3528 else if (Op1Not)
3529 // ~x | y = orc(y, x)
3530 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3531 MVT::i1, MachineNode->getOperand(1),
3532 MachineNode->getOperand(0).
3533 getOperand(0));
3534 else if (Op2Not)
3535 // x | ~y = orc(x, y)
3536 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3537 MVT::i1, MachineNode->getOperand(0),
3538 MachineNode->getOperand(1).
3539 getOperand(0));
3540 else if (AllUsersSelectZero(MachineNode))
3541 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3542 MVT::i1, MachineNode->getOperand(0),
3543 MachineNode->getOperand(1)),
3544 SelectSwap = true;
3545 break;
3546 case PPC::CRXOR:
3547 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3548 // xor(x, x) = 0
3549 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3550 MVT::i1);
3551 else if (Op1Set)
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));
3556 else if (Op2Set)
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));
3561 else if (Op1Unset)
3562 // xor(0, y) = y
3563 ResNode = MachineNode->getOperand(1).getNode();
3564 else if (Op2Unset)
3565 // xor(x, 0) = x
3566 ResNode = MachineNode->getOperand(0).getNode();
3567 else if (Op1Not)
3568 // xor(~x, y) = eqv(x, y)
3569 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3570 MVT::i1, MachineNode->getOperand(0).
3571 getOperand(0),
3572 MachineNode->getOperand(1));
3573 else if (Op2Not)
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).
3578 getOperand(0));
3579 else if (AllUsersSelectZero(MachineNode))
3580 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3581 MVT::i1, MachineNode->getOperand(0),
3582 MachineNode->getOperand(1)),
3583 SelectSwap = true;
3584 break;
3585 case PPC::CRNOR:
3586 if (Op1Set || Op2Set)
3587 // nor(1, y) -> 0
3588 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3589 MVT::i1);
3590 else if (Op1Unset)
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));
3595 else if (Op2Unset)
3596 // nor(x, 0) = ~x
3597 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3598 MVT::i1, MachineNode->getOperand(0),
3599 MachineNode->getOperand(0));
3600 else if (Op1Not)
3601 // nor(~x, y) = andc(x, y)
3602 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3603 MVT::i1, MachineNode->getOperand(0).
3604 getOperand(0),
3605 MachineNode->getOperand(1));
3606 else if (Op2Not)
3607 // nor(x, ~y) = andc(y, x)
3608 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3609 MVT::i1, MachineNode->getOperand(1).
3610 getOperand(0),
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)),
3616 SelectSwap = true;
3617 break;
3618 case PPC::CREQV:
3619 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3620 // eqv(x, x) = 1
3621 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3622 MVT::i1);
3623 else if (Op1Set)
3624 // eqv(1, y) = y
3625 ResNode = MachineNode->getOperand(1).getNode();
3626 else if (Op2Set)
3627 // eqv(x, 1) = x
3628 ResNode = MachineNode->getOperand(0).getNode();
3629 else if (Op1Unset)
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));
3634 else if (Op2Unset)
3635 // eqv(x, 0) = ~x
3636 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3637 MVT::i1, MachineNode->getOperand(0),
3638 MachineNode->getOperand(0));
3639 else if (Op1Not)
3640 // eqv(~x, y) = xor(x, y)
3641 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3642 MVT::i1, MachineNode->getOperand(0).
3643 getOperand(0),
3644 MachineNode->getOperand(1));
3645 else if (Op2Not)
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).
3650 getOperand(0));
3651 else if (AllUsersSelectZero(MachineNode))
3652 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3653 MVT::i1, MachineNode->getOperand(0),
3654 MachineNode->getOperand(1)),
3655 SelectSwap = true;
3656 break;
3657 case PPC::CRANDC:
3658 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3659 // andc(x, x) = 0
3660 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3661 MVT::i1);
3662 else if (Op1Set)
3663 // andc(1, y) = ~y
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),
3670 MVT::i1);
3671 else if (Op2Unset)
3672 // andc(x, 0) = x
3673 ResNode = MachineNode->getOperand(0).getNode();
3674 else if (Op1Not)
3675 // andc(~x, y) = ~(x | y) = nor(x, y)
3676 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3677 MVT::i1, MachineNode->getOperand(0).
3678 getOperand(0),
3679 MachineNode->getOperand(1));
3680 else if (Op2Not)
3681 // andc(x, ~y) = x & y
3682 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3683 MVT::i1, MachineNode->getOperand(0),
3684 MachineNode->getOperand(1).
3685 getOperand(0));
3686 else if (AllUsersSelectZero(MachineNode))
3687 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3688 MVT::i1, MachineNode->getOperand(1),
3689 MachineNode->getOperand(0)),
3690 SelectSwap = true;
3691 break;
3692 case PPC::CRORC:
3693 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3694 // orc(x, x) = 1
3695 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3696 MVT::i1);
3697 else if (Op1Set || Op2Unset)
3698 // orc(1, y) = orc(x, 0) = 1
3699 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3700 MVT::i1);
3701 else if (Op2Set)
3702 // orc(x, 1) = x
3703 ResNode = MachineNode->getOperand(0).getNode();
3704 else if (Op1Unset)
3705 // orc(0, y) = ~y
3706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3707 MVT::i1, MachineNode->getOperand(1),
3708 MachineNode->getOperand(1));
3709 else if (Op1Not)
3710 // orc(~x, y) = ~(x & y) = nand(x, y)
3711 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3712 MVT::i1, MachineNode->getOperand(0).
3713 getOperand(0),
3714 MachineNode->getOperand(1));
3715 else if (Op2Not)
3716 // orc(x, ~y) = x | y
3717 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3718 MVT::i1, MachineNode->getOperand(0),
3719 MachineNode->getOperand(1).
3720 getOperand(0));
3721 else if (AllUsersSelectZero(MachineNode))
3722 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3723 MVT::i1, MachineNode->getOperand(1),
3724 MachineNode->getOperand(0)),
3725 SelectSwap = true;
3726 break;
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:
3737 if (Op1Set)
3738 ResNode = MachineNode->getOperand(1).getNode();
3739 else if (Op1Unset)
3740 ResNode = MachineNode->getOperand(2).getNode();
3741 else if (Op1Not)
3742 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3743 SDLoc(MachineNode),
3744 MachineNode->getValueType(0),
3745 MachineNode->getOperand(0).
3746 getOperand(0),
3747 MachineNode->getOperand(2),
3748 MachineNode->getOperand(1));
3749 break;
3750 case PPC::BC:
3751 case PPC::BCn:
3752 if (Op1Not)
3753 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3754 PPC::BC,
3755 SDLoc(MachineNode),
3756 MVT::Other,
3757 MachineNode->getOperand(0).
3758 getOperand(0),
3759 MachineNode->getOperand(1),
3760 MachineNode->getOperand(2));
3761 // FIXME: Handle Op1Set, Op1Unset here too.
3762 break;
3763 }
3764
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.
3767 if (SelectSwap)
3768 SwapAllSelectUsers(MachineNode);
3769
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");
3776
3777 ReplaceUses(MachineNode, ResNode);
3778 IsModified = true;
3779 }
3780 }
3781 if (IsModified)
3782 CurDAG->RemoveDeadNodes();
3783 } while (IsModified);
3784 }
3785
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.
PeepholePPC64ZExtGather(SDValue Op32,SmallPtrSetImpl<SDNode * > & ToPromote)3788 static bool PeepholePPC64ZExtGather(SDValue Op32,
3789 SmallPtrSetImpl<SDNode *> &ToPromote) {
3790 if (!Op32.isMachineOpcode())
3791 return false;
3792
3793 // First, check for the "frontier" instructions (those that will clear the
3794 // higher-order 32 bits.
3795
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());
3803 return true;
3804 }
3805
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());
3810 return true;
3811 }
3812
3813 // For LI and LIS, we need the immediate to be positive (so that it is not
3814 // sign extended).
3815 if (Op32.getMachineOpcode() == PPC::LI ||
3816 Op32.getMachineOpcode() == PPC::LIS) {
3817 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
3818 return false;
3819
3820 ToPromote.insert(Op32.getNode());
3821 return true;
3822 }
3823
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());
3828 return true;
3829 }
3830
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());
3834 return true;
3835 }
3836
3837 // Next, check for those instructions we can look through.
3838
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))
3845 return false;
3846
3847 ToPromote.insert(Op32.getNode());
3848 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3849 return true;
3850 }
3851
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
3854 // shifted by 1).
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))
3860 return false;
3861 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
3862 return false;
3863
3864 ToPromote.insert(Op32.getNode());
3865 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3866 return true;
3867 }
3868
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
3871 // extended).
3872 if (Op32.getMachineOpcode() == PPC::ORI ||
3873 Op32.getMachineOpcode() == PPC::ORIS) {
3874 SmallPtrSet<SDNode *, 16> ToPromote1;
3875 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
3876 return false;
3877 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
3878 return false;
3879
3880 ToPromote.insert(Op32.getNode());
3881 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3882 return true;
3883 }
3884
3885 // The higher-order bits of AND are zero if that is true for at least one of
3886 // the operands.
3887 if (Op32.getMachineOpcode() == PPC::AND) {
3888 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
3889 bool Op0OK =
3890 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3891 bool Op1OK =
3892 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
3893 if (!Op0OK && !Op1OK)
3894 return false;
3895
3896 ToPromote.insert(Op32.getNode());
3897
3898 if (Op0OK)
3899 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3900
3901 if (Op1OK)
3902 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
3903
3904 return true;
3905 }
3906
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;
3913 bool Op0OK =
3914 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
3915 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
3916 if (!Op0OK && !Op1OK)
3917 return false;
3918
3919 ToPromote.insert(Op32.getNode());
3920
3921 if (Op0OK)
3922 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
3923
3924 return true;
3925 }
3926
3927 return false;
3928 }
3929
PeepholePPC64ZExt()3930 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
3931 if (!PPCSubTarget->isPPC64())
3932 return;
3933
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),
3937 // 0, 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.
3942
3943 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3944 ++Position;
3945
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())
3951 continue;
3952
3953 if (N->getMachineOpcode() != PPC::RLDICL)
3954 continue;
3955
3956 if (N->getConstantOperandVal(1) != 0 ||
3957 N->getConstantOperandVal(2) != 32)
3958 continue;
3959
3960 SDValue ISR = N->getOperand(0);
3961 if (!ISR.isMachineOpcode() ||
3962 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
3963 continue;
3964
3965 if (!ISR.hasOneUse())
3966 continue;
3967
3968 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
3969 continue;
3970
3971 SDValue IDef = ISR.getOperand(0);
3972 if (!IDef.isMachineOpcode() ||
3973 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
3974 continue;
3975
3976 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
3977 // can get rid of it.
3978
3979 SDValue Op32 = ISR->getOperand(1);
3980 if (!Op32.isMachineOpcode())
3981 continue;
3982
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
3985 // through.
3986 SmallPtrSet<SDNode *, 16> ToPromote;
3987 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
3988 continue;
3989
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()) {
3996 OutsideUse = true;
3997 break;
3998 }
3999 }
4000
4001 if (OutsideUse)
4002 break;
4003 }
4004 if (OutsideUse)
4005 continue;
4006
4007 MadeChange = true;
4008
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
4012 // operands.
4013 for (SDNode *PN : ToPromote) {
4014 unsigned NewOpcode;
4015 switch (PN->getMachineOpcode()) {
4016 default:
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;
4035 }
4036
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
4040 // again.
4041
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) };
4047 SDNode *ReplOp =
4048 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4049 ISR.getNode()->getVTList(), ReplOpOps);
4050 Ops.push_back(SDValue(ReplOp, 0));
4051 } else {
4052 Ops.push_back(V);
4053 }
4054 }
4055
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.
4059
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);
4065 else
4066 NewVTs.push_back(VTs.VTs[i]);
4067
4068 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4069 DEBUG(PN->dump(CurDAG));
4070
4071 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4072
4073 DEBUG(dbgs() << "\nNew: ");
4074 DEBUG(PN->dump(CurDAG));
4075 DEBUG(dbgs() << "\n");
4076 }
4077
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
4080 // return an i64).
4081
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");
4087
4088 ReplaceUses(N, Op32.getNode());
4089 }
4090
4091 if (MadeChange)
4092 CurDAG->RemoveDeadNodes();
4093 }
4094
PeepholePPC64()4095 void PPCDAGToDAGISel::PeepholePPC64() {
4096 // These optimizations are currently supported only for 64-bit SVR4.
4097 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4098 return;
4099
4100 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4101 ++Position;
4102
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())
4107 continue;
4108
4109 unsigned FirstOp;
4110 unsigned StorageOpcode = N->getMachineOpcode();
4111
4112 switch (StorageOpcode) {
4113 default: continue;
4114
4115 case PPC::LBZ:
4116 case PPC::LBZ8:
4117 case PPC::LD:
4118 case PPC::LFD:
4119 case PPC::LFS:
4120 case PPC::LHA:
4121 case PPC::LHA8:
4122 case PPC::LHZ:
4123 case PPC::LHZ8:
4124 case PPC::LWA:
4125 case PPC::LWZ:
4126 case PPC::LWZ8:
4127 FirstOp = 0;
4128 break;
4129
4130 case PPC::STB:
4131 case PPC::STB8:
4132 case PPC::STD:
4133 case PPC::STFD:
4134 case PPC::STFS:
4135 case PPC::STH:
4136 case PPC::STH8:
4137 case PPC::STW:
4138 case PPC::STW8:
4139 FirstOp = 1;
4140 break;
4141 }
4142
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)
4147 continue;
4148
4149 SDValue Base = N->getOperand(FirstOp + 1);
4150 if (!Base.isMachineOpcode())
4151 continue;
4152
4153 unsigned Flags = 0;
4154 bool ReplaceFlags = true;
4155
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.
4160 //
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()) {
4167 default: continue;
4168
4169 case PPC::ADDI8:
4170 case PPC::ADDI:
4171 // In some cases (such as TLS) the relocation information
4172 // is already in place on the operand, so copying the operand
4173 // is sufficient.
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))
4183 continue;
4184 break;
4185 case PPC::ADDIdtprelL:
4186 Flags = PPCII::MO_DTPREL_LO;
4187 break;
4188 case PPC::ADDItlsldL:
4189 Flags = PPCII::MO_TLSLD_LO;
4190 break;
4191 case PPC::ADDItocL:
4192 Flags = PPCII::MO_TOC_LO;
4193 break;
4194 }
4195
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");
4205
4206 SDValue ImmOpnd = Base.getOperand(1);
4207
4208 // If the relocation information isn't already present on the
4209 // immediate operand, add it now.
4210 if (ReplaceFlags) {
4211 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4212 SDLoc dl(GA);
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");
4220 continue;
4221 }
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,
4227 CP->getAlignment(),
4228 0, Flags);
4229 }
4230 }
4231
4232 if (FirstOp == 1) // Store
4233 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4234 Base.getOperand(0), N->getOperand(3));
4235 else // Load
4236 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4237 N->getOperand(2));
4238
4239 // The add-immediate may now be dead, in which case remove it.
4240 if (Base.getNode()->use_empty())
4241 CurDAG->RemoveDeadNode(Base.getNode());
4242 }
4243 }
4244
4245
4246 /// createPPCISelDag - This pass converts a legalized DAG into a
4247 /// PowerPC-specific DAG, ready for instruction scheduling.
4248 ///
createPPCISelDag(PPCTargetMachine & TM)4249 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4250 return new PPCDAGToDAGISel(TM);
4251 }
4252
initializePassOnce(PassRegistry & Registry)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);
4258 }
4259
initializePPCDAGToDAGISelPass(PassRegistry & Registry)4260 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
4261 CALL_ONCE_INITIALIZATION(initializePassOnce);
4262 }
4263
4264