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