LLVM  10.0.0svn
MipsISelLowering.cpp
Go to the documentation of this file.
1 //===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that Mips uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsISelLowering.h"
18 #include "MipsCCState.h"
19 #include "MipsInstrInfo.h"
20 #include "MipsMachineFunction.h"
21 #include "MipsRegisterInfo.h"
22 #include "MipsSubtarget.h"
23 #include "MipsTargetMachine.h"
24 #include "MipsTargetObjectFile.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/MC/MCRegisterInfo.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CodeGen.h"
64 #include "llvm/Support/Compiler.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cctype>
73 #include <cstdint>
74 #include <deque>
75 #include <iterator>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 #define DEBUG_TYPE "mips-lower"
82 
83 STATISTIC(NumTailCalls, "Number of tail calls");
84 
85 static cl::opt<bool>
86 LargeGOT("mxgot", cl::Hidden,
87  cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
88 
89 static cl::opt<bool>
90 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
91  cl::desc("MIPS: Don't trap on integer division by zero."),
92  cl::init(false));
93 
95 
96 static const MCPhysReg Mips64DPRegs[8] = {
97  Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
98  Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
99 };
100 
101 // If I is a shifted mask, set the size (Size) and the first bit of the
102 // mask (Pos), and return true.
103 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
104 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
105  if (!isShiftedMask_64(I))
106  return false;
107 
108  Size = countPopulation(I);
109  Pos = countTrailingZeros(I);
110  return true;
111 }
112 
113 // The MIPS MSA ABI passes vector arguments in the integer register set.
114 // The number of integer registers used is dependant on the ABI used.
116  CallingConv::ID CC,
117  EVT VT) const {
118  if (VT.isVector()) {
119  if (Subtarget.isABI_O32()) {
120  return MVT::i32;
121  } else {
122  return (VT.getSizeInBits() == 32) ? MVT::i32 : MVT::i64;
123  }
124  }
125  return MipsTargetLowering::getRegisterType(Context, VT);
126 }
127 
129  CallingConv::ID CC,
130  EVT VT) const {
131  if (VT.isVector())
132  return std::max((VT.getSizeInBits() / (Subtarget.isABI_O32() ? 32 : 64)),
133  1U);
134  return MipsTargetLowering::getNumRegisters(Context, VT);
135 }
136 
138  LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
139  unsigned &NumIntermediates, MVT &RegisterVT) const {
140  // Break down vector types to either 2 i64s or 4 i32s.
141  RegisterVT = getRegisterTypeForCallingConv(Context, CC, VT);
142  IntermediateVT = RegisterVT;
143  NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits()
144  ? VT.getVectorNumElements()
145  : VT.getSizeInBits() / RegisterVT.getSizeInBits();
146 
147  return NumIntermediates;
148 }
149 
152  return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
153 }
154 
155 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
156  SelectionDAG &DAG,
157  unsigned Flag) const {
158  return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
159 }
160 
161 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
162  SelectionDAG &DAG,
163  unsigned Flag) const {
164  return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
165 }
166 
167 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
168  SelectionDAG &DAG,
169  unsigned Flag) const {
170  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
171 }
172 
173 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
174  SelectionDAG &DAG,
175  unsigned Flag) const {
176  return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
177 }
178 
179 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
180  SelectionDAG &DAG,
181  unsigned Flag) const {
182  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
183  N->getOffset(), Flag);
184 }
185 
186 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
187  switch ((MipsISD::NodeType)Opcode) {
188  case MipsISD::FIRST_NUMBER: break;
189  case MipsISD::JmpLink: return "MipsISD::JmpLink";
190  case MipsISD::TailCall: return "MipsISD::TailCall";
191  case MipsISD::Highest: return "MipsISD::Highest";
192  case MipsISD::Higher: return "MipsISD::Higher";
193  case MipsISD::Hi: return "MipsISD::Hi";
194  case MipsISD::Lo: return "MipsISD::Lo";
195  case MipsISD::GotHi: return "MipsISD::GotHi";
196  case MipsISD::TlsHi: return "MipsISD::TlsHi";
197  case MipsISD::GPRel: return "MipsISD::GPRel";
198  case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
199  case MipsISD::Ret: return "MipsISD::Ret";
200  case MipsISD::ERet: return "MipsISD::ERet";
201  case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
202  case MipsISD::FMS: return "MipsISD::FMS";
203  case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
204  case MipsISD::FPCmp: return "MipsISD::FPCmp";
205  case MipsISD::FSELECT: return "MipsISD::FSELECT";
206  case MipsISD::MTC1_D64: return "MipsISD::MTC1_D64";
207  case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
208  case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
209  case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
210  case MipsISD::MFHI: return "MipsISD::MFHI";
211  case MipsISD::MFLO: return "MipsISD::MFLO";
212  case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
213  case MipsISD::Mult: return "MipsISD::Mult";
214  case MipsISD::Multu: return "MipsISD::Multu";
215  case MipsISD::MAdd: return "MipsISD::MAdd";
216  case MipsISD::MAddu: return "MipsISD::MAddu";
217  case MipsISD::MSub: return "MipsISD::MSub";
218  case MipsISD::MSubu: return "MipsISD::MSubu";
219  case MipsISD::DivRem: return "MipsISD::DivRem";
220  case MipsISD::DivRemU: return "MipsISD::DivRemU";
221  case MipsISD::DivRem16: return "MipsISD::DivRem16";
222  case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
223  case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
224  case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
225  case MipsISD::Wrapper: return "MipsISD::Wrapper";
226  case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
227  case MipsISD::Sync: return "MipsISD::Sync";
228  case MipsISD::Ext: return "MipsISD::Ext";
229  case MipsISD::Ins: return "MipsISD::Ins";
230  case MipsISD::CIns: return "MipsISD::CIns";
231  case MipsISD::LWL: return "MipsISD::LWL";
232  case MipsISD::LWR: return "MipsISD::LWR";
233  case MipsISD::SWL: return "MipsISD::SWL";
234  case MipsISD::SWR: return "MipsISD::SWR";
235  case MipsISD::LDL: return "MipsISD::LDL";
236  case MipsISD::LDR: return "MipsISD::LDR";
237  case MipsISD::SDL: return "MipsISD::SDL";
238  case MipsISD::SDR: return "MipsISD::SDR";
239  case MipsISD::EXTP: return "MipsISD::EXTP";
240  case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
241  case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
242  case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
243  case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
244  case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
245  case MipsISD::SHILO: return "MipsISD::SHILO";
246  case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
247  case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
248  case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
249  case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
250  case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
251  case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
252  case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
253  case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
254  case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
255  case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
256  case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
257  case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
258  case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
259  case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
260  case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
261  case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
262  case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
263  case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
264  case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
265  case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
266  case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
267  case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
268  case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
269  case MipsISD::MULT: return "MipsISD::MULT";
270  case MipsISD::MULTU: return "MipsISD::MULTU";
271  case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
272  case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
273  case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
274  case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
275  case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
276  case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
277  case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
278  case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
279  case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
280  case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
281  case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
282  case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
283  case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
284  case MipsISD::VCEQ: return "MipsISD::VCEQ";
285  case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
286  case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
287  case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
288  case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
289  case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
290  case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
291  case MipsISD::VNOR: return "MipsISD::VNOR";
292  case MipsISD::VSHF: return "MipsISD::VSHF";
293  case MipsISD::SHF: return "MipsISD::SHF";
294  case MipsISD::ILVEV: return "MipsISD::ILVEV";
295  case MipsISD::ILVOD: return "MipsISD::ILVOD";
296  case MipsISD::ILVL: return "MipsISD::ILVL";
297  case MipsISD::ILVR: return "MipsISD::ILVR";
298  case MipsISD::PCKEV: return "MipsISD::PCKEV";
299  case MipsISD::PCKOD: return "MipsISD::PCKOD";
300  case MipsISD::INSVE: return "MipsISD::INSVE";
301  }
302  return nullptr;
303 }
304 
306  const MipsSubtarget &STI)
307  : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
308  // Mips does not have i1 type, so use i32 for
309  // setcc operations results (slt, sgt, ...).
312  // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
313  // does. Integer booleans still use 0 and 1.
314  if (Subtarget.hasMips32r6())
317 
318  // Load extented operations for i1 types must be promoted
319  for (MVT VT : MVT::integer_valuetypes()) {
323  }
324 
325  // MIPS doesn't have extending float->double load/store. Set LoadExtAction
326  // for f32, f16
327  for (MVT VT : MVT::fp_valuetypes()) {
330  }
331 
332  // Set LoadExtAction for f16 vectors to Expand
334  MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
335  if (F16VT.isValid())
336  setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
337  }
338 
341 
343 
344  // Used by legalize types to correctly generate the setcc result.
345  // Without this, every float setcc comes with a AND/OR with the result,
346  // we don't want this, since the fpcmp result goes to a flag register,
347  // which is used implicitly by brcond and select operations.
349 
350  // Mips Custom Operations
366 
367  if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) {
370  }
371 
372  if (Subtarget.isGP64bit()) {
385  }
386 
387  if (!Subtarget.isGP64bit()) {
391  }
392 
394  if (Subtarget.isGP64bit())
396 
405 
406  // Operations not directly supported by Mips.
420  if (Subtarget.hasCnMips()) {
423  } else {
426  }
433 
434  if (!Subtarget.hasMips32r2())
436 
437  if (!Subtarget.hasMips64r2())
439 
456 
457  // Lower f16 conversion operations into library calls
462 
464 
469 
470  // Use the default for now
473 
474  if (!Subtarget.isGP64bit()) {
477  }
478 
479  if (!Subtarget.hasMips32r2()) {
482  }
483 
484  // MIPS16 lacks MIPS32's clz and clo instructions.
487  if (!Subtarget.hasMips64())
489 
490  if (!Subtarget.hasMips32r2())
492  if (!Subtarget.hasMips64r2())
494 
495  if (Subtarget.isGP64bit()) {
500  }
501 
503 
513 
514  if (ABI.IsO32()) {
515  // These libcalls are not available in 32-bit.
516  setLibcallName(RTLIB::SHL_I128, nullptr);
517  setLibcallName(RTLIB::SRL_I128, nullptr);
518  setLibcallName(RTLIB::SRA_I128, nullptr);
519  }
520 
522  : llvm::Align(4));
523 
524  // The arguments on the stack are defined in terms of 4-byte slots on O32
525  // and 8-byte slots on N32/N64.
527  : llvm::Align(4));
528 
529  setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
530 
531  MaxStoresPerMemcpy = 16;
532 
533  isMicroMips = Subtarget.inMicroMipsMode();
534 }
535 
537  const MipsSubtarget &STI) {
538  if (STI.inMips16Mode())
539  return createMips16TargetLowering(TM, STI);
540 
541  return createMipsSETargetLowering(TM, STI);
542 }
543 
544 // Create a fast isel object.
545 FastISel *
547  const TargetLibraryInfo *libInfo) const {
548  const MipsTargetMachine &TM =
549  static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
550 
551  // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
552  bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
555 
556  // Disable if either of the following is true:
557  // We do not generate PIC, the ABI is not O32, LargeGOT is being used.
558  if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || LargeGOT)
559  UseFastISel = false;
560 
561  return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
562 }
563 
565  EVT VT) const {
566  if (!VT.isVector())
567  return MVT::i32;
569 }
570 
573  const MipsSubtarget &Subtarget) {
574  if (DCI.isBeforeLegalizeOps())
575  return SDValue();
576 
577  EVT Ty = N->getValueType(0);
578  unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
579  unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
580  unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
582  SDLoc DL(N);
583 
584  SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
585  N->getOperand(0), N->getOperand(1));
586  SDValue InChain = DAG.getEntryNode();
587  SDValue InGlue = DivRem;
588 
589  // insert MFLO
590  if (N->hasAnyUseOfValue(0)) {
591  SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
592  InGlue);
593  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
594  InChain = CopyFromLo.getValue(1);
595  InGlue = CopyFromLo.getValue(2);
596  }
597 
598  // insert MFHI
599  if (N->hasAnyUseOfValue(1)) {
600  SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
601  HI, Ty, InGlue);
602  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
603  }
604 
605  return SDValue();
606 }
607 
609  switch (CC) {
610  default: llvm_unreachable("Unknown fp condition code!");
611  case ISD::SETEQ:
612  case ISD::SETOEQ: return Mips::FCOND_OEQ;
613  case ISD::SETUNE: return Mips::FCOND_UNE;
614  case ISD::SETLT:
615  case ISD::SETOLT: return Mips::FCOND_OLT;
616  case ISD::SETGT:
617  case ISD::SETOGT: return Mips::FCOND_OGT;
618  case ISD::SETLE:
619  case ISD::SETOLE: return Mips::FCOND_OLE;
620  case ISD::SETGE:
621  case ISD::SETOGE: return Mips::FCOND_OGE;
622  case ISD::SETULT: return Mips::FCOND_ULT;
623  case ISD::SETULE: return Mips::FCOND_ULE;
624  case ISD::SETUGT: return Mips::FCOND_UGT;
625  case ISD::SETUGE: return Mips::FCOND_UGE;
626  case ISD::SETUO: return Mips::FCOND_UN;
627  case ISD::SETO: return Mips::FCOND_OR;
628  case ISD::SETNE:
629  case ISD::SETONE: return Mips::FCOND_ONE;
630  case ISD::SETUEQ: return Mips::FCOND_UEQ;
631  }
632 }
633 
634 /// This function returns true if the floating point conditional branches and
635 /// conditional moves which use condition code CC should be inverted.
637  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
638  return false;
639 
640  assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
641  "Illegal Condition Code");
642 
643  return true;
644 }
645 
646 // Creates and returns an FPCmp node from a setcc node.
647 // Returns Op if setcc is not a floating point comparison.
648 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
649  // must be a SETCC node
650  if (Op.getOpcode() != ISD::SETCC)
651  return Op;
652 
653  SDValue LHS = Op.getOperand(0);
654 
655  if (!LHS.getValueType().isFloatingPoint())
656  return Op;
657 
658  SDValue RHS = Op.getOperand(1);
659  SDLoc DL(Op);
660 
661  // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
662  // node if necessary.
663  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
664 
665  return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
666  DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
667 }
668 
669 // Creates and returns a CMovFPT/F node.
671  SDValue False, const SDLoc &DL) {
672  ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
673  bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
674  SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
675 
676  return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
677  True.getValueType(), True, FCC0, False, Cond);
678 }
679 
682  const MipsSubtarget &Subtarget) {
683  if (DCI.isBeforeLegalizeOps())
684  return SDValue();
685 
686  SDValue SetCC = N->getOperand(0);
687 
688  if ((SetCC.getOpcode() != ISD::SETCC) ||
689  !SetCC.getOperand(0).getValueType().isInteger())
690  return SDValue();
691 
692  SDValue False = N->getOperand(2);
693  EVT FalseTy = False.getValueType();
694 
695  if (!FalseTy.isInteger())
696  return SDValue();
697 
698  ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
699 
700  // If the RHS (False) is 0, we swap the order of the operands
701  // of ISD::SELECT (obviously also inverting the condition) so that we can
702  // take advantage of conditional moves using the $0 register.
703  // Example:
704  // return (a != 0) ? x : 0;
705  // load $reg, x
706  // movz $reg, $0, a
707  if (!FalseC)
708  return SDValue();
709 
710  const SDLoc DL(N);
711 
712  if (!FalseC->getZExtValue()) {
713  ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
714  SDValue True = N->getOperand(1);
715 
716  SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
717  SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
718 
719  return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
720  }
721 
722  // If both operands are integer constants there's a possibility that we
723  // can do some interesting optimizations.
724  SDValue True = N->getOperand(1);
725  ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
726 
727  if (!TrueC || !True.getValueType().isInteger())
728  return SDValue();
729 
730  // We'll also ignore MVT::i64 operands as this optimizations proves
731  // to be ineffective because of the required sign extensions as the result
732  // of a SETCC operator is always MVT::i32 for non-vector types.
733  if (True.getValueType() == MVT::i64)
734  return SDValue();
735 
736  int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
737 
738  // 1) (a < x) ? y : y-1
739  // slti $reg1, a, x
740  // addiu $reg2, $reg1, y-1
741  if (Diff == 1)
742  return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
743 
744  // 2) (a < x) ? y-1 : y
745  // slti $reg1, a, x
746  // xor $reg1, $reg1, 1
747  // addiu $reg2, $reg1, y-1
748  if (Diff == -1) {
749  ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
750  SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
751  SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
752  return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
753  }
754 
755  // Could not optimize.
756  return SDValue();
757 }
758 
761  const MipsSubtarget &Subtarget) {
762  if (DCI.isBeforeLegalizeOps())
763  return SDValue();
764 
765  SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
766 
767  ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
768  if (!FalseC || FalseC->getZExtValue())
769  return SDValue();
770 
771  // Since RHS (False) is 0, we swap the order of the True/False operands
772  // (obviously also inverting the condition) so that we can
773  // take advantage of conditional moves using the $0 register.
774  // Example:
775  // return (a != 0) ? x : 0;
776  // load $reg, x
777  // movz $reg, $0, a
778  unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
780 
781  SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
782  return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
783  ValueIfFalse, FCC, ValueIfTrue, Glue);
784 }
785 
788  const MipsSubtarget &Subtarget) {
789  if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
790  return SDValue();
791 
792  SDValue FirstOperand = N->getOperand(0);
793  unsigned FirstOperandOpc = FirstOperand.getOpcode();
794  SDValue Mask = N->getOperand(1);
795  EVT ValTy = N->getValueType(0);
796  SDLoc DL(N);
797 
798  uint64_t Pos = 0, SMPos, SMSize;
799  ConstantSDNode *CN;
800  SDValue NewOperand;
801  unsigned Opc;
802 
803  // Op's second operand must be a shifted mask.
804  if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
805  !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
806  return SDValue();
807 
808  if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
809  // Pattern match EXT.
810  // $dst = and ((sra or srl) $src , pos), (2**size - 1)
811  // => ext $dst, $src, pos, size
812 
813  // The second operand of the shift must be an immediate.
814  if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
815  return SDValue();
816 
817  Pos = CN->getZExtValue();
818 
819  // Return if the shifted mask does not start at bit 0 or the sum of its size
820  // and Pos exceeds the word's size.
821  if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
822  return SDValue();
823 
824  Opc = MipsISD::Ext;
825  NewOperand = FirstOperand.getOperand(0);
826  } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
827  // Pattern match CINS.
828  // $dst = and (shl $src , pos), mask
829  // => cins $dst, $src, pos, size
830  // mask is a shifted mask with consecutive 1's, pos = shift amount,
831  // size = population count.
832 
833  // The second operand of the shift must be an immediate.
834  if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
835  return SDValue();
836 
837  Pos = CN->getZExtValue();
838 
839  if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
840  Pos + SMSize > ValTy.getSizeInBits())
841  return SDValue();
842 
843  NewOperand = FirstOperand.getOperand(0);
844  // SMSize is 'location' (position) in this case, not size.
845  SMSize--;
846  Opc = MipsISD::CIns;
847  } else {
848  // Pattern match EXT.
849  // $dst = and $src, (2**size - 1) , if size > 16
850  // => ext $dst, $src, pos, size , pos = 0
851 
852  // If the mask is <= 0xffff, andi can be used instead.
853  if (CN->getZExtValue() <= 0xffff)
854  return SDValue();
855 
856  // Return if the mask doesn't start at position 0.
857  if (SMPos)
858  return SDValue();
859 
860  Opc = MipsISD::Ext;
861  NewOperand = FirstOperand;
862  }
863  return DAG.getNode(Opc, DL, ValTy, NewOperand,
864  DAG.getConstant(Pos, DL, MVT::i32),
865  DAG.getConstant(SMSize, DL, MVT::i32));
866 }
867 
870  const MipsSubtarget &Subtarget) {
871  // Pattern match INS.
872  // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
873  // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
874  // => ins $dst, $src, size, pos, $src1
875  if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
876  return SDValue();
877 
878  SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
879  uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
880  ConstantSDNode *CN, *CN1;
881 
882  // See if Op's first operand matches (and $src1 , mask0).
883  if (And0.getOpcode() != ISD::AND)
884  return SDValue();
885 
886  if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
887  !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
888  return SDValue();
889 
890  // See if Op's second operand matches (and (shl $src, pos), mask1).
891  if (And1.getOpcode() == ISD::AND &&
892  And1.getOperand(0).getOpcode() == ISD::SHL) {
893 
894  if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
895  !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
896  return SDValue();
897 
898  // The shift masks must have the same position and size.
899  if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
900  return SDValue();
901 
902  SDValue Shl = And1.getOperand(0);
903 
904  if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
905  return SDValue();
906 
907  unsigned Shamt = CN->getZExtValue();
908 
909  // Return if the shift amount and the first bit position of mask are not the
910  // same.
911  EVT ValTy = N->getValueType(0);
912  if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
913  return SDValue();
914 
915  SDLoc DL(N);
916  return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
917  DAG.getConstant(SMPos0, DL, MVT::i32),
918  DAG.getConstant(SMSize0, DL, MVT::i32),
919  And0.getOperand(0));
920  } else {
921  // Pattern match DINS.
922  // $dst = or (and $src, mask0), mask1
923  // where mask0 = ((1 << SMSize0) -1) << SMPos0
924  // => dins $dst, $src, pos, size
925  if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
926  ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
927  (SMSize0 + SMPos0 <= 32))) {
928  // Check if AND instruction has constant as argument
929  bool isConstCase = And1.getOpcode() != ISD::AND;
930  if (And1.getOpcode() == ISD::AND) {
931  if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
932  return SDValue();
933  } else {
934  if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
935  return SDValue();
936  }
937  // Don't generate INS if constant OR operand doesn't fit into bits
938  // cleared by constant AND operand.
939  if (CN->getSExtValue() & CN1->getSExtValue())
940  return SDValue();
941 
942  SDLoc DL(N);
943  EVT ValTy = N->getOperand(0)->getValueType(0);
944  SDValue Const1;
945  SDValue SrlX;
946  if (!isConstCase) {
947  Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
948  SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
949  }
950  return DAG.getNode(
951  MipsISD::Ins, DL, N->getValueType(0),
952  isConstCase
953  ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
954  : SrlX,
955  DAG.getConstant(SMPos0, DL, MVT::i32),
956  DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
957  : SMSize0,
958  DL, MVT::i32),
959  And0->getOperand(0));
960 
961  }
962  return SDValue();
963  }
964 }
965 
967  const MipsSubtarget &Subtarget) {
968  // ROOTNode must have a multiplication as an operand for the match to be
969  // successful.
970  if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
971  ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
972  return SDValue();
973 
974  // We don't handle vector types here.
975  if (ROOTNode->getValueType(0).isVector())
976  return SDValue();
977 
978  // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
979  // arithmetic. E.g.
980  // (add (mul a b) c) =>
981  // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
982  // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
983  // or
984  // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
985  //
986  // The overhead of setting up the Hi/Lo registers and reassembling the
987  // result makes this a dubious optimzation for MIPS64. The core of the
988  // problem is that Hi/Lo contain the upper and lower 32 bits of the
989  // operand and result.
990  //
991  // It requires a chain of 4 add/mul for MIPS64R2 to get better code
992  // density than doing it naively, 5 for MIPS64. Additionally, using
993  // madd/msub on MIPS64 requires the operands actually be 32 bit sign
994  // extended operands, not true 64 bit values.
995  //
996  // FIXME: For the moment, disable this completely for MIPS64.
997  if (Subtarget.hasMips64())
998  return SDValue();
999 
1000  SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1001  ? ROOTNode->getOperand(0)
1002  : ROOTNode->getOperand(1);
1003 
1004  SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1005  ? ROOTNode->getOperand(1)
1006  : ROOTNode->getOperand(0);
1007 
1008  // Transform this to a MADD only if the user of this node is the add.
1009  // If there are other users of the mul, this function returns here.
1010  if (!Mult.hasOneUse())
1011  return SDValue();
1012 
1013  // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
1014  // must be in canonical form, i.e. sign extended. For MIPS32, the operands
1015  // of the multiply must have 32 or more sign bits, otherwise we cannot
1016  // perform this optimization. We have to check this here as we're performing
1017  // this optimization pre-legalization.
1018  SDValue MultLHS = Mult->getOperand(0);
1019  SDValue MultRHS = Mult->getOperand(1);
1020 
1021  bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
1022  MultRHS->getOpcode() == ISD::SIGN_EXTEND;
1023  bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1024  MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1025 
1026  if (!IsSigned && !IsUnsigned)
1027  return SDValue();
1028 
1029  // Initialize accumulator.
1030  SDLoc DL(ROOTNode);
1031  SDValue TopHalf;
1032  SDValue BottomHalf;
1033  BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1034  CurDAG.getIntPtrConstant(0, DL));
1035 
1036  TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1037  CurDAG.getIntPtrConstant(1, DL));
1038  SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1039  BottomHalf,
1040  TopHalf);
1041 
1042  // Create MipsMAdd(u) / MipsMSub(u) node.
1043  bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1044  unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1045  : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1046  SDValue MAddOps[3] = {
1047  CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1048  CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1049  EVT VTs[2] = {MVT::i32, MVT::i32};
1050  SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1051 
1052  SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1053  SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1054  SDValue Combined =
1055  CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1056  return Combined;
1057 }
1058 
1061  const MipsSubtarget &Subtarget) {
1062  // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1063  if (DCI.isBeforeLegalizeOps()) {
1064  if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1065  !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1066  return performMADD_MSUBCombine(N, DAG, Subtarget);
1067 
1068  return SDValue();
1069  }
1070 
1071  return SDValue();
1072 }
1073 
1076  const MipsSubtarget &Subtarget) {
1077  // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1078  if (DCI.isBeforeLegalizeOps()) {
1079  if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1080  !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1081  return performMADD_MSUBCombine(N, DAG, Subtarget);
1082 
1083  return SDValue();
1084  }
1085 
1086  // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1087  SDValue Add = N->getOperand(1);
1088 
1089  if (Add.getOpcode() != ISD::ADD)
1090  return SDValue();
1091 
1092  SDValue Lo = Add.getOperand(1);
1093 
1094  if ((Lo.getOpcode() != MipsISD::Lo) ||
1096  return SDValue();
1097 
1098  EVT ValTy = N->getValueType(0);
1099  SDLoc DL(N);
1100 
1101  SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1102  Add.getOperand(0));
1103  return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1104 }
1105 
1108  const MipsSubtarget &Subtarget) {
1109  // Pattern match CINS.
1110  // $dst = shl (and $src , imm), pos
1111  // => cins $dst, $src, pos, size
1112 
1113  if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1114  return SDValue();
1115 
1116  SDValue FirstOperand = N->getOperand(0);
1117  unsigned FirstOperandOpc = FirstOperand.getOpcode();
1118  SDValue SecondOperand = N->getOperand(1);
1119  EVT ValTy = N->getValueType(0);
1120  SDLoc DL(N);
1121 
1122  uint64_t Pos = 0, SMPos, SMSize;
1123  ConstantSDNode *CN;
1124  SDValue NewOperand;
1125 
1126  // The second operand of the shift must be an immediate.
1127  if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1128  return SDValue();
1129 
1130  Pos = CN->getZExtValue();
1131 
1132  if (Pos >= ValTy.getSizeInBits())
1133  return SDValue();
1134 
1135  if (FirstOperandOpc != ISD::AND)
1136  return SDValue();
1137 
1138  // AND's second operand must be a shifted mask.
1139  if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1140  !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1141  return SDValue();
1142 
1143  // Return if the shifted mask does not start at bit 0 or the sum of its size
1144  // and Pos exceeds the word's size.
1145  if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1146  return SDValue();
1147 
1148  NewOperand = FirstOperand.getOperand(0);
1149  // SMSize is 'location' (position) in this case, not size.
1150  SMSize--;
1151 
1152  return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1153  DAG.getConstant(Pos, DL, MVT::i32),
1154  DAG.getConstant(SMSize, DL, MVT::i32));
1155 }
1156 
1158  const {
1159  SelectionDAG &DAG = DCI.DAG;
1160  unsigned Opc = N->getOpcode();
1161 
1162  switch (Opc) {
1163  default: break;
1164  case ISD::SDIVREM:
1165  case ISD::UDIVREM:
1166  return performDivRemCombine(N, DAG, DCI, Subtarget);
1167  case ISD::SELECT:
1168  return performSELECTCombine(N, DAG, DCI, Subtarget);
1169  case MipsISD::CMovFP_F:
1170  case MipsISD::CMovFP_T:
1171  return performCMovFPCombine(N, DAG, DCI, Subtarget);
1172  case ISD::AND:
1173  return performANDCombine(N, DAG, DCI, Subtarget);
1174  case ISD::OR:
1175  return performORCombine(N, DAG, DCI, Subtarget);
1176  case ISD::ADD:
1177  return performADDCombine(N, DAG, DCI, Subtarget);
1178  case ISD::SHL:
1179  return performSHLCombine(N, DAG, DCI, Subtarget);
1180  case ISD::SUB:
1181  return performSUBCombine(N, DAG, DCI, Subtarget);
1182  }
1183 
1184  return SDValue();
1185 }
1186 
1188  return Subtarget.hasMips32();
1189 }
1190 
1192  return Subtarget.hasMips32();
1193 }
1194 
1196  const SDNode *N, CombineLevel Level) const {
1197  if (N->getOperand(0).getValueType().isVector())
1198  return false;
1199  return true;
1200 }
1201 
1202 void
1205  SelectionDAG &DAG) const {
1206  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1207 
1208  if (Res)
1209  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1210  Results.push_back(Res.getValue(I));
1211 }
1212 
1213 void
1216  SelectionDAG &DAG) const {
1217  return LowerOperationWrapper(N, Results, DAG);
1218 }
1219 
1222 {
1223  switch (Op.getOpcode())
1224  {
1225  case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1226  case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1227  case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1228  case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1229  case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1230  case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1231  case ISD::SELECT: return lowerSELECT(Op, DAG);
1232  case ISD::SETCC: return lowerSETCC(Op, DAG);
1233  case ISD::VASTART: return lowerVASTART(Op, DAG);
1234  case ISD::VAARG: return lowerVAARG(Op, DAG);
1235  case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1236  case ISD::FABS: return lowerFABS(Op, DAG);
1237  case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1238  case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1239  case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1240  case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1241  case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1242  case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1243  case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1244  case ISD::LOAD: return lowerLOAD(Op, DAG);
1245  case ISD::STORE: return lowerSTORE(Op, DAG);
1246  case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1247  case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1248  }
1249  return SDValue();
1250 }
1251 
1252 //===----------------------------------------------------------------------===//
1253 // Lower helper functions
1254 //===----------------------------------------------------------------------===//
1255 
1256 // addLiveIn - This helper function adds the specified physical register to the
1257 // MachineFunction as a live in value. It also creates a corresponding
1258 // virtual register for it.
1259 static unsigned
1260 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1261 {
1262  Register VReg = MF.getRegInfo().createVirtualRegister(RC);
1263  MF.getRegInfo().addLiveIn(PReg, VReg);
1264  return VReg;
1265 }
1266 
1268  MachineBasicBlock &MBB,
1269  const TargetInstrInfo &TII,
1270  bool Is64Bit, bool IsMicroMips) {
1271  if (NoZeroDivCheck)
1272  return &MBB;
1273 
1274  // Insert instruction "teq $divisor_reg, $zero, 7".
1276  MachineInstrBuilder MIB;
1277  MachineOperand &Divisor = MI.getOperand(2);
1278  MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1279  TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1280  .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1281  .addReg(Mips::ZERO)
1282  .addImm(7);
1283 
1284  // Use the 32-bit sub-register if this is a 64-bit division.
1285  if (Is64Bit)
1286  MIB->getOperand(0).setSubReg(Mips::sub_32);
1287 
1288  // Clear Divisor's kill flag.
1289  Divisor.setIsKill(false);
1290 
1291  // We would normally delete the original instruction here but in this case
1292  // we only needed to inject an additional instruction rather than replace it.
1293 
1294  return &MBB;
1295 }
1296 
1299  MachineBasicBlock *BB) const {
1300  switch (MI.getOpcode()) {
1301  default:
1302  llvm_unreachable("Unexpected instr type to insert");
1303  case Mips::ATOMIC_LOAD_ADD_I8:
1304  return emitAtomicBinaryPartword(MI, BB, 1);
1305  case Mips::ATOMIC_LOAD_ADD_I16:
1306  return emitAtomicBinaryPartword(MI, BB, 2);
1307  case Mips::ATOMIC_LOAD_ADD_I32:
1308  return emitAtomicBinary(MI, BB);
1309  case Mips::ATOMIC_LOAD_ADD_I64:
1310  return emitAtomicBinary(MI, BB);
1311 
1312  case Mips::ATOMIC_LOAD_AND_I8:
1313  return emitAtomicBinaryPartword(MI, BB, 1);
1314  case Mips::ATOMIC_LOAD_AND_I16:
1315  return emitAtomicBinaryPartword(MI, BB, 2);
1316  case Mips::ATOMIC_LOAD_AND_I32:
1317  return emitAtomicBinary(MI, BB);
1318  case Mips::ATOMIC_LOAD_AND_I64:
1319  return emitAtomicBinary(MI, BB);
1320 
1321  case Mips::ATOMIC_LOAD_OR_I8:
1322  return emitAtomicBinaryPartword(MI, BB, 1);
1323  case Mips::ATOMIC_LOAD_OR_I16:
1324  return emitAtomicBinaryPartword(MI, BB, 2);
1325  case Mips::ATOMIC_LOAD_OR_I32:
1326  return emitAtomicBinary(MI, BB);
1327  case Mips::ATOMIC_LOAD_OR_I64:
1328  return emitAtomicBinary(MI, BB);
1329 
1330  case Mips::ATOMIC_LOAD_XOR_I8:
1331  return emitAtomicBinaryPartword(MI, BB, 1);
1332  case Mips::ATOMIC_LOAD_XOR_I16:
1333  return emitAtomicBinaryPartword(MI, BB, 2);
1334  case Mips::ATOMIC_LOAD_XOR_I32:
1335  return emitAtomicBinary(MI, BB);
1336  case Mips::ATOMIC_LOAD_XOR_I64:
1337  return emitAtomicBinary(MI, BB);
1338 
1339  case Mips::ATOMIC_LOAD_NAND_I8:
1340  return emitAtomicBinaryPartword(MI, BB, 1);
1341  case Mips::ATOMIC_LOAD_NAND_I16:
1342  return emitAtomicBinaryPartword(MI, BB, 2);
1343  case Mips::ATOMIC_LOAD_NAND_I32:
1344  return emitAtomicBinary(MI, BB);
1345  case Mips::ATOMIC_LOAD_NAND_I64:
1346  return emitAtomicBinary(MI, BB);
1347 
1348  case Mips::ATOMIC_LOAD_SUB_I8:
1349  return emitAtomicBinaryPartword(MI, BB, 1);
1350  case Mips::ATOMIC_LOAD_SUB_I16:
1351  return emitAtomicBinaryPartword(MI, BB, 2);
1352  case Mips::ATOMIC_LOAD_SUB_I32:
1353  return emitAtomicBinary(MI, BB);
1354  case Mips::ATOMIC_LOAD_SUB_I64:
1355  return emitAtomicBinary(MI, BB);
1356 
1357  case Mips::ATOMIC_SWAP_I8:
1358  return emitAtomicBinaryPartword(MI, BB, 1);
1359  case Mips::ATOMIC_SWAP_I16:
1360  return emitAtomicBinaryPartword(MI, BB, 2);
1361  case Mips::ATOMIC_SWAP_I32:
1362  return emitAtomicBinary(MI, BB);
1363  case Mips::ATOMIC_SWAP_I64:
1364  return emitAtomicBinary(MI, BB);
1365 
1366  case Mips::ATOMIC_CMP_SWAP_I8:
1367  return emitAtomicCmpSwapPartword(MI, BB, 1);
1368  case Mips::ATOMIC_CMP_SWAP_I16:
1369  return emitAtomicCmpSwapPartword(MI, BB, 2);
1370  case Mips::ATOMIC_CMP_SWAP_I32:
1371  return emitAtomicCmpSwap(MI, BB);
1372  case Mips::ATOMIC_CMP_SWAP_I64:
1373  return emitAtomicCmpSwap(MI, BB);
1374  case Mips::PseudoSDIV:
1375  case Mips::PseudoUDIV:
1376  case Mips::DIV:
1377  case Mips::DIVU:
1378  case Mips::MOD:
1379  case Mips::MODU:
1380  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1381  false);
1382  case Mips::SDIV_MM_Pseudo:
1383  case Mips::UDIV_MM_Pseudo:
1384  case Mips::SDIV_MM:
1385  case Mips::UDIV_MM:
1386  case Mips::DIV_MMR6:
1387  case Mips::DIVU_MMR6:
1388  case Mips::MOD_MMR6:
1389  case Mips::MODU_MMR6:
1390  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1391  case Mips::PseudoDSDIV:
1392  case Mips::PseudoDUDIV:
1393  case Mips::DDIV:
1394  case Mips::DDIVU:
1395  case Mips::DMOD:
1396  case Mips::DMODU:
1397  return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1398 
1399  case Mips::PseudoSELECT_I:
1400  case Mips::PseudoSELECT_I64:
1401  case Mips::PseudoSELECT_S:
1402  case Mips::PseudoSELECT_D32:
1403  case Mips::PseudoSELECT_D64:
1404  return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1405  case Mips::PseudoSELECTFP_F_I:
1406  case Mips::PseudoSELECTFP_F_I64:
1407  case Mips::PseudoSELECTFP_F_S:
1408  case Mips::PseudoSELECTFP_F_D32:
1409  case Mips::PseudoSELECTFP_F_D64:
1410  return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1411  case Mips::PseudoSELECTFP_T_I:
1412  case Mips::PseudoSELECTFP_T_I64:
1413  case Mips::PseudoSELECTFP_T_S:
1414  case Mips::PseudoSELECTFP_T_D32:
1415  case Mips::PseudoSELECTFP_T_D64:
1416  return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1417  case Mips::PseudoD_SELECT_I:
1418  case Mips::PseudoD_SELECT_I64:
1419  return emitPseudoD_SELECT(MI, BB);
1420  }
1421 }
1422 
1423 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1424 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1426 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1427  MachineBasicBlock *BB) const {
1428 
1429  MachineFunction *MF = BB->getParent();
1430  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1432  DebugLoc DL = MI.getDebugLoc();
1433 
1434  unsigned AtomicOp;
1435  switch (MI.getOpcode()) {
1436  case Mips::ATOMIC_LOAD_ADD_I32:
1437  AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1438  break;
1439  case Mips::ATOMIC_LOAD_SUB_I32:
1440  AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1441  break;
1442  case Mips::ATOMIC_LOAD_AND_I32:
1443  AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1444  break;
1445  case Mips::ATOMIC_LOAD_OR_I32:
1446  AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1447  break;
1448  case Mips::ATOMIC_LOAD_XOR_I32:
1449  AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1450  break;
1451  case Mips::ATOMIC_LOAD_NAND_I32:
1452  AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1453  break;
1454  case Mips::ATOMIC_SWAP_I32:
1455  AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1456  break;
1457  case Mips::ATOMIC_LOAD_ADD_I64:
1458  AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1459  break;
1460  case Mips::ATOMIC_LOAD_SUB_I64:
1461  AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1462  break;
1463  case Mips::ATOMIC_LOAD_AND_I64:
1464  AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1465  break;
1466  case Mips::ATOMIC_LOAD_OR_I64:
1467  AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1468  break;
1469  case Mips::ATOMIC_LOAD_XOR_I64:
1470  AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1471  break;
1472  case Mips::ATOMIC_LOAD_NAND_I64:
1473  AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1474  break;
1475  case Mips::ATOMIC_SWAP_I64:
1476  AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1477  break;
1478  default:
1479  llvm_unreachable("Unknown pseudo atomic for replacement!");
1480  }
1481 
1482  Register OldVal = MI.getOperand(0).getReg();
1483  Register Ptr = MI.getOperand(1).getReg();
1484  Register Incr = MI.getOperand(2).getReg();
1485  Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1486 
1488 
1489  // The scratch registers here with the EarlyClobber | Define | Implicit
1490  // flags is used to persuade the register allocator and the machine
1491  // verifier to accept the usage of this register. This has to be a real
1492  // register which has an UNDEF value but is dead after the instruction which
1493  // is unique among the registers chosen for the instruction.
1494 
1495  // The EarlyClobber flag has the semantic properties that the operand it is
1496  // attached to is clobbered before the rest of the inputs are read. Hence it
1497  // must be unique among the operands to the instruction.
1498  // The Define flag is needed to coerce the machine verifier that an Undef
1499  // value isn't a problem.
1500  // The Dead flag is needed as the value in scratch isn't used by any other
1501  // instruction. Kill isn't used as Dead is more precise.
1502  // The implicit flag is here due to the interaction between the other flags
1503  // and the machine verifier.
1504 
1505  // For correctness purpose, a new pseudo is introduced here. We need this
1506  // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1507  // that is spread over >1 basic blocks. A register allocator which
1508  // introduces (or any codegen infact) a store, can violate the expectations
1509  // of the hardware.
1510  //
1511  // An atomic read-modify-write sequence starts with a linked load
1512  // instruction and ends with a store conditional instruction. The atomic
1513  // read-modify-write sequence fails if any of the following conditions
1514  // occur between the execution of ll and sc:
1515  // * A coherent store is completed by another process or coherent I/O
1516  // module into the block of synchronizable physical memory containing
1517  // the word. The size and alignment of the block is
1518  // implementation-dependent.
1519  // * A coherent store is executed between an LL and SC sequence on the
1520  // same processor to the block of synchornizable physical memory
1521  // containing the word.
1522  //
1523 
1524  Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1525  Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1526 
1527  BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1528  BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1529 
1530  BuildMI(*BB, II, DL, TII->get(AtomicOp))
1531  .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1532  .addReg(PtrCopy)
1533  .addReg(IncrCopy)
1536 
1537  MI.eraseFromParent();
1538 
1539  return BB;
1540 }
1541 
1542 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1543  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1544  unsigned SrcReg) const {
1546  const DebugLoc &DL = MI.getDebugLoc();
1547 
1548  if (Subtarget.hasMips32r2() && Size == 1) {
1549  BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1550  return BB;
1551  }
1552 
1553  if (Subtarget.hasMips32r2() && Size == 2) {
1554  BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1555  return BB;
1556  }
1557 
1558  MachineFunction *MF = BB->getParent();
1559  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1561  Register ScrReg = RegInfo.createVirtualRegister(RC);
1562 
1563  assert(Size < 32);
1564  int64_t ShiftImm = 32 - (Size * 8);
1565 
1566  BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1567  BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1568 
1569  return BB;
1570 }
1571 
1572 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1573  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1574  assert((Size == 1 || Size == 2) &&
1575  "Unsupported size for EmitAtomicBinaryPartial.");
1576 
1577  MachineFunction *MF = BB->getParent();
1578  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1580  const bool ArePtrs64bit = ABI.ArePtrs64bit();
1581  const TargetRegisterClass *RCp =
1582  getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1584  DebugLoc DL = MI.getDebugLoc();
1585 
1586  Register Dest = MI.getOperand(0).getReg();
1587  Register Ptr = MI.getOperand(1).getReg();
1588  Register Incr = MI.getOperand(2).getReg();
1589 
1590  Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1591  Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1592  Register Mask = RegInfo.createVirtualRegister(RC);
1593  Register Mask2 = RegInfo.createVirtualRegister(RC);
1594  Register Incr2 = RegInfo.createVirtualRegister(RC);
1595  Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1596  Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1597  Register MaskUpper = RegInfo.createVirtualRegister(RC);
1598  Register Scratch = RegInfo.createVirtualRegister(RC);
1599  Register Scratch2 = RegInfo.createVirtualRegister(RC);
1600  Register Scratch3 = RegInfo.createVirtualRegister(RC);
1601 
1602  unsigned AtomicOp = 0;
1603  switch (MI.getOpcode()) {
1604  case Mips::ATOMIC_LOAD_NAND_I8:
1605  AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1606  break;
1607  case Mips::ATOMIC_LOAD_NAND_I16:
1608  AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1609  break;
1610  case Mips::ATOMIC_SWAP_I8:
1611  AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1612  break;
1613  case Mips::ATOMIC_SWAP_I16:
1614  AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1615  break;
1616  case Mips::ATOMIC_LOAD_ADD_I8:
1617  AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1618  break;
1619  case Mips::ATOMIC_LOAD_ADD_I16:
1620  AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1621  break;
1622  case Mips::ATOMIC_LOAD_SUB_I8:
1623  AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1624  break;
1625  case Mips::ATOMIC_LOAD_SUB_I16:
1626  AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1627  break;
1628  case Mips::ATOMIC_LOAD_AND_I8:
1629  AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1630  break;
1631  case Mips::ATOMIC_LOAD_AND_I16:
1632  AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1633  break;
1634  case Mips::ATOMIC_LOAD_OR_I8:
1635  AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1636  break;
1637  case Mips::ATOMIC_LOAD_OR_I16:
1638  AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1639  break;
1640  case Mips::ATOMIC_LOAD_XOR_I8:
1641  AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1642  break;
1643  case Mips::ATOMIC_LOAD_XOR_I16:
1644  AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1645  break;
1646  default:
1647  llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1648  }
1649 
1650  // insert new blocks after the current block
1651  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1652  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1654  MF->insert(It, exitMBB);
1655 
1656  // Transfer the remainder of BB and its successor edges to exitMBB.
1657  exitMBB->splice(exitMBB->begin(), BB,
1658  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1659  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1660 
1661  BB->addSuccessor(exitMBB, BranchProbability::getOne());
1662 
1663  // thisMBB:
1664  // addiu masklsb2,$0,-4 # 0xfffffffc
1665  // and alignedaddr,ptr,masklsb2
1666  // andi ptrlsb2,ptr,3
1667  // sll shiftamt,ptrlsb2,3
1668  // ori maskupper,$0,255 # 0xff
1669  // sll mask,maskupper,shiftamt
1670  // nor mask2,$0,mask
1671  // sll incr2,incr,shiftamt
1672 
1673  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1674  BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1675  .addReg(ABI.GetNullPtr()).addImm(-4);
1676  BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1677  .addReg(Ptr).addReg(MaskLSB2);
1678  BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1679  .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1680  if (Subtarget.isLittle()) {
1681  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1682  } else {
1683  Register Off = RegInfo.createVirtualRegister(RC);
1684  BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1685  .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1686  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1687  }
1688  BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1689  .addReg(Mips::ZERO).addImm(MaskImm);
1690  BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1691  .addReg(MaskUpper).addReg(ShiftAmt);
1692  BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1693  BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1694 
1695 
1696  // The purposes of the flags on the scratch registers is explained in
1697  // emitAtomicBinary. In summary, we need a scratch register which is going to
1698  // be undef, that is unique among registers chosen for the instruction.
1699 
1700  BuildMI(BB, DL, TII->get(AtomicOp))
1701  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1702  .addReg(AlignedAddr)
1703  .addReg(Incr2)
1704  .addReg(Mask)
1705  .addReg(Mask2)
1706  .addReg(ShiftAmt)
1713 
1714  MI.eraseFromParent(); // The instruction is gone now.
1715 
1716  return exitMBB;
1717 }
1718 
1719 // Lower atomic compare and swap to a pseudo instruction, taking care to
1720 // define a scratch register for the pseudo instruction's expansion. The
1721 // instruction is expanded after the register allocator as to prevent
1722 // the insertion of stores between the linked load and the store conditional.
1723 
1725 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1726  MachineBasicBlock *BB) const {
1727 
1728  assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1729  MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1730  "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1731 
1732  const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1733 
1734  MachineFunction *MF = BB->getParent();
1736  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1738  DebugLoc DL = MI.getDebugLoc();
1739 
1740  unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1741  ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1742  : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1743  Register Dest = MI.getOperand(0).getReg();
1744  Register Ptr = MI.getOperand(1).getReg();
1745  Register OldVal = MI.getOperand(2).getReg();
1746  Register NewVal = MI.getOperand(3).getReg();
1747 
1748  Register Scratch = MRI.createVirtualRegister(RC);
1750 
1751  // We need to create copies of the various registers and kill them at the
1752  // atomic pseudo. If the copies are not made, when the atomic is expanded
1753  // after fast register allocation, the spills will end up outside of the
1754  // blocks that their values are defined in, causing livein errors.
1755 
1756  Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1757  Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1758  Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1759 
1760  BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1761  BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1762  BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1763 
1764  // The purposes of the flags on the scratch registers is explained in
1765  // emitAtomicBinary. In summary, we need a scratch register which is going to
1766  // be undef, that is unique among registers chosen for the instruction.
1767 
1768  BuildMI(*BB, II, DL, TII->get(AtomicOp))
1769  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1770  .addReg(PtrCopy, RegState::Kill)
1771  .addReg(OldValCopy, RegState::Kill)
1772  .addReg(NewValCopy, RegState::Kill)
1775 
1776  MI.eraseFromParent(); // The instruction is gone now.
1777 
1778  return BB;
1779 }
1780 
1781 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1782  MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1783  assert((Size == 1 || Size == 2) &&
1784  "Unsupported size for EmitAtomicCmpSwapPartial.");
1785 
1786  MachineFunction *MF = BB->getParent();
1787  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1789  const bool ArePtrs64bit = ABI.ArePtrs64bit();
1790  const TargetRegisterClass *RCp =
1791  getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1793  DebugLoc DL = MI.getDebugLoc();
1794 
1795  Register Dest = MI.getOperand(0).getReg();
1796  Register Ptr = MI.getOperand(1).getReg();
1797  Register CmpVal = MI.getOperand(2).getReg();
1798  Register NewVal = MI.getOperand(3).getReg();
1799 
1800  Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1801  Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1802  Register Mask = RegInfo.createVirtualRegister(RC);
1803  Register Mask2 = RegInfo.createVirtualRegister(RC);
1804  Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1805  Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1806  Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1807  Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1808  Register MaskUpper = RegInfo.createVirtualRegister(RC);
1809  Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1810  Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1811  unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1812  ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1813  : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1814 
1815  // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1816  // flags are used to coerce the register allocator and the machine verifier to
1817  // accept the usage of these registers.
1818  // The EarlyClobber flag has the semantic properties that the operand it is
1819  // attached to is clobbered before the rest of the inputs are read. Hence it
1820  // must be unique among the operands to the instruction.
1821  // The Define flag is needed to coerce the machine verifier that an Undef
1822  // value isn't a problem.
1823  // The Dead flag is needed as the value in scratch isn't used by any other
1824  // instruction. Kill isn't used as Dead is more precise.
1825  Register Scratch = RegInfo.createVirtualRegister(RC);
1826  Register Scratch2 = RegInfo.createVirtualRegister(RC);
1827 
1828  // insert new blocks after the current block
1829  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1830  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1832  MF->insert(It, exitMBB);
1833 
1834  // Transfer the remainder of BB and its successor edges to exitMBB.
1835  exitMBB->splice(exitMBB->begin(), BB,
1836  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1837  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1838 
1839  BB->addSuccessor(exitMBB, BranchProbability::getOne());
1840 
1841  // thisMBB:
1842  // addiu masklsb2,$0,-4 # 0xfffffffc
1843  // and alignedaddr,ptr,masklsb2
1844  // andi ptrlsb2,ptr,3
1845  // xori ptrlsb2,ptrlsb2,3 # Only for BE
1846  // sll shiftamt,ptrlsb2,3
1847  // ori maskupper,$0,255 # 0xff
1848  // sll mask,maskupper,shiftamt
1849  // nor mask2,$0,mask
1850  // andi maskedcmpval,cmpval,255
1851  // sll shiftedcmpval,maskedcmpval,shiftamt
1852  // andi maskednewval,newval,255
1853  // sll shiftednewval,maskednewval,shiftamt
1854  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1855  BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1856  .addReg(ABI.GetNullPtr()).addImm(-4);
1857  BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1858  .addReg(Ptr).addReg(MaskLSB2);
1859  BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1860  .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1861  if (Subtarget.isLittle()) {
1862  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1863  } else {
1864  Register Off = RegInfo.createVirtualRegister(RC);
1865  BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1866  .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1867  BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1868  }
1869  BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1870  .addReg(Mips::ZERO).addImm(MaskImm);
1871  BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1872  .addReg(MaskUpper).addReg(ShiftAmt);
1873  BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1874  BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1875  .addReg(CmpVal).addImm(MaskImm);
1876  BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1877  .addReg(MaskedCmpVal).addReg(ShiftAmt);
1878  BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1879  .addReg(NewVal).addImm(MaskImm);
1880  BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1881  .addReg(MaskedNewVal).addReg(ShiftAmt);
1882 
1883  // The purposes of the flags on the scratch registers are explained in
1884  // emitAtomicBinary. In summary, we need a scratch register which is going to
1885  // be undef, that is unique among the register chosen for the instruction.
1886 
1887  BuildMI(BB, DL, TII->get(AtomicOp))
1888  .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1889  .addReg(AlignedAddr)
1890  .addReg(Mask)
1891  .addReg(ShiftedCmpVal)
1892  .addReg(Mask2)
1893  .addReg(ShiftedNewVal)
1894  .addReg(ShiftAmt)
1899 
1900  MI.eraseFromParent(); // The instruction is gone now.
1901 
1902  return exitMBB;
1903 }
1904 
1905 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1906  // The first operand is the chain, the second is the condition, the third is
1907  // the block to branch to if the condition is true.
1908  SDValue Chain = Op.getOperand(0);
1909  SDValue Dest = Op.getOperand(2);
1910  SDLoc DL(Op);
1911 
1913  SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1914 
1915  // Return if flag is not set by a floating point comparison.
1916  if (CondRes.getOpcode() != MipsISD::FPCmp)
1917  return Op;
1918 
1919  SDValue CCNode = CondRes.getOperand(2);
1920  Mips::CondCode CC =
1921  (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1922  unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1923  SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1924  SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1925  return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1926  FCC0, Dest, CondRes);
1927 }
1928 
1929 SDValue MipsTargetLowering::
1930 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1931 {
1933  SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1934 
1935  // Return if flag is not set by a floating point comparison.
1936  if (Cond.getOpcode() != MipsISD::FPCmp)
1937  return Op;
1938 
1939  return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1940  SDLoc(Op));
1941 }
1942 
1943 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1945  SDValue Cond = createFPCmp(DAG, Op);
1946 
1947  assert(Cond.getOpcode() == MipsISD::FPCmp &&
1948  "Floating point operand expected.");
1949 
1950  SDLoc DL(Op);
1951  SDValue True = DAG.getConstant(1, DL, MVT::i32);
1952  SDValue False = DAG.getConstant(0, DL, MVT::i32);
1953 
1954  return createCMovFP(DAG, Cond, True, False, DL);
1955 }
1956 
1957 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1958  SelectionDAG &DAG) const {
1959  EVT Ty = Op.getValueType();
1960  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1961  const GlobalValue *GV = N->getGlobal();
1962 
1963  if (!isPositionIndependent()) {
1964  const MipsTargetObjectFile *TLOF =
1965  static_cast<const MipsTargetObjectFile *>(
1967  const GlobalObject *GO = GV->getBaseObject();
1968  if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
1969  // %gp_rel relocation
1970  return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
1971 
1972  // %hi/%lo relocation
1973  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1974  // %highest/%higher/%hi/%lo relocation
1975  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1976  }
1977 
1978  // Every other architecture would use shouldAssumeDSOLocal in here, but
1979  // mips is special.
1980  // * In PIC code mips requires got loads even for local statics!
1981  // * To save on got entries, for local statics the got entry contains the
1982  // page and an additional add instruction takes care of the low bits.
1983  // * It is legal to access a hidden symbol with a non hidden undefined,
1984  // so one cannot guarantee that all access to a hidden symbol will know
1985  // it is hidden.
1986  // * Mips linkers don't support creating a page and a full got entry for
1987  // the same symbol.
1988  // * Given all that, we have to use a full got entry for hidden symbols :-(
1989  if (GV->hasLocalLinkage())
1990  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1991 
1992  if (LargeGOT)
1993  return getAddrGlobalLargeGOT(
1995  DAG.getEntryNode(),
1996  MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1997 
1998  return getAddrGlobal(
1999  N, SDLoc(N), Ty, DAG,
2001  DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2002 }
2003 
2004 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2005  SelectionDAG &DAG) const {
2006  BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2007  EVT Ty = Op.getValueType();
2008 
2009  if (!isPositionIndependent())
2010  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2011  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2012 
2013  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2014 }
2015 
2016 SDValue MipsTargetLowering::
2017 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2018 {
2019  // If the relocation model is PIC, use the General Dynamic TLS Model or
2020  // Local Dynamic TLS model, otherwise use the Initial Exec or
2021  // Local Exec TLS Model.
2022 
2023  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2024  if (DAG.getTarget().useEmulatedTLS())
2025  return LowerToTLSEmulatedModel(GA, DAG);
2026 
2027  SDLoc DL(GA);
2028  const GlobalValue *GV = GA->getGlobal();
2029  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2030 
2032 
2033  if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2034  // General Dynamic and Local Dynamic TLS Model.
2035  unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2036  : MipsII::MO_TLSGD;
2037 
2038  SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2039  SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2040  getGlobalReg(DAG, PtrVT), TGA);
2041  unsigned PtrSize = PtrVT.getSizeInBits();
2042  IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2043 
2044  SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2045 
2046  ArgListTy Args;
2048  Entry.Node = Argument;
2049  Entry.Ty = PtrTy;
2050  Args.push_back(Entry);
2051 
2053  CLI.setDebugLoc(DL)
2054  .setChain(DAG.getEntryNode())
2055  .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2056  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2057 
2058  SDValue Ret = CallResult.first;
2059 
2060  if (model != TLSModel::LocalDynamic)
2061  return Ret;
2062 
2063  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2065  SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2066  SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2068  SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2069  SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2070  return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2071  }
2072 
2073  SDValue Offset;
2074  if (model == TLSModel::InitialExec) {
2075  // Initial Exec TLS Model
2076  SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2078  TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2079  TGA);
2080  Offset =
2081  DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2082  } else {
2083  // Local Exec TLS Model
2084  assert(model == TLSModel::LocalExec);
2085  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2087  SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2089  SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2090  SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2091  Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2092  }
2093 
2095  return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2096 }
2097 
2098 SDValue MipsTargetLowering::
2099 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2100 {
2101  JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2102  EVT Ty = Op.getValueType();
2103 
2104  if (!isPositionIndependent())
2105  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2106  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2107 
2108  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2109 }
2110 
2111 SDValue MipsTargetLowering::
2112 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2113 {
2114  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2115  EVT Ty = Op.getValueType();
2116 
2117  if (!isPositionIndependent()) {
2118  const MipsTargetObjectFile *TLOF =
2119  static_cast<const MipsTargetObjectFile *>(
2121 
2122  if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2123  getTargetMachine()))
2124  // %gp_rel relocation
2125  return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2126 
2127  return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2128  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2129  }
2130 
2131  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2132 }
2133 
2134 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2135  MachineFunction &MF = DAG.getMachineFunction();
2136  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2137 
2138  SDLoc DL(Op);
2139  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2140  getPointerTy(MF.getDataLayout()));
2141 
2142  // vastart just stores the address of the VarArgsFrameIndex slot into the
2143  // memory location argument.
2144  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2145  return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2146  MachinePointerInfo(SV));
2147 }
2148 
2149 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2150  SDNode *Node = Op.getNode();
2151  EVT VT = Node->getValueType(0);
2152  SDValue Chain = Node->getOperand(0);
2153  SDValue VAListPtr = Node->getOperand(1);
2154  const llvm::Align Align =
2155  llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2156  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2157  SDLoc DL(Node);
2158  unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2159 
2160  SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2161  VAListPtr, MachinePointerInfo(SV));
2162  SDValue VAList = VAListLoad;
2163 
2164  // Re-align the pointer if necessary.
2165  // It should only ever be necessary for 64-bit types on O32 since the minimum
2166  // argument alignment is the same as the maximum type alignment for N32/N64.
2167  //
2168  // FIXME: We currently align too often. The code generator doesn't notice
2169  // when the pointer is still aligned from the last va_arg (or pair of
2170  // va_args for the i64 on O32 case).
2171  if (Align > getMinStackArgumentAlignment()) {
2172  VAList = DAG.getNode(
2173  ISD::ADD, DL, VAList.getValueType(), VAList,
2174  DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2175 
2176  VAList = DAG.getNode(
2177  ISD::AND, DL, VAList.getValueType(), VAList,
2178  DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2179  }
2180 
2181  // Increment the pointer, VAList, to the next vaarg.
2182  auto &TD = DAG.getDataLayout();
2183  unsigned ArgSizeInBytes =
2184  TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2185  SDValue Tmp3 =
2186  DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2187  DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2188  DL, VAList.getValueType()));
2189  // Store the incremented VAList to the legalized pointer
2190  Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2191  MachinePointerInfo(SV));
2192 
2193  // In big-endian mode we must adjust the pointer when the load size is smaller
2194  // than the argument slot size. We must also reduce the known alignment to
2195  // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2196  // the correct half of the slot, and reduce the alignment from 8 (slot
2197  // alignment) down to 4 (type alignment).
2198  if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2199  unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2200  VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2201  DAG.getIntPtrConstant(Adjustment, DL));
2202  }
2203  // Load the actual argument out of the pointer VAList
2204  return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2205 }
2206 
2208  bool HasExtractInsert) {
2209  EVT TyX = Op.getOperand(0).getValueType();
2210  EVT TyY = Op.getOperand(1).getValueType();
2211  SDLoc DL(Op);
2212  SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2213  SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2214  SDValue Res;
2215 
2216  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2217  // to i32.
2218  SDValue X = (TyX == MVT::f32) ?
2219  DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2221  Const1);
2222  SDValue Y = (TyY == MVT::f32) ?
2223  DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2225  Const1);
2226 
2227  if (HasExtractInsert) {
2228  // ext E, Y, 31, 1 ; extract bit31 of Y
2229  // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2230  SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2231  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2232  } else {
2233  // sll SllX, X, 1
2234  // srl SrlX, SllX, 1
2235  // srl SrlY, Y, 31
2236  // sll SllY, SrlX, 31
2237  // or Or, SrlX, SllY
2238  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2239  SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2240  SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2241  SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2242  Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2243  }
2244 
2245  if (TyX == MVT::f32)
2246  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2247 
2249  Op.getOperand(0),
2250  DAG.getConstant(0, DL, MVT::i32));
2251  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2252 }
2253 
2255  bool HasExtractInsert) {
2256  unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2257  unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2258  EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2259  SDLoc DL(Op);
2260  SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2261 
2262  // Bitcast to integer nodes.
2263  SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2264  SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2265 
2266  if (HasExtractInsert) {
2267  // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2268  // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2269  SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2270  DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2271 
2272  if (WidthX > WidthY)
2273  E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2274  else if (WidthY > WidthX)
2275  E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2276 
2277  SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2278  DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2279  X);
2280  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2281  }
2282 
2283  // (d)sll SllX, X, 1
2284  // (d)srl SrlX, SllX, 1
2285  // (d)srl SrlY, Y, width(Y)-1
2286  // (d)sll SllY, SrlX, width(Y)-1
2287  // or Or, SrlX, SllY
2288  SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2289  SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2290  SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2291  DAG.getConstant(WidthY - 1, DL, MVT::i32));
2292 
2293  if (WidthX > WidthY)
2294  SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2295  else if (WidthY > WidthX)
2296  SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2297 
2298  SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2299  DAG.getConstant(WidthX - 1, DL, MVT::i32));
2300  SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2301  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2302 }
2303 
2304 SDValue
2305 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2306  if (Subtarget.isGP64bit())
2307  return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2308 
2309  return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2310 }
2311 
2313  bool HasExtractInsert) {
2314  SDLoc DL(Op);
2315  SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2316 
2317  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2318  // to i32.
2319  SDValue X = (Op.getValueType() == MVT::f32)
2320  ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2322  Op.getOperand(0), Const1);
2323 
2324  // Clear MSB.
2325  if (HasExtractInsert)
2326  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2327  DAG.getRegister(Mips::ZERO, MVT::i32),
2328  DAG.getConstant(31, DL, MVT::i32), Const1, X);
2329  else {
2330  // TODO: Provide DAG patterns which transform (and x, cst)
2331  // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2332  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2333  Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2334  }
2335 
2336  if (Op.getValueType() == MVT::f32)
2337  return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2338 
2339  // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2340  // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2341  // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2342  // place.
2343  SDValue LowX =
2345  DAG.getConstant(0, DL, MVT::i32));
2346  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2347 }
2348 
2350  bool HasExtractInsert) {
2351  SDLoc DL(Op);
2352  SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2353 
2354  // Bitcast to integer node.
2355  SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2356 
2357  // Clear MSB.
2358  if (HasExtractInsert)
2359  Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2360  DAG.getRegister(Mips::ZERO_64, MVT::i64),
2361  DAG.getConstant(63, DL, MVT::i32), Const1, X);
2362  else {
2363  SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2364  Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2365  }
2366 
2367  return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2368 }
2369 
2370 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2371  if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2372  return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2373 
2374  return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2375 }
2376 
2377 SDValue MipsTargetLowering::
2378 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2379  // check the depth
2380  if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2381  DAG.getContext()->emitError(
2382  "return address can be determined only for current frame");
2383  return SDValue();
2384  }
2385 
2387  MFI.setFrameAddressIsTaken(true);
2388  EVT VT = Op.getValueType();
2389  SDLoc DL(Op);
2390  SDValue FrameAddr = DAG.getCopyFromReg(
2391  DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2392  return FrameAddr;
2393 }
2394 
2395 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2396  SelectionDAG &DAG) const {
2398  return SDValue();
2399 
2400  // check the depth
2401  if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2402  DAG.getContext()->emitError(
2403  "return address can be determined only for current frame");
2404  return SDValue();
2405  }
2406 
2407  MachineFunction &MF = DAG.getMachineFunction();
2408  MachineFrameInfo &MFI = MF.getFrameInfo();
2409  MVT VT = Op.getSimpleValueType();
2410  unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2411  MFI.setReturnAddressIsTaken(true);
2412 
2413  // Return RA, which contains the return address. Mark it an implicit live-in.
2414  unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2415  return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2416 }
2417 
2418 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2419 // generated from __builtin_eh_return (offset, handler)
2420 // The effect of this is to adjust the stack pointer by "offset"
2421 // and then branch to "handler".
2422 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2423  const {
2424  MachineFunction &MF = DAG.getMachineFunction();
2425  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2426 
2427  MipsFI->setCallsEhReturn();
2428  SDValue Chain = Op.getOperand(0);
2429  SDValue Offset = Op.getOperand(1);
2430  SDValue Handler = Op.getOperand(2);
2431  SDLoc DL(Op);
2432  EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2433 
2434  // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2435  // EH_RETURN nodes, so that instructions are emitted back-to-back.
2436  unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2437  unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2438  Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2439  Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2440  return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2441  DAG.getRegister(OffsetReg, Ty),
2442  DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2443  Chain.getValue(1));
2444 }
2445 
2446 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2447  SelectionDAG &DAG) const {
2448  // FIXME: Need pseudo-fence for 'singlethread' fences
2449  // FIXME: Set SType for weaker fences where supported/appropriate.
2450  unsigned SType = 0;
2451  SDLoc DL(Op);
2452  return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2453  DAG.getConstant(SType, DL, MVT::i32));
2454 }
2455 
2456 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2457  SelectionDAG &DAG) const {
2458  SDLoc DL(Op);
2460 
2461  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2462  SDValue Shamt = Op.getOperand(2);
2463  // if shamt < (VT.bits):
2464  // lo = (shl lo, shamt)
2465  // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2466  // else:
2467  // lo = 0
2468  // hi = (shl lo, shamt[4:0])
2469  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2470  DAG.getConstant(-1, DL, MVT::i32));
2471  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2472  DAG.getConstant(1, DL, VT));
2473  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2474  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2475  SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2476  SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2477  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2478  DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2479  Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2480  DAG.getConstant(0, DL, VT), ShiftLeftLo);
2481  Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2482 
2483  SDValue Ops[2] = {Lo, Hi};
2484  return DAG.getMergeValues(Ops, DL);
2485 }
2486 
2487 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2488  bool IsSRA) const {
2489  SDLoc DL(Op);
2490  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2491  SDValue Shamt = Op.getOperand(2);
2493 
2494  // if shamt < (VT.bits):
2495  // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2496  // if isSRA:
2497  // hi = (sra hi, shamt)
2498  // else:
2499  // hi = (srl hi, shamt)
2500  // else:
2501  // if isSRA:
2502  // lo = (sra hi, shamt[4:0])
2503  // hi = (sra hi, 31)
2504  // else:
2505  // lo = (srl hi, shamt[4:0])
2506  // hi = 0
2507  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2508  DAG.getConstant(-1, DL, MVT::i32));
2509  SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2510  DAG.getConstant(1, DL, VT));
2511  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2512  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2513  SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2514  SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2515  DL, VT, Hi, Shamt);
2516  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2517  DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2518  SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2519  DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2520 
2521  if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2522  SDVTList VTList = DAG.getVTList(VT, VT);
2523  return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2524  : Mips::PseudoD_SELECT_I,
2525  DL, VTList, Cond, ShiftRightHi,
2526  IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2527  ShiftRightHi);
2528  }
2529 
2530  Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2531  Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2532  IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2533 
2534  SDValue Ops[2] = {Lo, Hi};
2535  return DAG.getMergeValues(Ops, DL);
2536 }
2537 
2538 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2539  SDValue Chain, SDValue Src, unsigned Offset) {
2540  SDValue Ptr = LD->getBasePtr();
2541  EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2542  EVT BasePtrVT = Ptr.getValueType();
2543  SDLoc DL(LD);
2544  SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2545 
2546  if (Offset)
2547  Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2548  DAG.getConstant(Offset, DL, BasePtrVT));
2549 
2550  SDValue Ops[] = { Chain, Ptr, Src };
2551  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2552  LD->getMemOperand());
2553 }
2554 
2555 // Expand an unaligned 32 or 64-bit integer load node.
2557  LoadSDNode *LD = cast<LoadSDNode>(Op);
2558  EVT MemVT = LD->getMemoryVT();
2559 
2561  return Op;
2562 
2563  // Return if load is aligned or if MemVT is neither i32 nor i64.
2564  if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2565  ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2566  return SDValue();
2567 
2568  bool IsLittle = Subtarget.isLittle();
2569  EVT VT = Op.getValueType();
2571  SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2572 
2573  assert((VT == MVT::i32) || (VT == MVT::i64));
2574 
2575  // Expand
2576  // (set dst, (i64 (load baseptr)))
2577  // to
2578  // (set tmp, (ldl (add baseptr, 7), undef))
2579  // (set dst, (ldr baseptr, tmp))
2580  if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2581  SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2582  IsLittle ? 7 : 0);
2583  return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2584  IsLittle ? 0 : 7);
2585  }
2586 
2587  SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2588  IsLittle ? 3 : 0);
2589  SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2590  IsLittle ? 0 : 3);
2591 
2592  // Expand
2593  // (set dst, (i32 (load baseptr))) or
2594  // (set dst, (i64 (sextload baseptr))) or
2595  // (set dst, (i64 (extload baseptr)))
2596  // to
2597  // (set tmp, (lwl (add baseptr, 3), undef))
2598  // (set dst, (lwr baseptr, tmp))
2599  if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2600  (ExtType == ISD::EXTLOAD))
2601  return LWR;
2602 
2603  assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2604 
2605  // Expand
2606  // (set dst, (i64 (zextload baseptr)))
2607  // to
2608  // (set tmp0, (lwl (add baseptr, 3), undef))
2609  // (set tmp1, (lwr baseptr, tmp0))
2610  // (set tmp2, (shl tmp1, 32))
2611  // (set dst, (srl tmp2, 32))
2612  SDLoc DL(LD);
2613  SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2614  SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2615  SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2616  SDValue Ops[] = { SRL, LWR.getValue(1) };
2617  return DAG.getMergeValues(Ops, DL);
2618 }
2619 
2620 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2621  SDValue Chain, unsigned Offset) {
2622  SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2623  EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2624  SDLoc DL(SD);
2625  SDVTList VTList = DAG.getVTList(MVT::Other);
2626 
2627  if (Offset)
2628  Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2629  DAG.getConstant(Offset, DL, BasePtrVT));
2630 
2631  SDValue Ops[] = { Chain, Value, Ptr };
2632  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2633  SD->getMemOperand());
2634 }
2635 
2636 // Expand an unaligned 32 or 64-bit integer store node.
2638  bool IsLittle) {
2639  SDValue Value = SD->getValue(), Chain = SD->getChain();
2640  EVT VT = Value.getValueType();
2641 
2642  // Expand
2643  // (store val, baseptr) or
2644  // (truncstore val, baseptr)
2645  // to
2646  // (swl val, (add baseptr, 3))
2647  // (swr val, baseptr)
2648  if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2649  SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2650  IsLittle ? 3 : 0);
2651  return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2652  }
2653 
2654  assert(VT == MVT::i64);
2655 
2656  // Expand
2657  // (store val, baseptr)
2658  // to
2659  // (sdl val, (add baseptr, 7))
2660  // (sdr val, baseptr)
2661  SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2662  return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2663 }
2664 
2665 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2667  bool SingleFloat) {
2668  SDValue Val = SD->getValue();
2669 
2670  if (Val.getOpcode() != ISD::FP_TO_SINT ||
2671  (Val.getValueSizeInBits() > 32 && SingleFloat))
2672  return SDValue();
2673 
2675  SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2676  Val.getOperand(0));
2677  return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2678  SD->getPointerInfo(), SD->getAlignment(),
2679  SD->getMemOperand()->getFlags());
2680 }
2681 
2683  StoreSDNode *SD = cast<StoreSDNode>(Op);
2684  EVT MemVT = SD->getMemoryVT();
2685 
2686  // Lower unaligned integer stores.
2688  (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2689  ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2690  return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2691 
2692  return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2693 }
2694 
2695 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2696  SelectionDAG &DAG) const {
2697 
2698  // Return a fixed StackObject with offset 0 which points to the old stack
2699  // pointer.
2701  EVT ValTy = Op->getValueType(0);
2702  int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2703  return DAG.getFrameIndex(FI, ValTy);
2704 }
2705 
2706 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2707  SelectionDAG &DAG) const {
2708  if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2709  return SDValue();
2710 
2712  SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2713  Op.getOperand(0));
2714  return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2715 }
2716 
2717 //===----------------------------------------------------------------------===//
2718 // Calling Convention Implementation
2719 //===----------------------------------------------------------------------===//
2720 
2721 //===----------------------------------------------------------------------===//
2722 // TODO: Implement a generic logic using tblgen that can support this.
2723 // Mips O32 ABI rules:
2724 // ---
2725 // i32 - Passed in A0, A1, A2, A3 and stack
2726 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2727 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2728 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2729 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2730 // not used, it must be shadowed. If only A3 is available, shadow it and
2731 // go to stack.
2732 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2733 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2734 // with the remainder spilled to the stack.
2735 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2736 // spilling the remainder to the stack.
2737 //
2738 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2739 //===----------------------------------------------------------------------===//
2740 
2741 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2742  CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2743  CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2744  const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2745  State.getMachineFunction().getSubtarget());
2746 
2747  static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2748 
2749  const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2750 
2751  static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2752 
2753  static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2754 
2755  // Do not process byval args here.
2756  if (ArgFlags.isByVal())
2757  return true;
2758 
2759  // Promote i8 and i16
2760  if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2761  if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2762  LocVT = MVT::i32;
2763  if (ArgFlags.isSExt())
2764  LocInfo = CCValAssign::SExtUpper;
2765  else if (ArgFlags.isZExt())
2766  LocInfo = CCValAssign::ZExtUpper;
2767  else
2768  LocInfo = CCValAssign::AExtUpper;
2769  }
2770  }
2771 
2772  // Promote i8 and i16
2773  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2774  LocVT = MVT::i32;
2775  if (ArgFlags.isSExt())
2776  LocInfo = CCValAssign::SExt;
2777  else if (ArgFlags.isZExt())
2778  LocInfo = CCValAssign::ZExt;
2779  else
2780  LocInfo = CCValAssign::AExt;
2781  }
2782 
2783  unsigned Reg;
2784 
2785  // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2786  // is true: function is vararg, argument is 3rd or higher, there is previous
2787  // argument which is not f32 or f64.
2788  bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2789  State.getFirstUnallocated(F32Regs) != ValNo;
2790  unsigned OrigAlign = ArgFlags.getOrigAlign();
2791  bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2792  bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2793 
2794  // The MIPS vector ABI for floats passes them in a pair of registers
2795  if (ValVT == MVT::i32 && isVectorFloat) {
2796  // This is the start of an vector that was scalarized into an unknown number
2797  // of components. It doesn't matter how many there are. Allocate one of the
2798  // notional 8 byte aligned registers which map onto the argument stack, and
2799  // shadow the register lost to alignment requirements.
2800  if (ArgFlags.isSplit()) {
2801  Reg = State.AllocateReg(FloatVectorIntRegs);
2802  if (Reg == Mips::A2)
2803  State.AllocateReg(Mips::A1);
2804  else if (Reg == 0)
2805  State.AllocateReg(Mips::A3);
2806  } else {
2807  // If we're an intermediate component of the split, we can just attempt to
2808  // allocate a register directly.
2809  Reg = State.AllocateReg(IntRegs);
2810  }
2811  } else if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2812  Reg = State.AllocateReg(IntRegs);
2813  // If this is the first part of an i64 arg,
2814  // the allocated register must be either A0 or A2.
2815  if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2816  Reg = State.AllocateReg(IntRegs);
2817  LocVT = MVT::i32;
2818  } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2819  // Allocate int register and shadow next int register. If first
2820  // available register is Mips::A1 or Mips::A3, shadow it too.
2821  Reg = State.AllocateReg(IntRegs);
2822  if (Reg == Mips::A1 || Reg == Mips::A3)
2823  Reg = State.AllocateReg(IntRegs);
2824  State.AllocateReg(IntRegs);
2825  LocVT = MVT::i32;
2826  } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2827  // we are guaranteed to find an available float register
2828  if (ValVT == MVT::f32) {
2829  Reg = State.AllocateReg(F32Regs);
2830  // Shadow int register
2831  State.AllocateReg(IntRegs);
2832  } else {
2833  Reg = State.AllocateReg(F64Regs);
2834  // Shadow int registers
2835  unsigned Reg2 = State.AllocateReg(IntRegs);
2836  if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2837  State.AllocateReg(IntRegs);
2838  State.AllocateReg(IntRegs);
2839  }
2840  } else
2841  llvm_unreachable("Cannot handle this ValVT.");
2842 
2843  if (!Reg) {
2844  unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2845  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2846  } else
2847  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2848 
2849  return false;
2850 }
2851 
2852 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2853  MVT LocVT, CCValAssign::LocInfo LocInfo,
2854  ISD::ArgFlagsTy ArgFlags, CCState &State) {
2855  static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2856 
2857  return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2858 }
2859 
2860 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2861  MVT LocVT, CCValAssign::LocInfo LocInfo,
2862  ISD::ArgFlagsTy ArgFlags, CCState &State) {
2863  static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2864 
2865  return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2866 }
2867 
2868 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2869  CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2871 
2872 #include "MipsGenCallingConv.inc"
2873 
2875  return CC_Mips;
2876  }
2877 
2879  return RetCC_Mips;
2880  }
2881 //===----------------------------------------------------------------------===//
2882 // Call Calling Convention Implementation
2883 //===----------------------------------------------------------------------===//
2884 
2885 // Return next O32 integer argument register.
2886 static unsigned getNextIntArgReg(unsigned Reg) {
2887  assert((Reg == Mips::A0) || (Reg == Mips::A2));
2888  return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2889 }
2890 
2891 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2892  SDValue Chain, SDValue Arg,
2893  const SDLoc &DL, bool IsTailCall,
2894  SelectionDAG &DAG) const {
2895  if (!IsTailCall) {
2896  SDValue PtrOff =
2897  DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2898  DAG.getIntPtrConstant(Offset, DL));
2899  return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2900  }
2901 
2903  int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2904  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2905  return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2906  /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2907 }
2908 
2911  std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
2912  bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2913  bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2914  SDValue Chain) const {
2915  // Insert node "GP copy globalreg" before call to function.
2916  //
2917  // R_MIPS_CALL* operators (emitted when non-internal functions are called
2918  // in PIC mode) allow symbols to be resolved via lazy binding.
2919  // The lazy binding stub requires GP to point to the GOT.
2920  // Note that we don't need GP to point to the GOT for indirect calls
2921  // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2922  // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2923  // used for the function (that is, Mips linker doesn't generate lazy binding
2924  // stub for a function whose address is taken in the program).
2925  if (IsPICCall && !InternalLinkage && IsCallReloc) {
2926  unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2927  EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2928  RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2929  }
2930 
2931  // Build a sequence of copy-to-reg nodes chained together with token
2932  // chain and flag operands which copy the outgoing args into registers.
2933  // The InFlag in necessary since all emitted instructions must be
2934  // stuck together.
2935  SDValue InFlag;
2936 
2937  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2938  Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2939  RegsToPass[i].second, InFlag);
2940  InFlag = Chain.getValue(1);
2941  }
2942 
2943  // Add argument registers to the end of the list so that they are
2944  // known live into the call.
2945  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2946  Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2947  RegsToPass[i].second.getValueType()));
2948 
2949  // Add a register mask operand representing the call-preserved registers.
2951  const uint32_t *Mask =
2953  assert(Mask && "Missing call preserved mask for calling convention");
2954  if (Subtarget.inMips16HardFloat()) {
2955  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2956  StringRef Sym = G->getGlobal()->getName();
2957  Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2958  if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2960  }
2961  }
2962  }
2963  Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2964 
2965  if (InFlag.getNode())
2966  Ops.push_back(InFlag);
2967 }
2968 
2970  SDNode *Node) const {
2971  switch (MI.getOpcode()) {
2972  default:
2973  return;
2974  case Mips::JALR:
2975  case Mips::JALRPseudo:
2976  case Mips::JALR64:
2977  case Mips::JALR64Pseudo:
2978  case Mips::JALR16_MM:
2979  case Mips::JALRC16_MMR6:
2980  case Mips::TAILCALLREG:
2981  case Mips::TAILCALLREG64:
2982  case Mips::TAILCALLR6REG:
2983  case Mips::TAILCALL64R6REG:
2984  case Mips::TAILCALLREG_MM:
2985  case Mips::TAILCALLREG_MMR6: {
2986  if (!EmitJalrReloc ||
2987  Subtarget.inMips16Mode() ||
2988  !isPositionIndependent() ||
2989  Node->getNumOperands() < 1 ||
2990  Node->getOperand(0).getNumOperands() < 2) {
2991  return;
2992  }
2993  // We are after the callee address, set by LowerCall().
2994  // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
2995  // symbol.
2996  const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
2997  StringRef Sym;
2998  if (const GlobalAddressSDNode *G =
2999  dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3000  Sym = G->getGlobal()->getName();
3001  }
3002  else if (const ExternalSymbolSDNode *ES =
3003  dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3004  Sym = ES->getSymbol();
3005  }
3006 
3007  if (Sym.empty())
3008  return;
3009 
3010  MachineFunction *MF = MI.getParent()->getParent();
3011  MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3013  }
3014  }
3015 }
3016 
3017 /// LowerCall - functions arguments are copied from virtual regs to
3018 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3019 SDValue
3020 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3021  SmallVectorImpl<SDValue> &InVals) const {
3022  SelectionDAG &DAG = CLI.DAG;
3023  SDLoc DL = CLI.DL;
3025  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3027  SDValue Chain = CLI.Chain;
3028  SDValue Callee = CLI.Callee;
3029  bool &IsTailCall = CLI.IsTailCall;
3030  CallingConv::ID CallConv = CLI.CallConv;
3031  bool IsVarArg = CLI.IsVarArg;
3032 
3033  MachineFunction &MF = DAG.getMachineFunction();
3034  MachineFrameInfo &MFI = MF.getFrameInfo();
3036  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3037  bool IsPIC = isPositionIndependent();
3038 
3039  // Analyze operands of the call, assigning locations to each operand.
3041  MipsCCState CCInfo(
3042  CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3044 
3045  const ExternalSymbolSDNode *ES =
3046  dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
3047 
3048  // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3049  // is during the lowering of a call with a byval argument which produces
3050  // a call to memcpy. For the O32 case, this causes the caller to allocate
3051  // stack space for the reserved argument area for the callee, then recursively
3052  // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3053  // ABIs mandate that the callee allocates the reserved argument area. We do
3054  // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3055  //
3056  // If the callee has a byval argument and memcpy is used, we are mandated
3057  // to already have produced a reserved argument area for the callee for O32.
3058  // Therefore, the reserved argument area can be reused for both calls.
3059  //
3060  // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3061  // present, as we have yet to hook that node onto the chain.
3062  //
3063  // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3064  // case. GCC does a similar trick, in that wherever possible, it calculates
3065  // the maximum out going argument area (including the reserved area), and
3066  // preallocates the stack space on entrance to the caller.
3067  //
3068  // FIXME: We should do the same for efficiency and space.
3069 
3070  // Note: The check on the calling convention below must match
3071  // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3072  bool MemcpyInByVal = ES &&
3073  StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3074  CallConv != CallingConv::Fast &&
3075  Chain.getOpcode() == ISD::CALLSEQ_START;
3076 
3077  // Allocate the reserved argument area. It seems strange to do this from the
3078  // caller side but removing it breaks the frame size calculation.
3079  unsigned ReservedArgArea =
3080  MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3081  CCInfo.AllocateStack(ReservedArgArea, 1);
3082 
3083  CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3084  ES ? ES->getSymbol() : nullptr);
3085 
3086  // Get a count of how many bytes are to be pushed on the stack.
3087  unsigned NextStackOffset = CCInfo.getNextStackOffset();
3088 
3089  // Check if it's really possible to do a tail call. Restrict it to functions
3090  // that are part of this compilation unit.
3091  bool InternalLinkage = false;
3092  if (IsTailCall) {
3093  IsTailCall = isEligibleForTailCallOptimization(
3094  CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3095  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3096  InternalLinkage = G->getGlobal()->hasInternalLinkage();
3097  IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3098  G->getGlobal()->hasPrivateLinkage() ||
3099  G->getGlobal()->hasHiddenVisibility() ||
3100  G->getGlobal()->hasProtectedVisibility());
3101  }
3102  }
3103  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3104  report_fatal_error("failed to perform tail call elimination on a call "
3105  "site marked musttail");
3106 
3107  if (IsTailCall)
3108  ++NumTailCalls;
3109 
3110  // Chain is the output chain of the last Load/Store or CopyToReg node.
3111  // ByValChain is the output chain of the last Memcpy node created for copying
3112  // byval arguments to the stack.
3113  unsigned StackAlignment = TFL->getStackAlignment();
3114  NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3115  SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3116 
3117  if (!(IsTailCall || MemcpyInByVal))
3118  Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3119 
3120  SDValue StackPtr =
3121  DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3122  getPointerTy(DAG.getDataLayout()));
3123 
3124  std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3125  SmallVector<SDValue, 8> MemOpChains;
3126 
3127  CCInfo.rewindByValRegsInfo();
3128 
3129  // Walk the register/memloc assignments, inserting copies/loads.
3130  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131  SDValue Arg = OutVals[i];
3132  CCValAssign &VA = ArgLocs[i];
3133  MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3134  ISD::ArgFlagsTy Flags = Outs[i].Flags;
3135  bool UseUpperBits = false;
3136 
3137  // ByVal Arg.
3138  if (Flags.isByVal()) {
3139  unsigned FirstByValReg, LastByValReg;
3140  unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3141  CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3142 
3143  assert(Flags.getByValSize() &&
3144  "ByVal args of size 0 should have been ignored by front-end.");
3145  assert(ByValIdx < CCInfo.getInRegsParamsCount());
3146  assert(!IsTailCall &&
3147  "Do not tail-call optimize if there is a byval argument.");
3148  passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3149  FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3150  VA);
3151  CCInfo.nextInRegsParam();
3152  continue;
3153  }
3154 
3155  // Promote the value if needed.
3156  switch (VA.getLocInfo()) {
3157  default:
3158  llvm_unreachable("Unknown loc info!");
3159  case CCValAssign::Full:
3160  if (VA.isRegLoc()) {
3161  if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3162  (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3163  (ValVT == MVT::i64 && LocVT == MVT::f64))
3164  Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3165  else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3167  Arg, DAG.getConstant(0, DL, MVT::i32));
3169  Arg, DAG.getConstant(1, DL, MVT::i32));
3170  if (!Subtarget.isLittle())
3171  std::swap(Lo, Hi);
3172  Register LocRegLo = VA.getLocReg();
3173  unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3174  RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3175  RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3176  continue;
3177  }
3178  }
3179  break;
3180  case CCValAssign::BCvt:
3181  Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3182  break;
3184  UseUpperBits = true;
3186  case CCValAssign::SExt:
3187  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3188  break;
3190  UseUpperBits = true;
3192  case CCValAssign::ZExt:
3193  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3194  break;
3196  UseUpperBits = true;
3198  case CCValAssign::AExt:
3199  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3200  break;
3201  }
3202 
3203  if (UseUpperBits) {
3204  unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3205  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3206  Arg = DAG.getNode(
3207  ISD::SHL, DL, VA.getLocVT(), Arg,
3208  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3209  }
3210 
3211  // Arguments that can be passed on register must be kept at
3212  // RegsToPass vector
3213  if (VA.isRegLoc()) {
3214  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3215  continue;
3216  }
3217 
3218  // Register can't get to this point...
3219  assert(VA.isMemLoc());
3220 
3221  // emit ISD::STORE whichs stores the
3222  // parameter value to a stack Location
3223  MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3224  Chain, Arg, DL, IsTailCall, DAG));
3225  }
3226 
3227  // Transform all store nodes into one single node because all store
3228  // nodes are independent of each other.
3229  if (!MemOpChains.empty())
3230  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3231 
3232  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3233  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3234  // node so that legalize doesn't hack it.
3235 
3236  EVT Ty = Callee.getValueType();
3237  bool GlobalOrExternal = false, IsCallReloc = false;
3238 
3239  // The long-calls feature is ignored in case of PIC.
3240  // While we do not support -mshared / -mno-shared properly,
3241  // ignore long-calls in case of -mabicalls too.
3242  if (!Subtarget.isABICalls() && !IsPIC) {
3243  // If the function should be called using "long call",
3244  // get its address into a register to prevent using
3245  // of the `jal` instruction for the direct call.
3246  if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3247  if (Subtarget.useLongCalls())
3248  Callee = Subtarget.hasSym32()
3249  ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3250  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3251  } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3252  bool UseLongCalls = Subtarget.useLongCalls();
3253  // If the function has long-call/far/near attribute
3254  // it overrides command line switch pased to the backend.
3255  if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3256  if (F->hasFnAttribute("long-call"))
3257  UseLongCalls = true;
3258  else if (F->hasFnAttribute("short-call"))
3259  UseLongCalls = false;
3260  }
3261  if (UseLongCalls)
3262  Callee = Subtarget.hasSym32()
3263  ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3264  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3265  }
3266  }
3267 
3268  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3269  if (IsPIC) {
3270  const GlobalValue *Val = G->getGlobal();
3271  InternalLinkage = Val->hasInternalLinkage();
3272 
3273  if (InternalLinkage)
3274  Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3275  else if (LargeGOT) {
3276  Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3277  MipsII::MO_CALL_LO16, Chain,
3278  FuncInfo->callPtrInfo(Val));
3279  IsCallReloc = true;
3280  } else {
3281  Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3282  FuncInfo->callPtrInfo(Val));
3283  IsCallReloc = true;
3284  }
3285  } else
3286  Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3287  getPointerTy(DAG.getDataLayout()), 0,
3289  GlobalOrExternal = true;
3290  }
3291  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3292  const char *Sym = S->getSymbol();
3293 
3294  if (!IsPIC) // static
3295  Callee = DAG.getTargetExternalSymbol(
3297  else if (LargeGOT) {
3298  Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3299  MipsII::MO_CALL_LO16, Chain,
3300  FuncInfo->callPtrInfo(Sym));
3301  IsCallReloc = true;
3302  } else { // PIC
3303  Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3304  FuncInfo->callPtrInfo(Sym));
3305  IsCallReloc = true;
3306  }
3307 
3308  GlobalOrExternal = true;
3309  }
3310 
3311  SmallVector<SDValue, 8> Ops(1, Chain);
3312  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3313 
3314  getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3315  IsCallReloc, CLI, Callee, Chain);
3316 
3317  if (IsTailCall) {
3319  return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3320  }
3321 
3322  Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3323  SDValue InFlag = Chain.getValue(1);
3324 
3325  // Create the CALLSEQ_END node in the case of where it is not a call to
3326  // memcpy.
3327  if (!(MemcpyInByVal)) {
3328  Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3329  DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3330  InFlag = Chain.getValue(1);
3331  }
3332 
3333  // Handle result values, copying them out of physregs into vregs that we
3334  // return.
3335  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3336  InVals, CLI);
3337 }
3338 
3339 /// LowerCallResult - Lower the result values of a call into the
3340 /// appropriate copies out of appropriate physical registers.
3341 SDValue MipsTargetLowering::LowerCallResult(
3342  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3343  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3344  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3345  TargetLowering::CallLoweringInfo &CLI) const {
3346  // Assign locations to each value returned by this call.
3348  MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3349  *DAG.getContext());
3350 
3351  const ExternalSymbolSDNode *ES =
3352  dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3353  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3354  ES ? ES->getSymbol() : nullptr);
3355 
3356  // Copy all of the result registers out of their specified physreg.
3357  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3358  CCValAssign &VA = RVLocs[i];
3359  assert(VA.isRegLoc() && "Can only return in registers!");
3360 
3361  SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3362  RVLocs[i].getLocVT(), InFlag);
3363  Chain = Val.getValue(1);
3364  InFlag = Val.getValue(2);
3365 
3366  if (VA.isUpperBitsInLoc()) {
3367  unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3368  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3369  unsigned Shift =
3371  Val = DAG.getNode(
3372  Shift, DL, VA.getLocVT(), Val,
3373  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3374  }
3375 
3376  switch (VA.getLocInfo()) {
3377  default:
3378  llvm_unreachable("Unknown loc info!");
3379  case CCValAssign::Full:
3380  break;
3381  case CCValAssign::BCvt:
3382  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3383  break;
3384  case CCValAssign::AExt:
3386  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3387  break;
3388  case CCValAssign::ZExt:
3390  Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3391  DAG.getValueType(VA.getValVT()));
3392  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3393  break;
3394  case CCValAssign::SExt:
3396  Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3397  DAG.getValueType(VA.getValVT()));
3398  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3399  break;
3400  }
3401 
3402  InVals.push_back(Val);
3403  }
3404 
3405  return Chain;
3406 }
3407 
3409  EVT ArgVT, const SDLoc &DL,
3410  SelectionDAG &DAG) {
3411  MVT LocVT = VA.getLocVT();
3412  EVT ValVT = VA.getValVT();
3413 
3414  // Shift into the upper bits if necessary.
3415  switch (VA.getLocInfo()) {
3416  default:
3417  break;
3420  case CCValAssign::ZExtUpper: {
3421  unsigned ValSizeInBits = ArgVT.getSizeInBits();
3422  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3423  unsigned Opcode =
3425  Val = DAG.getNode(
3426  Opcode, DL, VA.getLocVT(), Val,
3427  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3428  break;
3429  }
3430  }
3431 
3432  // If this is an value smaller than the argument slot size (32-bit for O32,
3433  // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3434  // size. Extract the value and insert any appropriate assertions regarding
3435  // sign/zero extension.
3436  switch (VA.getLocInfo()) {
3437  default:
3438  llvm_unreachable("Unknown loc info!");
3439  case CCValAssign::Full:
3440  break;
3442  case CCValAssign::AExt:
3443  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3444  break;
3446  case CCValAssign::SExt:
3447  Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3448  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3449  break;
3451  case CCValAssign::ZExt:
3452  Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3453  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3454  break;
3455  case CCValAssign::BCvt:
3456  Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3457  break;
3458  }
3459 
3460  return Val;
3461 }
3462 
3463 //===----------------------------------------------------------------------===//
3464 // Formal Arguments Calling Convention Implementation
3465 //===----------------------------------------------------------------------===//
3466 /// LowerFormalArguments - transform physical registers into virtual registers
3467 /// and generate load operations for arguments places on the stack.
3468 SDValue MipsTargetLowering::LowerFormalArguments(
3469  SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3470  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3471  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3472  MachineFunction &MF = DAG.getMachineFunction();
3473  MachineFrameInfo &MFI = MF.getFrameInfo();
3474  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3475 
3476  MipsFI->setVarArgsFrameIndex(0);
3477 
3478  // Used with vargs to acumulate store chains.
3479  std::vector<SDValue> OutChains;
3480 
3481  // Assign locations to all of the incoming arguments.
3483  MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3484  *DAG.getContext());
3485  CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3486  const Function &Func = DAG.getMachineFunction().getFunction();
3487  Function::const_arg_iterator FuncArg = Func.arg_begin();
3488 
3489  if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3491  "Functions with the interrupt attribute cannot have arguments!");
3492 
3493  CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3494  MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3495  CCInfo.getInRegsParamsCount() > 0);
3496 
3497  unsigned CurArgIdx = 0;
3498  CCInfo.rewindByValRegsInfo();
3499 
3500  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3501  CCValAssign &VA = ArgLocs[i];
3502  if (Ins[i].isOrigArg()) {
3503  std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3504  CurArgIdx = Ins[i].getOrigArgIndex();
3505  }
3506  EVT ValVT = VA.getValVT();
3507  ISD::ArgFlagsTy Flags = Ins[i].Flags;
3508  bool IsRegLoc = VA.isRegLoc();
3509 
3510  if (Flags.isByVal()) {
3511  assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3512  unsigned FirstByValReg, LastByValReg;
3513  unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3514  CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3515 
3516  assert(Flags.getByValSize() &&
3517  "ByVal args of size 0 should have been ignored by front-end.");
3518  assert(ByValIdx < CCInfo.getInRegsParamsCount());
3519  copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3520  FirstByValReg, LastByValReg, VA, CCInfo);
3521  CCInfo.nextInRegsParam();
3522  continue;
3523  }
3524 
3525  // Arguments stored on registers
3526  if (IsRegLoc) {
3527  MVT RegVT = VA.getLocVT();
3528  Register ArgReg = VA.getLocReg();
3529  const TargetRegisterClass *RC = getRegClassFor(RegVT);
3530 
3531  // Transform the arguments stored on
3532  // physical registers into virtual ones
3533  unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3534  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3535 
3536  ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3537 
3538  // Handle floating point arguments passed in integer registers and
3539  // long double arguments passed in floating point registers.
3540  if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3541  (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3542  (RegVT == MVT::f64 && ValVT == MVT::i64))
3543  ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3544  else if (ABI.IsO32() && RegVT == MVT::i32 &&
3545  ValVT == MVT::f64) {
3546  unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3547  getNextIntArgReg(ArgReg), RC);
3548  SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3549  if (!Subtarget.isLittle())
3550  std::swap(ArgValue, ArgValue2);
3551  ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3552  ArgValue, ArgValue2);
3553  }
3554 
3555  InVals.push_back(ArgValue);
3556  } else { // VA.isRegLoc()
3557  MVT LocVT = VA.getLocVT();
3558 
3559  if (ABI.IsO32()) {
3560  // We ought to be able to use LocVT directly but O32 sets it to i32
3561  // when allocating floating point values to integer registers.
3562  // This shouldn't influence how we load the value into registers unless
3563  // we are targeting softfloat.
3565  LocVT = VA.getValVT();
3566  }
3567 
3568  // sanity check
3569  assert(VA.isMemLoc());
3570 
3571  // The stack pointer offset is relative to the caller stack frame.
3572  int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3573  VA.getLocMemOffset(), true);
3574 
3575  // Create load nodes to retrieve arguments from the stack
3576  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3577  SDValue ArgValue = DAG.getLoad(
3578  LocVT, DL, Chain, FIN,
3580  OutChains.push_back(ArgValue.getValue(1));
3581 
3582  ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3583 
3584  InVals.push_back(ArgValue);
3585  }
3586  }
3587 
3588  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3589  // The mips ABIs for returning structs by value requires that we copy
3590  // the sret argument into $v0 for the return. Save the argument into
3591  // a virtual register so that we can access it from the return points.
3592  if (Ins[i].Flags.isSRet()) {
3593  unsigned Reg = MipsFI->getSRetReturnReg();
3594  if (!Reg) {
3595  Reg = MF.getRegInfo().createVirtualRegister(
3597  MipsFI->setSRetReturnReg(Reg);
3598  }
3599  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3600  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3601  break;
3602  }
3603  }
3604 
3605  if (IsVarArg)
3606  writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3607 
3608  // All stores are grouped in one node to allow the matching between
3609  // the size of Ins and InVals. This only happens when on varg functions
3610  if (!OutChains.empty()) {
3611  OutChains.push_back(Chain);
3612  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3613  }
3614 
3615  return Chain;
3616 }
3617 
3618 //===----------------------------------------------------------------------===//
3619 // Return Value Calling Convention Implementation
3620 //===----------------------------------------------------------------------===//
3621 
3622 bool
3623 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3624  MachineFunction &MF, bool IsVarArg,
3625  const SmallVectorImpl<ISD::OutputArg> &Outs,
3626  LLVMContext &Context) const {
3628  MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3629  return CCInfo.CheckReturn(Outs, RetCC_Mips);
3630 }
3631 
3632 bool
3633 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3634  if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3635  return true;
3636 
3637  return IsSigned;
3638 }
3639 
3640 SDValue
3641 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3642  const SDLoc &DL,
3643  SelectionDAG &DAG) const {
3644  MachineFunction &MF = DAG.getMachineFunction();
3645  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3646 
3647  MipsFI->setISR();
3648 
3649  return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3650 }
3651 
3652 SDValue
3653 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3654  bool IsVarArg,
3655  const SmallVectorImpl<ISD::OutputArg> &Outs,
3656  const SmallVectorImpl<SDValue> &OutVals,
3657  const SDLoc &DL, SelectionDAG &DAG) const {
3658  // CCValAssign - represent the assignment of
3659  // the return value to a location
3661  MachineFunction &MF = DAG.getMachineFunction();
3662 
3663  // CCState - Info about the registers and stack slot.
3664  MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3665 
3666  // Analyze return values.
3667  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3668 
3669  SDValue Flag;
3670  SmallVector<SDValue, 4> RetOps(1, Chain);
3671 
3672  // Copy the result values into the output registers.
3673  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3674  SDValue Val = OutVals[i];
3675  CCValAssign &VA = RVLocs[i];
3676  assert(VA.isRegLoc() && "Can only return in registers!");
3677  bool UseUpperBits = false;
3678 
3679  switch (VA.getLocInfo()) {
3680  default:
3681  llvm_unreachable("Unknown loc info!");
3682  case CCValAssign::Full:
3683  break;
3684  case CCValAssign::BCvt:
3685  Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3686  break;
3688  UseUpperBits = true;
3690  case CCValAssign::AExt:
3691  Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3692  break;
3694  UseUpperBits = true;
3696  case CCValAssign::ZExt:
3697  Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3698  break;
3700  UseUpperBits = true;
3702  case CCValAssign::SExt:
3703  Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3704  break;
3705  }
3706 
3707  if (UseUpperBits) {
3708  unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3709  unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3710  Val = DAG.getNode(
3711  ISD::SHL, DL, VA.getLocVT(), Val,
3712  DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3713  }
3714 
3715  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3716 
3717  // Guarantee that all emitted copies are stuck together with flags.
3718  Flag = Chain.getValue(1);
3719  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3720  }
3721 
3722  // The mips ABIs for returning structs by value requires that we copy
3723  // the sret argument into $v0 for the return. We saved the argument into
3724  // a virtual register in the entry block, so now we copy the value out
3725  // and into $v0.
3726  if (MF.getFunction().hasStructRetAttr()) {
3727  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3728  unsigned Reg = MipsFI->getSRetReturnReg();
3729 
3730  if (!Reg)
3731  llvm_unreachable("sret virtual register not created in the entry block");
3732  SDValue Val =
3733  DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3734  unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3735 
3736  Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3737  Flag = Chain.getValue(1);
3738  RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3739  }
3740 
3741  RetOps[0] = Chain; // Update chain.
3742 
3743  // Add the flag if we have it.
3744  if (Flag.getNode())
3745  RetOps.push_back(Flag);
3746 
3747  // ISRs must use "eret".
3748  if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3749  return LowerInterruptReturn(RetOps, DL, DAG);
3750 
3751  // Standard return on Mips is a "jr $ra"
3752  return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3753 }
3754 
3755 //===----------------------------------------------------------------------===//
3756 // Mips Inline Assembly Support
3757 //===----------------------------------------------------------------------===//
3758 
3759 /// getConstraintType - Given a constraint letter, return the type of
3760 /// constraint it is for this target.
3762 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3763  // Mips specific constraints
3764  // GCC config/mips/constraints.md
3765  //
3766  // 'd' : An address register. Equivalent to r
3767  // unless generating MIPS16 code.
3768  // 'y' : Equivalent to r; retained for
3769  // backwards compatibility.
3770  // 'c' : A register suitable for use in an indirect
3771  // jump. This will always be $25 for -mabicalls.
3772  // 'l' : The lo register. 1 word storage.
3773  // 'x' : The hilo register pair. Double word storage.
3774  if (Constraint.size() == 1) {
3775  switch (Constraint[0]) {
3776  default : break;
3777  case 'd':
3778  case 'y':
3779  case 'f':
3780  case 'c':
3781  case 'l':
3782  case 'x':
3783  return C_RegisterClass;
3784  case 'R':
3785  return C_Memory;
3786  }
3787  }
3788 
3789  if (Constraint == "ZC")
3790  return C_Memory;
3791 
3792  return TargetLowering::getConstraintType(Constraint);
3793 }
3794 
3795 /// Examine constraint type and operand type and determine a weight value.
3796 /// This object must already have been set up with the operand type
3797 /// and the current alternative constraint selected.
3799 MipsTargetLowering::getSingleConstraintMatchWeight(
3800  AsmOperandInfo &info, const char *constraint) const {
3801  ConstraintWeight weight = CW_Invalid;
3802  Value *CallOperandVal = info.CallOperandVal;
3803  // If we don't have a value, we can't do a match,
3804  // but allow it at the lowest weight.
3805  if (!CallOperandVal)
3806  return CW_Default;
3807  Type *type = CallOperandVal->getType();
3808  // Look at the constraint type.
3809  switch (*constraint) {
3810  default:
3811  weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3812  break;
3813  case 'd':
3814  case 'y':
3815  if (type->isIntegerTy())
3816  weight = CW_Register;
3817  break;
3818  case 'f': // FPU or MSA register
3819  if (Subtarget.hasMSA() && type->isVectorTy() &&
3820  cast<VectorType>(type)->getBitWidth() == 128)
3821  weight = CW_Register;
3822  else if (type->isFloatTy())
3823  weight = CW_Register;
3824  break;
3825  case 'c': // $25 for indirect jumps
3826  case 'l': // lo register
3827  case 'x': // hilo register pair
3828  if (type->isIntegerTy())
3829  weight = CW_SpecificReg;
3830  break;
3831  case 'I': // signed 16 bit immediate
3832  case 'J': // integer zero
3833  case 'K': // unsigned 16 bit immediate
3834  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3835  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3836  case 'O': // signed 15 bit immediate (+- 16383)
3837  case 'P': // immediate in the range of 65535 to 1 (inclusive)
3838  if (isa<ConstantInt>(CallOperandVal))
3839  weight = CW_Constant;
3840  break;
3841  case 'R':
3842  weight = CW_Memory;
3843  break;
3844  }
3845  return weight;
3846 }
3847 
3848 /// This is a helper function to parse a physical register string and split it
3849 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3850 /// that is returned indicates whether parsing was successful. The second flag
3851 /// is true if the numeric part exists.
3852 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3853  unsigned long long &Reg) {
3854  if (C.front() != '{' || C.back() != '}')
3855  return std::make_pair(false, false);
3856 
3857  // Search for the first numeric character.
3858  StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3859  I = std::find_if(B, E, isdigit);
3860 
3861  Prefix = StringRef(B, I - B);
3862 
3863  // The second flag is set to false if no numeric characters were found.
3864  if (I == E)
3865  return std::make_pair(true, false);
3866 
3867  // Parse the numeric characters.
3868  return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3869  true);
3870 }
3871 
3873  ISD::NodeType) const {
3874  bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
3875  EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
3876  return VT.bitsLT(MinVT) ? MinVT : VT;
3877 }
3878 
3879 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3880 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3881  const TargetRegisterInfo *TRI =
3883  const TargetRegisterClass *RC;
3884  StringRef Prefix;
3885  unsigned long long Reg;
3886 
3887  std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3888 
3889  if (!R.first)
3890  return std::make_pair(0U, nullptr);
3891 
3892  if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3893  // No numeric characters follow "hi" or "lo".
3894  if (R.second)
3895  return std::make_pair(0U, nullptr);
3896 
3897  RC = TRI->getRegClass(Prefix == "hi" ?
3898  Mips::HI32RegClassID : Mips::LO32RegClassID);
3899  return std::make_pair(*(RC->begin()), RC);
3900  } else if (Prefix.startswith("$msa")) {
3901  // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3902 
3903  // No numeric characters follow the name.
3904  if (R.second)
3905  return std::make_pair(0U, nullptr);
3906 
3908  .Case("$msair", Mips::MSAIR)
3909  .Case("$msacsr", Mips::MSACSR)
3910  .Case("$msaaccess", Mips::MSAAccess)
3911  .Case("$msasave", Mips::MSASave)
3912  .Case("$msamodify", Mips::MSAModify)
3913  .Case("$msarequest", Mips::MSARequest)
3914  .Case("$msamap", Mips::MSAMap)
3915  .Case("$msaunmap", Mips::MSAUnmap)
3916  .Default(0);
3917 
3918  if (!Reg)
3919  return std::make_pair(0U, nullptr);
3920 
3921  RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3922  return std::make_pair(Reg, RC);
3923  }
3924 
3925  if (!R.second)
3926  return std::make_pair(0U, nullptr);
3927 
3928  if (Prefix == "$f") { // Parse $f0-$f31.
3929  // If the size of FP registers is 64-bit or Reg is an even number, select
3930  // the 64-bit register class. Otherwise, select the 32-bit register class.
3931  if (VT == MVT::Other)
3932  VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3933 
3934  RC = getRegClassFor(VT);
3935 
3936  if (RC == &Mips::AFGR64RegClass) {
3937  assert(Reg % 2 == 0);
3938  Reg >>= 1;
3939  }
3940  } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3941  RC = TRI->getRegClass(Mips::FCCRegClassID);
3942  else if (Prefix == "$w") { // Parse $w0-$w31.
3943  RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3944  } else { // Parse $0-$31.
3945  assert(Prefix == "$");
3946  RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3947  }
3948 
3949  assert(Reg < RC->getNumRegs());
3950  return std::make_pair(*(RC->begin() + Reg), RC);
3951 }
3952 
3953 /// Given a register class constraint, like 'r', if this corresponds directly
3954 /// to an LLVM register class, return a register of 0 and the register class
3955 /// pointer.
3956 std::pair<unsigned, const TargetRegisterClass *>
3957 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3958  StringRef Constraint,
3959  MVT VT) const {
3960  if (Constraint.size() == 1) {
3961  switch (Constraint[0]) {
3962  case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3963  case 'y': // Same as 'r'. Exists for compatibility.
3964  case 'r':
3965  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3966  if (Subtarget.inMips16Mode())
3967  return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3968  return std::make_pair(0U, &Mips::GPR32RegClass);
3969  }
3970  if (VT == MVT::i64 && !Subtarget.isGP64bit())
3971  return std::make_pair(0U, &Mips::GPR32RegClass);
3972  if (VT == MVT::i64 && Subtarget.isGP64bit())
3973  return std::make_pair(0U, &Mips::GPR64RegClass);
3974  // This will generate an error message
3975  return std::make_pair(0U, nullptr);
3976  case 'f': // FPU or MSA register
3977  if (VT == MVT::v16i8)
3978  return std::make_pair(0U, &Mips::MSA128BRegClass);
3979  else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3980  return std::make_pair(0U, &Mips::MSA128HRegClass);
3981  else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3982  return std::make_pair(0U, &Mips::MSA128WRegClass);
3983  else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3984  return std::make_pair(0U, &Mips::MSA128DRegClass);
3985  else if (VT == MVT::f32)
3986  return std::make_pair(0U, &Mips::FGR32RegClass);
3987  else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3988  if (Subtarget.isFP64bit())
3989  return std::make_pair(0U, &Mips::FGR64RegClass);
3990  return std::make_pair(0U, &Mips::AFGR64RegClass);
3991  }
3992  break;
3993  case 'c': // register suitable for indirect jump
3994  if (VT == MVT::i32)
3995  return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3996  if (VT == MVT::i64)
3997  return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3998  // This will generate an error message
3999  return std::make_pair(0U, nullptr);
4000  case 'l': // use the `lo` register to store values
4001  // that are no bigger than a word
4002  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4003  return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4004  return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4005  case 'x': // use the concatenated `hi` and `lo` registers
4006  // to store doubleword values
4007  // Fixme: Not triggering the use of both hi and low
4008  // This will generate an error message
4009  return std::make_pair(0U, nullptr);
4010  }
4011  }
4012 
4013  std::pair<unsigned, const TargetRegisterClass *> R;
4014  R = parseRegForInlineAsmConstraint(Constraint, VT);
4015 
4016  if (R.second)
4017  return R;
4018 
4019  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4020 }
4021 
4022 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4023 /// vector. If it is invalid, don't add anything to Ops.
4024 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4025  std::string &Constraint,
4026  std::vector<SDValue>&Ops,
4027  SelectionDAG &DAG) const {
4028  SDLoc DL(Op);
4029  SDValue Result;
4030 
4031  // Only support length 1 constraints for now.
4032  if (Constraint.length() > 1) return;
4033 
4034  char ConstraintLetter = Constraint[0];
4035  switch (ConstraintLetter) {
4036  default: break; // This will fall through to the generic implementation
4037  case 'I': // Signed 16 bit constant
4038  // If this fails, the parent routine will give an error
4039  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4040  EVT Type = Op.getValueType();
4041  int64_t Val = C->getSExtValue();
4042  if (isInt<16>(Val)) {
4043  Result = DAG.getTargetConstant(Val, DL, Type);
4044  break;
4045  }
4046  }
4047  return;
4048  case 'J': // integer zero
4049  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4050  EVT Type = Op.getValueType();
4051  int64_t Val = C->getZExtValue();
4052  if (Val == 0) {
4053  Result = DAG.getTargetConstant(0, DL, Type);
4054  break;
4055  }
4056  }
4057  return;
4058  case 'K': // unsigned 16 bit immediate
4059  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4060  EVT Type = Op.getValueType();
4061  uint64_t Val = (uint64_t)C->getZExtValue();
4062  if (isUInt<16>(Val)) {
4063  Result = DAG.getTargetConstant(Val, DL, Type);
4064  break;
4065  }
4066  }
4067  return;
4068  case 'L': // signed 32 bit immediate where lower 16 bits are 0
4069  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4070  EVT Type = Op.getValueType();
4071  int64_t Val = C->getSExtValue();
4072  if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4073  Result = DAG.getTargetConstant(Val, DL, Type);
4074  break;
4075  }
4076  }
4077  return;
4078  case 'N': // immediate in the range of -65535 to -1 (inclusive)
4079  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4080  EVT Type = Op.getValueType();
4081  int64_t Val = C->getSExtValue();
4082  if ((Val >= -65535) && (Val <= -1)) {
4083  Result = DAG.getTargetConstant(Val, DL, Type);
4084  break;
4085  }
4086  }
4087  return;
4088  case 'O': // signed 15 bit immediate
4089  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4090  EVT Type = Op.getValueType();
4091  int64_t Val = C->getSExtValue();
4092  if ((isInt<15>(Val))) {
4093  Result = DAG.getTargetConstant(Val, DL, Type);
4094  break;
4095  }
4096  }
4097  return;
4098  case 'P': // immediate in the range of 1 to 65535 (inclusive)
4099  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4100  EVT Type = Op.getValueType();
4101  int64_t Val = C->getSExtValue();
4102  if ((Val <= 65535) && (Val >= 1)) {
4103  Result = DAG.getTargetConstant(Val, DL, Type);
4104  break;
4105  }
4106  }
4107  return;
4108  }
4109 
4110  if (Result.getNode()) {
4111  Ops.push_back(Result);
4112  return;
4113  }
4114 
4115  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4116 }
4117 
4118 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4119  const AddrMode &AM, Type *Ty,
4120  unsigned AS, Instruction *I) const {
4121  // No global is ever allowed as a base.
4122  if (AM.BaseGV)
4123  return false;
4124 
4125  switch (AM.Scale) {
4126  case 0: // "r+i" or just "i", depending on HasBaseReg.
4127  break;
4128  case 1:
4129  if (!AM.HasBaseReg) // allow "r+i".
4130  break;
4131  return false; // disallow "r+r" or "r+r+i".
4132  default:
4133  return false;
4134  }
4135 
4136  return true;
4137 }
4138 
4139 bool
4140 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4141  // The Mips target isn't yet aware of offsets.
4142  return false;
4143 }
4144 
4145 EVT MipsTargetLowering::getOptimalMemOpType(
4146  uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
4147  bool ZeroMemset, bool MemcpyStrSrc,
4148  const AttributeList &FuncAttributes) const {
4149  if (Subtarget.hasMips64())
4150  return MVT::i64;
4151 
4152  return MVT::i32;
4153 }
4154 
4155 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4156  bool ForCodeSize) const {
4157  if (VT != MVT::f32 && VT != MVT::f64)
4158  return false;
4159  if (Imm.isNegZero())
4160  return false;
4161  return Imm.isZero();
4162 }
4163 
4164 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4165 
4166  // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4167  if (ABI.IsN64() && isPositionIndependent())
4169 
4171 }
4172 
4173 bool MipsTargetLowering::useSoftFloat() const {
4174  return Subtarget.useSoftFloat();
4175 }
4176 
4177 void MipsTargetLowering::copyByValRegs(
4178  SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4179  SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4180  SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4181  unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4182  MipsCCState &State) const {
4183  MachineFunction &MF = DAG.getMachineFunction();
4184  MachineFrameInfo &MFI = MF.getFrameInfo();
4185  unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4186  unsigned NumRegs = LastReg - FirstReg;
4187  unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4188  unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4189  int FrameObjOffset;
4190  ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4191 
4192  if (RegAreaSize)
4193  FrameObjOffset =
4195  (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4196  else
4197  FrameObjOffset = VA.getLocMemOffset();
4198 
4199  // Create frame object.
4200  EVT PtrTy = getPointerTy(DAG.getDataLayout());
4201  // Make the fixed object stored to mutable so that the load instructions
4202  // referencing it have their memory dependencies added.
4203  // Set the frame object as isAliased which clears the underlying objects
4204  // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4205  // stores as dependencies for loads referencing this fixed object.
4206  int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4207  SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4208  InVals.push_back(FIN);
4209 
4210  if (!NumRegs)
4211  return;
4212 
4213  // Copy arg registers.
4214  MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4215  const TargetRegisterClass *RC = getRegClassFor(RegTy);
4216 
4217  for (unsigned I = 0; I < NumRegs; ++I) {
4218  unsigned ArgReg = ByValArgRegs[FirstReg + I];
4219  unsigned VReg = addLiveIn(MF, ArgReg, RC);
4220  unsigned Offset = I * GPRSizeInBytes;
4221  SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4222  DAG.getConstant(Offset, DL, PtrTy));
4223  SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4224  StorePtr, MachinePointerInfo(FuncArg, Offset));
4225  OutChains.push_back(Store);
4226  }
4227 }
4228 
4229 // Copy byVal arg to registers and stack.
4230 void MipsTargetLowering::passByValArg(
4231  SDValue Chain, const SDLoc &DL,
4232  std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4233  SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4234  MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4235  unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4236  const CCValAssign &VA) const {
4237  unsigned ByValSizeInBytes = Flags.getByValSize();
4238  unsigned OffsetInBytes = 0; // From beginning of struct
4239  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4240  unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4241  EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4242  RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4243  unsigned NumRegs = LastReg - FirstReg;
4244 
4245  if (NumRegs) {
4247  bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4248  unsigned I = 0;
4249 
4250  // Copy words to registers.
4251  for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4252  SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4253  DAG.getConstant(OffsetInBytes, DL, PtrTy));
4254  SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4255  MachinePointerInfo(), Alignment);
4256  MemOpChains.push_back(LoadVal.getValue(1));
4257  unsigned ArgReg = ArgRegs[FirstReg + I];
4258  RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4259  }
4260 
4261  // Return if the struct has been fully copied.
4262  if (ByValSizeInBytes == OffsetInBytes)
4263  return;
4264 
4265  // Copy the remainder of the byval argument with sub-word loads and shifts.
4266  if (LeftoverBytes) {
4267  SDValue Val;
4268 
4269  for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4270  OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4271  unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4272 
4273  if (RemainingSizeInBytes < LoadSizeInBytes)
4274  continue;
4275 
4276  // Load subword.
4277  SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4278  DAG.getConstant(OffsetInBytes, DL,
4279  PtrTy));
4280  SDValue LoadVal = DAG.getExtLoad(
4281  ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4282  MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4283  MemOpChains.push_back(LoadVal.getValue(1));
4284 
4285  // Shift the loaded value.
4286  unsigned Shamt;
4287 
4288  if (isLittle)
4289  Shamt = TotalBytesLoaded * 8;
4290  else
4291  Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4292 
4293  SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4294  DAG.getConstant(Shamt, DL, MVT::i32));
4295 
4296  if (Val.getNode())
4297  Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4298  else
4299  Val = Shift;
4300 
4301  OffsetInBytes += LoadSizeInBytes;
4302  TotalBytesLoaded += LoadSizeInBytes;
4303  Alignment = std::min(Alignment, LoadSizeInBytes);
4304  }
4305 
4306  unsigned ArgReg = ArgRegs[FirstReg + I];
4307  RegsToPass.push_back(std::make_pair(ArgReg, Val));
4308  return;
4309  }
4310  }
4311 
4312  // Copy remainder of byval arg to it with memcpy.
4313  unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4314  SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4315  DAG.getConstant(OffsetInBytes, DL, PtrTy));
4316  SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4317  DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4318  Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4319  DAG.getConstant(MemCpySize, DL, PtrTy),
4320  Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4321  /*isTailCall=*/false,
4323  MemOpChains.push_back(Chain);
4324 }
4325 
4326 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4327  SDValue Chain, const SDLoc &DL,
4328  SelectionDAG &DAG,
4329  CCState &State) const {
4331  unsigned Idx = State.getFirstUnallocated(ArgRegs);
4332  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4333  MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4334  const TargetRegisterClass *RC = getRegClassFor(RegTy);
4335  MachineFunction &MF = DAG.getMachineFunction();
4336  MachineFrameInfo &MFI = MF.getFrameInfo();
4337  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4338 
4339  // Offset of the first variable argument from stack pointer.
4340  int VaArgOffset;
4341 
4342  if (ArgRegs.size() == Idx)
4343  VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4344  else {
4345  VaArgOffset =
4347  (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4348  }
4349 
4350  // Record the frame index of the first variable argument
4351  // which is a value necessary to VASTART.
4352  int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4353  MipsFI->setVarArgsFrameIndex(FI);
4354 
4355  // Copy the integer registers that have not been used for argument passing
4356  // to the argument register save area. For O32, the save area is allocated
4357  // in the caller's stack frame, while for N32/64, it is allocated in the
4358  // callee's stack frame.
4359  for (unsigned I = Idx; I < ArgRegs.size();
4360  ++I, VaArgOffset += RegSizeInBytes) {
4361  unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4362  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4363  FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4364  SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4365  SDValue Store =
4366  DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4367  cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4368  (Value *)nullptr);
4369  OutChains.push_back(Store);
4370  }
4371 }
4372 
4373 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4374  unsigned Align) const {
4376 
4377  assert(Size && "Byval argument's size shouldn't be 0.");
4378 
4379  Align = std::min(Align, TFL->getStackAlignment());
4380 
4381  unsigned FirstReg = 0;
4382  unsigned NumRegs = 0;
4383 
4384  if (State->getCallingConv() != CallingConv::Fast) {
4385  unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4386  ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4387  // FIXME: The O32 case actually describes no shadow registers.
4388  const MCPhysReg *ShadowRegs =
4389  ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4390 
4391  // We used to check the size as well but we can't do that anymore since
4392  // CCState::HandleByVal() rounds up the size after calling this function.
4393  assert(!(Align % RegSizeInBytes) &&
4394  "Byval argument's alignment should be a multiple of"
4395  "RegSizeInBytes.");
4396 
4397  FirstReg = State->getFirstUnallocated(IntArgRegs);
4398 
4399  // If Align > RegSizeInBytes, the first arg register must be even.
4400  // FIXME: This condition happens to do the right thing but it's not the
4401  // right way to test it. We want to check that the stack frame offset
4402  // of the register is aligned.
4403  if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4404  State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4405  ++FirstReg;
4406  }
4407 
4408  // Mark the registers allocated.
4409  Size = alignTo(Size, RegSizeInBytes);
4410  for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4411  Size -= RegSizeInBytes, ++I, ++NumRegs)
4412  State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4413  }
4414 
4415  State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4416 }
4417 
4418 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4419  MachineBasicBlock *BB,
4420  bool isFPCmp,
4421  unsigned Opc) const {
4423  "Subtarget already supports SELECT nodes with the use of"
4424  "conditional-move instructions.");
4425 
4426  const TargetInstrInfo *TII =
4428  DebugLoc DL = MI.getDebugLoc();
4429 
4430  // To "insert" a SELECT instruction, we actually have to insert the
4431  // diamond control-flow pattern. The incoming instruction knows the
4432  // destination vreg to set, the condition code register to branch on, the
4433  // true/false values to select between, and a branch opcode to use.
4434  const BasicBlock *LLVM_BB = BB->getBasicBlock();
4436 
4437  // thisMBB:
4438  // ...
4439  // TrueVal = ...
4440  // setcc r1, r2, r3
4441  // bNE r1, r0, copy1MBB
4442  // fallthrough --> copy0MBB
4443  MachineBasicBlock *thisMBB = BB;
4444  MachineFunction *F = BB->getParent();
4445  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4446  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4447  F->insert(It, copy0MBB);
4448  F->insert(It, sinkMBB);
4449 
4450  // Transfer the remainder of BB and its successor edges to sinkMBB.
4451  sinkMBB->splice(sinkMBB->begin(), BB,
4452  std::next(MachineBasicBlock::iterator(MI)), BB->end());
4453  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4454 
4455  // Next, add the true and fallthrough blocks as its successors.
4456  BB->addSuccessor(copy0MBB);
4457  BB->addSuccessor(sinkMBB);
4458 
4459  if (isFPCmp) {
4460  // bc1[tf] cc, sinkMBB
4461  BuildMI(BB, DL, TII->g