PPCISelDAGToDAG.cpp revision bb22df31d9cf329deca2cf770885869bd7c26c94
1//===-- PPC32ISelDAGToDAG.cpp - PPC32 pattern matching inst selector ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a pattern matching instruction selector for 32 bit PowerPC,
11// converting from a legalized dag to a PPC dag.
12//
13//===----------------------------------------------------------------------===//
14
15#include "PowerPC.h"
16#include "PPC32TargetMachine.h"
17#include "PPC32ISelLowering.h"
18#include "llvm/CodeGen/MachineConstantPool.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/SSARegMap.h"
22#include "llvm/CodeGen/SelectionDAG.h"
23#include "llvm/CodeGen/SelectionDAGISel.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Constants.h"
27#include "llvm/GlobalValue.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/MathExtras.h"
30using namespace llvm;
31
32namespace {
33  Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
34  Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
35
36  //===--------------------------------------------------------------------===//
37  /// PPC32DAGToDAGISel - PPC32 specific code to select PPC32 machine
38  /// instructions for SelectionDAG operations.
39  ///
40  class PPC32DAGToDAGISel : public SelectionDAGISel {
41    PPC32TargetLowering PPC32Lowering;
42    unsigned GlobalBaseReg;
43  public:
44    PPC32DAGToDAGISel(TargetMachine &TM)
45      : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) {}
46
47    virtual bool runOnFunction(Function &Fn) {
48      // Make sure we re-emit a set of the global base reg if necessary
49      GlobalBaseReg = 0;
50      return SelectionDAGISel::runOnFunction(Fn);
51    }
52
53    /// getI32Imm - Return a target constant with the specified value, of type
54    /// i32.
55    inline SDOperand getI32Imm(unsigned Imm) {
56      return CurDAG->getTargetConstant(Imm, MVT::i32);
57    }
58
59    /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
60    /// base register.  Return the virtual register that holds this value.
61    SDOperand getGlobalBaseReg();
62
63    // Select - Convert the specified operand from a target-independent to a
64    // target-specific node if it hasn't already been changed.
65    SDOperand Select(SDOperand Op);
66
67    SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
68                                   unsigned OCHi, unsigned OCLo,
69                                   bool IsArithmetic = false,
70                                   bool Negate = false);
71    SDNode *SelectBitfieldInsert(SDNode *N);
72
73    /// SelectCC - Select a comparison of the specified values with the
74    /// specified condition code, returning the CR# of the expression.
75    SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
76
77    /// SelectAddr - Given the specified address, return the two operands for a
78    /// load/store instruction, and return true if it should be an indexed [r+r]
79    /// operation.
80    bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
81
82    SDOperand BuildSDIVSequence(SDNode *N);
83    SDOperand BuildUDIVSequence(SDNode *N);
84
85    /// InstructionSelectBasicBlock - This callback is invoked by
86    /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
87    virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
88      DEBUG(BB->dump());
89      // Select target instructions for the DAG.
90      Select(DAG.getRoot());
91      DAG.RemoveDeadNodes();
92
93      // Emit machine code to BB.
94      ScheduleAndEmitDAG(DAG);
95    }
96
97    virtual const char *getPassName() const {
98      return "PowerPC DAG->DAG Pattern Instruction Selection";
99    }
100  };
101}
102
103/// getGlobalBaseReg - Output the instructions required to put the
104/// base address to use for accessing globals into a register.
105///
106SDOperand PPC32DAGToDAGISel::getGlobalBaseReg() {
107  if (!GlobalBaseReg) {
108    // Insert the set of GlobalBaseReg into the first MBB of the function
109    MachineBasicBlock &FirstMBB = BB->getParent()->front();
110    MachineBasicBlock::iterator MBBI = FirstMBB.begin();
111    SSARegMap *RegMap = BB->getParent()->getSSARegMap();
112    GlobalBaseReg = RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
113    BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
114    BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
115  }
116  return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
117}
118
119
120// isIntImmediate - This method tests to see if a constant operand.
121// If so Imm will receive the 32 bit value.
122static bool isIntImmediate(SDNode *N, unsigned& Imm) {
123  if (N->getOpcode() == ISD::Constant) {
124    Imm = cast<ConstantSDNode>(N)->getValue();
125    return true;
126  }
127  return false;
128}
129
130// isOprShiftImm - Returns true if the specified operand is a shift opcode with
131// a immediate shift count less than 32.
132static bool isOprShiftImm(SDNode *N, unsigned& Opc, unsigned& SH) {
133  Opc = N->getOpcode();
134  return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
135    isIntImmediate(N->getOperand(1).Val, SH) && SH < 32;
136}
137
138// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
139// any number of 0s on either side.  The 1s are allowed to wrap from LSB to
140// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
141// not, since all 1s are not contiguous.
142static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
143  if (isShiftedMask_32(Val)) {
144    // look for the first non-zero bit
145    MB = CountLeadingZeros_32(Val);
146    // look for the first zero bit after the run of ones
147    ME = CountLeadingZeros_32((Val - 1) ^ Val);
148    return true;
149  } else {
150    Val = ~Val; // invert mask
151    if (isShiftedMask_32(Val)) {
152      // effectively look for the first zero bit
153      ME = CountLeadingZeros_32(Val) - 1;
154      // effectively look for the first one bit after the run of zeros
155      MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
156      return true;
157    }
158  }
159  // no run present
160  return false;
161}
162
163// isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
164// and mask opcode and mask operation.
165static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
166                            unsigned &SH, unsigned &MB, unsigned &ME) {
167  unsigned Shift  = 32;
168  unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
169  unsigned Opcode = N->getOpcode();
170  if (!isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
171    return false;
172
173  if (Opcode == ISD::SHL) {
174    // apply shift left to mask if it comes first
175    if (IsShiftMask) Mask = Mask << Shift;
176    // determine which bits are made indeterminant by shift
177    Indeterminant = ~(0xFFFFFFFFu << Shift);
178  } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) {
179    // apply shift right to mask if it comes first
180    if (IsShiftMask) Mask = Mask >> Shift;
181    // determine which bits are made indeterminant by shift
182    Indeterminant = ~(0xFFFFFFFFu >> Shift);
183    // adjust for the left rotate
184    Shift = 32 - Shift;
185  } else {
186    return false;
187  }
188
189  // if the mask doesn't intersect any Indeterminant bits
190  if (Mask && !(Mask & Indeterminant)) {
191    SH = Shift;
192    // make sure the mask is still a mask (wrap arounds may not be)
193    return isRunOfOnes(Mask, MB, ME);
194  }
195  return false;
196}
197
198// isOpcWithIntImmediate - This method tests to see if the node is a specific
199// opcode and that it has a immediate integer right operand.
200// If so Imm will receive the 32 bit value.
201static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
202  return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
203}
204
205// isOprNot - Returns true if the specified operand is an xor with immediate -1.
206static bool isOprNot(SDNode *N) {
207  unsigned Imm;
208  return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
209}
210
211// Immediate constant composers.
212// Lo16 - grabs the lo 16 bits from a 32 bit constant.
213// Hi16 - grabs the hi 16 bits from a 32 bit constant.
214// HA16 - computes the hi bits required if the lo bits are add/subtracted in
215// arithmethically.
216static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
217static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
218static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
219
220// isIntImmediate - This method tests to see if a constant operand.
221// If so Imm will receive the 32 bit value.
222static bool isIntImmediate(SDOperand N, unsigned& Imm) {
223  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
224    Imm = (unsigned)CN->getSignExtended();
225    return true;
226  }
227  return false;
228}
229
230/// SelectBitfieldInsert - turn an or of two masked values into
231/// the rotate left word immediate then mask insert (rlwimi) instruction.
232/// Returns true on success, false if the caller still needs to select OR.
233///
234/// Patterns matched:
235/// 1. or shl, and   5. or and, and
236/// 2. or and, shl   6. or shl, shr
237/// 3. or shr, and   7. or shr, shl
238/// 4. or and, shr
239SDNode *PPC32DAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
240  bool IsRotate = false;
241  unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
242  unsigned Value;
243
244  SDOperand Op0 = N->getOperand(0);
245  SDOperand Op1 = N->getOperand(1);
246
247  unsigned Op0Opc = Op0.getOpcode();
248  unsigned Op1Opc = Op1.getOpcode();
249
250  // Verify that we have the correct opcodes
251  if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
252    return false;
253  if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
254    return false;
255
256  // Generate Mask value for Target
257  if (isIntImmediate(Op0.getOperand(1), Value)) {
258    switch(Op0Opc) {
259      case ISD::SHL: TgtMask <<= Value; break;
260      case ISD::SRL: TgtMask >>= Value; break;
261      case ISD::AND: TgtMask &= Value; break;
262    }
263  } else {
264    return 0;
265  }
266
267  // Generate Mask value for Insert
268  if (isIntImmediate(Op1.getOperand(1), Value)) {
269    switch(Op1Opc) {
270      case ISD::SHL:
271        SH = Value;
272        InsMask <<= SH;
273        if (Op0Opc == ISD::SRL) IsRotate = true;
274          break;
275      case ISD::SRL:
276        SH = Value;
277        InsMask >>= SH;
278        SH = 32-SH;
279        if (Op0Opc == ISD::SHL) IsRotate = true;
280          break;
281      case ISD::AND:
282        InsMask &= Value;
283        break;
284    }
285  } else {
286    return 0;
287  }
288
289  // If both of the inputs are ANDs and one of them has a logical shift by
290  // constant as its input, make that AND the inserted value so that we can
291  // combine the shift into the rotate part of the rlwimi instruction
292  bool IsAndWithShiftOp = false;
293  if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
294    if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
295        Op1.getOperand(0).getOpcode() == ISD::SRL) {
296      if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
297        SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
298        IsAndWithShiftOp = true;
299      }
300    } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
301               Op0.getOperand(0).getOpcode() == ISD::SRL) {
302      if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
303        std::swap(Op0, Op1);
304        std::swap(TgtMask, InsMask);
305        SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
306        IsAndWithShiftOp = true;
307      }
308    }
309  }
310
311  // Verify that the Target mask and Insert mask together form a full word mask
312  // and that the Insert mask is a run of set bits (which implies both are runs
313  // of set bits).  Given that, Select the arguments and generate the rlwimi
314  // instruction.
315  unsigned MB, ME;
316  if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
317    bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
318    bool Op0IsAND = Op0Opc == ISD::AND;
319    // Check for rotlwi / rotrwi here, a special case of bitfield insert
320    // where both bitfield halves are sourced from the same value.
321    if (IsRotate && fullMask &&
322        N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
323      Op0 = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32,
324                                  Select(N->getOperand(0).getOperand(0)),
325                                  getI32Imm(SH), getI32Imm(0), getI32Imm(31));
326      return Op0.Val;
327    }
328    SDOperand Tmp1 = (Op0IsAND && fullMask) ? Select(Op0.getOperand(0))
329                                            : Select(Op0);
330    SDOperand Tmp2 = IsAndWithShiftOp ? Select(Op1.getOperand(0).getOperand(0))
331                                      : Select(Op1.getOperand(0));
332    Op0 = CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
333                                getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
334    return Op0.Val;
335  }
336  return 0;
337}
338
339// SelectIntImmediateExpr - Choose code for integer operations with an immediate
340// operand.
341SDNode *PPC32DAGToDAGISel::SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
342                                                  unsigned OCHi, unsigned OCLo,
343                                                  bool IsArithmetic,
344                                                  bool Negate) {
345  // Check to make sure this is a constant.
346  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS);
347  // Exit if not a constant.
348  if (!CN) return 0;
349  // Extract immediate.
350  unsigned C = (unsigned)CN->getValue();
351  // Negate if required (ISD::SUB).
352  if (Negate) C = -C;
353  // Get the hi and lo portions of constant.
354  unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
355  unsigned Lo = Lo16(C);
356
357  // If two instructions are needed and usage indicates it would be better to
358  // load immediate into a register, bail out.
359  if (Hi && Lo && CN->use_size() > 2) return false;
360
361  // Select the first operand.
362  SDOperand Opr0 = Select(LHS);
363
364  if (Lo)  // Add in the lo-part.
365    Opr0 = CurDAG->getTargetNode(OCLo, MVT::i32, Opr0, getI32Imm(Lo));
366  if (Hi)  // Add in the hi-part.
367    Opr0 = CurDAG->getTargetNode(OCHi, MVT::i32, Opr0, getI32Imm(Hi));
368  return Opr0.Val;
369}
370
371/// SelectAddr - Given the specified address, return the two operands for a
372/// load/store instruction, and return true if it should be an indexed [r+r]
373/// operation.
374bool PPC32DAGToDAGISel::SelectAddr(SDOperand Addr, SDOperand &Op1,
375                                   SDOperand &Op2) {
376  unsigned imm = 0;
377  if (Addr.getOpcode() == ISD::ADD) {
378    if (isIntImmediate(Addr.getOperand(1), imm) && isInt16(imm)) {
379      Op1 = getI32Imm(Lo16(imm));
380      if (FrameIndexSDNode *FI =
381            dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
382        ++FrameOff;
383        Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
384      } else {
385        Op2 = Select(Addr.getOperand(0));
386      }
387      return false;
388    } else {
389      Op1 = Select(Addr.getOperand(0));
390      Op2 = Select(Addr.getOperand(1));
391      return true;   // [r+r]
392    }
393  }
394
395  // Now check if we're dealing with a global, and whether or not we should emit
396  // an optimized load or store for statics.
397  if (GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Addr)) {
398    GlobalValue *GV = GN->getGlobal();
399    if (!GV->hasWeakLinkage() && !GV->isExternal()) {
400      Op1 = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
401      if (PICEnabled)
402        Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),
403                                    Op1);
404      else
405        Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
406      return false;
407    }
408  } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Addr)) {
409    Op1 = getI32Imm(0);
410    Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
411    return false;
412  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Addr)) {
413    Op1 = Addr;
414    if (PICEnabled)
415      Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),Op1);
416    else
417      Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
418    return false;
419  }
420  Op1 = getI32Imm(0);
421  Op2 = Select(Addr);
422  return false;
423}
424
425/// SelectCC - Select a comparison of the specified values with the specified
426/// condition code, returning the CR# of the expression.
427SDOperand PPC32DAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
428                                      ISD::CondCode CC) {
429  // Always select the LHS.
430  LHS = Select(LHS);
431
432  // Use U to determine whether the SETCC immediate range is signed or not.
433  if (MVT::isInteger(LHS.getValueType())) {
434    bool U = ISD::isUnsignedIntSetCC(CC);
435    unsigned Imm;
436    if (isIntImmediate(RHS, Imm) &&
437        ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
438      return CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI, MVT::i32,
439                                   LHS, getI32Imm(Lo16(Imm)));
440    return CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
441                                 LHS, Select(RHS));
442  } else {
443    return CurDAG->getTargetNode(PPC::FCMPU, MVT::i32, LHS, Select(RHS));
444  }
445}
446
447/// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
448/// to Condition.
449static unsigned getBCCForSetCC(ISD::CondCode CC) {
450  switch (CC) {
451  default: assert(0 && "Unknown condition!"); abort();
452  case ISD::SETEQ:  return PPC::BEQ;
453  case ISD::SETNE:  return PPC::BNE;
454  case ISD::SETULT:
455  case ISD::SETLT:  return PPC::BLT;
456  case ISD::SETULE:
457  case ISD::SETLE:  return PPC::BLE;
458  case ISD::SETUGT:
459  case ISD::SETGT:  return PPC::BGT;
460  case ISD::SETUGE:
461  case ISD::SETGE:  return PPC::BGE;
462  }
463  return 0;
464}
465
466/// getCRIdxForSetCC - Return the index of the condition register field
467/// associated with the SetCC condition, and whether or not the field is
468/// treated as inverted.  That is, lt = 0; ge = 0 inverted.
469static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
470  switch (CC) {
471  default: assert(0 && "Unknown condition!"); abort();
472  case ISD::SETULT:
473  case ISD::SETLT:  Inv = false;  return 0;
474  case ISD::SETUGE:
475  case ISD::SETGE:  Inv = true;   return 0;
476  case ISD::SETUGT:
477  case ISD::SETGT:  Inv = false;  return 1;
478  case ISD::SETULE:
479  case ISD::SETLE:  Inv = true;   return 1;
480  case ISD::SETEQ:  Inv = false;  return 2;
481  case ISD::SETNE:  Inv = true;   return 2;
482  }
483  return 0;
484}
485
486// Structure used to return the necessary information to codegen an SDIV as
487// a multiply.
488struct ms {
489  int m; // magic number
490  int s; // shift amount
491};
492
493struct mu {
494  unsigned int m; // magic number
495  int a;          // add indicator
496  int s;          // shift amount
497};
498
499/// magic - calculate the magic numbers required to codegen an integer sdiv as
500/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
501/// or -1.
502static struct ms magic(int d) {
503  int p;
504  unsigned int ad, anc, delta, q1, r1, q2, r2, t;
505  const unsigned int two31 = 0x80000000U;
506  struct ms mag;
507
508  ad = abs(d);
509  t = two31 + ((unsigned int)d >> 31);
510  anc = t - 1 - t%ad;   // absolute value of nc
511  p = 31;               // initialize p
512  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
513  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
514  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
515  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
516  do {
517    p = p + 1;
518    q1 = 2*q1;        // update q1 = 2p/abs(nc)
519    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
520    if (r1 >= anc) {  // must be unsigned comparison
521      q1 = q1 + 1;
522      r1 = r1 - anc;
523    }
524    q2 = 2*q2;        // update q2 = 2p/abs(d)
525    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
526    if (r2 >= ad) {   // must be unsigned comparison
527      q2 = q2 + 1;
528      r2 = r2 - ad;
529    }
530    delta = ad - r2;
531  } while (q1 < delta || (q1 == delta && r1 == 0));
532
533  mag.m = q2 + 1;
534  if (d < 0) mag.m = -mag.m; // resulting magic number
535  mag.s = p - 32;            // resulting shift
536  return mag;
537}
538
539/// magicu - calculate the magic numbers required to codegen an integer udiv as
540/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
541static struct mu magicu(unsigned d)
542{
543  int p;
544  unsigned int nc, delta, q1, r1, q2, r2;
545  struct mu magu;
546  magu.a = 0;               // initialize "add" indicator
547  nc = - 1 - (-d)%d;
548  p = 31;                   // initialize p
549  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
550  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
551  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
552  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
553  do {
554    p = p + 1;
555    if (r1 >= nc - r1 ) {
556      q1 = 2*q1 + 1;  // update q1
557      r1 = 2*r1 - nc; // update r1
558    }
559    else {
560      q1 = 2*q1; // update q1
561      r1 = 2*r1; // update r1
562    }
563    if (r2 + 1 >= d - r2) {
564      if (q2 >= 0x7FFFFFFF) magu.a = 1;
565      q2 = 2*q2 + 1;     // update q2
566      r2 = 2*r2 + 1 - d; // update r2
567    }
568    else {
569      if (q2 >= 0x80000000) magu.a = 1;
570      q2 = 2*q2;     // update q2
571      r2 = 2*r2 + 1; // update r2
572    }
573    delta = d - 1 - r2;
574  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
575  magu.m = q2 + 1; // resulting magic number
576  magu.s = p - 32;  // resulting shift
577  return magu;
578}
579
580/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
581/// return a DAG expression to select that will generate the same value by
582/// multiplying by a magic number.  See:
583/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
584SDOperand PPC32DAGToDAGISel::BuildSDIVSequence(SDNode *N) {
585  int d = (int)cast<ConstantSDNode>(N->getOperand(1))->getValue();
586  ms magics = magic(d);
587  // Multiply the numerator (operand 0) by the magic value
588  SDOperand Q = CurDAG->getNode(ISD::MULHS, MVT::i32, N->getOperand(0),
589                                CurDAG->getConstant(magics.m, MVT::i32));
590  // If d > 0 and m < 0, add the numerator
591  if (d > 0 && magics.m < 0)
592    Q = CurDAG->getNode(ISD::ADD, MVT::i32, Q, N->getOperand(0));
593  // If d < 0 and m > 0, subtract the numerator.
594  if (d < 0 && magics.m > 0)
595    Q = CurDAG->getNode(ISD::SUB, MVT::i32, Q, N->getOperand(0));
596  // Shift right algebraic if shift value is nonzero
597  if (magics.s > 0)
598    Q = CurDAG->getNode(ISD::SRA, MVT::i32, Q,
599                        CurDAG->getConstant(magics.s, MVT::i32));
600  // Extract the sign bit and add it to the quotient
601  SDOperand T =
602    CurDAG->getNode(ISD::SRL, MVT::i32, Q, CurDAG->getConstant(31, MVT::i32));
603  return CurDAG->getNode(ISD::ADD, MVT::i32, Q, T);
604}
605
606/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
607/// return a DAG expression to select that will generate the same value by
608/// multiplying by a magic number.  See:
609/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
610SDOperand PPC32DAGToDAGISel::BuildUDIVSequence(SDNode *N) {
611  unsigned d = (unsigned)cast<ConstantSDNode>(N->getOperand(1))->getValue();
612  mu magics = magicu(d);
613  // Multiply the numerator (operand 0) by the magic value
614  SDOperand Q = CurDAG->getNode(ISD::MULHU, MVT::i32, N->getOperand(0),
615                                CurDAG->getConstant(magics.m, MVT::i32));
616  if (magics.a == 0) {
617    return CurDAG->getNode(ISD::SRL, MVT::i32, Q,
618                           CurDAG->getConstant(magics.s, MVT::i32));
619  } else {
620    SDOperand NPQ = CurDAG->getNode(ISD::SUB, MVT::i32, N->getOperand(0), Q);
621    NPQ = CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
622                           CurDAG->getConstant(1, MVT::i32));
623    NPQ = CurDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
624    return CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
625                           CurDAG->getConstant(magics.s-1, MVT::i32));
626  }
627}
628
629// Select - Convert the specified operand from a target-independent to a
630// target-specific node if it hasn't already been changed.
631SDOperand PPC32DAGToDAGISel::Select(SDOperand Op) {
632  SDNode *N = Op.Val;
633  if (N->getOpcode() >= ISD::BUILTIN_OP_END)
634    return Op;   // Already selected.
635
636  switch (N->getOpcode()) {
637  default:
638    std::cerr << "Cannot yet select: ";
639    N->dump();
640    std::cerr << "\n";
641    abort();
642  case ISD::EntryToken:       // These leaves remain the same.
643    return Op;
644  case ISD::TokenFactor: {
645    SDOperand New;
646    if (N->getNumOperands() == 2) {
647      SDOperand Op0 = Select(N->getOperand(0));
648      SDOperand Op1 = Select(N->getOperand(1));
649      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
650    } else {
651      std::vector<SDOperand> Ops;
652      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
653        Ops.push_back(Select(N->getOperand(i)));
654      New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
655    }
656
657    if (New.Val != N) {
658      CurDAG->ReplaceAllUsesWith(N, New.Val);
659      N = New.Val;
660    }
661    break;
662  }
663  case ISD::CopyFromReg: {
664    SDOperand Chain = Select(N->getOperand(0));
665    if (Chain == N->getOperand(0)) return Op; // No change
666    SDOperand New = CurDAG->getCopyFromReg(Chain,
667         cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
668    return New.getValue(Op.ResNo);
669  }
670  case ISD::CopyToReg: {
671    SDOperand Chain = Select(N->getOperand(0));
672    SDOperand Reg = N->getOperand(1);
673    SDOperand Val = Select(N->getOperand(2));
674    if (Chain != N->getOperand(0) || Val != N->getOperand(2)) {
675      SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
676                                      Chain, Reg, Val);
677      CurDAG->ReplaceAllUsesWith(N, New.Val);
678      N = New.Val;
679    }
680    break;
681  }
682  case ISD::Constant: {
683    assert(N->getValueType(0) == MVT::i32);
684    unsigned v = (unsigned)cast<ConstantSDNode>(N)->getValue();
685    unsigned Hi = HA16(v);
686    unsigned Lo = Lo16(v);
687    if (Hi && Lo) {
688      SDOperand Top = CurDAG->getTargetNode(PPC::LIS, MVT::i32,
689                                            getI32Imm(v >> 16));
690      CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORI, Top, getI32Imm(v & 0xFFFF));
691    } else if (Lo) {
692      CurDAG->SelectNodeTo(N, MVT::i32, PPC::LI, getI32Imm(v));
693    } else {
694      CurDAG->SelectNodeTo(N, MVT::i32, PPC::LIS, getI32Imm(v >> 16));
695    }
696    break;
697  }
698  case ISD::ConstantFP: {  // FIXME: this should get sucked into the legalizer
699    MachineConstantPool *CP = CurDAG->getMachineFunction().getConstantPool();
700    Constant *CFP = ConstantFP::get(Type::FloatTy,
701                                    cast<ConstantFPSDNode>(N)->getValue());
702    SDOperand CPN = CurDAG->getConstantPool(CP->getConstantPoolIndex(CFP),
703                                            MVT::i32);
704    SDOperand Tmp;
705    if (PICEnabled)
706      Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPN);
707    else
708      Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPN);
709    CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::LFS, CPN, Tmp);
710    break;
711  }
712  case ISD::UNDEF:
713    if (N->getValueType(0) == MVT::i32)
714      CurDAG->SelectNodeTo(N, MVT::i32, PPC::IMPLICIT_DEF_GPR);
715    else
716      CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::IMPLICIT_DEF_FP);
717    break;
718  case ISD::FrameIndex: {
719    int FI = cast<FrameIndexSDNode>(N)->getIndex();
720    CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDI,
721                         CurDAG->getTargetFrameIndex(FI, MVT::i32),
722                         getI32Imm(0));
723    break;
724  }
725  case ISD::ConstantPool: {
726    unsigned CPIIdx = cast<ConstantPoolSDNode>(N)->getIndex();
727    SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(CPIIdx, MVT::i32);
728    if (PICEnabled)
729      Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPI);
730    else
731      Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPI);
732    CurDAG->SelectNodeTo(N, MVT::i32, PPC::LA, Tmp, CPI);
733    break;
734  }
735  case ISD::GlobalAddress: {
736    GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
737    SDOperand Tmp;
738    SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
739    if (PICEnabled)
740      Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(), GA);
741    else
742      Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, GA);
743
744    if (GV->hasWeakLinkage() || GV->isExternal())
745      CurDAG->SelectNodeTo(N, MVT::i32, PPC::LWZ, GA, Tmp);
746    else
747      CurDAG->SelectNodeTo(N, MVT::i32, PPC::LA, Tmp, GA);
748    break;
749  }
750  case ISD::SIGN_EXTEND_INREG:
751    switch(cast<VTSDNode>(N->getOperand(1))->getVT()) {
752    default: assert(0 && "Illegal type in SIGN_EXTEND_INREG"); break;
753    case MVT::i16:
754      CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSH, Select(N->getOperand(0)));
755      break;
756    case MVT::i8:
757      CurDAG->SelectNodeTo(N, MVT::i32, PPC::EXTSB, Select(N->getOperand(0)));
758      break;
759    }
760    break;
761  case ISD::CTLZ:
762    assert(N->getValueType(0) == MVT::i32);
763    CurDAG->SelectNodeTo(N, MVT::i32, PPC::CNTLZW, Select(N->getOperand(0)));
764    break;
765  case ISD::ADD: {
766    MVT::ValueType Ty = N->getValueType(0);
767    if (Ty == MVT::i32) {
768      if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
769                                             PPC::ADDIS, PPC::ADDI, true)) {
770        CurDAG->ReplaceAllUsesWith(N, I);
771        N = I;
772      } else {
773        CurDAG->SelectNodeTo(N, Ty, PPC::ADD, Select(N->getOperand(0)),
774                             Select(N->getOperand(1)));
775      }
776      break;
777    }
778
779    if (!NoExcessFPPrecision) {  // Match FMA ops
780      if (N->getOperand(0).getOpcode() == ISD::MUL &&
781          N->getOperand(0).Val->hasOneUse()) {
782        ++FusedFP; // Statistic
783        CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
784                             Select(N->getOperand(0).getOperand(0)),
785                             Select(N->getOperand(0).getOperand(1)),
786                             Select(N->getOperand(1)));
787        break;
788      } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
789                 N->getOperand(1).hasOneUse()) {
790        ++FusedFP; // Statistic
791        CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS,
792                             Select(N->getOperand(1).getOperand(0)),
793                             Select(N->getOperand(1).getOperand(1)),
794                             Select(N->getOperand(0)));
795        break;
796      }
797    }
798
799    CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FADD : PPC::FADDS,
800                         Select(N->getOperand(0)), Select(N->getOperand(1)));
801    break;
802  }
803  case ISD::SUB: {
804    MVT::ValueType Ty = N->getValueType(0);
805    if (Ty == MVT::i32) {
806      unsigned Imm;
807      if (isIntImmediate(N->getOperand(0), Imm) && isInt16(Imm)) {
808        if (0 == Imm)
809          CurDAG->SelectNodeTo(N, Ty, PPC::NEG, Select(N->getOperand(1)));
810        else
811          CurDAG->SelectNodeTo(N, Ty, PPC::SUBFIC, Select(N->getOperand(1)),
812                               getI32Imm(Lo16(Imm)));
813        break;
814      }
815      if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
816                                          PPC::ADDIS, PPC::ADDI, true, true)) {
817        CurDAG->ReplaceAllUsesWith(N, I);
818        N = I;
819      } else {
820        CurDAG->SelectNodeTo(N, Ty, PPC::SUBF, Select(N->getOperand(1)),
821                             Select(N->getOperand(0)));
822      }
823      break;
824    }
825
826    if (!NoExcessFPPrecision) {  // Match FMA ops
827      if (N->getOperand(0).getOpcode() == ISD::MUL &&
828          N->getOperand(0).Val->hasOneUse()) {
829        ++FusedFP; // Statistic
830        CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS,
831                             Select(N->getOperand(0).getOperand(0)),
832                             Select(N->getOperand(0).getOperand(1)),
833                             Select(N->getOperand(1)));
834        break;
835      } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
836                 N->getOperand(1).Val->hasOneUse()) {
837        ++FusedFP; // Statistic
838        CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS,
839                             Select(N->getOperand(1).getOperand(0)),
840                             Select(N->getOperand(1).getOperand(1)),
841                             Select(N->getOperand(0)));
842        break;
843      }
844    }
845    CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSUB : PPC::FSUBS,
846                         Select(N->getOperand(0)),
847                         Select(N->getOperand(1)));
848    break;
849  }
850  case ISD::MUL: {
851    unsigned Imm, Opc;
852    if (isIntImmediate(N->getOperand(1), Imm) && isInt16(Imm)) {
853      CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::MULLI,
854                           Select(N->getOperand(0)), getI32Imm(Lo16(Imm)));
855      break;
856    }
857    switch (N->getValueType(0)) {
858      default: assert(0 && "Unhandled multiply type!");
859      case MVT::i32: Opc = PPC::MULLW; break;
860      case MVT::f32: Opc = PPC::FMULS; break;
861      case MVT::f64: Opc = PPC::FMUL;  break;
862    }
863    CurDAG->SelectNodeTo(N, MVT::i32, Opc, Select(N->getOperand(0)),
864                         Select(N->getOperand(1)));
865    break;
866  }
867  case ISD::SDIV: {
868    unsigned Imm;
869    if (isIntImmediate(N->getOperand(1), Imm)) {
870      if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
871        SDOperand Op =
872          CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
873                                Select(N->getOperand(0)),
874                                getI32Imm(Log2_32(Imm)));
875        CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDZE,
876                             Op.getValue(0), Op.getValue(1));
877        break;
878      } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
879        SDOperand Op =
880          CurDAG->getTargetNode(PPC::SRAWI, MVT::Flag, MVT::i32,
881                                Select(N->getOperand(0)),
882                                getI32Imm(Log2_32(-Imm)));
883        SDOperand PT =
884          CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, Op.getValue(1),
885                                Op.getValue(0));
886        CurDAG->SelectNodeTo(N, MVT::i32, PPC::NEG, PT);
887        break;
888      } else if (Imm) {
889        SDOperand Result = Select(BuildSDIVSequence(N));
890        assert(Result.ResNo == 0);
891        CurDAG->ReplaceAllUsesWith(N, Result.Val);
892        N = Result.Val;
893        break;
894      }
895    }
896
897    unsigned Opc;
898    switch (N->getValueType(0)) {
899    default: assert(0 && "Unknown type to ISD::SDIV"); break;
900    case MVT::i32: Opc = PPC::DIVW; break;
901    case MVT::f32: Opc = PPC::FDIVS; break;
902    case MVT::f64: Opc = PPC::FDIV; break;
903    }
904    CurDAG->SelectNodeTo(N, N->getValueType(0), Opc, Select(N->getOperand(0)),
905                         Select(N->getOperand(1)));
906    break;
907  }
908  case ISD::UDIV: {
909    // If this is a divide by constant, we can emit code using some magic
910    // constants to implement it as a multiply instead.
911    unsigned Imm;
912    if (isIntImmediate(N->getOperand(1), Imm) && Imm) {
913      SDOperand Result = Select(BuildUDIVSequence(N));
914      assert(Result.ResNo == 0);
915      CurDAG->ReplaceAllUsesWith(N, Result.Val);
916      N = Result.Val;
917      break;
918    }
919
920    CurDAG->SelectNodeTo(N, MVT::i32, PPC::DIVWU, Select(N->getOperand(0)),
921                         Select(N->getOperand(1)));
922    break;
923  }
924  case ISD::MULHS:
925    assert(N->getValueType(0) == MVT::i32);
926    CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHW, Select(N->getOperand(0)),
927                         Select(N->getOperand(1)));
928    break;
929  case ISD::MULHU:
930    assert(N->getValueType(0) == MVT::i32);
931    CurDAG->SelectNodeTo(N, MVT::i32, PPC::MULHWU, Select(N->getOperand(0)),
932                         Select(N->getOperand(1)));
933    break;
934  case ISD::AND: {
935    unsigned Imm;
936    // If this is an and of a value rotated between 0 and 31 bits and then and'd
937    // with a mask, emit rlwinm
938    if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
939                                                  isShiftedMask_32(~Imm))) {
940      SDOperand Val;
941      unsigned SH, MB, ME;
942      if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
943        Val = Select(N->getOperand(0).getOperand(0));
944      } else {
945        Val = Select(N->getOperand(0));
946        isRunOfOnes(Imm, MB, ME);
947        SH = 0;
948      }
949      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Val, getI32Imm(SH),
950                           getI32Imm(MB), getI32Imm(ME));
951      break;
952    }
953    // If this is an and with an immediate that isn't a mask, then codegen it as
954    // high and low 16 bit immediate ands.
955    if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0),
956                                           N->getOperand(1),
957                                           PPC::ANDISo, PPC::ANDIo)) {
958      CurDAG->ReplaceAllUsesWith(N, I);
959      N = I;
960      break;
961    }
962    // Finally, check for the case where we are being asked to select
963    // and (not(a), b) or and (a, not(b)) which can be selected as andc.
964    if (isOprNot(N->getOperand(0).Val))
965      CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(1)),
966                           Select(N->getOperand(0).getOperand(0)));
967    else if (isOprNot(N->getOperand(1).Val))
968      CurDAG->SelectNodeTo(N, MVT::i32, PPC::ANDC, Select(N->getOperand(0)),
969                           Select(N->getOperand(1).getOperand(0)));
970    else
971      CurDAG->SelectNodeTo(N, MVT::i32, PPC::AND, Select(N->getOperand(0)),
972                           Select(N->getOperand(1)));
973    break;
974  }
975  case ISD::OR:
976    if (SDNode *I = SelectBitfieldInsert(N)) {
977      CurDAG->ReplaceAllUsesWith(N, I);
978      N = I;
979      break;
980    }
981    if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0),
982                                           N->getOperand(1),
983                                           PPC::ORIS, PPC::ORI)) {
984      CurDAG->ReplaceAllUsesWith(N, I);
985      N = I;
986      break;
987    }
988    // Finally, check for the case where we are being asked to select
989    // 'or (not(a), b)' or 'or (a, not(b))' which can be selected as orc.
990    if (isOprNot(N->getOperand(0).Val))
991      CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(1)),
992                           Select(N->getOperand(0).getOperand(0)));
993    else if (isOprNot(N->getOperand(1).Val))
994      CurDAG->SelectNodeTo(N, MVT::i32, PPC::ORC, Select(N->getOperand(0)),
995                           Select(N->getOperand(1).getOperand(0)));
996    else
997      CurDAG->SelectNodeTo(N, MVT::i32, PPC::OR, Select(N->getOperand(0)),
998                           Select(N->getOperand(1)));
999    break;
1000  case ISD::XOR:
1001    // Check whether or not this node is a logical 'not'.  This is represented
1002    // by llvm as a xor with the constant value -1 (all bits set).  If this is a
1003    // 'not', then fold 'or' into 'nor', and so forth for the supported ops.
1004    if (isOprNot(N)) {
1005      unsigned Opc;
1006      SDOperand Val = Select(N->getOperand(0));
1007      switch (Val.getTargetOpcode()) {
1008      default:        Opc = 0;          break;
1009      case PPC::OR:   Opc = PPC::NOR;   break;
1010      case PPC::AND:  Opc = PPC::NAND;  break;
1011      case PPC::XOR:  Opc = PPC::EQV;   break;
1012      }
1013      if (Opc)
1014        CurDAG->SelectNodeTo(N, MVT::i32, Opc, Val.getOperand(0),
1015                             Val.getOperand(1));
1016      else
1017        CurDAG->SelectNodeTo(N, MVT::i32, PPC::NOR, Val, Val);
1018      break;
1019    }
1020    // If this is a xor with an immediate other than -1, then codegen it as high
1021    // and low 16 bit immediate xors.
1022    if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0),
1023                                           N->getOperand(1),
1024                                           PPC::XORIS, PPC::XORI)) {
1025      CurDAG->ReplaceAllUsesWith(N, I);
1026      N = I;
1027      break;
1028    }
1029    // Finally, check for the case where we are being asked to select
1030    // xor (not(a), b) which is equivalent to not(xor a, b), which is eqv
1031    if (isOprNot(N->getOperand(0).Val))
1032      CurDAG->SelectNodeTo(N, MVT::i32, PPC::EQV,
1033                           Select(N->getOperand(0).getOperand(0)),
1034                           Select(N->getOperand(1)));
1035    else
1036      CurDAG->SelectNodeTo(N, MVT::i32, PPC::XOR, Select(N->getOperand(0)),
1037                           Select(N->getOperand(1)));
1038    break;
1039  case ISD::SHL: {
1040    unsigned Imm, SH, MB, ME;
1041    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1042        isRotateAndMask(N, Imm, true, SH, MB, ME))
1043      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM,
1044                           Select(N->getOperand(0).getOperand(0)),
1045                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1046    else if (isIntImmediate(N->getOperand(1), Imm))
1047      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
1048                           getI32Imm(Imm), getI32Imm(0), getI32Imm(31-Imm));
1049    else
1050      CurDAG->SelectNodeTo(N, MVT::i32, PPC::SLW, Select(N->getOperand(0)),
1051                           Select(N->getOperand(1)));
1052    break;
1053  }
1054  case ISD::SRL: {
1055    unsigned Imm, SH, MB, ME;
1056    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1057        isRotateAndMask(N, Imm, true, SH, MB, ME))
1058      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM,
1059                           Select(N->getOperand(0).getOperand(0)),
1060                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1061    else if (isIntImmediate(N->getOperand(1), Imm))
1062      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Select(N->getOperand(0)),
1063                           getI32Imm(32-Imm), getI32Imm(Imm), getI32Imm(31));
1064    else
1065      CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRW, Select(N->getOperand(0)),
1066                           Select(N->getOperand(1)));
1067    break;
1068  }
1069  case ISD::SRA: {
1070    unsigned Imm, SH, MB, ME;
1071    if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1072        isRotateAndMask(N, Imm, true, SH, MB, ME))
1073      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM,
1074                           Select(N->getOperand(0).getOperand(0)),
1075                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1076    else if (isIntImmediate(N->getOperand(1), Imm))
1077      CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAWI, Select(N->getOperand(0)),
1078                           getI32Imm(Imm));
1079    else
1080      CurDAG->SelectNodeTo(N, MVT::i32, PPC::SRAW, Select(N->getOperand(0)),
1081                           Select(N->getOperand(1)));
1082    break;
1083  }
1084  case ISD::FABS:
1085    CurDAG->SelectNodeTo(N, N->getValueType(0), PPC::FABS,
1086                         Select(N->getOperand(0)));
1087    break;
1088  case ISD::FP_EXTEND:
1089    assert(MVT::f64 == N->getValueType(0) &&
1090           MVT::f32 == N->getOperand(0).getValueType() && "Illegal FP_EXTEND");
1091    CurDAG->SelectNodeTo(N, MVT::f64, PPC::FMR, Select(N->getOperand(0)));
1092    break;
1093  case ISD::FP_ROUND:
1094    assert(MVT::f32 == N->getValueType(0) &&
1095           MVT::f64 == N->getOperand(0).getValueType() && "Illegal FP_ROUND");
1096    CurDAG->SelectNodeTo(N, MVT::f32, PPC::FRSP, Select(N->getOperand(0)));
1097    break;
1098  case ISD::FNEG: {
1099    SDOperand Val = Select(N->getOperand(0));
1100    MVT::ValueType Ty = N->getValueType(0);
1101    if (Val.Val->hasOneUse()) {
1102      unsigned Opc;
1103      switch (Val.getTargetOpcode()) {
1104      default:          Opc = 0;            break;
1105      case PPC::FABS:   Opc = PPC::FNABS;   break;
1106      case PPC::FMADD:  Opc = PPC::FNMADD;  break;
1107      case PPC::FMADDS: Opc = PPC::FNMADDS; break;
1108      case PPC::FMSUB:  Opc = PPC::FNMSUB;  break;
1109      case PPC::FMSUBS: Opc = PPC::FNMSUBS; break;
1110      }
1111      // If we inverted the opcode, then emit the new instruction with the
1112      // inverted opcode and the original instruction's operands.  Otherwise,
1113      // fall through and generate a fneg instruction.
1114      if (Opc) {
1115        if (PPC::FNABS == Opc)
1116          CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0));
1117        else
1118          CurDAG->SelectNodeTo(N, Ty, Opc, Val.getOperand(0),
1119                               Val.getOperand(1), Val.getOperand(2));
1120        break;
1121      }
1122    }
1123    CurDAG->SelectNodeTo(N, Ty, PPC::FNEG, Val);
1124    break;
1125  }
1126  case ISD::FSQRT: {
1127    MVT::ValueType Ty = N->getValueType(0);
1128    CurDAG->SelectNodeTo(N, Ty, Ty == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS,
1129                         Select(N->getOperand(0)));
1130    break;
1131  }
1132
1133  case ISD::ADD_PARTS: {
1134    SDOperand LHSL = Select(N->getOperand(0));
1135    SDOperand LHSH = Select(N->getOperand(1));
1136
1137    unsigned Imm;
1138    bool ME, ZE;
1139    if (isIntImmediate(N->getOperand(3), Imm)) {
1140      ME = (signed)Imm == -1;
1141      ZE = Imm == 0;
1142    }
1143
1144    std::vector<SDOperand> Result;
1145    SDOperand CarryFromLo;
1146    if (isIntImmediate(N->getOperand(2), Imm) &&
1147        ((signed)Imm >= -32768 || (signed)Imm < 32768)) {
1148      // Codegen the low 32 bits of the add.  Interestingly, there is no
1149      // shifted form of add immediate carrying.
1150      CarryFromLo = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1151                                          LHSL, getI32Imm(Imm));
1152    } else {
1153      CarryFromLo = CurDAG->getTargetNode(PPC::ADDC, MVT::i32, MVT::Flag,
1154                                          LHSL, Select(N->getOperand(2)));
1155    }
1156    CarryFromLo = CarryFromLo.getValue(1);
1157
1158    // Codegen the high 32 bits, adding zero, minus one, or the full value
1159    // along with the carry flag produced by addc/addic.
1160    SDOperand ResultHi;
1161    if (ZE)
1162      ResultHi = CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, LHSH, CarryFromLo);
1163    else if (ME)
1164      ResultHi = CurDAG->getTargetNode(PPC::ADDME, MVT::i32, LHSH, CarryFromLo);
1165    else
1166      ResultHi = CurDAG->getTargetNode(PPC::ADDE, MVT::i32, LHSH,
1167                                       Select(N->getOperand(3)), CarryFromLo);
1168    Result.push_back(ResultHi);
1169    Result.push_back(CarryFromLo.getValue(0));
1170    CurDAG->ReplaceAllUsesWith(N, Result);
1171    return Result[Op.ResNo];
1172  }
1173  case ISD::SUB_PARTS: {
1174    SDOperand LHSL = Select(N->getOperand(0));
1175    SDOperand LHSH = Select(N->getOperand(1));
1176    SDOperand RHSL = Select(N->getOperand(2));
1177    SDOperand RHSH = Select(N->getOperand(3));
1178
1179    std::vector<SDOperand> Result;
1180    Result.push_back(CurDAG->getTargetNode(PPC::SUBFC, MVT::i32, MVT::Flag,
1181                                           RHSL, LHSL));
1182    Result.push_back(CurDAG->getTargetNode(PPC::SUBFE, MVT::i32, RHSH, LHSH,
1183                                           Result[0].getValue(1)));
1184    CurDAG->ReplaceAllUsesWith(N, Result);
1185    return Result[Op.ResNo];
1186  }
1187  case ISD::SHL_PARTS: {
1188    SDOperand HI = Select(N->getOperand(0));
1189    SDOperand LO = Select(N->getOperand(1));
1190    SDOperand SH = Select(N->getOperand(2));
1191    SDOperand SH_LO_R = CurDAG->getTargetNode(PPC::SUBFIC, MVT::i32, MVT::Flag,
1192                                              SH, getI32Imm(32));
1193    SDOperand SH_LO_L = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, SH,
1194                                          getI32Imm((unsigned)-32));
1195    SDOperand HI_SHL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, HI, SH);
1196    SDOperand HI_LOR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, LO, SH_LO_R);
1197    SDOperand HI_LOL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, LO, SH_LO_L);
1198    SDOperand HI_OR =  CurDAG->getTargetNode(PPC::OR, MVT::i32, HI_SHL, HI_LOR);
1199
1200    std::vector<SDOperand> Result;
1201    Result.push_back(CurDAG->getTargetNode(PPC::SLW, MVT::i32, LO, SH));
1202    Result.push_back(CurDAG->getTargetNode(PPC::OR, MVT::i32, HI_OR, HI_LOL));
1203    CurDAG->ReplaceAllUsesWith(N, Result);
1204    return Result[Op.ResNo];
1205  }
1206  case ISD::SRL_PARTS: {
1207    SDOperand HI = Select(N->getOperand(0));
1208    SDOperand LO = Select(N->getOperand(1));
1209    SDOperand SH = Select(N->getOperand(2));
1210    SDOperand SH_HI_L = CurDAG->getTargetNode(PPC::SUBFIC, MVT::i32, MVT::Flag,
1211                                              SH, getI32Imm(32));
1212    SDOperand SH_HI_R = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, SH,
1213                                              getI32Imm((unsigned)-32));
1214    SDOperand LO_SHR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, LO, SH);
1215    SDOperand LO_HIL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, HI, SH_HI_L);
1216    SDOperand LO_HIR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, HI, SH_HI_R);
1217    SDOperand LO_OR =  CurDAG->getTargetNode(PPC::OR, MVT::i32, LO_SHR, LO_HIL);
1218
1219    std::vector<SDOperand> Result;
1220    Result.push_back(CurDAG->getTargetNode(PPC::OR, MVT::i32, LO_OR, LO_HIR));
1221    Result.push_back(CurDAG->getTargetNode(PPC::SRW, MVT::i32, HI, SH));
1222    CurDAG->ReplaceAllUsesWith(N, Result);
1223    return Result[Op.ResNo];
1224  }
1225
1226  case ISD::LOAD:
1227  case ISD::EXTLOAD:
1228  case ISD::ZEXTLOAD:
1229  case ISD::SEXTLOAD: {
1230    SDOperand Op1, Op2;
1231    bool isIdx = SelectAddr(N->getOperand(1), Op1, Op2);
1232
1233    MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
1234      N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
1235    unsigned Opc;
1236    switch (TypeBeingLoaded) {
1237    default: N->dump(); assert(0 && "Cannot load this type!");
1238    case MVT::i1:
1239    case MVT::i8:  Opc = isIdx ? PPC::LBZX : PPC::LBZ; break;
1240    case MVT::i16:
1241      if (N->getOpcode() == ISD::SEXTLOAD) { // SEXT load?
1242        Opc = isIdx ? PPC::LHAX : PPC::LHA;
1243      } else {
1244        Opc = isIdx ? PPC::LHZX : PPC::LHZ;
1245      }
1246      break;
1247    case MVT::i32: Opc = isIdx ? PPC::LWZX : PPC::LWZ; break;
1248    case MVT::f32: Opc = isIdx ? PPC::LFSX : PPC::LFS; break;
1249    case MVT::f64: Opc = isIdx ? PPC::LFDX : PPC::LFD; break;
1250    }
1251
1252    CurDAG->SelectNodeTo(N, N->getValueType(0), MVT::Other, Opc,
1253                         Op1, Op2, Select(N->getOperand(0)));
1254    break;
1255  }
1256
1257  case ISD::TRUNCSTORE:
1258  case ISD::STORE: {
1259    SDOperand AddrOp1, AddrOp2;
1260    bool isIdx = SelectAddr(N->getOperand(2), AddrOp1, AddrOp2);
1261
1262    unsigned Opc;
1263    if (N->getOpcode() == ISD::STORE) {
1264      switch (N->getOperand(1).getValueType()) {
1265      default: assert(0 && "unknown Type in store");
1266      case MVT::i32: Opc = isIdx ? PPC::STWX  : PPC::STW; break;
1267      case MVT::f64: Opc = isIdx ? PPC::STFDX : PPC::STFD; break;
1268      case MVT::f32: Opc = isIdx ? PPC::STFSX : PPC::STFS; break;
1269      }
1270    } else { //ISD::TRUNCSTORE
1271      switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
1272      default: assert(0 && "unknown Type in store");
1273      case MVT::i1:
1274      case MVT::i8:  Opc = isIdx ? PPC::STBX : PPC::STB; break;
1275      case MVT::i16: Opc = isIdx ? PPC::STHX : PPC::STH; break;
1276      }
1277    }
1278
1279    CurDAG->SelectNodeTo(N, MVT::Other, Opc, Select(N->getOperand(1)),
1280                         AddrOp1, AddrOp2, Select(N->getOperand(0)));
1281    break;
1282  }
1283
1284  case ISD::SETCC: {
1285    unsigned Imm;
1286    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1287    if (isIntImmediate(N->getOperand(1), Imm)) {
1288      // We can codegen setcc op, imm very efficiently compared to a brcond.
1289      // Check for those cases here.
1290      // setcc op, 0
1291      if (Imm == 0) {
1292        SDOperand Op = Select(N->getOperand(0));
1293        switch (CC) {
1294        default: assert(0 && "Unhandled SetCC condition"); abort();
1295        case ISD::SETEQ:
1296          Op = CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op);
1297          CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Op, getI32Imm(27),
1298                               getI32Imm(5), getI32Imm(31));
1299          break;
1300        case ISD::SETNE: {
1301          SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1302                                               Op, getI32Imm(~0U));
1303          CurDAG->SelectNodeTo(N, MVT::i32, PPC::SUBFE, AD, Op, AD.getValue(1));
1304          break;
1305        }
1306        case ISD::SETLT:
1307          CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, Op, getI32Imm(1),
1308                               getI32Imm(31), getI32Imm(31));
1309          break;
1310        case ISD::SETGT: {
1311          SDOperand T = CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op);
1312          T = CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op);;
1313          CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, T, getI32Imm(1),
1314                               getI32Imm(31), getI32Imm(31));
1315          break;
1316        }
1317        }
1318        break;
1319      } else if (Imm == ~0U) {        // setcc op, -1
1320        SDOperand Op = Select(N->getOperand(0));
1321        switch (CC) {
1322        default: assert(0 && "Unhandled SetCC condition"); abort();
1323        case ISD::SETEQ:
1324          Op = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1325                                     Op, getI32Imm(1));
1326          CurDAG->SelectNodeTo(N, MVT::i32, PPC::ADDZE,
1327                               CurDAG->getTargetNode(PPC::LI, MVT::i32,
1328                                                     getI32Imm(0)),
1329                               Op.getValue(1));
1330          break;
1331        case ISD::SETNE: {
1332          Op = CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op);
1333          SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, Op,
1334                                               getI32Imm(~0U));
1335          CurDAG->SelectNodeTo(N, MVT::i32, PPC::SUBFE, AD, Op, AD.getValue(1));
1336          break;
1337        }
1338        case ISD::SETLT: {
1339          SDOperand AD = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
1340                                               getI32Imm(1));
1341          SDOperand AN = CurDAG->getTargetNode(PPC::AND, MVT::i32, AD, Op);
1342          CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, AN, getI32Imm(1),
1343                               getI32Imm(31), getI32Imm(31));
1344          break;
1345        }
1346        case ISD::SETGT:
1347          Op = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
1348                                     getI32Imm(31), getI32Imm(31));
1349          CurDAG->SelectNodeTo(N, MVT::i32, PPC::XORI, Op, getI32Imm(1));
1350          break;
1351        }
1352        break;
1353      }
1354    }
1355
1356    bool Inv;
1357    unsigned Idx = getCRIdxForSetCC(CC, Inv);
1358    SDOperand CCReg =
1359      SelectCC(Select(N->getOperand(0)), Select(N->getOperand(1)), CC);
1360    SDOperand IntCR;
1361
1362    // Force the ccreg into CR7.
1363    SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
1364
1365    std::vector<MVT::ValueType> VTs;
1366    VTs.push_back(MVT::Other);
1367    VTs.push_back(MVT::Flag);    // NONSTANDARD CopyToReg node: defines a flag
1368    std::vector<SDOperand> Ops;
1369    Ops.push_back(CurDAG->getEntryNode());
1370    Ops.push_back(CR7Reg);
1371    Ops.push_back(CCReg);
1372    CCReg = CurDAG->getNode(ISD::CopyToReg, VTs, Ops).getValue(1);
1373
1374    if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
1375      IntCR = CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg, CCReg);
1376    else
1377      IntCR = CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg);
1378
1379    if (!Inv) {
1380      CurDAG->SelectNodeTo(N, MVT::i32, PPC::RLWINM, IntCR,
1381                           getI32Imm(32-(3-Idx)), getI32Imm(31), getI32Imm(31));
1382    } else {
1383      SDOperand Tmp =
1384      CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
1385                            getI32Imm(32-(3-Idx)), getI32Imm(31),getI32Imm(31));
1386      CurDAG->SelectNodeTo(N, MVT::i32, PPC::XORI, Tmp, getI32Imm(1));
1387    }
1388
1389    break;
1390  }
1391
1392  case ISD::CALLSEQ_START:
1393  case ISD::CALLSEQ_END: {
1394    unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1395    unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
1396                       PPC::ADJCALLSTACKDOWN : PPC::ADJCALLSTACKUP;
1397    CurDAG->SelectNodeTo(N, MVT::Other, Opc,
1398                         getI32Imm(Amt), Select(N->getOperand(0)));
1399    break;
1400  }
1401  case ISD::CALL:
1402  case ISD::TAILCALL: {
1403    SDOperand Chain = Select(N->getOperand(0));
1404
1405    unsigned CallOpcode;
1406    std::vector<SDOperand> CallOperands;
1407
1408    if (GlobalAddressSDNode *GASD =
1409        dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
1410      CallOpcode = PPC::CALLpcrel;
1411      CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
1412                                                            MVT::i32));
1413    } else if (ExternalSymbolSDNode *ESSDN =
1414               dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
1415      CallOpcode = PPC::CALLpcrel;
1416      CallOperands.push_back(N->getOperand(1));
1417    } else {
1418      // Copy the callee address into the CTR register.
1419      SDOperand Callee = Select(N->getOperand(1));
1420      Chain = CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee, Chain);
1421
1422      // Copy the callee address into R12 on darwin.
1423      SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
1424      Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, R12, Callee, Chain);
1425
1426      CallOperands.push_back(getI32Imm(20));  // Information to encode indcall
1427      CallOperands.push_back(getI32Imm(0));   // Information to encode indcall
1428      CallOperands.push_back(R12);
1429      CallOpcode = PPC::CALLindirect;
1430    }
1431
1432    unsigned GPR_idx = 0, FPR_idx = 0;
1433    static const unsigned GPR[] = {
1434      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1435      PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1436    };
1437    static const unsigned FPR[] = {
1438      PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1439      PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1440    };
1441
1442    for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i)
1443      if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
1444        unsigned DestReg = 0;
1445        MVT::ValueType RegTy;
1446        if (N->getOperand(i).getValueType() == MVT::i32) {
1447          assert(GPR_idx < 8 && "Too many int args");
1448          DestReg = GPR[GPR_idx++];
1449          RegTy = MVT::i32;
1450        } else {
1451          assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
1452                 "Unpromoted integer arg?");
1453          assert(FPR_idx < 13 && "Too many fp args");
1454          DestReg = FPR[FPR_idx++];
1455          RegTy = MVT::f64;   // Even if this is really f32!
1456        }
1457
1458        SDOperand Reg = CurDAG->getRegister(DestReg, RegTy);
1459        Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg,
1460                                Select(N->getOperand(i)));
1461        CallOperands.push_back(Reg);
1462      }
1463
1464    // Finally, once everything is in registers to pass to the call, emit the
1465    // call itself.
1466    CallOperands.push_back(Chain);
1467    Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, CallOperands);
1468
1469    std::vector<SDOperand> CallResults;
1470
1471    // If the call has results, copy the values out of the ret val registers.
1472    switch (N->getValueType(0)) {
1473    default: assert(0 && "Unexpected ret value!");
1474    case MVT::Other: break;
1475    case MVT::i32:
1476      if (N->getValueType(1) == MVT::i32) {
1477        Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32).getValue(1);
1478        CallResults.push_back(Chain.getValue(0));
1479        Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1480        CallResults.push_back(Chain.getValue(0));
1481      } else {
1482        Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1483        CallResults.push_back(Chain.getValue(0));
1484      }
1485      break;
1486    case MVT::f32:
1487    case MVT::f64:
1488      Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, MVT::f64).getValue(1);
1489      CallResults.push_back(Chain.getValue(0));
1490      break;
1491    }
1492
1493    CallResults.push_back(Chain);
1494    CurDAG->ReplaceAllUsesWith(N, CallResults);
1495    return CallResults[Op.ResNo];
1496  }
1497  case ISD::RET: {
1498    SDOperand Chain = Select(N->getOperand(0));     // Token chain.
1499
1500    if (N->getNumOperands() > 1) {
1501      SDOperand Val = Select(N->getOperand(1));
1502      switch (N->getOperand(1).getValueType()) {
1503      default: assert(0 && "Unknown return type!");
1504      case MVT::f64:
1505      case MVT::f32:
1506        Chain = CurDAG->getCopyToReg(Chain, PPC::F1, Val);
1507        break;
1508      case MVT::i32:
1509        Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Val);
1510        break;
1511      }
1512
1513      if (N->getNumOperands() > 2) {
1514        assert(N->getOperand(1).getValueType() == MVT::i32 &&
1515               N->getOperand(2).getValueType() == MVT::i32 &&
1516               N->getNumOperands() == 3 && "Unknown two-register ret value!");
1517        Val = Select(N->getOperand(2));
1518        Chain = CurDAG->getCopyToReg(Chain, PPC::R4, Val);
1519      }
1520    }
1521
1522    // Finally, select this to a blr (return) instruction.
1523    CurDAG->SelectNodeTo(N, MVT::Other, PPC::BLR, Chain);
1524    break;
1525  }
1526  case ISD::BR:
1527    CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(1),
1528                         Select(N->getOperand(0)));
1529    break;
1530  case ISD::BR_CC:
1531  case ISD::BRTWOWAY_CC: {
1532    SDOperand Chain = Select(N->getOperand(0));
1533    MachineBasicBlock *Dest =
1534      cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1535    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1536    SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1537    unsigned Opc = getBCCForSetCC(CC);
1538
1539    // If this is a two way branch, then grab the fallthrough basic block
1540    // argument and build a PowerPC branch pseudo-op, suitable for long branch
1541    // conversion if necessary by the branch selection pass.  Otherwise, emit a
1542    // standard conditional branch.
1543    if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1544      MachineBasicBlock *Fallthrough =
1545        cast<BasicBlockSDNode>(N->getOperand(5))->getBasicBlock();
1546      SDOperand CB = CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1547                                           CondCode, getI32Imm(Opc),
1548                                           N->getOperand(4), N->getOperand(5),
1549                                           Chain);
1550      CurDAG->SelectNodeTo(N, MVT::Other, PPC::B, N->getOperand(5), CB);
1551    } else {
1552      // Iterate to the next basic block
1553      ilist<MachineBasicBlock>::iterator It = BB;
1554      ++It;
1555
1556      // If the fallthrough path is off the end of the function, which would be
1557      // undefined behavior, set it to be the same as the current block because
1558      // we have nothing better to set it to, and leaving it alone will cause
1559      // the PowerPC Branch Selection pass to crash.
1560      if (It == BB->getParent()->end()) It = Dest;
1561      CurDAG->SelectNodeTo(N, MVT::Other, PPC::COND_BRANCH, CondCode,
1562                           getI32Imm(Opc), N->getOperand(4),
1563                           CurDAG->getBasicBlock(It), Chain);
1564    }
1565    break;
1566  }
1567  }
1568  return SDOperand(N, Op.ResNo);
1569}
1570
1571
1572/// createPPC32ISelDag - This pass converts a legalized DAG into a
1573/// PowerPC-specific DAG, ready for instruction scheduling.
1574///
1575FunctionPass *llvm::createPPC32ISelDag(TargetMachine &TM) {
1576  return new PPC32DAGToDAGISel(TM);
1577}
1578
1579