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