[mips][mips64r6] Replace m[tf]hi, m[tf]lo, mult, multu, dmult, dmultu, div, ddiv...
[oota-llvm.git] / lib / Target / Mips / MipsSEISelLowering.cpp
1 //===-- MipsSEISelLowering.cpp - MipsSE DAG Lowering Interface --*- C++ -*-===//
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 // Subclass of MipsTargetLowering specialized for mips32/64.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "MipsSEISelLowering.h"
14 #include "MipsRegisterInfo.h"
15 #include "MipsTargetMachine.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23
24 using namespace llvm;
25
26 #define DEBUG_TYPE "mips-isel"
27
28 static cl::opt<bool>
29 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
30                     cl::desc("MIPS: Enable tail calls."), cl::init(false));
31
32 static cl::opt<bool> NoDPLoadStore("mno-ldc1-sdc1", cl::init(false),
33                                    cl::desc("Expand double precision loads and "
34                                             "stores to their single precision "
35                                             "counterparts"));
36
37 MipsSETargetLowering::MipsSETargetLowering(MipsTargetMachine &TM)
38   : MipsTargetLowering(TM) {
39   // Set up the register classes
40   addRegisterClass(MVT::i32, &Mips::GPR32RegClass);
41
42   if (isGP64bit())
43     addRegisterClass(MVT::i64, &Mips::GPR64RegClass);
44
45   if (Subtarget->hasDSP() || Subtarget->hasMSA()) {
46     // Expand all truncating stores and extending loads.
47     unsigned FirstVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
48     unsigned LastVT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
49
50     for (unsigned VT0 = FirstVT; VT0 <= LastVT; ++VT0) {
51       for (unsigned VT1 = FirstVT; VT1 <= LastVT; ++VT1)
52         setTruncStoreAction((MVT::SimpleValueType)VT0,
53                             (MVT::SimpleValueType)VT1, Expand);
54
55       setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
56       setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT0, Expand);
57       setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT0, Expand);
58     }
59   }
60
61   if (Subtarget->hasDSP()) {
62     MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
63
64     for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
65       addRegisterClass(VecTys[i], &Mips::DSPRRegClass);
66
67       // Expand all builtin opcodes.
68       for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
69         setOperationAction(Opc, VecTys[i], Expand);
70
71       setOperationAction(ISD::ADD, VecTys[i], Legal);
72       setOperationAction(ISD::SUB, VecTys[i], Legal);
73       setOperationAction(ISD::LOAD, VecTys[i], Legal);
74       setOperationAction(ISD::STORE, VecTys[i], Legal);
75       setOperationAction(ISD::BITCAST, VecTys[i], Legal);
76     }
77
78     setTargetDAGCombine(ISD::SHL);
79     setTargetDAGCombine(ISD::SRA);
80     setTargetDAGCombine(ISD::SRL);
81     setTargetDAGCombine(ISD::SETCC);
82     setTargetDAGCombine(ISD::VSELECT);
83   }
84
85   if (Subtarget->hasDSPR2())
86     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
87
88   if (Subtarget->hasMSA()) {
89     addMSAIntType(MVT::v16i8, &Mips::MSA128BRegClass);
90     addMSAIntType(MVT::v8i16, &Mips::MSA128HRegClass);
91     addMSAIntType(MVT::v4i32, &Mips::MSA128WRegClass);
92     addMSAIntType(MVT::v2i64, &Mips::MSA128DRegClass);
93     addMSAFloatType(MVT::v8f16, &Mips::MSA128HRegClass);
94     addMSAFloatType(MVT::v4f32, &Mips::MSA128WRegClass);
95     addMSAFloatType(MVT::v2f64, &Mips::MSA128DRegClass);
96
97     setTargetDAGCombine(ISD::AND);
98     setTargetDAGCombine(ISD::OR);
99     setTargetDAGCombine(ISD::SRA);
100     setTargetDAGCombine(ISD::VSELECT);
101     setTargetDAGCombine(ISD::XOR);
102   }
103
104   if (!Subtarget->mipsSEUsesSoftFloat()) {
105     addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
106
107     // When dealing with single precision only, use libcalls
108     if (!Subtarget->isSingleFloat()) {
109       if (Subtarget->isFP64bit())
110         addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
111       else
112         addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
113     }
114   }
115
116   setOperationAction(ISD::SMUL_LOHI,          MVT::i32, Custom);
117   setOperationAction(ISD::UMUL_LOHI,          MVT::i32, Custom);
118   setOperationAction(ISD::MULHS,              MVT::i32, Custom);
119   setOperationAction(ISD::MULHU,              MVT::i32, Custom);
120
121   if (Subtarget->hasCnMips())
122     setOperationAction(ISD::MUL,              MVT::i64, Legal);
123   else if (isGP64bit())
124     setOperationAction(ISD::MUL,              MVT::i64, Custom);
125
126   if (isGP64bit()) {
127     setOperationAction(ISD::MULHS,            MVT::i64, Custom);
128     setOperationAction(ISD::MULHU,            MVT::i64, Custom);
129   }
130
131   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
132   setOperationAction(ISD::INTRINSIC_W_CHAIN,  MVT::i64, Custom);
133
134   setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
135   setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
136   setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
137   setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
138   setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
139   setOperationAction(ISD::LOAD,               MVT::i32, Custom);
140   setOperationAction(ISD::STORE,              MVT::i32, Custom);
141
142   setTargetDAGCombine(ISD::ADDE);
143   setTargetDAGCombine(ISD::SUBE);
144   setTargetDAGCombine(ISD::MUL);
145
146   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
147   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
148   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
149
150   if (NoDPLoadStore) {
151     setOperationAction(ISD::LOAD, MVT::f64, Custom);
152     setOperationAction(ISD::STORE, MVT::f64, Custom);
153   }
154
155   if (Subtarget->hasMips32r6()) {
156     // MIPS32r6 replaces the accumulator-based multiplies with a three register
157     // instruction
158     setOperationAction(ISD::MUL, MVT::i32, Legal);
159     setOperationAction(ISD::MULHS, MVT::i32, Legal);
160     setOperationAction(ISD::MULHU, MVT::i32, Legal);
161
162     // MIPS32r6 replaces the accumulator-based division/remainder with separate
163     // three register division and remainder instructions.
164     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
165     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
166     setOperationAction(ISD::SDIV, MVT::i32, Legal);
167     setOperationAction(ISD::UDIV, MVT::i32, Legal);
168     setOperationAction(ISD::SREM, MVT::i32, Legal);
169     setOperationAction(ISD::UREM, MVT::i32, Legal);
170   }
171
172   if (Subtarget->hasMips64r6()) {
173     // MIPS64r6 replaces the accumulator-based multiplies with a three register
174     // instruction
175     setOperationAction(ISD::MUL, MVT::i64, Legal);
176     setOperationAction(ISD::MULHS, MVT::i64, Legal);
177     setOperationAction(ISD::MULHU, MVT::i64, Legal);
178
179     // MIPS32r6 replaces the accumulator-based division/remainder with separate
180     // three register division and remainder instructions.
181     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
182     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
183     setOperationAction(ISD::SDIV, MVT::i64, Legal);
184     setOperationAction(ISD::UDIV, MVT::i64, Legal);
185     setOperationAction(ISD::SREM, MVT::i64, Legal);
186     setOperationAction(ISD::UREM, MVT::i64, Legal);
187   }
188
189   computeRegisterProperties();
190 }
191
192 const MipsTargetLowering *
193 llvm::createMipsSETargetLowering(MipsTargetMachine &TM) {
194   return new MipsSETargetLowering(TM);
195 }
196
197 // Enable MSA support for the given integer type and Register class.
198 void MipsSETargetLowering::
199 addMSAIntType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
200   addRegisterClass(Ty, RC);
201
202   // Expand all builtin opcodes.
203   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
204     setOperationAction(Opc, Ty, Expand);
205
206   setOperationAction(ISD::BITCAST, Ty, Legal);
207   setOperationAction(ISD::LOAD, Ty, Legal);
208   setOperationAction(ISD::STORE, Ty, Legal);
209   setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Custom);
210   setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
211   setOperationAction(ISD::BUILD_VECTOR, Ty, Custom);
212
213   setOperationAction(ISD::ADD, Ty, Legal);
214   setOperationAction(ISD::AND, Ty, Legal);
215   setOperationAction(ISD::CTLZ, Ty, Legal);
216   setOperationAction(ISD::CTPOP, Ty, Legal);
217   setOperationAction(ISD::MUL, Ty, Legal);
218   setOperationAction(ISD::OR, Ty, Legal);
219   setOperationAction(ISD::SDIV, Ty, Legal);
220   setOperationAction(ISD::SREM, Ty, Legal);
221   setOperationAction(ISD::SHL, Ty, Legal);
222   setOperationAction(ISD::SRA, Ty, Legal);
223   setOperationAction(ISD::SRL, Ty, Legal);
224   setOperationAction(ISD::SUB, Ty, Legal);
225   setOperationAction(ISD::UDIV, Ty, Legal);
226   setOperationAction(ISD::UREM, Ty, Legal);
227   setOperationAction(ISD::VECTOR_SHUFFLE, Ty, Custom);
228   setOperationAction(ISD::VSELECT, Ty, Legal);
229   setOperationAction(ISD::XOR, Ty, Legal);
230
231   if (Ty == MVT::v4i32 || Ty == MVT::v2i64) {
232     setOperationAction(ISD::FP_TO_SINT, Ty, Legal);
233     setOperationAction(ISD::FP_TO_UINT, Ty, Legal);
234     setOperationAction(ISD::SINT_TO_FP, Ty, Legal);
235     setOperationAction(ISD::UINT_TO_FP, Ty, Legal);
236   }
237
238   setOperationAction(ISD::SETCC, Ty, Legal);
239   setCondCodeAction(ISD::SETNE, Ty, Expand);
240   setCondCodeAction(ISD::SETGE, Ty, Expand);
241   setCondCodeAction(ISD::SETGT, Ty, Expand);
242   setCondCodeAction(ISD::SETUGE, Ty, Expand);
243   setCondCodeAction(ISD::SETUGT, Ty, Expand);
244 }
245
246 // Enable MSA support for the given floating-point type and Register class.
247 void MipsSETargetLowering::
248 addMSAFloatType(MVT::SimpleValueType Ty, const TargetRegisterClass *RC) {
249   addRegisterClass(Ty, RC);
250
251   // Expand all builtin opcodes.
252   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
253     setOperationAction(Opc, Ty, Expand);
254
255   setOperationAction(ISD::LOAD, Ty, Legal);
256   setOperationAction(ISD::STORE, Ty, Legal);
257   setOperationAction(ISD::BITCAST, Ty, Legal);
258   setOperationAction(ISD::EXTRACT_VECTOR_ELT, Ty, Legal);
259   setOperationAction(ISD::INSERT_VECTOR_ELT, Ty, Legal);
260   setOperationAction(ISD::BUILD_VECTOR, Ty, Custom);
261
262   if (Ty != MVT::v8f16) {
263     setOperationAction(ISD::FABS,  Ty, Legal);
264     setOperationAction(ISD::FADD,  Ty, Legal);
265     setOperationAction(ISD::FDIV,  Ty, Legal);
266     setOperationAction(ISD::FEXP2, Ty, Legal);
267     setOperationAction(ISD::FLOG2, Ty, Legal);
268     setOperationAction(ISD::FMA,   Ty, Legal);
269     setOperationAction(ISD::FMUL,  Ty, Legal);
270     setOperationAction(ISD::FRINT, Ty, Legal);
271     setOperationAction(ISD::FSQRT, Ty, Legal);
272     setOperationAction(ISD::FSUB,  Ty, Legal);
273     setOperationAction(ISD::VSELECT, Ty, Legal);
274
275     setOperationAction(ISD::SETCC, Ty, Legal);
276     setCondCodeAction(ISD::SETOGE, Ty, Expand);
277     setCondCodeAction(ISD::SETOGT, Ty, Expand);
278     setCondCodeAction(ISD::SETUGE, Ty, Expand);
279     setCondCodeAction(ISD::SETUGT, Ty, Expand);
280     setCondCodeAction(ISD::SETGE,  Ty, Expand);
281     setCondCodeAction(ISD::SETGT,  Ty, Expand);
282   }
283 }
284
285 bool
286 MipsSETargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
287                                                     unsigned,
288                                                     bool *Fast) const {
289   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
290
291   if (Subtarget->systemSupportsUnalignedAccess()) {
292     // MIPS32r6/MIPS64r6 is required to support unaligned access. It's
293     // implementation defined whether this is handled by hardware, software, or
294     // a hybrid of the two but it's expected that most implementations will
295     // handle the majority of cases in hardware.
296     if (Fast)
297       *Fast = true;
298     return true;
299   }
300
301   switch (SVT) {
302   case MVT::i64:
303   case MVT::i32:
304     if (Fast)
305       *Fast = true;
306     return true;
307   default:
308     return false;
309   }
310 }
311
312 SDValue MipsSETargetLowering::LowerOperation(SDValue Op,
313                                              SelectionDAG &DAG) const {
314   switch(Op.getOpcode()) {
315   case ISD::LOAD:  return lowerLOAD(Op, DAG);
316   case ISD::STORE: return lowerSTORE(Op, DAG);
317   case ISD::SMUL_LOHI: return lowerMulDiv(Op, MipsISD::Mult, true, true, DAG);
318   case ISD::UMUL_LOHI: return lowerMulDiv(Op, MipsISD::Multu, true, true, DAG);
319   case ISD::MULHS:     return lowerMulDiv(Op, MipsISD::Mult, false, true, DAG);
320   case ISD::MULHU:     return lowerMulDiv(Op, MipsISD::Multu, false, true, DAG);
321   case ISD::MUL:       return lowerMulDiv(Op, MipsISD::Mult, true, false, DAG);
322   case ISD::SDIVREM:   return lowerMulDiv(Op, MipsISD::DivRem, true, true, DAG);
323   case ISD::UDIVREM:   return lowerMulDiv(Op, MipsISD::DivRemU, true, true,
324                                           DAG);
325   case ISD::INTRINSIC_WO_CHAIN: return lowerINTRINSIC_WO_CHAIN(Op, DAG);
326   case ISD::INTRINSIC_W_CHAIN:  return lowerINTRINSIC_W_CHAIN(Op, DAG);
327   case ISD::INTRINSIC_VOID:     return lowerINTRINSIC_VOID(Op, DAG);
328   case ISD::EXTRACT_VECTOR_ELT: return lowerEXTRACT_VECTOR_ELT(Op, DAG);
329   case ISD::BUILD_VECTOR:       return lowerBUILD_VECTOR(Op, DAG);
330   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, DAG);
331   }
332
333   return MipsTargetLowering::LowerOperation(Op, DAG);
334 }
335
336 // selectMADD -
337 // Transforms a subgraph in CurDAG if the following pattern is found:
338 //  (addc multLo, Lo0), (adde multHi, Hi0),
339 // where,
340 //  multHi/Lo: product of multiplication
341 //  Lo0: initial value of Lo register
342 //  Hi0: initial value of Hi register
343 // Return true if pattern matching was successful.
344 static bool selectMADD(SDNode *ADDENode, SelectionDAG *CurDAG) {
345   // ADDENode's second operand must be a flag output of an ADDC node in order
346   // for the matching to be successful.
347   SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
348
349   if (ADDCNode->getOpcode() != ISD::ADDC)
350     return false;
351
352   SDValue MultHi = ADDENode->getOperand(0);
353   SDValue MultLo = ADDCNode->getOperand(0);
354   SDNode *MultNode = MultHi.getNode();
355   unsigned MultOpc = MultHi.getOpcode();
356
357   // MultHi and MultLo must be generated by the same node,
358   if (MultLo.getNode() != MultNode)
359     return false;
360
361   // and it must be a multiplication.
362   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
363     return false;
364
365   // MultLo amd MultHi must be the first and second output of MultNode
366   // respectively.
367   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
368     return false;
369
370   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
371   // of the values of MultNode, in which case MultNode will be removed in later
372   // phases.
373   // If there exist users other than ADDENode or ADDCNode, this function returns
374   // here, which will result in MultNode being mapped to a single MULT
375   // instruction node rather than a pair of MULT and MADD instructions being
376   // produced.
377   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
378     return false;
379
380   SDLoc DL(ADDENode);
381
382   // Initialize accumulator.
383   SDValue ACCIn = CurDAG->getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
384                                   ADDCNode->getOperand(1),
385                                   ADDENode->getOperand(1));
386
387   // create MipsMAdd(u) node
388   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
389
390   SDValue MAdd = CurDAG->getNode(MultOpc, DL, MVT::Untyped,
391                                  MultNode->getOperand(0),// Factor 0
392                                  MultNode->getOperand(1),// Factor 1
393                                  ACCIn);
394
395   // replace uses of adde and addc here
396   if (!SDValue(ADDCNode, 0).use_empty()) {
397     SDValue LoOut = CurDAG->getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
398     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), LoOut);
399   }
400   if (!SDValue(ADDENode, 0).use_empty()) {
401     SDValue HiOut = CurDAG->getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
402     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), HiOut);
403   }
404
405   return true;
406 }
407
408 // selectMSUB -
409 // Transforms a subgraph in CurDAG if the following pattern is found:
410 //  (addc Lo0, multLo), (sube Hi0, multHi),
411 // where,
412 //  multHi/Lo: product of multiplication
413 //  Lo0: initial value of Lo register
414 //  Hi0: initial value of Hi register
415 // Return true if pattern matching was successful.
416 static bool selectMSUB(SDNode *SUBENode, SelectionDAG *CurDAG) {
417   // SUBENode's second operand must be a flag output of an SUBC node in order
418   // for the matching to be successful.
419   SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
420
421   if (SUBCNode->getOpcode() != ISD::SUBC)
422     return false;
423
424   SDValue MultHi = SUBENode->getOperand(1);
425   SDValue MultLo = SUBCNode->getOperand(1);
426   SDNode *MultNode = MultHi.getNode();
427   unsigned MultOpc = MultHi.getOpcode();
428
429   // MultHi and MultLo must be generated by the same node,
430   if (MultLo.getNode() != MultNode)
431     return false;
432
433   // and it must be a multiplication.
434   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
435     return false;
436
437   // MultLo amd MultHi must be the first and second output of MultNode
438   // respectively.
439   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
440     return false;
441
442   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
443   // of the values of MultNode, in which case MultNode will be removed in later
444   // phases.
445   // If there exist users other than SUBENode or SUBCNode, this function returns
446   // here, which will result in MultNode being mapped to a single MULT
447   // instruction node rather than a pair of MULT and MSUB instructions being
448   // produced.
449   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
450     return false;
451
452   SDLoc DL(SUBENode);
453
454   // Initialize accumulator.
455   SDValue ACCIn = CurDAG->getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
456                                   SUBCNode->getOperand(0),
457                                   SUBENode->getOperand(0));
458
459   // create MipsSub(u) node
460   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
461
462   SDValue MSub = CurDAG->getNode(MultOpc, DL, MVT::Glue,
463                                  MultNode->getOperand(0),// Factor 0
464                                  MultNode->getOperand(1),// Factor 1
465                                  ACCIn);
466
467   // replace uses of sube and subc here
468   if (!SDValue(SUBCNode, 0).use_empty()) {
469     SDValue LoOut = CurDAG->getNode(MipsISD::MFLO, DL, MVT::i32, MSub);
470     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), LoOut);
471   }
472   if (!SDValue(SUBENode, 0).use_empty()) {
473     SDValue HiOut = CurDAG->getNode(MipsISD::MFHI, DL, MVT::i32, MSub);
474     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), HiOut);
475   }
476
477   return true;
478 }
479
480 static SDValue performADDECombine(SDNode *N, SelectionDAG &DAG,
481                                   TargetLowering::DAGCombinerInfo &DCI,
482                                   const MipsSubtarget *Subtarget) {
483   if (DCI.isBeforeLegalize())
484     return SDValue();
485
486   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
487       selectMADD(N, &DAG))
488     return SDValue(N, 0);
489
490   return SDValue();
491 }
492
493 // Fold zero extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT
494 //
495 // Performs the following transformations:
496 // - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to zero extension if its
497 //   sign/zero-extension is completely overwritten by the new one performed by
498 //   the ISD::AND.
499 // - Removes redundant zero extensions performed by an ISD::AND.
500 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
501                                  TargetLowering::DAGCombinerInfo &DCI,
502                                  const MipsSubtarget *Subtarget) {
503   if (!Subtarget->hasMSA())
504     return SDValue();
505
506   SDValue Op0 = N->getOperand(0);
507   SDValue Op1 = N->getOperand(1);
508   unsigned Op0Opcode = Op0->getOpcode();
509
510   // (and (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d)
511   // where $d + 1 == 2^n and n == 32
512   // or    $d + 1 == 2^n and n <= 32 and ZExt
513   // -> (MipsVExtractZExt $a, $b, $c)
514   if (Op0Opcode == MipsISD::VEXTRACT_SEXT_ELT ||
515       Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT) {
516     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Op1);
517
518     if (!Mask)
519       return SDValue();
520
521     int32_t Log2IfPositive = (Mask->getAPIntValue() + 1).exactLogBase2();
522
523     if (Log2IfPositive <= 0)
524       return SDValue(); // Mask+1 is not a power of 2
525
526     SDValue Op0Op2 = Op0->getOperand(2);
527     EVT ExtendTy = cast<VTSDNode>(Op0Op2)->getVT();
528     unsigned ExtendTySize = ExtendTy.getSizeInBits();
529     unsigned Log2 = Log2IfPositive;
530
531     if ((Op0Opcode == MipsISD::VEXTRACT_ZEXT_ELT && Log2 >= ExtendTySize) ||
532         Log2 == ExtendTySize) {
533       SDValue Ops[] = { Op0->getOperand(0), Op0->getOperand(1), Op0Op2 };
534       DAG.MorphNodeTo(Op0.getNode(), MipsISD::VEXTRACT_ZEXT_ELT,
535                       Op0->getVTList(),
536                       makeArrayRef(Ops, Op0->getNumOperands()));
537       return Op0;
538     }
539   }
540
541   return SDValue();
542 }
543
544 // Determine if the specified node is a constant vector splat.
545 //
546 // Returns true and sets Imm if:
547 // * N is a ISD::BUILD_VECTOR representing a constant splat
548 //
549 // This function is quite similar to MipsSEDAGToDAGISel::selectVSplat. The
550 // differences are that it assumes the MSA has already been checked and the
551 // arbitrary requirement for a maximum of 32-bit integers isn't applied (and
552 // must not be in order for binsri.d to be selectable).
553 static bool isVSplat(SDValue N, APInt &Imm, bool IsLittleEndian) {
554   BuildVectorSDNode *Node = dyn_cast<BuildVectorSDNode>(N.getNode());
555
556   if (!Node)
557     return false;
558
559   APInt SplatValue, SplatUndef;
560   unsigned SplatBitSize;
561   bool HasAnyUndefs;
562
563   if (!Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
564                              8, !IsLittleEndian))
565     return false;
566
567   Imm = SplatValue;
568
569   return true;
570 }
571
572 // Test whether the given node is an all-ones build_vector.
573 static bool isVectorAllOnes(SDValue N) {
574   // Look through bitcasts. Endianness doesn't matter because we are looking
575   // for an all-ones value.
576   if (N->getOpcode() == ISD::BITCAST)
577     N = N->getOperand(0);
578
579   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
580
581   if (!BVN)
582     return false;
583
584   APInt SplatValue, SplatUndef;
585   unsigned SplatBitSize;
586   bool HasAnyUndefs;
587
588   // Endianness doesn't matter in this context because we are looking for
589   // an all-ones value.
590   if (BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs))
591     return SplatValue.isAllOnesValue();
592
593   return false;
594 }
595
596 // Test whether N is the bitwise inverse of OfNode.
597 static bool isBitwiseInverse(SDValue N, SDValue OfNode) {
598   if (N->getOpcode() != ISD::XOR)
599     return false;
600
601   if (isVectorAllOnes(N->getOperand(0)))
602     return N->getOperand(1) == OfNode;
603
604   if (isVectorAllOnes(N->getOperand(1)))
605     return N->getOperand(0) == OfNode;
606
607   return false;
608 }
609
610 // Perform combines where ISD::OR is the root node.
611 //
612 // Performs the following transformations:
613 // - (or (and $a, $mask), (and $b, $inv_mask)) => (vselect $mask, $a, $b)
614 //   where $inv_mask is the bitwise inverse of $mask and the 'or' has a 128-bit
615 //   vector type.
616 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
617                                 TargetLowering::DAGCombinerInfo &DCI,
618                                 const MipsSubtarget *Subtarget) {
619   if (!Subtarget->hasMSA())
620     return SDValue();
621
622   EVT Ty = N->getValueType(0);
623
624   if (!Ty.is128BitVector())
625     return SDValue();
626
627   SDValue Op0 = N->getOperand(0);
628   SDValue Op1 = N->getOperand(1);
629
630   if (Op0->getOpcode() == ISD::AND && Op1->getOpcode() == ISD::AND) {
631     SDValue Op0Op0 = Op0->getOperand(0);
632     SDValue Op0Op1 = Op0->getOperand(1);
633     SDValue Op1Op0 = Op1->getOperand(0);
634     SDValue Op1Op1 = Op1->getOperand(1);
635     bool IsLittleEndian = !Subtarget->isLittle();
636
637     SDValue IfSet, IfClr, Cond;
638     bool IsConstantMask = false;
639     APInt Mask, InvMask;
640
641     // If Op0Op0 is an appropriate mask, try to find it's inverse in either
642     // Op1Op0, or Op1Op1. Keep track of the Cond, IfSet, and IfClr nodes, while
643     // looking.
644     // IfClr will be set if we find a valid match.
645     if (isVSplat(Op0Op0, Mask, IsLittleEndian)) {
646       Cond = Op0Op0;
647       IfSet = Op0Op1;
648
649       if (isVSplat(Op1Op0, InvMask, IsLittleEndian) &&
650           Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
651         IfClr = Op1Op1;
652       else if (isVSplat(Op1Op1, InvMask, IsLittleEndian) &&
653                Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
654         IfClr = Op1Op0;
655
656       IsConstantMask = true;
657     }
658
659     // If IfClr is not yet set, and Op0Op1 is an appropriate mask, try the same
660     // thing again using this mask.
661     // IfClr will be set if we find a valid match.
662     if (!IfClr.getNode() && isVSplat(Op0Op1, Mask, IsLittleEndian)) {
663       Cond = Op0Op1;
664       IfSet = Op0Op0;
665
666       if (isVSplat(Op1Op0, InvMask, IsLittleEndian) &&
667           Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
668         IfClr = Op1Op1;
669       else if (isVSplat(Op1Op1, InvMask, IsLittleEndian) &&
670                Mask.getBitWidth() == InvMask.getBitWidth() && Mask == ~InvMask)
671         IfClr = Op1Op0;
672
673       IsConstantMask = true;
674     }
675
676     // If IfClr is not yet set, try looking for a non-constant match.
677     // IfClr will be set if we find a valid match amongst the eight
678     // possibilities.
679     if (!IfClr.getNode()) {
680       if (isBitwiseInverse(Op0Op0, Op1Op0)) {
681         Cond = Op1Op0;
682         IfSet = Op1Op1;
683         IfClr = Op0Op1;
684       } else if (isBitwiseInverse(Op0Op1, Op1Op0)) {
685         Cond = Op1Op0;
686         IfSet = Op1Op1;
687         IfClr = Op0Op0;
688       } else if (isBitwiseInverse(Op0Op0, Op1Op1)) {
689         Cond = Op1Op1;
690         IfSet = Op1Op0;
691         IfClr = Op0Op1;
692       } else if (isBitwiseInverse(Op0Op1, Op1Op1)) {
693         Cond = Op1Op1;
694         IfSet = Op1Op0;
695         IfClr = Op0Op0;
696       } else if (isBitwiseInverse(Op1Op0, Op0Op0)) {
697         Cond = Op0Op0;
698         IfSet = Op0Op1;
699         IfClr = Op1Op1;
700       } else if (isBitwiseInverse(Op1Op1, Op0Op0)) {
701         Cond = Op0Op0;
702         IfSet = Op0Op1;
703         IfClr = Op1Op0;
704       } else if (isBitwiseInverse(Op1Op0, Op0Op1)) {
705         Cond = Op0Op1;
706         IfSet = Op0Op0;
707         IfClr = Op1Op1;
708       } else if (isBitwiseInverse(Op1Op1, Op0Op1)) {
709         Cond = Op0Op1;
710         IfSet = Op0Op0;
711         IfClr = Op1Op0;
712       }
713     }
714
715     // At this point, IfClr will be set if we have a valid match.
716     if (!IfClr.getNode())
717       return SDValue();
718
719     assert(Cond.getNode() && IfSet.getNode());
720
721     // Fold degenerate cases.
722     if (IsConstantMask) {
723       if (Mask.isAllOnesValue())
724         return IfSet;
725       else if (Mask == 0)
726         return IfClr;
727     }
728
729     // Transform the DAG into an equivalent VSELECT.
730     return DAG.getNode(ISD::VSELECT, SDLoc(N), Ty, Cond, IfSet, IfClr);
731   }
732
733   return SDValue();
734 }
735
736 static SDValue performSUBECombine(SDNode *N, SelectionDAG &DAG,
737                                   TargetLowering::DAGCombinerInfo &DCI,
738                                   const MipsSubtarget *Subtarget) {
739   if (DCI.isBeforeLegalize())
740     return SDValue();
741
742   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
743       selectMSUB(N, &DAG))
744     return SDValue(N, 0);
745
746   return SDValue();
747 }
748
749 static SDValue genConstMult(SDValue X, uint64_t C, SDLoc DL, EVT VT,
750                             EVT ShiftTy, SelectionDAG &DAG) {
751   // Clear the upper (64 - VT.sizeInBits) bits.
752   C &= ((uint64_t)-1) >> (64 - VT.getSizeInBits());
753
754   // Return 0.
755   if (C == 0)
756     return DAG.getConstant(0, VT);
757
758   // Return x.
759   if (C == 1)
760     return X;
761
762   // If c is power of 2, return (shl x, log2(c)).
763   if (isPowerOf2_64(C))
764     return DAG.getNode(ISD::SHL, DL, VT, X,
765                        DAG.getConstant(Log2_64(C), ShiftTy));
766
767   unsigned Log2Ceil = Log2_64_Ceil(C);
768   uint64_t Floor = 1LL << Log2_64(C);
769   uint64_t Ceil = Log2Ceil == 64 ? 0LL : 1LL << Log2Ceil;
770
771   // If |c - floor_c| <= |c - ceil_c|,
772   // where floor_c = pow(2, floor(log2(c))) and ceil_c = pow(2, ceil(log2(c))),
773   // return (add constMult(x, floor_c), constMult(x, c - floor_c)).
774   if (C - Floor <= Ceil - C) {
775     SDValue Op0 = genConstMult(X, Floor, DL, VT, ShiftTy, DAG);
776     SDValue Op1 = genConstMult(X, C - Floor, DL, VT, ShiftTy, DAG);
777     return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
778   }
779
780   // If |c - floor_c| > |c - ceil_c|,
781   // return (sub constMult(x, ceil_c), constMult(x, ceil_c - c)).
782   SDValue Op0 = genConstMult(X, Ceil, DL, VT, ShiftTy, DAG);
783   SDValue Op1 = genConstMult(X, Ceil - C, DL, VT, ShiftTy, DAG);
784   return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
785 }
786
787 static SDValue performMULCombine(SDNode *N, SelectionDAG &DAG,
788                                  const TargetLowering::DAGCombinerInfo &DCI,
789                                  const MipsSETargetLowering *TL) {
790   EVT VT = N->getValueType(0);
791
792   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
793     if (!VT.isVector())
794       return genConstMult(N->getOperand(0), C->getZExtValue(), SDLoc(N),
795                           VT, TL->getScalarShiftAmountTy(VT), DAG);
796
797   return SDValue(N, 0);
798 }
799
800 static SDValue performDSPShiftCombine(unsigned Opc, SDNode *N, EVT Ty,
801                                       SelectionDAG &DAG,
802                                       const MipsSubtarget *Subtarget) {
803   // See if this is a vector splat immediate node.
804   APInt SplatValue, SplatUndef;
805   unsigned SplatBitSize;
806   bool HasAnyUndefs;
807   unsigned EltSize = Ty.getVectorElementType().getSizeInBits();
808   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
809
810   if (!Subtarget->hasDSP())
811     return SDValue();
812
813   if (!BV ||
814       !BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
815                            EltSize, !Subtarget->isLittle()) ||
816       (SplatBitSize != EltSize) ||
817       (SplatValue.getZExtValue() >= EltSize))
818     return SDValue();
819
820   return DAG.getNode(Opc, SDLoc(N), Ty, N->getOperand(0),
821                      DAG.getConstant(SplatValue.getZExtValue(), MVT::i32));
822 }
823
824 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
825                                  TargetLowering::DAGCombinerInfo &DCI,
826                                  const MipsSubtarget *Subtarget) {
827   EVT Ty = N->getValueType(0);
828
829   if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
830     return SDValue();
831
832   return performDSPShiftCombine(MipsISD::SHLL_DSP, N, Ty, DAG, Subtarget);
833 }
834
835 // Fold sign-extensions into MipsISD::VEXTRACT_[SZ]EXT_ELT for MSA and fold
836 // constant splats into MipsISD::SHRA_DSP for DSPr2.
837 //
838 // Performs the following transformations:
839 // - Changes MipsISD::VEXTRACT_[SZ]EXT_ELT to sign extension if its
840 //   sign/zero-extension is completely overwritten by the new one performed by
841 //   the ISD::SRA and ISD::SHL nodes.
842 // - Removes redundant sign extensions performed by an ISD::SRA and ISD::SHL
843 //   sequence.
844 //
845 // See performDSPShiftCombine for more information about the transformation
846 // used for DSPr2.
847 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
848                                  TargetLowering::DAGCombinerInfo &DCI,
849                                  const MipsSubtarget *Subtarget) {
850   EVT Ty = N->getValueType(0);
851
852   if (Subtarget->hasMSA()) {
853     SDValue Op0 = N->getOperand(0);
854     SDValue Op1 = N->getOperand(1);
855
856     // (sra (shl (MipsVExtract[SZ]Ext $a, $b, $c), imm:$d), imm:$d)
857     // where $d + sizeof($c) == 32
858     // or    $d + sizeof($c) <= 32 and SExt
859     // -> (MipsVExtractSExt $a, $b, $c)
860     if (Op0->getOpcode() == ISD::SHL && Op1 == Op0->getOperand(1)) {
861       SDValue Op0Op0 = Op0->getOperand(0);
862       ConstantSDNode *ShAmount = dyn_cast<ConstantSDNode>(Op1);
863
864       if (!ShAmount)
865         return SDValue();
866
867       if (Op0Op0->getOpcode() != MipsISD::VEXTRACT_SEXT_ELT &&
868           Op0Op0->getOpcode() != MipsISD::VEXTRACT_ZEXT_ELT)
869         return SDValue();
870
871       EVT ExtendTy = cast<VTSDNode>(Op0Op0->getOperand(2))->getVT();
872       unsigned TotalBits = ShAmount->getZExtValue() + ExtendTy.getSizeInBits();
873
874       if (TotalBits == 32 ||
875           (Op0Op0->getOpcode() == MipsISD::VEXTRACT_SEXT_ELT &&
876            TotalBits <= 32)) {
877         SDValue Ops[] = { Op0Op0->getOperand(0), Op0Op0->getOperand(1),
878                           Op0Op0->getOperand(2) };
879         DAG.MorphNodeTo(Op0Op0.getNode(), MipsISD::VEXTRACT_SEXT_ELT,
880                         Op0Op0->getVTList(),
881                         makeArrayRef(Ops, Op0Op0->getNumOperands()));
882         return Op0Op0;
883       }
884     }
885   }
886
887   if ((Ty != MVT::v2i16) && ((Ty != MVT::v4i8) || !Subtarget->hasDSPR2()))
888     return SDValue();
889
890   return performDSPShiftCombine(MipsISD::SHRA_DSP, N, Ty, DAG, Subtarget);
891 }
892
893
894 static SDValue performSRLCombine(SDNode *N, SelectionDAG &DAG,
895                                  TargetLowering::DAGCombinerInfo &DCI,
896                                  const MipsSubtarget *Subtarget) {
897   EVT Ty = N->getValueType(0);
898
899   if (((Ty != MVT::v2i16) || !Subtarget->hasDSPR2()) && (Ty != MVT::v4i8))
900     return SDValue();
901
902   return performDSPShiftCombine(MipsISD::SHRL_DSP, N, Ty, DAG, Subtarget);
903 }
904
905 static bool isLegalDSPCondCode(EVT Ty, ISD::CondCode CC) {
906   bool IsV216 = (Ty == MVT::v2i16);
907
908   switch (CC) {
909   case ISD::SETEQ:
910   case ISD::SETNE:  return true;
911   case ISD::SETLT:
912   case ISD::SETLE:
913   case ISD::SETGT:
914   case ISD::SETGE:  return IsV216;
915   case ISD::SETULT:
916   case ISD::SETULE:
917   case ISD::SETUGT:
918   case ISD::SETUGE: return !IsV216;
919   default:          return false;
920   }
921 }
922
923 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
924   EVT Ty = N->getValueType(0);
925
926   if ((Ty != MVT::v2i16) && (Ty != MVT::v4i8))
927     return SDValue();
928
929   if (!isLegalDSPCondCode(Ty, cast<CondCodeSDNode>(N->getOperand(2))->get()))
930     return SDValue();
931
932   return DAG.getNode(MipsISD::SETCC_DSP, SDLoc(N), Ty, N->getOperand(0),
933                      N->getOperand(1), N->getOperand(2));
934 }
935
936 static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG) {
937   EVT Ty = N->getValueType(0);
938
939   if (Ty.is128BitVector() && Ty.isInteger()) {
940     // Try the following combines:
941     //   (vselect (setcc $a, $b, SETLT), $b, $a)) -> (vsmax $a, $b)
942     //   (vselect (setcc $a, $b, SETLE), $b, $a)) -> (vsmax $a, $b)
943     //   (vselect (setcc $a, $b, SETLT), $a, $b)) -> (vsmin $a, $b)
944     //   (vselect (setcc $a, $b, SETLE), $a, $b)) -> (vsmin $a, $b)
945     //   (vselect (setcc $a, $b, SETULT), $b, $a)) -> (vumax $a, $b)
946     //   (vselect (setcc $a, $b, SETULE), $b, $a)) -> (vumax $a, $b)
947     //   (vselect (setcc $a, $b, SETULT), $a, $b)) -> (vumin $a, $b)
948     //   (vselect (setcc $a, $b, SETULE), $a, $b)) -> (vumin $a, $b)
949     // SETGT/SETGE/SETUGT/SETUGE variants of these will show up initially but
950     // will be expanded to equivalent SETLT/SETLE/SETULT/SETULE versions by the
951     // legalizer.
952     SDValue Op0 = N->getOperand(0);
953
954     if (Op0->getOpcode() != ISD::SETCC)
955       return SDValue();
956
957     ISD::CondCode CondCode = cast<CondCodeSDNode>(Op0->getOperand(2))->get();
958     bool Signed;
959
960     if (CondCode == ISD::SETLT  || CondCode == ISD::SETLE)
961       Signed = true;
962     else if (CondCode == ISD::SETULT || CondCode == ISD::SETULE)
963       Signed = false;
964     else
965       return SDValue();
966
967     SDValue Op1 = N->getOperand(1);
968     SDValue Op2 = N->getOperand(2);
969     SDValue Op0Op0 = Op0->getOperand(0);
970     SDValue Op0Op1 = Op0->getOperand(1);
971
972     if (Op1 == Op0Op0 && Op2 == Op0Op1)
973       return DAG.getNode(Signed ? MipsISD::VSMIN : MipsISD::VUMIN, SDLoc(N),
974                          Ty, Op1, Op2);
975     else if (Op1 == Op0Op1 && Op2 == Op0Op0)
976       return DAG.getNode(Signed ? MipsISD::VSMAX : MipsISD::VUMAX, SDLoc(N),
977                          Ty, Op1, Op2);
978   } else if ((Ty == MVT::v2i16) || (Ty == MVT::v4i8)) {
979     SDValue SetCC = N->getOperand(0);
980
981     if (SetCC.getOpcode() != MipsISD::SETCC_DSP)
982       return SDValue();
983
984     return DAG.getNode(MipsISD::SELECT_CC_DSP, SDLoc(N), Ty,
985                        SetCC.getOperand(0), SetCC.getOperand(1),
986                        N->getOperand(1), N->getOperand(2), SetCC.getOperand(2));
987   }
988
989   return SDValue();
990 }
991
992 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG,
993                                  const MipsSubtarget *Subtarget) {
994   EVT Ty = N->getValueType(0);
995
996   if (Subtarget->hasMSA() && Ty.is128BitVector() && Ty.isInteger()) {
997     // Try the following combines:
998     //   (xor (or $a, $b), (build_vector allones))
999     //   (xor (or $a, $b), (bitcast (build_vector allones)))
1000     SDValue Op0 = N->getOperand(0);
1001     SDValue Op1 = N->getOperand(1);
1002     SDValue NotOp;
1003
1004     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
1005       NotOp = Op1;
1006     else if (ISD::isBuildVectorAllOnes(Op1.getNode()))
1007       NotOp = Op0;
1008     else
1009       return SDValue();
1010
1011     if (NotOp->getOpcode() == ISD::OR)
1012       return DAG.getNode(MipsISD::VNOR, SDLoc(N), Ty, NotOp->getOperand(0),
1013                          NotOp->getOperand(1));
1014   }
1015
1016   return SDValue();
1017 }
1018
1019 SDValue
1020 MipsSETargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1021   SelectionDAG &DAG = DCI.DAG;
1022   SDValue Val;
1023
1024   switch (N->getOpcode()) {
1025   case ISD::ADDE:
1026     return performADDECombine(N, DAG, DCI, Subtarget);
1027   case ISD::AND:
1028     Val = performANDCombine(N, DAG, DCI, Subtarget);
1029     break;
1030   case ISD::OR:
1031     Val = performORCombine(N, DAG, DCI, Subtarget);
1032     break;
1033   case ISD::SUBE:
1034     return performSUBECombine(N, DAG, DCI, Subtarget);
1035   case ISD::MUL:
1036     return performMULCombine(N, DAG, DCI, this);
1037   case ISD::SHL:
1038     return performSHLCombine(N, DAG, DCI, Subtarget);
1039   case ISD::SRA:
1040     return performSRACombine(N, DAG, DCI, Subtarget);
1041   case ISD::SRL:
1042     return performSRLCombine(N, DAG, DCI, Subtarget);
1043   case ISD::VSELECT:
1044     return performVSELECTCombine(N, DAG);
1045   case ISD::XOR:
1046     Val = performXORCombine(N, DAG, Subtarget);
1047     break;
1048   case ISD::SETCC:
1049     Val = performSETCCCombine(N, DAG);
1050     break;
1051   }
1052
1053   if (Val.getNode()) {
1054     DEBUG(dbgs() << "\nMipsSE DAG Combine:\n";
1055           N->printrWithDepth(dbgs(), &DAG);
1056           dbgs() << "\n=> \n";
1057           Val.getNode()->printrWithDepth(dbgs(), &DAG);
1058           dbgs() << "\n");
1059     return Val;
1060   }
1061
1062   return MipsTargetLowering::PerformDAGCombine(N, DCI);
1063 }
1064
1065 MachineBasicBlock *
1066 MipsSETargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1067                                                   MachineBasicBlock *BB) const {
1068   switch (MI->getOpcode()) {
1069   default:
1070     return MipsTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1071   case Mips::BPOSGE32_PSEUDO:
1072     return emitBPOSGE32(MI, BB);
1073   case Mips::SNZ_B_PSEUDO:
1074     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_B);
1075   case Mips::SNZ_H_PSEUDO:
1076     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_H);
1077   case Mips::SNZ_W_PSEUDO:
1078     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_W);
1079   case Mips::SNZ_D_PSEUDO:
1080     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_D);
1081   case Mips::SNZ_V_PSEUDO:
1082     return emitMSACBranchPseudo(MI, BB, Mips::BNZ_V);
1083   case Mips::SZ_B_PSEUDO:
1084     return emitMSACBranchPseudo(MI, BB, Mips::BZ_B);
1085   case Mips::SZ_H_PSEUDO:
1086     return emitMSACBranchPseudo(MI, BB, Mips::BZ_H);
1087   case Mips::SZ_W_PSEUDO:
1088     return emitMSACBranchPseudo(MI, BB, Mips::BZ_W);
1089   case Mips::SZ_D_PSEUDO:
1090     return emitMSACBranchPseudo(MI, BB, Mips::BZ_D);
1091   case Mips::SZ_V_PSEUDO:
1092     return emitMSACBranchPseudo(MI, BB, Mips::BZ_V);
1093   case Mips::COPY_FW_PSEUDO:
1094     return emitCOPY_FW(MI, BB);
1095   case Mips::COPY_FD_PSEUDO:
1096     return emitCOPY_FD(MI, BB);
1097   case Mips::INSERT_FW_PSEUDO:
1098     return emitINSERT_FW(MI, BB);
1099   case Mips::INSERT_FD_PSEUDO:
1100     return emitINSERT_FD(MI, BB);
1101   case Mips::INSERT_B_VIDX_PSEUDO:
1102     return emitINSERT_DF_VIDX(MI, BB, 1, false);
1103   case Mips::INSERT_H_VIDX_PSEUDO:
1104     return emitINSERT_DF_VIDX(MI, BB, 2, false);
1105   case Mips::INSERT_W_VIDX_PSEUDO:
1106     return emitINSERT_DF_VIDX(MI, BB, 4, false);
1107   case Mips::INSERT_D_VIDX_PSEUDO:
1108     return emitINSERT_DF_VIDX(MI, BB, 8, false);
1109   case Mips::INSERT_FW_VIDX_PSEUDO:
1110     return emitINSERT_DF_VIDX(MI, BB, 4, true);
1111   case Mips::INSERT_FD_VIDX_PSEUDO:
1112     return emitINSERT_DF_VIDX(MI, BB, 8, true);
1113   case Mips::FILL_FW_PSEUDO:
1114     return emitFILL_FW(MI, BB);
1115   case Mips::FILL_FD_PSEUDO:
1116     return emitFILL_FD(MI, BB);
1117   case Mips::FEXP2_W_1_PSEUDO:
1118     return emitFEXP2_W_1(MI, BB);
1119   case Mips::FEXP2_D_1_PSEUDO:
1120     return emitFEXP2_D_1(MI, BB);
1121   }
1122 }
1123
1124 bool MipsSETargetLowering::
1125 isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
1126                                   unsigned NextStackOffset,
1127                                   const MipsFunctionInfo& FI) const {
1128   if (!EnableMipsTailCalls)
1129     return false;
1130
1131   // Return false if either the callee or caller has a byval argument.
1132   if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
1133     return false;
1134
1135   // Return true if the callee's argument area is no larger than the
1136   // caller's.
1137   return NextStackOffset <= FI.getIncomingArgSize();
1138 }
1139
1140 void MipsSETargetLowering::
1141 getOpndList(SmallVectorImpl<SDValue> &Ops,
1142             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
1143             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
1144             CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
1145   Ops.push_back(Callee);
1146   MipsTargetLowering::getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal,
1147                                   InternalLinkage, CLI, Callee, Chain);
1148 }
1149
1150 SDValue MipsSETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1151   LoadSDNode &Nd = *cast<LoadSDNode>(Op);
1152
1153   if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
1154     return MipsTargetLowering::lowerLOAD(Op, DAG);
1155
1156   // Replace a double precision load with two i32 loads and a buildpair64.
1157   SDLoc DL(Op);
1158   SDValue Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
1159   EVT PtrVT = Ptr.getValueType();
1160
1161   // i32 load from lower address.
1162   SDValue Lo = DAG.getLoad(MVT::i32, DL, Chain, Ptr,
1163                            MachinePointerInfo(), Nd.isVolatile(),
1164                            Nd.isNonTemporal(), Nd.isInvariant(),
1165                            Nd.getAlignment());
1166
1167   // i32 load from higher address.
1168   Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
1169   SDValue Hi = DAG.getLoad(MVT::i32, DL, Lo.getValue(1), Ptr,
1170                            MachinePointerInfo(), Nd.isVolatile(),
1171                            Nd.isNonTemporal(), Nd.isInvariant(),
1172                            std::min(Nd.getAlignment(), 4U));
1173
1174   if (!Subtarget->isLittle())
1175     std::swap(Lo, Hi);
1176
1177   SDValue BP = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1178   SDValue Ops[2] = {BP, Hi.getValue(1)};
1179   return DAG.getMergeValues(Ops, DL);
1180 }
1181
1182 SDValue MipsSETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1183   StoreSDNode &Nd = *cast<StoreSDNode>(Op);
1184
1185   if (Nd.getMemoryVT() != MVT::f64 || !NoDPLoadStore)
1186     return MipsTargetLowering::lowerSTORE(Op, DAG);
1187
1188   // Replace a double precision store with two extractelement64s and i32 stores.
1189   SDLoc DL(Op);
1190   SDValue Val = Nd.getValue(), Ptr = Nd.getBasePtr(), Chain = Nd.getChain();
1191   EVT PtrVT = Ptr.getValueType();
1192   SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1193                            Val, DAG.getConstant(0, MVT::i32));
1194   SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1195                            Val, DAG.getConstant(1, MVT::i32));
1196
1197   if (!Subtarget->isLittle())
1198     std::swap(Lo, Hi);
1199
1200   // i32 store to lower address.
1201   Chain = DAG.getStore(Chain, DL, Lo, Ptr, MachinePointerInfo(),
1202                        Nd.isVolatile(), Nd.isNonTemporal(), Nd.getAlignment(),
1203                        Nd.getTBAAInfo());
1204
1205   // i32 store to higher address.
1206   Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr, DAG.getConstant(4, PtrVT));
1207   return DAG.getStore(Chain, DL, Hi, Ptr, MachinePointerInfo(),
1208                       Nd.isVolatile(), Nd.isNonTemporal(),
1209                       std::min(Nd.getAlignment(), 4U), Nd.getTBAAInfo());
1210 }
1211
1212 SDValue MipsSETargetLowering::lowerMulDiv(SDValue Op, unsigned NewOpc,
1213                                           bool HasLo, bool HasHi,
1214                                           SelectionDAG &DAG) const {
1215   // MIPS32r6/MIPS64r6 removed accumulator based multiplies.
1216   assert(!Subtarget->hasMips32r6());
1217
1218   EVT Ty = Op.getOperand(0).getValueType();
1219   SDLoc DL(Op);
1220   SDValue Mult = DAG.getNode(NewOpc, DL, MVT::Untyped,
1221                              Op.getOperand(0), Op.getOperand(1));
1222   SDValue Lo, Hi;
1223
1224   if (HasLo)
1225     Lo = DAG.getNode(MipsISD::MFLO, DL, Ty, Mult);
1226   if (HasHi)
1227     Hi = DAG.getNode(MipsISD::MFHI, DL, Ty, Mult);
1228
1229   if (!HasLo || !HasHi)
1230     return HasLo ? Lo : Hi;
1231
1232   SDValue Vals[] = { Lo, Hi };
1233   return DAG.getMergeValues(Vals, DL);
1234 }
1235
1236
1237 static SDValue initAccumulator(SDValue In, SDLoc DL, SelectionDAG &DAG) {
1238   SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
1239                              DAG.getConstant(0, MVT::i32));
1240   SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, In,
1241                              DAG.getConstant(1, MVT::i32));
1242   return DAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, InLo, InHi);
1243 }
1244
1245 static SDValue extractLOHI(SDValue Op, SDLoc DL, SelectionDAG &DAG) {
1246   SDValue Lo = DAG.getNode(MipsISD::MFLO, DL, MVT::i32, Op);
1247   SDValue Hi = DAG.getNode(MipsISD::MFHI, DL, MVT::i32, Op);
1248   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
1249 }
1250
1251 // This function expands mips intrinsic nodes which have 64-bit input operands
1252 // or output values.
1253 //
1254 // out64 = intrinsic-node in64
1255 // =>
1256 // lo = copy (extract-element (in64, 0))
1257 // hi = copy (extract-element (in64, 1))
1258 // mips-specific-node
1259 // v0 = copy lo
1260 // v1 = copy hi
1261 // out64 = merge-values (v0, v1)
1262 //
1263 static SDValue lowerDSPIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
1264   SDLoc DL(Op);
1265   bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
1266   SmallVector<SDValue, 3> Ops;
1267   unsigned OpNo = 0;
1268
1269   // See if Op has a chain input.
1270   if (HasChainIn)
1271     Ops.push_back(Op->getOperand(OpNo++));
1272
1273   // The next operand is the intrinsic opcode.
1274   assert(Op->getOperand(OpNo).getOpcode() == ISD::TargetConstant);
1275
1276   // See if the next operand has type i64.
1277   SDValue Opnd = Op->getOperand(++OpNo), In64;
1278
1279   if (Opnd.getValueType() == MVT::i64)
1280     In64 = initAccumulator(Opnd, DL, DAG);
1281   else
1282     Ops.push_back(Opnd);
1283
1284   // Push the remaining operands.
1285   for (++OpNo ; OpNo < Op->getNumOperands(); ++OpNo)
1286     Ops.push_back(Op->getOperand(OpNo));
1287
1288   // Add In64 to the end of the list.
1289   if (In64.getNode())
1290     Ops.push_back(In64);
1291
1292   // Scan output.
1293   SmallVector<EVT, 2> ResTys;
1294
1295   for (SDNode::value_iterator I = Op->value_begin(), E = Op->value_end();
1296        I != E; ++I)
1297     ResTys.push_back((*I == MVT::i64) ? MVT::Untyped : *I);
1298
1299   // Create node.
1300   SDValue Val = DAG.getNode(Opc, DL, ResTys, Ops);
1301   SDValue Out = (ResTys[0] == MVT::Untyped) ? extractLOHI(Val, DL, DAG) : Val;
1302
1303   if (!HasChainIn)
1304     return Out;
1305
1306   assert(Val->getValueType(1) == MVT::Other);
1307   SDValue Vals[] = { Out, SDValue(Val.getNode(), 1) };
1308   return DAG.getMergeValues(Vals, DL);
1309 }
1310
1311 // Lower an MSA copy intrinsic into the specified SelectionDAG node
1312 static SDValue lowerMSACopyIntr(SDValue Op, SelectionDAG &DAG, unsigned Opc) {
1313   SDLoc DL(Op);
1314   SDValue Vec = Op->getOperand(1);
1315   SDValue Idx = Op->getOperand(2);
1316   EVT ResTy = Op->getValueType(0);
1317   EVT EltTy = Vec->getValueType(0).getVectorElementType();
1318
1319   SDValue Result = DAG.getNode(Opc, DL, ResTy, Vec, Idx,
1320                                DAG.getValueType(EltTy));
1321
1322   return Result;
1323 }
1324
1325 static SDValue lowerMSASplatZExt(SDValue Op, unsigned OpNr, SelectionDAG &DAG) {
1326   EVT ResVecTy = Op->getValueType(0);
1327   EVT ViaVecTy = ResVecTy;
1328   SDLoc DL(Op);
1329
1330   // When ResVecTy == MVT::v2i64, LaneA is the upper 32 bits of the lane and
1331   // LaneB is the lower 32-bits. Otherwise LaneA and LaneB are alternating
1332   // lanes.
1333   SDValue LaneA;
1334   SDValue LaneB = Op->getOperand(2);
1335
1336   if (ResVecTy == MVT::v2i64) {
1337     LaneA = DAG.getConstant(0, MVT::i32);
1338     ViaVecTy = MVT::v4i32;
1339   } else
1340     LaneA = LaneB;
1341
1342   SDValue Ops[16] = { LaneA, LaneB, LaneA, LaneB, LaneA, LaneB, LaneA, LaneB,
1343                       LaneA, LaneB, LaneA, LaneB, LaneA, LaneB, LaneA, LaneB };
1344
1345   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, DL, ViaVecTy,
1346                        makeArrayRef(Ops, ViaVecTy.getVectorNumElements()));
1347
1348   if (ViaVecTy != ResVecTy)
1349     Result = DAG.getNode(ISD::BITCAST, DL, ResVecTy, Result);
1350
1351   return Result;
1352 }
1353
1354 static SDValue lowerMSASplatImm(SDValue Op, unsigned ImmOp, SelectionDAG &DAG) {
1355   return DAG.getConstant(Op->getConstantOperandVal(ImmOp), Op->getValueType(0));
1356 }
1357
1358 static SDValue getBuildVectorSplat(EVT VecTy, SDValue SplatValue,
1359                                    bool BigEndian, SelectionDAG &DAG) {
1360   EVT ViaVecTy = VecTy;
1361   SDValue SplatValueA = SplatValue;
1362   SDValue SplatValueB = SplatValue;
1363   SDLoc DL(SplatValue);
1364
1365   if (VecTy == MVT::v2i64) {
1366     // v2i64 BUILD_VECTOR must be performed via v4i32 so split into i32's.
1367     ViaVecTy = MVT::v4i32;
1368
1369     SplatValueA = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, SplatValue);
1370     SplatValueB = DAG.getNode(ISD::SRL, DL, MVT::i64, SplatValue,
1371                               DAG.getConstant(32, MVT::i32));
1372     SplatValueB = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, SplatValueB);
1373   }
1374
1375   // We currently hold the parts in little endian order. Swap them if
1376   // necessary.
1377   if (BigEndian)
1378     std::swap(SplatValueA, SplatValueB);
1379
1380   SDValue Ops[16] = { SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1381                       SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1382                       SplatValueA, SplatValueB, SplatValueA, SplatValueB,
1383                       SplatValueA, SplatValueB, SplatValueA, SplatValueB };
1384
1385   SDValue Result = DAG.getNode(ISD::BUILD_VECTOR, DL, ViaVecTy,
1386                        makeArrayRef(Ops, ViaVecTy.getVectorNumElements()));
1387
1388   if (VecTy != ViaVecTy)
1389     Result = DAG.getNode(ISD::BITCAST, DL, VecTy, Result);
1390
1391   return Result;
1392 }
1393
1394 static SDValue lowerMSABinaryBitImmIntr(SDValue Op, SelectionDAG &DAG,
1395                                         unsigned Opc, SDValue Imm,
1396                                         bool BigEndian) {
1397   EVT VecTy = Op->getValueType(0);
1398   SDValue Exp2Imm;
1399   SDLoc DL(Op);
1400
1401   // The DAG Combiner can't constant fold bitcasted vectors yet so we must do it
1402   // here for now.
1403   if (VecTy == MVT::v2i64) {
1404     if (ConstantSDNode *CImm = dyn_cast<ConstantSDNode>(Imm)) {
1405       APInt BitImm = APInt(64, 1) << CImm->getAPIntValue();
1406
1407       SDValue BitImmHiOp = DAG.getConstant(BitImm.lshr(32).trunc(32), MVT::i32);
1408       SDValue BitImmLoOp = DAG.getConstant(BitImm.trunc(32), MVT::i32);
1409
1410       if (BigEndian)
1411         std::swap(BitImmLoOp, BitImmHiOp);
1412
1413       Exp2Imm =
1414           DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
1415                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, BitImmLoOp,
1416                                   BitImmHiOp, BitImmLoOp, BitImmHiOp));
1417     }
1418   }
1419
1420   if (!Exp2Imm.getNode()) {
1421     // We couldnt constant fold, do a vector shift instead
1422
1423     // Extend i32 to i64 if necessary. Sign or zero extend doesn't matter since
1424     // only values 0-63 are valid.
1425     if (VecTy == MVT::v2i64)
1426       Imm = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Imm);
1427
1428     Exp2Imm = getBuildVectorSplat(VecTy, Imm, BigEndian, DAG);
1429
1430     Exp2Imm =
1431         DAG.getNode(ISD::SHL, DL, VecTy, DAG.getConstant(1, VecTy), Exp2Imm);
1432   }
1433
1434   return DAG.getNode(Opc, DL, VecTy, Op->getOperand(1), Exp2Imm);
1435 }
1436
1437 static SDValue lowerMSABitClear(SDValue Op, SelectionDAG &DAG) {
1438   EVT ResTy = Op->getValueType(0);
1439   SDLoc DL(Op);
1440   SDValue One = DAG.getConstant(1, ResTy);
1441   SDValue Bit = DAG.getNode(ISD::SHL, DL, ResTy, One, Op->getOperand(2));
1442
1443   return DAG.getNode(ISD::AND, DL, ResTy, Op->getOperand(1),
1444                      DAG.getNOT(DL, Bit, ResTy));
1445 }
1446
1447 static SDValue lowerMSABitClearImm(SDValue Op, SelectionDAG &DAG) {
1448   SDLoc DL(Op);
1449   EVT ResTy = Op->getValueType(0);
1450   APInt BitImm = APInt(ResTy.getVectorElementType().getSizeInBits(), 1)
1451                  << cast<ConstantSDNode>(Op->getOperand(2))->getAPIntValue();
1452   SDValue BitMask = DAG.getConstant(~BitImm, ResTy);
1453
1454   return DAG.getNode(ISD::AND, DL, ResTy, Op->getOperand(1), BitMask);
1455 }
1456
1457 SDValue MipsSETargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
1458                                                       SelectionDAG &DAG) const {
1459   SDLoc DL(Op);
1460
1461   switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
1462   default:
1463     return SDValue();
1464   case Intrinsic::mips_shilo:
1465     return lowerDSPIntr(Op, DAG, MipsISD::SHILO);
1466   case Intrinsic::mips_dpau_h_qbl:
1467     return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL);
1468   case Intrinsic::mips_dpau_h_qbr:
1469     return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR);
1470   case Intrinsic::mips_dpsu_h_qbl:
1471     return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL);
1472   case Intrinsic::mips_dpsu_h_qbr:
1473     return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR);
1474   case Intrinsic::mips_dpa_w_ph:
1475     return lowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH);
1476   case Intrinsic::mips_dps_w_ph:
1477     return lowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH);
1478   case Intrinsic::mips_dpax_w_ph:
1479     return lowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH);
1480   case Intrinsic::mips_dpsx_w_ph:
1481     return lowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH);
1482   case Intrinsic::mips_mulsa_w_ph:
1483     return lowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH);
1484   case Intrinsic::mips_mult:
1485     return lowerDSPIntr(Op, DAG, MipsISD::Mult);
1486   case Intrinsic::mips_multu:
1487     return lowerDSPIntr(Op, DAG, MipsISD::Multu);
1488   case Intrinsic::mips_madd:
1489     return lowerDSPIntr(Op, DAG, MipsISD::MAdd);
1490   case Intrinsic::mips_maddu:
1491     return lowerDSPIntr(Op, DAG, MipsISD::MAddu);
1492   case Intrinsic::mips_msub:
1493     return lowerDSPIntr(Op, DAG, MipsISD::MSub);
1494   case Intrinsic::mips_msubu:
1495     return lowerDSPIntr(Op, DAG, MipsISD::MSubu);
1496   case Intrinsic::mips_addv_b:
1497   case Intrinsic::mips_addv_h:
1498   case Intrinsic::mips_addv_w:
1499   case Intrinsic::mips_addv_d:
1500     return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1501                        Op->getOperand(2));
1502   case Intrinsic::mips_addvi_b:
1503   case Intrinsic::mips_addvi_h:
1504   case Intrinsic::mips_addvi_w:
1505   case Intrinsic::mips_addvi_d:
1506     return DAG.getNode(ISD::ADD, DL, Op->getValueType(0), Op->getOperand(1),
1507                        lowerMSASplatImm(Op, 2, DAG));
1508   case Intrinsic::mips_and_v:
1509     return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1510                        Op->getOperand(2));
1511   case Intrinsic::mips_andi_b:
1512     return DAG.getNode(ISD::AND, DL, Op->getValueType(0), Op->getOperand(1),
1513                        lowerMSASplatImm(Op, 2, DAG));
1514   case Intrinsic::mips_bclr_b:
1515   case Intrinsic::mips_bclr_h:
1516   case Intrinsic::mips_bclr_w:
1517   case Intrinsic::mips_bclr_d:
1518     return lowerMSABitClear(Op, DAG);
1519   case Intrinsic::mips_bclri_b:
1520   case Intrinsic::mips_bclri_h:
1521   case Intrinsic::mips_bclri_w:
1522   case Intrinsic::mips_bclri_d:
1523     return lowerMSABitClearImm(Op, DAG);
1524   case Intrinsic::mips_binsli_b:
1525   case Intrinsic::mips_binsli_h:
1526   case Intrinsic::mips_binsli_w:
1527   case Intrinsic::mips_binsli_d: {
1528     // binsli_x(IfClear, IfSet, nbits) -> (vselect LBitsMask, IfSet, IfClear)
1529     EVT VecTy = Op->getValueType(0);
1530     EVT EltTy = VecTy.getVectorElementType();
1531     APInt Mask = APInt::getHighBitsSet(EltTy.getSizeInBits(),
1532                                        Op->getConstantOperandVal(3));
1533     return DAG.getNode(ISD::VSELECT, DL, VecTy,
1534                        DAG.getConstant(Mask, VecTy, true), Op->getOperand(2),
1535                        Op->getOperand(1));
1536   }
1537   case Intrinsic::mips_binsri_b:
1538   case Intrinsic::mips_binsri_h:
1539   case Intrinsic::mips_binsri_w:
1540   case Intrinsic::mips_binsri_d: {
1541     // binsri_x(IfClear, IfSet, nbits) -> (vselect RBitsMask, IfSet, IfClear)
1542     EVT VecTy = Op->getValueType(0);
1543     EVT EltTy = VecTy.getVectorElementType();
1544     APInt Mask = APInt::getLowBitsSet(EltTy.getSizeInBits(),
1545                                       Op->getConstantOperandVal(3));
1546     return DAG.getNode(ISD::VSELECT, DL, VecTy,
1547                        DAG.getConstant(Mask, VecTy, true), Op->getOperand(2),
1548                        Op->getOperand(1));
1549   }
1550   case Intrinsic::mips_bmnz_v:
1551     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0), Op->getOperand(3),
1552                        Op->getOperand(2), Op->getOperand(1));
1553   case Intrinsic::mips_bmnzi_b:
1554     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1555                        lowerMSASplatImm(Op, 3, DAG), Op->getOperand(2),
1556                        Op->getOperand(1));
1557   case Intrinsic::mips_bmz_v:
1558     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0), Op->getOperand(3),
1559                        Op->getOperand(1), Op->getOperand(2));
1560   case Intrinsic::mips_bmzi_b:
1561     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1562                        lowerMSASplatImm(Op, 3, DAG), Op->getOperand(1),
1563                        Op->getOperand(2));
1564   case Intrinsic::mips_bneg_b:
1565   case Intrinsic::mips_bneg_h:
1566   case Intrinsic::mips_bneg_w:
1567   case Intrinsic::mips_bneg_d: {
1568     EVT VecTy = Op->getValueType(0);
1569     SDValue One = DAG.getConstant(1, VecTy);
1570
1571     return DAG.getNode(ISD::XOR, DL, VecTy, Op->getOperand(1),
1572                        DAG.getNode(ISD::SHL, DL, VecTy, One,
1573                                    Op->getOperand(2)));
1574   }
1575   case Intrinsic::mips_bnegi_b:
1576   case Intrinsic::mips_bnegi_h:
1577   case Intrinsic::mips_bnegi_w:
1578   case Intrinsic::mips_bnegi_d:
1579     return lowerMSABinaryBitImmIntr(Op, DAG, ISD::XOR, Op->getOperand(2),
1580                                     !Subtarget->isLittle());
1581   case Intrinsic::mips_bnz_b:
1582   case Intrinsic::mips_bnz_h:
1583   case Intrinsic::mips_bnz_w:
1584   case Intrinsic::mips_bnz_d:
1585     return DAG.getNode(MipsISD::VALL_NONZERO, DL, Op->getValueType(0),
1586                        Op->getOperand(1));
1587   case Intrinsic::mips_bnz_v:
1588     return DAG.getNode(MipsISD::VANY_NONZERO, DL, Op->getValueType(0),
1589                        Op->getOperand(1));
1590   case Intrinsic::mips_bsel_v:
1591     // bsel_v(Mask, IfClear, IfSet) -> (vselect Mask, IfSet, IfClear)
1592     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1593                        Op->getOperand(1), Op->getOperand(3),
1594                        Op->getOperand(2));
1595   case Intrinsic::mips_bseli_b:
1596     // bseli_v(Mask, IfClear, IfSet) -> (vselect Mask, IfSet, IfClear)
1597     return DAG.getNode(ISD::VSELECT, DL, Op->getValueType(0),
1598                        Op->getOperand(1), lowerMSASplatImm(Op, 3, DAG),
1599                        Op->getOperand(2));
1600   case Intrinsic::mips_bset_b:
1601   case Intrinsic::mips_bset_h:
1602   case Intrinsic::mips_bset_w:
1603   case Intrinsic::mips_bset_d: {
1604     EVT VecTy = Op->getValueType(0);
1605     SDValue One = DAG.getConstant(1, VecTy);
1606
1607     return DAG.getNode(ISD::OR, DL, VecTy, Op->getOperand(1),
1608                        DAG.getNode(ISD::SHL, DL, VecTy, One,
1609                                    Op->getOperand(2)));
1610   }
1611   case Intrinsic::mips_bseti_b:
1612   case Intrinsic::mips_bseti_h:
1613   case Intrinsic::mips_bseti_w:
1614   case Intrinsic::mips_bseti_d:
1615     return lowerMSABinaryBitImmIntr(Op, DAG, ISD::OR, Op->getOperand(2),
1616                                     !Subtarget->isLittle());
1617   case Intrinsic::mips_bz_b:
1618   case Intrinsic::mips_bz_h:
1619   case Intrinsic::mips_bz_w:
1620   case Intrinsic::mips_bz_d:
1621     return DAG.getNode(MipsISD::VALL_ZERO, DL, Op->getValueType(0),
1622                        Op->getOperand(1));
1623   case Intrinsic::mips_bz_v:
1624     return DAG.getNode(MipsISD::VANY_ZERO, DL, Op->getValueType(0),
1625                        Op->getOperand(1));
1626   case Intrinsic::mips_ceq_b:
1627   case Intrinsic::mips_ceq_h:
1628   case Intrinsic::mips_ceq_w:
1629   case Intrinsic::mips_ceq_d:
1630     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1631                         Op->getOperand(2), ISD::SETEQ);
1632   case Intrinsic::mips_ceqi_b:
1633   case Intrinsic::mips_ceqi_h:
1634   case Intrinsic::mips_ceqi_w:
1635   case Intrinsic::mips_ceqi_d:
1636     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1637                         lowerMSASplatImm(Op, 2, DAG), ISD::SETEQ);
1638   case Intrinsic::mips_cle_s_b:
1639   case Intrinsic::mips_cle_s_h:
1640   case Intrinsic::mips_cle_s_w:
1641   case Intrinsic::mips_cle_s_d:
1642     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1643                         Op->getOperand(2), ISD::SETLE);
1644   case Intrinsic::mips_clei_s_b:
1645   case Intrinsic::mips_clei_s_h:
1646   case Intrinsic::mips_clei_s_w:
1647   case Intrinsic::mips_clei_s_d:
1648     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1649                         lowerMSASplatImm(Op, 2, DAG), ISD::SETLE);
1650   case Intrinsic::mips_cle_u_b:
1651   case Intrinsic::mips_cle_u_h:
1652   case Intrinsic::mips_cle_u_w:
1653   case Intrinsic::mips_cle_u_d:
1654     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1655                         Op->getOperand(2), ISD::SETULE);
1656   case Intrinsic::mips_clei_u_b:
1657   case Intrinsic::mips_clei_u_h:
1658   case Intrinsic::mips_clei_u_w:
1659   case Intrinsic::mips_clei_u_d:
1660     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1661                         lowerMSASplatImm(Op, 2, DAG), ISD::SETULE);
1662   case Intrinsic::mips_clt_s_b:
1663   case Intrinsic::mips_clt_s_h:
1664   case Intrinsic::mips_clt_s_w:
1665   case Intrinsic::mips_clt_s_d:
1666     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1667                         Op->getOperand(2), ISD::SETLT);
1668   case Intrinsic::mips_clti_s_b:
1669   case Intrinsic::mips_clti_s_h:
1670   case Intrinsic::mips_clti_s_w:
1671   case Intrinsic::mips_clti_s_d:
1672     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1673                         lowerMSASplatImm(Op, 2, DAG), ISD::SETLT);
1674   case Intrinsic::mips_clt_u_b:
1675   case Intrinsic::mips_clt_u_h:
1676   case Intrinsic::mips_clt_u_w:
1677   case Intrinsic::mips_clt_u_d:
1678     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1679                         Op->getOperand(2), ISD::SETULT);
1680   case Intrinsic::mips_clti_u_b:
1681   case Intrinsic::mips_clti_u_h:
1682   case Intrinsic::mips_clti_u_w:
1683   case Intrinsic::mips_clti_u_d:
1684     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1685                         lowerMSASplatImm(Op, 2, DAG), ISD::SETULT);
1686   case Intrinsic::mips_copy_s_b:
1687   case Intrinsic::mips_copy_s_h:
1688   case Intrinsic::mips_copy_s_w:
1689     return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_SEXT_ELT);
1690   case Intrinsic::mips_copy_s_d:
1691     if (hasMips64())
1692       // Lower directly into VEXTRACT_SEXT_ELT since i64 is legal on Mips64.
1693       return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_SEXT_ELT);
1694     else {
1695       // Lower into the generic EXTRACT_VECTOR_ELT node and let the type
1696       // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1697       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
1698                          Op->getValueType(0), Op->getOperand(1),
1699                          Op->getOperand(2));
1700     }
1701   case Intrinsic::mips_copy_u_b:
1702   case Intrinsic::mips_copy_u_h:
1703   case Intrinsic::mips_copy_u_w:
1704     return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_ZEXT_ELT);
1705   case Intrinsic::mips_copy_u_d:
1706     if (hasMips64())
1707       // Lower directly into VEXTRACT_ZEXT_ELT since i64 is legal on Mips64.
1708       return lowerMSACopyIntr(Op, DAG, MipsISD::VEXTRACT_ZEXT_ELT);
1709     else {
1710       // Lower into the generic EXTRACT_VECTOR_ELT node and let the type
1711       // legalizer and EXTRACT_VECTOR_ELT lowering sort it out.
1712       // Note: When i64 is illegal, this results in copy_s.w instructions
1713       // instead of copy_u.w instructions. This makes no difference to the
1714       // behaviour since i64 is only illegal when the register file is 32-bit.
1715       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op),
1716                          Op->getValueType(0), Op->getOperand(1),
1717                          Op->getOperand(2));
1718     }
1719   case Intrinsic::mips_div_s_b:
1720   case Intrinsic::mips_div_s_h:
1721   case Intrinsic::mips_div_s_w:
1722   case Intrinsic::mips_div_s_d:
1723     return DAG.getNode(ISD::SDIV, DL, Op->getValueType(0), Op->getOperand(1),
1724                        Op->getOperand(2));
1725   case Intrinsic::mips_div_u_b:
1726   case Intrinsic::mips_div_u_h:
1727   case Intrinsic::mips_div_u_w:
1728   case Intrinsic::mips_div_u_d:
1729     return DAG.getNode(ISD::UDIV, DL, Op->getValueType(0), Op->getOperand(1),
1730                        Op->getOperand(2));
1731   case Intrinsic::mips_fadd_w:
1732   case Intrinsic::mips_fadd_d:
1733     return DAG.getNode(ISD::FADD, DL, Op->getValueType(0), Op->getOperand(1),
1734                        Op->getOperand(2));
1735   // Don't lower mips_fcaf_[wd] since LLVM folds SETFALSE condcodes away
1736   case Intrinsic::mips_fceq_w:
1737   case Intrinsic::mips_fceq_d:
1738     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1739                         Op->getOperand(2), ISD::SETOEQ);
1740   case Intrinsic::mips_fcle_w:
1741   case Intrinsic::mips_fcle_d:
1742     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1743                         Op->getOperand(2), ISD::SETOLE);
1744   case Intrinsic::mips_fclt_w:
1745   case Intrinsic::mips_fclt_d:
1746     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1747                         Op->getOperand(2), ISD::SETOLT);
1748   case Intrinsic::mips_fcne_w:
1749   case Intrinsic::mips_fcne_d:
1750     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1751                         Op->getOperand(2), ISD::SETONE);
1752   case Intrinsic::mips_fcor_w:
1753   case Intrinsic::mips_fcor_d:
1754     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1755                         Op->getOperand(2), ISD::SETO);
1756   case Intrinsic::mips_fcueq_w:
1757   case Intrinsic::mips_fcueq_d:
1758     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1759                         Op->getOperand(2), ISD::SETUEQ);
1760   case Intrinsic::mips_fcule_w:
1761   case Intrinsic::mips_fcule_d:
1762     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1763                         Op->getOperand(2), ISD::SETULE);
1764   case Intrinsic::mips_fcult_w:
1765   case Intrinsic::mips_fcult_d:
1766     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1767                         Op->getOperand(2), ISD::SETULT);
1768   case Intrinsic::mips_fcun_w:
1769   case Intrinsic::mips_fcun_d:
1770     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1771                         Op->getOperand(2), ISD::SETUO);
1772   case Intrinsic::mips_fcune_w:
1773   case Intrinsic::mips_fcune_d:
1774     return DAG.getSetCC(DL, Op->getValueType(0), Op->getOperand(1),
1775                         Op->getOperand(2), ISD::SETUNE);
1776   case Intrinsic::mips_fdiv_w:
1777   case Intrinsic::mips_fdiv_d:
1778     return DAG.getNode(ISD::FDIV, DL, Op->getValueType(0), Op->getOperand(1),
1779                        Op->getOperand(2));
1780   case Intrinsic::mips_ffint_u_w:
1781   case Intrinsic::mips_ffint_u_d:
1782     return DAG.getNode(ISD::UINT_TO_FP, DL, Op->getValueType(0),
1783                        Op->getOperand(1));
1784   case Intrinsic::mips_ffint_s_w:
1785   case Intrinsic::mips_ffint_s_d:
1786     return DAG.getNode(ISD::SINT_TO_FP, DL, Op->getValueType(0),
1787                        Op->getOperand(1));
1788   case Intrinsic::mips_fill_b:
1789   case Intrinsic::mips_fill_h:
1790   case Intrinsic::mips_fill_w:
1791   case Intrinsic::mips_fill_d: {
1792     SmallVector<SDValue, 16> Ops;
1793     EVT ResTy = Op->getValueType(0);
1794
1795     for (unsigned i = 0; i < ResTy.getVectorNumElements(); ++i)
1796       Ops.push_back(Op->getOperand(1));
1797
1798     // If ResTy is v2i64 then the type legalizer will break this node down into
1799     // an equivalent v4i32.
1800     return DAG.getNode(ISD::BUILD_VECTOR, DL, ResTy, Ops);
1801   }
1802   case Intrinsic::mips_fexp2_w:
1803   case Intrinsic::mips_fexp2_d: {
1804     EVT ResTy = Op->getValueType(0);
1805     return DAG.getNode(
1806         ISD::FMUL, SDLoc(Op), ResTy, Op->getOperand(1),
1807         DAG.getNode(ISD::FEXP2, SDLoc(Op), ResTy, Op->getOperand(2)));
1808   }
1809   case Intrinsic::mips_flog2_w:
1810   case Intrinsic::mips_flog2_d:
1811     return DAG.getNode(ISD::FLOG2, DL, Op->getValueType(0), Op->getOperand(1));
1812   case Intrinsic::mips_fmadd_w:
1813   case Intrinsic::mips_fmadd_d:
1814     return DAG.getNode(ISD::FMA, SDLoc(Op), Op->getValueType(0),
1815                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
1816   case Intrinsic::mips_fmul_w:
1817   case Intrinsic::mips_fmul_d:
1818     return DAG.getNode(ISD::FMUL, DL, Op->getValueType(0), Op->getOperand(1),
1819                        Op->getOperand(2));
1820   case Intrinsic::mips_fmsub_w:
1821   case Intrinsic::mips_fmsub_d: {
1822     EVT ResTy = Op->getValueType(0);
1823     return DAG.getNode(ISD::FSUB, SDLoc(Op), ResTy, Op->getOperand(1),
1824                        DAG.getNode(ISD::FMUL, SDLoc(Op), ResTy,
1825                                    Op->getOperand(2), Op->getOperand(3)));
1826   }
1827   case Intrinsic::mips_frint_w:
1828   case Intrinsic::mips_frint_d:
1829     return DAG.getNode(ISD::FRINT, DL, Op->getValueType(0), Op->getOperand(1));
1830   case Intrinsic::mips_fsqrt_w:
1831   case Intrinsic::mips_fsqrt_d:
1832     return DAG.getNode(ISD::FSQRT, DL, Op->getValueType(0), Op->getOperand(1));
1833   case Intrinsic::mips_fsub_w:
1834   case Intrinsic::mips_fsub_d:
1835     return DAG.getNode(ISD::FSUB, DL, Op->getValueType(0), Op->getOperand(1),
1836                        Op->getOperand(2));
1837   case Intrinsic::mips_ftrunc_u_w:
1838   case Intrinsic::mips_ftrunc_u_d:
1839     return DAG.getNode(ISD::FP_TO_UINT, DL, Op->getValueType(0),
1840                        Op->getOperand(1));
1841   case Intrinsic::mips_ftrunc_s_w:
1842   case Intrinsic::mips_ftrunc_s_d:
1843     return DAG.getNode(ISD::FP_TO_SINT, DL, Op->getValueType(0),
1844                        Op->getOperand(1));
1845   case Intrinsic::mips_ilvev_b:
1846   case Intrinsic::mips_ilvev_h:
1847   case Intrinsic::mips_ilvev_w:
1848   case Intrinsic::mips_ilvev_d:
1849     return DAG.getNode(MipsISD::ILVEV, DL, Op->getValueType(0),
1850                        Op->getOperand(1), Op->getOperand(2));
1851   case Intrinsic::mips_ilvl_b:
1852   case Intrinsic::mips_ilvl_h:
1853   case Intrinsic::mips_ilvl_w:
1854   case Intrinsic::mips_ilvl_d:
1855     return DAG.getNode(MipsISD::ILVL, DL, Op->getValueType(0),
1856                        Op->getOperand(1), Op->getOperand(2));
1857   case Intrinsic::mips_ilvod_b:
1858   case Intrinsic::mips_ilvod_h:
1859   case Intrinsic::mips_ilvod_w:
1860   case Intrinsic::mips_ilvod_d:
1861     return DAG.getNode(MipsISD::ILVOD, DL, Op->getValueType(0),
1862                        Op->getOperand(1), Op->getOperand(2));
1863   case Intrinsic::mips_ilvr_b:
1864   case Intrinsic::mips_ilvr_h:
1865   case Intrinsic::mips_ilvr_w:
1866   case Intrinsic::mips_ilvr_d:
1867     return DAG.getNode(MipsISD::ILVR, DL, Op->getValueType(0),
1868                        Op->getOperand(1), Op->getOperand(2));
1869   case Intrinsic::mips_insert_b:
1870   case Intrinsic::mips_insert_h:
1871   case Intrinsic::mips_insert_w:
1872   case Intrinsic::mips_insert_d:
1873     return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), Op->getValueType(0),
1874                        Op->getOperand(1), Op->getOperand(3), Op->getOperand(2));
1875   case Intrinsic::mips_insve_b:
1876   case Intrinsic::mips_insve_h:
1877   case Intrinsic::mips_insve_w:
1878   case Intrinsic::mips_insve_d:
1879     return DAG.getNode(MipsISD::INSVE, DL, Op->getValueType(0),
1880                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3),
1881                        DAG.getConstant(0, MVT::i32));
1882   case Intrinsic::mips_ldi_b:
1883   case Intrinsic::mips_ldi_h:
1884   case Intrinsic::mips_ldi_w:
1885   case Intrinsic::mips_ldi_d:
1886     return lowerMSASplatImm(Op, 1, DAG);
1887   case Intrinsic::mips_lsa:
1888   case Intrinsic::mips_dlsa: {
1889     EVT ResTy = Op->getValueType(0);
1890     return DAG.getNode(ISD::ADD, SDLoc(Op), ResTy, Op->getOperand(1),
1891                        DAG.getNode(ISD::SHL, SDLoc(Op), ResTy,
1892                                    Op->getOperand(2), Op->getOperand(3)));
1893   }
1894   case Intrinsic::mips_maddv_b:
1895   case Intrinsic::mips_maddv_h:
1896   case Intrinsic::mips_maddv_w:
1897   case Intrinsic::mips_maddv_d: {
1898     EVT ResTy = Op->getValueType(0);
1899     return DAG.getNode(ISD::ADD, SDLoc(Op), ResTy, Op->getOperand(1),
1900                        DAG.getNode(ISD::MUL, SDLoc(Op), ResTy,
1901                                    Op->getOperand(2), Op->getOperand(3)));
1902   }
1903   case Intrinsic::mips_max_s_b:
1904   case Intrinsic::mips_max_s_h:
1905   case Intrinsic::mips_max_s_w:
1906   case Intrinsic::mips_max_s_d:
1907     return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1908                        Op->getOperand(1), Op->getOperand(2));
1909   case Intrinsic::mips_max_u_b:
1910   case Intrinsic::mips_max_u_h:
1911   case Intrinsic::mips_max_u_w:
1912   case Intrinsic::mips_max_u_d:
1913     return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1914                        Op->getOperand(1), Op->getOperand(2));
1915   case Intrinsic::mips_maxi_s_b:
1916   case Intrinsic::mips_maxi_s_h:
1917   case Intrinsic::mips_maxi_s_w:
1918   case Intrinsic::mips_maxi_s_d:
1919     return DAG.getNode(MipsISD::VSMAX, DL, Op->getValueType(0),
1920                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1921   case Intrinsic::mips_maxi_u_b:
1922   case Intrinsic::mips_maxi_u_h:
1923   case Intrinsic::mips_maxi_u_w:
1924   case Intrinsic::mips_maxi_u_d:
1925     return DAG.getNode(MipsISD::VUMAX, DL, Op->getValueType(0),
1926                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1927   case Intrinsic::mips_min_s_b:
1928   case Intrinsic::mips_min_s_h:
1929   case Intrinsic::mips_min_s_w:
1930   case Intrinsic::mips_min_s_d:
1931     return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1932                        Op->getOperand(1), Op->getOperand(2));
1933   case Intrinsic::mips_min_u_b:
1934   case Intrinsic::mips_min_u_h:
1935   case Intrinsic::mips_min_u_w:
1936   case Intrinsic::mips_min_u_d:
1937     return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1938                        Op->getOperand(1), Op->getOperand(2));
1939   case Intrinsic::mips_mini_s_b:
1940   case Intrinsic::mips_mini_s_h:
1941   case Intrinsic::mips_mini_s_w:
1942   case Intrinsic::mips_mini_s_d:
1943     return DAG.getNode(MipsISD::VSMIN, DL, Op->getValueType(0),
1944                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1945   case Intrinsic::mips_mini_u_b:
1946   case Intrinsic::mips_mini_u_h:
1947   case Intrinsic::mips_mini_u_w:
1948   case Intrinsic::mips_mini_u_d:
1949     return DAG.getNode(MipsISD::VUMIN, DL, Op->getValueType(0),
1950                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
1951   case Intrinsic::mips_mod_s_b:
1952   case Intrinsic::mips_mod_s_h:
1953   case Intrinsic::mips_mod_s_w:
1954   case Intrinsic::mips_mod_s_d:
1955     return DAG.getNode(ISD::SREM, DL, Op->getValueType(0), Op->getOperand(1),
1956                        Op->getOperand(2));
1957   case Intrinsic::mips_mod_u_b:
1958   case Intrinsic::mips_mod_u_h:
1959   case Intrinsic::mips_mod_u_w:
1960   case Intrinsic::mips_mod_u_d:
1961     return DAG.getNode(ISD::UREM, DL, Op->getValueType(0), Op->getOperand(1),
1962                        Op->getOperand(2));
1963   case Intrinsic::mips_mulv_b:
1964   case Intrinsic::mips_mulv_h:
1965   case Intrinsic::mips_mulv_w:
1966   case Intrinsic::mips_mulv_d:
1967     return DAG.getNode(ISD::MUL, DL, Op->getValueType(0), Op->getOperand(1),
1968                        Op->getOperand(2));
1969   case Intrinsic::mips_msubv_b:
1970   case Intrinsic::mips_msubv_h:
1971   case Intrinsic::mips_msubv_w:
1972   case Intrinsic::mips_msubv_d: {
1973     EVT ResTy = Op->getValueType(0);
1974     return DAG.getNode(ISD::SUB, SDLoc(Op), ResTy, Op->getOperand(1),
1975                        DAG.getNode(ISD::MUL, SDLoc(Op), ResTy,
1976                                    Op->getOperand(2), Op->getOperand(3)));
1977   }
1978   case Intrinsic::mips_nlzc_b:
1979   case Intrinsic::mips_nlzc_h:
1980   case Intrinsic::mips_nlzc_w:
1981   case Intrinsic::mips_nlzc_d:
1982     return DAG.getNode(ISD::CTLZ, DL, Op->getValueType(0), Op->getOperand(1));
1983   case Intrinsic::mips_nor_v: {
1984     SDValue Res = DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1985                               Op->getOperand(1), Op->getOperand(2));
1986     return DAG.getNOT(DL, Res, Res->getValueType(0));
1987   }
1988   case Intrinsic::mips_nori_b: {
1989     SDValue Res =  DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1990                                Op->getOperand(1),
1991                                lowerMSASplatImm(Op, 2, DAG));
1992     return DAG.getNOT(DL, Res, Res->getValueType(0));
1993   }
1994   case Intrinsic::mips_or_v:
1995     return DAG.getNode(ISD::OR, DL, Op->getValueType(0), Op->getOperand(1),
1996                        Op->getOperand(2));
1997   case Intrinsic::mips_ori_b:
1998     return DAG.getNode(ISD::OR, DL, Op->getValueType(0),
1999                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2000   case Intrinsic::mips_pckev_b:
2001   case Intrinsic::mips_pckev_h:
2002   case Intrinsic::mips_pckev_w:
2003   case Intrinsic::mips_pckev_d:
2004     return DAG.getNode(MipsISD::PCKEV, DL, Op->getValueType(0),
2005                        Op->getOperand(1), Op->getOperand(2));
2006   case Intrinsic::mips_pckod_b:
2007   case Intrinsic::mips_pckod_h:
2008   case Intrinsic::mips_pckod_w:
2009   case Intrinsic::mips_pckod_d:
2010     return DAG.getNode(MipsISD::PCKOD, DL, Op->getValueType(0),
2011                        Op->getOperand(1), Op->getOperand(2));
2012   case Intrinsic::mips_pcnt_b:
2013   case Intrinsic::mips_pcnt_h:
2014   case Intrinsic::mips_pcnt_w:
2015   case Intrinsic::mips_pcnt_d:
2016     return DAG.getNode(ISD::CTPOP, DL, Op->getValueType(0), Op->getOperand(1));
2017   case Intrinsic::mips_shf_b:
2018   case Intrinsic::mips_shf_h:
2019   case Intrinsic::mips_shf_w:
2020     return DAG.getNode(MipsISD::SHF, DL, Op->getValueType(0),
2021                        Op->getOperand(2), Op->getOperand(1));
2022   case Intrinsic::mips_sll_b:
2023   case Intrinsic::mips_sll_h:
2024   case Intrinsic::mips_sll_w:
2025   case Intrinsic::mips_sll_d:
2026     return DAG.getNode(ISD::SHL, DL, Op->getValueType(0), Op->getOperand(1),
2027                        Op->getOperand(2));
2028   case Intrinsic::mips_slli_b:
2029   case Intrinsic::mips_slli_h:
2030   case Intrinsic::mips_slli_w:
2031   case Intrinsic::mips_slli_d:
2032     return DAG.getNode(ISD::SHL, DL, Op->getValueType(0),
2033                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2034   case Intrinsic::mips_splat_b:
2035   case Intrinsic::mips_splat_h:
2036   case Intrinsic::mips_splat_w:
2037   case Intrinsic::mips_splat_d:
2038     // We can't lower via VECTOR_SHUFFLE because it requires constant shuffle
2039     // masks, nor can we lower via BUILD_VECTOR & EXTRACT_VECTOR_ELT because
2040     // EXTRACT_VECTOR_ELT can't extract i64's on MIPS32.
2041     // Instead we lower to MipsISD::VSHF and match from there.
2042     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2043                        lowerMSASplatZExt(Op, 2, DAG), Op->getOperand(1),
2044                        Op->getOperand(1));
2045   case Intrinsic::mips_splati_b:
2046   case Intrinsic::mips_splati_h:
2047   case Intrinsic::mips_splati_w:
2048   case Intrinsic::mips_splati_d:
2049     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2050                        lowerMSASplatImm(Op, 2, DAG), Op->getOperand(1),
2051                        Op->getOperand(1));
2052   case Intrinsic::mips_sra_b:
2053   case Intrinsic::mips_sra_h:
2054   case Intrinsic::mips_sra_w:
2055   case Intrinsic::mips_sra_d:
2056     return DAG.getNode(ISD::SRA, DL, Op->getValueType(0), Op->getOperand(1),
2057                        Op->getOperand(2));
2058   case Intrinsic::mips_srai_b:
2059   case Intrinsic::mips_srai_h:
2060   case Intrinsic::mips_srai_w:
2061   case Intrinsic::mips_srai_d:
2062     return DAG.getNode(ISD::SRA, DL, Op->getValueType(0),
2063                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2064   case Intrinsic::mips_srl_b:
2065   case Intrinsic::mips_srl_h:
2066   case Intrinsic::mips_srl_w:
2067   case Intrinsic::mips_srl_d:
2068     return DAG.getNode(ISD::SRL, DL, Op->getValueType(0), Op->getOperand(1),
2069                        Op->getOperand(2));
2070   case Intrinsic::mips_srli_b:
2071   case Intrinsic::mips_srli_h:
2072   case Intrinsic::mips_srli_w:
2073   case Intrinsic::mips_srli_d:
2074     return DAG.getNode(ISD::SRL, DL, Op->getValueType(0),
2075                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2076   case Intrinsic::mips_subv_b:
2077   case Intrinsic::mips_subv_h:
2078   case Intrinsic::mips_subv_w:
2079   case Intrinsic::mips_subv_d:
2080     return DAG.getNode(ISD::SUB, DL, Op->getValueType(0), Op->getOperand(1),
2081                        Op->getOperand(2));
2082   case Intrinsic::mips_subvi_b:
2083   case Intrinsic::mips_subvi_h:
2084   case Intrinsic::mips_subvi_w:
2085   case Intrinsic::mips_subvi_d:
2086     return DAG.getNode(ISD::SUB, DL, Op->getValueType(0),
2087                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2088   case Intrinsic::mips_vshf_b:
2089   case Intrinsic::mips_vshf_h:
2090   case Intrinsic::mips_vshf_w:
2091   case Intrinsic::mips_vshf_d:
2092     return DAG.getNode(MipsISD::VSHF, DL, Op->getValueType(0),
2093                        Op->getOperand(1), Op->getOperand(2), Op->getOperand(3));
2094   case Intrinsic::mips_xor_v:
2095     return DAG.getNode(ISD::XOR, DL, Op->getValueType(0), Op->getOperand(1),
2096                        Op->getOperand(2));
2097   case Intrinsic::mips_xori_b:
2098     return DAG.getNode(ISD::XOR, DL, Op->getValueType(0),
2099                        Op->getOperand(1), lowerMSASplatImm(Op, 2, DAG));
2100   }
2101 }
2102
2103 static SDValue lowerMSALoadIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
2104   SDLoc DL(Op);
2105   SDValue ChainIn = Op->getOperand(0);
2106   SDValue Address = Op->getOperand(2);
2107   SDValue Offset  = Op->getOperand(3);
2108   EVT ResTy = Op->getValueType(0);
2109   EVT PtrTy = Address->getValueType(0);
2110
2111   Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
2112
2113   return DAG.getLoad(ResTy, DL, ChainIn, Address, MachinePointerInfo(), false,
2114                      false, false, 16);
2115 }
2116
2117 SDValue MipsSETargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
2118                                                      SelectionDAG &DAG) const {
2119   unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
2120   switch (Intr) {
2121   default:
2122     return SDValue();
2123   case Intrinsic::mips_extp:
2124     return lowerDSPIntr(Op, DAG, MipsISD::EXTP);
2125   case Intrinsic::mips_extpdp:
2126     return lowerDSPIntr(Op, DAG, MipsISD::EXTPDP);
2127   case Intrinsic::mips_extr_w:
2128     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_W);
2129   case Intrinsic::mips_extr_r_w:
2130     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W);
2131   case Intrinsic::mips_extr_rs_w:
2132     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W);
2133   case Intrinsic::mips_extr_s_h:
2134     return lowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H);
2135   case Intrinsic::mips_mthlip:
2136     return lowerDSPIntr(Op, DAG, MipsISD::MTHLIP);
2137   case Intrinsic::mips_mulsaq_s_w_ph:
2138     return lowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH);
2139   case Intrinsic::mips_maq_s_w_phl:
2140     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL);
2141   case Intrinsic::mips_maq_s_w_phr:
2142     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR);
2143   case Intrinsic::mips_maq_sa_w_phl:
2144     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL);
2145   case Intrinsic::mips_maq_sa_w_phr:
2146     return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR);
2147   case Intrinsic::mips_dpaq_s_w_ph:
2148     return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH);
2149   case Intrinsic::mips_dpsq_s_w_ph:
2150     return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH);
2151   case Intrinsic::mips_dpaq_sa_l_w:
2152     return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W);
2153   case Intrinsic::mips_dpsq_sa_l_w:
2154     return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W);
2155   case Intrinsic::mips_dpaqx_s_w_ph:
2156     return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH);
2157   case Intrinsic::mips_dpaqx_sa_w_ph:
2158     return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH);
2159   case Intrinsic::mips_dpsqx_s_w_ph:
2160     return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH);
2161   case Intrinsic::mips_dpsqx_sa_w_ph:
2162     return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH);
2163   case Intrinsic::mips_ld_b:
2164   case Intrinsic::mips_ld_h:
2165   case Intrinsic::mips_ld_w:
2166   case Intrinsic::mips_ld_d:
2167    return lowerMSALoadIntr(Op, DAG, Intr);
2168   }
2169 }
2170
2171 static SDValue lowerMSAStoreIntr(SDValue Op, SelectionDAG &DAG, unsigned Intr) {
2172   SDLoc DL(Op);
2173   SDValue ChainIn = Op->getOperand(0);
2174   SDValue Value   = Op->getOperand(2);
2175   SDValue Address = Op->getOperand(3);
2176   SDValue Offset  = Op->getOperand(4);
2177   EVT PtrTy = Address->getValueType(0);
2178
2179   Address = DAG.getNode(ISD::ADD, DL, PtrTy, Address, Offset);
2180
2181   return DAG.getStore(ChainIn, DL, Value, Address, MachinePointerInfo(), false,
2182                       false, 16);
2183 }
2184
2185 SDValue MipsSETargetLowering::lowerINTRINSIC_VOID(SDValue Op,
2186                                                   SelectionDAG &DAG) const {
2187   unsigned Intr = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
2188   switch (Intr) {
2189   default:
2190     return SDValue();
2191   case Intrinsic::mips_st_b:
2192   case Intrinsic::mips_st_h:
2193   case Intrinsic::mips_st_w:
2194   case Intrinsic::mips_st_d:
2195     return lowerMSAStoreIntr(Op, DAG, Intr);
2196   }
2197 }
2198
2199 /// \brief Check if the given BuildVectorSDNode is a splat.
2200 /// This method currently relies on DAG nodes being reused when equivalent,
2201 /// so it's possible for this to return false even when isConstantSplat returns
2202 /// true.
2203 static bool isSplatVector(const BuildVectorSDNode *N) {
2204   unsigned int nOps = N->getNumOperands();
2205   assert(nOps > 1 && "isSplatVector has 0 or 1 sized build vector");
2206
2207   SDValue Operand0 = N->getOperand(0);
2208
2209   for (unsigned int i = 1; i < nOps; ++i) {
2210     if (N->getOperand(i) != Operand0)
2211       return false;
2212   }
2213
2214   return true;
2215 }
2216
2217 // Lower ISD::EXTRACT_VECTOR_ELT into MipsISD::VEXTRACT_SEXT_ELT.
2218 //
2219 // The non-value bits resulting from ISD::EXTRACT_VECTOR_ELT are undefined. We
2220 // choose to sign-extend but we could have equally chosen zero-extend. The
2221 // DAGCombiner will fold any sign/zero extension of the ISD::EXTRACT_VECTOR_ELT
2222 // result into this node later (possibly changing it to a zero-extend in the
2223 // process).
2224 SDValue MipsSETargetLowering::
2225 lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
2226   SDLoc DL(Op);
2227   EVT ResTy = Op->getValueType(0);
2228   SDValue Op0 = Op->getOperand(0);
2229   EVT VecTy = Op0->getValueType(0);
2230
2231   if (!VecTy.is128BitVector())
2232     return SDValue();
2233
2234   if (ResTy.isInteger()) {
2235     SDValue Op1 = Op->getOperand(1);
2236     EVT EltTy = VecTy.getVectorElementType();
2237     return DAG.getNode(MipsISD::VEXTRACT_SEXT_ELT, DL, ResTy, Op0, Op1,
2238                        DAG.getValueType(EltTy));
2239   }
2240
2241   return Op;
2242 }
2243
2244 static bool isConstantOrUndef(const SDValue Op) {
2245   if (Op->getOpcode() == ISD::UNDEF)
2246     return true;
2247   if (dyn_cast<ConstantSDNode>(Op))
2248     return true;
2249   if (dyn_cast<ConstantFPSDNode>(Op))
2250     return true;
2251   return false;
2252 }
2253
2254 static bool isConstantOrUndefBUILD_VECTOR(const BuildVectorSDNode *Op) {
2255   for (unsigned i = 0; i < Op->getNumOperands(); ++i)
2256     if (isConstantOrUndef(Op->getOperand(i)))
2257       return true;
2258   return false;
2259 }
2260
2261 // Lowers ISD::BUILD_VECTOR into appropriate SelectionDAG nodes for the
2262 // backend.
2263 //
2264 // Lowers according to the following rules:
2265 // - Constant splats are legal as-is as long as the SplatBitSize is a power of
2266 //   2 less than or equal to 64 and the value fits into a signed 10-bit
2267 //   immediate
2268 // - Constant splats are lowered to bitconverted BUILD_VECTORs if SplatBitSize
2269 //   is a power of 2 less than or equal to 64 and the value does not fit into a
2270 //   signed 10-bit immediate
2271 // - Non-constant splats are legal as-is.
2272 // - Non-constant non-splats are lowered to sequences of INSERT_VECTOR_ELT.
2273 // - All others are illegal and must be expanded.
2274 SDValue MipsSETargetLowering::lowerBUILD_VECTOR(SDValue Op,
2275                                                 SelectionDAG &DAG) const {
2276   BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);
2277   EVT ResTy = Op->getValueType(0);
2278   SDLoc DL(Op);
2279   APInt SplatValue, SplatUndef;
2280   unsigned SplatBitSize;
2281   bool HasAnyUndefs;
2282
2283   if (!Subtarget->hasMSA() || !ResTy.is128BitVector())
2284     return SDValue();
2285
2286   if (Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2287                             HasAnyUndefs, 8,
2288                             !Subtarget->isLittle()) && SplatBitSize <= 64) {
2289     // We can only cope with 8, 16, 32, or 64-bit elements
2290     if (SplatBitSize != 8 && SplatBitSize != 16 && SplatBitSize != 32 &&
2291         SplatBitSize != 64)
2292       return SDValue();
2293
2294     // If the value fits into a simm10 then we can use ldi.[bhwd]
2295     // However, if it isn't an integer type we will have to bitcast from an
2296     // integer type first. Also, if there are any undefs, we must lower them
2297     // to defined values first.
2298     if (ResTy.isInteger() && !HasAnyUndefs && SplatValue.isSignedIntN(10))
2299       return Op;
2300
2301     EVT ViaVecTy;
2302
2303     switch (SplatBitSize) {
2304     default:
2305       return SDValue();
2306     case 8:
2307       ViaVecTy = MVT::v16i8;
2308       break;
2309     case 16:
2310       ViaVecTy = MVT::v8i16;
2311       break;
2312     case 32:
2313       ViaVecTy = MVT::v4i32;
2314       break;
2315     case 64:
2316       // There's no fill.d to fall back on for 64-bit values
2317       return SDValue();
2318     }
2319
2320     // SelectionDAG::getConstant will promote SplatValue appropriately.
2321     SDValue Result = DAG.getConstant(SplatValue, ViaVecTy);
2322
2323     // Bitcast to the type we originally wanted
2324     if (ViaVecTy != ResTy)
2325       Result = DAG.getNode(ISD::BITCAST, SDLoc(Node), ResTy, Result);
2326
2327     return Result;
2328   } else if (isSplatVector(Node))
2329     return Op;
2330   else if (!isConstantOrUndefBUILD_VECTOR(Node)) {
2331     // Use INSERT_VECTOR_ELT operations rather than expand to stores.
2332     // The resulting code is the same length as the expansion, but it doesn't
2333     // use memory operations
2334     EVT ResTy = Node->getValueType(0);
2335
2336     assert(ResTy.isVector());
2337
2338     unsigned NumElts = ResTy.getVectorNumElements();
2339     SDValue Vector = DAG.getUNDEF(ResTy);
2340     for (unsigned i = 0; i < NumElts; ++i) {
2341       Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ResTy, Vector,
2342                            Node->getOperand(i),
2343                            DAG.getConstant(i, MVT::i32));
2344     }
2345     return Vector;
2346   }
2347
2348   return SDValue();
2349 }
2350
2351 // Lower VECTOR_SHUFFLE into SHF (if possible).
2352 //
2353 // SHF splits the vector into blocks of four elements, then shuffles these
2354 // elements according to a <4 x i2> constant (encoded as an integer immediate).
2355 //
2356 // It is therefore possible to lower into SHF when the mask takes the form:
2357 //   <a, b, c, d, a+4, b+4, c+4, d+4, a+8, b+8, c+8, d+8, ...>
2358 // When undef's appear they are treated as if they were whatever value is
2359 // necessary in order to fit the above form.
2360 //
2361 // For example:
2362 //   %2 = shufflevector <8 x i16> %0, <8 x i16> undef,
2363 //                      <8 x i32> <i32 3, i32 2, i32 1, i32 0,
2364 //                                 i32 7, i32 6, i32 5, i32 4>
2365 // is lowered to:
2366 //   (SHF_H $w0, $w1, 27)
2367 // where the 27 comes from:
2368 //   3 + (2 << 2) + (1 << 4) + (0 << 6)
2369 static SDValue lowerVECTOR_SHUFFLE_SHF(SDValue Op, EVT ResTy,
2370                                        SmallVector<int, 16> Indices,
2371                                        SelectionDAG &DAG) {
2372   int SHFIndices[4] = { -1, -1, -1, -1 };
2373
2374   if (Indices.size() < 4)
2375     return SDValue();
2376
2377   for (unsigned i = 0; i < 4; ++i) {
2378     for (unsigned j = i; j < Indices.size(); j += 4) {
2379       int Idx = Indices[j];
2380
2381       // Convert from vector index to 4-element subvector index
2382       // If an index refers to an element outside of the subvector then give up
2383       if (Idx != -1) {
2384         Idx -= 4 * (j / 4);
2385         if (Idx < 0 || Idx >= 4)
2386           return SDValue();
2387       }
2388
2389       // If the mask has an undef, replace it with the current index.
2390       // Note that it might still be undef if the current index is also undef
2391       if (SHFIndices[i] == -1)
2392         SHFIndices[i] = Idx;
2393
2394       // Check that non-undef values are the same as in the mask. If they
2395       // aren't then give up
2396       if (!(Idx == -1 || Idx == SHFIndices[i]))
2397         return SDValue();
2398     }
2399   }
2400
2401   // Calculate the immediate. Replace any remaining undefs with zero
2402   APInt Imm(32, 0);
2403   for (int i = 3; i >= 0; --i) {
2404     int Idx = SHFIndices[i];
2405
2406     if (Idx == -1)
2407       Idx = 0;
2408
2409     Imm <<= 2;
2410     Imm |= Idx & 0x3;
2411   }
2412
2413   return DAG.getNode(MipsISD::SHF, SDLoc(Op), ResTy,
2414                      DAG.getConstant(Imm, MVT::i32), Op->getOperand(0));
2415 }
2416
2417 // Lower VECTOR_SHUFFLE into ILVEV (if possible).
2418 //
2419 // ILVEV interleaves the even elements from each vector.
2420 //
2421 // It is possible to lower into ILVEV when the mask takes the form:
2422 //   <0, n, 2, n+2, 4, n+4, ...>
2423 // where n is the number of elements in the vector.
2424 //
2425 // When undef's appear in the mask they are treated as if they were whatever
2426 // value is necessary in order to fit the above form.
2427 static SDValue lowerVECTOR_SHUFFLE_ILVEV(SDValue Op, EVT ResTy,
2428                                          SmallVector<int, 16> Indices,
2429                                          SelectionDAG &DAG) {
2430   assert ((Indices.size() % 2) == 0);
2431   int WsIdx = 0;
2432   int WtIdx = ResTy.getVectorNumElements();
2433
2434   for (unsigned i = 0; i < Indices.size(); i += 2) {
2435     if (Indices[i] != -1 && Indices[i] != WsIdx)
2436       return SDValue();
2437     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2438       return SDValue();
2439     WsIdx += 2;
2440     WtIdx += 2;
2441   }
2442
2443   return DAG.getNode(MipsISD::ILVEV, SDLoc(Op), ResTy, Op->getOperand(0),
2444                      Op->getOperand(1));
2445 }
2446
2447 // Lower VECTOR_SHUFFLE into ILVOD (if possible).
2448 //
2449 // ILVOD interleaves the odd elements from each vector.
2450 //
2451 // It is possible to lower into ILVOD when the mask takes the form:
2452 //   <1, n+1, 3, n+3, 5, n+5, ...>
2453 // where n is the number of elements in the vector.
2454 //
2455 // When undef's appear in the mask they are treated as if they were whatever
2456 // value is necessary in order to fit the above form.
2457 static SDValue lowerVECTOR_SHUFFLE_ILVOD(SDValue Op, EVT ResTy,
2458                                          SmallVector<int, 16> Indices,
2459                                          SelectionDAG &DAG) {
2460   assert ((Indices.size() % 2) == 0);
2461   int WsIdx = 1;
2462   int WtIdx = ResTy.getVectorNumElements() + 1;
2463
2464   for (unsigned i = 0; i < Indices.size(); i += 2) {
2465     if (Indices[i] != -1 && Indices[i] != WsIdx)
2466       return SDValue();
2467     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2468       return SDValue();
2469     WsIdx += 2;
2470     WtIdx += 2;
2471   }
2472
2473   return DAG.getNode(MipsISD::ILVOD, SDLoc(Op), ResTy, Op->getOperand(0),
2474                      Op->getOperand(1));
2475 }
2476
2477 // Lower VECTOR_SHUFFLE into ILVL (if possible).
2478 //
2479 // ILVL interleaves consecutive elements from the left half of each vector.
2480 //
2481 // It is possible to lower into ILVL when the mask takes the form:
2482 //   <0, n, 1, n+1, 2, n+2, ...>
2483 // where n is the number of elements in the vector.
2484 //
2485 // When undef's appear in the mask they are treated as if they were whatever
2486 // value is necessary in order to fit the above form.
2487 static SDValue lowerVECTOR_SHUFFLE_ILVL(SDValue Op, EVT ResTy,
2488                                         SmallVector<int, 16> Indices,
2489                                         SelectionDAG &DAG) {
2490   assert ((Indices.size() % 2) == 0);
2491   int WsIdx = 0;
2492   int WtIdx = ResTy.getVectorNumElements();
2493
2494   for (unsigned i = 0; i < Indices.size(); i += 2) {
2495     if (Indices[i] != -1 && Indices[i] != WsIdx)
2496       return SDValue();
2497     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2498       return SDValue();
2499     WsIdx ++;
2500     WtIdx ++;
2501   }
2502
2503   return DAG.getNode(MipsISD::ILVL, SDLoc(Op), ResTy, Op->getOperand(0),
2504                      Op->getOperand(1));
2505 }
2506
2507 // Lower VECTOR_SHUFFLE into ILVR (if possible).
2508 //
2509 // ILVR interleaves consecutive elements from the right half of each vector.
2510 //
2511 // It is possible to lower into ILVR when the mask takes the form:
2512 //   <x, n+x, x+1, n+x+1, x+2, n+x+2, ...>
2513 // where n is the number of elements in the vector and x is half n.
2514 //
2515 // When undef's appear in the mask they are treated as if they were whatever
2516 // value is necessary in order to fit the above form.
2517 static SDValue lowerVECTOR_SHUFFLE_ILVR(SDValue Op, EVT ResTy,
2518                                         SmallVector<int, 16> Indices,
2519                                         SelectionDAG &DAG) {
2520   assert ((Indices.size() % 2) == 0);
2521   unsigned NumElts = ResTy.getVectorNumElements();
2522   int WsIdx = NumElts / 2;
2523   int WtIdx = NumElts + NumElts / 2;
2524
2525   for (unsigned i = 0; i < Indices.size(); i += 2) {
2526     if (Indices[i] != -1 && Indices[i] != WsIdx)
2527       return SDValue();
2528     if (Indices[i+1] != -1 && Indices[i+1] != WtIdx)
2529       return SDValue();
2530     WsIdx ++;
2531     WtIdx ++;
2532   }
2533
2534   return DAG.getNode(MipsISD::ILVR, SDLoc(Op), ResTy, Op->getOperand(0),
2535                      Op->getOperand(1));
2536 }
2537
2538 // Lower VECTOR_SHUFFLE into PCKEV (if possible).
2539 //
2540 // PCKEV copies the even elements of each vector into the result vector.
2541 //
2542 // It is possible to lower into PCKEV when the mask takes the form:
2543 //   <0, 2, 4, ..., n, n+2, n+4, ...>
2544 // where n is the number of elements in the vector.
2545 //
2546 // When undef's appear in the mask they are treated as if they were whatever
2547 // value is necessary in order to fit the above form.
2548 static SDValue lowerVECTOR_SHUFFLE_PCKEV(SDValue Op, EVT ResTy,
2549                                          SmallVector<int, 16> Indices,
2550                                          SelectionDAG &DAG) {
2551   assert ((Indices.size() % 2) == 0);
2552   int Idx = 0;
2553
2554   for (unsigned i = 0; i < Indices.size(); ++i) {
2555     if (Indices[i] != -1 && Indices[i] != Idx)
2556       return SDValue();
2557     Idx += 2;
2558   }
2559
2560   return DAG.getNode(MipsISD::PCKEV, SDLoc(Op), ResTy, Op->getOperand(0),
2561                      Op->getOperand(1));
2562 }
2563
2564 // Lower VECTOR_SHUFFLE into PCKOD (if possible).
2565 //
2566 // PCKOD copies the odd elements of each vector into the result vector.
2567 //
2568 // It is possible to lower into PCKOD when the mask takes the form:
2569 //   <1, 3, 5, ..., n+1, n+3, n+5, ...>
2570 // where n is the number of elements in the vector.
2571 //
2572 // When undef's appear in the mask they are treated as if they were whatever
2573 // value is necessary in order to fit the above form.
2574 static SDValue lowerVECTOR_SHUFFLE_PCKOD(SDValue Op, EVT ResTy,
2575                                          SmallVector<int, 16> Indices,
2576                                          SelectionDAG &DAG) {
2577   assert ((Indices.size() % 2) == 0);
2578   int Idx = 1;
2579
2580   for (unsigned i = 0; i < Indices.size(); ++i) {
2581     if (Indices[i] != -1 && Indices[i] != Idx)
2582       return SDValue();
2583     Idx += 2;
2584   }
2585
2586   return DAG.getNode(MipsISD::PCKOD, SDLoc(Op), ResTy, Op->getOperand(0),
2587                      Op->getOperand(1));
2588 }
2589
2590 // Lower VECTOR_SHUFFLE into VSHF.
2591 //
2592 // This mostly consists of converting the shuffle indices in Indices into a
2593 // BUILD_VECTOR and adding it as an operand to the resulting VSHF. There is
2594 // also code to eliminate unused operands of the VECTOR_SHUFFLE. For example,
2595 // if the type is v8i16 and all the indices are less than 8 then the second
2596 // operand is unused and can be replaced with anything. We choose to replace it
2597 // with the used operand since this reduces the number of instructions overall.
2598 static SDValue lowerVECTOR_SHUFFLE_VSHF(SDValue Op, EVT ResTy,
2599                                         SmallVector<int, 16> Indices,
2600                                         SelectionDAG &DAG) {
2601   SmallVector<SDValue, 16> Ops;
2602   SDValue Op0;
2603   SDValue Op1;
2604   EVT MaskVecTy = ResTy.changeVectorElementTypeToInteger();
2605   EVT MaskEltTy = MaskVecTy.getVectorElementType();
2606   bool Using1stVec = false;
2607   bool Using2ndVec = false;
2608   SDLoc DL(Op);
2609   int ResTyNumElts = ResTy.getVectorNumElements();
2610
2611   for (int i = 0; i < ResTyNumElts; ++i) {
2612     // Idx == -1 means UNDEF
2613     int Idx = Indices[i];
2614
2615     if (0 <= Idx && Idx < ResTyNumElts)
2616       Using1stVec = true;
2617     if (ResTyNumElts <= Idx && Idx < ResTyNumElts * 2)
2618       Using2ndVec = true;
2619   }
2620
2621   for (SmallVector<int, 16>::iterator I = Indices.begin(); I != Indices.end();
2622        ++I)
2623     Ops.push_back(DAG.getTargetConstant(*I, MaskEltTy));
2624
2625   SDValue MaskVec = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecTy, Ops);
2626
2627   if (Using1stVec && Using2ndVec) {
2628     Op0 = Op->getOperand(0);
2629     Op1 = Op->getOperand(1);
2630   } else if (Using1stVec)
2631     Op0 = Op1 = Op->getOperand(0);
2632   else if (Using2ndVec)
2633     Op0 = Op1 = Op->getOperand(1);
2634   else
2635     llvm_unreachable("shuffle vector mask references neither vector operand?");
2636
2637   // VECTOR_SHUFFLE concatenates the vectors in an vectorwise fashion.
2638   // <0b00, 0b01> + <0b10, 0b11> -> <0b00, 0b01, 0b10, 0b11>
2639   // VSHF concatenates the vectors in a bitwise fashion:
2640   // <0b00, 0b01> + <0b10, 0b11> ->
2641   // 0b0100       + 0b1110       -> 0b01001110
2642   //                                <0b10, 0b11, 0b00, 0b01>
2643   // We must therefore swap the operands to get the correct result.
2644   return DAG.getNode(MipsISD::VSHF, DL, ResTy, MaskVec, Op1, Op0);
2645 }
2646
2647 // Lower VECTOR_SHUFFLE into one of a number of instructions depending on the
2648 // indices in the shuffle.
2649 SDValue MipsSETargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
2650                                                   SelectionDAG &DAG) const {
2651   ShuffleVectorSDNode *Node = cast<ShuffleVectorSDNode>(Op);
2652   EVT ResTy = Op->getValueType(0);
2653
2654   if (!ResTy.is128BitVector())
2655     return SDValue();
2656
2657   int ResTyNumElts = ResTy.getVectorNumElements();
2658   SmallVector<int, 16> Indices;
2659
2660   for (int i = 0; i < ResTyNumElts; ++i)
2661     Indices.push_back(Node->getMaskElt(i));
2662
2663   SDValue Result = lowerVECTOR_SHUFFLE_SHF(Op, ResTy, Indices, DAG);
2664   if (Result.getNode())
2665     return Result;
2666   Result = lowerVECTOR_SHUFFLE_ILVEV(Op, ResTy, Indices, DAG);
2667   if (Result.getNode())
2668     return Result;
2669   Result = lowerVECTOR_SHUFFLE_ILVOD(Op, ResTy, Indices, DAG);
2670   if (Result.getNode())
2671     return Result;
2672   Result = lowerVECTOR_SHUFFLE_ILVL(Op, ResTy, Indices, DAG);
2673   if (Result.getNode())
2674     return Result;
2675   Result = lowerVECTOR_SHUFFLE_ILVR(Op, ResTy, Indices, DAG);
2676   if (Result.getNode())
2677     return Result;
2678   Result = lowerVECTOR_SHUFFLE_PCKEV(Op, ResTy, Indices, DAG);
2679   if (Result.getNode())
2680     return Result;
2681   Result = lowerVECTOR_SHUFFLE_PCKOD(Op, ResTy, Indices, DAG);
2682   if (Result.getNode())
2683     return Result;
2684   return lowerVECTOR_SHUFFLE_VSHF(Op, ResTy, Indices, DAG);
2685 }
2686
2687 MachineBasicBlock * MipsSETargetLowering::
2688 emitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
2689   // $bb:
2690   //  bposge32_pseudo $vr0
2691   //  =>
2692   // $bb:
2693   //  bposge32 $tbb
2694   // $fbb:
2695   //  li $vr2, 0
2696   //  b $sink
2697   // $tbb:
2698   //  li $vr1, 1
2699   // $sink:
2700   //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
2701
2702   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2703   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2704   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2705   DebugLoc DL = MI->getDebugLoc();
2706   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2707   MachineFunction::iterator It = std::next(MachineFunction::iterator(BB));
2708   MachineFunction *F = BB->getParent();
2709   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2710   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2711   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2712   F->insert(It, FBB);
2713   F->insert(It, TBB);
2714   F->insert(It, Sink);
2715
2716   // Transfer the remainder of BB and its successor edges to Sink.
2717   Sink->splice(Sink->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
2718                BB->end());
2719   Sink->transferSuccessorsAndUpdatePHIs(BB);
2720
2721   // Add successors.
2722   BB->addSuccessor(FBB);
2723   BB->addSuccessor(TBB);
2724   FBB->addSuccessor(Sink);
2725   TBB->addSuccessor(Sink);
2726
2727   // Insert the real bposge32 instruction to $BB.
2728   BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
2729
2730   // Fill $FBB.
2731   unsigned VR2 = RegInfo.createVirtualRegister(RC);
2732   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
2733     .addReg(Mips::ZERO).addImm(0);
2734   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2735
2736   // Fill $TBB.
2737   unsigned VR1 = RegInfo.createVirtualRegister(RC);
2738   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
2739     .addReg(Mips::ZERO).addImm(1);
2740
2741   // Insert phi function to $Sink.
2742   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2743           MI->getOperand(0).getReg())
2744     .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
2745
2746   MI->eraseFromParent();   // The pseudo instruction is gone now.
2747   return Sink;
2748 }
2749
2750 MachineBasicBlock * MipsSETargetLowering::
2751 emitMSACBranchPseudo(MachineInstr *MI, MachineBasicBlock *BB,
2752                      unsigned BranchOp) const{
2753   // $bb:
2754   //  vany_nonzero $rd, $ws
2755   //  =>
2756   // $bb:
2757   //  bnz.b $ws, $tbb
2758   //  b $fbb
2759   // $fbb:
2760   //  li $rd1, 0
2761   //  b $sink
2762   // $tbb:
2763   //  li $rd2, 1
2764   // $sink:
2765   //  $rd = phi($rd1, $fbb, $rd2, $tbb)
2766
2767   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2768   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2769   const TargetRegisterClass *RC = &Mips::GPR32RegClass;
2770   DebugLoc DL = MI->getDebugLoc();
2771   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2772   MachineFunction::iterator It = std::next(MachineFunction::iterator(BB));
2773   MachineFunction *F = BB->getParent();
2774   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
2775   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
2776   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
2777   F->insert(It, FBB);
2778   F->insert(It, TBB);
2779   F->insert(It, Sink);
2780
2781   // Transfer the remainder of BB and its successor edges to Sink.
2782   Sink->splice(Sink->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
2783                BB->end());
2784   Sink->transferSuccessorsAndUpdatePHIs(BB);
2785
2786   // Add successors.
2787   BB->addSuccessor(FBB);
2788   BB->addSuccessor(TBB);
2789   FBB->addSuccessor(Sink);
2790   TBB->addSuccessor(Sink);
2791
2792   // Insert the real bnz.b instruction to $BB.
2793   BuildMI(BB, DL, TII->get(BranchOp))
2794     .addReg(MI->getOperand(1).getReg())
2795     .addMBB(TBB);
2796
2797   // Fill $FBB.
2798   unsigned RD1 = RegInfo.createVirtualRegister(RC);
2799   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), RD1)
2800     .addReg(Mips::ZERO).addImm(0);
2801   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
2802
2803   // Fill $TBB.
2804   unsigned RD2 = RegInfo.createVirtualRegister(RC);
2805   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), RD2)
2806     .addReg(Mips::ZERO).addImm(1);
2807
2808   // Insert phi function to $Sink.
2809   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
2810           MI->getOperand(0).getReg())
2811     .addReg(RD1).addMBB(FBB).addReg(RD2).addMBB(TBB);
2812
2813   MI->eraseFromParent();   // The pseudo instruction is gone now.
2814   return Sink;
2815 }
2816
2817 // Emit the COPY_FW pseudo instruction.
2818 //
2819 // copy_fw_pseudo $fd, $ws, n
2820 // =>
2821 // copy_u_w $rt, $ws, $n
2822 // mtc1     $rt, $fd
2823 //
2824 // When n is zero, the equivalent operation can be performed with (potentially)
2825 // zero instructions due to register overlaps. This optimization is never valid
2826 // for lane 1 because it would require FR=0 mode which isn't supported by MSA.
2827 MachineBasicBlock * MipsSETargetLowering::
2828 emitCOPY_FW(MachineInstr *MI, MachineBasicBlock *BB) const{
2829   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2830   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2831   DebugLoc DL = MI->getDebugLoc();
2832   unsigned Fd = MI->getOperand(0).getReg();
2833   unsigned Ws = MI->getOperand(1).getReg();
2834   unsigned Lane = MI->getOperand(2).getImm();
2835
2836   if (Lane == 0)
2837     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_lo);
2838   else {
2839     unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2840
2841     BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_W), Wt).addReg(Ws).addImm(Lane);
2842     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_lo);
2843   }
2844
2845   MI->eraseFromParent();   // The pseudo instruction is gone now.
2846   return BB;
2847 }
2848
2849 // Emit the COPY_FD pseudo instruction.
2850 //
2851 // copy_fd_pseudo $fd, $ws, n
2852 // =>
2853 // splati.d $wt, $ws, $n
2854 // copy $fd, $wt:sub_64
2855 //
2856 // When n is zero, the equivalent operation can be performed with (potentially)
2857 // zero instructions due to register overlaps. This optimization is always
2858 // valid because FR=1 mode which is the only supported mode in MSA.
2859 MachineBasicBlock * MipsSETargetLowering::
2860 emitCOPY_FD(MachineInstr *MI, MachineBasicBlock *BB) const{
2861   assert(Subtarget->isFP64bit());
2862
2863   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2864   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2865   unsigned Fd  = MI->getOperand(0).getReg();
2866   unsigned Ws  = MI->getOperand(1).getReg();
2867   unsigned Lane = MI->getOperand(2).getImm() * 2;
2868   DebugLoc DL = MI->getDebugLoc();
2869
2870   if (Lane == 0)
2871     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Ws, 0, Mips::sub_64);
2872   else {
2873     unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2874
2875     BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_D), Wt).addReg(Ws).addImm(1);
2876     BuildMI(*BB, MI, DL, TII->get(Mips::COPY), Fd).addReg(Wt, 0, Mips::sub_64);
2877   }
2878
2879   MI->eraseFromParent();   // The pseudo instruction is gone now.
2880   return BB;
2881 }
2882
2883 // Emit the INSERT_FW pseudo instruction.
2884 //
2885 // insert_fw_pseudo $wd, $wd_in, $n, $fs
2886 // =>
2887 // subreg_to_reg $wt:sub_lo, $fs
2888 // insve_w $wd[$n], $wd_in, $wt[0]
2889 MachineBasicBlock *
2890 MipsSETargetLowering::emitINSERT_FW(MachineInstr *MI,
2891                                     MachineBasicBlock *BB) const {
2892   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2893   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2894   DebugLoc DL = MI->getDebugLoc();
2895   unsigned Wd = MI->getOperand(0).getReg();
2896   unsigned Wd_in = MI->getOperand(1).getReg();
2897   unsigned Lane = MI->getOperand(2).getImm();
2898   unsigned Fs = MI->getOperand(3).getReg();
2899   unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
2900
2901   BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2902       .addImm(0)
2903       .addReg(Fs)
2904       .addImm(Mips::sub_lo);
2905   BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_W), Wd)
2906       .addReg(Wd_in)
2907       .addImm(Lane)
2908       .addReg(Wt)
2909       .addImm(0);
2910
2911   MI->eraseFromParent(); // The pseudo instruction is gone now.
2912   return BB;
2913 }
2914
2915 // Emit the INSERT_FD pseudo instruction.
2916 //
2917 // insert_fd_pseudo $wd, $fs, n
2918 // =>
2919 // subreg_to_reg $wt:sub_64, $fs
2920 // insve_d $wd[$n], $wd_in, $wt[0]
2921 MachineBasicBlock *
2922 MipsSETargetLowering::emitINSERT_FD(MachineInstr *MI,
2923                                     MachineBasicBlock *BB) const {
2924   assert(Subtarget->isFP64bit());
2925
2926   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2927   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2928   DebugLoc DL = MI->getDebugLoc();
2929   unsigned Wd = MI->getOperand(0).getReg();
2930   unsigned Wd_in = MI->getOperand(1).getReg();
2931   unsigned Lane = MI->getOperand(2).getImm();
2932   unsigned Fs = MI->getOperand(3).getReg();
2933   unsigned Wt = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
2934
2935   BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
2936       .addImm(0)
2937       .addReg(Fs)
2938       .addImm(Mips::sub_64);
2939   BuildMI(*BB, MI, DL, TII->get(Mips::INSVE_D), Wd)
2940       .addReg(Wd_in)
2941       .addImm(Lane)
2942       .addReg(Wt)
2943       .addImm(0);
2944
2945   MI->eraseFromParent(); // The pseudo instruction is gone now.
2946   return BB;
2947 }
2948
2949 // Emit the INSERT_([BHWD]|F[WD])_VIDX pseudo instruction.
2950 //
2951 // For integer:
2952 // (INSERT_([BHWD]|F[WD])_PSEUDO $wd, $wd_in, $n, $rs)
2953 // =>
2954 // (SLL $lanetmp1, $lane, <log2size)
2955 // (SLD_B $wdtmp1, $wd_in, $wd_in, $lanetmp1)
2956 // (INSERT_[BHWD], $wdtmp2, $wdtmp1, 0, $rs)
2957 // (NEG $lanetmp2, $lanetmp1)
2958 // (SLD_B $wd, $wdtmp2, $wdtmp2,  $lanetmp2)
2959 //
2960 // For floating point:
2961 // (INSERT_([BHWD]|F[WD])_PSEUDO $wd, $wd_in, $n, $fs)
2962 // =>
2963 // (SUBREG_TO_REG $wt, $fs, <subreg>)
2964 // (SLL $lanetmp1, $lane, <log2size)
2965 // (SLD_B $wdtmp1, $wd_in, $wd_in, $lanetmp1)
2966 // (INSVE_[WD], $wdtmp2, 0, $wdtmp1, 0)
2967 // (NEG $lanetmp2, $lanetmp1)
2968 // (SLD_B $wd, $wdtmp2, $wdtmp2,  $lanetmp2)
2969 MachineBasicBlock *
2970 MipsSETargetLowering::emitINSERT_DF_VIDX(MachineInstr *MI,
2971                                          MachineBasicBlock *BB,
2972                                          unsigned EltSizeInBytes,
2973                                          bool IsFP) const {
2974   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2975   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
2976   DebugLoc DL = MI->getDebugLoc();
2977   unsigned Wd = MI->getOperand(0).getReg();
2978   unsigned SrcVecReg = MI->getOperand(1).getReg();
2979   unsigned LaneReg = MI->getOperand(2).getReg();
2980   unsigned SrcValReg = MI->getOperand(3).getReg();
2981
2982   const TargetRegisterClass *VecRC = nullptr;
2983   const TargetRegisterClass *GPRRC = isGP64bit() ? &Mips::GPR64RegClass
2984                                                  : &Mips::GPR32RegClass;
2985   unsigned EltLog2Size;
2986   unsigned InsertOp = 0;
2987   unsigned InsveOp = 0;
2988   switch (EltSizeInBytes) {
2989   default:
2990     llvm_unreachable("Unexpected size");
2991   case 1:
2992     EltLog2Size = 0;
2993     InsertOp = Mips::INSERT_B;
2994     InsveOp = Mips::INSVE_B;
2995     VecRC = &Mips::MSA128BRegClass;
2996     break;
2997   case 2:
2998     EltLog2Size = 1;
2999     InsertOp = Mips::INSERT_H;
3000     InsveOp = Mips::INSVE_H;
3001     VecRC = &Mips::MSA128HRegClass;
3002     break;
3003   case 4:
3004     EltLog2Size = 2;
3005     InsertOp = Mips::INSERT_W;
3006     InsveOp = Mips::INSVE_W;
3007     VecRC = &Mips::MSA128WRegClass;
3008     break;
3009   case 8:
3010     EltLog2Size = 3;
3011     InsertOp = Mips::INSERT_D;
3012     InsveOp = Mips::INSVE_D;
3013     VecRC = &Mips::MSA128DRegClass;
3014     break;
3015   }
3016
3017   if (IsFP) {
3018     unsigned Wt = RegInfo.createVirtualRegister(VecRC);
3019     BuildMI(*BB, MI, DL, TII->get(Mips::SUBREG_TO_REG), Wt)
3020         .addImm(0)
3021         .addReg(SrcValReg)
3022         .addImm(EltSizeInBytes == 8 ? Mips::sub_64 : Mips::sub_lo);
3023     SrcValReg = Wt;
3024   }
3025
3026   // Convert the lane index into a byte index
3027   if (EltSizeInBytes != 1) {
3028     unsigned LaneTmp1 = RegInfo.createVirtualRegister(GPRRC);
3029     BuildMI(*BB, MI, DL, TII->get(Mips::SLL), LaneTmp1)
3030         .addReg(LaneReg)
3031         .addImm(EltLog2Size);
3032     LaneReg = LaneTmp1;
3033   }
3034
3035   // Rotate bytes around so that the desired lane is element zero
3036   unsigned WdTmp1 = RegInfo.createVirtualRegister(VecRC);
3037   BuildMI(*BB, MI, DL, TII->get(Mips::SLD_B), WdTmp1)
3038       .addReg(SrcVecReg)
3039       .addReg(SrcVecReg)
3040       .addReg(LaneReg);
3041
3042   unsigned WdTmp2 = RegInfo.createVirtualRegister(VecRC);
3043   if (IsFP) {
3044     // Use insve.df to insert to element zero
3045     BuildMI(*BB, MI, DL, TII->get(InsveOp), WdTmp2)
3046         .addReg(WdTmp1)
3047         .addImm(0)
3048         .addReg(SrcValReg)
3049         .addImm(0);
3050   } else {
3051     // Use insert.df to insert to element zero
3052     BuildMI(*BB, MI, DL, TII->get(InsertOp), WdTmp2)
3053         .addReg(WdTmp1)
3054         .addReg(SrcValReg)
3055         .addImm(0);
3056   }
3057
3058   // Rotate elements the rest of the way for a full rotation.
3059   // sld.df inteprets $rt modulo the number of columns so we only need to negate
3060   // the lane index to do this.
3061   unsigned LaneTmp2 = RegInfo.createVirtualRegister(GPRRC);
3062   BuildMI(*BB, MI, DL, TII->get(Mips::SUB), LaneTmp2)
3063       .addReg(Mips::ZERO)
3064       .addReg(LaneReg);
3065   BuildMI(*BB, MI, DL, TII->get(Mips::SLD_B), Wd)
3066       .addReg(WdTmp2)
3067       .addReg(WdTmp2)
3068       .addReg(LaneTmp2);
3069
3070   MI->eraseFromParent(); // The pseudo instruction is gone now.
3071   return BB;
3072 }
3073
3074 // Emit the FILL_FW pseudo instruction.
3075 //
3076 // fill_fw_pseudo $wd, $fs
3077 // =>
3078 // implicit_def $wt1
3079 // insert_subreg $wt2:subreg_lo, $wt1, $fs
3080 // splati.w $wd, $wt2[0]
3081 MachineBasicBlock *
3082 MipsSETargetLowering::emitFILL_FW(MachineInstr *MI,
3083                                   MachineBasicBlock *BB) const {
3084   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3085   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3086   DebugLoc DL = MI->getDebugLoc();
3087   unsigned Wd = MI->getOperand(0).getReg();
3088   unsigned Fs = MI->getOperand(1).getReg();
3089   unsigned Wt1 = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
3090   unsigned Wt2 = RegInfo.createVirtualRegister(&Mips::MSA128WRegClass);
3091
3092   BuildMI(*BB, MI, DL, TII->get(Mips::IMPLICIT_DEF), Wt1);
3093   BuildMI(*BB, MI, DL, TII->get(Mips::INSERT_SUBREG), Wt2)
3094       .addReg(Wt1)
3095       .addReg(Fs)
3096       .addImm(Mips::sub_lo);
3097   BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_W), Wd).addReg(Wt2).addImm(0);
3098
3099   MI->eraseFromParent(); // The pseudo instruction is gone now.
3100   return BB;
3101 }
3102
3103 // Emit the FILL_FD pseudo instruction.
3104 //
3105 // fill_fd_pseudo $wd, $fs
3106 // =>
3107 // implicit_def $wt1
3108 // insert_subreg $wt2:subreg_64, $wt1, $fs
3109 // splati.d $wd, $wt2[0]
3110 MachineBasicBlock *
3111 MipsSETargetLowering::emitFILL_FD(MachineInstr *MI,
3112                                   MachineBasicBlock *BB) const {
3113   assert(Subtarget->isFP64bit());
3114
3115   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3116   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3117   DebugLoc DL = MI->getDebugLoc();
3118   unsigned Wd = MI->getOperand(0).getReg();
3119   unsigned Fs = MI->getOperand(1).getReg();
3120   unsigned Wt1 = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
3121   unsigned Wt2 = RegInfo.createVirtualRegister(&Mips::MSA128DRegClass);
3122
3123   BuildMI(*BB, MI, DL, TII->get(Mips::IMPLICIT_DEF), Wt1);
3124   BuildMI(*BB, MI, DL, TII->get(Mips::INSERT_SUBREG), Wt2)
3125       .addReg(Wt1)
3126       .addReg(Fs)
3127       .addImm(Mips::sub_64);
3128   BuildMI(*BB, MI, DL, TII->get(Mips::SPLATI_D), Wd).addReg(Wt2).addImm(0);
3129
3130   MI->eraseFromParent();   // The pseudo instruction is gone now.
3131   return BB;
3132 }
3133
3134 // Emit the FEXP2_W_1 pseudo instructions.
3135 //
3136 // fexp2_w_1_pseudo $wd, $wt
3137 // =>
3138 // ldi.w $ws, 1
3139 // fexp2.w $wd, $ws, $wt
3140 MachineBasicBlock *
3141 MipsSETargetLowering::emitFEXP2_W_1(MachineInstr *MI,
3142                                     MachineBasicBlock *BB) const {
3143   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3144   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3145   const TargetRegisterClass *RC = &Mips::MSA128WRegClass;
3146   unsigned Ws1 = RegInfo.createVirtualRegister(RC);
3147   unsigned Ws2 = RegInfo.createVirtualRegister(RC);
3148   DebugLoc DL = MI->getDebugLoc();
3149
3150   // Splat 1.0 into a vector
3151   BuildMI(*BB, MI, DL, TII->get(Mips::LDI_W), Ws1).addImm(1);
3152   BuildMI(*BB, MI, DL, TII->get(Mips::FFINT_U_W), Ws2).addReg(Ws1);
3153
3154   // Emit 1.0 * fexp2(Wt)
3155   BuildMI(*BB, MI, DL, TII->get(Mips::FEXP2_W), MI->getOperand(0).getReg())
3156       .addReg(Ws2)
3157       .addReg(MI->getOperand(1).getReg());
3158
3159   MI->eraseFromParent(); // The pseudo instruction is gone now.
3160   return BB;
3161 }
3162
3163 // Emit the FEXP2_D_1 pseudo instructions.
3164 //
3165 // fexp2_d_1_pseudo $wd, $wt
3166 // =>
3167 // ldi.d $ws, 1
3168 // fexp2.d $wd, $ws, $wt
3169 MachineBasicBlock *
3170 MipsSETargetLowering::emitFEXP2_D_1(MachineInstr *MI,
3171                                     MachineBasicBlock *BB) const {
3172   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3173   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
3174   const TargetRegisterClass *RC = &Mips::MSA128DRegClass;
3175   unsigned Ws1 = RegInfo.createVirtualRegister(RC);
3176   unsigned Ws2 = RegInfo.createVirtualRegister(RC);
3177   DebugLoc DL = MI->getDebugLoc();
3178
3179   // Splat 1.0 into a vector
3180   BuildMI(*BB, MI, DL, TII->get(Mips::LDI_D), Ws1).addImm(1);
3181   BuildMI(*BB, MI, DL, TII->get(Mips::FFINT_U_D), Ws2).addReg(Ws1);
3182
3183   // Emit 1.0 * fexp2(Wt)
3184   BuildMI(*BB, MI, DL, TII->get(Mips::FEXP2_D), MI->getOperand(0).getReg())
3185       .addReg(Ws2)
3186       .addReg(MI->getOperand(1).getReg());
3187
3188   MI->eraseFromParent(); // The pseudo instruction is gone now.
3189   return BB;
3190 }