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