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