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