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