"on the rare occasion the SPU BE produces illegal assembly - it tries to emit an...
[oota-llvm.git] / lib / Target / CellSPU / SPUISelDAGToDAG.cpp
1 //===-- SPUISelDAGToDAG.cpp - CellSPU 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 the Cell SPU,
11 // converting from a legalized dag to a SPU-target dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SPU.h"
16 #include "SPUTargetMachine.h"
17 #include "SPUHazardRecognizers.h"
18 #include "SPUFrameInfo.h"
19 #include "SPURegisterNames.h"
20 #include "SPUTargetMachine.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Constants.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/LLVMContext.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 namespace {
42   //! ConstantSDNode predicate for i32 sign-extended, 10-bit immediates
43   bool
44   isI64IntS10Immediate(ConstantSDNode *CN)
45   {
46     return isInt<10>(CN->getSExtValue());
47   }
48
49   //! ConstantSDNode predicate for i32 sign-extended, 10-bit immediates
50   bool
51   isI32IntS10Immediate(ConstantSDNode *CN)
52   {
53     return isInt<10>(CN->getSExtValue());
54   }
55
56   //! ConstantSDNode predicate for i32 unsigned 10-bit immediate values
57   bool
58   isI32IntU10Immediate(ConstantSDNode *CN)
59   {
60     return isUInt<10>(CN->getSExtValue());
61   }
62
63   //! ConstantSDNode predicate for i16 sign-extended, 10-bit immediate values
64   bool
65   isI16IntS10Immediate(ConstantSDNode *CN)
66   {
67     return isInt<10>(CN->getSExtValue());
68   }
69
70   //! SDNode predicate for i16 sign-extended, 10-bit immediate values
71   bool
72   isI16IntS10Immediate(SDNode *N)
73   {
74     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
75     return (CN != 0 && isI16IntS10Immediate(CN));
76   }
77
78   //! ConstantSDNode predicate for i16 unsigned 10-bit immediate values
79   bool
80   isI16IntU10Immediate(ConstantSDNode *CN)
81   {
82     return isUInt<10>((short) CN->getZExtValue());
83   }
84
85   //! SDNode predicate for i16 sign-extended, 10-bit immediate values
86   bool
87   isI16IntU10Immediate(SDNode *N)
88   {
89     return (N->getOpcode() == ISD::Constant
90             && isI16IntU10Immediate(cast<ConstantSDNode>(N)));
91   }
92
93   //! ConstantSDNode predicate for signed 16-bit values
94   /*!
95     \arg CN The constant SelectionDAG node holding the value
96     \arg Imm The returned 16-bit value, if returning true
97
98     This predicate tests the value in \a CN to see whether it can be
99     represented as a 16-bit, sign-extended quantity. Returns true if
100     this is the case.
101    */
102   bool
103   isIntS16Immediate(ConstantSDNode *CN, short &Imm)
104   {
105     EVT vt = CN->getValueType(0);
106     Imm = (short) CN->getZExtValue();
107     if (vt.getSimpleVT() >= MVT::i1 && vt.getSimpleVT() <= MVT::i16) {
108       return true;
109     } else if (vt == MVT::i32) {
110       int32_t i_val = (int32_t) CN->getZExtValue();
111       short s_val = (short) i_val;
112       return i_val == s_val;
113     } else {
114       int64_t i_val = (int64_t) CN->getZExtValue();
115       short s_val = (short) i_val;
116       return i_val == s_val;
117     }
118
119     return false;
120   }
121
122   //! SDNode predicate for signed 16-bit values.
123   bool
124   isIntS16Immediate(SDNode *N, short &Imm)
125   {
126     return (N->getOpcode() == ISD::Constant
127             && isIntS16Immediate(cast<ConstantSDNode>(N), Imm));
128   }
129
130   //! ConstantFPSDNode predicate for representing floats as 16-bit sign ext.
131   static bool
132   isFPS16Immediate(ConstantFPSDNode *FPN, short &Imm)
133   {
134     EVT vt = FPN->getValueType(0);
135     if (vt == MVT::f32) {
136       int val = FloatToBits(FPN->getValueAPF().convertToFloat());
137       int sval = (int) ((val << 16) >> 16);
138       Imm = (short) val;
139       return val == sval;
140     }
141
142     return false;
143   }
144
145   bool
146   isHighLow(const SDValue &Op)
147   {
148     return (Op.getOpcode() == SPUISD::IndirectAddr
149             && ((Op.getOperand(0).getOpcode() == SPUISD::Hi
150                  && Op.getOperand(1).getOpcode() == SPUISD::Lo)
151                 || (Op.getOperand(0).getOpcode() == SPUISD::Lo
152                     && Op.getOperand(1).getOpcode() == SPUISD::Hi)));
153   }
154
155   //===------------------------------------------------------------------===//
156   //! EVT to "useful stuff" mapping structure:
157
158   struct valtype_map_s {
159     EVT VT;
160     unsigned ldresult_ins;      /// LDRESULT instruction (0 = undefined)
161     bool ldresult_imm;          /// LDRESULT instruction requires immediate?
162     unsigned lrinst;            /// LR instruction
163   };
164
165   const valtype_map_s valtype_map[] = {
166     { MVT::i8,    SPU::ORBIr8,  true,  SPU::LRr8 },
167     { MVT::i16,   SPU::ORHIr16, true,  SPU::LRr16 },
168     { MVT::i32,   SPU::ORIr32,  true,  SPU::LRr32 },
169     { MVT::i64,   SPU::ORr64,   false, SPU::LRr64 },
170     { MVT::f32,   SPU::ORf32,   false, SPU::LRf32 },
171     { MVT::f64,   SPU::ORf64,   false, SPU::LRf64 },
172     // vector types... (sigh!)
173     { MVT::v16i8, 0,            false, SPU::LRv16i8 },
174     { MVT::v8i16, 0,            false, SPU::LRv8i16 },
175     { MVT::v4i32, 0,            false, SPU::LRv4i32 },
176     { MVT::v2i64, 0,            false, SPU::LRv2i64 },
177     { MVT::v4f32, 0,            false, SPU::LRv4f32 },
178     { MVT::v2f64, 0,            false, SPU::LRv2f64 }
179   };
180
181   const size_t n_valtype_map = sizeof(valtype_map) / sizeof(valtype_map[0]);
182
183   const valtype_map_s *getValueTypeMapEntry(EVT VT)
184   {
185     const valtype_map_s *retval = 0;
186     for (size_t i = 0; i < n_valtype_map; ++i) {
187       if (valtype_map[i].VT == VT) {
188         retval = valtype_map + i;
189         break;
190       }
191     }
192
193
194 #ifndef NDEBUG
195     if (retval == 0) {
196       report_fatal_error("SPUISelDAGToDAG.cpp: getValueTypeMapEntry returns"
197                          "NULL for " + Twine(VT.getEVTString()));
198     }
199 #endif
200
201     return retval;
202   }
203
204   //! Generate the carry-generate shuffle mask.
205   SDValue getCarryGenerateShufMask(SelectionDAG &DAG, DebugLoc dl) {
206     SmallVector<SDValue, 16 > ShufBytes;
207
208     // Create the shuffle mask for "rotating" the borrow up one register slot
209     // once the borrow is generated.
210     ShufBytes.push_back(DAG.getConstant(0x04050607, MVT::i32));
211     ShufBytes.push_back(DAG.getConstant(0x80808080, MVT::i32));
212     ShufBytes.push_back(DAG.getConstant(0x0c0d0e0f, MVT::i32));
213     ShufBytes.push_back(DAG.getConstant(0x80808080, MVT::i32));
214
215     return DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
216                        &ShufBytes[0], ShufBytes.size());
217   }
218
219   //! Generate the borrow-generate shuffle mask
220   SDValue getBorrowGenerateShufMask(SelectionDAG &DAG, DebugLoc dl) {
221     SmallVector<SDValue, 16 > ShufBytes;
222
223     // Create the shuffle mask for "rotating" the borrow up one register slot
224     // once the borrow is generated.
225     ShufBytes.push_back(DAG.getConstant(0x04050607, MVT::i32));
226     ShufBytes.push_back(DAG.getConstant(0xc0c0c0c0, MVT::i32));
227     ShufBytes.push_back(DAG.getConstant(0x0c0d0e0f, MVT::i32));
228     ShufBytes.push_back(DAG.getConstant(0xc0c0c0c0, MVT::i32));
229
230     return DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
231                        &ShufBytes[0], ShufBytes.size());
232   }
233
234   //===------------------------------------------------------------------===//
235   /// SPUDAGToDAGISel - Cell SPU-specific code to select SPU machine
236   /// instructions for SelectionDAG operations.
237   ///
238   class SPUDAGToDAGISel :
239     public SelectionDAGISel
240   {
241     const SPUTargetMachine &TM;
242     const SPUTargetLowering &SPUtli;
243     unsigned GlobalBaseReg;
244
245   public:
246     explicit SPUDAGToDAGISel(SPUTargetMachine &tm) :
247       SelectionDAGISel(tm),
248       TM(tm),
249       SPUtli(*tm.getTargetLowering())
250     { }
251
252     virtual bool runOnMachineFunction(MachineFunction &MF) {
253       // Make sure we re-emit a set of the global base reg if necessary
254       GlobalBaseReg = 0;
255       SelectionDAGISel::runOnMachineFunction(MF);
256       return true;
257     }
258
259     /// getI32Imm - Return a target constant with the specified value, of type
260     /// i32.
261     inline SDValue getI32Imm(uint32_t Imm) {
262       return CurDAG->getTargetConstant(Imm, MVT::i32);
263     }
264
265     /// getI64Imm - Return a target constant with the specified value, of type
266     /// i64.
267     inline SDValue getI64Imm(uint64_t Imm) {
268       return CurDAG->getTargetConstant(Imm, MVT::i64);
269     }
270
271     /// getSmallIPtrImm - Return a target constant of pointer type.
272     inline SDValue getSmallIPtrImm(unsigned Imm) {
273       return CurDAG->getTargetConstant(Imm, SPUtli.getPointerTy());
274       }
275
276     SDNode *emitBuildVector(SDNode *bvNode) {
277       EVT vecVT = bvNode->getValueType(0);
278       EVT eltVT = vecVT.getVectorElementType();
279       DebugLoc dl = bvNode->getDebugLoc();
280
281       // Check to see if this vector can be represented as a CellSPU immediate
282       // constant by invoking all of the instruction selection predicates:
283       if (((vecVT == MVT::v8i16) &&
284            (SPU::get_vec_i16imm(bvNode, *CurDAG, MVT::i16).getNode() != 0)) ||
285           ((vecVT == MVT::v4i32) &&
286            ((SPU::get_vec_i16imm(bvNode, *CurDAG, MVT::i32).getNode() != 0) ||
287             (SPU::get_ILHUvec_imm(bvNode, *CurDAG, MVT::i32).getNode() != 0) ||
288             (SPU::get_vec_u18imm(bvNode, *CurDAG, MVT::i32).getNode() != 0) ||
289             (SPU::get_v4i32_imm(bvNode, *CurDAG).getNode() != 0))) ||
290           ((vecVT == MVT::v2i64) &&
291            ((SPU::get_vec_i16imm(bvNode, *CurDAG, MVT::i64).getNode() != 0) ||
292             (SPU::get_ILHUvec_imm(bvNode, *CurDAG, MVT::i64).getNode() != 0) ||
293             (SPU::get_vec_u18imm(bvNode, *CurDAG, MVT::i64).getNode() != 0)))) {
294         HandleSDNode Dummy(SDValue(bvNode, 0));
295         if (SDNode *N = Select(bvNode))
296           return N;
297         return Dummy.getValue().getNode();
298       }
299
300       // No, need to emit a constant pool spill:
301       std::vector<Constant*> CV;
302
303       for (size_t i = 0; i < bvNode->getNumOperands(); ++i) {
304         ConstantSDNode *V = cast<ConstantSDNode > (bvNode->getOperand(i));
305         CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
306       }
307
308       const Constant *CP = ConstantVector::get(CV);
309       SDValue CPIdx = CurDAG->getConstantPool(CP, SPUtli.getPointerTy());
310       unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
311       SDValue CGPoolOffset =
312               SPU::LowerConstantPool(CPIdx, *CurDAG, TM);
313       
314       HandleSDNode Dummy(CurDAG->getLoad(vecVT, dl,
315                                          CurDAG->getEntryNode(), CGPoolOffset,
316                                          PseudoSourceValue::getConstantPool(),0,
317                                          false, false, Alignment));
318       CurDAG->ReplaceAllUsesWith(SDValue(bvNode, 0), Dummy.getValue());
319       if (SDNode *N = SelectCode(Dummy.getValue().getNode()))
320         return N;
321       return Dummy.getValue().getNode();
322     }
323
324     /// Select - Convert the specified operand from a target-independent to a
325     /// target-specific node if it hasn't already been changed.
326     SDNode *Select(SDNode *N);
327
328     //! Emit the instruction sequence for i64 shl
329     SDNode *SelectSHLi64(SDNode *N, EVT OpVT);
330
331     //! Emit the instruction sequence for i64 srl
332     SDNode *SelectSRLi64(SDNode *N, EVT OpVT);
333
334     //! Emit the instruction sequence for i64 sra
335     SDNode *SelectSRAi64(SDNode *N, EVT OpVT);
336
337     //! Emit the necessary sequence for loading i64 constants:
338     SDNode *SelectI64Constant(SDNode *N, EVT OpVT, DebugLoc dl);
339
340     //! Alternate instruction emit sequence for loading i64 constants
341     SDNode *SelectI64Constant(uint64_t i64const, EVT OpVT, DebugLoc dl);
342
343     //! Returns true if the address N is an A-form (local store) address
344     bool SelectAFormAddr(SDNode *Op, SDValue N, SDValue &Base,
345                          SDValue &Index);
346
347     //! D-form address predicate
348     bool SelectDFormAddr(SDNode *Op, SDValue N, SDValue &Base,
349                          SDValue &Index);
350
351     /// Alternate D-form address using i7 offset predicate
352     bool SelectDForm2Addr(SDNode *Op, SDValue N, SDValue &Disp,
353                           SDValue &Base);
354
355     /// D-form address selection workhorse
356     bool DFormAddressPredicate(SDNode *Op, SDValue N, SDValue &Disp,
357                                SDValue &Base, int minOffset, int maxOffset);
358
359     //! Address predicate if N can be expressed as an indexed [r+r] operation.
360     bool SelectXFormAddr(SDNode *Op, SDValue N, SDValue &Base,
361                          SDValue &Index);
362
363     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
364     /// inline asm expressions.
365     virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
366                                               char ConstraintCode,
367                                               std::vector<SDValue> &OutOps) {
368       SDValue Op0, Op1;
369       switch (ConstraintCode) {
370       default: return true;
371       case 'm':   // memory
372         if (!SelectDFormAddr(Op.getNode(), Op, Op0, Op1)
373             && !SelectAFormAddr(Op.getNode(), Op, Op0, Op1))
374           SelectXFormAddr(Op.getNode(), Op, Op0, Op1);
375         break;
376       case 'o':   // offsetable
377         if (!SelectDFormAddr(Op.getNode(), Op, Op0, Op1)
378             && !SelectAFormAddr(Op.getNode(), Op, Op0, Op1)) {
379           Op0 = Op;
380           Op1 = getSmallIPtrImm(0);
381         }
382         break;
383       case 'v':   // not offsetable
384 #if 1
385         llvm_unreachable("InlineAsmMemoryOperand 'v' constraint not handled.");
386 #else
387         SelectAddrIdxOnly(Op, Op, Op0, Op1);
388 #endif
389         break;
390       }
391
392       OutOps.push_back(Op0);
393       OutOps.push_back(Op1);
394       return false;
395     }
396
397     virtual const char *getPassName() const {
398       return "Cell SPU DAG->DAG Pattern Instruction Selection";
399     }
400
401     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
402     /// this target when scheduling the DAG.
403     virtual ScheduleHazardRecognizer *CreateTargetHazardRecognizer() {
404       const TargetInstrInfo *II = TM.getInstrInfo();
405       assert(II && "No InstrInfo?");
406       return new SPUHazardRecognizer(*II);
407     }
408
409     // Include the pieces autogenerated from the target description.
410 #include "SPUGenDAGISel.inc"
411   };
412 }
413
414 /*!
415  \arg Op The ISD instruction operand
416  \arg N The address to be tested
417  \arg Base The base address
418  \arg Index The base address index
419  */
420 bool
421 SPUDAGToDAGISel::SelectAFormAddr(SDNode *Op, SDValue N, SDValue &Base,
422                     SDValue &Index) {
423   // These match the addr256k operand type:
424   EVT OffsVT = MVT::i16;
425   SDValue Zero = CurDAG->getTargetConstant(0, OffsVT);
426
427   switch (N.getOpcode()) {
428   case ISD::Constant:
429   case ISD::ConstantPool:
430   case ISD::GlobalAddress:
431     report_fatal_error("SPU SelectAFormAddr: Constant/Pool/Global not lowered.");
432     /*NOTREACHED*/
433
434   case ISD::TargetConstant:
435   case ISD::TargetGlobalAddress:
436   case ISD::TargetJumpTable:
437     report_fatal_error("SPUSelectAFormAddr: Target Constant/Pool/Global "
438                       "not wrapped as A-form address.");
439     /*NOTREACHED*/
440
441   case SPUISD::AFormAddr:
442     // Just load from memory if there's only a single use of the location,
443     // otherwise, this will get handled below with D-form offset addresses
444     if (N.hasOneUse()) {
445       SDValue Op0 = N.getOperand(0);
446       switch (Op0.getOpcode()) {
447       case ISD::TargetConstantPool:
448       case ISD::TargetJumpTable:
449         Base = Op0;
450         Index = Zero;
451         return true;
452
453       case ISD::TargetGlobalAddress: {
454         GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op0);
455         const GlobalValue *GV = GSDN->getGlobal();
456         if (GV->getAlignment() == 16) {
457           Base = Op0;
458           Index = Zero;
459           return true;
460         }
461         break;
462       }
463       }
464     }
465     break;
466   }
467   return false;
468 }
469
470 bool
471 SPUDAGToDAGISel::SelectDForm2Addr(SDNode *Op, SDValue N, SDValue &Disp,
472                                   SDValue &Base) {
473   const int minDForm2Offset = -(1 << 7);
474   const int maxDForm2Offset = (1 << 7) - 1;
475   return DFormAddressPredicate(Op, N, Disp, Base, minDForm2Offset,
476                                maxDForm2Offset);
477 }
478
479 /*!
480   \arg Op The ISD instruction (ignored)
481   \arg N The address to be tested
482   \arg Base Base address register/pointer
483   \arg Index Base address index
484
485   Examine the input address by a base register plus a signed 10-bit
486   displacement, [r+I10] (D-form address).
487
488   \return true if \a N is a D-form address with \a Base and \a Index set
489   to non-empty SDValue instances.
490 */
491 bool
492 SPUDAGToDAGISel::SelectDFormAddr(SDNode *Op, SDValue N, SDValue &Base,
493                                  SDValue &Index) {
494   return DFormAddressPredicate(Op, N, Base, Index,
495                                SPUFrameInfo::minFrameOffset(),
496                                SPUFrameInfo::maxFrameOffset());
497 }
498
499 bool
500 SPUDAGToDAGISel::DFormAddressPredicate(SDNode *Op, SDValue N, SDValue &Base,
501                                       SDValue &Index, int minOffset,
502                                       int maxOffset) {
503   unsigned Opc = N.getOpcode();
504   EVT PtrTy = SPUtli.getPointerTy();
505
506   if (Opc == ISD::FrameIndex) {
507     // Stack frame index must be less than 512 (divided by 16):
508     FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(N);
509     int FI = int(FIN->getIndex());
510     DEBUG(errs() << "SelectDFormAddr: ISD::FrameIndex = "
511                << FI << "\n");
512     if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
513       Base = CurDAG->getTargetConstant(0, PtrTy);
514       Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
515       return true;
516     }
517   } else if (Opc == ISD::ADD) {
518     // Generated by getelementptr
519     const SDValue Op0 = N.getOperand(0);
520     const SDValue Op1 = N.getOperand(1);
521
522     if ((Op0.getOpcode() == SPUISD::Hi && Op1.getOpcode() == SPUISD::Lo)
523         || (Op1.getOpcode() == SPUISD::Hi && Op0.getOpcode() == SPUISD::Lo)) {
524       Base = CurDAG->getTargetConstant(0, PtrTy);
525       Index = N;
526       return true;
527     } else if (Op1.getOpcode() == ISD::Constant
528                || Op1.getOpcode() == ISD::TargetConstant) {
529       ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
530       int32_t offset = int32_t(CN->getSExtValue());
531
532       if (Op0.getOpcode() == ISD::FrameIndex) {
533         FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op0);
534         int FI = int(FIN->getIndex());
535         DEBUG(errs() << "SelectDFormAddr: ISD::ADD offset = " << offset
536                    << " frame index = " << FI << "\n");
537
538         if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
539           Base = CurDAG->getTargetConstant(offset, PtrTy);
540           Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
541           return true;
542         }
543       } else if (offset > minOffset && offset < maxOffset) {
544         Base = CurDAG->getTargetConstant(offset, PtrTy);
545         Index = Op0;
546         return true;
547       }
548     } else if (Op0.getOpcode() == ISD::Constant
549                || Op0.getOpcode() == ISD::TargetConstant) {
550       ConstantSDNode *CN = cast<ConstantSDNode>(Op0);
551       int32_t offset = int32_t(CN->getSExtValue());
552
553       if (Op1.getOpcode() == ISD::FrameIndex) {
554         FrameIndexSDNode *FIN = cast<FrameIndexSDNode>(Op1);
555         int FI = int(FIN->getIndex());
556         DEBUG(errs() << "SelectDFormAddr: ISD::ADD offset = " << offset
557                    << " frame index = " << FI << "\n");
558
559         if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
560           Base = CurDAG->getTargetConstant(offset, PtrTy);
561           Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
562           return true;
563         }
564       } else if (offset > minOffset && offset < maxOffset) {
565         Base = CurDAG->getTargetConstant(offset, PtrTy);
566         Index = Op1;
567         return true;
568       }
569     }
570   } else if (Opc == SPUISD::IndirectAddr) {
571     // Indirect with constant offset -> D-Form address
572     const SDValue Op0 = N.getOperand(0);
573     const SDValue Op1 = N.getOperand(1);
574
575     if (Op0.getOpcode() == SPUISD::Hi
576         && Op1.getOpcode() == SPUISD::Lo) {
577       // (SPUindirect (SPUhi <arg>, 0), (SPUlo <arg>, 0))
578       Base = CurDAG->getTargetConstant(0, PtrTy);
579       Index = N;
580       return true;
581     } else if (isa<ConstantSDNode>(Op0) || isa<ConstantSDNode>(Op1)) {
582       int32_t offset = 0;
583       SDValue idxOp;
584
585       if (isa<ConstantSDNode>(Op1)) {
586         ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
587         offset = int32_t(CN->getSExtValue());
588         idxOp = Op0;
589       } else if (isa<ConstantSDNode>(Op0)) {
590         ConstantSDNode *CN = cast<ConstantSDNode>(Op0);
591         offset = int32_t(CN->getSExtValue());
592         idxOp = Op1;
593       }
594
595       if (offset >= minOffset && offset <= maxOffset) {
596         Base = CurDAG->getTargetConstant(offset, PtrTy);
597         Index = idxOp;
598         return true;
599       }
600     }
601   } else if (Opc == SPUISD::AFormAddr) {
602     Base = CurDAG->getTargetConstant(0, N.getValueType());
603     Index = N;
604     return true;
605   } else if (Opc == SPUISD::LDRESULT) {
606     Base = CurDAG->getTargetConstant(0, N.getValueType());
607     Index = N;
608     return true;
609   } else if (Opc == ISD::Register || Opc == ISD::CopyFromReg) {
610     unsigned OpOpc = Op->getOpcode();
611
612     if (OpOpc == ISD::STORE || OpOpc == ISD::LOAD) {
613       // Direct load/store without getelementptr
614       SDValue Addr, Offs;
615
616       // Get the register from CopyFromReg
617       if (Opc == ISD::CopyFromReg)
618         Addr = N.getOperand(1);
619       else
620         Addr = N;                       // Register
621
622       Offs = ((OpOpc == ISD::STORE) ? Op->getOperand(3) : Op->getOperand(2));
623
624       if (Offs.getOpcode() == ISD::Constant || Offs.getOpcode() == ISD::UNDEF) {
625         if (Offs.getOpcode() == ISD::UNDEF)
626           Offs = CurDAG->getTargetConstant(0, Offs.getValueType());
627
628         Base = Offs;
629         Index = Addr;
630         return true;
631       }
632     } else {
633       /* If otherwise unadorned, default to D-form address with 0 offset: */
634       if (Opc == ISD::CopyFromReg) {
635         Index = N.getOperand(1);
636       } else {
637         Index = N;
638       }
639
640       Base = CurDAG->getTargetConstant(0, Index.getValueType());
641       return true;
642     }
643   }
644
645   return false;
646 }
647
648 /*!
649   \arg Op The ISD instruction operand
650   \arg N The address operand
651   \arg Base The base pointer operand
652   \arg Index The offset/index operand
653
654   If the address \a N can be expressed as an A-form or D-form address, returns
655   false.  Otherwise, creates two operands, Base and Index that will become the
656   (r)(r) X-form address.
657 */
658 bool
659 SPUDAGToDAGISel::SelectXFormAddr(SDNode *Op, SDValue N, SDValue &Base,
660                                  SDValue &Index) {
661   if (!SelectAFormAddr(Op, N, Base, Index)
662       && !SelectDFormAddr(Op, N, Base, Index)) {
663     // If the address is neither A-form or D-form, punt and use an X-form
664     // address:
665     Base = N.getOperand(1);
666     Index = N.getOperand(0);
667     return true;
668   }
669
670   return false;
671 }
672
673 //! Convert the operand from a target-independent to a target-specific node
674 /*!
675  */
676 SDNode *
677 SPUDAGToDAGISel::Select(SDNode *N) {
678   unsigned Opc = N->getOpcode();
679   int n_ops = -1;
680   unsigned NewOpc;
681   EVT OpVT = N->getValueType(0);
682   SDValue Ops[8];
683   DebugLoc dl = N->getDebugLoc();
684
685   if (N->isMachineOpcode())
686     return NULL;   // Already selected.
687
688   if (Opc == ISD::FrameIndex) {
689     int FI = cast<FrameIndexSDNode>(N)->getIndex();
690     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
691     SDValue Imm0 = CurDAG->getTargetConstant(0, N->getValueType(0));
692
693     if (FI < 128) {
694       NewOpc = SPU::AIr32;
695       Ops[0] = TFI;
696       Ops[1] = Imm0;
697       n_ops = 2;
698     } else {
699       NewOpc = SPU::Ar32;
700       Ops[0] = CurDAG->getRegister(SPU::R1, N->getValueType(0));
701       Ops[1] = SDValue(CurDAG->getMachineNode(SPU::ILAr32, dl,
702                                               N->getValueType(0), TFI, Imm0),
703                        0);
704       n_ops = 2;
705     }
706   } else if (Opc == ISD::Constant && OpVT == MVT::i64) {
707     // Catch the i64 constants that end up here. Note: The backend doesn't
708     // attempt to legalize the constant (it's useless because DAGCombiner
709     // will insert 64-bit constants and we can't stop it).
710     return SelectI64Constant(N, OpVT, N->getDebugLoc());
711   } else if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND)
712              && OpVT == MVT::i64) {
713     SDValue Op0 = N->getOperand(0);
714     EVT Op0VT = Op0.getValueType();
715     EVT Op0VecVT = EVT::getVectorVT(*CurDAG->getContext(),
716                                     Op0VT, (128 / Op0VT.getSizeInBits()));
717     EVT OpVecVT = EVT::getVectorVT(*CurDAG->getContext(), 
718                                    OpVT, (128 / OpVT.getSizeInBits()));
719     SDValue shufMask;
720
721     switch (Op0VT.getSimpleVT().SimpleTy) {
722     default:
723       report_fatal_error("CellSPU Select: Unhandled zero/any extend EVT");
724       /*NOTREACHED*/
725     case MVT::i32:
726       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
727                                  CurDAG->getConstant(0x80808080, MVT::i32),
728                                  CurDAG->getConstant(0x00010203, MVT::i32),
729                                  CurDAG->getConstant(0x80808080, MVT::i32),
730                                  CurDAG->getConstant(0x08090a0b, MVT::i32));
731       break;
732
733     case MVT::i16:
734       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
735                                  CurDAG->getConstant(0x80808080, MVT::i32),
736                                  CurDAG->getConstant(0x80800203, MVT::i32),
737                                  CurDAG->getConstant(0x80808080, MVT::i32),
738                                  CurDAG->getConstant(0x80800a0b, MVT::i32));
739       break;
740
741     case MVT::i8:
742       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
743                                  CurDAG->getConstant(0x80808080, MVT::i32),
744                                  CurDAG->getConstant(0x80808003, MVT::i32),
745                                  CurDAG->getConstant(0x80808080, MVT::i32),
746                                  CurDAG->getConstant(0x8080800b, MVT::i32));
747       break;
748     }
749
750     SDNode *shufMaskLoad = emitBuildVector(shufMask.getNode());
751     
752     HandleSDNode PromoteScalar(CurDAG->getNode(SPUISD::PREFSLOT2VEC, dl,
753                                                Op0VecVT, Op0));
754     
755     SDValue PromScalar;
756     if (SDNode *N = SelectCode(PromoteScalar.getValue().getNode()))
757       PromScalar = SDValue(N, 0);
758     else
759       PromScalar = PromoteScalar.getValue();
760     
761     SDValue zextShuffle =
762             CurDAG->getNode(SPUISD::SHUFB, dl, OpVecVT,
763                             PromScalar, PromScalar, 
764                             SDValue(shufMaskLoad, 0));
765
766     HandleSDNode Dummy2(zextShuffle);
767     if (SDNode *N = SelectCode(Dummy2.getValue().getNode()))
768       zextShuffle = SDValue(N, 0);
769     else
770       zextShuffle = Dummy2.getValue();
771     HandleSDNode Dummy(CurDAG->getNode(SPUISD::VEC2PREFSLOT, dl, OpVT,
772                                        zextShuffle));
773     
774     CurDAG->ReplaceAllUsesWith(N, Dummy.getValue().getNode());
775     SelectCode(Dummy.getValue().getNode());
776     return Dummy.getValue().getNode();
777   } else if (Opc == ISD::ADD && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
778     SDNode *CGLoad =
779             emitBuildVector(getCarryGenerateShufMask(*CurDAG, dl).getNode());
780
781     HandleSDNode Dummy(CurDAG->getNode(SPUISD::ADD64_MARKER, dl, OpVT,
782                                        N->getOperand(0), N->getOperand(1),
783                                        SDValue(CGLoad, 0)));
784     
785     CurDAG->ReplaceAllUsesWith(N, Dummy.getValue().getNode());
786     if (SDNode *N = SelectCode(Dummy.getValue().getNode()))
787       return N;
788     return Dummy.getValue().getNode();
789   } else if (Opc == ISD::SUB && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
790     SDNode *CGLoad =
791             emitBuildVector(getBorrowGenerateShufMask(*CurDAG, dl).getNode());
792
793     HandleSDNode Dummy(CurDAG->getNode(SPUISD::SUB64_MARKER, dl, OpVT,
794                                        N->getOperand(0), N->getOperand(1),
795                                        SDValue(CGLoad, 0)));
796     
797     CurDAG->ReplaceAllUsesWith(N, Dummy.getValue().getNode());
798     if (SDNode *N = SelectCode(Dummy.getValue().getNode()))
799       return N;
800     return Dummy.getValue().getNode();
801   } else if (Opc == ISD::MUL && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
802     SDNode *CGLoad =
803             emitBuildVector(getCarryGenerateShufMask(*CurDAG, dl).getNode());
804
805     HandleSDNode Dummy(CurDAG->getNode(SPUISD::MUL64_MARKER, dl, OpVT,
806                                        N->getOperand(0), N->getOperand(1),
807                                        SDValue(CGLoad, 0)));
808     CurDAG->ReplaceAllUsesWith(N, Dummy.getValue().getNode());
809     if (SDNode *N = SelectCode(Dummy.getValue().getNode()))
810       return N;
811     return Dummy.getValue().getNode();
812   } else if (Opc == ISD::TRUNCATE) {
813     SDValue Op0 = N->getOperand(0);
814     if ((Op0.getOpcode() == ISD::SRA || Op0.getOpcode() == ISD::SRL)
815         && OpVT == MVT::i32
816         && Op0.getValueType() == MVT::i64) {
817       // Catch (truncate:i32 ([sra|srl]:i64 arg, c), where c >= 32
818       //
819       // Take advantage of the fact that the upper 32 bits are in the
820       // i32 preferred slot and avoid shuffle gymnastics:
821       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
822       if (CN != 0) {
823         unsigned shift_amt = unsigned(CN->getZExtValue());
824
825         if (shift_amt >= 32) {
826           SDNode *hi32 =
827                   CurDAG->getMachineNode(SPU::ORr32_r64, dl, OpVT,
828                                          Op0.getOperand(0));
829
830           shift_amt -= 32;
831           if (shift_amt > 0) {
832             // Take care of the additional shift, if present:
833             SDValue shift = CurDAG->getTargetConstant(shift_amt, MVT::i32);
834             unsigned Opc = SPU::ROTMAIr32_i32;
835
836             if (Op0.getOpcode() == ISD::SRL)
837               Opc = SPU::ROTMr32;
838
839             hi32 = CurDAG->getMachineNode(Opc, dl, OpVT, SDValue(hi32, 0),
840                                           shift);
841           }
842
843           return hi32;
844         }
845       }
846     }
847   } else if (Opc == ISD::SHL) {
848     if (OpVT == MVT::i64)
849       return SelectSHLi64(N, OpVT);
850   } else if (Opc == ISD::SRL) {
851     if (OpVT == MVT::i64)
852       return SelectSRLi64(N, OpVT);
853   } else if (Opc == ISD::SRA) {
854     if (OpVT == MVT::i64)
855       return SelectSRAi64(N, OpVT);
856   } else if (Opc == ISD::FNEG
857              && (OpVT == MVT::f64 || OpVT == MVT::v2f64)) {
858     DebugLoc dl = N->getDebugLoc();
859     // Check if the pattern is a special form of DFNMS:
860     // (fneg (fsub (fmul R64FP:$rA, R64FP:$rB), R64FP:$rC))
861     SDValue Op0 = N->getOperand(0);
862     if (Op0.getOpcode() == ISD::FSUB) {
863       SDValue Op00 = Op0.getOperand(0);
864       if (Op00.getOpcode() == ISD::FMUL) {
865         unsigned Opc = SPU::DFNMSf64;
866         if (OpVT == MVT::v2f64)
867           Opc = SPU::DFNMSv2f64;
868
869         return CurDAG->getMachineNode(Opc, dl, OpVT,
870                                       Op00.getOperand(0),
871                                       Op00.getOperand(1),
872                                       Op0.getOperand(1));
873       }
874     }
875
876     SDValue negConst = CurDAG->getConstant(0x8000000000000000ULL, MVT::i64);
877     SDNode *signMask = 0;
878     unsigned Opc = SPU::XORfneg64;
879
880     if (OpVT == MVT::f64) {
881       signMask = SelectI64Constant(negConst.getNode(), MVT::i64, dl);
882     } else if (OpVT == MVT::v2f64) {
883       Opc = SPU::XORfnegvec;
884       signMask = emitBuildVector(CurDAG->getNode(ISD::BUILD_VECTOR, dl,
885                                                  MVT::v2i64,
886                                                  negConst, negConst).getNode());
887     }
888
889     return CurDAG->getMachineNode(Opc, dl, OpVT,
890                                   N->getOperand(0), SDValue(signMask, 0));
891   } else if (Opc == ISD::FABS) {
892     if (OpVT == MVT::f64) {
893       SDNode *signMask = SelectI64Constant(0x7fffffffffffffffULL, MVT::i64, dl);
894       return CurDAG->getMachineNode(SPU::ANDfabs64, dl, OpVT,
895                                     N->getOperand(0), SDValue(signMask, 0));
896     } else if (OpVT == MVT::v2f64) {
897       SDValue absConst = CurDAG->getConstant(0x7fffffffffffffffULL, MVT::i64);
898       SDValue absVec = CurDAG->getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64,
899                                        absConst, absConst);
900       SDNode *signMask = emitBuildVector(absVec.getNode());
901       return CurDAG->getMachineNode(SPU::ANDfabsvec, dl, OpVT,
902                                     N->getOperand(0), SDValue(signMask, 0));
903     }
904   } else if (Opc == SPUISD::LDRESULT) {
905     // Custom select instructions for LDRESULT
906     EVT VT = N->getValueType(0);
907     SDValue Arg = N->getOperand(0);
908     SDValue Chain = N->getOperand(1);
909     SDNode *Result;
910     const valtype_map_s *vtm = getValueTypeMapEntry(VT);
911
912     if (vtm->ldresult_ins == 0) {
913       report_fatal_error("LDRESULT for unsupported type: " +
914                          Twine(VT.getEVTString()));
915     }
916
917     Opc = vtm->ldresult_ins;
918     if (vtm->ldresult_imm) {
919       SDValue Zero = CurDAG->getTargetConstant(0, VT);
920
921       Result = CurDAG->getMachineNode(Opc, dl, VT, MVT::Other, Arg, Zero, Chain);
922     } else {
923       Result = CurDAG->getMachineNode(Opc, dl, VT, MVT::Other, Arg, Arg, Chain);
924     }
925
926     return Result;
927   } else if (Opc == SPUISD::IndirectAddr) {
928     // Look at the operands: SelectCode() will catch the cases that aren't
929     // specifically handled here.
930     //
931     // SPUInstrInfo catches the following patterns:
932     // (SPUindirect (SPUhi ...), (SPUlo ...))
933     // (SPUindirect $sp, imm)
934     EVT VT = N->getValueType(0);
935     SDValue Op0 = N->getOperand(0);
936     SDValue Op1 = N->getOperand(1);
937     RegisterSDNode *RN;
938
939     if ((Op0.getOpcode() != SPUISD::Hi && Op1.getOpcode() != SPUISD::Lo)
940         || (Op0.getOpcode() == ISD::Register
941             && ((RN = dyn_cast<RegisterSDNode>(Op0.getNode())) != 0
942                 && RN->getReg() != SPU::R1))) {
943       NewOpc = SPU::Ar32;
944       Ops[1] = Op1;
945       if (Op1.getOpcode() == ISD::Constant) {
946         ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
947         Op1 = CurDAG->getTargetConstant(CN->getSExtValue(), VT);
948         if (isInt<10>(CN->getSExtValue())) {
949           NewOpc = SPU::AIr32;
950           Ops[1] = Op1;
951         } else {
952           Ops[1] = SDValue(CurDAG->getMachineNode(SPU::ILr32, dl, 
953                                                   N->getValueType(0), 
954                                                   Op1),
955                            0); 
956         }
957       }
958       Ops[0] = Op0;
959       n_ops = 2;
960     }
961   }
962
963   if (n_ops > 0) {
964     if (N->hasOneUse())
965       return CurDAG->SelectNodeTo(N, NewOpc, OpVT, Ops, n_ops);
966     else
967       return CurDAG->getMachineNode(NewOpc, dl, OpVT, Ops, n_ops);
968   } else
969     return SelectCode(N);
970 }
971
972 /*!
973  * Emit the instruction sequence for i64 left shifts. The basic algorithm
974  * is to fill the bottom two word slots with zeros so that zeros are shifted
975  * in as the entire quadword is shifted left.
976  *
977  * \note This code could also be used to implement v2i64 shl.
978  *
979  * @param Op The shl operand
980  * @param OpVT Op's machine value value type (doesn't need to be passed, but
981  * makes life easier.)
982  * @return The SDNode with the entire instruction sequence
983  */
984 SDNode *
985 SPUDAGToDAGISel::SelectSHLi64(SDNode *N, EVT OpVT) {
986   SDValue Op0 = N->getOperand(0);
987   EVT VecVT = EVT::getVectorVT(*CurDAG->getContext(), 
988                                OpVT, (128 / OpVT.getSizeInBits()));
989   SDValue ShiftAmt = N->getOperand(1);
990   EVT ShiftAmtVT = ShiftAmt.getValueType();
991   SDNode *VecOp0, *SelMask, *ZeroFill, *Shift = 0;
992   SDValue SelMaskVal;
993   DebugLoc dl = N->getDebugLoc();
994
995   VecOp0 = CurDAG->getMachineNode(SPU::ORv2i64_i64, dl, VecVT, Op0);
996   SelMaskVal = CurDAG->getTargetConstant(0xff00ULL, MVT::i16);
997   SelMask = CurDAG->getMachineNode(SPU::FSMBIv2i64, dl, VecVT, SelMaskVal);
998   ZeroFill = CurDAG->getMachineNode(SPU::ILv2i64, dl, VecVT,
999                                     CurDAG->getTargetConstant(0, OpVT));
1000   VecOp0 = CurDAG->getMachineNode(SPU::SELBv2i64, dl, VecVT,
1001                                   SDValue(ZeroFill, 0),
1002                                   SDValue(VecOp0, 0),
1003                                   SDValue(SelMask, 0));
1004
1005   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
1006     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
1007     unsigned bits = unsigned(CN->getZExtValue()) & 7;
1008
1009     if (bytes > 0) {
1010       Shift =
1011         CurDAG->getMachineNode(SPU::SHLQBYIv2i64, dl, VecVT,
1012                                SDValue(VecOp0, 0),
1013                                CurDAG->getTargetConstant(bytes, ShiftAmtVT));
1014     }
1015
1016     if (bits > 0) {
1017       Shift =
1018         CurDAG->getMachineNode(SPU::SHLQBIIv2i64, dl, VecVT,
1019                                SDValue((Shift != 0 ? Shift : VecOp0), 0),
1020                                CurDAG->getTargetConstant(bits, ShiftAmtVT));
1021     }
1022   } else {
1023     SDNode *Bytes =
1024       CurDAG->getMachineNode(SPU::ROTMIr32, dl, ShiftAmtVT,
1025                              ShiftAmt,
1026                              CurDAG->getTargetConstant(3, ShiftAmtVT));
1027     SDNode *Bits =
1028       CurDAG->getMachineNode(SPU::ANDIr32, dl, ShiftAmtVT,
1029                              ShiftAmt,
1030                              CurDAG->getTargetConstant(7, ShiftAmtVT));
1031     Shift =
1032       CurDAG->getMachineNode(SPU::SHLQBYv2i64, dl, VecVT,
1033                              SDValue(VecOp0, 0), SDValue(Bytes, 0));
1034     Shift =
1035       CurDAG->getMachineNode(SPU::SHLQBIv2i64, dl, VecVT,
1036                              SDValue(Shift, 0), SDValue(Bits, 0));
1037   }
1038
1039   return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT, SDValue(Shift, 0));
1040 }
1041
1042 /*!
1043  * Emit the instruction sequence for i64 logical right shifts.
1044  *
1045  * @param Op The shl operand
1046  * @param OpVT Op's machine value value type (doesn't need to be passed, but
1047  * makes life easier.)
1048  * @return The SDNode with the entire instruction sequence
1049  */
1050 SDNode *
1051 SPUDAGToDAGISel::SelectSRLi64(SDNode *N, EVT OpVT) {
1052   SDValue Op0 = N->getOperand(0);
1053   EVT VecVT = EVT::getVectorVT(*CurDAG->getContext(),
1054                                OpVT, (128 / OpVT.getSizeInBits()));
1055   SDValue ShiftAmt = N->getOperand(1);
1056   EVT ShiftAmtVT = ShiftAmt.getValueType();
1057   SDNode *VecOp0, *Shift = 0;
1058   DebugLoc dl = N->getDebugLoc();
1059
1060   VecOp0 = CurDAG->getMachineNode(SPU::ORv2i64_i64, dl, VecVT, Op0);
1061
1062   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
1063     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
1064     unsigned bits = unsigned(CN->getZExtValue()) & 7;
1065
1066     if (bytes > 0) {
1067       Shift =
1068         CurDAG->getMachineNode(SPU::ROTQMBYIv2i64, dl, VecVT,
1069                                SDValue(VecOp0, 0),
1070                                CurDAG->getTargetConstant(bytes, ShiftAmtVT));
1071     }
1072
1073     if (bits > 0) {
1074       Shift =
1075         CurDAG->getMachineNode(SPU::ROTQMBIIv2i64, dl, VecVT,
1076                                SDValue((Shift != 0 ? Shift : VecOp0), 0),
1077                                CurDAG->getTargetConstant(bits, ShiftAmtVT));
1078     }
1079   } else {
1080     SDNode *Bytes =
1081       CurDAG->getMachineNode(SPU::ROTMIr32, dl, ShiftAmtVT,
1082                              ShiftAmt,
1083                              CurDAG->getTargetConstant(3, ShiftAmtVT));
1084     SDNode *Bits =
1085       CurDAG->getMachineNode(SPU::ANDIr32, dl, ShiftAmtVT,
1086                              ShiftAmt,
1087                              CurDAG->getTargetConstant(7, ShiftAmtVT));
1088
1089     // Ensure that the shift amounts are negated!
1090     Bytes = CurDAG->getMachineNode(SPU::SFIr32, dl, ShiftAmtVT,
1091                                    SDValue(Bytes, 0),
1092                                    CurDAG->getTargetConstant(0, ShiftAmtVT));
1093
1094     Bits = CurDAG->getMachineNode(SPU::SFIr32, dl, ShiftAmtVT,
1095                                   SDValue(Bits, 0),
1096                                   CurDAG->getTargetConstant(0, ShiftAmtVT));
1097
1098     Shift =
1099       CurDAG->getMachineNode(SPU::ROTQMBYv2i64, dl, VecVT,
1100                              SDValue(VecOp0, 0), SDValue(Bytes, 0));
1101     Shift =
1102       CurDAG->getMachineNode(SPU::ROTQMBIv2i64, dl, VecVT,
1103                              SDValue(Shift, 0), SDValue(Bits, 0));
1104   }
1105
1106   return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT, SDValue(Shift, 0));
1107 }
1108
1109 /*!
1110  * Emit the instruction sequence for i64 arithmetic right shifts.
1111  *
1112  * @param Op The shl operand
1113  * @param OpVT Op's machine value value type (doesn't need to be passed, but
1114  * makes life easier.)
1115  * @return The SDNode with the entire instruction sequence
1116  */
1117 SDNode *
1118 SPUDAGToDAGISel::SelectSRAi64(SDNode *N, EVT OpVT) {
1119   // Promote Op0 to vector
1120   EVT VecVT = EVT::getVectorVT(*CurDAG->getContext(), 
1121                                OpVT, (128 / OpVT.getSizeInBits()));
1122   SDValue ShiftAmt = N->getOperand(1);
1123   EVT ShiftAmtVT = ShiftAmt.getValueType();
1124   DebugLoc dl = N->getDebugLoc();
1125
1126   SDNode *VecOp0 =
1127     CurDAG->getMachineNode(SPU::ORv2i64_i64, dl, VecVT, N->getOperand(0));
1128
1129   SDValue SignRotAmt = CurDAG->getTargetConstant(31, ShiftAmtVT);
1130   SDNode *SignRot =
1131     CurDAG->getMachineNode(SPU::ROTMAIv2i64_i32, dl, MVT::v2i64,
1132                            SDValue(VecOp0, 0), SignRotAmt);
1133   SDNode *UpperHalfSign =
1134     CurDAG->getMachineNode(SPU::ORi32_v4i32, dl, MVT::i32, SDValue(SignRot, 0));
1135
1136   SDNode *UpperHalfSignMask =
1137     CurDAG->getMachineNode(SPU::FSM64r32, dl, VecVT, SDValue(UpperHalfSign, 0));
1138   SDNode *UpperLowerMask =
1139     CurDAG->getMachineNode(SPU::FSMBIv2i64, dl, VecVT,
1140                            CurDAG->getTargetConstant(0xff00ULL, MVT::i16));
1141   SDNode *UpperLowerSelect =
1142     CurDAG->getMachineNode(SPU::SELBv2i64, dl, VecVT,
1143                            SDValue(UpperHalfSignMask, 0),
1144                            SDValue(VecOp0, 0),
1145                            SDValue(UpperLowerMask, 0));
1146
1147   SDNode *Shift = 0;
1148
1149   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
1150     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
1151     unsigned bits = unsigned(CN->getZExtValue()) & 7;
1152
1153     if (bytes > 0) {
1154       bytes = 31 - bytes;
1155       Shift =
1156         CurDAG->getMachineNode(SPU::ROTQBYIv2i64, dl, VecVT,
1157                                SDValue(UpperLowerSelect, 0),
1158                                CurDAG->getTargetConstant(bytes, ShiftAmtVT));
1159     }
1160
1161     if (bits > 0) {
1162       bits = 8 - bits;
1163       Shift =
1164         CurDAG->getMachineNode(SPU::ROTQBIIv2i64, dl, VecVT,
1165                                SDValue((Shift != 0 ? Shift : UpperLowerSelect), 0),
1166                                CurDAG->getTargetConstant(bits, ShiftAmtVT));
1167     }
1168   } else {
1169     SDNode *NegShift =
1170       CurDAG->getMachineNode(SPU::SFIr32, dl, ShiftAmtVT,
1171                              ShiftAmt, CurDAG->getTargetConstant(0, ShiftAmtVT));
1172
1173     Shift =
1174       CurDAG->getMachineNode(SPU::ROTQBYBIv2i64_r32, dl, VecVT,
1175                              SDValue(UpperLowerSelect, 0), SDValue(NegShift, 0));
1176     Shift =
1177       CurDAG->getMachineNode(SPU::ROTQBIv2i64, dl, VecVT,
1178                              SDValue(Shift, 0), SDValue(NegShift, 0));
1179   }
1180
1181   return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT, SDValue(Shift, 0));
1182 }
1183
1184 /*!
1185  Do the necessary magic necessary to load a i64 constant
1186  */
1187 SDNode *SPUDAGToDAGISel::SelectI64Constant(SDNode *N, EVT OpVT,
1188                                            DebugLoc dl) {
1189   ConstantSDNode *CN = cast<ConstantSDNode>(N);
1190   return SelectI64Constant(CN->getZExtValue(), OpVT, dl);
1191 }
1192
1193 SDNode *SPUDAGToDAGISel::SelectI64Constant(uint64_t Value64, EVT OpVT,
1194                                            DebugLoc dl) {
1195   EVT OpVecVT = EVT::getVectorVT(*CurDAG->getContext(), OpVT, 2);
1196   SDValue i64vec =
1197           SPU::LowerV2I64Splat(OpVecVT, *CurDAG, Value64, dl);
1198
1199   // Here's where it gets interesting, because we have to parse out the
1200   // subtree handed back in i64vec:
1201
1202   if (i64vec.getOpcode() == ISD::BIT_CONVERT) {
1203     // The degenerate case where the upper and lower bits in the splat are
1204     // identical:
1205     SDValue Op0 = i64vec.getOperand(0);
1206
1207     ReplaceUses(i64vec, Op0);
1208     return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT,
1209                                   SDValue(emitBuildVector(Op0.getNode()), 0));
1210   } else if (i64vec.getOpcode() == SPUISD::SHUFB) {
1211     SDValue lhs = i64vec.getOperand(0);
1212     SDValue rhs = i64vec.getOperand(1);
1213     SDValue shufmask = i64vec.getOperand(2);
1214
1215     if (lhs.getOpcode() == ISD::BIT_CONVERT) {
1216       ReplaceUses(lhs, lhs.getOperand(0));
1217       lhs = lhs.getOperand(0);
1218     }
1219
1220     SDNode *lhsNode = (lhs.getNode()->isMachineOpcode()
1221                        ? lhs.getNode()
1222                        : emitBuildVector(lhs.getNode()));
1223
1224     if (rhs.getOpcode() == ISD::BIT_CONVERT) {
1225       ReplaceUses(rhs, rhs.getOperand(0));
1226       rhs = rhs.getOperand(0);
1227     }
1228
1229     SDNode *rhsNode = (rhs.getNode()->isMachineOpcode()
1230                        ? rhs.getNode()
1231                        : emitBuildVector(rhs.getNode()));
1232
1233     if (shufmask.getOpcode() == ISD::BIT_CONVERT) {
1234       ReplaceUses(shufmask, shufmask.getOperand(0));
1235       shufmask = shufmask.getOperand(0);
1236     }
1237
1238     SDNode *shufMaskNode = (shufmask.getNode()->isMachineOpcode()
1239                             ? shufmask.getNode()
1240                             : emitBuildVector(shufmask.getNode()));
1241
1242    SDValue shufNode =
1243             CurDAG->getNode(SPUISD::SHUFB, dl, OpVecVT,
1244                                    SDValue(lhsNode, 0), SDValue(rhsNode, 0),
1245                                    SDValue(shufMaskNode, 0));
1246     HandleSDNode Dummy(shufNode);
1247     SDNode *SN = SelectCode(Dummy.getValue().getNode());
1248     if (SN == 0) SN = Dummy.getValue().getNode();
1249     
1250     return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT, SDValue(SN, 0));
1251   } else if (i64vec.getOpcode() == ISD::BUILD_VECTOR) {
1252     return CurDAG->getMachineNode(SPU::ORi64_v2i64, dl, OpVT,
1253                                   SDValue(emitBuildVector(i64vec.getNode()), 0));
1254   } else {
1255     report_fatal_error("SPUDAGToDAGISel::SelectI64Constant: Unhandled i64vec"
1256                       "condition");
1257   }
1258 }
1259
1260 /// createSPUISelDag - This pass converts a legalized DAG into a
1261 /// SPU-specific DAG, ready for instruction scheduling.
1262 ///
1263 FunctionPass *llvm::createSPUISelDag(SPUTargetMachine &TM) {
1264   return new SPUDAGToDAGISel(TM);
1265 }