MipsSEISelDAGToDAG.cpp revision f5926fd844a84adcf1ae4f193146f2877997b82c
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#define DEBUG_TYPE "mips-isel"
15#include "MipsSEISelDAGToDAG.h"
16#include "Mips.h"
17#include "MCTargetDesc/MipsBaseInfo.h"
18#include "MipsAnalyzeImmediate.h"
19#include "MipsMachineFunction.h"
20#include "MipsRegisterInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SelectionDAGNodes.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/CFG.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"
36using namespace llvm;
37
38
39bool MipsSEDAGToDAGISel::replaceUsesWithZeroReg(MachineRegisterInfo *MRI,
40                                                const MachineInstr& MI) {
41  unsigned DstReg = 0, ZeroReg = 0;
42
43  // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
44  if ((MI.getOpcode() == Mips::ADDiu) &&
45      (MI.getOperand(1).getReg() == Mips::ZERO) &&
46      (MI.getOperand(2).getImm() == 0)) {
47    DstReg = MI.getOperand(0).getReg();
48    ZeroReg = Mips::ZERO;
49  } else if ((MI.getOpcode() == Mips::DADDiu) &&
50             (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
51             (MI.getOperand(2).getImm() == 0)) {
52    DstReg = MI.getOperand(0).getReg();
53    ZeroReg = Mips::ZERO_64;
54  }
55
56  if (!DstReg)
57    return false;
58
59  // Replace uses with ZeroReg.
60  for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
61       E = MRI->use_end(); U != E;) {
62    MachineOperand &MO = U.getOperand();
63    unsigned OpNo = U.getOperandNo();
64    MachineInstr *MI = MO.getParent();
65    ++U;
66
67    // Do not replace if it is a phi's operand or is tied to def operand.
68    if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
69      continue;
70
71    MO.setReg(ZeroReg);
72  }
73
74  return true;
75}
76
77void MipsSEDAGToDAGISel::initGlobalBaseReg(MachineFunction &MF) {
78  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
79
80  if (!MipsFI->globalBaseRegSet())
81    return;
82
83  MachineBasicBlock &MBB = MF.front();
84  MachineBasicBlock::iterator I = MBB.begin();
85  MachineRegisterInfo &RegInfo = MF.getRegInfo();
86  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
87  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
88  unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
89  const TargetRegisterClass *RC;
90
91  if (Subtarget.isABI_N64())
92    RC = (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
93  else
94    RC = (const TargetRegisterClass*)&Mips::CPURegsRegClass;
95
96  V0 = RegInfo.createVirtualRegister(RC);
97  V1 = RegInfo.createVirtualRegister(RC);
98
99  if (Subtarget.isABI_N64()) {
100    MF.getRegInfo().addLiveIn(Mips::T9_64);
101    MBB.addLiveIn(Mips::T9_64);
102
103    // lui $v0, %hi(%neg(%gp_rel(fname)))
104    // daddu $v1, $v0, $t9
105    // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
106    const GlobalValue *FName = MF.getFunction();
107    BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
108      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
109    BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
110      .addReg(Mips::T9_64);
111    BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
112      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
113    return;
114  }
115
116  if (MF.getTarget().getRelocationModel() == Reloc::Static) {
117    // Set global register to __gnu_local_gp.
118    //
119    // lui   $v0, %hi(__gnu_local_gp)
120    // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
121    BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
122      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
123    BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
124      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
125    return;
126  }
127
128  MF.getRegInfo().addLiveIn(Mips::T9);
129  MBB.addLiveIn(Mips::T9);
130
131  if (Subtarget.isABI_N32()) {
132    // lui $v0, %hi(%neg(%gp_rel(fname)))
133    // addu $v1, $v0, $t9
134    // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
135    const GlobalValue *FName = MF.getFunction();
136    BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
137      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
138    BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
139    BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
140      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
141    return;
142  }
143
144  assert(Subtarget.isABI_O32());
145
146  // For O32 ABI, the following instruction sequence is emitted to initialize
147  // the global base register:
148  //
149  //  0. lui   $2, %hi(_gp_disp)
150  //  1. addiu $2, $2, %lo(_gp_disp)
151  //  2. addu  $globalbasereg, $2, $t9
152  //
153  // We emit only the last instruction here.
154  //
155  // GNU linker requires that the first two instructions appear at the beginning
156  // of a function and no instructions be inserted before or between them.
157  // The two instructions are emitted during lowering to MC layer in order to
158  // avoid any reordering.
159  //
160  // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
161  // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
162  // reads it.
163  MF.getRegInfo().addLiveIn(Mips::V0);
164  MBB.addLiveIn(Mips::V0);
165  BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
166    .addReg(Mips::V0).addReg(Mips::T9);
167}
168
169void MipsSEDAGToDAGISel::processFunctionAfterISel(MachineFunction &MF) {
170  initGlobalBaseReg(MF);
171
172  MachineRegisterInfo *MRI = &MF.getRegInfo();
173
174  for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
175       ++MFI)
176    for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
177      replaceUsesWithZeroReg(MRI, *I);
178}
179
180/// Select multiply instructions.
181std::pair<SDNode*, SDNode*>
182MipsSEDAGToDAGISel::selectMULT(SDNode *N, unsigned Opc, DebugLoc DL, EVT Ty,
183                               bool HasLo, bool HasHi) {
184  SDNode *Lo = 0, *Hi = 0;
185  SDNode *Mul = CurDAG->getMachineNode(Opc, DL, MVT::Glue, N->getOperand(0),
186                                       N->getOperand(1));
187  SDValue InFlag = SDValue(Mul, 0);
188
189  if (HasLo) {
190    unsigned Opcode = (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64);
191    Lo = CurDAG->getMachineNode(Opcode, DL, Ty, MVT::Glue, InFlag);
192    InFlag = SDValue(Lo, 1);
193  }
194  if (HasHi) {
195    unsigned Opcode = (Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64);
196    Hi = CurDAG->getMachineNode(Opcode, DL, Ty, InFlag);
197  }
198  return std::make_pair(Lo, Hi);
199}
200
201SDNode *MipsSEDAGToDAGISel::selectAddESubE(unsigned MOp, SDValue InFlag,
202                                           SDValue CmpLHS, DebugLoc DL,
203                                           SDNode *Node) const {
204  unsigned Opc = InFlag.getOpcode(); (void)Opc;
205
206  assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
207          (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
208         "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
209
210  SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
211  SDValue LHS = Node->getOperand(0), RHS = Node->getOperand(1);
212  EVT VT = LHS.getValueType();
213
214  SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, DL, VT, Ops, 2);
215  SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, DL, VT,
216                                            SDValue(Carry, 0), RHS);
217  return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS,
218                              SDValue(AddCarry, 0));
219}
220
221/// ComplexPattern used on MipsInstrInfo
222/// Used on Mips Load/Store instructions
223bool MipsSEDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
224                                          SDValue &Offset) const {
225  EVT ValTy = Addr.getValueType();
226
227  // if Address is FI, get the TargetFrameIndex.
228  if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
229    Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
230    Offset = CurDAG->getTargetConstant(0, ValTy);
231    return true;
232  }
233
234  // on PIC code Load GA
235  if (Addr.getOpcode() == MipsISD::Wrapper) {
236    Base   = Addr.getOperand(0);
237    Offset = Addr.getOperand(1);
238    return true;
239  }
240
241  if (TM.getRelocationModel() != Reloc::PIC_) {
242    if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
243        Addr.getOpcode() == ISD::TargetGlobalAddress))
244      return false;
245  }
246
247  // Addresses of the form FI+const or FI|const
248  if (CurDAG->isBaseWithConstantOffset(Addr)) {
249    ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
250    if (isInt<16>(CN->getSExtValue())) {
251
252      // If the first operand is a FI, get the TargetFI Node
253      if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
254                                  (Addr.getOperand(0)))
255        Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
256      else
257        Base = Addr.getOperand(0);
258
259      Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
260      return true;
261    }
262  }
263
264  // Operand is a result from an ADD.
265  if (Addr.getOpcode() == ISD::ADD) {
266    // When loading from constant pools, load the lower address part in
267    // the instruction itself. Example, instead of:
268    //  lui $2, %hi($CPI1_0)
269    //  addiu $2, $2, %lo($CPI1_0)
270    //  lwc1 $f0, 0($2)
271    // Generate:
272    //  lui $2, %hi($CPI1_0)
273    //  lwc1 $f0, %lo($CPI1_0)($2)
274    if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
275        Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
276      SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
277      if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
278          isa<JumpTableSDNode>(Opnd0)) {
279        Base = Addr.getOperand(0);
280        Offset = Opnd0;
281        return true;
282      }
283    }
284  }
285
286  return false;
287}
288
289bool MipsSEDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
290                                           SDValue &Offset) const {
291  Base = Addr;
292  Offset = CurDAG->getTargetConstant(0, Addr.getValueType());
293  return true;
294}
295
296bool MipsSEDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
297                                       SDValue &Offset) const {
298  return selectAddrRegImm(Addr, Base, Offset) ||
299    selectAddrDefault(Addr, Base, Offset);
300}
301
302std::pair<bool, SDNode*> MipsSEDAGToDAGISel::selectNode(SDNode *Node) {
303  unsigned Opcode = Node->getOpcode();
304  DebugLoc DL = Node->getDebugLoc();
305
306  ///
307  // Instruction Selection not handled by the auto-generated
308  // tablegen selection should be handled here.
309  ///
310  EVT NodeTy = Node->getValueType(0);
311  SDNode *Result;
312  unsigned MultOpc;
313
314  switch(Opcode) {
315  default: break;
316
317  case ISD::SUBE: {
318    SDValue InFlag = Node->getOperand(2);
319    Result = selectAddESubE(Mips::SUBu, InFlag, InFlag.getOperand(0), DL, Node);
320    return std::make_pair(true, Result);
321  }
322
323  case ISD::ADDE: {
324    SDValue InFlag = Node->getOperand(2);
325    Result = selectAddESubE(Mips::ADDu, InFlag, InFlag.getValue(0), DL, Node);
326    return std::make_pair(true, Result);
327  }
328
329  /// Mul with two results
330  case ISD::SMUL_LOHI:
331  case ISD::UMUL_LOHI: {
332    if (NodeTy == MVT::i32)
333      MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
334    else
335      MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
336
337    std::pair<SDNode*, SDNode*> LoHi = selectMULT(Node, MultOpc, DL, NodeTy,
338                                                  true, true);
339
340    if (!SDValue(Node, 0).use_empty())
341      ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
342
343    if (!SDValue(Node, 1).use_empty())
344      ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
345
346    return std::make_pair(true, (SDNode*)NULL);
347  }
348
349  /// Special Muls
350  case ISD::MUL: {
351    // Mips32 has a 32-bit three operand mul instruction.
352    if (Subtarget.hasMips32() && NodeTy == MVT::i32)
353      break;
354    MultOpc = NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT;
355    Result = selectMULT(Node, MultOpc, DL, NodeTy, true, false).first;
356    return std::make_pair(true, Result);
357  }
358  case ISD::MULHS:
359  case ISD::MULHU: {
360    if (NodeTy == MVT::i32)
361      MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
362    else
363      MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
364
365    Result = selectMULT(Node, MultOpc, DL, NodeTy, false, true).second;
366    return std::make_pair(true, Result);
367  }
368
369  case ISD::ConstantFP: {
370    ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
371    if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
372      if (Subtarget.hasMips64()) {
373        SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
374                                              Mips::ZERO_64, MVT::i64);
375        Result = CurDAG->getMachineNode(Mips::DMTC1, DL, MVT::f64, Zero);
376      } else {
377        SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
378                                              Mips::ZERO, MVT::i32);
379        Result = CurDAG->getMachineNode(Mips::BuildPairF64, DL, MVT::f64, Zero,
380                                        Zero);
381      }
382
383      return std::make_pair(true, Result);
384    }
385    break;
386  }
387
388  case ISD::Constant: {
389    const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
390    unsigned Size = CN->getValueSizeInBits(0);
391
392    if (Size == 32)
393      break;
394
395    MipsAnalyzeImmediate AnalyzeImm;
396    int64_t Imm = CN->getSExtValue();
397
398    const MipsAnalyzeImmediate::InstSeq &Seq =
399      AnalyzeImm.Analyze(Imm, Size, false);
400
401    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
402    DebugLoc DL = CN->getDebugLoc();
403    SDNode *RegOpnd;
404    SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
405                                                MVT::i64);
406
407    // The first instruction can be a LUi which is different from other
408    // instructions (ADDiu, ORI and SLL) in that it does not have a register
409    // operand.
410    if (Inst->Opc == Mips::LUi64)
411      RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
412    else
413      RegOpnd =
414        CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
415                               CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
416                               ImmOpnd);
417
418    // The remaining instructions in the sequence are handled here.
419    for (++Inst; Inst != Seq.end(); ++Inst) {
420      ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
421                                          MVT::i64);
422      RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
423                                       SDValue(RegOpnd, 0), ImmOpnd);
424    }
425
426    return std::make_pair(true, RegOpnd);
427  }
428
429  case MipsISD::ThreadPointer: {
430    EVT PtrVT = TLI.getPointerTy();
431    unsigned RdhwrOpc, SrcReg, DestReg;
432
433    if (PtrVT == MVT::i32) {
434      RdhwrOpc = Mips::RDHWR;
435      SrcReg = Mips::HWR29;
436      DestReg = Mips::V1;
437    } else {
438      RdhwrOpc = Mips::RDHWR64;
439      SrcReg = Mips::HWR29_64;
440      DestReg = Mips::V1_64;
441    }
442
443    SDNode *Rdhwr =
444      CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
445                             Node->getValueType(0),
446                             CurDAG->getRegister(SrcReg, PtrVT));
447    SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, DestReg,
448                                         SDValue(Rdhwr, 0));
449    SDValue ResNode = CurDAG->getCopyFromReg(Chain, DL, DestReg, PtrVT);
450    ReplaceUses(SDValue(Node, 0), ResNode);
451    return std::make_pair(true, ResNode.getNode());
452  }
453
454  case MipsISD::InsertLOHI: {
455    unsigned RCID = Subtarget.hasDSP() ? Mips::ACRegsDSPRegClassID :
456                                         Mips::ACRegsRegClassID;
457    SDValue RegClass = CurDAG->getTargetConstant(RCID, MVT::i32);
458    SDValue LoIdx = CurDAG->getTargetConstant(Mips::sub_lo, MVT::i32);
459    SDValue HiIdx = CurDAG->getTargetConstant(Mips::sub_hi, MVT::i32);
460    const SDValue Ops[] = { RegClass, Node->getOperand(0), LoIdx,
461                            Node->getOperand(1), HiIdx };
462    SDNode *Res = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
463                                         MVT::Untyped, Ops, 5);
464    return std::make_pair(true, Res);
465  }
466  }
467
468  return std::make_pair(false, (SDNode*)NULL);
469}
470
471FunctionPass *llvm::createMipsSEISelDag(MipsTargetMachine &TM) {
472  return new MipsSEDAGToDAGISel(TM);
473}
474