CellSPU:
[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),
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 ScheduleHazardRecognizer *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::ADD && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
749     SDNode *CGLoad =
750             emitBuildVector(SPU::getCarryGenerateShufMask(*CurDAG));
751
752     return SelectCode(CurDAG->getNode(SPUISD::ADD64_MARKER, OpVT,
753                                       Op.getOperand(0), Op.getOperand(1),
754                                       SDValue(CGLoad, 0)));
755   } else if (Opc == ISD::SUB && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
756     SDNode *CGLoad =
757             emitBuildVector(SPU::getBorrowGenerateShufMask(*CurDAG));
758
759     return SelectCode(CurDAG->getNode(SPUISD::SUB64_MARKER, OpVT,
760                                       Op.getOperand(0), Op.getOperand(1),
761                                       SDValue(CGLoad, 0)));
762   } else if (Opc == ISD::MUL && (OpVT == MVT::i64 || OpVT == MVT::v2i64)) {
763     SDNode *CGLoad =
764             emitBuildVector(SPU::getCarryGenerateShufMask(*CurDAG));
765
766     return SelectCode(CurDAG->getNode(SPUISD::MUL64_MARKER, OpVT,
767                                       Op.getOperand(0), Op.getOperand(1),
768                                       SDValue(CGLoad, 0)));
769   } else if (Opc == ISD::SHL) {
770     if (OpVT == MVT::i64) {
771       return SelectSHLi64(Op, OpVT);
772     }
773   } else if (Opc == ISD::SRL) {
774     if (OpVT == MVT::i64) {
775       return SelectSRLi64(Op, OpVT);
776     }
777   } else if (Opc == ISD::SRA) {
778     if (OpVT == MVT::i64) {
779       return SelectSRAi64(Op, OpVT);
780     }
781   } else if (Opc == SPUISD::LDRESULT) {
782     // Custom select instructions for LDRESULT
783     MVT VT = N->getValueType(0);
784     SDValue Arg = N->getOperand(0);
785     SDValue Chain = N->getOperand(1);
786     SDNode *Result;
787     const valtype_map_s *vtm = getValueTypeMapEntry(VT);
788
789     if (vtm->ldresult_ins == 0) {
790       cerr << "LDRESULT for unsupported type: "
791            << VT.getMVTString()
792            << "\n";
793       abort();
794     }
795
796     Opc = vtm->ldresult_ins;
797     if (vtm->ldresult_imm) {
798       SDValue Zero = CurDAG->getTargetConstant(0, VT);
799
800       Result = CurDAG->getTargetNode(Opc, VT, MVT::Other, Arg, Zero, Chain);
801     } else {
802       Result = CurDAG->getTargetNode(Opc, VT, MVT::Other, Arg, Arg, Chain);
803     }
804
805     return Result;
806   } else if (Opc == SPUISD::IndirectAddr) {
807     // Look at the operands: SelectCode() will catch the cases that aren't
808     // specifically handled here.
809     //
810     // SPUInstrInfo catches the following patterns:
811     // (SPUindirect (SPUhi ...), (SPUlo ...))
812     // (SPUindirect $sp, imm)
813     MVT VT = Op.getValueType();
814     SDValue Op0 = N->getOperand(0);
815     SDValue Op1 = N->getOperand(1);
816     RegisterSDNode *RN;
817
818     if ((Op0.getOpcode() != SPUISD::Hi && Op1.getOpcode() != SPUISD::Lo)
819         || (Op0.getOpcode() == ISD::Register
820             && ((RN = dyn_cast<RegisterSDNode>(Op0.getNode())) != 0
821                 && RN->getReg() != SPU::R1))) {
822       NewOpc = SPU::Ar32;
823       if (Op1.getOpcode() == ISD::Constant) {
824         ConstantSDNode *CN = cast<ConstantSDNode>(Op1);
825         Op1 = CurDAG->getTargetConstant(CN->getSExtValue(), VT);
826         NewOpc = (isI32IntS10Immediate(CN) ? SPU::AIr32 : SPU::Ar32);
827       }
828       Ops[0] = Op0;
829       Ops[1] = Op1;
830       n_ops = 2;
831     }
832   }
833
834   if (n_ops > 0) {
835     if (N->hasOneUse())
836       return CurDAG->SelectNodeTo(N, NewOpc, OpVT, Ops, n_ops);
837     else
838       return CurDAG->getTargetNode(NewOpc, OpVT, Ops, n_ops);
839   } else
840     return SelectCode(Op);
841 }
842
843 /*!
844  * Emit the instruction sequence for i64 left shifts. The basic algorithm
845  * is to fill the bottom two word slots with zeros so that zeros are shifted
846  * in as the entire quadword is shifted left.
847  *
848  * \note This code could also be used to implement v2i64 shl.
849  *
850  * @param Op The shl operand
851  * @param OpVT Op's machine value value type (doesn't need to be passed, but
852  * makes life easier.)
853  * @return The SDNode with the entire instruction sequence
854  */
855 SDNode *
856 SPUDAGToDAGISel::SelectSHLi64(SDValue &Op, MVT OpVT) {
857   SDValue Op0 = Op.getOperand(0);
858   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
859   SDValue ShiftAmt = Op.getOperand(1);
860   MVT ShiftAmtVT = ShiftAmt.getValueType();
861   SDNode *VecOp0, *SelMask, *ZeroFill, *Shift = 0;
862   SDValue SelMaskVal;
863
864   VecOp0 = CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op0);
865   SelMaskVal = CurDAG->getTargetConstant(0xff00ULL, MVT::i16);
866   SelMask = CurDAG->getTargetNode(SPU::FSMBIv2i64, VecVT, SelMaskVal);
867   ZeroFill = CurDAG->getTargetNode(SPU::ILv2i64, VecVT,
868                                    CurDAG->getTargetConstant(0, OpVT));
869   VecOp0 = CurDAG->getTargetNode(SPU::SELBv2i64, VecVT,
870                                  SDValue(ZeroFill, 0),
871                                  SDValue(VecOp0, 0),
872                                  SDValue(SelMask, 0));
873
874   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
875     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
876     unsigned bits = unsigned(CN->getZExtValue()) & 7;
877
878     if (bytes > 0) {
879       Shift =
880         CurDAG->getTargetNode(SPU::SHLQBYIv2i64, VecVT,
881                               SDValue(VecOp0, 0),
882                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
883     }
884
885     if (bits > 0) {
886       Shift =
887         CurDAG->getTargetNode(SPU::SHLQBIIv2i64, VecVT,
888                               SDValue((Shift != 0 ? Shift : VecOp0), 0),
889                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
890     }
891   } else {
892     SDNode *Bytes =
893       CurDAG->getTargetNode(SPU::ROTMIr32, ShiftAmtVT,
894                             ShiftAmt,
895                             CurDAG->getTargetConstant(3, ShiftAmtVT));
896     SDNode *Bits =
897       CurDAG->getTargetNode(SPU::ANDIr32, ShiftAmtVT,
898                             ShiftAmt,
899                             CurDAG->getTargetConstant(7, ShiftAmtVT));
900     Shift =
901       CurDAG->getTargetNode(SPU::SHLQBYv2i64, VecVT,
902                             SDValue(VecOp0, 0), SDValue(Bytes, 0));
903     Shift =
904       CurDAG->getTargetNode(SPU::SHLQBIv2i64, VecVT,
905                             SDValue(Shift, 0), SDValue(Bits, 0));
906   }
907
908   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
909 }
910
911 /*!
912  * Emit the instruction sequence for i64 logical right shifts.
913  *
914  * @param Op The shl operand
915  * @param OpVT Op's machine value value type (doesn't need to be passed, but
916  * makes life easier.)
917  * @return The SDNode with the entire instruction sequence
918  */
919 SDNode *
920 SPUDAGToDAGISel::SelectSRLi64(SDValue &Op, MVT OpVT) {
921   SDValue Op0 = Op.getOperand(0);
922   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
923   SDValue ShiftAmt = Op.getOperand(1);
924   MVT ShiftAmtVT = ShiftAmt.getValueType();
925   SDNode *VecOp0, *Shift = 0;
926
927   VecOp0 = CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op0);
928
929   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
930     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
931     unsigned bits = unsigned(CN->getZExtValue()) & 7;
932
933     if (bytes > 0) {
934       Shift =
935         CurDAG->getTargetNode(SPU::ROTQMBYIv2i64, VecVT,
936                               SDValue(VecOp0, 0),
937                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
938     }
939
940     if (bits > 0) {
941       Shift =
942         CurDAG->getTargetNode(SPU::ROTQMBIIv2i64, VecVT,
943                               SDValue((Shift != 0 ? Shift : VecOp0), 0),
944                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
945     }
946   } else {
947     SDNode *Bytes =
948       CurDAG->getTargetNode(SPU::ROTMIr32, ShiftAmtVT,
949                             ShiftAmt,
950                             CurDAG->getTargetConstant(3, ShiftAmtVT));
951     SDNode *Bits =
952       CurDAG->getTargetNode(SPU::ANDIr32, ShiftAmtVT,
953                             ShiftAmt,
954                             CurDAG->getTargetConstant(7, ShiftAmtVT));
955
956     // Ensure that the shift amounts are negated!
957     Bytes = CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
958                                   SDValue(Bytes, 0),
959                                   CurDAG->getTargetConstant(0, ShiftAmtVT));
960
961     Bits = CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
962                                  SDValue(Bits, 0),
963                                  CurDAG->getTargetConstant(0, ShiftAmtVT));
964
965     Shift =
966       CurDAG->getTargetNode(SPU::ROTQMBYv2i64, VecVT,
967                             SDValue(VecOp0, 0), SDValue(Bytes, 0));
968     Shift =
969       CurDAG->getTargetNode(SPU::ROTQMBIv2i64, VecVT,
970                             SDValue(Shift, 0), SDValue(Bits, 0));
971   }
972
973   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
974 }
975
976 /*!
977  * Emit the instruction sequence for i64 arithmetic right shifts.
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::SelectSRAi64(SDValue &Op, MVT OpVT) {
986   // Promote Op0 to vector
987   MVT VecVT = MVT::getVectorVT(OpVT, (128 / OpVT.getSizeInBits()));
988   SDValue ShiftAmt = Op.getOperand(1);
989   MVT ShiftAmtVT = ShiftAmt.getValueType();
990
991   SDNode *VecOp0 =
992     CurDAG->getTargetNode(SPU::ORv2i64_i64, VecVT, Op.getOperand(0));
993
994   SDValue SignRotAmt = CurDAG->getTargetConstant(31, ShiftAmtVT);
995   SDNode *SignRot =
996     CurDAG->getTargetNode(SPU::ROTMAIv2i64_i32, MVT::v2i64,
997                           SDValue(VecOp0, 0), SignRotAmt);
998   SDNode *UpperHalfSign =
999     CurDAG->getTargetNode(SPU::ORi32_v4i32, MVT::i32, SDValue(SignRot, 0));
1000
1001   SDNode *UpperHalfSignMask =
1002     CurDAG->getTargetNode(SPU::FSM64r32, VecVT, SDValue(UpperHalfSign, 0));
1003   SDNode *UpperLowerMask =
1004     CurDAG->getTargetNode(SPU::FSMBIv2i64, VecVT,
1005                           CurDAG->getTargetConstant(0xff00ULL, MVT::i16));
1006   SDNode *UpperLowerSelect =
1007     CurDAG->getTargetNode(SPU::SELBv2i64, VecVT,
1008                           SDValue(UpperHalfSignMask, 0),
1009                           SDValue(VecOp0, 0),
1010                           SDValue(UpperLowerMask, 0));
1011
1012   SDNode *Shift = 0;
1013
1014   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(ShiftAmt)) {
1015     unsigned bytes = unsigned(CN->getZExtValue()) >> 3;
1016     unsigned bits = unsigned(CN->getZExtValue()) & 7;
1017
1018     if (bytes > 0) {
1019       bytes = 31 - bytes;
1020       Shift =
1021         CurDAG->getTargetNode(SPU::ROTQBYIv2i64, VecVT,
1022                               SDValue(UpperLowerSelect, 0),
1023                               CurDAG->getTargetConstant(bytes, ShiftAmtVT));
1024     }
1025
1026     if (bits > 0) {
1027       bits = 8 - bits;
1028       Shift =
1029         CurDAG->getTargetNode(SPU::ROTQBIIv2i64, VecVT,
1030                               SDValue((Shift != 0 ? Shift : UpperLowerSelect), 0),
1031                               CurDAG->getTargetConstant(bits, ShiftAmtVT));
1032     }
1033   } else {
1034     SDNode *NegShift =
1035       CurDAG->getTargetNode(SPU::SFIr32, ShiftAmtVT,
1036                             ShiftAmt, CurDAG->getTargetConstant(0, ShiftAmtVT));
1037
1038     Shift =
1039       CurDAG->getTargetNode(SPU::ROTQBYBIv2i64_r32, VecVT,
1040                             SDValue(UpperLowerSelect, 0), SDValue(NegShift, 0));
1041     Shift =
1042       CurDAG->getTargetNode(SPU::ROTQBIv2i64, VecVT,
1043                             SDValue(Shift, 0), SDValue(NegShift, 0));
1044   }
1045
1046   return CurDAG->getTargetNode(SPU::ORi64_v2i64, OpVT, SDValue(Shift, 0));
1047 }
1048
1049 /// createSPUISelDag - This pass converts a legalized DAG into a
1050 /// SPU-specific DAG, ready for instruction scheduling.
1051 ///
1052 FunctionPass *llvm::createSPUISelDag(SPUTargetMachine &TM) {
1053   return new SPUDAGToDAGISel(TM);
1054 }