LLVM  5.0.0
PPCISelDAGToDAG.cpp
Go to the documentation of this file.
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 
17 #include "PPC.h"
18 #include "PPCISelLowering.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCSubtarget.h"
21 #include "PPCTargetMachine.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CodeGen.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/KnownBits.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstdint>
61 #include <iterator>
62 #include <limits>
63 #include <memory>
64 #include <new>
65 #include <tuple>
66 #include <utility>
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "ppc-codegen"
71 
72 STATISTIC(NumSextSetcc,
73  "Number of (sext(setcc)) nodes expanded into GPR sequence.");
74 STATISTIC(NumZextSetcc,
75  "Number of (zext(setcc)) nodes expanded into GPR sequence.");
76 STATISTIC(SignExtensionsAdded,
77  "Number of sign extensions for compare inputs added.");
78 STATISTIC(ZeroExtensionsAdded,
79  "Number of zero extensions for compare inputs added.");
80 STATISTIC(NumLogicOpsOnComparison,
81  "Number of logical ops on i1 values calculated in GPR.");
82 STATISTIC(OmittedForNonExtendUses,
83  "Number of compares not eliminated as they have non-extending uses.");
84 
85 // FIXME: Remove this once the bug has been fixed!
86 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
87 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
88 
89 static cl::opt<bool>
90  UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
91  cl::desc("use aggressive ppc isel for bit permutations"),
92  cl::Hidden);
94  "ppc-bit-perm-rewriter-stress-rotates",
95  cl::desc("stress rotate selection in aggressive ppc isel for "
96  "bit permutations"),
97  cl::Hidden);
98 
100  "ppc-use-branch-hint", cl::init(true),
101  cl::desc("Enable static hinting of branches on ppc"),
102  cl::Hidden);
103 
104 namespace {
105 
106  //===--------------------------------------------------------------------===//
107  /// PPCDAGToDAGISel - PPC specific code to select PPC machine
108  /// instructions for SelectionDAG operations.
109  ///
110  class PPCDAGToDAGISel : public SelectionDAGISel {
111  const PPCTargetMachine &TM;
112  const PPCSubtarget *PPCSubTarget;
113  const PPCTargetLowering *PPCLowering;
114  unsigned GlobalBaseReg;
115 
116  public:
117  explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
118  : SelectionDAGISel(tm, OptLevel), TM(tm) {}
119 
120  bool runOnMachineFunction(MachineFunction &MF) override {
121  // Make sure we re-emit a set of the global base reg if necessary
122  GlobalBaseReg = 0;
123  PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
124  PPCLowering = PPCSubTarget->getTargetLowering();
126 
127  if (!PPCSubTarget->isSVR4ABI())
128  InsertVRSaveCode(MF);
129 
130  return true;
131  }
132 
133  void PreprocessISelDAG() override;
134  void PostprocessISelDAG() override;
135 
136  /// getI32Imm - Return a target constant with the specified value, of type
137  /// i32.
138  inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
139  return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
140  }
141 
142  /// getI64Imm - Return a target constant with the specified value, of type
143  /// i64.
144  inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
145  return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
146  }
147 
148  /// getSmallIPtrImm - Return a target constant of pointer type.
149  inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
150  return CurDAG->getTargetConstant(
151  Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
152  }
153 
154  /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
155  /// rotate and mask opcode and mask operation.
156  static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
157  unsigned &SH, unsigned &MB, unsigned &ME);
158 
159  /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
160  /// base register. Return the virtual register that holds this value.
161  SDNode *getGlobalBaseReg();
162 
163  void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
164 
165  // Select - Convert the specified operand from a target-independent to a
166  // target-specific node if it hasn't already been changed.
167  void Select(SDNode *N) override;
168 
169  bool tryBitfieldInsert(SDNode *N);
170  bool tryBitPermutation(SDNode *N);
171 
172  /// SelectCC - Select a comparison of the specified values with the
173  /// specified condition code, returning the CR# of the expression.
174  SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
175  const SDLoc &dl);
176 
177  /// SelectAddrImm - Returns true if the address N can be represented by
178  /// a base register plus a signed 16-bit displacement [r+imm].
179  bool SelectAddrImm(SDValue N, SDValue &Disp,
180  SDValue &Base) {
181  return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 0);
182  }
183 
184  /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
185  /// immediate field. Note that the operand at this point is already the
186  /// result of a prior SelectAddressRegImm call.
187  bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
188  if (N.getOpcode() == ISD::TargetConstant ||
190  Out = N;
191  return true;
192  }
193 
194  return false;
195  }
196 
197  /// SelectAddrIdx - Given the specified addressed, check to see if it can be
198  /// represented as an indexed [r+r] operation. Returns false if it can
199  /// be represented by [r+imm], which are preferred.
200  bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
201  return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
202  }
203 
204  /// SelectAddrIdxOnly - Given the specified addressed, force it to be
205  /// represented as an indexed [r+r] operation.
206  bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
207  return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
208  }
209 
210  /// SelectAddrImmX4 - Returns true if the address N can be represented by
211  /// a base register plus a signed 16-bit displacement that is a multiple of 4.
212  /// Suitable for use by STD and friends.
213  bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
214  return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 4);
215  }
216 
217  bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
218  return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 16);
219  }
220 
221  // Select an address into a single register.
222  bool SelectAddr(SDValue N, SDValue &Base) {
223  Base = N;
224  return true;
225  }
226 
227  /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
228  /// inline asm expressions. It is always correct to compute the value into
229  /// a register. The case of adding a (possibly relocatable) constant to a
230  /// register can be improved, but it is wrong to substitute Reg+Reg for
231  /// Reg in an asm, because the load or store opcode would have to change.
232  bool SelectInlineAsmMemoryOperand(const SDValue &Op,
233  unsigned ConstraintID,
234  std::vector<SDValue> &OutOps) override {
235  switch(ConstraintID) {
236  default:
237  errs() << "ConstraintID: " << ConstraintID << "\n";
238  llvm_unreachable("Unexpected asm memory constraint");
246  // We need to make sure that this one operand does not end up in r0
247  // (because we might end up lowering this as 0(%op)).
248  const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
249  const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
250  SDLoc dl(Op);
251  SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
252  SDValue NewOp =
253  SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
254  dl, Op.getValueType(),
255  Op, RC), 0);
256 
257  OutOps.push_back(NewOp);
258  return false;
259  }
260  return true;
261  }
262 
263  void InsertVRSaveCode(MachineFunction &MF);
264 
265  StringRef getPassName() const override {
266  return "PowerPC DAG->DAG Pattern Instruction Selection";
267  }
268 
269 // Include the pieces autogenerated from the target description.
270 #include "PPCGenDAGISel.inc"
271 
272 private:
273  // Conversion type for interpreting results of a 32-bit instruction as
274  // a 64-bit value or vice versa.
275  enum ExtOrTruncConversion { Ext, Trunc };
276 
277  // Modifiers to guide how an ISD::SETCC node's result is to be computed
278  // in a GPR.
279  // ZExtOrig - use the original condition code, zero-extend value
280  // ZExtInvert - invert the condition code, zero-extend value
281  // SExtOrig - use the original condition code, sign-extend value
282  // SExtInvert - invert the condition code, sign-extend value
283  enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
284 
285  bool trySETCC(SDNode *N);
286  bool tryEXTEND(SDNode *N);
287  bool tryLogicOpOfCompares(SDNode *N);
288  SDValue computeLogicOpInGPR(SDValue LogicOp);
289  SDValue signExtendInputIfNeeded(SDValue Input);
290  SDValue zeroExtendInputIfNeeded(SDValue Input);
291  SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
292  SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
293  int64_t RHSValue, SDLoc dl);
294  SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
295  int64_t RHSValue, SDLoc dl);
296  SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
297  int64_t RHSValue, SDLoc dl);
298  SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
299  int64_t RHSValue, SDLoc dl);
300  SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
301 
302  void PeepholePPC64();
303  void PeepholePPC64ZExt();
304  void PeepholeCROps();
305 
306  SDValue combineToCMPB(SDNode *N);
307  void foldBoolExts(SDValue &Res, SDNode *&N);
308 
309  bool AllUsersSelectZero(SDNode *N);
310  void SwapAllSelectUsers(SDNode *N);
311 
312  bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
313  void transferMemOperands(SDNode *N, SDNode *Result);
314  };
315 
316 } // end anonymous namespace
317 
318 /// InsertVRSaveCode - Once the entire function has been instruction selected,
319 /// all virtual registers are created and all machine instructions are built,
320 /// check to see if we need to save/restore VRSAVE. If so, do it.
321 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
322  // Check to see if this function uses vector registers, which means we have to
323  // save and restore the VRSAVE register and update it with the regs we use.
324  //
325  // In this case, there will be virtual registers of vector type created
326  // by the scheduler. Detect them now.
327  bool HasVectorVReg = false;
328  for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
330  if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
331  HasVectorVReg = true;
332  break;
333  }
334  }
335  if (!HasVectorVReg) return; // nothing to do.
336 
337  // If we have a vector register, we want to emit code into the entry and exit
338  // blocks to save and restore the VRSAVE register. We do this here (instead
339  // of marking all vector instructions as clobbering VRSAVE) for two reasons:
340  //
341  // 1. This (trivially) reduces the load on the register allocator, by not
342  // having to represent the live range of the VRSAVE register.
343  // 2. This (more significantly) allows us to create a temporary virtual
344  // register to hold the saved VRSAVE value, allowing this temporary to be
345  // register allocated, instead of forcing it to be spilled to the stack.
346 
347  // Create two vregs - one to hold the VRSAVE register that is live-in to the
348  // function and one for the value after having bits or'd into it.
349  unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
350  unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
351 
352  const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
353  MachineBasicBlock &EntryBB = *Fn.begin();
354  DebugLoc dl;
355  // Emit the following code into the entry block:
356  // InVRSAVE = MFVRSAVE
357  // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
358  // MTVRSAVE UpdatedVRSAVE
359  MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
360  BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
361  BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
362  UpdatedVRSAVE).addReg(InVRSAVE);
363  BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
364 
365  // Find all return blocks, outputting a restore in each epilog.
366  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
367  if (BB->isReturnBlock()) {
368  IP = BB->end(); --IP;
369 
370  // Skip over all terminator instructions, which are part of the return
371  // sequence.
373  while (I2 != BB->begin() && (--I2)->isTerminator())
374  IP = I2;
375 
376  // Emit: MTVRSAVE InVRSave
377  BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
378  }
379  }
380 }
381 
382 /// getGlobalBaseReg - Output the instructions required to put the
383 /// base address to use for accessing globals into a register.
384 ///
385 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
386  if (!GlobalBaseReg) {
387  const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
388  // Insert the set of GlobalBaseReg into the first MBB of the function
389  MachineBasicBlock &FirstMBB = MF->front();
390  MachineBasicBlock::iterator MBBI = FirstMBB.begin();
391  const Module *M = MF->getFunction()->getParent();
392  DebugLoc dl;
393 
394  if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
395  if (PPCSubTarget->isTargetELF()) {
396  GlobalBaseReg = PPC::R30;
397  if (M->getPICLevel() == PICLevel::SmallPIC) {
398  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
399  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
400  MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
401  } else {
402  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
403  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
404  unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
405  BuildMI(FirstMBB, MBBI, dl,
406  TII.get(PPC::UpdateGBR), GlobalBaseReg)
407  .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
408  MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
409  }
410  } else {
411  GlobalBaseReg =
412  RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
413  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
414  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
415  }
416  } else {
417  GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
418  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
419  BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
420  }
421  }
422  return CurDAG->getRegister(GlobalBaseReg,
423  PPCLowering->getPointerTy(CurDAG->getDataLayout()))
424  .getNode();
425 }
426 
427 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
428 /// operand. If so Imm will receive the 32-bit value.
429 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
430  if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
431  Imm = cast<ConstantSDNode>(N)->getZExtValue();
432  return true;
433  }
434  return false;
435 }
436 
437 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
438 /// operand. If so Imm will receive the 64-bit value.
439 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
440  if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
441  Imm = cast<ConstantSDNode>(N)->getZExtValue();
442  return true;
443  }
444  return false;
445 }
446 
447 // isInt32Immediate - This method tests to see if a constant operand.
448 // If so Imm will receive the 32 bit value.
449 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
450  return isInt32Immediate(N.getNode(), Imm);
451 }
452 
453 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
454  const SDValue &DestMBB) {
455  assert(isa<BasicBlockSDNode>(DestMBB));
456 
457  if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
458 
459  const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
460  const TerminatorInst *BBTerm = BB->getTerminator();
461 
462  if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
463 
464  const BasicBlock *TBB = BBTerm->getSuccessor(0);
465  const BasicBlock *FBB = BBTerm->getSuccessor(1);
466 
467  auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
468  auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
469 
470  // We only want to handle cases which are easy to predict at static time, e.g.
471  // C++ throw statement, that is very likely not taken, or calling never
472  // returned function, e.g. stdlib exit(). So we set Threshold to filter
473  // unwanted cases.
474  //
475  // Below is LLVM branch weight table, we only want to handle case 1, 2
476  //
477  // Case Taken:Nontaken Example
478  // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
479  // 2. Invoke-terminating 1:1048575
480  // 3. Coldblock 4:64 __builtin_expect
481  // 4. Loop Branch 124:4 For loop
482  // 5. PH/ZH/FPH 20:12
483  const uint32_t Threshold = 10000;
484 
485  if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
486  return PPC::BR_NO_HINT;
487 
488  DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
489  << BB->getName() << "'\n"
490  << " -> " << TBB->getName() << ": " << TProb << "\n"
491  << " -> " << FBB->getName() << ": " << FProb << "\n");
492 
493  const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
494 
495  // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
496  // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
497  if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
498  std::swap(TProb, FProb);
499 
500  return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
501 }
502 
503 // isOpcWithIntImmediate - This method tests to see if the node is a specific
504 // opcode and that it has a immediate integer right operand.
505 // If so Imm will receive the 32 bit value.
506 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
507  return N->getOpcode() == Opc
508  && isInt32Immediate(N->getOperand(1).getNode(), Imm);
509 }
510 
511 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
512  SDLoc dl(SN);
513  int FI = cast<FrameIndexSDNode>(N)->getIndex();
514  SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
515  unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
516  if (SN->hasOneUse())
517  CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
518  getSmallIPtrImm(Offset, dl));
519  else
520  ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
521  getSmallIPtrImm(Offset, dl)));
522 }
523 
524 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
525  bool isShiftMask, unsigned &SH,
526  unsigned &MB, unsigned &ME) {
527  // Don't even go down this path for i64, since different logic will be
528  // necessary for rldicl/rldicr/rldimi.
529  if (N->getValueType(0) != MVT::i32)
530  return false;
531 
532  unsigned Shift = 32;
533  unsigned Indeterminant = ~0; // bit mask marking indeterminant results
534  unsigned Opcode = N->getOpcode();
535  if (N->getNumOperands() != 2 ||
536  !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
537  return false;
538 
539  if (Opcode == ISD::SHL) {
540  // apply shift left to mask if it comes first
541  if (isShiftMask) Mask = Mask << Shift;
542  // determine which bits are made indeterminant by shift
543  Indeterminant = ~(0xFFFFFFFFu << Shift);
544  } else if (Opcode == ISD::SRL) {
545  // apply shift right to mask if it comes first
546  if (isShiftMask) Mask = Mask >> Shift;
547  // determine which bits are made indeterminant by shift
548  Indeterminant = ~(0xFFFFFFFFu >> Shift);
549  // adjust for the left rotate
550  Shift = 32 - Shift;
551  } else if (Opcode == ISD::ROTL) {
552  Indeterminant = 0;
553  } else {
554  return false;
555  }
556 
557  // if the mask doesn't intersect any Indeterminant bits
558  if (Mask && !(Mask & Indeterminant)) {
559  SH = Shift & 31;
560  // make sure the mask is still a mask (wrap arounds may not be)
561  return isRunOfOnes(Mask, MB, ME);
562  }
563  return false;
564 }
565 
566 /// Turn an or of two masked values into the rotate left word immediate then
567 /// mask insert (rlwimi) instruction.
568 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
569  SDValue Op0 = N->getOperand(0);
570  SDValue Op1 = N->getOperand(1);
571  SDLoc dl(N);
572 
573  KnownBits LKnown, RKnown;
574  CurDAG->computeKnownBits(Op0, LKnown);
575  CurDAG->computeKnownBits(Op1, RKnown);
576 
577  unsigned TargetMask = LKnown.Zero.getZExtValue();
578  unsigned InsertMask = RKnown.Zero.getZExtValue();
579 
580  if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
581  unsigned Op0Opc = Op0.getOpcode();
582  unsigned Op1Opc = Op1.getOpcode();
583  unsigned Value, SH = 0;
584  TargetMask = ~TargetMask;
585  InsertMask = ~InsertMask;
586 
587  // If the LHS has a foldable shift and the RHS does not, then swap it to the
588  // RHS so that we can fold the shift into the insert.
589  if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
590  if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
591  Op0.getOperand(0).getOpcode() == ISD::SRL) {
592  if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
593  Op1.getOperand(0).getOpcode() != ISD::SRL) {
594  std::swap(Op0, Op1);
595  std::swap(Op0Opc, Op1Opc);
596  std::swap(TargetMask, InsertMask);
597  }
598  }
599  } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
600  if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
601  Op1.getOperand(0).getOpcode() != ISD::SRL) {
602  std::swap(Op0, Op1);
603  std::swap(Op0Opc, Op1Opc);
604  std::swap(TargetMask, InsertMask);
605  }
606  }
607 
608  unsigned MB, ME;
609  if (isRunOfOnes(InsertMask, MB, ME)) {
610  SDValue Tmp1, Tmp2;
611 
612  if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
613  isInt32Immediate(Op1.getOperand(1), Value)) {
614  Op1 = Op1.getOperand(0);
615  SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
616  }
617  if (Op1Opc == ISD::AND) {
618  // The AND mask might not be a constant, and we need to make sure that
619  // if we're going to fold the masking with the insert, all bits not
620  // know to be zero in the mask are known to be one.
621  KnownBits MKnown;
622  CurDAG->computeKnownBits(Op1.getOperand(1), MKnown);
623  bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
624 
625  unsigned SHOpc = Op1.getOperand(0).getOpcode();
626  if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
627  isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
628  // Note that Value must be in range here (less than 32) because
629  // otherwise there would not be any bits set in InsertMask.
630  Op1 = Op1.getOperand(0).getOperand(0);
631  SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
632  }
633  }
634 
635  SH &= 31;
636  SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
637  getI32Imm(ME, dl) };
638  ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
639  return true;
640  }
641  }
642  return false;
643 }
644 
645 // Predict the number of instructions that would be generated by calling
646 // getInt64(N).
647 static unsigned getInt64CountDirect(int64_t Imm) {
648  // Assume no remaining bits.
649  unsigned Remainder = 0;
650  // Assume no shift required.
651  unsigned Shift = 0;
652 
653  // If it can't be represented as a 32 bit value.
654  if (!isInt<32>(Imm)) {
655  Shift = countTrailingZeros<uint64_t>(Imm);
656  int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
657 
658  // If the shifted value fits 32 bits.
659  if (isInt<32>(ImmSh)) {
660  // Go with the shifted value.
661  Imm = ImmSh;
662  } else {
663  // Still stuck with a 64 bit value.
664  Remainder = Imm;
665  Shift = 32;
666  Imm >>= 32;
667  }
668  }
669 
670  // Intermediate operand.
671  unsigned Result = 0;
672 
673  // Handle first 32 bits.
674  unsigned Lo = Imm & 0xFFFF;
675 
676  // Simple value.
677  if (isInt<16>(Imm)) {
678  // Just the Lo bits.
679  ++Result;
680  } else if (Lo) {
681  // Handle the Hi bits and Lo bits.
682  Result += 2;
683  } else {
684  // Just the Hi bits.
685  ++Result;
686  }
687 
688  // If no shift, we're done.
689  if (!Shift) return Result;
690 
691  // If Hi word == Lo word,
692  // we can use rldimi to insert the Lo word into Hi word.
693  if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
694  ++Result;
695  return Result;
696  }
697 
698  // Shift for next step if the upper 32-bits were not zero.
699  if (Imm)
700  ++Result;
701 
702  // Add in the last bits as required.
703  if ((Remainder >> 16) & 0xFFFF)
704  ++Result;
705  if (Remainder & 0xFFFF)
706  ++Result;
707 
708  return Result;
709 }
710 
711 static uint64_t Rot64(uint64_t Imm, unsigned R) {
712  return (Imm << R) | (Imm >> (64 - R));
713 }
714 
715 static unsigned getInt64Count(int64_t Imm) {
716  unsigned Count = getInt64CountDirect(Imm);
717 
718  // If the instruction count is 1 or 2, we do not need further analysis
719  // since rotate + load constant requires at least 2 instructions.
720  if (Count <= 2)
721  return Count;
722 
723  for (unsigned r = 1; r < 63; ++r) {
724  uint64_t RImm = Rot64(Imm, r);
725  unsigned RCount = getInt64CountDirect(RImm) + 1;
726  Count = std::min(Count, RCount);
727 
728  // See comments in getInt64 for an explanation of the logic below.
729  unsigned LS = findLastSet(RImm);
730  if (LS != r-1)
731  continue;
732 
733  uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
734  uint64_t RImmWithOnes = RImm | OnesMask;
735 
736  RCount = getInt64CountDirect(RImmWithOnes) + 1;
737  Count = std::min(Count, RCount);
738  }
739 
740  return Count;
741 }
742 
743 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count
744 // (above) needs to be kept in sync with this function.
745 static SDNode *getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl,
746  int64_t Imm) {
747  // Assume no remaining bits.
748  unsigned Remainder = 0;
749  // Assume no shift required.
750  unsigned Shift = 0;
751 
752  // If it can't be represented as a 32 bit value.
753  if (!isInt<32>(Imm)) {
754  Shift = countTrailingZeros<uint64_t>(Imm);
755  int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
756 
757  // If the shifted value fits 32 bits.
758  if (isInt<32>(ImmSh)) {
759  // Go with the shifted value.
760  Imm = ImmSh;
761  } else {
762  // Still stuck with a 64 bit value.
763  Remainder = Imm;
764  Shift = 32;
765  Imm >>= 32;
766  }
767  }
768 
769  // Intermediate operand.
770  SDNode *Result;
771 
772  // Handle first 32 bits.
773  unsigned Lo = Imm & 0xFFFF;
774  unsigned Hi = (Imm >> 16) & 0xFFFF;
775 
776  auto getI32Imm = [CurDAG, dl](unsigned Imm) {
777  return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
778  };
779 
780  // Simple value.
781  if (isInt<16>(Imm)) {
782  // Just the Lo bits.
783  Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
784  } else if (Lo) {
785  // Handle the Hi bits.
786  unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
787  Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
788  // And Lo bits.
789  Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
790  SDValue(Result, 0), getI32Imm(Lo));
791  } else {
792  // Just the Hi bits.
793  Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
794  }
795 
796  // If no shift, we're done.
797  if (!Shift) return Result;
798 
799  // If Hi word == Lo word,
800  // we can use rldimi to insert the Lo word into Hi word.
801  if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
802  SDValue Ops[] =
803  { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
804  return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
805  }
806 
807  // Shift for next step if the upper 32-bits were not zero.
808  if (Imm) {
809  Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
810  SDValue(Result, 0),
811  getI32Imm(Shift),
812  getI32Imm(63 - Shift));
813  }
814 
815  // Add in the last bits as required.
816  if ((Hi = (Remainder >> 16) & 0xFFFF)) {
817  Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
818  SDValue(Result, 0), getI32Imm(Hi));
819  }
820  if ((Lo = Remainder & 0xFFFF)) {
821  Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
822  SDValue(Result, 0), getI32Imm(Lo));
823  }
824 
825  return Result;
826 }
827 
828 static SDNode *getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm) {
829  unsigned Count = getInt64CountDirect(Imm);
830 
831  // If the instruction count is 1 or 2, we do not need further analysis
832  // since rotate + load constant requires at least 2 instructions.
833  if (Count <= 2)
834  return getInt64Direct(CurDAG, dl, Imm);
835 
836  unsigned RMin = 0;
837 
838  int64_t MatImm;
839  unsigned MaskEnd;
840 
841  for (unsigned r = 1; r < 63; ++r) {
842  uint64_t RImm = Rot64(Imm, r);
843  unsigned RCount = getInt64CountDirect(RImm) + 1;
844  if (RCount < Count) {
845  Count = RCount;
846  RMin = r;
847  MatImm = RImm;
848  MaskEnd = 63;
849  }
850 
851  // If the immediate to generate has many trailing zeros, it might be
852  // worthwhile to generate a rotated value with too many leading ones
853  // (because that's free with li/lis's sign-extension semantics), and then
854  // mask them off after rotation.
855 
856  unsigned LS = findLastSet(RImm);
857  // We're adding (63-LS) higher-order ones, and we expect to mask them off
858  // after performing the inverse rotation by (64-r). So we need that:
859  // 63-LS == 64-r => LS == r-1
860  if (LS != r-1)
861  continue;
862 
863  uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
864  uint64_t RImmWithOnes = RImm | OnesMask;
865 
866  RCount = getInt64CountDirect(RImmWithOnes) + 1;
867  if (RCount < Count) {
868  Count = RCount;
869  RMin = r;
870  MatImm = RImmWithOnes;
871  MaskEnd = LS;
872  }
873  }
874 
875  if (!RMin)
876  return getInt64Direct(CurDAG, dl, Imm);
877 
878  auto getI32Imm = [CurDAG, dl](unsigned Imm) {
879  return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
880  };
881 
882  SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0);
883  return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
884  getI32Imm(64 - RMin), getI32Imm(MaskEnd));
885 }
886 
887 // Select a 64-bit constant.
888 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) {
889  SDLoc dl(N);
890 
891  // Get 64 bit value.
892  int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
893  return getInt64(CurDAG, dl, Imm);
894 }
895 
896 namespace {
897 
898 class BitPermutationSelector {
899  struct ValueBit {
900  SDValue V;
901 
902  // The bit number in the value, using a convention where bit 0 is the
903  // lowest-order bit.
904  unsigned Idx;
905 
906  enum Kind {
907  ConstZero,
908  Variable
909  } K;
910 
911  ValueBit(SDValue V, unsigned I, Kind K = Variable)
912  : V(V), Idx(I), K(K) {}
913  ValueBit(Kind K = Variable)
914  : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
915 
916  bool isZero() const {
917  return K == ConstZero;
918  }
919 
920  bool hasValue() const {
921  return K == Variable;
922  }
923 
924  SDValue getValue() const {
925  assert(hasValue() && "Cannot get the value of a constant bit");
926  return V;
927  }
928 
929  unsigned getValueBitIndex() const {
930  assert(hasValue() && "Cannot get the value bit index of a constant bit");
931  return Idx;
932  }
933  };
934 
935  // A bit group has the same underlying value and the same rotate factor.
936  struct BitGroup {
937  SDValue V;
938  unsigned RLAmt;
939  unsigned StartIdx, EndIdx;
940 
941  // This rotation amount assumes that the lower 32 bits of the quantity are
942  // replicated in the high 32 bits by the rotation operator (which is done
943  // by rlwinm and friends in 64-bit mode).
944  bool Repl32;
945  // Did converting to Repl32 == true change the rotation factor? If it did,
946  // it decreased it by 32.
947  bool Repl32CR;
948  // Was this group coalesced after setting Repl32 to true?
949  bool Repl32Coalesced;
950 
951  BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
952  : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
953  Repl32Coalesced(false) {
954  DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
955  " [" << S << ", " << E << "]\n");
956  }
957  };
958 
959  // Information on each (Value, RLAmt) pair (like the number of groups
960  // associated with each) used to choose the lowering method.
961  struct ValueRotInfo {
962  SDValue V;
963  unsigned RLAmt = std::numeric_limits<unsigned>::max();
964  unsigned NumGroups = 0;
965  unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
966  bool Repl32 = false;
967 
968  ValueRotInfo() = default;
969 
970  // For sorting (in reverse order) by NumGroups, and then by
971  // FirstGroupStartIdx.
972  bool operator < (const ValueRotInfo &Other) const {
973  // We need to sort so that the non-Repl32 come first because, when we're
974  // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
975  // masking operation.
976  if (Repl32 < Other.Repl32)
977  return true;
978  else if (Repl32 > Other.Repl32)
979  return false;
980  else if (NumGroups > Other.NumGroups)
981  return true;
982  else if (NumGroups < Other.NumGroups)
983  return false;
984  else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
985  return true;
986  return false;
987  }
988  };
989 
990  using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
991  using ValueBitsMemoizer =
993  ValueBitsMemoizer Memoizer;
994 
995  // Return a pair of bool and a SmallVector pointer to a memoization entry.
996  // The bool is true if something interesting was deduced, otherwise if we're
997  // providing only a generic representation of V (or something else likewise
998  // uninteresting for instruction selection) through the SmallVector.
999  std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1000  unsigned NumBits) {
1001  auto &ValueEntry = Memoizer[V];
1002  if (ValueEntry)
1003  return std::make_pair(ValueEntry->first, &ValueEntry->second);
1004  ValueEntry.reset(new ValueBitsMemoizedValue());
1005  bool &Interesting = ValueEntry->first;
1006  SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1007  Bits.resize(NumBits);
1008 
1009  switch (V.getOpcode()) {
1010  default: break;
1011  case ISD::ROTL:
1012  if (isa<ConstantSDNode>(V.getOperand(1))) {
1013  unsigned RotAmt = V.getConstantOperandVal(1);
1014 
1015  const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1016 
1017  for (unsigned i = 0; i < NumBits; ++i)
1018  Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1019 
1020  return std::make_pair(Interesting = true, &Bits);
1021  }
1022  break;
1023  case ISD::SHL:
1024  if (isa<ConstantSDNode>(V.getOperand(1))) {
1025  unsigned ShiftAmt = V.getConstantOperandVal(1);
1026 
1027  const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1028 
1029  for (unsigned i = ShiftAmt; i < NumBits; ++i)
1030  Bits[i] = LHSBits[i - ShiftAmt];
1031 
1032  for (unsigned i = 0; i < ShiftAmt; ++i)
1033  Bits[i] = ValueBit(ValueBit::ConstZero);
1034 
1035  return std::make_pair(Interesting = true, &Bits);
1036  }
1037  break;
1038  case ISD::SRL:
1039  if (isa<ConstantSDNode>(V.getOperand(1))) {
1040  unsigned ShiftAmt = V.getConstantOperandVal(1);
1041 
1042  const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1043 
1044  for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1045  Bits[i] = LHSBits[i + ShiftAmt];
1046 
1047  for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1048  Bits[i] = ValueBit(ValueBit::ConstZero);
1049 
1050  return std::make_pair(Interesting = true, &Bits);
1051  }
1052  break;
1053  case ISD::AND:
1054  if (isa<ConstantSDNode>(V.getOperand(1))) {
1055  uint64_t Mask = V.getConstantOperandVal(1);
1056 
1057  const SmallVector<ValueBit, 64> *LHSBits;
1058  // Mark this as interesting, only if the LHS was also interesting. This
1059  // prevents the overall procedure from matching a single immediate 'and'
1060  // (which is non-optimal because such an and might be folded with other
1061  // things if we don't select it here).
1062  std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1063 
1064  for (unsigned i = 0; i < NumBits; ++i)
1065  if (((Mask >> i) & 1) == 1)
1066  Bits[i] = (*LHSBits)[i];
1067  else
1068  Bits[i] = ValueBit(ValueBit::ConstZero);
1069 
1070  return std::make_pair(Interesting, &Bits);
1071  }
1072  break;
1073  case ISD::OR: {
1074  const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1075  const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1076 
1077  bool AllDisjoint = true;
1078  for (unsigned i = 0; i < NumBits; ++i)
1079  if (LHSBits[i].isZero())
1080  Bits[i] = RHSBits[i];
1081  else if (RHSBits[i].isZero())
1082  Bits[i] = LHSBits[i];
1083  else {
1084  AllDisjoint = false;
1085  break;
1086  }
1087 
1088  if (!AllDisjoint)
1089  break;
1090 
1091  return std::make_pair(Interesting = true, &Bits);
1092  }
1093  }
1094 
1095  for (unsigned i = 0; i < NumBits; ++i)
1096  Bits[i] = ValueBit(V, i);
1097 
1098  return std::make_pair(Interesting = false, &Bits);
1099  }
1100 
1101  // For each value (except the constant ones), compute the left-rotate amount
1102  // to get it from its original to final position.
1103  void computeRotationAmounts() {
1104  HasZeros = false;
1105  RLAmt.resize(Bits.size());
1106  for (unsigned i = 0; i < Bits.size(); ++i)
1107  if (Bits[i].hasValue()) {
1108  unsigned VBI = Bits[i].getValueBitIndex();
1109  if (i >= VBI)
1110  RLAmt[i] = i - VBI;
1111  else
1112  RLAmt[i] = Bits.size() - (VBI - i);
1113  } else if (Bits[i].isZero()) {
1114  HasZeros = true;
1115  RLAmt[i] = UINT32_MAX;
1116  } else {
1117  llvm_unreachable("Unknown value bit type");
1118  }
1119  }
1120 
1121  // Collect groups of consecutive bits with the same underlying value and
1122  // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1123  // they break up groups.
1124  void collectBitGroups(bool LateMask) {
1125  BitGroups.clear();
1126 
1127  unsigned LastRLAmt = RLAmt[0];
1128  SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1129  unsigned LastGroupStartIdx = 0;
1130  for (unsigned i = 1; i < Bits.size(); ++i) {
1131  unsigned ThisRLAmt = RLAmt[i];
1132  SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1133  if (LateMask && !ThisValue) {
1134  ThisValue = LastValue;
1135  ThisRLAmt = LastRLAmt;
1136  // If we're doing late masking, then the first bit group always starts
1137  // at zero (even if the first bits were zero).
1138  if (BitGroups.empty())
1139  LastGroupStartIdx = 0;
1140  }
1141 
1142  // If this bit has the same underlying value and the same rotate factor as
1143  // the last one, then they're part of the same group.
1144  if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1145  continue;
1146 
1147  if (LastValue.getNode())
1148  BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1149  i-1));
1150  LastRLAmt = ThisRLAmt;
1151  LastValue = ThisValue;
1152  LastGroupStartIdx = i;
1153  }
1154  if (LastValue.getNode())
1155  BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1156  Bits.size()-1));
1157 
1158  if (BitGroups.empty())
1159  return;
1160 
1161  // We might be able to combine the first and last groups.
1162  if (BitGroups.size() > 1) {
1163  // If the first and last groups are the same, then remove the first group
1164  // in favor of the last group, making the ending index of the last group
1165  // equal to the ending index of the to-be-removed first group.
1166  if (BitGroups[0].StartIdx == 0 &&
1167  BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1168  BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1169  BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1170  DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1171  BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1172  BitGroups.erase(BitGroups.begin());
1173  }
1174  }
1175  }
1176 
1177  // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1178  // associated with each. If there is a degeneracy, pick the one that occurs
1179  // first (in the final value).
1180  void collectValueRotInfo() {
1181  ValueRots.clear();
1182 
1183  for (auto &BG : BitGroups) {
1184  unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1185  ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1186  VRI.V = BG.V;
1187  VRI.RLAmt = BG.RLAmt;
1188  VRI.Repl32 = BG.Repl32;
1189  VRI.NumGroups += 1;
1190  VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1191  }
1192 
1193  // Now that we've collected the various ValueRotInfo instances, we need to
1194  // sort them.
1195  ValueRotsVec.clear();
1196  for (auto &I : ValueRots) {
1197  ValueRotsVec.push_back(I.second);
1198  }
1199  std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1200  }
1201 
1202  // In 64-bit mode, rlwinm and friends have a rotation operator that
1203  // replicates the low-order 32 bits into the high-order 32-bits. The mask
1204  // indices of these instructions can only be in the lower 32 bits, so they
1205  // can only represent some 64-bit bit groups. However, when they can be used,
1206  // the 32-bit replication can be used to represent, as a single bit group,
1207  // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1208  // groups when possible. Returns true if any of the bit groups were
1209  // converted.
1210  void assignRepl32BitGroups() {
1211  // If we have bits like this:
1212  //
1213  // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1214  // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1215  // Groups: | RLAmt = 8 | RLAmt = 40 |
1216  //
1217  // But, making use of a 32-bit operation that replicates the low-order 32
1218  // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1219  // of 8.
1220 
1221  auto IsAllLow32 = [this](BitGroup & BG) {
1222  if (BG.StartIdx <= BG.EndIdx) {
1223  for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1224  if (!Bits[i].hasValue())
1225  continue;
1226  if (Bits[i].getValueBitIndex() >= 32)
1227  return false;
1228  }
1229  } else {
1230  for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1231  if (!Bits[i].hasValue())
1232  continue;
1233  if (Bits[i].getValueBitIndex() >= 32)
1234  return false;
1235  }
1236  for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1237  if (!Bits[i].hasValue())
1238  continue;
1239  if (Bits[i].getValueBitIndex() >= 32)
1240  return false;
1241  }
1242  }
1243 
1244  return true;
1245  };
1246 
1247  for (auto &BG : BitGroups) {
1248  if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1249  if (IsAllLow32(BG)) {
1250  if (BG.RLAmt >= 32) {
1251  BG.RLAmt -= 32;
1252  BG.Repl32CR = true;
1253  }
1254 
1255  BG.Repl32 = true;
1256 
1257  DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1258  BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1259  " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1260  }
1261  }
1262  }
1263 
1264  // Now walk through the bit groups, consolidating where possible.
1265  for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1266  // We might want to remove this bit group by merging it with the previous
1267  // group (which might be the ending group).
1268  auto IP = (I == BitGroups.begin()) ?
1269  std::prev(BitGroups.end()) : std::prev(I);
1270  if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1271  I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1272 
1273  DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1274  I->V.getNode() << " RLAmt = " << I->RLAmt <<
1275  " [" << I->StartIdx << ", " << I->EndIdx <<
1276  "] with group with range [" <<
1277  IP->StartIdx << ", " << IP->EndIdx << "]\n");
1278 
1279  IP->EndIdx = I->EndIdx;
1280  IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1281  IP->Repl32Coalesced = true;
1282  I = BitGroups.erase(I);
1283  continue;
1284  } else {
1285  // There is a special case worth handling: If there is a single group
1286  // covering the entire upper 32 bits, and it can be merged with both
1287  // the next and previous groups (which might be the same group), then
1288  // do so. If it is the same group (so there will be only one group in
1289  // total), then we need to reverse the order of the range so that it
1290  // covers the entire 64 bits.
1291  if (I->StartIdx == 32 && I->EndIdx == 63) {
1292  assert(std::next(I) == BitGroups.end() &&
1293  "bit group ends at index 63 but there is another?");
1294  auto IN = BitGroups.begin();
1295 
1296  if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1297  (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1298  IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1299  IsAllLow32(*I)) {
1300 
1301  DEBUG(dbgs() << "\tcombining bit group for " <<
1302  I->V.getNode() << " RLAmt = " << I->RLAmt <<
1303  " [" << I->StartIdx << ", " << I->EndIdx <<
1304  "] with 32-bit replicated groups with ranges [" <<
1305  IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1306  IN->StartIdx << ", " << IN->EndIdx << "]\n");
1307 
1308  if (IP == IN) {
1309  // There is only one other group; change it to cover the whole
1310  // range (backward, so that it can still be Repl32 but cover the
1311  // whole 64-bit range).
1312  IP->StartIdx = 31;
1313  IP->EndIdx = 30;
1314  IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1315  IP->Repl32Coalesced = true;
1316  I = BitGroups.erase(I);
1317  } else {
1318  // There are two separate groups, one before this group and one
1319  // after us (at the beginning). We're going to remove this group,
1320  // but also the group at the very beginning.
1321  IP->EndIdx = IN->EndIdx;
1322  IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1323  IP->Repl32Coalesced = true;
1324  I = BitGroups.erase(I);
1325  BitGroups.erase(BitGroups.begin());
1326  }
1327 
1328  // This must be the last group in the vector (and we might have
1329  // just invalidated the iterator above), so break here.
1330  break;
1331  }
1332  }
1333  }
1334 
1335  ++I;
1336  }
1337  }
1338 
1339  SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1340  return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1341  }
1342 
1343  uint64_t getZerosMask() {
1344  uint64_t Mask = 0;
1345  for (unsigned i = 0; i < Bits.size(); ++i) {
1346  if (Bits[i].hasValue())
1347  continue;
1348  Mask |= (UINT64_C(1) << i);
1349  }
1350 
1351  return ~Mask;
1352  }
1353 
1354  // Depending on the number of groups for a particular value, it might be
1355  // better to rotate, mask explicitly (using andi/andis), and then or the
1356  // result. Select this part of the result first.
1357  void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1359  return;
1360 
1361  for (ValueRotInfo &VRI : ValueRotsVec) {
1362  unsigned Mask = 0;
1363  for (unsigned i = 0; i < Bits.size(); ++i) {
1364  if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1365  continue;
1366  if (RLAmt[i] != VRI.RLAmt)
1367  continue;
1368  Mask |= (1u << i);
1369  }
1370 
1371  // Compute the masks for andi/andis that would be necessary.
1372  unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1373  assert((ANDIMask != 0 || ANDISMask != 0) &&
1374  "No set bits in mask for value bit groups");
1375  bool NeedsRotate = VRI.RLAmt != 0;
1376 
1377  // We're trying to minimize the number of instructions. If we have one
1378  // group, using one of andi/andis can break even. If we have three
1379  // groups, we can use both andi and andis and break even (to use both
1380  // andi and andis we also need to or the results together). We need four
1381  // groups if we also need to rotate. To use andi/andis we need to do more
1382  // than break even because rotate-and-mask instructions tend to be easier
1383  // to schedule.
1384 
1385  // FIXME: We've biased here against using andi/andis, which is right for
1386  // POWER cores, but not optimal everywhere. For example, on the A2,
1387  // andi/andis have single-cycle latency whereas the rotate-and-mask
1388  // instructions take two cycles, and it would be better to bias toward
1389  // andi/andis in break-even cases.
1390 
1391  unsigned NumAndInsts = (unsigned) NeedsRotate +
1392  (unsigned) (ANDIMask != 0) +
1393  (unsigned) (ANDISMask != 0) +
1394  (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1395  (unsigned) (bool) Res;
1396 
1397  DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1398  " RL: " << VRI.RLAmt << ":" <<
1399  "\n\t\t\tisel using masking: " << NumAndInsts <<
1400  " using rotates: " << VRI.NumGroups << "\n");
1401 
1402  if (NumAndInsts >= VRI.NumGroups)
1403  continue;
1404 
1405  DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1406 
1407  if (InstCnt) *InstCnt += NumAndInsts;
1408 
1409  SDValue VRot;
1410  if (VRI.RLAmt) {
1411  SDValue Ops[] =
1412  { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1413  getI32Imm(31, dl) };
1414  VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1415  Ops), 0);
1416  } else {
1417  VRot = VRI.V;
1418  }
1419 
1420  SDValue ANDIVal, ANDISVal;
1421  if (ANDIMask != 0)
1422  ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1423  VRot, getI32Imm(ANDIMask, dl)), 0);
1424  if (ANDISMask != 0)
1425  ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1426  VRot, getI32Imm(ANDISMask, dl)), 0);
1427 
1428  SDValue TotalVal;
1429  if (!ANDIVal)
1430  TotalVal = ANDISVal;
1431  else if (!ANDISVal)
1432  TotalVal = ANDIVal;
1433  else
1434  TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1435  ANDIVal, ANDISVal), 0);
1436 
1437  if (!Res)
1438  Res = TotalVal;
1439  else
1440  Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1441  Res, TotalVal), 0);
1442 
1443  // Now, remove all groups with this underlying value and rotation
1444  // factor.
1445  eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1446  return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1447  });
1448  }
1449  }
1450 
1451  // Instruction selection for the 32-bit case.
1452  SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1453  SDLoc dl(N);
1454  SDValue Res;
1455 
1456  if (InstCnt) *InstCnt = 0;
1457 
1458  // Take care of cases that should use andi/andis first.
1459  SelectAndParts32(dl, Res, InstCnt);
1460 
1461  // If we've not yet selected a 'starting' instruction, and we have no zeros
1462  // to fill in, select the (Value, RLAmt) with the highest priority (largest
1463  // number of groups), and start with this rotated value.
1464  if ((!HasZeros || LateMask) && !Res) {
1465  ValueRotInfo &VRI = ValueRotsVec[0];
1466  if (VRI.RLAmt) {
1467  if (InstCnt) *InstCnt += 1;
1468  SDValue Ops[] =
1469  { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1470  getI32Imm(31, dl) };
1471  Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1472  0);
1473  } else {
1474  Res = VRI.V;
1475  }
1476 
1477  // Now, remove all groups with this underlying value and rotation factor.
1478  eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1479  return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1480  });
1481  }
1482 
1483  if (InstCnt) *InstCnt += BitGroups.size();
1484 
1485  // Insert the other groups (one at a time).
1486  for (auto &BG : BitGroups) {
1487  if (!Res) {
1488  SDValue Ops[] =
1489  { BG.V, getI32Imm(BG.RLAmt, dl),
1490  getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1491  getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1492  Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1493  } else {
1494  SDValue Ops[] =
1495  { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1496  getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1497  getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1498  Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1499  }
1500  }
1501 
1502  if (LateMask) {
1503  unsigned Mask = (unsigned) getZerosMask();
1504 
1505  unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1506  assert((ANDIMask != 0 || ANDISMask != 0) &&
1507  "No set bits in zeros mask?");
1508 
1509  if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1510  (unsigned) (ANDISMask != 0) +
1511  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1512 
1513  SDValue ANDIVal, ANDISVal;
1514  if (ANDIMask != 0)
1515  ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1516  Res, getI32Imm(ANDIMask, dl)), 0);
1517  if (ANDISMask != 0)
1518  ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1519  Res, getI32Imm(ANDISMask, dl)), 0);
1520 
1521  if (!ANDIVal)
1522  Res = ANDISVal;
1523  else if (!ANDISVal)
1524  Res = ANDIVal;
1525  else
1526  Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1527  ANDIVal, ANDISVal), 0);
1528  }
1529 
1530  return Res.getNode();
1531  }
1532 
1533  unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1534  unsigned MaskStart, unsigned MaskEnd,
1535  bool IsIns) {
1536  // In the notation used by the instructions, 'start' and 'end' are reversed
1537  // because bits are counted from high to low order.
1538  unsigned InstMaskStart = 64 - MaskEnd - 1,
1539  InstMaskEnd = 64 - MaskStart - 1;
1540 
1541  if (Repl32)
1542  return 1;
1543 
1544  if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1545  InstMaskEnd == 63 - RLAmt)
1546  return 1;
1547 
1548  return 2;
1549  }
1550 
1551  // For 64-bit values, not all combinations of rotates and masks are
1552  // available. Produce one if it is available.
1553  SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1554  bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1555  unsigned *InstCnt = nullptr) {
1556  // In the notation used by the instructions, 'start' and 'end' are reversed
1557  // because bits are counted from high to low order.
1558  unsigned InstMaskStart = 64 - MaskEnd - 1,
1559  InstMaskEnd = 64 - MaskStart - 1;
1560 
1561  if (InstCnt) *InstCnt += 1;
1562 
1563  if (Repl32) {
1564  // This rotation amount assumes that the lower 32 bits of the quantity
1565  // are replicated in the high 32 bits by the rotation operator (which is
1566  // done by rlwinm and friends).
1567  assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1568  assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1569  SDValue Ops[] =
1570  { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1571  getI32Imm(InstMaskEnd - 32, dl) };
1572  return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1573  Ops), 0);
1574  }
1575 
1576  if (InstMaskEnd == 63) {
1577  SDValue Ops[] =
1578  { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1579  return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1580  }
1581 
1582  if (InstMaskStart == 0) {
1583  SDValue Ops[] =
1584  { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1585  return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1586  }
1587 
1588  if (InstMaskEnd == 63 - RLAmt) {
1589  SDValue Ops[] =
1590  { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1591  return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1592  }
1593 
1594  // We cannot do this with a single instruction, so we'll use two. The
1595  // problem is that we're not free to choose both a rotation amount and mask
1596  // start and end independently. We can choose an arbitrary mask start and
1597  // end, but then the rotation amount is fixed. Rotation, however, can be
1598  // inverted, and so by applying an "inverse" rotation first, we can get the
1599  // desired result.
1600  if (InstCnt) *InstCnt += 1;
1601 
1602  // The rotation mask for the second instruction must be MaskStart.
1603  unsigned RLAmt2 = MaskStart;
1604  // The first instruction must rotate V so that the overall rotation amount
1605  // is RLAmt.
1606  unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1607  if (RLAmt1)
1608  V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1609  return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1610  }
1611 
1612  // For 64-bit values, not all combinations of rotates and masks are
1613  // available. Produce a rotate-mask-and-insert if one is available.
1614  SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1615  unsigned RLAmt, bool Repl32, unsigned MaskStart,
1616  unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1617  // In the notation used by the instructions, 'start' and 'end' are reversed
1618  // because bits are counted from high to low order.
1619  unsigned InstMaskStart = 64 - MaskEnd - 1,
1620  InstMaskEnd = 64 - MaskStart - 1;
1621 
1622  if (InstCnt) *InstCnt += 1;
1623 
1624  if (Repl32) {
1625  // This rotation amount assumes that the lower 32 bits of the quantity
1626  // are replicated in the high 32 bits by the rotation operator (which is
1627  // done by rlwinm and friends).
1628  assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1629  assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1630  SDValue Ops[] =
1631  { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1632  getI32Imm(InstMaskEnd - 32, dl) };
1633  return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1634  Ops), 0);
1635  }
1636 
1637  if (InstMaskEnd == 63 - RLAmt) {
1638  SDValue Ops[] =
1639  { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1640  return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1641  }
1642 
1643  // We cannot do this with a single instruction, so we'll use two. The
1644  // problem is that we're not free to choose both a rotation amount and mask
1645  // start and end independently. We can choose an arbitrary mask start and
1646  // end, but then the rotation amount is fixed. Rotation, however, can be
1647  // inverted, and so by applying an "inverse" rotation first, we can get the
1648  // desired result.
1649  if (InstCnt) *InstCnt += 1;
1650 
1651  // The rotation mask for the second instruction must be MaskStart.
1652  unsigned RLAmt2 = MaskStart;
1653  // The first instruction must rotate V so that the overall rotation amount
1654  // is RLAmt.
1655  unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1656  if (RLAmt1)
1657  V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1658  return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1659  }
1660 
1661  void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1663  return;
1664 
1665  // The idea here is the same as in the 32-bit version, but with additional
1666  // complications from the fact that Repl32 might be true. Because we
1667  // aggressively convert bit groups to Repl32 form (which, for small
1668  // rotation factors, involves no other change), and then coalesce, it might
1669  // be the case that a single 64-bit masking operation could handle both
1670  // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1671  // form allowed coalescing, then we must use a 32-bit rotaton in order to
1672  // completely capture the new combined bit group.
1673 
1674  for (ValueRotInfo &VRI : ValueRotsVec) {
1675  uint64_t Mask = 0;
1676 
1677  // We need to add to the mask all bits from the associated bit groups.
1678  // If Repl32 is false, we need to add bits from bit groups that have
1679  // Repl32 true, but are trivially convertable to Repl32 false. Such a
1680  // group is trivially convertable if it overlaps only with the lower 32
1681  // bits, and the group has not been coalesced.
1682  auto MatchingBG = [VRI](const BitGroup &BG) {
1683  if (VRI.V != BG.V)
1684  return false;
1685 
1686  unsigned EffRLAmt = BG.RLAmt;
1687  if (!VRI.Repl32 && BG.Repl32) {
1688  if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1689  !BG.Repl32Coalesced) {
1690  if (BG.Repl32CR)
1691  EffRLAmt += 32;
1692  } else {
1693  return false;
1694  }
1695  } else if (VRI.Repl32 != BG.Repl32) {
1696  return false;
1697  }
1698 
1699  return VRI.RLAmt == EffRLAmt;
1700  };
1701 
1702  for (auto &BG : BitGroups) {
1703  if (!MatchingBG(BG))
1704  continue;
1705 
1706  if (BG.StartIdx <= BG.EndIdx) {
1707  for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1708  Mask |= (UINT64_C(1) << i);
1709  } else {
1710  for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1711  Mask |= (UINT64_C(1) << i);
1712  for (unsigned i = 0; i <= BG.EndIdx; ++i)
1713  Mask |= (UINT64_C(1) << i);
1714  }
1715  }
1716 
1717  // We can use the 32-bit andi/andis technique if the mask does not
1718  // require any higher-order bits. This can save an instruction compared
1719  // to always using the general 64-bit technique.
1720  bool Use32BitInsts = isUInt<32>(Mask);
1721  // Compute the masks for andi/andis that would be necessary.
1722  unsigned ANDIMask = (Mask & UINT16_MAX),
1723  ANDISMask = (Mask >> 16) & UINT16_MAX;
1724 
1725  bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1726 
1727  unsigned NumAndInsts = (unsigned) NeedsRotate +
1728  (unsigned) (bool) Res;
1729  if (Use32BitInsts)
1730  NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1731  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1732  else
1733  NumAndInsts += getInt64Count(Mask) + /* and */ 1;
1734 
1735  unsigned NumRLInsts = 0;
1736  bool FirstBG = true;
1737  bool MoreBG = false;
1738  for (auto &BG : BitGroups) {
1739  if (!MatchingBG(BG)) {
1740  MoreBG = true;
1741  continue;
1742  }
1743  NumRLInsts +=
1744  SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1745  !FirstBG);
1746  FirstBG = false;
1747  }
1748 
1749  DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1750  " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1751  "\n\t\t\tisel using masking: " << NumAndInsts <<
1752  " using rotates: " << NumRLInsts << "\n");
1753 
1754  // When we'd use andi/andis, we bias toward using the rotates (andi only
1755  // has a record form, and is cracked on POWER cores). However, when using
1756  // general 64-bit constant formation, bias toward the constant form,
1757  // because that exposes more opportunities for CSE.
1758  if (NumAndInsts > NumRLInsts)
1759  continue;
1760  // When merging multiple bit groups, instruction or is used.
1761  // But when rotate is used, rldimi can inert the rotated value into any
1762  // register, so instruction or can be avoided.
1763  if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
1764  continue;
1765 
1766  DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1767 
1768  if (InstCnt) *InstCnt += NumAndInsts;
1769 
1770  SDValue VRot;
1771  // We actually need to generate a rotation if we have a non-zero rotation
1772  // factor or, in the Repl32 case, if we care about any of the
1773  // higher-order replicated bits. In the latter case, we generate a mask
1774  // backward so that it actually includes the entire 64 bits.
1775  if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1776  VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1777  VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1778  else
1779  VRot = VRI.V;
1780 
1781  SDValue TotalVal;
1782  if (Use32BitInsts) {
1783  assert((ANDIMask != 0 || ANDISMask != 0) &&
1784  "No set bits in mask when using 32-bit ands for 64-bit value");
1785 
1786  SDValue ANDIVal, ANDISVal;
1787  if (ANDIMask != 0)
1788  ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1789  VRot, getI32Imm(ANDIMask, dl)), 0);
1790  if (ANDISMask != 0)
1791  ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1792  VRot, getI32Imm(ANDISMask, dl)), 0);
1793 
1794  if (!ANDIVal)
1795  TotalVal = ANDISVal;
1796  else if (!ANDISVal)
1797  TotalVal = ANDIVal;
1798  else
1799  TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1800  ANDIVal, ANDISVal), 0);
1801  } else {
1802  TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1803  TotalVal =
1804  SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1805  VRot, TotalVal), 0);
1806  }
1807 
1808  if (!Res)
1809  Res = TotalVal;
1810  else
1811  Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1812  Res, TotalVal), 0);
1813 
1814  // Now, remove all groups with this underlying value and rotation
1815  // factor.
1816  eraseMatchingBitGroups(MatchingBG);
1817  }
1818  }
1819 
1820  // Instruction selection for the 64-bit case.
1821  SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1822  SDLoc dl(N);
1823  SDValue Res;
1824 
1825  if (InstCnt) *InstCnt = 0;
1826 
1827  // Take care of cases that should use andi/andis first.
1828  SelectAndParts64(dl, Res, InstCnt);
1829 
1830  // If we've not yet selected a 'starting' instruction, and we have no zeros
1831  // to fill in, select the (Value, RLAmt) with the highest priority (largest
1832  // number of groups), and start with this rotated value.
1833  if ((!HasZeros || LateMask) && !Res) {
1834  // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1835  // groups will come first, and so the VRI representing the largest number
1836  // of groups might not be first (it might be the first Repl32 groups).
1837  unsigned MaxGroupsIdx = 0;
1838  if (!ValueRotsVec[0].Repl32) {
1839  for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1840  if (ValueRotsVec[i].Repl32) {
1841  if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1842  MaxGroupsIdx = i;
1843  break;
1844  }
1845  }
1846 
1847  ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1848  bool NeedsRotate = false;
1849  if (VRI.RLAmt) {
1850  NeedsRotate = true;
1851  } else if (VRI.Repl32) {
1852  for (auto &BG : BitGroups) {
1853  if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1854  BG.Repl32 != VRI.Repl32)
1855  continue;
1856 
1857  // We don't need a rotate if the bit group is confined to the lower
1858  // 32 bits.
1859  if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1860  continue;
1861 
1862  NeedsRotate = true;
1863  break;
1864  }
1865  }
1866 
1867  if (NeedsRotate)
1868  Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1869  VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1870  InstCnt);
1871  else
1872  Res = VRI.V;
1873 
1874  // Now, remove all groups with this underlying value and rotation factor.
1875  if (Res)
1876  eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1877  return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1878  BG.Repl32 == VRI.Repl32;
1879  });
1880  }
1881 
1882  // Because 64-bit rotates are more flexible than inserts, we might have a
1883  // preference regarding which one we do first (to save one instruction).
1884  if (!Res)
1885  for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1886  if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1887  false) <
1888  SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1889  true)) {
1890  if (I != BitGroups.begin()) {
1891  BitGroup BG = *I;
1892  BitGroups.erase(I);
1893  BitGroups.insert(BitGroups.begin(), BG);
1894  }
1895 
1896  break;
1897  }
1898  }
1899 
1900  // Insert the other groups (one at a time).
1901  for (auto &BG : BitGroups) {
1902  if (!Res)
1903  Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1904  BG.EndIdx, InstCnt);
1905  else
1906  Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1907  BG.StartIdx, BG.EndIdx, InstCnt);
1908  }
1909 
1910  if (LateMask) {
1911  uint64_t Mask = getZerosMask();
1912 
1913  // We can use the 32-bit andi/andis technique if the mask does not
1914  // require any higher-order bits. This can save an instruction compared
1915  // to always using the general 64-bit technique.
1916  bool Use32BitInsts = isUInt<32>(Mask);
1917  // Compute the masks for andi/andis that would be necessary.
1918  unsigned ANDIMask = (Mask & UINT16_MAX),
1919  ANDISMask = (Mask >> 16) & UINT16_MAX;
1920 
1921  if (Use32BitInsts) {
1922  assert((ANDIMask != 0 || ANDISMask != 0) &&
1923  "No set bits in mask when using 32-bit ands for 64-bit value");
1924 
1925  if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1926  (unsigned) (ANDISMask != 0) +
1927  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1928 
1929  SDValue ANDIVal, ANDISVal;
1930  if (ANDIMask != 0)
1931  ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1932  Res, getI32Imm(ANDIMask, dl)), 0);
1933  if (ANDISMask != 0)
1934  ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1935  Res, getI32Imm(ANDISMask, dl)), 0);
1936 
1937  if (!ANDIVal)
1938  Res = ANDISVal;
1939  else if (!ANDISVal)
1940  Res = ANDIVal;
1941  else
1942  Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1943  ANDIVal, ANDISVal), 0);
1944  } else {
1945  if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1;
1946 
1947  SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1948  Res =
1949  SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1950  Res, MaskVal), 0);
1951  }
1952  }
1953 
1954  return Res.getNode();
1955  }
1956 
1957  SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1958  // Fill in BitGroups.
1959  collectBitGroups(LateMask);
1960  if (BitGroups.empty())
1961  return nullptr;
1962 
1963  // For 64-bit values, figure out when we can use 32-bit instructions.
1964  if (Bits.size() == 64)
1965  assignRepl32BitGroups();
1966 
1967  // Fill in ValueRotsVec.
1968  collectValueRotInfo();
1969 
1970  if (Bits.size() == 32) {
1971  return Select32(N, LateMask, InstCnt);
1972  } else {
1973  assert(Bits.size() == 64 && "Not 64 bits here?");
1974  return Select64(N, LateMask, InstCnt);
1975  }
1976 
1977  return nullptr;
1978  }
1979 
1980  void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1981  BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
1982  }
1983 
1985 
1986  bool HasZeros;
1988 
1989  SmallVector<BitGroup, 16> BitGroups;
1990 
1991  DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1992  SmallVector<ValueRotInfo, 16> ValueRotsVec;
1993 
1994  SelectionDAG *CurDAG;
1995 
1996 public:
1997  BitPermutationSelector(SelectionDAG *DAG)
1998  : CurDAG(DAG) {}
1999 
2000  // Here we try to match complex bit permutations into a set of
2001  // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2002  // known to produce optimial code for common cases (like i32 byte swapping).
2003  SDNode *Select(SDNode *N) {
2004  Memoizer.clear();
2005  auto Result =
2006  getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2007  if (!Result.first)
2008  return nullptr;
2009  Bits = std::move(*Result.second);
2010 
2011  DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2012  " selection for: ");
2013  DEBUG(N->dump(CurDAG));
2014 
2015  // Fill it RLAmt and set HasZeros.
2016  computeRotationAmounts();
2017 
2018  if (!HasZeros)
2019  return Select(N, false);
2020 
2021  // We currently have two techniques for handling results with zeros: early
2022  // masking (the default) and late masking. Late masking is sometimes more
2023  // efficient, but because the structure of the bit groups is different, it
2024  // is hard to tell without generating both and comparing the results. With
2025  // late masking, we ignore zeros in the resulting value when inserting each
2026  // set of bit groups, and then mask in the zeros at the end. With early
2027  // masking, we only insert the non-zero parts of the result at every step.
2028 
2029  unsigned InstCnt, InstCntLateMask;
2030  DEBUG(dbgs() << "\tEarly masking:\n");
2031  SDNode *RN = Select(N, false, &InstCnt);
2032  DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2033 
2034  DEBUG(dbgs() << "\tLate masking:\n");
2035  SDNode *RNLM = Select(N, true, &InstCntLateMask);
2036  DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
2037  " instructions\n");
2038 
2039  if (InstCnt <= InstCntLateMask) {
2040  DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2041  return RN;
2042  }
2043 
2044  DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2045  return RNLM;
2046  }
2047 };
2048 
2049 } // end anonymous namespace
2050 
2051 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
2052  if (N->getValueType(0) != MVT::i32 &&
2053  N->getValueType(0) != MVT::i64)
2054  return false;
2055 
2056  if (!UseBitPermRewriter)
2057  return false;
2058 
2059  switch (N->getOpcode()) {
2060  default: break;
2061  case ISD::ROTL:
2062  case ISD::SHL:
2063  case ISD::SRL:
2064  case ISD::AND:
2065  case ISD::OR: {
2066  BitPermutationSelector BPS(CurDAG);
2067  if (SDNode *New = BPS.Select(N)) {
2068  ReplaceNode(N, New);
2069  return true;
2070  }
2071  return false;
2072  }
2073  }
2074 
2075  return false;
2076 }
2077 
2078 /// SelectCC - Select a comparison of the specified values with the specified
2079 /// condition code, returning the CR# of the expression.
2080 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2081  const SDLoc &dl) {
2082  // Always select the LHS.
2083  unsigned Opc;
2084 
2085  if (LHS.getValueType() == MVT::i32) {
2086  unsigned Imm;
2087  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2088  if (isInt32Immediate(RHS, Imm)) {
2089  // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2090  if (isUInt<16>(Imm))
2091  return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2092  getI32Imm(Imm & 0xFFFF, dl)),
2093  0);
2094  // If this is a 16-bit signed immediate, fold it.
2095  if (isInt<16>((int)Imm))
2096  return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2097  getI32Imm(Imm & 0xFFFF, dl)),
2098  0);
2099 
2100  // For non-equality comparisons, the default code would materialize the
2101  // constant, then compare against it, like this:
2102  // lis r2, 4660
2103  // ori r2, r2, 22136
2104  // cmpw cr0, r3, r2
2105  // Since we are just comparing for equality, we can emit this instead:
2106  // xoris r0,r3,0x1234
2107  // cmplwi cr0,r0,0x5678
2108  // beq cr0,L6
2109  SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2110  getI32Imm(Imm >> 16, dl)), 0);
2111  return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2112  getI32Imm(Imm & 0xFFFF, dl)), 0);
2113  }
2114  Opc = PPC::CMPLW;
2115  } else if (ISD::isUnsignedIntSetCC(CC)) {
2116  if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2117  return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2118  getI32Imm(Imm & 0xFFFF, dl)), 0);
2119  Opc = PPC::CMPLW;
2120  } else {
2121  int16_t SImm;
2122  if (isIntS16Immediate(RHS, SImm))
2123  return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2124  getI32Imm((int)SImm & 0xFFFF,
2125  dl)),
2126  0);
2127  Opc = PPC::CMPW;
2128  }
2129  } else if (LHS.getValueType() == MVT::i64) {
2130  uint64_t Imm;
2131  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2132  if (isInt64Immediate(RHS.getNode(), Imm)) {
2133  // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2134  if (isUInt<16>(Imm))
2135  return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2136  getI32Imm(Imm & 0xFFFF, dl)),
2137  0);
2138  // If this is a 16-bit signed immediate, fold it.
2139  if (isInt<16>(Imm))
2140  return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2141  getI32Imm(Imm & 0xFFFF, dl)),
2142  0);
2143 
2144  // For non-equality comparisons, the default code would materialize the
2145  // constant, then compare against it, like this:
2146  // lis r2, 4660
2147  // ori r2, r2, 22136
2148  // cmpd cr0, r3, r2
2149  // Since we are just comparing for equality, we can emit this instead:
2150  // xoris r0,r3,0x1234
2151  // cmpldi cr0,r0,0x5678
2152  // beq cr0,L6
2153  if (isUInt<32>(Imm)) {
2154  SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2155  getI64Imm(Imm >> 16, dl)), 0);
2156  return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2157  getI64Imm(Imm & 0xFFFF, dl)),
2158  0);
2159  }
2160  }
2161  Opc = PPC::CMPLD;
2162  } else if (ISD::isUnsignedIntSetCC(CC)) {
2163  if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2164  return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2165  getI64Imm(Imm & 0xFFFF, dl)), 0);
2166  Opc = PPC::CMPLD;
2167  } else {
2168  int16_t SImm;
2169  if (isIntS16Immediate(RHS, SImm))
2170  return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2171  getI64Imm(SImm & 0xFFFF, dl)),
2172  0);
2173  Opc = PPC::CMPD;
2174  }
2175  } else if (LHS.getValueType() == MVT::f32) {
2176  Opc = PPC::FCMPUS;
2177  } else {
2178  assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2179  Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2180  }
2181  return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2182 }
2183 
2185  switch (CC) {
2186  case ISD::SETUEQ:
2187  case ISD::SETONE:
2188  case ISD::SETOLE:
2189  case ISD::SETOGE:
2190  llvm_unreachable("Should be lowered by legalize!");
2191  default: llvm_unreachable("Unknown condition!");
2192  case ISD::SETOEQ:
2193  case ISD::SETEQ: return PPC::PRED_EQ;
2194  case ISD::SETUNE:
2195  case ISD::SETNE: return PPC::PRED_NE;
2196  case ISD::SETOLT:
2197  case ISD::SETLT: return PPC::PRED_LT;
2198  case ISD::SETULE:
2199  case ISD::SETLE: return PPC::PRED_LE;
2200  case ISD::SETOGT:
2201  case ISD::SETGT: return PPC::PRED_GT;
2202  case ISD::SETUGE:
2203  case ISD::SETGE: return PPC::PRED_GE;
2204  case ISD::SETO: return PPC::PRED_NU;
2205  case ISD::SETUO: return PPC::PRED_UN;
2206  // These two are invalid for floating point. Assume we have int.
2207  case ISD::SETULT: return PPC::PRED_LT;
2208  case ISD::SETUGT: return PPC::PRED_GT;
2209  }
2210 }
2211 
2212 /// getCRIdxForSetCC - Return the index of the condition register field
2213 /// associated with the SetCC condition, and whether or not the field is
2214 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2215 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2216  Invert = false;
2217  switch (CC) {
2218  default: llvm_unreachable("Unknown condition!");
2219  case ISD::SETOLT:
2220  case ISD::SETLT: return 0; // Bit #0 = SETOLT
2221  case ISD::SETOGT:
2222  case ISD::SETGT: return 1; // Bit #1 = SETOGT
2223  case ISD::SETOEQ:
2224  case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2225  case ISD::SETUO: return 3; // Bit #3 = SETUO
2226  case ISD::SETUGE:
2227  case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2228  case ISD::SETULE:
2229  case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2230  case ISD::SETUNE:
2231  case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2232  case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2233  case ISD::SETUEQ:
2234  case ISD::SETOGE:
2235  case ISD::SETOLE:
2236  case ISD::SETONE:
2237  llvm_unreachable("Invalid branch code: should be expanded by legalize");
2238  // These are invalid for floating point. Assume integer.
2239  case ISD::SETULT: return 0;
2240  case ISD::SETUGT: return 1;
2241  }
2242 }
2243 
2244 // getVCmpInst: return the vector compare instruction for the specified
2245 // vector type and condition code. Since this is for altivec specific code,
2246 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2247 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2248  bool HasVSX, bool &Swap, bool &Negate) {
2249  Swap = false;
2250  Negate = false;
2251 
2252  if (VecVT.isFloatingPoint()) {
2253  /* Handle some cases by swapping input operands. */
2254  switch (CC) {
2255  case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2256  case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2257  case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2258  case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2259  case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2260  case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2261  default: break;
2262  }
2263  /* Handle some cases by negating the result. */
2264  switch (CC) {
2265  case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2266  case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2267  case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2268  case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2269  default: break;
2270  }
2271  /* We have instructions implementing the remaining cases. */
2272  switch (CC) {
2273  case ISD::SETEQ:
2274  case ISD::SETOEQ:
2275  if (VecVT == MVT::v4f32)
2276  return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2277  else if (VecVT == MVT::v2f64)
2278  return PPC::XVCMPEQDP;
2279  break;
2280  case ISD::SETGT:
2281  case ISD::SETOGT:
2282  if (VecVT == MVT::v4f32)
2283  return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2284  else if (VecVT == MVT::v2f64)
2285  return PPC::XVCMPGTDP;
2286  break;
2287  case ISD::SETGE:
2288  case ISD::SETOGE:
2289  if (VecVT == MVT::v4f32)
2290  return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2291  else if (VecVT == MVT::v2f64)
2292  return PPC::XVCMPGEDP;
2293  break;
2294  default:
2295  break;
2296  }
2297  llvm_unreachable("Invalid floating-point vector compare condition");
2298  } else {
2299  /* Handle some cases by swapping input operands. */
2300  switch (CC) {
2301  case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2302  case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2303  case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2304  case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2305  default: break;
2306  }
2307  /* Handle some cases by negating the result. */
2308  switch (CC) {
2309  case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2310  case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2311  case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2312  case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2313  default: break;
2314  }
2315  /* We have instructions implementing the remaining cases. */
2316  switch (CC) {
2317  case ISD::SETEQ:
2318  case ISD::SETUEQ:
2319  if (VecVT == MVT::v16i8)
2320  return PPC::VCMPEQUB;
2321  else if (VecVT == MVT::v8i16)
2322  return PPC::VCMPEQUH;
2323  else if (VecVT == MVT::v4i32)
2324  return PPC::VCMPEQUW;
2325  else if (VecVT == MVT::v2i64)
2326  return PPC::VCMPEQUD;
2327  break;
2328  case ISD::SETGT:
2329  if (VecVT == MVT::v16i8)
2330  return PPC::VCMPGTSB;
2331  else if (VecVT == MVT::v8i16)
2332  return PPC::VCMPGTSH;
2333  else if (VecVT == MVT::v4i32)
2334  return PPC::VCMPGTSW;
2335  else if (VecVT == MVT::v2i64)
2336  return PPC::VCMPGTSD;
2337  break;
2338  case ISD::SETUGT:
2339  if (VecVT == MVT::v16i8)
2340  return PPC::VCMPGTUB;
2341  else if (VecVT == MVT::v8i16)
2342  return PPC::VCMPGTUH;
2343  else if (VecVT == MVT::v4i32)
2344  return PPC::VCMPGTUW;
2345  else if (VecVT == MVT::v2i64)
2346  return PPC::VCMPGTUD;
2347  break;
2348  default:
2349  break;
2350  }
2351  llvm_unreachable("Invalid integer vector compare condition");
2352  }
2353 }
2354 
2355 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
2356  SDLoc dl(N);
2357  unsigned Imm;
2358  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2359  EVT PtrVT =
2360  CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2361  bool isPPC64 = (PtrVT == MVT::i64);
2362 
2363  if (!PPCSubTarget->useCRBits() &&
2364  isInt32Immediate(N->getOperand(1), Imm)) {
2365  // We can codegen setcc op, imm very efficiently compared to a brcond.
2366  // Check for those cases here.
2367  // setcc op, 0
2368  if (Imm == 0) {
2369  SDValue Op = N->getOperand(0);
2370  switch (CC) {
2371  default: break;
2372  case ISD::SETEQ: {
2373  Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2374  SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2375  getI32Imm(31, dl) };
2376  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2377  return true;
2378  }
2379  case ISD::SETNE: {
2380  if (isPPC64) break;
2381  SDValue AD =
2382  SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2383  Op, getI32Imm(~0U, dl)), 0);
2384  CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
2385  return true;
2386  }
2387  case ISD::SETLT: {
2388  SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2389  getI32Imm(31, dl) };
2390  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2391  return true;
2392  }
2393  case ISD::SETGT: {
2394  SDValue T =
2395  SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2396  T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2397  SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2398  getI32Imm(31, dl) };
2399  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2400  return true;
2401  }
2402  }
2403  } else if (Imm == ~0U) { // setcc op, -1
2404  SDValue Op = N->getOperand(0);
2405  switch (CC) {
2406  default: break;
2407  case ISD::SETEQ:
2408  if (isPPC64) break;
2409  Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2410  Op, getI32Imm(1, dl)), 0);
2411  CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2412  SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2413  MVT::i32,
2414  getI32Imm(0, dl)),
2415  0), Op.getValue(1));
2416  return true;
2417  case ISD::SETNE: {
2418  if (isPPC64) break;
2419  Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2420  SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2421  Op, getI32Imm(~0U, dl));
2422  CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
2423  SDValue(AD, 1));
2424  return true;
2425  }
2426  case ISD::SETLT: {
2427  SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2428  getI32Imm(1, dl)), 0);
2429  SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2430  Op), 0);
2431  SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2432  getI32Imm(31, dl) };
2433  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2434  return true;
2435  }
2436  case ISD::SETGT: {
2437  SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2438  getI32Imm(31, dl) };
2439  Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2440  CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
2441  return true;
2442  }
2443  }
2444  }
2445  }
2446 
2447  SDValue LHS = N->getOperand(0);
2448  SDValue RHS = N->getOperand(1);
2449 
2450  // Altivec Vector compare instructions do not set any CR register by default and
2451  // vector compare operations return the same type as the operands.
2452  if (LHS.getValueType().isVector()) {
2453  if (PPCSubTarget->hasQPX())
2454  return false;
2455 
2456  EVT VecVT = LHS.getValueType();
2457  bool Swap, Negate;
2458  unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2459  PPCSubTarget->hasVSX(), Swap, Negate);
2460  if (Swap)
2461  std::swap(LHS, RHS);
2462 
2463  EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2464  if (Negate) {
2465  SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2466  CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
2467  ResVT, VCmp, VCmp);
2468  return true;
2469  }
2470 
2471  CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2472  return true;
2473  }
2474 
2475  if (PPCSubTarget->useCRBits())
2476  return false;
2477 
2478  bool Inv;
2479  unsigned Idx = getCRIdxForSetCC(CC, Inv);
2480  SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2481  SDValue IntCR;
2482 
2483  // Force the ccreg into CR7.
2484  SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2485 
2486  SDValue InFlag(nullptr, 0); // Null incoming flag value.
2487  CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2488  InFlag).getValue(1);
2489 
2490  IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2491  CCReg), 0);
2492 
2493  SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2494  getI32Imm(31, dl), getI32Imm(31, dl) };
2495  if (!Inv) {
2496  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2497  return true;
2498  }
2499 
2500  // Get the specified bit.
2501  SDValue Tmp =
2502  SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2503  CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2504  return true;
2505 }
2506 
2507 // Is this opcode a bitwise logical operation?
2508 static bool isLogicOp(unsigned Opc) {
2509  return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR;
2510 }
2511 
2512 /// If this node is a sign/zero extension of an integer comparison,
2513 /// it can usually be computed in GPR's rather than using comparison
2514 /// instructions and ISEL. We only do this on 64-bit targets for now
2515 /// as the code is specialized for 64-bit (it uses 64-bit instructions
2516 /// and assumes 64-bit registers).
2517 bool PPCDAGToDAGISel::tryEXTEND(SDNode *N) {
2518  if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2519  return false;
2520  assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2521  N->getOpcode() == ISD::SIGN_EXTEND) &&
2522  "Expecting a zero/sign extend node!");
2523 
2524  SDValue WideRes;
2525  // If we are zero-extending the result of a logical operation on i1
2526  // values, we can keep the values in GPRs.
2527  if (isLogicOp(N->getOperand(0).getOpcode()) &&
2528  N->getOperand(0).getValueType() == MVT::i1 &&
2529  N->getOpcode() == ISD::ZERO_EXTEND)
2530  WideRes = computeLogicOpInGPR(N->getOperand(0));
2531  else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2532  return false;
2533  else
2534  WideRes =
2535  getSETCCInGPR(N->getOperand(0),
2536  N->getOpcode() == ISD::SIGN_EXTEND ?
2537  SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2538 
2539  if (!WideRes)
2540  return false;
2541 
2542  SDLoc dl(N);
2543  bool Inputs32Bit = N->getOperand(0).getOperand(0).getValueType() == MVT::i32;
2544  bool Output32Bit = N->getValueType(0) == MVT::i32;
2545 
2546  NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2547  NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2548 
2549  SDValue ConvOp = WideRes;
2550  if (Inputs32Bit != Output32Bit)
2551  ConvOp = addExtOrTrunc(WideRes, Inputs32Bit ? ExtOrTruncConversion::Ext :
2552  ExtOrTruncConversion::Trunc);
2553  ReplaceNode(N, ConvOp.getNode());
2554 
2555  return true;
2556 }
2557 
2558 // Lower a logical operation on i1 values into a GPR sequence if possible.
2559 // The result can be kept in a GPR if requested.
2560 // Three types of inputs can be handled:
2561 // - SETCC
2562 // - TRUNCATE
2563 // - Logical operation (AND/OR/XOR)
2564 // There is also a special case that is handled (namely a complement operation
2565 // achieved with xor %a, -1).
2566 SDValue PPCDAGToDAGISel::computeLogicOpInGPR(SDValue LogicOp) {
2567  assert(isLogicOp(LogicOp.getOpcode()) &&
2568  "Can only handle logic operations here.");
2569  assert(LogicOp.getValueType() == MVT::i1 &&
2570  "Can only handle logic operations on i1 values here.");
2571  SDLoc dl(LogicOp);
2572  SDValue LHS, RHS;
2573 
2574  // Special case: xor %a, -1
2575  bool IsBitwiseNegation = isBitwiseNot(LogicOp);
2576 
2577  // Produces a GPR sequence for each operand of the binary logic operation.
2578  // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
2579  // the value in a GPR and for logic operations, it will recursively produce
2580  // a GPR sequence for the operation.
2581  auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
2582  unsigned OperandOpcode = Operand.getOpcode();
2583  if (OperandOpcode == ISD::SETCC)
2584  return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
2585  else if (OperandOpcode == ISD::TRUNCATE) {
2586  SDValue InputOp = Operand.getOperand(0);
2587  EVT InVT = InputOp.getValueType();
2588  return
2589  SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
2590  PPC::RLDICL, dl, InVT, InputOp,
2591  getI64Imm(0, dl), getI64Imm(63, dl)), 0);
2592  } else if (isLogicOp(OperandOpcode))
2593  return computeLogicOpInGPR(Operand);
2594  return SDValue();
2595  };
2596  LHS = getLogicOperand(LogicOp.getOperand(0));
2597  RHS = getLogicOperand(LogicOp.getOperand(1));
2598 
2599  // If a GPR sequence can't be produced for the LHS we can't proceed.
2600  // Not producing a GPR sequence for the RHS is only a problem if this isn't
2601  // a bitwise negation operation.
2602  if (!LHS || (!RHS && !IsBitwiseNegation))
2603  return SDValue();
2604 
2605  NumLogicOpsOnComparison++;
2606 
2607  // We will use the inputs as 64-bit values.
2608  if (LHS.getValueType() == MVT::i32)
2609  LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
2610  if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
2611  RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
2612 
2613  unsigned NewOpc;
2614  switch (LogicOp.getOpcode()) {
2615  default: llvm_unreachable("Unknown logic operation.");
2616  case ISD::AND: NewOpc = PPC::AND8; break;
2617  case ISD::OR: NewOpc = PPC::OR8; break;
2618  case ISD::XOR: NewOpc = PPC::XOR8; break;
2619  }
2620 
2621  if (IsBitwiseNegation) {
2622  RHS = getI64Imm(1, dl);
2623  NewOpc = PPC::XORI8;
2624  }
2625 
2626  return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
2627 
2628 }
2629 
2630 /// Try performing logical operations on results of comparisons in GPRs.
2631 /// It is typically preferred from a performance perspective over performing
2632 /// the operations on individual bits in the CR. We only do this on 64-bit
2633 /// targets for now as the code is specialized for 64-bit (it uses 64-bit
2634 /// instructions and assumes 64-bit registers).
2635 bool PPCDAGToDAGISel::tryLogicOpOfCompares(SDNode *N) {
2636  if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2637  return false;
2638  if (N->getValueType(0) != MVT::i1)
2639  return false;
2640  assert(isLogicOp(N->getOpcode()) &&
2641  "Expected a logic operation on setcc results.");
2642  SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2643  if (!LoweredLogical)
2644  return false;
2645 
2646  SDLoc dl(N);
2647  bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2648  unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2649  SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2650  SDValue LHS = LoweredLogical.getOperand(0);
2651  SDValue RHS = LoweredLogical.getOperand(1);
2652  SDValue WideOp;
2653  SDValue OpToConvToRecForm;
2654 
2655  // Look through any 32-bit to 64-bit implicit extend nodes to find the opcode
2656  // that is input to the XORI.
2657  if (IsBitwiseNegate &&
2658  LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
2659  OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
2660  else if (IsBitwiseNegate)
2661  // If the input to the XORI isn't an extension, that's what we're after.
2662  OpToConvToRecForm = LoweredLogical.getOperand(0);
2663  else
2664  // If this is not an XORI, it is a reg-reg logical op and we can convert it
2665  // to record-form.
2666  OpToConvToRecForm = LoweredLogical;
2667 
2668  // Get the record-form version of the node we're looking to use to get the
2669  // CR result from.
2670  uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
2671  int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
2672 
2673  // Convert the right node to record-form. This is either the logical we're
2674  // looking at or it is the input node to the negation (if we're looking at
2675  // a bitwise negation).
2676  if (NewOpc != -1 && IsBitwiseNegate) {
2677  // The input to the XORI has a record-form. Use it.
2678  assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
2679  "Expected a PPC::XORI8 only for bitwise negation.");
2680  // Emit the record-form instruction.
2681  std::vector<SDValue> Ops;
2682  for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
2683  Ops.push_back(OpToConvToRecForm.getOperand(i));
2684 
2685  WideOp =
2686  SDValue(CurDAG->getMachineNode(NewOpc, dl,
2687  OpToConvToRecForm.getValueType(),
2688  MVT::Glue, Ops), 0);
2689  } else {
2690  assert((NewOpc != -1 || !IsBitwiseNegate) &&
2691  "No record form available for AND8/OR8/XOR8?");
2692  WideOp =
2693  SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDIo8 : NewOpc, dl,
2694  MVT::i64, MVT::Glue, LHS, RHS), 0);
2695  }
2696 
2697  // Select this node to a single bit from CR0 set by the record-form node
2698  // just created. For bitwise negation, use the EQ bit which is the equivalent
2699  // of negating the result (i.e. it is a bit set when the result of the
2700  // operation is zero).
2701  SDValue SRIdxVal =
2702  CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
2703  SDValue CRBit =
2704  SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2705  MVT::i1, CR0Reg, SRIdxVal,
2706  WideOp.getValue(1)), 0);
2707  ReplaceNode(N, CRBit.getNode());
2708  return true;
2709 }
2710 
2711 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
2712 /// Useful when emitting comparison code for 32-bit values without using
2713 /// the compare instruction (which only considers the lower 32-bits).
2714 SDValue PPCDAGToDAGISel::signExtendInputIfNeeded(SDValue Input) {
2715  assert(Input.getValueType() == MVT::i32 &&
2716  "Can only sign-extend 32-bit values here.");
2717  unsigned Opc = Input.getOpcode();
2718 
2719  // The value was sign extended and then truncated to 32-bits. No need to
2720  // sign extend it again.
2721  if (Opc == ISD::TRUNCATE &&
2722  (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
2723  Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
2724  return Input;
2725 
2726  LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2727  // The input is a sign-extending load. No reason to sign-extend.
2728  if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
2729  return Input;
2730 
2731  ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2732  // We don't sign-extend constants and already sign-extended values.
2733  if (InputConst || Opc == ISD::AssertSext || Opc == ISD::SIGN_EXTEND_INREG ||
2734  Opc == ISD::SIGN_EXTEND)
2735  return Input;
2736 
2737  SDLoc dl(Input);
2738  SignExtensionsAdded++;
2739  return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32, dl, MVT::i32, Input), 0);
2740 }
2741 
2742 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
2743 /// Useful when emitting comparison code for 32-bit values without using
2744 /// the compare instruction (which only considers the lower 32-bits).
2745 SDValue PPCDAGToDAGISel::zeroExtendInputIfNeeded(SDValue Input) {
2746  assert(Input.getValueType() == MVT::i32 &&
2747  "Can only zero-extend 32-bit values here.");
2748  LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2749  unsigned Opc = Input.getOpcode();
2750 
2751  // No need to zero-extend loaded values (unless they're loaded with
2752  // a sign-extending load).
2753  if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
2754  return Input;
2755 
2756  ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2757  bool InputZExtConst = InputConst && InputConst->getSExtValue() >= 0;
2758  // An ISD::TRUNCATE will be lowered to an EXTRACT_SUBREG so we have
2759  // to conservatively actually clear the high bits. We also don't need to
2760  // zero-extend constants or values that are already zero-extended.
2761  if (InputZExtConst || Opc == ISD::AssertZext || Opc == ISD::ZERO_EXTEND)
2762  return Input;
2763 
2764  SDLoc dl(Input);
2765  ZeroExtensionsAdded++;
2766  return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32, Input,
2767  getI64Imm(0, dl), getI64Imm(32, dl)),
2768  0);
2769 }
2770 
2771 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of
2772 // course not actual zero/sign extensions that will generate machine code,
2773 // they're just a way to reinterpret a 32 bit value in a register as a
2774 // 64 bit value and vice-versa.
2775 SDValue PPCDAGToDAGISel::addExtOrTrunc(SDValue NatWidthRes,
2776  ExtOrTruncConversion Conv) {
2777  SDLoc dl(NatWidthRes);
2778 
2779  // For reinterpreting 32-bit values as 64 bit values, we generate
2780  // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
2781  if (Conv == ExtOrTruncConversion::Ext) {
2782  SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
2783  SDValue SubRegIdx =
2784  CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2785  return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
2786  ImDef, NatWidthRes, SubRegIdx), 0);
2787  }
2788 
2789  assert(Conv == ExtOrTruncConversion::Trunc &&
2790  "Unknown convertion between 32 and 64 bit values.");
2791  // For reinterpreting 64-bit values as 32-bit values, we just need to
2792  // EXTRACT_SUBREG (i.e. extract the low word).
2793  SDValue SubRegIdx =
2794  CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2795  return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
2796  NatWidthRes, SubRegIdx), 0);
2797 }
2798 
2799 /// Produces a zero-extended result of comparing two 32-bit values according to
2800 /// the passed condition code.
2801 SDValue PPCDAGToDAGISel::get32BitZExtCompare(SDValue LHS, SDValue RHS,
2802  ISD::CondCode CC,
2803  int64_t RHSValue, SDLoc dl) {
2804  bool IsRHSZero = RHSValue == 0;
2805  switch (CC) {
2806  default: return SDValue();
2807  case ISD::SETEQ: {
2808  // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
2809  // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
2810  SDValue Xor = IsRHSZero ? LHS :
2811  SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2812  SDValue Clz =
2813  SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2814  SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2815  getI32Imm(31, dl) };
2816  return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2817  ShiftOps), 0);
2818  }
2819  case ISD::SETNE: {
2820  // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
2821  // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
2822  SDValue Xor = IsRHSZero ? LHS :
2823  SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2824  SDValue Clz =
2825  SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2826  SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2827  getI32Imm(31, dl) };
2828  SDValue Shift =
2829  SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2830  return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2831  getI32Imm(1, dl)), 0);
2832  }
2833  }
2834 }
2835 
2836 /// Produces a sign-extended result of comparing two 32-bit values according to
2837 /// the passed condition code.
2838 SDValue PPCDAGToDAGISel::get32BitSExtCompare(SDValue LHS, SDValue RHS,
2839  ISD::CondCode CC,
2840  int64_t RHSValue, SDLoc dl) {
2841  bool IsRHSZero = RHSValue == 0;
2842  switch (CC) {
2843  default: return SDValue();
2844  case ISD::SETEQ: {
2845  // (sext (setcc %a, %b, seteq)) ->
2846  // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
2847  // (sext (setcc %a, 0, seteq)) ->
2848  // (ashr (shl (ctlz %a), 58), 63)
2849  SDValue CountInput = IsRHSZero ? LHS :
2850  SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2851  SDValue Cntlzw =
2852  SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
2853  SDValue SHLOps[] = { Cntlzw, getI32Imm(58, dl), getI32Imm(0, dl) };
2854  SDValue Sldi =
2855  SDValue(CurDAG->getMachineNode(PPC::RLDICR_32, dl, MVT::i32, SHLOps), 0);
2856  return SDValue(CurDAG->getMachineNode(PPC::SRADI_32, dl, MVT::i32, Sldi,
2857  getI32Imm(63, dl)), 0);
2858  }
2859  case ISD::SETNE: {
2860  // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
2861  // flip the bit, finally take 2's complement.
2862  // (sext (setcc %a, %b, setne)) ->
2863  // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
2864  // Same as above, but the first xor is not needed.
2865  // (sext (setcc %a, 0, setne)) ->
2866  // (neg (xor (lshr (ctlz %a), 5), 1))
2867  SDValue Xor = IsRHSZero ? LHS :
2868  SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2869  SDValue Clz =
2870  SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2871  SDValue ShiftOps[] =
2872  { Clz, getI32Imm(27, dl), getI32Imm(5, dl), getI32Imm(31, dl) };
2873  SDValue Shift =
2874  SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2875  SDValue Xori =
2876  SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2877  getI32Imm(1, dl)), 0);
2878  return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
2879  }
2880  }
2881 }
2882 
2883 /// Produces a zero-extended result of comparing two 64-bit values according to
2884 /// the passed condition code.
2885 SDValue PPCDAGToDAGISel::get64BitZExtCompare(SDValue LHS, SDValue RHS,
2886  ISD::CondCode CC,
2887  int64_t RHSValue, SDLoc dl) {
2888  bool IsRHSZero = RHSValue == 0;
2889  switch (CC) {
2890  default: return SDValue();
2891  case ISD::SETEQ: {
2892  // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
2893  // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
2894  SDValue Xor = IsRHSZero ? LHS :
2895  SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2896  SDValue Clz =
2897  SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
2898  return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
2899  getI64Imm(58, dl), getI64Imm(63, dl)),
2900  0);
2901  }
2902  }
2903 }
2904 
2905 /// Produces a sign-extended result of comparing two 64-bit values according to
2906 /// the passed condition code.
2907 SDValue PPCDAGToDAGISel::get64BitSExtCompare(SDValue LHS, SDValue RHS,
2908  ISD::CondCode CC,
2909  int64_t RHSValue, SDLoc dl) {
2910  bool IsRHSZero = RHSValue == 0;
2911  switch (CC) {
2912  default: return SDValue();
2913  case ISD::SETEQ: {
2914  // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
2915  // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
2916  // {addcz.reg, addcz.CA} = (addcarry %a, -1)
2917  // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
2918  SDValue AddInput = IsRHSZero ? LHS :
2919  SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2920  SDValue Addic =
2921  SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
2922  AddInput, getI32Imm(~0U, dl)), 0);
2923  return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
2924  Addic, Addic.getValue(1)), 0);
2925  }
2926  }
2927 }
2928 
2929 /// Does this SDValue have any uses for which keeping the value in a GPR is
2930 /// appropriate. This is meant to be used on values that have type i1 since
2931 /// it is somewhat meaningless to ask if values of other types can be kept in
2932 /// GPR's.
2934  assert(Compare.getOpcode() == ISD::SETCC &&
2935  "An ISD::SETCC node required here.");
2936 
2937  // For values that have a single use, the caller should obviously already have
2938  // checked if that use is an extending use. We check the other uses here.
2939  if (Compare.hasOneUse())
2940  return true;
2941  // We want the value in a GPR if it is being extended, used for a select, or
2942  // used in logical operations.
2943  for (auto CompareUse : Compare.getNode()->uses())
2944  if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
2945  CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
2946  CompareUse->getOpcode() != ISD::SELECT &&
2947  !isLogicOp(CompareUse->getOpcode())) {
2948  OmittedForNonExtendUses++;
2949  return false;
2950  }
2951  return true;
2952 }
2953 
2954 /// Returns an equivalent of a SETCC node but with the result the same width as
2955 /// the inputs. This can nalso be used for SELECT_CC if either the true or false
2956 /// values is a power of two while the other is zero.
2957 SDValue PPCDAGToDAGISel::getSETCCInGPR(SDValue Compare,
2958  SetccInGPROpts ConvOpts) {
2959  assert((Compare.getOpcode() == ISD::SETCC ||
2960  Compare.getOpcode() == ISD::SELECT_CC) &&
2961  "An ISD::SETCC node required here.");
2962 
2963  // Don't convert this comparison to a GPR sequence because there are uses
2964  // of the i1 result (i.e. uses that require the result in the CR).
2965  if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
2966  return SDValue();
2967 
2968  SDValue LHS = Compare.getOperand(0);
2969  SDValue RHS = Compare.getOperand(1);
2970 
2971  // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
2972  int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
2973  ISD::CondCode CC =
2974  cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
2975  EVT InputVT = LHS.getValueType();
2976  if (InputVT != MVT::i32 && InputVT != MVT::i64)
2977  return SDValue();
2978 
2979  if (ConvOpts == SetccInGPROpts::ZExtInvert ||
2980  ConvOpts == SetccInGPROpts::SExtInvert)
2981  CC = ISD::getSetCCInverse(CC, true);
2982 
2983  bool Inputs32Bit = InputVT == MVT::i32;
2984  if (ISD::isSignedIntSetCC(CC) && Inputs32Bit) {
2985  LHS = signExtendInputIfNeeded(LHS);
2986  RHS = signExtendInputIfNeeded(RHS);
2987  } else if (ISD::isUnsignedIntSetCC(CC) && Inputs32Bit) {
2988  LHS = zeroExtendInputIfNeeded(LHS);
2989  RHS = zeroExtendInputIfNeeded(RHS);
2990  }
2991 
2992  SDLoc dl(Compare);
2993  ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2994  int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
2995  bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
2996  ConvOpts == SetccInGPROpts::SExtInvert;
2997 
2998  if (IsSext && Inputs32Bit)
2999  return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3000  else if (Inputs32Bit)
3001  return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3002  else if (IsSext)
3003  return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3004  return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3005 }
3006 
3007 /// Does this node represent a load/store node whose address can be represented
3008 /// with a register plus an immediate that's a multiple of \p Val:
3009 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
3010  LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
3011  StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
3012  SDValue AddrOp;
3013  if (LDN)
3014  AddrOp = LDN->getOperand(1);
3015  else if (STN)
3016  AddrOp = STN->getOperand(2);
3017 
3018  short Imm = 0;
3019  if (AddrOp.getOpcode() == ISD::ADD)
3020  return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
3021 
3022  // If the address comes from the outside, the offset will be zero.
3023  return AddrOp.getOpcode() == ISD::CopyFromReg;
3024 }
3025 
3026 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
3027  // Transfer memoperands.
3029  MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
3030  cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
3031 }
3032 
3033 // Select - Convert the specified operand from a target-independent to a
3034 // target-specific node if it hasn't already been changed.
3036  SDLoc dl(N);
3037  if (N->isMachineOpcode()) {
3038  N->setNodeId(-1);
3039  return; // Already selected.
3040  }
3041 
3042  // In case any misguided DAG-level optimizations form an ADD with a
3043  // TargetConstant operand, crash here instead of miscompiling (by selecting
3044  // an r+r add instead of some kind of r+i add).
3045  if (N->getOpcode() == ISD::ADD &&
3047  llvm_unreachable("Invalid ADD with TargetConstant operand");
3048 
3049  // Try matching complex bit permutations before doing anything else.
3050  if (tryBitPermutation(N))
3051  return;
3052 
3053  switch (N->getOpcode()) {
3054  default: break;
3055 
3056  case ISD::Constant:
3057  if (N->getValueType(0) == MVT::i64) {
3058  ReplaceNode(N, getInt64(CurDAG, N));
3059  return;
3060  }
3061  break;
3062 
3063  case ISD::ZERO_EXTEND:
3064  case ISD::SIGN_EXTEND:
3065  if (tryEXTEND(N))
3066  return;
3067  break;
3068 
3069  case ISD::SETCC:
3070  if (trySETCC(N))
3071  return;
3072  break;
3073 
3074  case PPCISD::GlobalBaseReg:
3075  ReplaceNode(N, getGlobalBaseReg());
3076  return;
3077 
3078  case ISD::FrameIndex:
3079  selectFrameIndex(N, N);
3080  return;
3081 
3082  case PPCISD::MFOCRF: {
3083  SDValue InFlag = N->getOperand(1);
3084  ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
3085  N->getOperand(0), InFlag));
3086  return;
3087  }
3088 
3090  ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
3091  MVT::Other, N->getOperand(0)));
3092  return;
3093 
3094  case PPCISD::SRA_ADDZE: {
3095  SDValue N0 = N->getOperand(0);
3096  SDValue ShiftAmt =
3097  CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
3098  getConstantIntValue(), dl,
3099  N->getValueType(0));
3100  if (N->getValueType(0) == MVT::i64) {
3101  SDNode *Op =
3102  CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
3103  N0, ShiftAmt);
3104  CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
3105  SDValue(Op, 1));
3106  return;
3107  } else {
3108  assert(N->getValueType(0) == MVT::i32 &&
3109  "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
3110  SDNode *Op =
3111  CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
3112  N0, ShiftAmt);
3113  CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
3114  SDValue(Op, 1));
3115  return;
3116  }
3117  }
3118 
3119  case ISD::LOAD: {
3120  // Handle preincrement loads.
3121  LoadSDNode *LD = cast<LoadSDNode>(N);
3122  EVT LoadedVT = LD->getMemoryVT();
3123 
3124  // Normal loads are handled by code generated from the .td file.
3125  if (LD->getAddressingMode() != ISD::PRE_INC)
3126  break;
3127 
3128  SDValue Offset = LD->getOffset();
3129  if (Offset.getOpcode() == ISD::TargetConstant ||
3130  Offset.getOpcode() == ISD::TargetGlobalAddress) {
3131 
3132  unsigned Opcode;
3133  bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3134  if (LD->getValueType(0) != MVT::i64) {
3135  // Handle PPC32 integer and normal FP loads.
3136  assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3137  switch (LoadedVT.getSimpleVT().SimpleTy) {
3138  default: llvm_unreachable("Invalid PPC load type!");
3139  case MVT::f64: Opcode = PPC::LFDU; break;
3140  case MVT::f32: Opcode = PPC::LFSU; break;
3141  case MVT::i32: Opcode = PPC::LWZU; break;
3142  case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
3143  case MVT::i1:
3144  case MVT::i8: Opcode = PPC::LBZU; break;
3145  }
3146  } else {
3147  assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3148  assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3149  switch (LoadedVT.getSimpleVT().SimpleTy) {
3150  default: llvm_unreachable("Invalid PPC load type!");
3151  case MVT::i64: Opcode = PPC::LDU; break;
3152  case MVT::i32: Opcode = PPC::LWZU8; break;
3153  case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
3154  case MVT::i1:
3155  case MVT::i8: Opcode = PPC::LBZU8; break;
3156  }
3157  }
3158 
3159  SDValue Chain = LD->getChain();
3160  SDValue Base = LD->getBasePtr();
3161  SDValue Ops[] = { Offset, Base, Chain };
3162  SDNode *MN = CurDAG->getMachineNode(
3163  Opcode, dl, LD->getValueType(0),
3164  PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3165  transferMemOperands(N, MN);
3166  ReplaceNode(N, MN);
3167  return;
3168  } else {
3169  unsigned Opcode;
3170  bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3171  if (LD->getValueType(0) != MVT::i64) {
3172  // Handle PPC32 integer and normal FP loads.
3173  assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3174  switch (LoadedVT.getSimpleVT().SimpleTy) {
3175  default: llvm_unreachable("Invalid PPC load type!");
3176  case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
3177  case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
3178  case MVT::f64: Opcode = PPC::LFDUX; break;
3179  case MVT::f32: Opcode = PPC::LFSUX; break;
3180  case MVT::i32: Opcode = PPC::LWZUX; break;
3181  case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
3182  case MVT::i1:
3183  case MVT::i8: Opcode = PPC::LBZUX; break;
3184  }
3185  } else {
3186  assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3187  assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
3188  "Invalid sext update load");
3189  switch (LoadedVT.getSimpleVT().SimpleTy) {
3190  default: llvm_unreachable("Invalid PPC load type!");
3191  case MVT::i64: Opcode = PPC::LDUX; break;
3192  case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
3193  case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
3194  case MVT::i1:
3195  case MVT::i8: Opcode = PPC::LBZUX8; break;
3196  }
3197  }
3198 
3199  SDValue Chain = LD->getChain();
3200  SDValue Base = LD->getBasePtr();
3201  SDValue Ops[] = { Base, Offset, Chain };
3202  SDNode *MN = CurDAG->getMachineNode(
3203  Opcode, dl, LD->getValueType(0),
3204  PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3205  transferMemOperands(N, MN);
3206  ReplaceNode(N, MN);
3207  return;
3208  }
3209  }
3210 
3211  case ISD::AND: {
3212  if (tryLogicOpOfCompares(N))
3213  return;
3214 
3215  unsigned Imm, Imm2, SH, MB, ME;
3216  uint64_t Imm64;
3217 
3218  // If this is an and of a value rotated between 0 and 31 bits and then and'd
3219  // with a mask, emit rlwinm
3220  if (isInt32Immediate(N->getOperand(1), Imm) &&
3221  isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
3222  SDValue Val = N->getOperand(0).getOperand(0);
3223  SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
3224  getI32Imm(ME, dl) };
3225  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3226  return;
3227  }
3228  // If this is just a masked value where the input is not handled above, and
3229  // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
3230  if (isInt32Immediate(N->getOperand(1), Imm) &&
3231  isRunOfOnes(Imm, MB, ME) &&
3232  N->getOperand(0).getOpcode() != ISD::ROTL) {
3233  SDValue Val = N->getOperand(0);
3234  SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
3235  getI32Imm(ME, dl) };
3236  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3237  return;
3238  }
3239  // If this is a 64-bit zero-extension mask, emit rldicl.
3240  if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3241  isMask_64(Imm64)) {
3242  SDValue Val = N->getOperand(0);
3243  MB = 64 - countTrailingOnes(Imm64);
3244  SH = 0;
3245 
3246  if (Val.getOpcode() == ISD::ANY_EXTEND) {
3247  auto Op0 = Val.getOperand(0);
3248  if ( Op0.getOpcode() == ISD::SRL &&
3249  isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
3250 
3251  auto ResultType = Val.getNode()->getValueType(0);
3252  auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
3253  ResultType);
3254  SDValue IDVal (ImDef, 0);
3255 
3256  Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
3257  ResultType, IDVal, Op0.getOperand(0),
3258  getI32Imm(1, dl)), 0);
3259  SH = 64 - Imm;
3260  }
3261  }
3262 
3263  // If the operand is a logical right shift, we can fold it into this
3264  // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
3265  // for n <= mb. The right shift is really a left rotate followed by a
3266  // mask, and this mask is a more-restrictive sub-mask of the mask implied
3267  // by the shift.
3268  if (Val.getOpcode() == ISD::SRL &&
3269  isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
3270  assert(Imm < 64 && "Illegal shift amount");
3271  Val = Val.getOperand(0);
3272  SH = 64 - Imm;
3273  }
3274 
3275  SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3276  CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
3277  return;
3278  }
3279  // If this is a negated 64-bit zero-extension mask,
3280  // i.e. the immediate is a sequence of ones from most significant side
3281  // and all zero for reminder, we should use rldicr.
3282  if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3283  isMask_64(~Imm64)) {
3284  SDValue Val = N->getOperand(0);
3285  MB = 63 - countTrailingOnes(~Imm64);
3286  SH = 0;
3287  SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3288  CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
3289  return;
3290  }
3291 
3292  // AND X, 0 -> 0, not "rlwinm 32".
3293  if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
3294  ReplaceUses(SDValue(N, 0), N->getOperand(1));
3295  return;
3296  }
3297  // ISD::OR doesn't get all the bitfield insertion fun.
3298  // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
3299  // bitfield insert.
3300  if (isInt32Immediate(N->getOperand(1), Imm) &&
3301  N->getOperand(0).getOpcode() == ISD::OR &&
3302  isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
3303  // The idea here is to check whether this is equivalent to:
3304  // (c1 & m) | (x & ~m)
3305  // where m is a run-of-ones mask. The logic here is that, for each bit in
3306  // c1 and c2:
3307  // - if both are 1, then the output will be 1.
3308  // - if both are 0, then the output will be 0.
3309  // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
3310  // come from x.
3311  // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
3312  // be 0.
3313  // If that last condition is never the case, then we can form m from the
3314  // bits that are the same between c1 and c2.
3315  unsigned MB, ME;
3316  if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
3317  SDValue Ops[] = { N->getOperand(0).getOperand(0),
3318  N->getOperand(0).getOperand(1),
3319  getI32Imm(0, dl), getI32Imm(MB, dl),
3320  getI32Imm(ME, dl) };
3321  ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
3322  return;
3323  }
3324  }
3325 
3326  // Other cases are autogenerated.
3327  break;
3328  }
3329  case ISD::OR: {
3330  if (N->getValueType(0) == MVT::i32)
3331  if (tryBitfieldInsert(N))
3332  return;
3333 
3334  if (tryLogicOpOfCompares(N))
3335  return;
3336 
3337  int16_t Imm;
3338  if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3339  isIntS16Immediate(N->getOperand(1), Imm)) {
3340  KnownBits LHSKnown;
3341  CurDAG->computeKnownBits(N->getOperand(0), LHSKnown);
3342 
3343  // If this is equivalent to an add, then we can fold it with the
3344  // FrameIndex calculation.
3345  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
3346  selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3347  return;
3348  }
3349  }
3350 
3351  // Other cases are autogenerated.
3352  break;
3353  }
3354  case ISD::XOR: {
3355  if (tryLogicOpOfCompares(N))
3356  return;
3357  break;
3358  }
3359  case ISD::ADD: {
3360  int16_t Imm;
3361  if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3362  isIntS16Immediate(N->getOperand(1), Imm)) {
3363  selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3364  return;
3365  }
3366 
3367  break;
3368  }
3369  case ISD::SHL: {
3370  unsigned Imm, SH, MB, ME;
3371  if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3372  isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3373  SDValue Ops[] = { N->getOperand(0).getOperand(0),
3374  getI32Imm(SH, dl), getI32Imm(MB, dl),
3375  getI32Imm(ME, dl) };
3376  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3377  return;
3378  }
3379 
3380  // Other cases are autogenerated.
3381  break;
3382  }
3383  case ISD::SRL: {
3384  unsigned Imm, SH, MB, ME;
3385  if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3386  isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3387  SDValue Ops[] = { N->getOperand(0).getOperand(0),
3388  getI32Imm(SH, dl), getI32Imm(MB, dl),
3389  getI32Imm(ME, dl) };
3390  CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3391  return;
3392  }
3393 
3394  // Other cases are autogenerated.
3395  break;
3396  }
3397  // FIXME: Remove this once the ANDI glue bug is fixed:
3399  case PPCISD::ANDIo_1_GT_BIT: {
3400  if (!ANDIGlueBug)
3401  break;
3402 
3403  EVT InVT = N->getOperand(0).getValueType();
3404  assert((InVT == MVT::i64 || InVT == MVT::i32) &&
3405  "Invalid input type for ANDIo_1_EQ_BIT");
3406 
3407  unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
3408  SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
3409  N->getOperand(0),
3410  CurDAG->getTargetConstant(1, dl, InVT)),
3411  0);
3412  SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
3413  SDValue SRIdxVal =
3415  PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
3416 
3417  CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
3418  SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
3419  return;
3420  }
3421  case ISD::SELECT_CC: {
3422  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
3423  EVT PtrVT =
3424  CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
3425  bool isPPC64 = (PtrVT == MVT::i64);
3426 
3427  // If this is a select of i1 operands, we'll pattern match it.
3428  if (PPCSubTarget->useCRBits() &&
3429  N->getOperand(0).getValueType() == MVT::i1)
3430  break;
3431 
3432  // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
3433  if (!isPPC64)
3434  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3435  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
3436  if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
3437  if (N1C->isNullValue() && N3C->isNullValue() &&
3438  N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
3439  // FIXME: Implement this optzn for PPC64.
3440  N->getValueType(0) == MVT::i32) {
3441  SDNode *Tmp =
3442  CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
3443  N->getOperand(0), getI32Imm(~0U, dl));
3444  CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
3445  N->getOperand(0), SDValue(Tmp, 1));
3446  return;
3447  }
3448 
3449  SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
3450 
3451  if (N->getValueType(0) == MVT::i1) {
3452  // An i1 select is: (c & t) | (!c & f).
3453  bool Inv;
3454  unsigned Idx = getCRIdxForSetCC(CC, Inv);
3455 
3456  unsigned SRI;
3457  switch (Idx) {
3458  default: llvm_unreachable("Invalid CC index");
3459  case 0: SRI = PPC::sub_lt; break;
3460  case 1: SRI = PPC::sub_gt; break;
3461  case 2: SRI = PPC::sub_eq; break;
3462  case 3: SRI = PPC::sub_un; break;
3463  }
3464 
3465  SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
3466 
3467  SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
3468  CCBit, CCBit), 0);
3469  SDValue C = Inv ? NotCCBit : CCBit,
3470  NotC = Inv ? CCBit : NotCCBit;
3471 
3472  SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3473  C, N->getOperand(2)), 0);
3474  SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3475  NotC, N->getOperand(3)), 0);
3476 
3477  CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
3478  return;
3479  }
3480 
3481  unsigned BROpc = getPredicateForSetCC(CC);
3482 
3483  unsigned SelectCCOp;
3484  if (N->getValueType(0) == MVT::i32)
3485  SelectCCOp = PPC::SELECT_CC_I4;
3486  else if (N->getValueType(0) == MVT::i64)
3487  SelectCCOp = PPC::SELECT_CC_I8;
3488  else if (N->getValueType(0) == MVT::f32)
3489  if (PPCSubTarget->hasP8Vector())
3490  SelectCCOp = PPC::SELECT_CC_VSSRC;
3491  else
3492  SelectCCOp = PPC::SELECT_CC_F4;
3493  else if (N->getValueType(0) == MVT::f64)
3494  if (PPCSubTarget->hasVSX())
3495  SelectCCOp = PPC::SELECT_CC_VSFRC;
3496  else
3497  SelectCCOp = PPC::SELECT_CC_F8;
3498  else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
3499  SelectCCOp = PPC::SELECT_CC_QFRC;
3500  else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
3501  SelectCCOp = PPC::SELECT_CC_QSRC;
3502  else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
3503  SelectCCOp = PPC::SELECT_CC_QBRC;
3504  else if (N->getValueType(0) == MVT::v2f64 ||
3505  N->getValueType(0) == MVT::v2i64)
3506  SelectCCOp = PPC::SELECT_CC_VSRC;
3507  else
3508  SelectCCOp = PPC::SELECT_CC_VRRC;
3509 
3510  SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
3511  getI32Imm(BROpc, dl) };
3512  CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
3513  return;
3514  }
3515  case ISD::VSELECT:
3516  if (PPCSubTarget->hasVSX()) {
3517  SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
3518  CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
3519  return;
3520  }
3521  break;
3522 
3523  case ISD::VECTOR_SHUFFLE:
3524  if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
3525  N->getValueType(0) == MVT::v2i64)) {
3526  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
3527 
3528  SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
3529  Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
3530  unsigned DM[2];
3531 
3532  for (int i = 0; i < 2; ++i)
3533  if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
3534  DM[i] = 0;
3535  else
3536  DM[i] = 1;
3537 
3538  if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
3539  Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3540  isa<LoadSDNode>(Op1.getOperand(0))) {
3541  LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
3542  SDValue Base, Offset;
3543 
3544  if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
3545  (LD->getMemoryVT() == MVT::f64 ||
3546  LD->getMemoryVT() == MVT::i64) &&
3547  SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
3548  SDValue Chain = LD->getChain();
3549  SDValue Ops[] = { Base, Offset, Chain };
3551  MemOp[0] = LD->getMemOperand();
3552  SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
3553  N->getValueType(0), Ops);
3554  cast<MachineSDNode>(NewN)->setMemRefs(MemOp, MemOp + 1);
3555  return;
3556  }
3557  }
3558 
3559  // For little endian, we must swap the input operands and adjust
3560  // the mask elements (reverse and invert them).
3561  if (PPCSubTarget->isLittleEndian()) {
3562  std::swap(Op1, Op2);
3563  unsigned tmp = DM[0];
3564  DM[0] = 1 - DM[1];
3565  DM[1] = 1 - tmp;
3566  }
3567 
3568  SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
3569  MVT::i32);
3570  SDValue Ops[] = { Op1, Op2, DMV };
3571  CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
3572  return;
3573  }
3574 
3575  break;
3576  case PPCISD::BDNZ:
3577  case PPCISD::BDZ: {
3578  bool IsPPC64 = PPCSubTarget->isPPC64();
3579  SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
3580  CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
3581  ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
3582  : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
3583  MVT::Other, Ops);
3584  return;
3585  }
3586  case PPCISD::COND_BRANCH: {
3587  // Op #0 is the Chain.
3588  // Op #1 is the PPC::PRED_* number.
3589  // Op #2 is the CR#
3590  // Op #3 is the Dest MBB
3591  // Op #4 is the Flag.
3592  // Prevent PPC::PRED_* from being selected into LI.
3593  unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3594  if (EnableBranchHint)
3595  PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
3596 
3597  SDValue Pred = getI32Imm(PCC, dl);
3598  SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
3599  N->getOperand(0), N->getOperand(4) };
3600  CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3601  return;
3602  }
3603  case ISD::BR_CC: {
3604  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3605  unsigned PCC = getPredicateForSetCC(CC);
3606 
3607  if (N->getOperand(2).getValueType() == MVT::i1) {
3608  unsigned Opc;
3609  bool Swap;
3610  switch (PCC) {
3611  default: llvm_unreachable("Unexpected Boolean-operand predicate");
3612  case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
3613  case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
3614  case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
3615  case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
3616  case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
3617  case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
3618  }
3619 
3620  SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
3621  N->getOperand(Swap ? 3 : 2),
3622  N->getOperand(Swap ? 2 : 3)), 0);
3623  CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
3624  N->getOperand(0));
3625  return;
3626  }
3627 
3628  if (EnableBranchHint)
3629  PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
3630 
3631  SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
3632  SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
3633  N->getOperand(4), N->getOperand(0) };
3634  CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3635  return;
3636  }
3637  case ISD::BRIND: {
3638  // FIXME: Should custom lower this.
3639  SDValue Chain = N->getOperand(0);
3640  SDValue Target = N->getOperand(1);
3641  unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
3642  unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
3643  Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
3644  Chain), 0);
3645  CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
3646  return;
3647  }
3648  case PPCISD::TOC_ENTRY: {
3649  assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
3650  "Only supported for 64-bit ABI and 32-bit SVR4");
3651  if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
3652  SDValue GA = N->getOperand(0);
3653  SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
3654  N->getOperand(1));
3655  transferMemOperands(N, MN);
3656  ReplaceNode(N, MN);
3657  return;
3658  }
3659 
3660  // For medium and large code model, we generate two instructions as
3661  // described below. Otherwise we allow SelectCodeCommon to handle this,
3662  // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
3663  CodeModel::Model CModel = TM.getCodeModel();
3664  if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
3665  break;
3666 
3667  // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
3668  // If it must be toc-referenced according to PPCSubTarget, we generate:
3669  // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
3670  // Otherwise we generate:
3671  // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
3672  SDValue GA = N->getOperand(0);
3673  SDValue TOCbase = N->getOperand(1);
3674  SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
3675  TOCbase, GA);
3676 
3677  if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
3678  CModel == CodeModel::Large) {
3679  SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3680  SDValue(Tmp, 0));
3681  transferMemOperands(N, MN);
3682  ReplaceNode(N, MN);
3683  return;
3684  }
3685 
3686  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
3687  const GlobalValue *GV = G->getGlobal();
3688  unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
3689  if (GVFlags & PPCII::MO_NLP_FLAG) {
3690  SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3691  SDValue(Tmp, 0));
3692  transferMemOperands(N, MN);
3693  ReplaceNode(N, MN);
3694  return;
3695  }
3696  }
3697 
3698  ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
3699  SDValue(Tmp, 0), GA));
3700  return;
3701  }
3702  case PPCISD::PPC32_PICGOT:
3703  // Generate a PIC-safe GOT reference.
3704  assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
3705  "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
3706  CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
3707  PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3708  MVT::i32);
3709  return;
3710 
3711  case PPCISD::VADD_SPLAT: {
3712  // This expands into one of three sequences, depending on whether
3713  // the first operand is odd or even, positive or negative.
3714  assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3715  isa<ConstantSDNode>(N->getOperand(1)) &&
3716  "Invalid operand on VADD_SPLAT!");
3717 
3718  int Elt = N->getConstantOperandVal(0);
3719  int EltSize = N->getConstantOperandVal(1);
3720  unsigned Opc1, Opc2, Opc3;
3721  EVT VT;
3722 
3723  if (EltSize == 1) {
3724  Opc1 = PPC::VSPLTISB;
3725  Opc2 = PPC::VADDUBM;
3726  Opc3 = PPC::VSUBUBM;
3727  VT = MVT::v16i8;
3728  } else if (EltSize == 2) {
3729  Opc1 = PPC::VSPLTISH;
3730  Opc2 = PPC::VADDUHM;
3731  Opc3 = PPC::VSUBUHM;
3732  VT = MVT::v8i16;
3733  } else {
3734  assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3735  Opc1 = PPC::VSPLTISW;
3736  Opc2 = PPC::VADDUWM;
3737  Opc3 = PPC::VSUBUWM;
3738  VT = MVT::v4i32;
3739  }
3740 
3741  if ((Elt & 1) == 0) {
3742  // Elt is even, in the range [-32,-18] + [16,30].
3743  //
3744  // Convert: VADD_SPLAT elt, size
3745  // Into: tmp = VSPLTIS[BHW] elt
3746  // VADDU[BHW]M tmp, tmp
3747  // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3748  SDValue EltVal = getI32Imm(Elt >> 1, dl);
3749  SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3750  SDValue TmpVal = SDValue(Tmp, 0);
3751  ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
3752  return;
3753  } else if (Elt > 0) {
3754  // Elt is odd and positive, in the range [17,31].
3755  //
3756  // Convert: VADD_SPLAT elt, size
3757  // Into: tmp1 = VSPLTIS[BHW] elt-16
3758  // tmp2 = VSPLTIS[BHW] -16
3759  // VSUBU[BHW]M tmp1, tmp2
3760  SDValue EltVal = getI32Imm(Elt - 16, dl);
3761  SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3762  EltVal = getI32Imm(-16, dl);
3763  SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3764  ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3765  SDValue(Tmp2, 0)));
3766  return;
3767  } else {
3768  // Elt is odd and negative, in the range [-31,-17].
3769  //
3770  // Convert: VADD_SPLAT elt, size
3771  // Into: tmp1 = VSPLTIS[BHW] elt+16
3772  // tmp2 = VSPLTIS[BHW] -16
3773  // VADDU[BHW]M tmp1, tmp2
3774  SDValue EltVal = getI32Imm(Elt + 16, dl);
3775  SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3776  EltVal = getI32Imm(-16, dl);
3777  SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3778  ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3779  SDValue(Tmp2, 0)));
3780  return;
3781  }
3782  }
3783  }
3784 
3785  SelectCode(N);
3786 }
3787 
3788 // If the target supports the cmpb instruction, do the idiom recognition here.
3789 // We don't do this as a DAG combine because we don't want to do it as nodes
3790 // are being combined (because we might miss part of the eventual idiom). We
3791 // don't want to do it during instruction selection because we want to reuse
3792 // the logic for lowering the masking operations already part of the
3793 // instruction selector.
3794 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3795  SDLoc dl(N);
3796 
3797  assert(N->getOpcode() == ISD::OR &&
3798  "Only OR nodes are supported for CMPB");
3799 
3800  SDValue Res;
3801  if (!PPCSubTarget->hasCMPB())
3802  return Res;
3803 
3804  if (N->getValueType(0) != MVT::i32 &&
3805  N->getValueType(0) != MVT::i64)
3806  return Res;
3807 
3808  EVT VT = N->getValueType(0);
3809 
3810  SDValue RHS, LHS;
3811  bool BytesFound[8] = {false, false, false, false, false, false, false, false};
3812  uint64_t Mask = 0, Alt = 0;
3813 
3814  auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3815  uint64_t &Mask, uint64_t &Alt,
3816  SDValue &LHS, SDValue &RHS) {
3817  if (O.getOpcode() != ISD::SELECT_CC)
3818  return false;
3819  ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3820 
3821  if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3822  !isa<ConstantSDNode>(O.getOperand(3)))
3823  return false;
3824 
3825  uint64_t PM = O.getConstantOperandVal(2);
3826  uint64_t PAlt = O.getConstantOperandVal(3);
3827  for (b = 0; b < 8; ++b) {
3828  uint64_t Mask = UINT64_C(0xFF) << (8*b);
3829  if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3830  break;
3831  }
3832 
3833  if (b == 8)
3834  return false;
3835  Mask |= PM;
3836  Alt |= PAlt;
3837 
3838  if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3839  O.getConstantOperandVal(1) != 0) {
3840  SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3841  if (Op0.getOpcode() == ISD::TRUNCATE)
3842  Op0 = Op0.getOperand(0);
3843  if (Op1.getOpcode() == ISD::TRUNCATE)
3844  Op1 = Op1.getOperand(0);
3845 
3846  if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3847  Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3848  isa<ConstantSDNode>(Op0.getOperand(1))) {
3849 
3850  unsigned Bits = Op0.getValueSizeInBits();
3851  if (b != Bits/8-1)
3852  return false;
3853  if (Op0.getConstantOperandVal(1) != Bits-8)
3854  return false;
3855 
3856  LHS = Op0.getOperand(0);
3857  RHS = Op1.getOperand(0);
3858  return true;
3859  }
3860 
3861  // When we have small integers (i16 to be specific), the form present
3862  // post-legalization uses SETULT in the SELECT_CC for the
3863  // higher-order byte, depending on the fact that the
3864  // even-higher-order bytes are known to all be zero, for example:
3865  // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3866  // (so when the second byte is the same, because all higher-order
3867  // bits from bytes 3 and 4 are known to be zero, the result of the
3868  // xor can be at most 255)
3869  if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3870  isa<ConstantSDNode>(O.getOperand(1))) {
3871 
3872  uint64_t ULim = O.getConstantOperandVal(1);
3873  if (ULim != (UINT64_C(1) << b*8))
3874  return false;
3875 
3876  // Now we need to make sure that the upper bytes are known to be
3877  // zero.
3878  unsigned Bits = Op0.getValueSizeInBits();
3879  if (!CurDAG->MaskedValueIsZero(
3880  Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
3881  return false;
3882 
3883  LHS = Op0.getOperand(0);
3884  RHS = Op0.getOperand(1);
3885  return true;
3886  }
3887 
3888  return false;
3889  }
3890 
3891  if (CC != ISD::SETEQ)
3892  return false;
3893 
3894  SDValue Op = O.getOperand(0);
3895  if (Op.getOpcode() == ISD::AND) {
3896  if (!isa<ConstantSDNode>(Op.getOperand(1)))
3897  return false;
3898  if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3899  return false;
3900 
3901  SDValue XOR = Op.getOperand(0);
3902  if (XOR.getOpcode() == ISD::TRUNCATE)
3903  XOR = XOR.getOperand(0);
3904  if (XOR.getOpcode() != ISD::XOR)
3905  return false;
3906 
3907  LHS = XOR.getOperand(0);
3908  RHS = XOR.getOperand(1);
3909  return true;
3910  } else if (Op.getOpcode() == ISD::SRL) {
3911  if (!isa<ConstantSDNode>(Op.getOperand(1)))
3912  return false;
3913  unsigned Bits = Op.getValueSizeInBits();
3914  if (b != Bits/8-1)
3915  return false;
3916  if (Op.getConstantOperandVal(1) != Bits-8)
3917  return false;
3918 
3919  SDValue XOR = Op.getOperand(0);
3920  if (XOR.getOpcode() == ISD::TRUNCATE)
3921  XOR = XOR.getOperand(0);
3922  if (XOR.getOpcode() != ISD::XOR)
3923  return false;
3924 
3925  LHS = XOR.getOperand(0);
3926  RHS = XOR.getOperand(1);
3927  return true;
3928  }
3929 
3930  return false;
3931  };
3932 
3934  while (!Queue.empty()) {
3935  SDValue V = Queue.pop_back_val();
3936 
3937  for (const SDValue &O : V.getNode()->ops()) {
3938  unsigned b;
3939  uint64_t M = 0, A = 0;
3940  SDValue OLHS, ORHS;
3941  if (O.getOpcode() == ISD::OR) {
3942  Queue.push_back(O);
3943  } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3944  if (!LHS) {
3945  LHS = OLHS;
3946  RHS = ORHS;
3947  BytesFound[b] = true;
3948  Mask |= M;
3949  Alt |= A;
3950  } else if ((LHS == ORHS && RHS == OLHS) ||
3951  (RHS == ORHS && LHS == OLHS)) {
3952  BytesFound[b] = true;
3953  Mask |= M;
3954  Alt |= A;
3955  } else {
3956  return Res;
3957  }
3958  } else {
3959  return Res;
3960  }
3961  }
3962  }
3963 
3964  unsigned LastB = 0, BCnt = 0;
3965  for (unsigned i = 0; i < 8; ++i)
3966  if (BytesFound[LastB]) {
3967  ++BCnt;
3968  LastB = i;
3969  }
3970 
3971  if (!LastB || BCnt < 2)
3972  return Res;
3973 
3974  // Because we'll be zero-extending the output anyway if don't have a specific
3975  // value for each input byte (via the Mask), we can 'anyext' the inputs.
3976  if (LHS.getValueType() != VT) {
3977  LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3978  RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3979  }
3980 
3981  Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3982 
3983  bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3984  if (NonTrivialMask && !Alt) {
3985  // Res = Mask & CMPB
3986  Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3987  CurDAG->getConstant(Mask, dl, VT));
3988  } else if (Alt) {
3989  // Res = (CMPB & Mask) | (~CMPB & Alt)
3990  // Which, as suggested here:
3991  // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3992  // can be written as:
3993  // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3994  // useful because the (Alt ^ Mask) can be pre-computed.
3995  Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3996  CurDAG->getConstant(Mask ^ Alt, dl, VT));
3997  Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3998  CurDAG->getConstant(Alt, dl, VT));
3999  }
4000 
4001  return Res;
4002 }
4003 
4004 // When CR bit registers are enabled, an extension of an i1 variable to a i32
4005 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
4006 // involves constant materialization of a 0 or a 1 or both. If the result of
4007 // the extension is then operated upon by some operator that can be constant
4008 // folded with a constant 0 or 1, and that constant can be materialized using
4009 // only one instruction (like a zero or one), then we should fold in those
4010 // operations with the select.
4011 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
4012  if (!PPCSubTarget->useCRBits())
4013  return;
4014 
4015  if (N->getOpcode() != ISD::ZERO_EXTEND &&
4016  N->getOpcode() != ISD::SIGN_EXTEND &&
4017  N->getOpcode() != ISD::ANY_EXTEND)
4018  return;
4019 
4020  if (N->getOperand(0).getValueType() != MVT::i1)
4021  return;
4022 
4023  if (!N->hasOneUse())
4024  return;
4025 
4026  SDLoc dl(N);
4027  EVT VT = N->getValueType(0);
4028  SDValue Cond = N->getOperand(0);
4029  SDValue ConstTrue =
4030  CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
4031  SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
4032 
4033  do {
4034  SDNode *User = *N->use_begin();
4035  if (User->getNumOperands() != 2)
4036  break;
4037 
4038  auto TryFold = [this, N, User, dl](SDValue Val) {
4039  SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
4040  SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
4041  SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
4042 
4043  return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
4044  User->getValueType(0),
4045  O0.getNode(), O1.getNode());
4046  };
4047 
4048  // FIXME: When the semantics of the interaction between select and undef
4049  // are clearly defined, it may turn out to be unnecessary to break here.
4050  SDValue TrueRes = TryFold(ConstTrue);
4051  if (!TrueRes || TrueRes.isUndef())
4052  break;
4053  SDValue FalseRes = TryFold(ConstFalse);
4054  if (!FalseRes || FalseRes.isUndef())
4055  break;
4056 
4057  // For us to materialize these using one instruction, we must be able to
4058  // represent them as signed 16-bit integers.
4059  uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
4060  False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
4061  if (!isInt<16>(True) || !isInt<16>(False))
4062  break;
4063 
4064  // We can replace User with a new SELECT node, and try again to see if we
4065  // can fold the select with its user.
4066  Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
4067  N = User;
4068  ConstTrue = TrueRes;
4069  ConstFalse = FalseRes;
4070  } while (N->hasOneUse());
4071 }
4072 
4073 void PPCDAGToDAGISel::PreprocessISelDAG() {
4074  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4075  ++Position;
4076 
4077  bool MadeChange = false;
4078  while (Position != CurDAG->allnodes_begin()) {
4079  SDNode *N = &*--Position;
4080  if (N->use_empty())
4081  continue;
4082 
4083  SDValue Res;
4084  switch (N->getOpcode()) {
4085  default: break;
4086  case ISD::OR:
4087  Res = combineToCMPB(N);
4088  break;
4089  }
4090 
4091  if (!Res)
4092  foldBoolExts(Res, N);
4093 
4094  if (Res) {
4095  DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
4096  DEBUG(N->dump(CurDAG));
4097  DEBUG(dbgs() << "\nNew: ");
4098  DEBUG(Res.getNode()->dump(CurDAG));
4099  DEBUG(dbgs() << "\n");
4100 
4101  CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
4102  MadeChange = true;
4103  }
4104  }
4105 
4106  if (MadeChange)
4107  CurDAG->RemoveDeadNodes();
4108 }
4109 
4110 /// PostprocessISelDAG - Perform some late peephole optimizations
4111 /// on the DAG representation.
4112 void PPCDAGToDAGISel::PostprocessISelDAG() {
4113  // Skip peepholes at -O0.
4114  if (TM.getOptLevel() == CodeGenOpt::None)
4115  return;
4116 
4117  PeepholePPC64();
4118  PeepholeCROps();
4119  PeepholePPC64ZExt();
4120 }
4121 
4122 // Check if all users of this node will become isel where the second operand
4123 // is the constant zero. If this is so, and if we can negate the condition,
4124 // then we can flip the true and false operands. This will allow the zero to
4125 // be folded with the isel so that we don't need to materialize a register
4126 // containing zero.
4127 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
4128  for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4129  UI != UE; ++UI) {
4130  SDNode *User = *UI;
4131  if (!User->isMachineOpcode())
4132  return false;
4133  if (User->getMachineOpcode() != PPC::SELECT_I4 &&
4134  User->getMachineOpcode() != PPC::SELECT_I8)
4135  return false;
4136 
4137  SDNode *Op2 = User->getOperand(2).getNode();
4138  if (!Op2->isMachineOpcode())
4139  return false;
4140 
4141  if (Op2->getMachineOpcode() != PPC::LI &&
4142  Op2->getMachineOpcode() != PPC::LI8)
4143  return false;
4144 
4146  if (!C)
4147  return false;
4148 
4149  if (!C->isNullValue())
4150  return false;
4151  }
4152 
4153  return true;
4154 }
4155 
4156 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
4157  SmallVector<SDNode *, 4> ToReplace;
4158  for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4159  UI != UE; ++UI) {
4160  SDNode *User = *UI;
4161  assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
4162  User->getMachineOpcode() == PPC::SELECT_I8) &&
4163  "Must have all select users");
4164  ToReplace.push_back(User);
4165  }
4166 
4167  for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
4168  UE = ToReplace.end(); UI != UE; ++UI) {
4169  SDNode *User = *UI;
4170  SDNode *ResNode =
4171  CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
4172  User->getValueType(0), User->getOperand(0),
4173  User->getOperand(2),
4174  User->getOperand(1));
4175 
4176  DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4177  DEBUG(User->dump(CurDAG));
4178  DEBUG(dbgs() << "\nNew: ");
4179  DEBUG(ResNode->dump(CurDAG));
4180  DEBUG(dbgs() << "\n");
4181 
4182  ReplaceUses(User, ResNode);
4183  }
4184 }
4185 
4186 void PPCDAGToDAGISel::PeepholeCROps() {
4187  bool IsModified;
4188  do {
4189  IsModified = false;
4190  for (SDNode &Node : CurDAG->allnodes()) {
4191  MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
4192  if (!MachineNode || MachineNode->use_empty())
4193  continue;
4194  SDNode *ResNode = MachineNode;
4195 
4196  bool Op1Set = false, Op1Unset = false,
4197  Op1Not = false,
4198  Op2Set = false, Op2Unset = false,
4199  Op2Not = false;
4200 
4201  unsigned Opcode = MachineNode->getMachineOpcode();
4202  switch (Opcode) {
4203  default: break;
4204  case PPC::CRAND:
4205  case PPC::CRNAND:
4206  case PPC::CROR:
4207  case PPC::CRXOR:
4208  case PPC::CRNOR:
4209  case PPC::CREQV:
4210  case PPC::CRANDC:
4211  case PPC::CRORC: {
4212  SDValue Op = MachineNode->getOperand(1);
4213  if (Op.isMachineOpcode()) {
4214  if (Op.getMachineOpcode() == PPC::CRSET)
4215  Op2Set = true;
4216  else if (Op.getMachineOpcode() == PPC::CRUNSET)
4217  Op2Unset = true;
4218  else if (Op.getMachineOpcode() == PPC::CRNOR &&
4219  Op.getOperand(0) == Op.getOperand(1))
4220  Op2Not = true;
4221  }
4223  }
4224  case PPC::BC:
4225  case PPC::BCn:
4226  case PPC::SELECT_I4:
4227  case PPC::SELECT_I8:
4228  case PPC::SELECT_F4:
4229  case PPC::SELECT_F8:
4230  case PPC::SELECT_QFRC:
4231  case PPC::SELECT_QSRC:
4232  case PPC::SELECT_QBRC:
4233  case PPC::SELECT_VRRC:
4234  case PPC::SELECT_VSFRC:
4235  case PPC::SELECT_VSSRC:
4236  case PPC::SELECT_VSRC: {
4237  SDValue Op = MachineNode->getOperand(0);
4238  if (Op.isMachineOpcode()) {
4239  if (Op.getMachineOpcode() == PPC::CRSET)
4240  Op1Set = true;
4241  else if (Op.getMachineOpcode() == PPC::CRUNSET)
4242  Op1Unset = true;
4243  else if (Op.getMachineOpcode() == PPC::CRNOR &&
4244  Op.getOperand(0) == Op.getOperand(1))
4245  Op1Not = true;
4246  }
4247  }
4248  break;
4249  }
4250 
4251  bool SelectSwap = false;
4252  switch (Opcode) {
4253  default: break;
4254  case PPC::CRAND:
4255  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4256  // x & x = x
4257  ResNode = MachineNode->getOperand(0).getNode();
4258  else if (Op1Set)
4259  // 1 & y = y
4260  ResNode = MachineNode->getOperand(1).getNode();
4261  else if (Op2Set)
4262  // x & 1 = x
4263  ResNode = MachineNode->getOperand(0).getNode();
4264  else if (Op1Unset || Op2Unset)
4265  // x & 0 = 0 & y = 0
4266  ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4267  MVT::i1);
4268  else if (Op1Not)
4269  // ~x & y = andc(y, x)
4270  ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4271  MVT::i1, MachineNode->getOperand(1),
4272  MachineNode->getOperand(0).
4273  getOperand(0));
4274  else if (Op2Not)
4275  // x & ~y = andc(x, y)
4276  ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4277  MVT::i1, MachineNode->getOperand(0),
4278  MachineNode->getOperand(1).
4279  getOperand(0));
4280  else if (AllUsersSelectZero(MachineNode)) {
4281  ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4282  MVT::i1, MachineNode->getOperand(0),
4283  MachineNode->getOperand(1));
4284  SelectSwap = true;
4285  }
4286  break;
4287  case PPC::CRNAND:
4288  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4289  // nand(x, x) -> nor(x, x)
4290  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4291  MVT::i1, MachineNode->getOperand(0),
4292  MachineNode->getOperand(0));
4293  else if (Op1Set)
4294  // nand(1, y) -> nor(y, y)
4295  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4296  MVT::i1, MachineNode->getOperand(1),
4297  MachineNode->getOperand(1));
4298  else if (Op2Set)
4299  // nand(x, 1) -> nor(x, x)
4300  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4301  MVT::i1, MachineNode->getOperand(0),
4302  MachineNode->getOperand(0));
4303  else if (Op1Unset || Op2Unset)
4304  // nand(x, 0) = nand(0, y) = 1
4305  ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4306  MVT::i1);
4307  else if (Op1Not)
4308  // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
4309  ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4310  MVT::i1, MachineNode->getOperand(0).
4311  getOperand(0),
4312  MachineNode->getOperand(1));
4313  else if (Op2Not)
4314  // nand(x, ~y) = ~x | y = orc(y, x)
4315  ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4316  MVT::i1, MachineNode->getOperand(1).
4317  getOperand(0),
4318  MachineNode->getOperand(0));
4319  else if (AllUsersSelectZero(MachineNode)) {
4320  ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4321  MVT::i1, MachineNode->getOperand(0),
4322  MachineNode->getOperand(1));
4323  SelectSwap = true;
4324  }
4325  break;
4326  case PPC::CROR:
4327  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4328  // x | x = x
4329  ResNode = MachineNode->getOperand(0).getNode();
4330  else if (Op1Set || Op2Set)
4331  // x | 1 = 1 | y = 1
4332  ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4333  MVT::i1);
4334  else if (Op1Unset)
4335  // 0 | y = y
4336  ResNode = MachineNode->getOperand(1).getNode();
4337  else if (Op2Unset)
4338  // x | 0 = x
4339  ResNode = MachineNode->getOperand(0).getNode();
4340  else if (Op1Not)
4341  // ~x | y = orc(y, x)
4342  ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4343  MVT::i1, MachineNode->getOperand(1),
4344  MachineNode->getOperand(0).
4345  getOperand(0));
4346  else if (Op2Not)
4347  // x | ~y = orc(x, y)
4348  ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4349  MVT::i1, MachineNode->getOperand(0),
4350  MachineNode->getOperand(1).
4351  getOperand(0));
4352  else if (AllUsersSelectZero(MachineNode)) {
4353  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4354  MVT::i1, MachineNode->getOperand(0),
4355  MachineNode->getOperand(1));
4356  SelectSwap = true;
4357  }
4358  break;
4359  case PPC::CRXOR:
4360  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4361  // xor(x, x) = 0
4362  ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4363  MVT::i1);
4364  else if (Op1Set)
4365  // xor(1, y) -> nor(y, y)
4366  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4367  MVT::i1, MachineNode->getOperand(1),
4368  MachineNode->getOperand(1));
4369  else if (Op2Set)
4370  // xor(x, 1) -> nor(x, x)
4371  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4372  MVT::i1, MachineNode->getOperand(0),
4373  MachineNode->getOperand(0));
4374  else if (Op1Unset)
4375  // xor(0, y) = y
4376  ResNode = MachineNode->getOperand(1).getNode();
4377  else if (Op2Unset)
4378  // xor(x, 0) = x
4379  ResNode = MachineNode->getOperand(0).getNode();
4380  else if (Op1Not)
4381  // xor(~x, y) = eqv(x, y)
4382  ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4383  MVT::i1, MachineNode->getOperand(0).
4384  getOperand(0),
4385  MachineNode->getOperand(1));
4386  else if (Op2Not)
4387  // xor(x, ~y) = eqv(x, y)
4388  ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4389  MVT::i1, MachineNode->getOperand(0),
4390  MachineNode->getOperand(1).
4391  getOperand(0));
4392  else if (AllUsersSelectZero(MachineNode)) {
4393  ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4394  MVT::i1, MachineNode->getOperand(0),
4395  MachineNode->getOperand(1));
4396  SelectSwap = true;
4397  }
4398  break;
4399  case PPC::CRNOR:
4400  if (Op1Set || Op2Set)
4401  // nor(1, y) -> 0
4402  ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4403  MVT::i1);
4404  else if (Op1Unset)
4405  // nor(0, y) = ~y -> nor(y, y)
4406  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4407  MVT::i1, MachineNode->getOperand(1),
4408  MachineNode->getOperand(1));
4409  else if (Op2Unset)
4410  // nor(x, 0) = ~x
4411  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4412  MVT::i1, MachineNode->getOperand(0),
4413  MachineNode->getOperand(0));
4414  else if (Op1Not)
4415  // nor(~x, y) = andc(x, y)
4416  ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4417  MVT::i1, MachineNode->getOperand(0).
4418  getOperand(0),
4419  MachineNode->getOperand(1));
4420  else if (Op2Not)
4421  // nor(x, ~y) = andc(y, x)
4422  ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4423  MVT::i1, MachineNode->getOperand(1).
4424  getOperand(0),
4425  MachineNode->getOperand(0));
4426  else if (AllUsersSelectZero(MachineNode)) {
4427  ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4428  MVT::i1, MachineNode->getOperand(0),
4429  MachineNode->getOperand(1));
4430  SelectSwap = true;
4431  }
4432  break;
4433  case PPC::CREQV:
4434  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4435  // eqv(x, x) = 1
4436  ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4437  MVT::i1);
4438  else if (Op1Set)
4439  // eqv(1, y) = y
4440  ResNode = MachineNode->getOperand(1).getNode();
4441  else if (Op2Set)
4442  // eqv(x, 1) = x
4443  ResNode = MachineNode->getOperand(0).getNode();
4444  else if (Op1Unset)
4445  // eqv(0, y) = ~y -> nor(y, y)
4446  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4447  MVT::i1, MachineNode->getOperand(1),
4448  MachineNode->getOperand(1));
4449  else if (Op2Unset)
4450  // eqv(x, 0) = ~x
4451  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4452  MVT::i1, MachineNode->getOperand(0),
4453  MachineNode->getOperand(0));
4454  else if (Op1Not)
4455  // eqv(~x, y) = xor(x, y)
4456  ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4457  MVT::i1, MachineNode->getOperand(0).
4458  getOperand(0),
4459  MachineNode->getOperand(1));
4460  else if (Op2Not)
4461  // eqv(x, ~y) = xor(x, y)
4462  ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4463  MVT::i1, MachineNode->getOperand(0),
4464  MachineNode->getOperand(1).
4465  getOperand(0));
4466  else if (AllUsersSelectZero(MachineNode)) {
4467  ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4468  MVT::i1, MachineNode->getOperand(0),
4469  MachineNode->getOperand(1));
4470  SelectSwap = true;
4471  }
4472  break;
4473  case PPC::CRANDC:
4474  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4475  // andc(x, x) = 0
4476  ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4477  MVT::i1);
4478  else if (Op1Set)
4479  // andc(1, y) = ~y
4480  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4481  MVT::i1, MachineNode->getOperand(1),
4482  MachineNode->getOperand(1));
4483  else if (Op1Unset || Op2Set)
4484  // andc(0, y) = andc(x, 1) = 0
4485  ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4486  MVT::i1);
4487  else if (Op2Unset)
4488  // andc(x, 0) = x
4489  ResNode = MachineNode->getOperand(0).getNode();
4490  else if (Op1Not)
4491  // andc(~x, y) = ~(x | y) = nor(x, y)
4492  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4493  MVT::i1, MachineNode->getOperand(0).
4494  getOperand(0),
4495  MachineNode->getOperand(1));
4496  else if (Op2Not)
4497  // andc(x, ~y) = x & y
4498  ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4499  MVT::i1, MachineNode->getOperand(0),
4500  MachineNode->getOperand(1).
4501  getOperand(0));
4502  else if (AllUsersSelectZero(MachineNode)) {
4503  ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4504  MVT::i1, MachineNode->getOperand(1),
4505  MachineNode->getOperand(0));
4506  SelectSwap = true;
4507  }
4508  break;
4509  case PPC::CRORC:
4510  if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4511  // orc(x, x) = 1
4512  ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4513  MVT::i1);
4514  else if (Op1Set || Op2Unset)
4515  // orc(1, y) = orc(x, 0) = 1
4516  ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4517  MVT::i1);
4518  else if (Op2Set)
4519  // orc(x, 1) = x
4520  ResNode = MachineNode->getOperand(0).getNode();
4521  else if (Op1Unset)
4522  // orc(0, y) = ~y
4523  ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4524  MVT::i1, MachineNode->getOperand(1),
4525  MachineNode->getOperand(1));
4526  else if (Op1Not)
4527  // orc(~x, y) = ~(x & y) = nand(x, y)
4528  ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4529  MVT::i1, MachineNode->getOperand(0).
4530  getOperand(0),
4531  MachineNode->getOperand(1));
4532  else if (Op2Not)
4533  // orc(x, ~y) = x | y
4534  ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4535  MVT::i1, MachineNode->getOperand(0),
4536  MachineNode->getOperand(1).
4537  getOperand(0));
4538  else if (AllUsersSelectZero(MachineNode)) {
4539  ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4540  MVT::i1, MachineNode->getOperand(1),
4541  MachineNode->getOperand(0));
4542  SelectSwap = true;
4543  }
4544  break;
4545  case PPC::SELECT_I4:
4546  case PPC::SELECT_I8:
4547  case PPC::SELECT_F4:
4548  case PPC::SELECT_F8:
4549  case PPC::SELECT_QFRC:
4550  case PPC::SELECT_QSRC:
4551  case PPC::SELECT_QBRC:
4552  case PPC::SELECT_VRRC:
4553  case PPC::SELECT_VSFRC:
4554  case PPC::SELECT_VSSRC:
4555  case PPC::SELECT_VSRC:
4556  if (Op1Set)
4557  ResNode = MachineNode->getOperand(1).getNode();
4558  else if (Op1Unset)
4559  ResNode = MachineNode->getOperand(2).getNode();
4560  else if (Op1Not)
4561  ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
4562  SDLoc(MachineNode),
4563  MachineNode->getValueType(0),
4564  MachineNode->getOperand(0).
4565  getOperand(0),
4566  MachineNode->getOperand(2),
4567  MachineNode->getOperand(1));
4568  break;
4569  case PPC::BC:
4570  case PPC::BCn:
4571  if (Op1Not)
4572  ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
4573  PPC::BC,
4574  SDLoc(MachineNode),
4575  MVT::Other,
4576  MachineNode->getOperand(0).
4577  getOperand(0),
4578  MachineNode->getOperand(1),
4579  MachineNode->getOperand(2));
4580  // FIXME: Handle Op1Set, Op1Unset here too.
4581  break;
4582  }
4583 
4584  // If we're inverting this node because it is used only by selects that
4585  // we'd like to swap, then swap the selects before the node replacement.
4586  if (SelectSwap)
4587  SwapAllSelectUsers(MachineNode);
4588 
4589  if (ResNode != MachineNode) {
4590  DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4591  DEBUG(MachineNode->dump(CurDAG));
4592  DEBUG(dbgs() << "\nNew: ");
4593  DEBUG(ResNode->dump(CurDAG));
4594  DEBUG(dbgs() << "\n");
4595 
4596  ReplaceUses(MachineNode, ResNode);
4597  IsModified = true;
4598  }
4599  }
4600  if (IsModified)
4601  CurDAG->RemoveDeadNodes();
4602  } while (IsModified);
4603 }
4604 
4605 // Gather the set of 32-bit operations that are known to have their
4606 // higher-order 32 bits zero, where ToPromote contains all such operations.
4608  SmallPtrSetImpl<SDNode *> &ToPromote) {
4609  if (!Op32.isMachineOpcode())
4610  return false;
4611 
4612  // First, check for the "frontier" instructions (those that will clear the
4613  // higher-order 32 bits.
4614 
4615  // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
4616  // around. If it does not, then these instructions will clear the
4617  // higher-order bits.
4618  if ((Op32.getMachineOpcode() == PPC::RLWINM ||
4619  Op32.getMachineOpcode() == PPC::RLWNM) &&
4620  Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
4621  ToPromote.insert(Op32.getNode());
4622  return true;
4623  }
4624 
4625  // SLW and SRW always clear the higher-order bits.
4626  if (Op32.getMachineOpcode() == PPC::SLW ||
4627  Op32.getMachineOpcode() == PPC::SRW) {
4628  ToPromote.insert(Op32.getNode());
4629  return true;
4630  }
4631 
4632  // For LI and LIS, we need the immediate to be positive (so that it is not
4633  // sign extended).
4634  if (Op32.getMachineOpcode() == PPC::LI ||
4635  Op32.getMachineOpcode() == PPC::LIS) {
4636  if (!isUInt<15>(Op32.getConstantOperandVal(0)))
4637  return false;
4638 
4639  ToPromote.insert(Op32.getNode());
4640  return true;
4641  }
4642 
4643  // LHBRX and LWBRX always clear the higher-order bits.
4644  if (Op32.getMachineOpcode() == PPC::LHBRX ||
4645  Op32.getMachineOpcode() == PPC::LWBRX) {
4646  ToPromote.insert(Op32.getNode());
4647  return true;
4648  }
4649 
4650  // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
4651  if (Op32.getMachineOpcode() == PPC::CNTLZW ||
4652  Op32.getMachineOpcode() == PPC::CNTTZW) {
4653  ToPromote.insert(Op32.getNode());
4654  return true;
4655  }
4656 
4657  // Next, check for those instructions we can look through.
4658 
4659  // Assuming the mask does not wrap around, then the higher-order bits are
4660  // taken directly from the first operand.
4661  if (Op32.getMachineOpcode() == PPC::RLWIMI &&
4662  Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
4663  SmallPtrSet<SDNode *, 16> ToPromote1;
4664  if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4665  return false;
4666 
4667  ToPromote.insert(Op32.getNode());
4668  ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4669  return true;
4670  }
4671 
4672  // For OR, the higher-order bits are zero if that is true for both operands.
4673  // For SELECT_I4, the same is true (but the relevant operand numbers are
4674  // shifted by 1).
4675  if (Op32.getMachineOpcode() == PPC::OR ||
4676  Op32.getMachineOpcode() == PPC::SELECT_I4) {
4677  unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
4678  SmallPtrSet<SDNode *, 16> ToPromote1;
4679  if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
4680  return false;
4681  if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
4682  return false;
4683 
4684  ToPromote.insert(Op32.getNode());
4685  ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4686  return true;
4687  }
4688 
4689  // For ORI and ORIS, we need the higher-order bits of the first operand to be
4690  // zero, and also for the constant to be positive (so that it is not sign
4691  // extended).
4692  if (Op32.getMachineOpcode() == PPC::ORI ||
4693  Op32.getMachineOpcode() == PPC::ORIS) {
4694  SmallPtrSet<SDNode *, 16> ToPromote1;
4695  if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4696  return false;
4697  if (!isUInt<15>(Op32.getConstantOperandVal(1)))
4698  return false;
4699 
4700  ToPromote.insert(Op32.getNode());
4701  ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4702  return true;
4703  }
4704 
4705  // The higher-order bits of AND are zero if that is true for at least one of
4706  // the operands.
4707  if (Op32.getMachineOpcode() == PPC::AND) {
4708  SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
4709  bool Op0OK =
4710  PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4711  bool Op1OK =
4712  PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
4713  if (!Op0OK && !Op1OK)
4714  return false;
4715 
4716  ToPromote.insert(Op32.getNode());
4717 
4718  if (Op0OK)
4719  ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4720 
4721  if (Op1OK)
4722  ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4723 
4724  return true;
4725  }
4726 
4727  // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4728  // of the first operand, or if the second operand is positive (so that it is
4729  // not sign extended).
4730  if (Op32.getMachineOpcode() == PPC::ANDIo ||
4731  Op32.getMachineOpcode() == PPC::ANDISo) {
4732  SmallPtrSet<SDNode *, 16> ToPromote1;
4733  bool Op0OK =
4734  PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4735  bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4736  if (!Op0OK && !Op1OK)
4737  return false;
4738 
4739  ToPromote.insert(Op32.getNode());
4740 
4741  if (Op0OK)
4742  ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4743 
4744  return true;
4745  }
4746 
4747  return false;
4748 }
4749 
4750 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4751  if (!PPCSubTarget->isPPC64())
4752  return;
4753 
4754  // When we zero-extend from i32 to i64, we use a pattern like this:
4755  // def : Pat<(i64 (zext i32:$in)),
4756  // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4757  // 0, 32)>;
4758  // There are several 32-bit shift/rotate instructions, however, that will
4759  // clear the higher-order bits of their output, rendering the RLDICL
4760  // unnecessary. When that happens, we remove it here, and redefine the
4761  // relevant 32-bit operation to be a 64-bit operation.
4762 
4763  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4764  ++Position;
4765 
4766  bool MadeChange = false;
4767  while (Position != CurDAG->allnodes_begin()) {
4768  SDNode *N = &*--Position;
4769  // Skip dead nodes and any non-machine opcodes.
4770  if (N->use_empty() || !N->isMachineOpcode())
4771  continue;
4772 
4773  if (N->getMachineOpcode() != PPC::RLDICL)
4774  continue;
4775 
4776  if (N->getConstantOperandVal(1) != 0 ||
4777  N->getConstantOperandVal(2) != 32)
4778  continue;
4779 
4780  SDValue ISR = N->getOperand(0);
4781  if (!ISR.isMachineOpcode() ||
4782  ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4783  continue;
4784 
4785  if (!ISR.hasOneUse())
4786  continue;
4787 
4788  if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4789  continue;
4790 
4791  SDValue IDef = ISR.getOperand(0);
4792  if (!IDef.isMachineOpcode() ||
4793  IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4794  continue;
4795 
4796  // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4797  // can get rid of it.
4798 
4799  SDValue Op32 = ISR->getOperand(1);
4800  if (!Op32.isMachineOpcode())
4801  continue;
4802 
4803  // There are some 32-bit instructions that always clear the high-order 32
4804  // bits, there are also some instructions (like AND) that we can look
4805  // through.
4806  SmallPtrSet<SDNode *, 16> ToPromote;
4807  if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4808  continue;
4809 
4810  // If the ToPromote set contains nodes that have uses outside of the set
4811  // (except for the original INSERT_SUBREG), then abort the transformation.
4812  bool OutsideUse = false;
4813  for (SDNode *PN : ToPromote) {
4814  for (SDNode *UN : PN->uses()) {
4815  if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4816  OutsideUse = true;
4817  break;
4818  }
4819  }
4820 
4821  if (OutsideUse)
4822  break;
4823  }
4824  if (OutsideUse)
4825  continue;
4826 
4827  MadeChange = true;
4828 
4829  // We now know that this zero extension can be removed by promoting to
4830  // nodes in ToPromote to 64-bit operations, where for operations in the
4831  // frontier of the set, we need to insert INSERT_SUBREGs for their
4832  // operands.
4833  for (SDNode *PN : ToPromote) {
4834  unsigned NewOpcode;
4835  switch (PN->getMachineOpcode()) {
4836  default:
4837  llvm_unreachable("Don't know the 64-bit variant of this instruction");
4838  case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4839  case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4840  case PPC::SLW: NewOpcode = PPC::SLW8; break;
4841  case PPC::SRW: NewOpcode = PPC::SRW8; break;
4842  case PPC::LI: NewOpcode = PPC::LI8; break;
4843  case PPC::LIS: NewOpcode = PPC::LIS8; break;
4844  case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4845  case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4846  case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4847  case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
4848  case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4849  case PPC::OR: NewOpcode = PPC::OR8; break;
4850  case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4851  case PPC::ORI: NewOpcode = PPC::ORI8; break;
4852  case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4853  case PPC::AND: NewOpcode = PPC::AND8; break;
4854  case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4855  case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4856  }
4857 
4858  // Note: During the replacement process, the nodes will be in an
4859  // inconsistent state (some instructions will have operands with values
4860  // of the wrong type). Once done, however, everything should be right
4861  // again.
4862 
4864  for (const SDValue &V : PN->ops()) {
4865  if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4866  !isa<ConstantSDNode>(V)) {
4867  SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4868  SDNode *ReplOp =
4869  CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4870  ISR.getNode()->getVTList(), ReplOpOps);
4871  Ops.push_back(SDValue(ReplOp, 0));
4872  } else {
4873  Ops.push_back(V);
4874  }
4875  }
4876 
4877  // Because all to-be-promoted nodes only have users that are other
4878  // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4879  // the i32 result value type with i64.
4880 
4881  SmallVector<EVT, 2> NewVTs;
4882  SDVTList VTs = PN->getVTList();
4883  for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4884  if (VTs.VTs[i] == MVT::i32)
4885  NewVTs.push_back(MVT::i64);
4886  else
4887  NewVTs.push_back(VTs.VTs[i]);
4888 
4889  DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4890  DEBUG(PN->dump(CurDAG));
4891 
4892  CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4893 
4894  DEBUG(dbgs() << "\nNew: ");
4895  DEBUG(PN->dump(CurDAG));
4896  DEBUG(dbgs() << "\n");
4897  }
4898 
4899  // Now we replace the original zero extend and its associated INSERT_SUBREG
4900  // with the value feeding the INSERT_SUBREG (which has now been promoted to
4901  // return an i64).
4902 
4903  DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4904  DEBUG(N->dump(CurDAG));
4905  DEBUG(dbgs() << "\nNew: ");
4906  DEBUG(Op32.getNode()->dump(CurDAG));
4907  DEBUG(dbgs() << "\n");
4908 
4909  ReplaceUses(N, Op32.getNode());
4910  }
4911 
4912  if (MadeChange)
4913  CurDAG->RemoveDeadNodes();
4914 }
4915 
4916 void PPCDAGToDAGISel::PeepholePPC64() {
4917  // These optimizations are currently supported only for 64-bit SVR4.
4918  if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4919  return;
4920 
4921  SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4922  ++Position;
4923 
4924  while (Position != CurDAG->allnodes_begin()) {
4925  SDNode *N = &*--Position;
4926  // Skip dead nodes and any non-machine opcodes.
4927  if (N->use_empty() || !N->isMachineOpcode())
4928  continue;
4929 
4930  unsigned FirstOp;
4931  unsigned StorageOpcode = N->getMachineOpcode();
4932 
4933  switch (StorageOpcode) {
4934  default: continue;
4935 
4936  case PPC::LBZ:
4937  case PPC::LBZ8:
4938  case PPC::LD:
4939  case PPC::LFD:
4940  case PPC::LFS:
4941  case PPC::LHA:
4942  case PPC::LHA8:
4943  case PPC::LHZ:
4944  case PPC::LHZ8:
4945  case PPC::LWA:
4946  case PPC::LWZ:
4947  case PPC::LWZ8:
4948  FirstOp = 0;
4949  break;
4950 
4951  case PPC::STB:
4952  case PPC::STB8:
4953  case PPC::STD:
4954  case PPC::STFD:
4955  case PPC::STFS:
4956  case PPC::STH:
4957  case PPC::STH8:
4958  case PPC::STW:
4959  case PPC::STW8:
4960  FirstOp = 1;
4961  break;
4962  }
4963 
4964  // If this is a load or store with a zero offset, or within the alignment,
4965  // we may be able to fold an add-immediate into the memory operation.
4966  // The check against alignment is below, as it can't occur until we check
4967  // the arguments to N
4968  if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4969  continue;
4970 
4971  SDValue Base = N->getOperand(FirstOp + 1);
4972  if (!Base.isMachineOpcode())
4973  continue;
4974 
4975  unsigned Flags = 0;
4976  bool ReplaceFlags = true;
4977 
4978  // When the feeding operation is an add-immediate of some sort,
4979  // determine whether we need to add relocation information to the
4980  // target flags on the immediate operand when we fold it into the
4981  // load instruction.
4982  //
4983  // For something like ADDItocL, the relocation information is
4984  // inferred from the opcode; when we process it in the AsmPrinter,
4985  // we add the necessary relocation there. A load, though, can receive
4986  // relocation from various flavors of ADDIxxx, so we need to carry
4987  // the relocation information in the target flags.
4988  switch (Base.getMachineOpcode()) {
4989  default: continue;
4990 
4991  case PPC::ADDI8:
4992  case PPC::ADDI:
4993  // In some cases (such as TLS) the relocation information
4994  // is already in place on the operand, so copying the operand
4995  // is sufficient.
4996  ReplaceFlags = false;
4997  // For these cases, the immediate may not be divisible by 4, in
4998  // which case the fold is illegal for DS-form instructions. (The
4999  // other cases provide aligned addresses and are always safe.)
5000  if ((StorageOpcode == PPC::LWA ||
5001  StorageOpcode == PPC::LD ||
5002  StorageOpcode == PPC::STD) &&
5003  (!isa<ConstantSDNode>(Base.getOperand(1)) ||
5004  Base.getConstantOperandVal(1) % 4 != 0))
5005  continue;
5006  break;
5007  case PPC::ADDIdtprelL:
5008  Flags = PPCII::MO_DTPREL_LO;
5009  break;
5010  case PPC::ADDItlsldL:
5011  Flags = PPCII::MO_TLSLD_LO;
5012  break;
5013  case PPC::ADDItocL:
5014  Flags = PPCII::MO_TOC_LO;
5015  break;
5016  }
5017 
5018  SDValue ImmOpnd = Base.getOperand(1);
5019 
5020  // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
5021  // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
5022  // we might have needed different @ha relocation values for the offset
5023  // pointers).
5024  int MaxDisplacement = 7;
5025  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5026  const GlobalValue *GV = GA->getGlobal();
5027  MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
5028  }
5029 
5030  bool UpdateHBase = false;
5031  SDValue HBase = Base.getOperand(0);
5032 
5033  int Offset = N->getConstantOperandVal(FirstOp);
5034  if (ReplaceFlags) {
5035  if (Offset < 0 || Offset > MaxDisplacement) {
5036  // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
5037  // one use, then we can do this for any offset, we just need to also
5038  // update the offset (i.e. the symbol addend) on the addis also.
5039  if (Base.getMachineOpcode() != PPC::ADDItocL)
5040  continue;
5041 
5042  if (!HBase.isMachineOpcode() ||
5043  HBase.getMachineOpcode() != PPC::ADDIStocHA)
5044  continue;
5045 
5046  if (!Base.hasOneUse() || !HBase.hasOneUse())
5047  continue;
5048 
5049  SDValue HImmOpnd = HBase.getOperand(1);
5050  if (HImmOpnd != ImmOpnd)
5051  continue;
5052 
5053  UpdateHBase = true;
5054  }
5055  } else {
5056  // If we're directly folding the addend from an addi instruction, then:
5057  // 1. In general, the offset on the memory access must be zero.
5058  // 2. If the addend is a constant, then it can be combined with a
5059  // non-zero offset, but only if the result meets the encoding
5060  // requirements.
5061  if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
5062  Offset += C->getSExtValue();
5063 
5064  if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
5065  StorageOpcode == PPC::STD) && (Offset % 4) != 0)
5066  continue;
5067 
5068  if (!isInt<16>(Offset))
5069  continue;
5070 
5071  ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
5072  ImmOpnd.getValueType());
5073  } else if (Offset != 0) {
5074  continue;
5075  }
5076  }
5077 
5078  // We found an opportunity. Reverse the operands from the add
5079  // immediate and substitute them into the load or store. If
5080  // needed, update the target flags for the immediate operand to
5081  // reflect the necessary relocation information.
5082  DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
5083  DEBUG(Base->dump(CurDAG));
5084  DEBUG(dbgs() << "\nN: ");
5085  DEBUG(N->dump(CurDAG));
5086  DEBUG(dbgs() << "\n");
5087 
5088  // If the relocation information isn't already present on the
5089  // immediate operand, add it now.
5090  if (ReplaceFlags) {
5091  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5092  SDLoc dl(GA);
5093  const GlobalValue *GV = GA->getGlobal();
5094  // We can't perform this optimization for data whose alignment
5095  // is insufficient for the instruction encoding.
5096  if (GV->getAlignment() < 4 &&
5097  (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
5098  StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
5099  DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
5100  continue;
5101  }
5102  ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
5103  } else if (ConstantPoolSDNode *CP =
5104  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
5105  const Constant *C = CP->getConstVal();
5106  ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
5107  CP->getAlignment(),
5108  Offset, Flags);
5109  }
5110  }
5111 
5112  if (FirstOp == 1) // Store
5113  (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
5114  Base.getOperand(0), N->getOperand(3));
5115  else // Load
5116  (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
5117  N->getOperand(2));
5118 
5119  if (UpdateHBase)
5120  (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
5121  ImmOpnd);
5122 
5123  // The add-immediate may now be dead, in which case remove it.
5124  if (Base.getNode()->use_empty())
5125  CurDAG->RemoveDeadNode(Base.getNode());
5126  }
5127 }
5128 
5129 /// createPPCISelDag - This pass converts a legalized DAG into a
5130 /// PowerPC-specific DAG, ready for instruction scheduling.
5131 ///
5133  CodeGenOpt::Level OptLevel) {
5134  return new PPCDAGToDAGISel(TM, OptLevel);
5135 }
constexpr bool isUInt< 32 >(uint64_t x)
Definition: MathExtras.h:341
bool use_empty() const
Return true if there are no uses of this node.
SDValue getValue(unsigned R) const
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
T findLastSet(T Val, ZeroBehavior ZB=ZB_Max)
Get the index of the last set bit starting from the least significant bit.
Definition: MathExtras.h:236
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1542
STATISTIC(NumFunctions,"Total number of functions")
static cl::opt< bool > UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), cl::desc("use aggressive ppc isel for bit permutations"), cl::Hidden)
BR_CC - Conditional branch.
Definition: ISDOpcodes.h:616
GPRC = address of GLOBAL_OFFSET_TABLE.
bool hasOneUse() const
Return true if there is exactly one use of this node.
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition: ISDOpcodes.h:341
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:858
SDVTList getVTList() const
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
VRRC = VADD_SPLAT Elt, EltSize - Temporary node to be expanded during instruction selection to optimi...
static int getRecordFormOpcode(unsigned Opcode)
static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG)
Does this SDValue have any uses for which keeping the value in a GPR is appropriate.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
unsigned getID() const
Return the register class ID number.
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition: ISDOpcodes.h:131
bool isUnindexed() const
Return true if this is NOT a pre/post inc/dec load/store.
bool isBitwiseNot(SDValue V)
Returns true if V is a bitwise not operation.
unsigned second
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getNumOperands() const
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
unsigned getValueSizeInBits() const
Returns the size of the value in bits.
constexpr bool isInt< 16 >(int64_t x)
Definition: MathExtras.h:298
static bool isInt32Immediate(SDNode *N, unsigned &Imm)
isInt32Immediate - This method tests to see if the node is a 32-bit constant operand.
A debug info location.
Definition: DebugLoc.h:34
const SDValue & getOperand(unsigned Num) const
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS)
Helper function to make it easier to build Select's if you just have operands and don't want to check...
Definition: SelectionDAG.h:897
void setNodeId(int Id)
Set unique node id.
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned &Imm)
const SDValue & getBasePtr() const
static bool isLogicOp(unsigned Opc)
unsigned int NumVTs
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:403
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
Definition: ISDOpcodes.h:948
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
static SDNode * getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
GlobalBaseReg - On Darwin, this node represents the result of the mflr at function entry...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
static bool PeepholePPC64ZExtGather(SDValue Op32, SmallPtrSetImpl< SDNode * > &ToPromote)
A description of a memory reference used in the backend.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
const HexagonInstrInfo * TII
Shift and rotation operations.
Definition: ISDOpcodes.h:378
std::size_t countTrailingOnes(T Value, ZeroBehavior ZB=ZB_Width)
Count the number of ones from the least significant bit to the first zero bit.
Definition: MathExtras.h:470
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s), MachineInstr opcode, and operands.
Reg
All possible values of the reg field in the ModR/M byte.
unsigned getMachineOpcode() const
int getMaskElt(unsigned Idx) const
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
This file implements a class to represent arbitrary precision integral constant values and operations...
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
iterator_range< allnodes_iterator > allnodes()
Definition: SelectionDAG.h:423
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const MachineBasicBlock & front() const
#define F(x, y, z)
Definition: MD5.cpp:55
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:403
CHAIN = BDNZ CHAIN, DESTBB - These are used to create counter-based loops.
#define T
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition: ISDOpcodes.h:397
R32 = MFOCRF(CRREG, INFLAG) - Represents the MFOCRF instruction.
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:909
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification, or lowering of the constant.
Definition: ISDOpcodes.h:125
EVT getMemoryVT() const
Return the type of the in-memory value.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
Definition: SelectionDAG.h:546
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
Definition: ISDOpcodes.h:942
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:376
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
This class is used to represent ISD::STORE nodes.
TargetInstrInfo - Interface to description of machine instruction set.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:629
SDNode * getNode() const
get the SDNode which holds the desired result
Function Alias Analysis false
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
cl::opt< bool > ANDIGlueBug("expose-ppc-andi-glue-bug", cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden)
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
Machine Value Type.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
const SDValue & getOperand(unsigned i) const
This is an important base class in LLVM.
Definition: Constant.h:42
MO_NLP_FLAG - If this bit is set, the symbol reference is actually to the non_lazy_ptr for the global...
Definition: PPC.h:77
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC)
CHAIN,FLAG = MTCTR(VAL, CHAIN[, INFLAG]) - Directly corresponds to a MTCTR instruction.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static ManagedStatic< OptionRegistry > OR
Definition: Options.cpp:31
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
This class provides iterator support for SDUse operands that use a specific SDNode.
const PPCTargetLowering * getTargetLowering() const override
Definition: PPCSubtarget.h:180
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
static bool isInt64Immediate(SDNode *N, uint64_t &Imm)
isInt64Immediate - This method tests to see if the node is a 64-bit constant operand.
unsigned getOpcode() const
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition: ISDOpcodes.h:57
iterator begin() const
Definition: SmallPtrSet.h:398
void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
Common code between 32-bit and 64-bit PowerPC targets.
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
Extended Value Type.
Definition: ValueTypes.h:34
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
ISD::MemIndexedMode getAddressingMode() const
Return the addressing mode for this load or store: unindexed, pre-inc, pre-dec, post-inc, or post-dec.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
Definition: SelectionDAG.h:431
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:45
MachineBasicBlock * MBB
MBB - The current block.
const SDValue & getOffset() const
static cl::opt< bool > BPermRewriterNoMasking("ppc-bit-perm-rewriter-stress-rotates", cl::desc("stress rotate selection in aggressive ppc isel for ""bit permutations"), cl::Hidden)
SDValue getTargetConstantPool(const Constant *C, EVT VT, unsigned Align=0, int Offset=0, unsigned char TargetFlags=0)
Definition: SelectionDAG.h:605
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
GPRC = TOC_ENTRY GA, TOC Loads the entry for GA from the TOC, where the TOC base is given by the last...
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition: Module.cpp:473
void dump() const
Dump this node, for debugging.
constexpr bool isInt< 32 >(int64_t x)
Definition: MathExtras.h:301
allnodes_const_iterator allnodes_begin() const
Definition: SelectionDAG.h:411
#define B
Definition: LargeTest.cpp:24
void computeKnownBits(SDValue Op, KnownBits &Known, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
static SDNode * getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm)
SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:209
SDNode * SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:27
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
An SDNode that represents everything that will be needed to construct a MachineInstr.
const SDValue & getChain() const
const size_t N
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
bool isMachineOpcode() const
Represents one node in the SelectionDAG.
CondCode getSetCCInverse(CondCode Operation, bool isInteger)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
These values identify relocations on immediates folded into memory operations.
Definition: PPC.h:96
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N)
Definition: SelectionDAG.h:643
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
i1 = ANDIo_1_[EQ|GT]_BIT(i32 or i64 x) - Represents the result of the eq or gt bit of CR0 after execu...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
Target - Wrapper for Target specific information.
iterator_range< use_iterator > uses()
BranchProbabilityInfo * BPI
SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, SDNode *Cst1, SDNode *Cst2)
Select(COND, TRUEVAL, FALSEVAL).
Definition: ISDOpcodes.h:388
int64_t getSExtValue() const
static use_iterator use_end()
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:444
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:447
The combination of sra[wd]i and addze used to implemented signed integer division by a power of 2...
llvm_unreachable("Unknown RegBank!")
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
iterator end() const
Definition: SmallPtrSet.h:405
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:529
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
uint64_t getConstantOperandVal(unsigned i) const
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:361
FunctionPass * createPPCISelDag(PPCTargetMachine &TM, CodeGenOpt::Level OL)
createPPCISelDag - This pass converts a legalized DAG into a PowerPC-specific DAG, ready for instruction scheduling.
bool isUndef() const
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition: ISDOpcodes.h:462
#define C
Definition: LargeTest.cpp:25
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:580
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
#define I(x, y, z)
Definition: MD5.cpp:58
ArrayRef< SDUse > ops() const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
The CMPB instruction (takes two operands of i32 or i64).
static cl::opt< bool > EnableBranchHint("ppc-use-branch-hint", cl::init(true), cl::desc("Enable static hinting of branches on ppc"), cl::Hidden)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
static unsigned getInt64Count(int64_t Imm)
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:338
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition: ISDOpcodes.h:175
EVT getValueType() const
Return the ValueType of the referenced return value.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
const unsigned Kind
unsigned getAlignment() const
Definition: Globals.cpp:96
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME)
Returns true iff Val consists of one contiguous run of 1s with any number of 0s on either side...
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:326
static uint64_t Rot64(uint64_t Imm, unsigned R)
MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo, const SDValue &DestMBB)
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
SDValue getRegister(unsigned Reg, EVT VT)
SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
CHAIN = COND_BRANCH CHAIN, CRRC, OPC, DESTBB [, INFLAG] - This corresponds to the COND_BRANCH pseudo ...
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert)
getCRIdxForSetCC - Return the index of the condition register field associated with the SetCC conditi...
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:379
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.Val alone...
#define DEBUG(X)
Definition: Debug.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
SetCC operator - This evaluates to a true value iff the condition is true.
Definition: ISDOpcodes.h:411
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
Conversion operators.
Definition: ISDOpcodes.h:441
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
Definition: SelectionDAG.h:434
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:450
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
static unsigned getInt64CountDirect(int64_t Imm)
MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num)
allocateMemRefsArray - Allocate an array to hold MachineMemOperand pointers.
virtual const TargetRegisterClass * getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const
Returns a TargetRegisterClass used for pointer values.
bool isIntS16Immediate(SDNode *N, int16_t &Imm)
isIntS16Immediate - This method tests to see if the node is either a 32-bit or 64-bit immediate...
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition: ISDOpcodes.h:349
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition: ValueTypes.h:96
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:253
XXPERMDI - The PPC XXPERMDI instruction.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode...
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned char TargetFlags=0)
Definition: SelectionDAG.h:588
BRIND - Indirect branch.
Definition: ISDOpcodes.h:600
static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, bool HasVSX, bool &Swap, bool &Negate)
void resize(size_type N)
Definition: SmallVector.h:352
This class is used to represent ISD::LOAD nodes.