1 //===-- MipsSEISelDAGToDAG.cpp - A Dag to Dag Inst Selector for MipsSE ----===//
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 MipsDAGToDAGISel specialized for mips32/64.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsSEISelDAGToDAG.h"
15 #include "MCTargetDesc/MipsBaseInfo.h"
16 #include "Mips.h"
17 #include "MipsAnalyzeImmediate.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsRegisterInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAGNodes.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "mips-isel"
38 
39 bool MipsSEDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
40   Subtarget = &static_cast<const MipsSubtarget &>(MF.getSubtarget());
41   if (Subtarget->inMips16Mode())
42     return false;
43   return MipsDAGToDAGISel::runOnMachineFunction(MF);
44 }
45 
46 void MipsSEDAGToDAGISel::addDSPCtrlRegOperands(bool IsDef, MachineInstr &MI,
47                                                MachineFunction &MF) {
48   MachineInstrBuilder MIB(MF, &MI);
49   unsigned Mask = MI.getOperand(1).getImm();
50   unsigned Flag =
51       IsDef ? RegState::ImplicitDefine : RegState::Implicit | RegState::Undef;
52 
53   if (Mask & 1)
54     MIB.addReg(Mips::DSPPos, Flag);
55 
56   if (Mask & 2)
57     MIB.addReg(Mips::DSPSCount, Flag);
58 
59   if (Mask & 4)
60     MIB.addReg(Mips::DSPCarry, Flag);
61 
62   if (Mask & 8)
63     MIB.addReg(Mips::DSPOutFlag, Flag);
64 
65   if (Mask & 16)
66     MIB.addReg(Mips::DSPCCond, Flag);
67 
68   if (Mask & 32)
69     MIB.addReg(Mips::DSPEFI, Flag);
70 }
71 
72 unsigned MipsSEDAGToDAGISel::getMSACtrlReg(const SDValue RegIdx) const {
73   switch (cast<ConstantSDNode>(RegIdx)->getZExtValue()) {
74   default:
75     llvm_unreachable("Could not map int to register");
76   case 0: return Mips::MSAIR;
77   case 1: return Mips::MSACSR;
78   case 2: return Mips::MSAAccess;
79   case 3: return Mips::MSASave;
80   case 4: return Mips::MSAModify;
81   case 5: return Mips::MSARequest;
82   case 6: return Mips::MSAMap;
83   case 7: return Mips::MSAUnmap;
84   }
85 }
86 
87 bool MipsSEDAGToDAGISel::replaceUsesWithZeroReg(MachineRegisterInfo *MRI,
88                                                 const MachineInstr& MI) {
89   unsigned DstReg = 0, ZeroReg = 0;
90 
91   // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
92   if ((MI.getOpcode() == Mips::ADDiu) &&
93       (MI.getOperand(1).getReg() == Mips::ZERO) &&
94       (MI.getOperand(2).getImm() == 0)) {
95     DstReg = MI.getOperand(0).getReg();
96     ZeroReg = Mips::ZERO;
97   } else if ((MI.getOpcode() == Mips::DADDiu) &&
98              (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
99              (MI.getOperand(2).getImm() == 0)) {
100     DstReg = MI.getOperand(0).getReg();
101     ZeroReg = Mips::ZERO_64;
102   }
103 
104   if (!DstReg)
105     return false;
106 
107   // Replace uses with ZeroReg.
108   for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
109        E = MRI->use_end(); U != E;) {
110     MachineOperand &MO = *U;
111     unsigned OpNo = U.getOperandNo();
112     MachineInstr *MI = MO.getParent();
113     ++U;
114 
115     // Do not replace if it is a phi's operand or is tied to def operand.
116     if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
117       continue;
118 
119     // Also, we have to check that the register class of the operand
120     // contains the zero register.
121     if (!MRI->getRegClass(MO.getReg())->contains(ZeroReg))
122       continue;
123 
124     MO.setReg(ZeroReg);
125   }
126 
127   return true;
128 }
129 
130 void MipsSEDAGToDAGISel::initGlobalBaseReg(MachineFunction &MF) {
131   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
132 
133   if (!MipsFI->globalBaseRegSet())
134     return;
135 
136   MachineBasicBlock &MBB = MF.front();
137   MachineBasicBlock::iterator I = MBB.begin();
138   MachineRegisterInfo &RegInfo = MF.getRegInfo();
139   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
140   DebugLoc DL;
141   unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
142   const TargetRegisterClass *RC;
143   const MipsABIInfo &ABI = static_cast<const MipsTargetMachine &>(TM).getABI();
144   RC = (ABI.IsN64()) ? &Mips::GPR64RegClass : &Mips::GPR32RegClass;
145 
146   V0 = RegInfo.createVirtualRegister(RC);
147   V1 = RegInfo.createVirtualRegister(RC);
148 
149   if (ABI.IsN64()) {
150     MF.getRegInfo().addLiveIn(Mips::T9_64);
151     MBB.addLiveIn(Mips::T9_64);
152 
153     // lui $v0, %hi(%neg(%gp_rel(fname)))
154     // daddu $v1, $v0, $t9
155     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
156     const GlobalValue *FName = MF.getFunction();
157     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
158       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
159     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
160       .addReg(Mips::T9_64);
161     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
162       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
163     return;
164   }
165 
166   if (!MF.getTarget().isPositionIndependent()) {
167     // Set global register to __gnu_local_gp.
168     //
169     // lui   $v0, %hi(__gnu_local_gp)
170     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
171     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
172       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
173     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
174       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
175     return;
176   }
177 
178   MF.getRegInfo().addLiveIn(Mips::T9);
179   MBB.addLiveIn(Mips::T9);
180 
181   if (ABI.IsN32()) {
182     // lui $v0, %hi(%neg(%gp_rel(fname)))
183     // addu $v1, $v0, $t9
184     // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
185     const GlobalValue *FName = MF.getFunction();
186     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
187       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
188     BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
189     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
190       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
191     return;
192   }
193 
194   assert(ABI.IsO32());
195 
196   // For O32 ABI, the following instruction sequence is emitted to initialize
197   // the global base register:
198   //
199   //  0. lui   $2, %hi(_gp_disp)
200   //  1. addiu $2, $2, %lo(_gp_disp)
201   //  2. addu  $globalbasereg, $2, $t9
202   //
203   // We emit only the last instruction here.
204   //
205   // GNU linker requires that the first two instructions appear at the beginning
206   // of a function and no instructions be inserted before or between them.
207   // The two instructions are emitted during lowering to MC layer in order to
208   // avoid any reordering.
209   //
210   // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
211   // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
212   // reads it.
213   MF.getRegInfo().addLiveIn(Mips::V0);
214   MBB.addLiveIn(Mips::V0);
215   BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
216     .addReg(Mips::V0).addReg(Mips::T9);
217 }
218 
219 void MipsSEDAGToDAGISel::processFunctionAfterISel(MachineFunction &MF) {
220   initGlobalBaseReg(MF);
221 
222   MachineRegisterInfo *MRI = &MF.getRegInfo();
223 
224   for (auto &MBB: MF) {
225     for (auto &MI: MBB) {
226       switch (MI.getOpcode()) {
227       case Mips::RDDSP:
228         addDSPCtrlRegOperands(false, MI, MF);
229         break;
230       case Mips::WRDSP:
231         addDSPCtrlRegOperands(true, MI, MF);
232         break;
233       default:
234         replaceUsesWithZeroReg(MRI, MI);
235       }
236     }
237   }
238 }
239 
240 void MipsSEDAGToDAGISel::selectAddESubE(unsigned MOp, SDValue InFlag,
241                                         SDValue CmpLHS, const SDLoc &DL,
242                                         SDNode *Node) const {
243   unsigned Opc = InFlag.getOpcode(); (void)Opc;
244 
245   assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
246           (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
247          "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
248 
249   unsigned SLTuOp = Mips::SLTu, ADDuOp = Mips::ADDu;
250   if (Subtarget->isGP64bit()) {
251     SLTuOp = Mips::SLTu64;
252     ADDuOp = Mips::DADDu;
253   }
254 
255   SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
256   SDValue LHS = Node->getOperand(0), RHS = Node->getOperand(1);
257   EVT VT = LHS.getValueType();
258 
259   SDNode *Carry = CurDAG->getMachineNode(SLTuOp, DL, VT, Ops);
260 
261   if (Subtarget->isGP64bit()) {
262     // On 64-bit targets, sltu produces an i64 but our backend currently says
263     // that SLTu64 produces an i32. We need to fix this in the long run but for
264     // now, just make the DAG type-correct by asserting the upper bits are zero.
265     Carry = CurDAG->getMachineNode(Mips::SUBREG_TO_REG, DL, VT,
266                                    CurDAG->getTargetConstant(0, DL, VT),
267                                    SDValue(Carry, 0),
268                                    CurDAG->getTargetConstant(Mips::sub_32, DL,
269                                                              VT));
270   }
271 
272   // Generate a second addition only if we know that RHS is not a
273   // constant-zero node.
274   SDNode *AddCarry = Carry;
275   ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
276   if (!C || C->getZExtValue())
277     AddCarry = CurDAG->getMachineNode(ADDuOp, DL, VT, SDValue(Carry, 0), RHS);
278 
279   CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS, SDValue(AddCarry, 0));
280 }
281 
282 /// Match frameindex
283 bool MipsSEDAGToDAGISel::selectAddrFrameIndex(SDValue Addr, SDValue &Base,
284                                               SDValue &Offset) const {
285   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
286     EVT ValTy = Addr.getValueType();
287 
288     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
289     Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), ValTy);
290     return true;
291   }
292   return false;
293 }
294 
295 /// Match frameindex+offset and frameindex|offset
296 bool MipsSEDAGToDAGISel::selectAddrFrameIndexOffset(SDValue Addr, SDValue &Base,
297                                                     SDValue &Offset,
298                                                     unsigned OffsetBits) const {
299   if (CurDAG->isBaseWithConstantOffset(Addr)) {
300     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
301     if (isIntN(OffsetBits, CN->getSExtValue())) {
302       EVT ValTy = Addr.getValueType();
303 
304       // If the first operand is a FI, get the TargetFI Node
305       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
306                                   (Addr.getOperand(0)))
307         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
308       else
309         Base = Addr.getOperand(0);
310 
311       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(Addr),
312                                          ValTy);
313       return true;
314     }
315   }
316   return false;
317 }
318 
319 /// ComplexPattern used on MipsInstrInfo
320 /// Used on Mips Load/Store instructions
321 bool MipsSEDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
322                                           SDValue &Offset) const {
323   // if Address is FI, get the TargetFrameIndex.
324   if (selectAddrFrameIndex(Addr, Base, Offset))
325     return true;
326 
327   // on PIC code Load GA
328   if (Addr.getOpcode() == MipsISD::Wrapper) {
329     Base   = Addr.getOperand(0);
330     Offset = Addr.getOperand(1);
331     return true;
332   }
333 
334   if (!TM.isPositionIndependent()) {
335     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
336         Addr.getOpcode() == ISD::TargetGlobalAddress))
337       return false;
338   }
339 
340   // Addresses of the form FI+const or FI|const
341   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 16))
342     return true;
343 
344   // Operand is a result from an ADD.
345   if (Addr.getOpcode() == ISD::ADD) {
346     // When loading from constant pools, load the lower address part in
347     // the instruction itself. Example, instead of:
348     //  lui $2, %hi($CPI1_0)
349     //  addiu $2, $2, %lo($CPI1_0)
350     //  lwc1 $f0, 0($2)
351     // Generate:
352     //  lui $2, %hi($CPI1_0)
353     //  lwc1 $f0, %lo($CPI1_0)($2)
354     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
355         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
356       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
357       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
358           isa<JumpTableSDNode>(Opnd0)) {
359         Base = Addr.getOperand(0);
360         Offset = Opnd0;
361         return true;
362       }
363     }
364   }
365 
366   return false;
367 }
368 
369 /// ComplexPattern used on MipsInstrInfo
370 /// Used on Mips Load/Store instructions
371 bool MipsSEDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
372                                            SDValue &Offset) const {
373   Base = Addr;
374   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), Addr.getValueType());
375   return true;
376 }
377 
378 bool MipsSEDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
379                                        SDValue &Offset) const {
380   return selectAddrRegImm(Addr, Base, Offset) ||
381     selectAddrDefault(Addr, Base, Offset);
382 }
383 
384 bool MipsSEDAGToDAGISel::selectAddrRegImm9(SDValue Addr, SDValue &Base,
385                                            SDValue &Offset) const {
386   if (selectAddrFrameIndex(Addr, Base, Offset))
387     return true;
388 
389   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 9))
390     return true;
391 
392   return false;
393 }
394 
395 bool MipsSEDAGToDAGISel::selectAddrRegImm10(SDValue Addr, SDValue &Base,
396                                             SDValue &Offset) const {
397   if (selectAddrFrameIndex(Addr, Base, Offset))
398     return true;
399 
400   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 10))
401     return true;
402 
403   return false;
404 }
405 
406 /// Used on microMIPS Load/Store unaligned instructions (12-bit offset)
407 bool MipsSEDAGToDAGISel::selectAddrRegImm12(SDValue Addr, SDValue &Base,
408                                             SDValue &Offset) const {
409   if (selectAddrFrameIndex(Addr, Base, Offset))
410     return true;
411 
412   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 12))
413     return true;
414 
415   return false;
416 }
417 
418 bool MipsSEDAGToDAGISel::selectAddrRegImm16(SDValue Addr, SDValue &Base,
419                                             SDValue &Offset) const {
420   if (selectAddrFrameIndex(Addr, Base, Offset))
421     return true;
422 
423   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 16))
424     return true;
425 
426   return false;
427 }
428 
429 bool MipsSEDAGToDAGISel::selectIntAddrMM(SDValue Addr, SDValue &Base,
430                                          SDValue &Offset) const {
431   return selectAddrRegImm12(Addr, Base, Offset) ||
432     selectAddrDefault(Addr, Base, Offset);
433 }
434 
435 bool MipsSEDAGToDAGISel::selectIntAddrLSL2MM(SDValue Addr, SDValue &Base,
436                                              SDValue &Offset) const {
437   if (selectAddrFrameIndexOffset(Addr, Base, Offset, 7)) {
438     if (isa<FrameIndexSDNode>(Base))
439       return false;
440 
441     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Offset)) {
442       unsigned CnstOff = CN->getZExtValue();
443       return (CnstOff == (CnstOff & 0x3c));
444     }
445 
446     return false;
447   }
448 
449   // For all other cases where "lw" would be selected, don't select "lw16"
450   // because it would result in additional instructions to prepare operands.
451   if (selectAddrRegImm(Addr, Base, Offset))
452     return false;
453 
454   return selectAddrDefault(Addr, Base, Offset);
455 }
456 
457 bool MipsSEDAGToDAGISel::selectIntAddrMSA(SDValue Addr, SDValue &Base,
458                                           SDValue &Offset) const {
459   if (selectAddrRegImm10(Addr, Base, Offset))
460     return true;
461 
462   if (selectAddrDefault(Addr, Base, Offset))
463     return true;
464 
465   return false;
466 }
467 
468 // Select constant vector splats.
469 //
470 // Returns true and sets Imm if:
471 // * MSA is enabled
472 // * N is a ISD::BUILD_VECTOR representing a constant splat
473 bool MipsSEDAGToDAGISel::selectVSplat(SDNode *N, APInt &Imm,
474                                       unsigned MinSizeInBits) const {
475   if (!Subtarget->hasMSA())
476     return false;
477 
478   BuildVectorSDNode *Node = dyn_cast<BuildVectorSDNode>(N);
479 
480   if (!Node)
481     return false;
482 
483   APInt SplatValue, SplatUndef;
484   unsigned SplatBitSize;
485   bool HasAnyUndefs;
486 
487   if (!Node->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs,
488                              MinSizeInBits, !Subtarget->isLittle()))
489     return false;
490 
491   Imm = SplatValue;
492 
493   return true;
494 }
495 
496 // Select constant vector splats.
497 //
498 // In addition to the requirements of selectVSplat(), this function returns
499 // true and sets Imm if:
500 // * The splat value is the same width as the elements of the vector
501 // * The splat value fits in an integer with the specified signed-ness and
502 //   width.
503 //
504 // This function looks through ISD::BITCAST nodes.
505 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
506 //       sometimes a shuffle in big-endian mode.
507 //
508 // It's worth noting that this function is not used as part of the selection
509 // of ldi.[bhwd] since it does not permit using the wrong-typed ldi.[bhwd]
510 // instruction to achieve the desired bit pattern. ldi.[bhwd] is selected in
511 // MipsSEDAGToDAGISel::selectNode.
512 bool MipsSEDAGToDAGISel::
513 selectVSplatCommon(SDValue N, SDValue &Imm, bool Signed,
514                    unsigned ImmBitSize) const {
515   APInt ImmValue;
516   EVT EltTy = N->getValueType(0).getVectorElementType();
517 
518   if (N->getOpcode() == ISD::BITCAST)
519     N = N->getOperand(0);
520 
521   if (selectVSplat(N.getNode(), ImmValue, EltTy.getSizeInBits()) &&
522       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
523 
524     if (( Signed && ImmValue.isSignedIntN(ImmBitSize)) ||
525         (!Signed && ImmValue.isIntN(ImmBitSize))) {
526       Imm = CurDAG->getTargetConstant(ImmValue, SDLoc(N), EltTy);
527       return true;
528     }
529   }
530 
531   return false;
532 }
533 
534 // Select constant vector splats.
535 bool MipsSEDAGToDAGISel::
536 selectVSplatUimm1(SDValue N, SDValue &Imm) const {
537   return selectVSplatCommon(N, Imm, false, 1);
538 }
539 
540 bool MipsSEDAGToDAGISel::
541 selectVSplatUimm2(SDValue N, SDValue &Imm) const {
542   return selectVSplatCommon(N, Imm, false, 2);
543 }
544 
545 bool MipsSEDAGToDAGISel::
546 selectVSplatUimm3(SDValue N, SDValue &Imm) const {
547   return selectVSplatCommon(N, Imm, false, 3);
548 }
549 
550 // Select constant vector splats.
551 bool MipsSEDAGToDAGISel::
552 selectVSplatUimm4(SDValue N, SDValue &Imm) const {
553   return selectVSplatCommon(N, Imm, false, 4);
554 }
555 
556 // Select constant vector splats.
557 bool MipsSEDAGToDAGISel::
558 selectVSplatUimm5(SDValue N, SDValue &Imm) const {
559   return selectVSplatCommon(N, Imm, false, 5);
560 }
561 
562 // Select constant vector splats.
563 bool MipsSEDAGToDAGISel::
564 selectVSplatUimm6(SDValue N, SDValue &Imm) const {
565   return selectVSplatCommon(N, Imm, false, 6);
566 }
567 
568 // Select constant vector splats.
569 bool MipsSEDAGToDAGISel::
570 selectVSplatUimm8(SDValue N, SDValue &Imm) const {
571   return selectVSplatCommon(N, Imm, false, 8);
572 }
573 
574 // Select constant vector splats.
575 bool MipsSEDAGToDAGISel::
576 selectVSplatSimm5(SDValue N, SDValue &Imm) const {
577   return selectVSplatCommon(N, Imm, true, 5);
578 }
579 
580 // Select constant vector splats whose value is a power of 2.
581 //
582 // In addition to the requirements of selectVSplat(), this function returns
583 // true and sets Imm if:
584 // * The splat value is the same width as the elements of the vector
585 // * The splat value is a power of two.
586 //
587 // This function looks through ISD::BITCAST nodes.
588 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
589 //       sometimes a shuffle in big-endian mode.
590 bool MipsSEDAGToDAGISel::selectVSplatUimmPow2(SDValue N, SDValue &Imm) const {
591   APInt ImmValue;
592   EVT EltTy = N->getValueType(0).getVectorElementType();
593 
594   if (N->getOpcode() == ISD::BITCAST)
595     N = N->getOperand(0);
596 
597   if (selectVSplat(N.getNode(), ImmValue, EltTy.getSizeInBits()) &&
598       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
599     int32_t Log2 = ImmValue.exactLogBase2();
600 
601     if (Log2 != -1) {
602       Imm = CurDAG->getTargetConstant(Log2, SDLoc(N), EltTy);
603       return true;
604     }
605   }
606 
607   return false;
608 }
609 
610 // Select constant vector splats whose value only has a consecutive sequence
611 // of left-most bits set (e.g. 0b11...1100...00).
612 //
613 // In addition to the requirements of selectVSplat(), this function returns
614 // true and sets Imm if:
615 // * The splat value is the same width as the elements of the vector
616 // * The splat value is a consecutive sequence of left-most bits.
617 //
618 // This function looks through ISD::BITCAST nodes.
619 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
620 //       sometimes a shuffle in big-endian mode.
621 bool MipsSEDAGToDAGISel::selectVSplatMaskL(SDValue N, SDValue &Imm) const {
622   APInt ImmValue;
623   EVT EltTy = N->getValueType(0).getVectorElementType();
624 
625   if (N->getOpcode() == ISD::BITCAST)
626     N = N->getOperand(0);
627 
628   if (selectVSplat(N.getNode(), ImmValue, EltTy.getSizeInBits()) &&
629       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
630     // Extract the run of set bits starting with bit zero from the bitwise
631     // inverse of ImmValue, and test that the inverse of this is the same
632     // as the original value.
633     if (ImmValue == ~(~ImmValue & ~(~ImmValue + 1))) {
634 
635       Imm = CurDAG->getTargetConstant(ImmValue.countPopulation(), SDLoc(N),
636                                       EltTy);
637       return true;
638     }
639   }
640 
641   return false;
642 }
643 
644 // Select constant vector splats whose value only has a consecutive sequence
645 // of right-most bits set (e.g. 0b00...0011...11).
646 //
647 // In addition to the requirements of selectVSplat(), this function returns
648 // true and sets Imm if:
649 // * The splat value is the same width as the elements of the vector
650 // * The splat value is a consecutive sequence of right-most bits.
651 //
652 // This function looks through ISD::BITCAST nodes.
653 // TODO: This might not be appropriate for big-endian MSA since BITCAST is
654 //       sometimes a shuffle in big-endian mode.
655 bool MipsSEDAGToDAGISel::selectVSplatMaskR(SDValue N, SDValue &Imm) const {
656   APInt ImmValue;
657   EVT EltTy = N->getValueType(0).getVectorElementType();
658 
659   if (N->getOpcode() == ISD::BITCAST)
660     N = N->getOperand(0);
661 
662   if (selectVSplat(N.getNode(), ImmValue, EltTy.getSizeInBits()) &&
663       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
664     // Extract the run of set bits starting with bit zero, and test that the
665     // result is the same as the original value
666     if (ImmValue == (ImmValue & ~(ImmValue + 1))) {
667       Imm = CurDAG->getTargetConstant(ImmValue.countPopulation(), SDLoc(N),
668                                       EltTy);
669       return true;
670     }
671   }
672 
673   return false;
674 }
675 
676 bool MipsSEDAGToDAGISel::selectVSplatUimmInvPow2(SDValue N,
677                                                  SDValue &Imm) const {
678   APInt ImmValue;
679   EVT EltTy = N->getValueType(0).getVectorElementType();
680 
681   if (N->getOpcode() == ISD::BITCAST)
682     N = N->getOperand(0);
683 
684   if (selectVSplat(N.getNode(), ImmValue, EltTy.getSizeInBits()) &&
685       ImmValue.getBitWidth() == EltTy.getSizeInBits()) {
686     int32_t Log2 = (~ImmValue).exactLogBase2();
687 
688     if (Log2 != -1) {
689       Imm = CurDAG->getTargetConstant(Log2, SDLoc(N), EltTy);
690       return true;
691     }
692   }
693 
694   return false;
695 }
696 
697 bool MipsSEDAGToDAGISel::trySelect(SDNode *Node) {
698   unsigned Opcode = Node->getOpcode();
699   SDLoc DL(Node);
700 
701   ///
702   // Instruction Selection not handled by the auto-generated
703   // tablegen selection should be handled here.
704   ///
705   switch(Opcode) {
706   default: break;
707 
708   case ISD::SUBE: {
709     SDValue InFlag = Node->getOperand(2);
710     unsigned Opc = Subtarget->isGP64bit() ? Mips::DSUBu : Mips::SUBu;
711     selectAddESubE(Opc, InFlag, InFlag.getOperand(0), DL, Node);
712     return true;
713   }
714 
715   case ISD::ADDE: {
716     if (Subtarget->hasDSP()) // Select DSP instructions, ADDSC and ADDWC.
717       break;
718     SDValue InFlag = Node->getOperand(2);
719     unsigned Opc = Subtarget->isGP64bit() ? Mips::DADDu : Mips::ADDu;
720     selectAddESubE(Opc, InFlag, InFlag.getValue(0), DL, Node);
721     return true;
722   }
723 
724   case ISD::ConstantFP: {
725     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
726     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
727       if (Subtarget->isGP64bit()) {
728         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
729                                               Mips::ZERO_64, MVT::i64);
730         ReplaceNode(Node,
731                     CurDAG->getMachineNode(Mips::DMTC1, DL, MVT::f64, Zero));
732       } else if (Subtarget->isFP64bit()) {
733         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
734                                               Mips::ZERO, MVT::i32);
735         ReplaceNode(Node, CurDAG->getMachineNode(Mips::BuildPairF64_64, DL,
736                                                  MVT::f64, Zero, Zero));
737       } else {
738         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
739                                               Mips::ZERO, MVT::i32);
740         ReplaceNode(Node, CurDAG->getMachineNode(Mips::BuildPairF64, DL,
741                                                  MVT::f64, Zero, Zero));
742       }
743       return true;
744     }
745     break;
746   }
747 
748   case ISD::Constant: {
749     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
750     unsigned Size = CN->getValueSizeInBits(0);
751 
752     if (Size == 32)
753       break;
754 
755     MipsAnalyzeImmediate AnalyzeImm;
756     int64_t Imm = CN->getSExtValue();
757 
758     const MipsAnalyzeImmediate::InstSeq &Seq =
759       AnalyzeImm.Analyze(Imm, Size, false);
760 
761     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
762     SDLoc DL(CN);
763     SDNode *RegOpnd;
764     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
765                                                 DL, MVT::i64);
766 
767     // The first instruction can be a LUi which is different from other
768     // instructions (ADDiu, ORI and SLL) in that it does not have a register
769     // operand.
770     if (Inst->Opc == Mips::LUi64)
771       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
772     else
773       RegOpnd =
774         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
775                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
776                                ImmOpnd);
777 
778     // The remaining instructions in the sequence are handled here.
779     for (++Inst; Inst != Seq.end(); ++Inst) {
780       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd), DL,
781                                           MVT::i64);
782       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
783                                        SDValue(RegOpnd, 0), ImmOpnd);
784     }
785 
786     ReplaceNode(Node, RegOpnd);
787     return true;
788   }
789 
790   case ISD::INTRINSIC_W_CHAIN: {
791     switch (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
792     default:
793       break;
794 
795     case Intrinsic::mips_cfcmsa: {
796       SDValue ChainIn = Node->getOperand(0);
797       SDValue RegIdx = Node->getOperand(2);
798       SDValue Reg = CurDAG->getCopyFromReg(ChainIn, DL,
799                                            getMSACtrlReg(RegIdx), MVT::i32);
800       ReplaceNode(Node, Reg.getNode());
801       return true;
802     }
803     }
804     break;
805   }
806 
807   case ISD::INTRINSIC_WO_CHAIN: {
808     switch (cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue()) {
809     default:
810       break;
811 
812     case Intrinsic::mips_move_v:
813       // Like an assignment but will always produce a move.v even if
814       // unnecessary.
815       ReplaceNode(Node, CurDAG->getMachineNode(Mips::MOVE_V, DL,
816                                                Node->getValueType(0),
817                                                Node->getOperand(1)));
818       return true;
819     }
820     break;
821   }
822 
823   case ISD::INTRINSIC_VOID: {
824     switch (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
825     default:
826       break;
827 
828     case Intrinsic::mips_ctcmsa: {
829       SDValue ChainIn = Node->getOperand(0);
830       SDValue RegIdx  = Node->getOperand(2);
831       SDValue Value   = Node->getOperand(3);
832       SDValue ChainOut = CurDAG->getCopyToReg(ChainIn, DL,
833                                               getMSACtrlReg(RegIdx), Value);
834       ReplaceNode(Node, ChainOut.getNode());
835       return true;
836     }
837     }
838     break;
839   }
840 
841   case MipsISD::ThreadPointer: {
842     EVT PtrVT = getTargetLowering()->getPointerTy(CurDAG->getDataLayout());
843     unsigned RdhwrOpc, DestReg;
844 
845     if (PtrVT == MVT::i32) {
846       RdhwrOpc = Mips::RDHWR;
847       DestReg = Mips::V1;
848     } else {
849       RdhwrOpc = Mips::RDHWR64;
850       DestReg = Mips::V1_64;
851     }
852 
853     SDNode *Rdhwr =
854       CurDAG->getMachineNode(RdhwrOpc, DL,
855                              Node->getValueType(0),
856                              CurDAG->getRegister(Mips::HWR29, MVT::i32));
857     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, DestReg,
858                                          SDValue(Rdhwr, 0));
859     SDValue ResNode = CurDAG->getCopyFromReg(Chain, DL, DestReg, PtrVT);
860     ReplaceNode(Node, ResNode.getNode());
861     return true;
862   }
863 
864   case ISD::BUILD_VECTOR: {
865     // Select appropriate ldi.[bhwd] instructions for constant splats of
866     // 128-bit when MSA is enabled. Fixup any register class mismatches that
867     // occur as a result.
868     //
869     // This allows the compiler to use a wider range of immediates than would
870     // otherwise be allowed. If, for example, v4i32 could only use ldi.h then
871     // it would not be possible to load { 0x01010101, 0x01010101, 0x01010101,
872     // 0x01010101 } without using a constant pool. This would be sub-optimal
873     // when // 'ldi.b wd, 1' is capable of producing that bit-pattern in the
874     // same set/ of registers. Similarly, ldi.h isn't capable of producing {
875     // 0x00000000, 0x00000001, 0x00000000, 0x00000001 } but 'ldi.d wd, 1' can.
876 
877     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Node);
878     APInt SplatValue, SplatUndef;
879     unsigned SplatBitSize;
880     bool HasAnyUndefs;
881     unsigned LdiOp;
882     EVT ResVecTy = BVN->getValueType(0);
883     EVT ViaVecTy;
884 
885     if (!Subtarget->hasMSA() || !BVN->getValueType(0).is128BitVector())
886       return false;
887 
888     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
889                               HasAnyUndefs, 8,
890                               !Subtarget->isLittle()))
891       return false;
892 
893     switch (SplatBitSize) {
894     default:
895       return false;
896     case 8:
897       LdiOp = Mips::LDI_B;
898       ViaVecTy = MVT::v16i8;
899       break;
900     case 16:
901       LdiOp = Mips::LDI_H;
902       ViaVecTy = MVT::v8i16;
903       break;
904     case 32:
905       LdiOp = Mips::LDI_W;
906       ViaVecTy = MVT::v4i32;
907       break;
908     case 64:
909       LdiOp = Mips::LDI_D;
910       ViaVecTy = MVT::v2i64;
911       break;
912     }
913 
914     if (!SplatValue.isSignedIntN(10))
915       return false;
916 
917     SDValue Imm = CurDAG->getTargetConstant(SplatValue, DL,
918                                             ViaVecTy.getVectorElementType());
919 
920     SDNode *Res = CurDAG->getMachineNode(LdiOp, DL, ViaVecTy, Imm);
921 
922     if (ResVecTy != ViaVecTy) {
923       // If LdiOp is writing to a different register class to ResVecTy, then
924       // fix it up here. This COPY_TO_REGCLASS should never cause a move.v
925       // since the source and destination register sets contain the same
926       // registers.
927       const TargetLowering *TLI = getTargetLowering();
928       MVT ResVecTySimple = ResVecTy.getSimpleVT();
929       const TargetRegisterClass *RC = TLI->getRegClassFor(ResVecTySimple);
930       Res = CurDAG->getMachineNode(Mips::COPY_TO_REGCLASS, DL,
931                                    ResVecTy, SDValue(Res, 0),
932                                    CurDAG->getTargetConstant(RC->getID(), DL,
933                                                              MVT::i32));
934     }
935 
936     ReplaceNode(Node, Res);
937     return true;
938   }
939 
940   }
941 
942   return false;
943 }
944 
945 bool MipsSEDAGToDAGISel::
946 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
947                              std::vector<SDValue> &OutOps) {
948   SDValue Base, Offset;
949 
950   switch(ConstraintID) {
951   default:
952     llvm_unreachable("Unexpected asm memory constraint");
953   // All memory constraints can at least accept raw pointers.
954   case InlineAsm::Constraint_i:
955     OutOps.push_back(Op);
956     OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
957     return false;
958   case InlineAsm::Constraint_m:
959     if (selectAddrRegImm16(Op, Base, Offset)) {
960       OutOps.push_back(Base);
961       OutOps.push_back(Offset);
962       return false;
963     }
964     OutOps.push_back(Op);
965     OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
966     return false;
967   case InlineAsm::Constraint_R:
968     // The 'R' constraint is supposed to be much more complicated than this.
969     // However, it's becoming less useful due to architectural changes and
970     // ought to be replaced by other constraints such as 'ZC'.
971     // For now, support 9-bit signed offsets which is supportable by all
972     // subtargets for all instructions.
973     if (selectAddrRegImm9(Op, Base, Offset)) {
974       OutOps.push_back(Base);
975       OutOps.push_back(Offset);
976       return false;
977     }
978     OutOps.push_back(Op);
979     OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
980     return false;
981   case InlineAsm::Constraint_ZC:
982     // ZC matches whatever the pref, ll, and sc instructions can handle for the
983     // given subtarget.
984     if (Subtarget->inMicroMipsMode()) {
985       // On microMIPS, they can handle 12-bit offsets.
986       if (selectAddrRegImm12(Op, Base, Offset)) {
987         OutOps.push_back(Base);
988         OutOps.push_back(Offset);
989         return false;
990       }
991     } else if (Subtarget->hasMips32r6()) {
992       // On MIPS32r6/MIPS64r6, they can only handle 9-bit offsets.
993       if (selectAddrRegImm9(Op, Base, Offset)) {
994         OutOps.push_back(Base);
995         OutOps.push_back(Offset);
996         return false;
997       }
998     } else if (selectAddrRegImm16(Op, Base, Offset)) {
999       // Prior to MIPS32r6/MIPS64r6, they can handle 16-bit offsets.
1000       OutOps.push_back(Base);
1001       OutOps.push_back(Offset);
1002       return false;
1003     }
1004     // In all cases, 0-bit offsets are acceptable.
1005     OutOps.push_back(Op);
1006     OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
1007     return false;
1008   }
1009   return true;
1010 }
1011 
1012 FunctionPass *llvm::createMipsSEISelDag(MipsTargetMachine &TM) {
1013   return new MipsSEDAGToDAGISel(TM);
1014 }
1015