- Convert remaining i64 custom lowering into custom instruction emission
[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 "SPUISelLowering.h"
18 #include "SPUHazardRecognizers.h"
19 #include "SPUFrameInfo.h"
20 #include "SPURegisterNames.h"
21 #include "SPUTargetMachine.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Constants.h"
31 #include "llvm/GlobalValue.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Compiler.h"
36
37 using namespace llvm;
38
39 namespace {
40   //! ConstantSDNode predicate for i32 sign-extended, 10-bit immediates
41   bool
42   isI64IntS10Immediate(ConstantSDNode *CN)
43   {
44     return isS10Constant(CN->getSExtValue());
45   }
46
47   //! ConstantSDNode predicate for i32 sign-extended, 10-bit immediates
48   bool
49   isI32IntS10Immediate(ConstantSDNode *CN)
50   {
51     return isS10Constant(CN->getSExtValue());
52   }
53
54 #if 0
55   //! SDNode predicate for sign-extended, 10-bit immediate values
56   bool
57   isI32IntS10Immediate(SDNode *N)
58   {
59     return (N->getOpcode() == ISD::Constant
60             && isI32IntS10Immediate(cast<ConstantSDNode>(N)));
61   }
62 #endif
63
64   //! ConstantSDNode predicate for i32 unsigned 10-bit immediate values
65   bool
66   isI32IntU10Immediate(ConstantSDNode *CN)
67   {
68     return isU10Constant(CN->getSExtValue());
69   }
70
71   //! ConstantSDNode predicate for i16 sign-extended, 10-bit immediate values
72   bool
73   isI16IntS10Immediate(ConstantSDNode *CN)
74   {
75     return isS10Constant(CN->getSExtValue());
76   }
77
78   //! SDNode predicate for i16 sign-extended, 10-bit immediate values
79   bool
80   isI16IntS10Immediate(SDNode *N)
81   {
82     return (N->getOpcode() == ISD::Constant
83             && isI16IntS10Immediate(cast<ConstantSDNode>(N)));
84   }
85
86   //! ConstantSDNode predicate for i16 unsigned 10-bit immediate values
87   bool
88   isI16IntU10Immediate(ConstantSDNode *CN)
89   {
90     return isU10Constant((short) CN->getZExtValue());
91   }
92
93   //! SDNode predicate for i16 sign-extended, 10-bit immediate values
94   bool
95   isI16IntU10Immediate(SDNode *N)
96   {
97     return (N->getOpcode() == ISD::Constant
98             && isI16IntU10Immediate(cast<ConstantSDNode>(N)));
99   }
100
101   //! ConstantSDNode predicate for signed 16-bit values
102   /*!
103     \arg CN The constant SelectionDAG node holding the value
104     \arg Imm The returned 16-bit value, if returning true
105
106     This predicate tests the value in \a CN to see whether it can be
107     represented as a 16-bit, sign-extended quantity. Returns true if
108     this is the case.
109    */
110   bool
111   isIntS16Immediate(ConstantSDNode *CN, short &Imm)
112   {
113     MVT vt = CN->getValueType(0);
114     Imm = (short) CN->getZExtValue();
115     if (vt.getSimpleVT() >= MVT::i1 && vt.getSimpleVT() <= MVT::i16) {
116       return true;
117     } else if (vt == MVT::i32) {
118       int32_t i_val = (int32_t) CN->getZExtValue();
119       short s_val = (short) i_val;
120       return i_val == s_val;
121     } else {
122       int64_t i_val = (int64_t) CN->getZExtValue();
123       short s_val = (short) i_val;
124       return i_val == s_val;
125     }
126
127     return false;
128   }
129
130   //! SDNode predicate for signed 16-bit values.
131   bool
132   isIntS16Immediate(SDNode *N, short &Imm)
133   {
134     return (N->getOpcode() == ISD::Constant
135             && isIntS16Immediate(cast<ConstantSDNode>(N), Imm));
136   }
137
138   //! ConstantFPSDNode predicate for representing floats as 16-bit sign ext.
139   static bool
140   isFPS16Immediate(ConstantFPSDNode *FPN, short &Imm)
141   {
142     MVT vt = FPN->getValueType(0);
143     if (vt == MVT::f32) {
144       int val = FloatToBits(FPN->getValueAPF().convertToFloat());
145       int sval = (int) ((val << 16) >> 16);
146       Imm = (short) val;
147       return val == sval;
148     }
149
150     return false;
151   }
152
153   bool
154   isHighLow(const SDValue &Op)
155   {
156     return (Op.getOpcode() == SPUISD::IndirectAddr
157             && ((Op.getOperand(0).getOpcode() == SPUISD::Hi
158                  && Op.getOperand(1).getOpcode() == SPUISD::Lo)
159                 || (Op.getOperand(0).getOpcode() == SPUISD::Lo
160                     && Op.getOperand(1).getOpcode() == SPUISD::Hi)));
161   }
162
163   //===------------------------------------------------------------------===//
164   //! MVT to "useful stuff" mapping structure:
165
166   struct valtype_map_s {
167     MVT VT;
168     unsigned ldresult_ins;      /// LDRESULT instruction (0 = undefined)
169     bool ldresult_imm;          /// LDRESULT instruction requires immediate?
170     unsigned lrinst;            /// LR instruction
171   };
172
173   const valtype_map_s valtype_map[] = {
174     { MVT::i8,    SPU::ORBIr8,  true,  SPU::LRr8 },
175     { MVT::i16,   SPU::ORHIr16, true,  SPU::LRr16 },
176     { MVT::i32,   SPU::ORIr32,  true,  SPU::LRr32 },
177     { MVT::i64,   SPU::ORr64,   false, SPU::LRr64 },
178     { MVT::f32,   SPU::ORf32,   false, SPU::LRf32 },
179     { MVT::f64,   SPU::ORf64,   false, SPU::LRf64 },
180     // vector types... (sigh!)
181     { MVT::v16i8, 0,            false, SPU::LRv16i8 },
182     { MVT::v8i16, 0,            false, SPU::LRv8i16 },
183     { MVT::v4i32, 0,            false, SPU::LRv4i32 },
184     { MVT::v2i64, 0,            false, SPU::LRv2i64 },
185     { MVT::v4f32, 0,            false, SPU::LRv4f32 },
186     { MVT::v2f64, 0,            false, SPU::LRv2f64 }
187   };
188
189   const size_t n_valtype_map = sizeof(valtype_map) / sizeof(valtype_map[0]);
190
191   const valtype_map_s *getValueTypeMapEntry(MVT VT)
192   {
193     const valtype_map_s *retval = 0;
194     for (size_t i = 0; i < n_valtype_map; ++i) {
195       if (valtype_map[i].VT == VT) {
196         retval = valtype_map + i;
197         break;
198       }
199     }
200
201
202 #ifndef NDEBUG
203     if (retval == 0) {
204       cerr << "SPUISelDAGToDAG.cpp: getValueTypeMapEntry returns NULL for "
205            << VT.getMVTString()
206            << "\n";
207       abort();
208     }
209 #endif
210
211     return retval;
212   }
213 }
214
215 namespace {
216
217 //===--------------------------------------------------------------------===//
218 /// SPUDAGToDAGISel - Cell SPU-specific code to select SPU machine
219 /// instructions for SelectionDAG operations.
220 ///
221 class SPUDAGToDAGISel :
222   public SelectionDAGISel
223 {
224   SPUTargetMachine &TM;
225   SPUTargetLowering &SPUtli;
226   unsigned GlobalBaseReg;
227
228 public:
229   explicit SPUDAGToDAGISel(SPUTargetMachine &tm) :
230     SelectionDAGISel(*tm.getTargetLowering()),
231     TM(tm),
232     SPUtli(*tm.getTargetLowering())
233   {}
234
235   virtual bool runOnFunction(Function &Fn) {
236     // Make sure we re-emit a set of the global base reg if necessary
237     GlobalBaseReg = 0;
238     SelectionDAGISel::runOnFunction(Fn);
239     return true;
240   }
241
242   /// getI32Imm - Return a target constant with the specified value, of type
243   /// i32.
244   inline SDValue getI32Imm(uint32_t Imm) {
245     return CurDAG->getTargetConstant(Imm, MVT::i32);
246   }
247
248   /// getI64Imm - Return a target constant with the specified value, of type
249   /// i64.
250   inline SDValue getI64Imm(uint64_t Imm) {
251     return CurDAG->getTargetConstant(Imm, MVT::i64);
252   }
253
254   /// getSmallIPtrImm - Return a target constant of pointer type.
255   inline SDValue getSmallIPtrImm(unsigned Imm) {
256     return CurDAG->getTargetConstant(Imm, SPUtli.getPointerTy());
257   }
258
259   SDNode *emitBuildVector(SDValue build_vec) {
260     std::vector<Constant*> CV;
261
262     for (size_t i = 0; i < build_vec.getNumOperands(); ++i) {
263       ConstantSDNode *V = dyn_cast<ConstantSDNode>(build_vec.getOperand(i));
264       CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
265     }
266
267     Constant *CP = ConstantVector::get(CV);
268     SDValue CPIdx = CurDAG->getConstantPool(CP, SPUtli.getPointerTy());
269     unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
270     SDValue CGPoolOffset =
271             SPU::LowerConstantPool(CPIdx, *CurDAG,
272                                    SPUtli.getSPUTargetMachine());
273     return SelectCode(CurDAG->getLoad(build_vec.getValueType(),
274                       CurDAG->getEntryNode(), CGPoolOffset,
275                       PseudoSourceValue::getConstantPool(), 0,
276                       false, Alignment));
277   }
278
279   /// Select - Convert the specified operand from a target-independent to a
280   /// target-specific node if it hasn't already been changed.
281   SDNode *Select(SDValue Op);
282
283   //! Emit the instruction sequence for i64 shl
284   SDNode *SelectSHLi64(SDValue &Op, MVT OpVT);
285
286   //! Emit the instruction sequence for i64 srl
287   SDNode *SelectSRLi64(SDValue &Op, MVT OpVT);
288
289   //! Emit the instruction sequence for i64 sra
290   SDNode *SelectSRAi64(SDValue &Op, MVT OpVT);
291
292   //! Returns true if the address N is an A-form (local store) address
293   bool SelectAFormAddr(SDValue Op, SDValue N, SDValue &Base,
294                        SDValue &Index);
295
296   //! D-form address predicate
297   bool SelectDFormAddr(SDValue Op, SDValue N, SDValue &Base,
298                        SDValue &Index);
299
300   /// Alternate D-form address using i7 offset predicate
301   bool SelectDForm2Addr(SDValue Op, SDValue N, SDValue &Disp,
302                         SDValue &Base);
303
304   /// D-form address selection workhorse
305   bool DFormAddressPredicate(SDValue Op, SDValue N, SDValue &Disp,
306                              SDValue &Base, int minOffset, int maxOffset);
307
308   //! Address predicate if N can be expressed as an indexed [r+r] operation.
309   bool SelectXFormAddr(SDValue Op, SDValue N, SDValue &Base,
310                        SDValue &Index);
311
312   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
313   /// inline asm expressions.
314   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
315                                             char ConstraintCode,
316                                             std::vector<SDValue> &OutOps) {
317     SDValue Op0, Op1;
318     switch (ConstraintCode) {
319     default: return true;
320     case 'm':   // memory
321       if (!SelectDFormAddr(Op, Op, Op0, Op1)
322           && !SelectAFormAddr(Op, Op, Op0, Op1))
323         SelectXFormAddr(Op, Op, Op0, Op1);
324       break;
325     case 'o':   // offsetable
326       if (!SelectDFormAddr(Op, Op, Op0, Op1)
327           && !SelectAFormAddr(Op, Op, Op0, Op1)) {
328         Op0 = Op;
329         Op1 = getSmallIPtrImm(0);
330       }
331       break;
332     case 'v':   // not offsetable
333 #if 1
334       assert(0 && "InlineAsmMemoryOperand 'v' constraint not handled.");
335 #else
336       SelectAddrIdxOnly(Op, Op, Op0, Op1);
337 #endif
338       break;
339     }
340
341     OutOps.push_back(Op0);
342     OutOps.push_back(Op1);
343     return false;
344   }
345
346   /// InstructionSelect - This callback is invoked by
347   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
348   virtual void InstructionSelect();
349
350   virtual const char *getPassName() const {
351     return "Cell SPU DAG->DAG Pattern Instruction Selection";
352   }
353
354   /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
355   /// this target when scheduling the DAG.
356   virtual HazardRecognizer *CreateTargetHazardRecognizer() {
357     const TargetInstrInfo *II = TM.getInstrInfo();
358     assert(II && "No InstrInfo?");
359     return new SPUHazardRecognizer(*II);
360   }
361
362   // Include the pieces autogenerated from the target description.
363 #include "SPUGenDAGISel.inc"
364 };
365
366 }
367
368 /// InstructionSelect - This callback is invoked by
369 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
370 void
371 SPUDAGToDAGISel::InstructionSelect()
372 {
373   DEBUG(BB->dump());
374
375   // Select target instructions for the DAG.
376   SelectRoot(*CurDAG);
377   CurDAG->RemoveDeadNodes();
378 }
379
380 /*!
381  \arg Op The ISD instructio operand
382  \arg N The address to be tested
383  \arg Base The base address
384  \arg Index The base address index
385  */
386 bool
387 SPUDAGToDAGISel::SelectAFormAddr(SDValue Op, SDValue N, SDValue &Base,
388                     SDValue &Index) {
389   // These match the addr256k operand type:
390   MVT OffsVT = MVT::i16;
391   SDValue Zero = CurDAG->getTargetConstant(0, OffsVT);
392
393   switch (N.getOpcode()) {
394   case ISD::Constant:
395   case ISD::ConstantPool:
396   case ISD::GlobalAddress:
397     cerr << "SPU SelectAFormAddr: Constant/Pool/Global not lowered.\n";
398     abort();
399     /*NOTREACHED*/
400
401   case ISD::TargetConstant:
402   case ISD::TargetGlobalAddress:
403   case ISD::TargetJumpTable:
404     cerr << "SPUSelectAFormAddr: Target Constant/Pool/Global not wrapped as "
405          << "A-form address.\n";
406     abort();
407     /*NOTREACHED*/
408
409   case SPUISD::AFormAddr:
410     // Just load from memory if there's only a single use of the location,
411     // otherwise, this will get handled below with D-form offset addresses
412     if (N.hasOneUse()) {
413       SDValue Op0 = N.getOperand(0);
414       switch (Op0.getOpcode()) {
415       case ISD::TargetConstantPool:
416       case ISD::TargetJumpTable:
417         Base = Op0;
418         Index = Zero;
419         return true;
420
421       case ISD::TargetGlobalAddress: {
422         GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op0);
423         GlobalValue *GV = GSDN->getGlobal();
424         if (GV->getAlignment() == 16) {
425           Base = Op0;
426           Index = Zero;
427           return true;
428         }
429         break;
430       }
431       }
432     }
433     break;
434   }
435   return false;
436 }
437
438 bool
439 SPUDAGToDAGISel::SelectDForm2Addr(SDValue Op, SDValue N, SDValue &Disp,
440                                   SDValue &Base) {
441   const int minDForm2Offset = -(1 << 7);
442   const int maxDForm2Offset = (1 << 7) - 1;
443   return DFormAddressPredicate(Op, N, Disp, Base, minDForm2Offset,
444                                maxDForm2Offset);
445 }
446
447 /*!
448   \arg Op The ISD instruction (ignored)
449   \arg N The address to be tested
450   \arg Base Base address register/pointer
451   \arg Index Base address index
452
453   Examine the input address by a base register plus a signed 10-bit
454   displacement, [r+I10] (D-form address).
455
456   \return true if \a N is a D-form address with \a Base and \a Index set
457   to non-empty SDValue instances.
458 */
459 bool
460 SPUDAGToDAGISel::SelectDFormAddr(SDValue Op, SDValue N, SDValue &Base,
461                                  SDValue &Index) {
462   return DFormAddressPredicate(Op, N, Base, Index,
463                                SPUFrameInfo::minFrameOffset(),
464                                SPUFrameInfo::maxFrameOffset());
465 }
466
467 bool
468 SPUDAGToDAGISel::DFormAddressPredicate(SDValue Op, SDValue N, SDValue &Base,
469                                       SDValue &Index, int minOffset,
470                                       int maxOffset) {
471   unsigned Opc = N.getOpcode();
472   MVT PtrTy = SPUtli.getPointerTy();
473
474   if (Opc == ISD::FrameIndex) {
475     // Stack frame index must be less than 512 (divided by 16):
476     FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(N);
477     int FI = int(FIN->getIndex());
478     DEBUG(cerr << "SelectDFormAddr: ISD::FrameIndex = "
479                << FI << "\n");
480     if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
481       Base = CurDAG->getTargetConstant(0, PtrTy);
482       Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
483       return true;
484     }
485   } else if (Opc == ISD::ADD) {
486     // Generated by getelementptr
487     const SDValue Op0 = N.getOperand(0);
488     const SDValue Op1 = N.getOperand(1);
489
490     if ((Op0.getOpcode() == SPUISD::Hi && Op1.getOpcode() == SPUISD::Lo)
491         || (Op1.getOpcode() == SPUISD::Hi && Op0.getOpcode() == SPUISD::Lo)) {
492       Base = CurDAG->getTargetConstant(0, PtrTy);
493       Index = N;
494       return true;
495     } else if (Op1.getOpcode() == ISD::Constant
496                || Op1.getOpcode() == ISD::TargetConstant) {
497       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1);
498       int32_t offset = int32_t(CN->getSExtValue());
499
500       if (Op0.getOpcode() == ISD::FrameIndex) {
501         FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op0);
502         int FI = int(FIN->getIndex());
503         DEBUG(cerr << "SelectDFormAddr: ISD::ADD offset = " << offset
504                    << " frame index = " << FI << "\n");
505
506         if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
507           Base = CurDAG->getTargetConstant(offset, PtrTy);
508           Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
509           return true;
510         }
511       } else if (offset > minOffset && offset < maxOffset) {
512         Base = CurDAG->getTargetConstant(offset, PtrTy);
513         Index = Op0;
514         return true;
515       }
516     } else if (Op0.getOpcode() == ISD::Constant
517                || Op0.getOpcode() == ISD::TargetConstant) {
518       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op0);
519       int32_t offset = int32_t(CN->getSExtValue());
520
521       if (Op1.getOpcode() == ISD::FrameIndex) {
522         FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op1);
523         int FI = int(FIN->getIndex());
524         DEBUG(cerr << "SelectDFormAddr: ISD::ADD offset = " << offset
525                    << " frame index = " << FI << "\n");
526
527         if (SPUFrameInfo::FItoStackOffset(FI) < maxOffset) {
528           Base = CurDAG->getTargetConstant(offset, PtrTy);
529           Index = CurDAG->getTargetFrameIndex(FI, PtrTy);
530           return true;
531         }
532       } else if (offset > minOffset && offset < maxOffset) {
533         Base = CurDAG->getTargetConstant(offset, PtrTy);
534         Index = Op1;
535         return true;
536       }
537     }
538   } else if (Opc == SPUISD::IndirectAddr) {
539     // Indirect with constant offset -> D-Form address
540     const SDValue Op0 = N.getOperand(0);
541     const SDValue Op1 = N.getOperand(1);
542
543     if (Op0.getOpcode() == SPUISD::Hi
544         && Op1.getOpcode() == SPUISD::Lo) {
545       // (SPUindirect (SPUhi <arg>, 0), (SPUlo <arg>, 0))
546       Base = CurDAG->getTargetConstant(0, PtrTy);
547       Index = N;
548       return true;
549     } else if (isa<ConstantSDNode>(Op0) || isa<ConstantSDNode>(Op1)) {
550       int32_t offset = 0;
551       SDValue idxOp;
552
553       if (isa<ConstantSDNode>(Op1)) {
554         ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
555         offset = int32_t(CN->getSExtValue());
556         idxOp = Op0;
557       } else if (isa<ConstantSDNode>(Op0)) {
558         ConstantSDNode *CN = cast<ConstantSDNode>(Op0);
559         offset = int32_t(CN->getSExtValue());
560         idxOp = Op1;
561       }
562
563       if (offset >= minOffset && offset <= maxOffset) {
564         Base = CurDAG->getTargetConstant(offset, PtrTy);
565         Index = idxOp;
566         return true;
567       }
568     }
569   } else if (Opc == SPUISD::AFormAddr) {
570     Base = CurDAG->getTargetConstant(0, N.getValueType());
571     Index = N;
572     return true;
573   } else if (Opc == SPUISD::LDRESULT) {
574     Base = CurDAG->getTargetConstant(0, N.getValueType());
575     Index = N;
576     return true;
577   } else if (Opc == ISD::Register || Opc == ISD::CopyFromReg) {
578     unsigned OpOpc = Op.getOpcode();
579
580     if (OpOpc == ISD::STORE || OpOpc == ISD::LOAD) {
581       // Direct load/store without getelementptr
582       SDValue Addr, Offs;
583
584       // Get the register from CopyFromReg
585       if (Opc == ISD::CopyFromReg)
586         Addr = N.getOperand(1);
587       else
588         Addr = N;                       // Register
589
590       Offs = ((OpOpc == ISD::STORE) ? Op.getOperand(3) : Op.getOperand(2));
591
592       if (Offs.getOpcode() == ISD::Constant || Offs.getOpcode() == ISD::UNDEF) {
593         if (Offs.getOpcode() == ISD::UNDEF)
594           Offs = CurDAG->getTargetConstant(0, Offs.getValueType());
595
596         Base = Offs;
597         Index = Addr;
598         return true;
599       }
600     } else {
601       /* If otherwise unadorned, default to D-form address with 0 offset: */
602       if (Opc == ISD::CopyFromReg) {
603         Index = N.getOperand(1);
604       } else {
605         Index = N;
606       }
607
608       Base = CurDAG->getTargetConstant(0, Index.getValueType());
609       return true;
610     }
611   }
612
613   return false;
614 }
615
616 /*!
617   \arg Op The ISD instruction operand
618   \arg N The address operand
619   \arg Base The base pointer operand
620   \arg Index The offset/index operand
621
622   If the address \a N can be expressed as an A-form or D-form address, returns
623   false.  Otherwise, creates two operands, Base and Index that will become the
624   (r)(r) X-form address.
625 */
626 bool
627 SPUDAGToDAGISel::SelectXFormAddr(SDValue Op, SDValue N, SDValue &Base,
628                                  SDValue &Index) {
629   if (!SelectAFormAddr(Op, N, Base, Index)
630       && !SelectDFormAddr(Op, N, Base, Index)) {
631     // If the address is neither A-form or D-form, punt and use an X-form
632     // address:
633     Base = N.getOperand(1);
634     Index = N.getOperand(0);
635     return true;
636   }
637
638   return false;
639 }
640
641 //! Convert the operand from a target-independent to a target-specific node
642 /*!
643  */
644 SDNode *
645 SPUDAGToDAGISel::Select(SDValue Op) {
646   SDNode *N = Op.getNode();
647   unsigned Opc = N->getOpcode();
648   int n_ops = -1;
649   unsigned NewOpc;
650   MVT OpVT = Op.getValueType();
651   SDValue Ops[8];
652
653   if (N->isMachineOpcode()) {
654     return NULL;   // Already selected.
655   } else if (Opc == ISD::FrameIndex) {
656     int FI = cast<FrameIndexSDNode>(N)->getIndex();
657     SDValue TFI = CurDAG->getTargetFrameIndex(FI, Op.getValueType());
658     SDValue Imm0 = CurDAG->getTargetConstant(0, Op.getValueType());
659
660     if (FI < 128) {
661       NewOpc = SPU::AIr32;
662       Ops[0] = TFI;
663       Ops[1] = Imm0;
664       n_ops = 2;
665     } else {
666       NewOpc = SPU::Ar32;
667       Ops[0] = CurDAG->getRegister(SPU::R1, Op.getValueType());
668       Ops[1] = SDValue(CurDAG->getTargetNode(SPU::ILAr32, Op.getValueType(),
669                                              TFI, Imm0), 0);
670       n_ops = 2;
671     }
672   } else if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND)
673              && OpVT == MVT::i64) {
674     SDValue Op0 = Op.getOperand(0);
675     MVT Op0VT = Op0.getValueType();
676     MVT Op0VecVT = MVT::getVectorVT(Op0VT, (128 / Op0VT.getSizeInBits()));
677     MVT OpVecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
678     SDValue shufMask;
679
680     switch (Op0VT.getSimpleVT()) {
681     default:
682       cerr << "CellSPU Select: Unhandled zero/any extend MVT\n";
683       abort();
684       /*NOTREACHED*/
685       break;
686     case MVT::i32:
687       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, MVT::v4i32,
688                              CurDAG->getConstant(0x80808080, MVT::i32),
689                              CurDAG->getConstant(0x00010203, MVT::i32),
690                              CurDAG->getConstant(0x80808080, MVT::i32),
691                              CurDAG->getConstant(0x08090a0b, MVT::i32));
692       break;
693
694     case MVT::i16:
695       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, MVT::v4i32,
696                              CurDAG->getConstant(0x80808080, MVT::i32),
697                              CurDAG->getConstant(0x80800203, MVT::i32),
698                              CurDAG->getConstant(0x80808080, MVT::i32),
699                              CurDAG->getConstant(0x80800a0b, MVT::i32));
700       break;
701
702     case MVT::i8:
703       shufMask = CurDAG->getNode(ISD::BUILD_VECTOR, MVT::v4i32,
704                              CurDAG->getConstant(0x80808080, MVT::i32),
705                              CurDAG->getConstant(0x80808003, MVT::i32),
706                              CurDAG->getConstant(0x80808080, MVT::i32),
707                              CurDAG->getConstant(0x8080800b, MVT::i32));
708       break;
709     }
710
711     SDNode *shufMaskLoad = emitBuildVector(shufMask);
712     SDNode *PromoteScalar =
713             SelectCode(CurDAG->getNode(SPUISD::PREFSLOT2VEC, Op0VecVT, Op0));
714
715     SDValue zextShuffle =
716             CurDAG->getNode(SPUISD::SHUFB, OpVecVT,
717                                        SDValue(PromoteScalar, 0),
718                                        SDValue(PromoteScalar, 0),
719                                        SDValue(shufMaskLoad, 0));
720
721     // N.B.: BIT_CONVERT replaces and updates the zextShuffle node, so we
722     // re-use it in the VEC2PREFSLOT selection without needing to explicitly
723     // call SelectCode (it's already done for us.)
724     SelectCode(CurDAG->getNode(ISD::BIT_CONVERT, OpVecVT, zextShuffle));
725     return SelectCode(CurDAG->getNode(SPUISD::VEC2PREFSLOT, OpVT,
726                                       zextShuffle));
727   } else if (Opc == ISD::ADD && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
728     SDNode *CGLoad =
729             emitBuildVector(SPU::getCarryGenerateShufMask(*CurDAG));
730
731     return SelectCode(CurDAG->getNode(SPUISD::ADD64_MARKER, OpVT,
732                                       Op.getOperand(0), Op.getOperand(1),
733                                       SDValue(CGLoad, 0)));
734   } else if (Opc == ISD::SUB && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
735     SDNode *CGLoad =
736             emitBuildVector(SPU::getBorrowGenerateShufMask(*CurDAG));
737
738     return SelectCode(CurDAG->getNode(SPUISD::SUB64_MARKER, OpVT,
739                                       Op.getOperand(0), Op.getOperand(1),
740                                       SDValue(CGLoad, 0)));
741   } else if (Opc == ISD::MUL && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
742     SDNode *CGLoad =
743             emitBuildVector(SPU::getCarryGenerateShufMask(*CurDAG));
744
745     return SelectCode(CurDAG->getNode(SPUISD::MUL64_MARKER, OpVT,
746                                       Op.getOperand(0), Op.getOperand(1),
747                                       SDValue(CGLoad, 0)));
748   } else if (Opc == ISD::SHL) {
749     if (OpVT == MVT::i64) {
750       return SelectSHLi64(Op, OpVT);
751     }
752   } else if (Opc == ISD::SRL) {
753     if (OpVT == MVT::i64) {
754       return SelectSRLi64(Op, OpVT);
755     }
756   } else if (Opc == ISD::SRA) {
757     if (OpVT == MVT::i64) {
758       return SelectSRAi64(Op, OpVT);
759     }
760   } else if (Opc == SPUISD::LDRESULT) {
761     // Custom select instructions for LDRESULT
762     MVT VT = N->getValueType(0);
763     SDValue Arg = N->getOperand(0);
764     SDValue Chain = N->getOperand(1);
765     SDNode *Result;
766     const valtype_map_s *vtm = getValueTypeMapEntry(VT);
767
768     if (vtm->ldresult_ins == 0) {
769       cerr << "LDRESULT for unsupported type: "
770            << VT.getMVTString()
771            << "\n";
772       abort();
773     }
774
775     Opc = vtm->ldresult_ins;
776     if (vtm->ldresult_imm) {
777       SDValue Zero = CurDAG->getTargetConstant(0, VT);
778
779       Result = CurDAG->getTargetNode(Opc, VT, MVT::Other, Arg, Zero, Chain);
780     } else {
781       Result = CurDAG->getTargetNode(Opc, VT, MVT::Other, Arg, Arg, Chain);
782     }
783
784     return Result;
785   } else if (Opc == SPUISD::IndirectAddr) {
786     // Look at the operands: SelectCode() will catch the cases that aren't
787     // specifically handled here.
788     //
789     // SPUInstrInfo catches the following patterns:
790     // (SPUindirect (SPUhi ...), (SPUlo ...))
791     // (SPUindirect $sp, imm)
792     MVT VT = Op.getValueType();
793     SDValue Op0 = N->getOperand(0);
794     SDValue Op1 = N->getOperand(1);
795     RegisterSDNode *RN;
796
797     if ((Op0.getOpcode() != SPUISD::Hi && Op1.getOpcode() != SPUISD::Lo)
798         || (Op0.getOpcode() == ISD::Register
799             && ((RN = dyn_cast<RegisterSDNode>(Op0.getNode())) != 0
800                 && RN->getReg() != SPU::R1))) {
801       NewOpc = SPU::Ar32;
802       if (Op1.getOpcode() == ISD::Constant) {
803         ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
804         Op1 = CurDAG->getTargetConstant(CN->getSExtValue(), VT);
805         NewOpc = (isI32IntS10Immediate(CN) ? SPU::AIr32 : SPU::Ar32);
806       }
807       Ops[0] = Op0;
808       Ops[1] = Op1;
809       n_ops = 2;
810     }
811   }
812
813   if (n_ops > 0) {
814     if (N->hasOneUse())
815       return CurDAG->SelectNodeTo(N, NewOpc, OpVT, Ops, n_ops);
816     else
817       return CurDAG->getTargetNode(NewOpc, OpVT, Ops, n_ops);
818   } else
819     return SelectCode(Op);
820 }
821
822 /*!
823  * Emit the instruction sequence for i64 left shifts. The basic algorithm
824  * is to fill the bottom two word slots with zeros so that zeros are shifted
825  * in as the entire quadword is shifted left.
826  *
827  * \note This code could also be used to implement v2i64 shl.
828  *
829  * @param Op The shl operand
830  * @param OpVT Op's machine value value type (doesn't need to be passed, but
831  * makes life easier.)
832  * @return The SDNode with the entire instruction sequence
833  */
834 SDNode *
835 SPUDAGToDAGISel::SelectSHLi64(SDValue &Op, MVT OpVT) {
836   SDValue Op0 = Op.getOperand(0);
837   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
838   SDValue ShiftAmt = Op.getOperand(1);
839   MVT ShiftAmtVT = ShiftAmt.getValueType();
840   SDNode *VecOp0, *SelMask, *ZeroFill, *Shift = 0;
841   SDValue SelMaskVal;
842
843   VecOp0 = CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op0);
844   SelMaskVal = CurDAG->getTargetConstant(0xff00ULL, MVT::i16);
845   SelMask = CurDAG->getTargetNode(SPU::FSMBIv2i64, VecVT, SelMaskVal);
846   ZeroFill = CurDAG->getTargetNode(SPU::ILv2i64, VecVT,
847                                    CurDAG->getTargetConstant(0, OpVT));
848   VecOp0 = CurDAG->getTargetNode(SPU::SELBv2i64, VecVT,
849                                  SDValue(ZeroFill, 0),
850                                  SDValue(VecOp0, 0),
851                                  SDValue(SelMask, 0));
852
853   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
854     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
855     unsigned bits = unsigned(CN->getZExtValue()) & 7;
856
857     if (bytes > 0) {
858       Shift =
859         CurDAG->getTargetNode(SPU::SHLQBYIv2i64, VecVT,
860                               SDValue(VecOp0, 0),
861                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
862     }
863
864     if (bits > 0) {
865       Shift =
866         CurDAG->getTargetNode(SPU::SHLQBIIv2i64, VecVT,
867                               SDValue((Shift != 0 ? Shift : VecOp0), 0),
868                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
869     }
870   } else {
871     SDNode *Bytes =
872       CurDAG->getTargetNode(SPU::ROTMIr32, ShiftAmtVT,
873                             ShiftAmt,
874                             CurDAG->getTargetConstant(3, ShiftAmtVT));
875     SDNode *Bits =
876       CurDAG->getTargetNode(SPU::ANDIr32, ShiftAmtVT,
877                             ShiftAmt,
878                             CurDAG->getTargetConstant(7, ShiftAmtVT));
879     Shift =
880       CurDAG->getTargetNode(SPU::SHLQBYv2i64, VecVT,
881                             SDValue(VecOp0, 0), SDValue(Bytes, 0));
882     Shift =
883       CurDAG->getTargetNode(SPU::SHLQBIv2i64, VecVT,
884                             SDValue(Shift, 0), SDValue(Bits, 0));
885   }
886
887   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
888 }
889
890 /*!
891  * Emit the instruction sequence for i64 logical right shifts.
892  *
893  * @param Op The shl operand
894  * @param OpVT Op's machine value value type (doesn't need to be passed, but
895  * makes life easier.)
896  * @return The SDNode with the entire instruction sequence
897  */
898 SDNode *
899 SPUDAGToDAGISel::SelectSRLi64(SDValue &Op, MVT OpVT) {
900   SDValue Op0 = Op.getOperand(0);
901   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
902   SDValue ShiftAmt = Op.getOperand(1);
903   MVT ShiftAmtVT = ShiftAmt.getValueType();
904   SDNode *VecOp0, *Shift = 0;
905
906   VecOp0 = CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op0);
907
908   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
909     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
910     unsigned bits = unsigned(CN->getZExtValue()) & 7;
911
912     if (bytes > 0) {
913       Shift =
914         CurDAG->getTargetNode(SPU::ROTQMBYIv2i64, VecVT,
915                               SDValue(VecOp0, 0),
916                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
917     }
918
919     if (bits > 0) {
920       Shift =
921         CurDAG->getTargetNode(SPU::ROTQMBIIv2i64, VecVT,
922                               SDValue((Shift != 0 ? Shift : VecOp0), 0),
923                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
924     }
925   } else {
926     SDNode *Bytes =
927       CurDAG->getTargetNode(SPU::ROTMIr32, ShiftAmtVT,
928                             ShiftAmt,
929                             CurDAG->getTargetConstant(3, ShiftAmtVT));
930     SDNode *Bits =
931       CurDAG->getTargetNode(SPU::ANDIr32, ShiftAmtVT,
932                             ShiftAmt,
933                             CurDAG->getTargetConstant(7, ShiftAmtVT));
934
935     // Ensure that the shift amounts are negated!
936     Bytes = CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
937                                   SDValue(Bytes, 0),
938                                   CurDAG->getTargetConstant(0, ShiftAmtVT));
939
940     Bits = CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
941                                  SDValue(Bits, 0),
942                                  CurDAG->getTargetConstant(0, ShiftAmtVT));
943
944     Shift =
945       CurDAG->getTargetNode(SPU::ROTQMBYv2i64, VecVT,
946                             SDValue(VecOp0, 0), SDValue(Bytes, 0));
947     Shift =
948       CurDAG->getTargetNode(SPU::ROTQMBIv2i64, VecVT,
949                             SDValue(Shift, 0), SDValue(Bits, 0));
950   }
951
952   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
953 }
954
955 /*!
956  * Emit the instruction sequence for i64 arithmetic right shifts.
957  *
958  * @param Op The shl operand
959  * @param OpVT Op's machine value value type (doesn't need to be passed, but
960  * makes life easier.)
961  * @return The SDNode with the entire instruction sequence
962  */
963 SDNode *
964 SPUDAGToDAGISel::SelectSRAi64(SDValue &Op, MVT OpVT) {
965   // Promote Op0 to vector
966   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
967   SDValue ShiftAmt = Op.getOperand(1);
968   MVT ShiftAmtVT = ShiftAmt.getValueType();
969
970   SDNode *VecOp0 =
971     CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op.getOperand(0));
972
973   SDValue SignRotAmt = CurDAG->getTargetConstant(31, ShiftAmtVT);
974   SDNode *SignRot =
975     CurDAG->getTargetNode(SPU::ROTMAIv2i64_i32, MVT::v2i64,
976                           SDValue(VecOp0, 0), SignRotAmt);
977   SDNode *UpperHalfSign =
978     CurDAG->getTargetNode(SPU::ORi32_v4i32, MVT::i32, SDValue(SignRot, 0));
979
980   SDNode *UpperHalfSignMask =
981     CurDAG->getTargetNode(SPU::FSM64r32, VecVT, SDValue(UpperHalfSign, 0));
982   SDNode *UpperLowerMask =
983     CurDAG->getTargetNode(SPU::FSMBIv2i64, VecVT,
984                           CurDAG->getTargetConstant(0xff00ULL, MVT::i16));
985   SDNode *UpperLowerSelect =
986     CurDAG->getTargetNode(SPU::SELBv2i64, VecVT,
987                           SDValue(UpperHalfSignMask, 0),
988                           SDValue(VecOp0, 0),
989                           SDValue(UpperLowerMask, 0));
990
991   SDNode *Shift = 0;
992
993   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
994     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
995     unsigned bits = unsigned(CN->getZExtValue()) & 7;
996
997     if (bytes > 0) {
998       bytes = 31 - bytes;
999       Shift =
1000         CurDAG->getTargetNode(SPU::ROTQBYIv2i64, VecVT,
1001                               SDValue(UpperLowerSelect, 0),
1002                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
1003     }
1004
1005     if (bits > 0) {
1006       bits = 8 - bits;
1007       Shift =
1008         CurDAG->getTargetNode(SPU::ROTQBIIv2i64, VecVT,
1009                               SDValue((Shift != 0 ? Shift : UpperLowerSelect), 0),
1010                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
1011     }
1012   } else {
1013     SDNode *NegShift =
1014       CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
1015                             ShiftAmt, CurDAG->getTargetConstant(0, ShiftAmtVT));
1016
1017     Shift =
1018       CurDAG->getTargetNode(SPU::ROTQBYBIv2i64_r32, VecVT,
1019                             SDValue(UpperLowerSelect, 0), SDValue(NegShift, 0));
1020     Shift =
1021       CurDAG->getTargetNode(SPU::ROTQBIv2i64, VecVT,
1022                             SDValue(Shift, 0), SDValue(NegShift, 0));
1023   }
1024
1025   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
1026 }
1027
1028 /// createSPUISelDag - This pass converts a legalized DAG into a
1029 /// SPU-specific DAG, ready for instruction scheduling.
1030 ///
1031 FunctionPass *llvm::createSPUISelDag(SPUTargetMachine &TM) {
1032   return new SPUDAGToDAGISel(TM);
1033 }