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