PPCISelDAGToDAG.cpp revision bd5cafd9bbba2180e7179436fb29071201d5ea9f
1//===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a pattern matching instruction selector for PowerPC,
11// converting from a legalized dag to a PPC dag.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "ppc-codegen"
16#include "PPC.h"
17#include "PPCTargetMachine.h"
18#include "MCTargetDesc/PPCPredicates.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/SelectionDAG.h"
23#include "llvm/CodeGen/SelectionDAGISel.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/Constants.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalValue.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33using namespace llvm;
34
35namespace {
36  //===--------------------------------------------------------------------===//
37  /// PPCDAGToDAGISel - PPC specific code to select PPC machine
38  /// instructions for SelectionDAG operations.
39  ///
40  class PPCDAGToDAGISel : public SelectionDAGISel {
41    const PPCTargetMachine &TM;
42    const PPCTargetLowering &PPCLowering;
43    const PPCSubtarget &PPCSubTarget;
44    unsigned GlobalBaseReg;
45  public:
46    explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
47      : SelectionDAGISel(tm), TM(tm),
48        PPCLowering(*TM.getTargetLowering()),
49        PPCSubTarget(*TM.getSubtargetImpl()) {}
50
51    virtual bool runOnMachineFunction(MachineFunction &MF) {
52      // Make sure we re-emit a set of the global base reg if necessary
53      GlobalBaseReg = 0;
54      SelectionDAGISel::runOnMachineFunction(MF);
55
56      InsertVRSaveCode(MF);
57      return true;
58    }
59
60    /// getI32Imm - Return a target constant with the specified value, of type
61    /// i32.
62    inline SDValue getI32Imm(unsigned Imm) {
63      return CurDAG->getTargetConstant(Imm, MVT::i32);
64    }
65
66    /// getI64Imm - Return a target constant with the specified value, of type
67    /// i64.
68    inline SDValue getI64Imm(uint64_t Imm) {
69      return CurDAG->getTargetConstant(Imm, MVT::i64);
70    }
71
72    /// getSmallIPtrImm - Return a target constant of pointer type.
73    inline SDValue getSmallIPtrImm(unsigned Imm) {
74      return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
75    }
76
77    /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
78    /// with any number of 0s on either side.  The 1s are allowed to wrap from
79    /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
80    /// 0x0F0F0000 is not, since all 1s are not contiguous.
81    static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
82
83
84    /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
85    /// rotate and mask opcode and mask operation.
86    static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
87                                unsigned &SH, unsigned &MB, unsigned &ME);
88
89    /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
90    /// base register.  Return the virtual register that holds this value.
91    SDNode *getGlobalBaseReg();
92
93    // Select - Convert the specified operand from a target-independent to a
94    // target-specific node if it hasn't already been changed.
95    SDNode *Select(SDNode *N);
96
97    SDNode *SelectBitfieldInsert(SDNode *N);
98
99    /// SelectCC - Select a comparison of the specified values with the
100    /// specified condition code, returning the CR# of the expression.
101    SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, DebugLoc dl);
102
103    /// SelectAddrImm - Returns true if the address N can be represented by
104    /// a base register plus a signed 16-bit displacement [r+imm].
105    bool SelectAddrImm(SDValue N, SDValue &Disp,
106                       SDValue &Base) {
107      return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG);
108    }
109
110    /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
111    /// immediate field.  Because preinc imms have already been validated, just
112    /// accept it.
113    bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
114      Out = N;
115      return true;
116    }
117
118    /// SelectAddrIdx - Given the specified addressed, check to see if it can be
119    /// represented as an indexed [r+r] operation.  Returns false if it can
120    /// be represented by [r+imm], which are preferred.
121    bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
122      return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
123    }
124
125    /// SelectAddrIdxOnly - Given the specified addressed, force it to be
126    /// represented as an indexed [r+r] operation.
127    bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
128      return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
129    }
130
131    /// SelectAddrImmShift - Returns true if the address N can be represented by
132    /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
133    /// for use by STD and friends.
134    bool SelectAddrImmShift(SDValue N, SDValue &Disp, SDValue &Base) {
135      return PPCLowering.SelectAddressRegImmShift(N, Disp, Base, *CurDAG);
136    }
137
138    /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
139    /// inline asm expressions.  It is always correct to compute the value into
140    /// a register.  The case of adding a (possibly relocatable) constant to a
141    /// register can be improved, but it is wrong to substitute Reg+Reg for
142    /// Reg in an asm, because the load or store opcode would have to change.
143   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
144                                              char ConstraintCode,
145                                              std::vector<SDValue> &OutOps) {
146      OutOps.push_back(Op);
147      return false;
148    }
149
150    void InsertVRSaveCode(MachineFunction &MF);
151
152    virtual const char *getPassName() const {
153      return "PowerPC DAG->DAG Pattern Instruction Selection";
154    }
155
156// Include the pieces autogenerated from the target description.
157#include "PPCGenDAGISel.inc"
158
159private:
160    SDNode *SelectSETCC(SDNode *N);
161  };
162}
163
164/// InsertVRSaveCode - Once the entire function has been instruction selected,
165/// all virtual registers are created and all machine instructions are built,
166/// check to see if we need to save/restore VRSAVE.  If so, do it.
167void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
168  // Check to see if this function uses vector registers, which means we have to
169  // save and restore the VRSAVE register and update it with the regs we use.
170  //
171  // In this case, there will be virtual registers of vector type created
172  // by the scheduler.  Detect them now.
173  bool HasVectorVReg = false;
174  for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
175    unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
176    if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
177      HasVectorVReg = true;
178      break;
179    }
180  }
181  if (!HasVectorVReg) return;  // nothing to do.
182
183  // If we have a vector register, we want to emit code into the entry and exit
184  // blocks to save and restore the VRSAVE register.  We do this here (instead
185  // of marking all vector instructions as clobbering VRSAVE) for two reasons:
186  //
187  // 1. This (trivially) reduces the load on the register allocator, by not
188  //    having to represent the live range of the VRSAVE register.
189  // 2. This (more significantly) allows us to create a temporary virtual
190  //    register to hold the saved VRSAVE value, allowing this temporary to be
191  //    register allocated, instead of forcing it to be spilled to the stack.
192
193  // Create two vregs - one to hold the VRSAVE register that is live-in to the
194  // function and one for the value after having bits or'd into it.
195  unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
196  unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
197
198  const TargetInstrInfo &TII = *TM.getInstrInfo();
199  MachineBasicBlock &EntryBB = *Fn.begin();
200  DebugLoc dl;
201  // Emit the following code into the entry block:
202  // InVRSAVE = MFVRSAVE
203  // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
204  // MTVRSAVE UpdatedVRSAVE
205  MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
206  BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
207  BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
208          UpdatedVRSAVE).addReg(InVRSAVE);
209  BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
210
211  // Find all return blocks, outputting a restore in each epilog.
212  for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
213    if (!BB->empty() && BB->back().isReturn()) {
214      IP = BB->end(); --IP;
215
216      // Skip over all terminator instructions, which are part of the return
217      // sequence.
218      MachineBasicBlock::iterator I2 = IP;
219      while (I2 != BB->begin() && (--I2)->isTerminator())
220        IP = I2;
221
222      // Emit: MTVRSAVE InVRSave
223      BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
224    }
225  }
226}
227
228
229/// getGlobalBaseReg - Output the instructions required to put the
230/// base address to use for accessing globals into a register.
231///
232SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
233  if (!GlobalBaseReg) {
234    const TargetInstrInfo &TII = *TM.getInstrInfo();
235    // Insert the set of GlobalBaseReg into the first MBB of the function
236    MachineBasicBlock &FirstMBB = MF->front();
237    MachineBasicBlock::iterator MBBI = FirstMBB.begin();
238    DebugLoc dl;
239
240    if (PPCLowering.getPointerTy() == MVT::i32) {
241      GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
242      BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
243      BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
244    } else {
245      GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RCRegClass);
246      BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
247      BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
248    }
249  }
250  return CurDAG->getRegister(GlobalBaseReg,
251                             PPCLowering.getPointerTy()).getNode();
252}
253
254/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
255/// or 64-bit immediate, and if the value can be accurately represented as a
256/// sign extension from a 16-bit value.  If so, this returns true and the
257/// immediate.
258static bool isIntS16Immediate(SDNode *N, short &Imm) {
259  if (N->getOpcode() != ISD::Constant)
260    return false;
261
262  Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
263  if (N->getValueType(0) == MVT::i32)
264    return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
265  else
266    return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
267}
268
269static bool isIntS16Immediate(SDValue Op, short &Imm) {
270  return isIntS16Immediate(Op.getNode(), Imm);
271}
272
273
274/// isInt32Immediate - This method tests to see if the node is a 32-bit constant
275/// operand. If so Imm will receive the 32-bit value.
276static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
277  if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
278    Imm = cast<ConstantSDNode>(N)->getZExtValue();
279    return true;
280  }
281  return false;
282}
283
284/// isInt64Immediate - This method tests to see if the node is a 64-bit constant
285/// operand.  If so Imm will receive the 64-bit value.
286static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
287  if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
288    Imm = cast<ConstantSDNode>(N)->getZExtValue();
289    return true;
290  }
291  return false;
292}
293
294// isInt32Immediate - This method tests to see if a constant operand.
295// If so Imm will receive the 32 bit value.
296static bool isInt32Immediate(SDValue N, unsigned &Imm) {
297  return isInt32Immediate(N.getNode(), Imm);
298}
299
300
301// isOpcWithIntImmediate - This method tests to see if the node is a specific
302// opcode and that it has a immediate integer right operand.
303// If so Imm will receive the 32 bit value.
304static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
305  return N->getOpcode() == Opc
306         && isInt32Immediate(N->getOperand(1).getNode(), Imm);
307}
308
309bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
310  if (isShiftedMask_32(Val)) {
311    // look for the first non-zero bit
312    MB = CountLeadingZeros_32(Val);
313    // look for the first zero bit after the run of ones
314    ME = CountLeadingZeros_32((Val - 1) ^ Val);
315    return true;
316  } else {
317    Val = ~Val; // invert mask
318    if (isShiftedMask_32(Val)) {
319      // effectively look for the first zero bit
320      ME = CountLeadingZeros_32(Val) - 1;
321      // effectively look for the first one bit after the run of zeros
322      MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
323      return true;
324    }
325  }
326  // no run present
327  return false;
328}
329
330bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
331                                      bool isShiftMask, unsigned &SH,
332                                      unsigned &MB, unsigned &ME) {
333  // Don't even go down this path for i64, since different logic will be
334  // necessary for rldicl/rldicr/rldimi.
335  if (N->getValueType(0) != MVT::i32)
336    return false;
337
338  unsigned Shift  = 32;
339  unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
340  unsigned Opcode = N->getOpcode();
341  if (N->getNumOperands() != 2 ||
342      !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
343    return false;
344
345  if (Opcode == ISD::SHL) {
346    // apply shift left to mask if it comes first
347    if (isShiftMask) Mask = Mask << Shift;
348    // determine which bits are made indeterminant by shift
349    Indeterminant = ~(0xFFFFFFFFu << Shift);
350  } else if (Opcode == ISD::SRL) {
351    // apply shift right to mask if it comes first
352    if (isShiftMask) Mask = Mask >> Shift;
353    // determine which bits are made indeterminant by shift
354    Indeterminant = ~(0xFFFFFFFFu >> Shift);
355    // adjust for the left rotate
356    Shift = 32 - Shift;
357  } else if (Opcode == ISD::ROTL) {
358    Indeterminant = 0;
359  } else {
360    return false;
361  }
362
363  // if the mask doesn't intersect any Indeterminant bits
364  if (Mask && !(Mask & Indeterminant)) {
365    SH = Shift & 31;
366    // make sure the mask is still a mask (wrap arounds may not be)
367    return isRunOfOnes(Mask, MB, ME);
368  }
369  return false;
370}
371
372/// SelectBitfieldInsert - turn an or of two masked values into
373/// the rotate left word immediate then mask insert (rlwimi) instruction.
374SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
375  SDValue Op0 = N->getOperand(0);
376  SDValue Op1 = N->getOperand(1);
377  DebugLoc dl = N->getDebugLoc();
378
379  APInt LKZ, LKO, RKZ, RKO;
380  CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
381  CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
382
383  unsigned TargetMask = LKZ.getZExtValue();
384  unsigned InsertMask = RKZ.getZExtValue();
385
386  if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
387    unsigned Op0Opc = Op0.getOpcode();
388    unsigned Op1Opc = Op1.getOpcode();
389    unsigned Value, SH = 0;
390    TargetMask = ~TargetMask;
391    InsertMask = ~InsertMask;
392
393    // If the LHS has a foldable shift and the RHS does not, then swap it to the
394    // RHS so that we can fold the shift into the insert.
395    if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
396      if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
397          Op0.getOperand(0).getOpcode() == ISD::SRL) {
398        if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
399            Op1.getOperand(0).getOpcode() != ISD::SRL) {
400          std::swap(Op0, Op1);
401          std::swap(Op0Opc, Op1Opc);
402          std::swap(TargetMask, InsertMask);
403        }
404      }
405    } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
406      if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
407          Op1.getOperand(0).getOpcode() != ISD::SRL) {
408        std::swap(Op0, Op1);
409        std::swap(Op0Opc, Op1Opc);
410        std::swap(TargetMask, InsertMask);
411      }
412    }
413
414    unsigned MB, ME;
415    if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
416      SDValue Tmp1, Tmp2;
417
418      if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
419          isInt32Immediate(Op1.getOperand(1), Value)) {
420        Op1 = Op1.getOperand(0);
421        SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
422      }
423      if (Op1Opc == ISD::AND) {
424        unsigned SHOpc = Op1.getOperand(0).getOpcode();
425        if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
426            isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
427          Op1 = Op1.getOperand(0).getOperand(0);
428          SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
429        } else {
430          Op1 = Op1.getOperand(0);
431        }
432      }
433
434      SH &= 31;
435      SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
436                          getI32Imm(ME) };
437      return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
438    }
439  }
440  return 0;
441}
442
443/// SelectCC - Select a comparison of the specified values with the specified
444/// condition code, returning the CR# of the expression.
445SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
446                                    ISD::CondCode CC, DebugLoc dl) {
447  // Always select the LHS.
448  unsigned Opc;
449
450  if (LHS.getValueType() == MVT::i32) {
451    unsigned Imm;
452    if (CC == ISD::SETEQ || CC == ISD::SETNE) {
453      if (isInt32Immediate(RHS, Imm)) {
454        // SETEQ/SETNE comparison with 16-bit immediate, fold it.
455        if (isUInt<16>(Imm))
456          return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
457                                                getI32Imm(Imm & 0xFFFF)), 0);
458        // If this is a 16-bit signed immediate, fold it.
459        if (isInt<16>((int)Imm))
460          return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
461                                                getI32Imm(Imm & 0xFFFF)), 0);
462
463        // For non-equality comparisons, the default code would materialize the
464        // constant, then compare against it, like this:
465        //   lis r2, 4660
466        //   ori r2, r2, 22136
467        //   cmpw cr0, r3, r2
468        // Since we are just comparing for equality, we can emit this instead:
469        //   xoris r0,r3,0x1234
470        //   cmplwi cr0,r0,0x5678
471        //   beq cr0,L6
472        SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
473                                           getI32Imm(Imm >> 16)), 0);
474        return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
475                                              getI32Imm(Imm & 0xFFFF)), 0);
476      }
477      Opc = PPC::CMPLW;
478    } else if (ISD::isUnsignedIntSetCC(CC)) {
479      if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
480        return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
481                                              getI32Imm(Imm & 0xFFFF)), 0);
482      Opc = PPC::CMPLW;
483    } else {
484      short SImm;
485      if (isIntS16Immediate(RHS, SImm))
486        return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
487                                              getI32Imm((int)SImm & 0xFFFF)),
488                         0);
489      Opc = PPC::CMPW;
490    }
491  } else if (LHS.getValueType() == MVT::i64) {
492    uint64_t Imm;
493    if (CC == ISD::SETEQ || CC == ISD::SETNE) {
494      if (isInt64Immediate(RHS.getNode(), Imm)) {
495        // SETEQ/SETNE comparison with 16-bit immediate, fold it.
496        if (isUInt<16>(Imm))
497          return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
498                                                getI32Imm(Imm & 0xFFFF)), 0);
499        // If this is a 16-bit signed immediate, fold it.
500        if (isInt<16>(Imm))
501          return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
502                                                getI32Imm(Imm & 0xFFFF)), 0);
503
504        // For non-equality comparisons, the default code would materialize the
505        // constant, then compare against it, like this:
506        //   lis r2, 4660
507        //   ori r2, r2, 22136
508        //   cmpd cr0, r3, r2
509        // Since we are just comparing for equality, we can emit this instead:
510        //   xoris r0,r3,0x1234
511        //   cmpldi cr0,r0,0x5678
512        //   beq cr0,L6
513        if (isUInt<32>(Imm)) {
514          SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
515                                             getI64Imm(Imm >> 16)), 0);
516          return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
517                                                getI64Imm(Imm & 0xFFFF)), 0);
518        }
519      }
520      Opc = PPC::CMPLD;
521    } else if (ISD::isUnsignedIntSetCC(CC)) {
522      if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
523        return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
524                                              getI64Imm(Imm & 0xFFFF)), 0);
525      Opc = PPC::CMPLD;
526    } else {
527      short SImm;
528      if (isIntS16Immediate(RHS, SImm))
529        return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
530                                              getI64Imm(SImm & 0xFFFF)),
531                         0);
532      Opc = PPC::CMPD;
533    }
534  } else if (LHS.getValueType() == MVT::f32) {
535    Opc = PPC::FCMPUS;
536  } else {
537    assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
538    Opc = PPC::FCMPUD;
539  }
540  return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
541}
542
543static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
544  switch (CC) {
545  case ISD::SETUEQ:
546  case ISD::SETONE:
547  case ISD::SETOLE:
548  case ISD::SETOGE:
549    llvm_unreachable("Should be lowered by legalize!");
550  default: llvm_unreachable("Unknown condition!");
551  case ISD::SETOEQ:
552  case ISD::SETEQ:  return PPC::PRED_EQ;
553  case ISD::SETUNE:
554  case ISD::SETNE:  return PPC::PRED_NE;
555  case ISD::SETOLT:
556  case ISD::SETLT:  return PPC::PRED_LT;
557  case ISD::SETULE:
558  case ISD::SETLE:  return PPC::PRED_LE;
559  case ISD::SETOGT:
560  case ISD::SETGT:  return PPC::PRED_GT;
561  case ISD::SETUGE:
562  case ISD::SETGE:  return PPC::PRED_GE;
563  case ISD::SETO:   return PPC::PRED_NU;
564  case ISD::SETUO:  return PPC::PRED_UN;
565    // These two are invalid for floating point.  Assume we have int.
566  case ISD::SETULT: return PPC::PRED_LT;
567  case ISD::SETUGT: return PPC::PRED_GT;
568  }
569}
570
571/// getCRIdxForSetCC - Return the index of the condition register field
572/// associated with the SetCC condition, and whether or not the field is
573/// treated as inverted.  That is, lt = 0; ge = 0 inverted.
574///
575/// If this returns with Other != -1, then the returned comparison is an or of
576/// two simpler comparisons.  In this case, Invert is guaranteed to be false.
577static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert, int &Other) {
578  Invert = false;
579  Other = -1;
580  switch (CC) {
581  default: llvm_unreachable("Unknown condition!");
582  case ISD::SETOLT:
583  case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
584  case ISD::SETOGT:
585  case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
586  case ISD::SETOEQ:
587  case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
588  case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
589  case ISD::SETUGE:
590  case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
591  case ISD::SETULE:
592  case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
593  case ISD::SETUNE:
594  case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
595  case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
596  case ISD::SETUEQ:
597  case ISD::SETOGE:
598  case ISD::SETOLE:
599  case ISD::SETONE:
600    llvm_unreachable("Invalid branch code: should be expanded by legalize");
601  // These are invalid for floating point.  Assume integer.
602  case ISD::SETULT: return 0;
603  case ISD::SETUGT: return 1;
604  }
605}
606
607SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
608  DebugLoc dl = N->getDebugLoc();
609  unsigned Imm;
610  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
611  EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
612  bool isPPC64 = (PtrVT == MVT::i64);
613
614  if (isInt32Immediate(N->getOperand(1), Imm)) {
615    // We can codegen setcc op, imm very efficiently compared to a brcond.
616    // Check for those cases here.
617    // setcc op, 0
618    if (Imm == 0) {
619      SDValue Op = N->getOperand(0);
620      switch (CC) {
621      default: break;
622      case ISD::SETEQ: {
623        Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
624        SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
625        return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
626      }
627      case ISD::SETNE: {
628        if (isPPC64) break;
629        SDValue AD =
630          SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
631                                         Op, getI32Imm(~0U)), 0);
632        return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
633                                    AD.getValue(1));
634      }
635      case ISD::SETLT: {
636        SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
637        return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
638      }
639      case ISD::SETGT: {
640        SDValue T =
641          SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
642        T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
643        SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
644        return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
645      }
646      }
647    } else if (Imm == ~0U) {        // setcc op, -1
648      SDValue Op = N->getOperand(0);
649      switch (CC) {
650      default: break;
651      case ISD::SETEQ:
652        if (isPPC64) break;
653        Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
654                                            Op, getI32Imm(1)), 0);
655        return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
656                              SDValue(CurDAG->getMachineNode(PPC::LI, dl,
657                                                             MVT::i32,
658                                                             getI32Imm(0)), 0),
659                                      Op.getValue(1));
660      case ISD::SETNE: {
661        if (isPPC64) break;
662        Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
663        SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
664                                            Op, getI32Imm(~0U));
665        return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
666                                    Op, SDValue(AD, 1));
667      }
668      case ISD::SETLT: {
669        SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
670                                                    getI32Imm(1)), 0);
671        SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
672                                                    Op), 0);
673        SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
674        return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
675      }
676      case ISD::SETGT: {
677        SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
678        Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4),
679                     0);
680        return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
681                                    getI32Imm(1));
682      }
683      }
684    }
685  }
686
687  bool Inv;
688  int OtherCondIdx;
689  unsigned Idx = getCRIdxForSetCC(CC, Inv, OtherCondIdx);
690  SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
691  SDValue IntCR;
692
693  // Force the ccreg into CR7.
694  SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
695
696  SDValue InFlag(0, 0);  // Null incoming flag value.
697  CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
698                               InFlag).getValue(1);
699
700  if (PPCSubTarget.hasMFOCRF() && OtherCondIdx == -1)
701    IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
702                                           CCReg), 0);
703 else
704    IntCR = SDValue(CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
705                                           CR7Reg, CCReg), 0);
706
707  SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
708                      getI32Imm(31), getI32Imm(31) };
709  if (OtherCondIdx == -1 && !Inv)
710    return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
711
712  // Get the specified bit.
713  SDValue Tmp =
714    SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
715  if (Inv) {
716    assert(OtherCondIdx == -1 && "Can't have split plus negation");
717    return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
718  }
719
720  // Otherwise, we have to turn an operation like SETONE -> SETOLT | SETOGT.
721  // We already got the bit for the first part of the comparison (e.g. SETULE).
722
723  // Get the other bit of the comparison.
724  Ops[1] = getI32Imm((32-(3-OtherCondIdx)) & 31);
725  SDValue OtherCond =
726    SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
727
728  return CurDAG->SelectNodeTo(N, PPC::OR, MVT::i32, Tmp, OtherCond);
729}
730
731
732// Select - Convert the specified operand from a target-independent to a
733// target-specific node if it hasn't already been changed.
734SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
735  DebugLoc dl = N->getDebugLoc();
736  if (N->isMachineOpcode())
737    return NULL;   // Already selected.
738
739  switch (N->getOpcode()) {
740  default: break;
741
742  case ISD::Constant: {
743    if (N->getValueType(0) == MVT::i64) {
744      // Get 64 bit value.
745      int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
746      // Assume no remaining bits.
747      unsigned Remainder = 0;
748      // Assume no shift required.
749      unsigned Shift = 0;
750
751      // If it can't be represented as a 32 bit value.
752      if (!isInt<32>(Imm)) {
753        Shift = CountTrailingZeros_64(Imm);
754        int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
755
756        // If the shifted value fits 32 bits.
757        if (isInt<32>(ImmSh)) {
758          // Go with the shifted value.
759          Imm = ImmSh;
760        } else {
761          // Still stuck with a 64 bit value.
762          Remainder = Imm;
763          Shift = 32;
764          Imm >>= 32;
765        }
766      }
767
768      // Intermediate operand.
769      SDNode *Result;
770
771      // Handle first 32 bits.
772      unsigned Lo = Imm & 0xFFFF;
773      unsigned Hi = (Imm >> 16) & 0xFFFF;
774
775      // Simple value.
776      if (isInt<16>(Imm)) {
777       // Just the Lo bits.
778        Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
779      } else if (Lo) {
780        // Handle the Hi bits.
781        unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
782        Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
783        // And Lo bits.
784        Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
785                                        SDValue(Result, 0), getI32Imm(Lo));
786      } else {
787       // Just the Hi bits.
788        Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
789      }
790
791      // If no shift, we're done.
792      if (!Shift) return Result;
793
794      // Shift for next step if the upper 32-bits were not zero.
795      if (Imm) {
796        Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
797                                        SDValue(Result, 0),
798                                        getI32Imm(Shift),
799                                        getI32Imm(63 - Shift));
800      }
801
802      // Add in the last bits as required.
803      if ((Hi = (Remainder >> 16) & 0xFFFF)) {
804        Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
805                                        SDValue(Result, 0), getI32Imm(Hi));
806      }
807      if ((Lo = Remainder & 0xFFFF)) {
808        Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
809                                        SDValue(Result, 0), getI32Imm(Lo));
810      }
811
812      return Result;
813    }
814    break;
815  }
816
817  case ISD::SETCC:
818    return SelectSETCC(N);
819  case PPCISD::GlobalBaseReg:
820    return getGlobalBaseReg();
821
822  case ISD::FrameIndex: {
823    int FI = cast<FrameIndexSDNode>(N)->getIndex();
824    SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
825    unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
826    if (N->hasOneUse())
827      return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
828                                  getSmallIPtrImm(0));
829    return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
830                                  getSmallIPtrImm(0));
831  }
832
833  case PPCISD::MFCR: {
834    SDValue InFlag = N->getOperand(1);
835    // Use MFOCRF if supported.
836    if (PPCSubTarget.hasMFOCRF())
837      return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
838                                    N->getOperand(0), InFlag);
839    else
840      return CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
841                                    N->getOperand(0), InFlag);
842  }
843
844  case ISD::SDIV: {
845    // FIXME: since this depends on the setting of the carry flag from the srawi
846    //        we should really be making notes about that for the scheduler.
847    // FIXME: It sure would be nice if we could cheaply recognize the
848    //        srl/add/sra pattern the dag combiner will generate for this as
849    //        sra/addze rather than having to handle sdiv ourselves.  oh well.
850    unsigned Imm;
851    if (isInt32Immediate(N->getOperand(1), Imm)) {
852      SDValue N0 = N->getOperand(0);
853      if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
854        SDNode *Op =
855          CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
856                                 N0, getI32Imm(Log2_32(Imm)));
857        return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
858                                    SDValue(Op, 0), SDValue(Op, 1));
859      } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
860        SDNode *Op =
861          CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
862                                 N0, getI32Imm(Log2_32(-Imm)));
863        SDValue PT =
864          SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
865                                         SDValue(Op, 0), SDValue(Op, 1)),
866                    0);
867        return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
868      }
869    }
870
871    // Other cases are autogenerated.
872    break;
873  }
874
875  case ISD::LOAD: {
876    // Handle preincrement loads.
877    LoadSDNode *LD = cast<LoadSDNode>(N);
878    EVT LoadedVT = LD->getMemoryVT();
879
880    // Normal loads are handled by code generated from the .td file.
881    if (LD->getAddressingMode() != ISD::PRE_INC)
882      break;
883
884    SDValue Offset = LD->getOffset();
885    if (isa<ConstantSDNode>(Offset) ||
886        Offset.getOpcode() == ISD::TargetGlobalAddress) {
887
888      unsigned Opcode;
889      bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
890      if (LD->getValueType(0) != MVT::i64) {
891        // Handle PPC32 integer and normal FP loads.
892        assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
893        switch (LoadedVT.getSimpleVT().SimpleTy) {
894          default: llvm_unreachable("Invalid PPC load type!");
895          case MVT::f64: Opcode = PPC::LFDU; break;
896          case MVT::f32: Opcode = PPC::LFSU; break;
897          case MVT::i32: Opcode = PPC::LWZU; break;
898          case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
899          case MVT::i1:
900          case MVT::i8:  Opcode = PPC::LBZU; break;
901        }
902      } else {
903        assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
904        assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
905        switch (LoadedVT.getSimpleVT().SimpleTy) {
906          default: llvm_unreachable("Invalid PPC load type!");
907          case MVT::i64: Opcode = PPC::LDU; break;
908          case MVT::i32: Opcode = PPC::LWZU8; break;
909          case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
910          case MVT::i1:
911          case MVT::i8:  Opcode = PPC::LBZU8; break;
912        }
913      }
914
915      SDValue Chain = LD->getChain();
916      SDValue Base = LD->getBasePtr();
917      SDValue Ops[] = { Offset, Base, Chain };
918      // FIXME: PPC64
919      return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
920                                    PPCLowering.getPointerTy(),
921                                    MVT::Other, Ops, 3);
922    } else {
923      llvm_unreachable("R+R preindex loads not supported yet!");
924    }
925  }
926
927  case ISD::AND: {
928    unsigned Imm, Imm2, SH, MB, ME;
929
930    // If this is an and of a value rotated between 0 and 31 bits and then and'd
931    // with a mask, emit rlwinm
932    if (isInt32Immediate(N->getOperand(1), Imm) &&
933        isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
934      SDValue Val = N->getOperand(0).getOperand(0);
935      SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
936      return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
937    }
938    // If this is just a masked value where the input is not handled above, and
939    // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
940    if (isInt32Immediate(N->getOperand(1), Imm) &&
941        isRunOfOnes(Imm, MB, ME) &&
942        N->getOperand(0).getOpcode() != ISD::ROTL) {
943      SDValue Val = N->getOperand(0);
944      SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
945      return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
946    }
947    // AND X, 0 -> 0, not "rlwinm 32".
948    if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
949      ReplaceUses(SDValue(N, 0), N->getOperand(1));
950      return NULL;
951    }
952    // ISD::OR doesn't get all the bitfield insertion fun.
953    // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
954    if (isInt32Immediate(N->getOperand(1), Imm) &&
955        N->getOperand(0).getOpcode() == ISD::OR &&
956        isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
957      unsigned MB, ME;
958      Imm = ~(Imm^Imm2);
959      if (isRunOfOnes(Imm, MB, ME)) {
960        SDValue Ops[] = { N->getOperand(0).getOperand(0),
961                            N->getOperand(0).getOperand(1),
962                            getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
963        return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
964      }
965    }
966
967    // Other cases are autogenerated.
968    break;
969  }
970  case ISD::OR:
971    if (N->getValueType(0) == MVT::i32)
972      if (SDNode *I = SelectBitfieldInsert(N))
973        return I;
974
975    // Other cases are autogenerated.
976    break;
977  case ISD::SHL: {
978    unsigned Imm, SH, MB, ME;
979    if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
980        isRotateAndMask(N, Imm, true, SH, MB, ME)) {
981      SDValue Ops[] = { N->getOperand(0).getOperand(0),
982                          getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
983      return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
984    }
985
986    // Other cases are autogenerated.
987    break;
988  }
989  case ISD::SRL: {
990    unsigned Imm, SH, MB, ME;
991    if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
992        isRotateAndMask(N, Imm, true, SH, MB, ME)) {
993      SDValue Ops[] = { N->getOperand(0).getOperand(0),
994                          getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
995      return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
996    }
997
998    // Other cases are autogenerated.
999    break;
1000  }
1001  case ISD::SELECT_CC: {
1002    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1003    EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1004    bool isPPC64 = (PtrVT == MVT::i64);
1005
1006    // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1007    if (!isPPC64)
1008      if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1009        if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1010          if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1011            if (N1C->isNullValue() && N3C->isNullValue() &&
1012                N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1013                // FIXME: Implement this optzn for PPC64.
1014                N->getValueType(0) == MVT::i32) {
1015              SDNode *Tmp =
1016                CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1017                                       N->getOperand(0), getI32Imm(~0U));
1018              return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1019                                          SDValue(Tmp, 0), N->getOperand(0),
1020                                          SDValue(Tmp, 1));
1021            }
1022
1023    SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1024    unsigned BROpc = getPredicateForSetCC(CC);
1025
1026    unsigned SelectCCOp;
1027    if (N->getValueType(0) == MVT::i32)
1028      SelectCCOp = PPC::SELECT_CC_I4;
1029    else if (N->getValueType(0) == MVT::i64)
1030      SelectCCOp = PPC::SELECT_CC_I8;
1031    else if (N->getValueType(0) == MVT::f32)
1032      SelectCCOp = PPC::SELECT_CC_F4;
1033    else if (N->getValueType(0) == MVT::f64)
1034      SelectCCOp = PPC::SELECT_CC_F8;
1035    else
1036      SelectCCOp = PPC::SELECT_CC_VRRC;
1037
1038    SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1039                        getI32Imm(BROpc) };
1040    return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1041  }
1042  case PPCISD::COND_BRANCH: {
1043    // Op #0 is the Chain.
1044    // Op #1 is the PPC::PRED_* number.
1045    // Op #2 is the CR#
1046    // Op #3 is the Dest MBB
1047    // Op #4 is the Flag.
1048    // Prevent PPC::PRED_* from being selected into LI.
1049    SDValue Pred =
1050      getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1051    SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1052      N->getOperand(0), N->getOperand(4) };
1053    return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1054  }
1055  case ISD::BR_CC: {
1056    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1057    SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1058    SDValue Ops[] = { getI32Imm(getPredicateForSetCC(CC)), CondCode,
1059                        N->getOperand(4), N->getOperand(0) };
1060    return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1061  }
1062  case ISD::BRIND: {
1063    // FIXME: Should custom lower this.
1064    SDValue Chain = N->getOperand(0);
1065    SDValue Target = N->getOperand(1);
1066    unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1067    unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1068    Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1069                                           Chain), 0);
1070    return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1071  }
1072  }
1073
1074  return SelectCode(N);
1075}
1076
1077
1078
1079/// createPPCISelDag - This pass converts a legalized DAG into a
1080/// PowerPC-specific DAG, ready for instruction scheduling.
1081///
1082FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1083  return new PPCDAGToDAGISel(TM);
1084}
1085
1086