LLVM 18.0.0git
MipsISelLowering.cpp
Go to the documentation of this file.
1//===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interfaces that Mips uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsISelLowering.h"
18#include "MipsCCState.h"
19#include "MipsInstrInfo.h"
20#include "MipsMachineFunction.h"
21#include "MipsRegisterInfo.h"
22#include "MipsSubtarget.h"
23#include "MipsTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.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"
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/MCContext.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
79using namespace llvm;
80
81#define DEBUG_TYPE "mips-lower"
82
83STATISTIC(NumTailCalls, "Number of tail calls");
84
85static cl::opt<bool>
86NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
87 cl::desc("MIPS: Don't trap on integer division by zero."),
88 cl::init(false));
89
91
92static const MCPhysReg Mips64DPRegs[8] = {
93 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
94 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
95};
96
97// The MIPS MSA ABI passes vector arguments in the integer register set.
98// The number of integer registers used is dependant on the ABI used.
101 EVT VT) const {
102 if (!VT.isVector())
103 return getRegisterType(Context, VT);
104
106 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
107 : MVT::i64;
109}
110
113 EVT VT) const {
114 if (VT.isVector()) {
116 return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64);
117 return VT.getVectorNumElements() *
119 }
121}
122
124 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
125 unsigned &NumIntermediates, MVT &RegisterVT) const {
126 if (VT.isPow2VectorType()) {
127 IntermediateVT = getRegisterTypeForCallingConv(Context, CC, VT);
128 RegisterVT = IntermediateVT.getSimpleVT();
129 NumIntermediates = getNumRegistersForCallingConv(Context, CC, VT);
130 return NumIntermediates;
131 }
132 IntermediateVT = VT.getVectorElementType();
133 NumIntermediates = VT.getVectorNumElements();
134 RegisterVT = getRegisterType(Context, IntermediateVT);
135 return NumIntermediates * getNumRegisters(Context, IntermediateVT);
136}
137
141 return DAG.getRegister(FI->getGlobalBaseReg(MF), Ty);
142}
143
144SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
145 SelectionDAG &DAG,
146 unsigned Flag) const {
147 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
148}
149
150SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
151 SelectionDAG &DAG,
152 unsigned Flag) const {
153 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
154}
155
156SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
157 SelectionDAG &DAG,
158 unsigned Flag) const {
159 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
160}
161
162SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
163 SelectionDAG &DAG,
164 unsigned Flag) const {
165 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
166}
167
168SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
169 SelectionDAG &DAG,
170 unsigned Flag) const {
171 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
172 N->getOffset(), Flag);
173}
174
176 switch ((MipsISD::NodeType)Opcode) {
177 case MipsISD::FIRST_NUMBER: break;
178 case MipsISD::JmpLink: return "MipsISD::JmpLink";
179 case MipsISD::TailCall: return "MipsISD::TailCall";
180 case MipsISD::Highest: return "MipsISD::Highest";
181 case MipsISD::Higher: return "MipsISD::Higher";
182 case MipsISD::Hi: return "MipsISD::Hi";
183 case MipsISD::Lo: return "MipsISD::Lo";
184 case MipsISD::GotHi: return "MipsISD::GotHi";
185 case MipsISD::TlsHi: return "MipsISD::TlsHi";
186 case MipsISD::GPRel: return "MipsISD::GPRel";
187 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
188 case MipsISD::Ret: return "MipsISD::Ret";
189 case MipsISD::ERet: return "MipsISD::ERet";
190 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
191 case MipsISD::FAbs: return "MipsISD::FAbs";
192 case MipsISD::FMS: return "MipsISD::FMS";
193 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
194 case MipsISD::FPCmp: return "MipsISD::FPCmp";
195 case MipsISD::FSELECT: return "MipsISD::FSELECT";
196 case MipsISD::MTC1_D64: return "MipsISD::MTC1_D64";
197 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
198 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
199 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
200 case MipsISD::MFHI: return "MipsISD::MFHI";
201 case MipsISD::MFLO: return "MipsISD::MFLO";
202 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
203 case MipsISD::Mult: return "MipsISD::Mult";
204 case MipsISD::Multu: return "MipsISD::Multu";
205 case MipsISD::MAdd: return "MipsISD::MAdd";
206 case MipsISD::MAddu: return "MipsISD::MAddu";
207 case MipsISD::MSub: return "MipsISD::MSub";
208 case MipsISD::MSubu: return "MipsISD::MSubu";
209 case MipsISD::DivRem: return "MipsISD::DivRem";
210 case MipsISD::DivRemU: return "MipsISD::DivRemU";
211 case MipsISD::DivRem16: return "MipsISD::DivRem16";
212 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
213 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
214 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
215 case MipsISD::Wrapper: return "MipsISD::Wrapper";
216 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
217 case MipsISD::Sync: return "MipsISD::Sync";
218 case MipsISD::Ext: return "MipsISD::Ext";
219 case MipsISD::Ins: return "MipsISD::Ins";
220 case MipsISD::CIns: return "MipsISD::CIns";
221 case MipsISD::LWL: return "MipsISD::LWL";
222 case MipsISD::LWR: return "MipsISD::LWR";
223 case MipsISD::SWL: return "MipsISD::SWL";
224 case MipsISD::SWR: return "MipsISD::SWR";
225 case MipsISD::LDL: return "MipsISD::LDL";
226 case MipsISD::LDR: return "MipsISD::LDR";
227 case MipsISD::SDL: return "MipsISD::SDL";
228 case MipsISD::SDR: return "MipsISD::SDR";
229 case MipsISD::EXTP: return "MipsISD::EXTP";
230 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
231 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
232 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
233 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
234 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
235 case MipsISD::SHILO: return "MipsISD::SHILO";
236 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
237 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
238 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
239 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
240 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
241 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
242 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
243 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
244 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
245 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
246 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
247 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
248 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
249 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
250 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
251 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
252 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
253 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
254 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
255 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
256 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
257 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
258 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
259 case MipsISD::MULT: return "MipsISD::MULT";
260 case MipsISD::MULTU: return "MipsISD::MULTU";
261 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
262 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
263 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
264 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
265 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
266 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
267 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
268 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
269 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
270 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
271 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
272 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
273 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
274 case MipsISD::VCEQ: return "MipsISD::VCEQ";
275 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
276 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
277 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
278 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
279 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
280 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
281 case MipsISD::VNOR: return "MipsISD::VNOR";
282 case MipsISD::VSHF: return "MipsISD::VSHF";
283 case MipsISD::SHF: return "MipsISD::SHF";
284 case MipsISD::ILVEV: return "MipsISD::ILVEV";
285 case MipsISD::ILVOD: return "MipsISD::ILVOD";
286 case MipsISD::ILVL: return "MipsISD::ILVL";
287 case MipsISD::ILVR: return "MipsISD::ILVR";
288 case MipsISD::PCKEV: return "MipsISD::PCKEV";
289 case MipsISD::PCKOD: return "MipsISD::PCKOD";
290 case MipsISD::INSVE: return "MipsISD::INSVE";
291 }
292 return nullptr;
293}
294
296 const MipsSubtarget &STI)
297 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
298 // Mips does not have i1 type, so use i32 for
299 // setcc operations results (slt, sgt, ...).
302 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
303 // does. Integer booleans still use 0 and 1.
307
308 // Load extented operations for i1 types must be promoted
309 for (MVT VT : MVT::integer_valuetypes()) {
313 }
314
315 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
316 // for f32, f16
317 for (MVT VT : MVT::fp_valuetypes()) {
318 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
319 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
320 }
321
322 // Set LoadExtAction for f16 vectors to Expand
324 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
325 if (F16VT.isValid())
327 }
328
329 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
330 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
331
332 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
333
334 // Used by legalize types to correctly generate the setcc result.
335 // Without this, every float setcc comes with a AND/OR with the result,
336 // we don't want this, since the fpcmp result goes to a flag register,
337 // which is used implicitly by brcond and select operations.
338 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
339
340 // Mips Custom Operations
358
359 if (Subtarget.isGP64bit()) {
372 }
373
374 if (!Subtarget.isGP64bit()) {
378 }
379
381 if (Subtarget.isGP64bit())
383
392
393 // Operations not directly supported by Mips.
407 if (Subtarget.hasCnMips()) {
410 } else {
413 }
420
421 if (!Subtarget.hasMips32r2())
423
424 if (!Subtarget.hasMips64r2())
426
443
444 // Lower f16 conversion operations into library calls
449
451
456
457 // Use the default for now
460
461 if (!Subtarget.isGP64bit()) {
464 }
465
466 if (!Subtarget.hasMips32r2()) {
469 }
470
471 // MIPS16 lacks MIPS32's clz and clo instructions.
474 if (!Subtarget.hasMips64())
476
477 if (!Subtarget.hasMips32r2())
479 if (!Subtarget.hasMips64r2())
481
482 if (Subtarget.isGP64bit()) {
483 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
484 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
485 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
486 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
487 }
488
489 setOperationAction(ISD::TRAP, MVT::Other, Legal);
490
493
494 if (ABI.IsO32()) {
495 // These libcalls are not available in 32-bit.
496 setLibcallName(RTLIB::SHL_I128, nullptr);
497 setLibcallName(RTLIB::SRL_I128, nullptr);
498 setLibcallName(RTLIB::SRA_I128, nullptr);
499 setLibcallName(RTLIB::MUL_I128, nullptr);
500 setLibcallName(RTLIB::MULO_I64, nullptr);
501 setLibcallName(RTLIB::MULO_I128, nullptr);
502 }
503
504 if (Subtarget.isGP64bit())
506 else
508
510
511 // The arguments on the stack are defined in terms of 4-byte slots on O32
512 // and 8-byte slots on N32/N64.
514 : Align(4));
515
516 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
517
519
520 isMicroMips = Subtarget.inMicroMipsMode();
521}
522
523const MipsTargetLowering *
525 const MipsSubtarget &STI) {
526 if (STI.inMips16Mode())
527 return createMips16TargetLowering(TM, STI);
528
529 return createMipsSETargetLowering(TM, STI);
530}
531
532// Create a fast isel object.
533FastISel *
535 const TargetLibraryInfo *libInfo) const {
536 const MipsTargetMachine &TM =
537 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
538
539 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
540 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
543
544 // Disable if either of the following is true:
545 // We do not generate PIC, the ABI is not O32, XGOT is being used.
546 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() ||
548 UseFastISel = false;
549
550 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
551}
552
554 EVT VT) const {
555 if (!VT.isVector())
556 return MVT::i32;
558}
559
562 const MipsSubtarget &Subtarget) {
563 if (DCI.isBeforeLegalizeOps())
564 return SDValue();
565
566 EVT Ty = N->getValueType(0);
567 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
568 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
569 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
571 SDLoc DL(N);
572
573 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
574 N->getOperand(0), N->getOperand(1));
575 SDValue InChain = DAG.getEntryNode();
576 SDValue InGlue = DivRem;
577
578 // insert MFLO
579 if (N->hasAnyUseOfValue(0)) {
580 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
581 InGlue);
582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
583 InChain = CopyFromLo.getValue(1);
584 InGlue = CopyFromLo.getValue(2);
585 }
586
587 // insert MFHI
588 if (N->hasAnyUseOfValue(1)) {
589 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
590 HI, Ty, InGlue);
591 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
592 }
593
594 return SDValue();
595}
596
598 switch (CC) {
599 default: llvm_unreachable("Unknown fp condition code!");
600 case ISD::SETEQ:
601 case ISD::SETOEQ: return Mips::FCOND_OEQ;
602 case ISD::SETUNE: return Mips::FCOND_UNE;
603 case ISD::SETLT:
604 case ISD::SETOLT: return Mips::FCOND_OLT;
605 case ISD::SETGT:
606 case ISD::SETOGT: return Mips::FCOND_OGT;
607 case ISD::SETLE:
608 case ISD::SETOLE: return Mips::FCOND_OLE;
609 case ISD::SETGE:
610 case ISD::SETOGE: return Mips::FCOND_OGE;
611 case ISD::SETULT: return Mips::FCOND_ULT;
612 case ISD::SETULE: return Mips::FCOND_ULE;
613 case ISD::SETUGT: return Mips::FCOND_UGT;
614 case ISD::SETUGE: return Mips::FCOND_UGE;
615 case ISD::SETUO: return Mips::FCOND_UN;
616 case ISD::SETO: return Mips::FCOND_OR;
617 case ISD::SETNE:
618 case ISD::SETONE: return Mips::FCOND_ONE;
619 case ISD::SETUEQ: return Mips::FCOND_UEQ;
620 }
621}
622
623/// This function returns true if the floating point conditional branches and
624/// conditional moves which use condition code CC should be inverted.
626 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
627 return false;
628
630 "Illegal Condition Code");
631
632 return true;
633}
634
635// Creates and returns an FPCmp node from a setcc node.
636// Returns Op if setcc is not a floating point comparison.
638 // must be a SETCC node
639 if (Op.getOpcode() != ISD::SETCC)
640 return Op;
641
642 SDValue LHS = Op.getOperand(0);
643
644 if (!LHS.getValueType().isFloatingPoint())
645 return Op;
646
647 SDValue RHS = Op.getOperand(1);
648 SDLoc DL(Op);
649
650 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
651 // node if necessary.
652 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
653
654 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
655 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
656}
657
658// Creates and returns a CMovFPT/F node.
660 SDValue False, const SDLoc &DL) {
661 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
662 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
663 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
664
665 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
666 True.getValueType(), True, FCC0, False, Cond);
667}
668
671 const MipsSubtarget &Subtarget) {
672 if (DCI.isBeforeLegalizeOps())
673 return SDValue();
674
675 SDValue SetCC = N->getOperand(0);
676
677 if ((SetCC.getOpcode() != ISD::SETCC) ||
678 !SetCC.getOperand(0).getValueType().isInteger())
679 return SDValue();
680
681 SDValue False = N->getOperand(2);
682 EVT FalseTy = False.getValueType();
683
684 if (!FalseTy.isInteger())
685 return SDValue();
686
687 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
688
689 // If the RHS (False) is 0, we swap the order of the operands
690 // of ISD::SELECT (obviously also inverting the condition) so that we can
691 // take advantage of conditional moves using the $0 register.
692 // Example:
693 // return (a != 0) ? x : 0;
694 // load $reg, x
695 // movz $reg, $0, a
696 if (!FalseC)
697 return SDValue();
698
699 const SDLoc DL(N);
700
701 if (!FalseC->getZExtValue()) {
702 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
703 SDValue True = N->getOperand(1);
704
705 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
706 SetCC.getOperand(1),
708
709 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
710 }
711
712 // If both operands are integer constants there's a possibility that we
713 // can do some interesting optimizations.
714 SDValue True = N->getOperand(1);
715 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
716
717 if (!TrueC || !True.getValueType().isInteger())
718 return SDValue();
719
720 // We'll also ignore MVT::i64 operands as this optimizations proves
721 // to be ineffective because of the required sign extensions as the result
722 // of a SETCC operator is always MVT::i32 for non-vector types.
723 if (True.getValueType() == MVT::i64)
724 return SDValue();
725
726 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
727
728 // 1) (a < x) ? y : y-1
729 // slti $reg1, a, x
730 // addiu $reg2, $reg1, y-1
731 if (Diff == 1)
732 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
733
734 // 2) (a < x) ? y-1 : y
735 // slti $reg1, a, x
736 // xor $reg1, $reg1, 1
737 // addiu $reg2, $reg1, y-1
738 if (Diff == -1) {
739 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
740 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
741 SetCC.getOperand(1),
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;
790 unsigned SMPos, SMSize;
791 ConstantSDNode *CN;
792 SDValue NewOperand;
793 unsigned Opc;
794
795 // Op's second operand must be a shifted mask.
796 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
797 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
798 return SDValue();
799
800 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
801 // Pattern match EXT.
802 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
803 // => ext $dst, $src, pos, size
804
805 // The second operand of the shift must be an immediate.
806 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
807 return SDValue();
808
809 Pos = CN->getZExtValue();
810
811 // Return if the shifted mask does not start at bit 0 or the sum of its size
812 // and Pos exceeds the word's size.
813 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
814 return SDValue();
815
816 Opc = MipsISD::Ext;
817 NewOperand = FirstOperand.getOperand(0);
818 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
819 // Pattern match CINS.
820 // $dst = and (shl $src , pos), mask
821 // => cins $dst, $src, pos, size
822 // mask is a shifted mask with consecutive 1's, pos = shift amount,
823 // size = population count.
824
825 // The second operand of the shift must be an immediate.
826 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
827 return SDValue();
828
829 Pos = CN->getZExtValue();
830
831 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
832 Pos + SMSize > ValTy.getSizeInBits())
833 return SDValue();
834
835 NewOperand = FirstOperand.getOperand(0);
836 // SMSize is 'location' (position) in this case, not size.
837 SMSize--;
838 Opc = MipsISD::CIns;
839 } else {
840 // Pattern match EXT.
841 // $dst = and $src, (2**size - 1) , if size > 16
842 // => ext $dst, $src, pos, size , pos = 0
843
844 // If the mask is <= 0xffff, andi can be used instead.
845 if (CN->getZExtValue() <= 0xffff)
846 return SDValue();
847
848 // Return if the mask doesn't start at position 0.
849 if (SMPos)
850 return SDValue();
851
852 Opc = MipsISD::Ext;
853 NewOperand = FirstOperand;
854 }
855 return DAG.getNode(Opc, DL, ValTy, NewOperand,
856 DAG.getConstant(Pos, DL, MVT::i32),
857 DAG.getConstant(SMSize, DL, MVT::i32));
858}
859
862 const MipsSubtarget &Subtarget) {
863 // Pattern match INS.
864 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
865 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
866 // => ins $dst, $src, size, pos, $src1
867 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
868 return SDValue();
869
870 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
871 unsigned SMPos0, SMSize0, SMPos1, SMSize1;
872 ConstantSDNode *CN, *CN1;
873
874 // See if Op's first operand matches (and $src1 , mask0).
875 if (And0.getOpcode() != ISD::AND)
876 return SDValue();
877
878 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
879 !isShiftedMask_64(~CN->getSExtValue(), SMPos0, SMSize0))
880 return SDValue();
881
882 // See if Op's second operand matches (and (shl $src, pos), mask1).
883 if (And1.getOpcode() == ISD::AND &&
884 And1.getOperand(0).getOpcode() == ISD::SHL) {
885
886 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
887 !isShiftedMask_64(CN->getZExtValue(), SMPos1, SMSize1))
888 return SDValue();
889
890 // The shift masks must have the same position and size.
891 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
892 return SDValue();
893
894 SDValue Shl = And1.getOperand(0);
895
896 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
897 return SDValue();
898
899 unsigned Shamt = CN->getZExtValue();
900
901 // Return if the shift amount and the first bit position of mask are not the
902 // same.
903 EVT ValTy = N->getValueType(0);
904 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
905 return SDValue();
906
907 SDLoc DL(N);
908 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
909 DAG.getConstant(SMPos0, DL, MVT::i32),
910 DAG.getConstant(SMSize0, DL, MVT::i32),
911 And0.getOperand(0));
912 } else {
913 // Pattern match DINS.
914 // $dst = or (and $src, mask0), mask1
915 // where mask0 = ((1 << SMSize0) -1) << SMPos0
916 // => dins $dst, $src, pos, size
917 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
918 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
919 (SMSize0 + SMPos0 <= 32))) {
920 // Check if AND instruction has constant as argument
921 bool isConstCase = And1.getOpcode() != ISD::AND;
922 if (And1.getOpcode() == ISD::AND) {
923 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
924 return SDValue();
925 } else {
926 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
927 return SDValue();
928 }
929 // Don't generate INS if constant OR operand doesn't fit into bits
930 // cleared by constant AND operand.
931 if (CN->getSExtValue() & CN1->getSExtValue())
932 return SDValue();
933
934 SDLoc DL(N);
935 EVT ValTy = N->getOperand(0)->getValueType(0);
936 SDValue Const1;
937 SDValue SrlX;
938 if (!isConstCase) {
939 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
940 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
941 }
942 return DAG.getNode(
943 MipsISD::Ins, DL, N->getValueType(0),
944 isConstCase
945 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
946 : SrlX,
947 DAG.getConstant(SMPos0, DL, MVT::i32),
948 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
949 : SMSize0,
950 DL, MVT::i32),
951 And0->getOperand(0));
952
953 }
954 return SDValue();
955 }
956}
957
959 const MipsSubtarget &Subtarget) {
960 // ROOTNode must have a multiplication as an operand for the match to be
961 // successful.
962 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
963 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
964 return SDValue();
965
966 // In the case where we have a multiplication as the left operand of
967 // of a subtraction, we can't combine into a MipsISD::MSub node as the
968 // the instruction definition of msub(u) places the multiplication on
969 // on the right.
970 if (ROOTNode->getOpcode() == ISD::SUB &&
971 ROOTNode->getOperand(0).getOpcode() == ISD::MUL)
972 return SDValue();
973
974 // We don't handle vector types here.
975 if (ROOTNode->getValueType(0).isVector())
976 return SDValue();
977
978 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
979 // arithmetic. E.g.
980 // (add (mul a b) c) =>
981 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
982 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
983 // or
984 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
985 //
986 // The overhead of setting up the Hi/Lo registers and reassembling the
987 // result makes this a dubious optimzation for MIPS64. The core of the
988 // problem is that Hi/Lo contain the upper and lower 32 bits of the
989 // operand and result.
990 //
991 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
992 // density than doing it naively, 5 for MIPS64. Additionally, using
993 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
994 // extended operands, not true 64 bit values.
995 //
996 // FIXME: For the moment, disable this completely for MIPS64.
997 if (Subtarget.hasMips64())
998 return SDValue();
999
1000 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1001 ? ROOTNode->getOperand(0)
1002 : ROOTNode->getOperand(1);
1003
1004 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1005 ? ROOTNode->getOperand(1)
1006 : ROOTNode->getOperand(0);
1007
1008 // Transform this to a MADD only if the user of this node is the add.
1009 // If there are other users of the mul, this function returns here.
1010 if (!Mult.hasOneUse())
1011 return SDValue();
1012
1013 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
1014 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
1015 // of the multiply must have 32 or more sign bits, otherwise we cannot
1016 // perform this optimization. We have to check this here as we're performing
1017 // this optimization pre-legalization.
1018 SDValue MultLHS = Mult->getOperand(0);
1019 SDValue MultRHS = Mult->getOperand(1);
1020
1021 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
1022 MultRHS->getOpcode() == ISD::SIGN_EXTEND;
1023 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1024 MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1025
1026 if (!IsSigned && !IsUnsigned)
1027 return SDValue();
1028
1029 // Initialize accumulator.
1030 SDLoc DL(ROOTNode);
1031 SDValue BottomHalf, TopHalf;
1032 std::tie(BottomHalf, TopHalf) =
1033 CurDAG.SplitScalar(AddOperand, DL, MVT::i32, MVT::i32);
1034 SDValue ACCIn =
1035 CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, BottomHalf, TopHalf);
1036
1037 // Create MipsMAdd(u) / MipsMSub(u) node.
1038 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1039 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1040 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1041 SDValue MAddOps[3] = {
1042 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1043 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1044 EVT VTs[2] = {MVT::i32, MVT::i32};
1045 SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1046
1047 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1048 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1049 SDValue Combined =
1050 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1051 return Combined;
1052}
1053
1056 const MipsSubtarget &Subtarget) {
1057 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1058 if (DCI.isBeforeLegalizeOps()) {
1059 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1060 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1061 return performMADD_MSUBCombine(N, DAG, Subtarget);
1062
1063 return SDValue();
1064 }
1065
1066 return SDValue();
1067}
1068
1071 const MipsSubtarget &Subtarget) {
1072 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1073 if (DCI.isBeforeLegalizeOps()) {
1074 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1075 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1076 return performMADD_MSUBCombine(N, DAG, Subtarget);
1077
1078 return SDValue();
1079 }
1080
1081 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1082 SDValue Add = N->getOperand(1);
1083
1084 if (Add.getOpcode() != ISD::ADD)
1085 return SDValue();
1086
1087 SDValue Lo = Add.getOperand(1);
1088
1089 if ((Lo.getOpcode() != MipsISD::Lo) ||
1090 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1091 return SDValue();
1092
1093 EVT ValTy = N->getValueType(0);
1094 SDLoc DL(N);
1095
1096 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1097 Add.getOperand(0));
1098 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1099}
1100
1103 const MipsSubtarget &Subtarget) {
1104 // Pattern match CINS.
1105 // $dst = shl (and $src , imm), pos
1106 // => cins $dst, $src, pos, size
1107
1108 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1109 return SDValue();
1110
1111 SDValue FirstOperand = N->getOperand(0);
1112 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1113 SDValue SecondOperand = N->getOperand(1);
1114 EVT ValTy = N->getValueType(0);
1115 SDLoc DL(N);
1116
1117 uint64_t Pos = 0;
1118 unsigned SMPos, SMSize;
1119 ConstantSDNode *CN;
1120 SDValue NewOperand;
1121
1122 // The second operand of the shift must be an immediate.
1123 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1124 return SDValue();
1125
1126 Pos = CN->getZExtValue();
1127
1128 if (Pos >= ValTy.getSizeInBits())
1129 return SDValue();
1130
1131 if (FirstOperandOpc != ISD::AND)
1132 return SDValue();
1133
1134 // AND's second operand must be a shifted mask.
1135 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1136 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
1137 return SDValue();
1138
1139 // Return if the shifted mask does not start at bit 0 or the sum of its size
1140 // and Pos exceeds the word's size.
1141 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1142 return SDValue();
1143
1144 NewOperand = FirstOperand.getOperand(0);
1145 // SMSize is 'location' (position) in this case, not size.
1146 SMSize--;
1147
1148 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1149 DAG.getConstant(Pos, DL, MVT::i32),
1150 DAG.getConstant(SMSize, DL, MVT::i32));
1151}
1152
1154 const {
1155 SelectionDAG &DAG = DCI.DAG;
1156 unsigned Opc = N->getOpcode();
1157
1158 switch (Opc) {
1159 default: break;
1160 case ISD::SDIVREM:
1161 case ISD::UDIVREM:
1162 return performDivRemCombine(N, DAG, DCI, Subtarget);
1163 case ISD::SELECT:
1164 return performSELECTCombine(N, DAG, DCI, Subtarget);
1165 case MipsISD::CMovFP_F:
1166 case MipsISD::CMovFP_T:
1167 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1168 case ISD::AND:
1169 return performANDCombine(N, DAG, DCI, Subtarget);
1170 case ISD::OR:
1171 return performORCombine(N, DAG, DCI, Subtarget);
1172 case ISD::ADD:
1173 return performADDCombine(N, DAG, DCI, Subtarget);
1174 case ISD::SHL:
1175 return performSHLCombine(N, DAG, DCI, Subtarget);
1176 case ISD::SUB:
1177 return performSUBCombine(N, DAG, DCI, Subtarget);
1178 }
1179
1180 return SDValue();
1181}
1182
1184 return Subtarget.hasMips32();
1185}
1186
1188 return Subtarget.hasMips32();
1189}
1190
1192 // We can use ANDI+SLTIU as a bit test. Y contains the bit position.
1193 // For MIPSR2 or later, we may be able to use the `ext` instruction or its'
1194 // double-word variants.
1195 if (auto *C = dyn_cast<ConstantSDNode>(Y))
1196 return C->getAPIntValue().ule(15);
1197
1198 return false;
1199}
1200
1202 const SDNode *N, CombineLevel Level) const {
1203 assert(((N->getOpcode() == ISD::SHL &&
1204 N->getOperand(0).getOpcode() == ISD::SRL) ||
1205 (N->getOpcode() == ISD::SRL &&
1206 N->getOperand(0).getOpcode() == ISD::SHL)) &&
1207 "Expected shift-shift mask");
1208
1209 if (N->getOperand(0).getValueType().isVector())
1210 return false;
1211 return true;
1212}
1213
1214void
1217 SelectionDAG &DAG) const {
1218 return LowerOperationWrapper(N, Results, DAG);
1219}
1220
1223{
1224 switch (Op.getOpcode())
1225 {
1226 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1227 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1228 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1229 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1230 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1231 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1232 case ISD::SELECT: return lowerSELECT(Op, DAG);
1233 case ISD::SETCC: return lowerSETCC(Op, DAG);
1234 case ISD::VASTART: return lowerVASTART(Op, DAG);
1235 case ISD::VAARG: return lowerVAARG(Op, DAG);
1236 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1237 case ISD::FABS: return lowerFABS(Op, DAG);
1238 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1239 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1240 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1241 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1242 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1243 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1244 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1245 case ISD::LOAD: return lowerLOAD(Op, DAG);
1246 case ISD::STORE: return lowerSTORE(Op, DAG);
1247 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1248 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1249 }
1250 return SDValue();
1251}
1252
1253//===----------------------------------------------------------------------===//
1254// Lower helper functions
1255//===----------------------------------------------------------------------===//
1256
1257// addLiveIn - This helper function adds the specified physical register to the
1258// MachineFunction as a live in value. It also creates a corresponding
1259// virtual register for it.
1260static unsigned
1261addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1262{
1264 MF.getRegInfo().addLiveIn(PReg, VReg);
1265 return VReg;
1266}
1267
1270 const TargetInstrInfo &TII,
1271 bool Is64Bit, bool IsMicroMips) {
1272 if (NoZeroDivCheck)
1273 return &MBB;
1274
1275 // Insert instruction "teq $divisor_reg, $zero, 7".
1278 MachineOperand &Divisor = MI.getOperand(2);
1279 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1280 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1281 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1282 .addReg(Mips::ZERO)
1283 .addImm(7);
1284
1285 // Use the 32-bit sub-register if this is a 64-bit division.
1286 if (Is64Bit)
1287 MIB->getOperand(0).setSubReg(Mips::sub_32);
1288
1289 // Clear Divisor's kill flag.
1290 Divisor.setIsKill(false);
1291
1292 // We would normally delete the original instruction here but in this case
1293 // we only needed to inject an additional instruction rather than replace it.
1294
1295 return &MBB;
1296}
1297
1300 MachineBasicBlock *BB) const {
1301 switch (MI.getOpcode()) {
1302 default:
1303 llvm_unreachable("Unexpected instr type to insert");
1304 case Mips::ATOMIC_LOAD_ADD_I8:
1305 return emitAtomicBinaryPartword(MI, BB, 1);
1306 case Mips::ATOMIC_LOAD_ADD_I16:
1307 return emitAtomicBinaryPartword(MI, BB, 2);
1308 case Mips::ATOMIC_LOAD_ADD_I32:
1309 return emitAtomicBinary(MI, BB);
1310 case Mips::ATOMIC_LOAD_ADD_I64:
1311 return emitAtomicBinary(MI, BB);
1312
1313 case Mips::ATOMIC_LOAD_AND_I8:
1314 return emitAtomicBinaryPartword(MI, BB, 1);
1315 case Mips::ATOMIC_LOAD_AND_I16:
1316 return emitAtomicBinaryPartword(MI, BB, 2);
1317 case Mips::ATOMIC_LOAD_AND_I32:
1318 return emitAtomicBinary(MI, BB);
1319 case Mips::ATOMIC_LOAD_AND_I64:
1320 return emitAtomicBinary(MI, BB);
1321
1322 case Mips::ATOMIC_LOAD_OR_I8:
1323 return emitAtomicBinaryPartword(MI, BB, 1);
1324 case Mips::ATOMIC_LOAD_OR_I16:
1325 return emitAtomicBinaryPartword(MI, BB, 2);
1326 case Mips::ATOMIC_LOAD_OR_I32:
1327 return emitAtomicBinary(MI, BB);
1328 case Mips::ATOMIC_LOAD_OR_I64:
1329 return emitAtomicBinary(MI, BB);
1330
1331 case Mips::ATOMIC_LOAD_XOR_I8:
1332 return emitAtomicBinaryPartword(MI, BB, 1);
1333 case Mips::ATOMIC_LOAD_XOR_I16:
1334 return emitAtomicBinaryPartword(MI, BB, 2);
1335 case Mips::ATOMIC_LOAD_XOR_I32:
1336 return emitAtomicBinary(MI, BB);
1337 case Mips::ATOMIC_LOAD_XOR_I64:
1338 return emitAtomicBinary(MI, BB);
1339
1340 case Mips::ATOMIC_LOAD_NAND_I8:
1341 return emitAtomicBinaryPartword(MI, BB, 1);
1342 case Mips::ATOMIC_LOAD_NAND_I16:
1343 return emitAtomicBinaryPartword(MI, BB, 2);
1344 case Mips::ATOMIC_LOAD_NAND_I32:
1345 return emitAtomicBinary(MI, BB);
1346 case Mips::ATOMIC_LOAD_NAND_I64:
1347 return emitAtomicBinary(MI, BB);
1348
1349 case Mips::ATOMIC_LOAD_SUB_I8:
1350 return emitAtomicBinaryPartword(MI, BB, 1);
1351 case Mips::ATOMIC_LOAD_SUB_I16:
1352 return emitAtomicBinaryPartword(MI, BB, 2);
1353 case Mips::ATOMIC_LOAD_SUB_I32:
1354 return emitAtomicBinary(MI, BB);
1355 case Mips::ATOMIC_LOAD_SUB_I64:
1356 return emitAtomicBinary(MI, BB);
1357
1358 case Mips::ATOMIC_SWAP_I8:
1359 return emitAtomicBinaryPartword(MI, BB, 1);
1360 case Mips::ATOMIC_SWAP_I16:
1361 return emitAtomicBinaryPartword(MI, BB, 2);
1362 case Mips::ATOMIC_SWAP_I32:
1363 return emitAtomicBinary(MI, BB);
1364 case Mips::ATOMIC_SWAP_I64:
1365 return emitAtomicBinary(MI, BB);
1366
1367 case Mips::ATOMIC_CMP_SWAP_I8:
1368 return emitAtomicCmpSwapPartword(MI, BB, 1);
1369 case Mips::ATOMIC_CMP_SWAP_I16:
1370 return emitAtomicCmpSwapPartword(MI, BB, 2);
1371 case Mips::ATOMIC_CMP_SWAP_I32:
1372 return emitAtomicCmpSwap(MI, BB);
1373 case Mips::ATOMIC_CMP_SWAP_I64:
1374 return emitAtomicCmpSwap(MI, BB);
1375
1376 case Mips::ATOMIC_LOAD_MIN_I8:
1377 return emitAtomicBinaryPartword(MI, BB, 1);
1378 case Mips::ATOMIC_LOAD_MIN_I16:
1379 return emitAtomicBinaryPartword(MI, BB, 2);
1380 case Mips::ATOMIC_LOAD_MIN_I32:
1381 return emitAtomicBinary(MI, BB);
1382 case Mips::ATOMIC_LOAD_MIN_I64:
1383 return emitAtomicBinary(MI, BB);
1384
1385 case Mips::ATOMIC_LOAD_MAX_I8:
1386 return emitAtomicBinaryPartword(MI, BB, 1);
1387 case Mips::ATOMIC_LOAD_MAX_I16:
1388 return emitAtomicBinaryPartword(MI, BB, 2);
1389 case Mips::ATOMIC_LOAD_MAX_I32:
1390 return emitAtomicBinary(MI, BB);
1391 case Mips::ATOMIC_LOAD_MAX_I64:
1392 return emitAtomicBinary(MI, BB);
1393
1394 case Mips::ATOMIC_LOAD_UMIN_I8:
1395 return emitAtomicBinaryPartword(MI, BB, 1);
1396 case Mips::ATOMIC_LOAD_UMIN_I16:
1397 return emitAtomicBinaryPartword(MI, BB, 2);
1398 case Mips::ATOMIC_LOAD_UMIN_I32:
1399 return emitAtomicBinary(MI, BB);
1400 case Mips::ATOMIC_LOAD_UMIN_I64:
1401 return emitAtomicBinary(MI, BB);
1402
1403 case Mips::ATOMIC_LOAD_UMAX_I8:
1404 return emitAtomicBinaryPartword(MI, BB, 1);
1405 case Mips::ATOMIC_LOAD_UMAX_I16:
1406 return emitAtomicBinaryPartword(MI, BB, 2);
1407 case Mips::ATOMIC_LOAD_UMAX_I32:
1408 return emitAtomicBinary(MI, BB);
1409 case Mips::ATOMIC_LOAD_UMAX_I64:
1410 return emitAtomicBinary(MI, BB);
1411
1412 case Mips::PseudoSDIV:
1413 case Mips::PseudoUDIV:
1414 case Mips::DIV:
1415 case Mips::DIVU:
1416 case Mips::MOD:
1417 case Mips::MODU:
1418 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1419 false);
1420 case Mips::SDIV_MM_Pseudo:
1421 case Mips::UDIV_MM_Pseudo:
1422 case Mips::SDIV_MM:
1423 case Mips::UDIV_MM:
1424 case Mips::DIV_MMR6:
1425 case Mips::DIVU_MMR6:
1426 case Mips::MOD_MMR6:
1427 case Mips::MODU_MMR6:
1428 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1429 case Mips::PseudoDSDIV:
1430 case Mips::PseudoDUDIV:
1431 case Mips::DDIV:
1432 case Mips::DDIVU:
1433 case Mips::DMOD:
1434 case Mips::DMODU:
1435 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1436
1437 case Mips::PseudoSELECT_I:
1438 case Mips::PseudoSELECT_I64:
1439 case Mips::PseudoSELECT_S:
1440 case Mips::PseudoSELECT_D32:
1441 case Mips::PseudoSELECT_D64:
1442 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1443 case Mips::PseudoSELECTFP_F_I:
1444 case Mips::PseudoSELECTFP_F_I64:
1445 case Mips::PseudoSELECTFP_F_S:
1446 case Mips::PseudoSELECTFP_F_D32:
1447 case Mips::PseudoSELECTFP_F_D64:
1448 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1449 case Mips::PseudoSELECTFP_T_I:
1450 case Mips::PseudoSELECTFP_T_I64:
1451 case Mips::PseudoSELECTFP_T_S:
1452 case Mips::PseudoSELECTFP_T_D32:
1453 case Mips::PseudoSELECTFP_T_D64:
1454 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1455 case Mips::PseudoD_SELECT_I:
1456 case Mips::PseudoD_SELECT_I64:
1457 return emitPseudoD_SELECT(MI, BB);
1458 case Mips::LDR_W:
1459 return emitLDR_W(MI, BB);
1460 case Mips::LDR_D:
1461 return emitLDR_D(MI, BB);
1462 case Mips::STR_W:
1463 return emitSTR_W(MI, BB);
1464 case Mips::STR_D:
1465 return emitSTR_D(MI, BB);
1466 }
1467}
1468
1469// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1470// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1472MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1473 MachineBasicBlock *BB) const {
1474
1475 MachineFunction *MF = BB->getParent();
1476 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1478 DebugLoc DL = MI.getDebugLoc();
1479
1480 unsigned AtomicOp;
1481 bool NeedsAdditionalReg = false;
1482 switch (MI.getOpcode()) {
1483 case Mips::ATOMIC_LOAD_ADD_I32:
1484 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1485 break;
1486 case Mips::ATOMIC_LOAD_SUB_I32:
1487 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1488 break;
1489 case Mips::ATOMIC_LOAD_AND_I32:
1490 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1491 break;
1492 case Mips::ATOMIC_LOAD_OR_I32:
1493 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1494 break;
1495 case Mips::ATOMIC_LOAD_XOR_I32:
1496 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1497 break;
1498 case Mips::ATOMIC_LOAD_NAND_I32:
1499 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1500 break;
1501 case Mips::ATOMIC_SWAP_I32:
1502 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1503 break;
1504 case Mips::ATOMIC_LOAD_ADD_I64:
1505 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1506 break;
1507 case Mips::ATOMIC_LOAD_SUB_I64:
1508 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1509 break;
1510 case Mips::ATOMIC_LOAD_AND_I64:
1511 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1512 break;
1513 case Mips::ATOMIC_LOAD_OR_I64:
1514 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1515 break;
1516 case Mips::ATOMIC_LOAD_XOR_I64:
1517 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1518 break;
1519 case Mips::ATOMIC_LOAD_NAND_I64:
1520 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1521 break;
1522 case Mips::ATOMIC_SWAP_I64:
1523 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1524 break;
1525 case Mips::ATOMIC_LOAD_MIN_I32:
1526 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1527 NeedsAdditionalReg = true;
1528 break;
1529 case Mips::ATOMIC_LOAD_MAX_I32:
1530 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1531 NeedsAdditionalReg = true;
1532 break;
1533 case Mips::ATOMIC_LOAD_UMIN_I32:
1534 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1535 NeedsAdditionalReg = true;
1536 break;
1537 case Mips::ATOMIC_LOAD_UMAX_I32:
1538 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1539 NeedsAdditionalReg = true;
1540 break;
1541 case Mips::ATOMIC_LOAD_MIN_I64:
1542 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1543 NeedsAdditionalReg = true;
1544 break;
1545 case Mips::ATOMIC_LOAD_MAX_I64:
1546 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1547 NeedsAdditionalReg = true;
1548 break;
1549 case Mips::ATOMIC_LOAD_UMIN_I64:
1550 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1551 NeedsAdditionalReg = true;
1552 break;
1553 case Mips::ATOMIC_LOAD_UMAX_I64:
1554 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1555 NeedsAdditionalReg = true;
1556 break;
1557 default:
1558 llvm_unreachable("Unknown pseudo atomic for replacement!");
1559 }
1560
1561 Register OldVal = MI.getOperand(0).getReg();
1562 Register Ptr = MI.getOperand(1).getReg();
1563 Register Incr = MI.getOperand(2).getReg();
1564 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1565
1567
1568 // The scratch registers here with the EarlyClobber | Define | Implicit
1569 // flags is used to persuade the register allocator and the machine
1570 // verifier to accept the usage of this register. This has to be a real
1571 // register which has an UNDEF value but is dead after the instruction which
1572 // is unique among the registers chosen for the instruction.
1573
1574 // The EarlyClobber flag has the semantic properties that the operand it is
1575 // attached to is clobbered before the rest of the inputs are read. Hence it
1576 // must be unique among the operands to the instruction.
1577 // The Define flag is needed to coerce the machine verifier that an Undef
1578 // value isn't a problem.
1579 // The Dead flag is needed as the value in scratch isn't used by any other
1580 // instruction. Kill isn't used as Dead is more precise.
1581 // The implicit flag is here due to the interaction between the other flags
1582 // and the machine verifier.
1583
1584 // For correctness purpose, a new pseudo is introduced here. We need this
1585 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1586 // that is spread over >1 basic blocks. A register allocator which
1587 // introduces (or any codegen infact) a store, can violate the expectations
1588 // of the hardware.
1589 //
1590 // An atomic read-modify-write sequence starts with a linked load
1591 // instruction and ends with a store conditional instruction. The atomic
1592 // read-modify-write sequence fails if any of the following conditions
1593 // occur between the execution of ll and sc:
1594 // * A coherent store is completed by another process or coherent I/O
1595 // module into the block of synchronizable physical memory containing
1596 // the word. The size and alignment of the block is
1597 // implementation-dependent.
1598 // * A coherent store is executed between an LL and SC sequence on the
1599 // same processor to the block of synchornizable physical memory
1600 // containing the word.
1601 //
1602
1603 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1604 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1605
1606 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1607 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1608
1610 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1612 .addReg(PtrCopy)
1613 .addReg(IncrCopy)
1616 if (NeedsAdditionalReg) {
1617 Register Scratch2 =
1618 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1621 }
1622
1623 MI.eraseFromParent();
1624
1625 return BB;
1626}
1627
1628MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1629 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1630 unsigned SrcReg) const {
1632 const DebugLoc &DL = MI.getDebugLoc();
1633
1634 if (Subtarget.hasMips32r2() && Size == 1) {
1635 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1636 return BB;
1637 }
1638
1639 if (Subtarget.hasMips32r2() && Size == 2) {
1640 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1641 return BB;
1642 }
1643
1644 MachineFunction *MF = BB->getParent();
1646 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1647 Register ScrReg = RegInfo.createVirtualRegister(RC);
1648
1649 assert(Size < 32);
1650 int64_t ShiftImm = 32 - (Size * 8);
1651
1652 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1653 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1654
1655 return BB;
1656}
1657
1658MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1659 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1660 assert((Size == 1 || Size == 2) &&
1661 "Unsupported size for EmitAtomicBinaryPartial.");
1662
1663 MachineFunction *MF = BB->getParent();
1665 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1666 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1667 const TargetRegisterClass *RCp =
1668 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1670 DebugLoc DL = MI.getDebugLoc();
1671
1672 Register Dest = MI.getOperand(0).getReg();
1673 Register Ptr = MI.getOperand(1).getReg();
1674 Register Incr = MI.getOperand(2).getReg();
1675
1676 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1677 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1678 Register Mask = RegInfo.createVirtualRegister(RC);
1679 Register Mask2 = RegInfo.createVirtualRegister(RC);
1680 Register Incr2 = RegInfo.createVirtualRegister(RC);
1681 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1682 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1683 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1684 Register Scratch = RegInfo.createVirtualRegister(RC);
1685 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1686 Register Scratch3 = RegInfo.createVirtualRegister(RC);
1687
1688 unsigned AtomicOp = 0;
1689 bool NeedsAdditionalReg = false;
1690 switch (MI.getOpcode()) {
1691 case Mips::ATOMIC_LOAD_NAND_I8:
1692 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1693 break;
1694 case Mips::ATOMIC_LOAD_NAND_I16:
1695 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1696 break;
1697 case Mips::ATOMIC_SWAP_I8:
1698 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1699 break;
1700 case Mips::ATOMIC_SWAP_I16:
1701 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1702 break;
1703 case Mips::ATOMIC_LOAD_ADD_I8:
1704 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1705 break;
1706 case Mips::ATOMIC_LOAD_ADD_I16:
1707 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1708 break;
1709 case Mips::ATOMIC_LOAD_SUB_I8:
1710 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1711 break;
1712 case Mips::ATOMIC_LOAD_SUB_I16:
1713 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1714 break;
1715 case Mips::ATOMIC_LOAD_AND_I8:
1716 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1717 break;
1718 case Mips::ATOMIC_LOAD_AND_I16:
1719 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1720 break;
1721 case Mips::ATOMIC_LOAD_OR_I8:
1722 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1723 break;
1724 case Mips::ATOMIC_LOAD_OR_I16:
1725 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1726 break;
1727 case Mips::ATOMIC_LOAD_XOR_I8:
1728 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1729 break;
1730 case Mips::ATOMIC_LOAD_XOR_I16:
1731 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1732 break;
1733 case Mips::ATOMIC_LOAD_MIN_I8:
1734 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1735 NeedsAdditionalReg = true;
1736 break;
1737 case Mips::ATOMIC_LOAD_MIN_I16:
1738 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1739 NeedsAdditionalReg = true;
1740 break;
1741 case Mips::ATOMIC_LOAD_MAX_I8:
1742 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1743 NeedsAdditionalReg = true;
1744 break;
1745 case Mips::ATOMIC_LOAD_MAX_I16:
1746 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1747 NeedsAdditionalReg = true;
1748 break;
1749 case Mips::ATOMIC_LOAD_UMIN_I8:
1750 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1751 NeedsAdditionalReg = true;
1752 break;
1753 case Mips::ATOMIC_LOAD_UMIN_I16:
1754 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1755 NeedsAdditionalReg = true;
1756 break;
1757 case Mips::ATOMIC_LOAD_UMAX_I8:
1758 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1759 NeedsAdditionalReg = true;
1760 break;
1761 case Mips::ATOMIC_LOAD_UMAX_I16:
1762 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1763 NeedsAdditionalReg = true;
1764 break;
1765 default:
1766 llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1767 }
1768
1769 // insert new blocks after the current block
1770 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1771 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1773 MF->insert(It, exitMBB);
1774
1775 // Transfer the remainder of BB and its successor edges to exitMBB.
1776 exitMBB->splice(exitMBB->begin(), BB,
1777 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1779
1781
1782 // thisMBB:
1783 // addiu masklsb2,$0,-4 # 0xfffffffc
1784 // and alignedaddr,ptr,masklsb2
1785 // andi ptrlsb2,ptr,3
1786 // sll shiftamt,ptrlsb2,3
1787 // ori maskupper,$0,255 # 0xff
1788 // sll mask,maskupper,shiftamt
1789 // nor mask2,$0,mask
1790 // sll incr2,incr,shiftamt
1791
1792 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1793 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1794 .addReg(ABI.GetNullPtr()).addImm(-4);
1795 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1796 .addReg(Ptr).addReg(MaskLSB2);
1797 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1798 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1799 if (Subtarget.isLittle()) {
1800 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1801 } else {
1802 Register Off = RegInfo.createVirtualRegister(RC);
1803 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1804 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1805 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1806 }
1807 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1808 .addReg(Mips::ZERO).addImm(MaskImm);
1809 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1810 .addReg(MaskUpper).addReg(ShiftAmt);
1811 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1812 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1813
1814
1815 // The purposes of the flags on the scratch registers is explained in
1816 // emitAtomicBinary. In summary, we need a scratch register which is going to
1817 // be undef, that is unique among registers chosen for the instruction.
1818
1820 BuildMI(BB, DL, TII->get(AtomicOp))
1822 .addReg(AlignedAddr)
1823 .addReg(Incr2)
1824 .addReg(Mask)
1825 .addReg(Mask2)
1826 .addReg(ShiftAmt)
1833 if (NeedsAdditionalReg) {
1834 Register Scratch4 = RegInfo.createVirtualRegister(RC);
1837 }
1838
1839 MI.eraseFromParent(); // The instruction is gone now.
1840
1841 return exitMBB;
1842}
1843
1844// Lower atomic compare and swap to a pseudo instruction, taking care to
1845// define a scratch register for the pseudo instruction's expansion. The
1846// instruction is expanded after the register allocator as to prevent
1847// the insertion of stores between the linked load and the store conditional.
1848
1850MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1851 MachineBasicBlock *BB) const {
1852
1853 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1854 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1855 "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1856
1857 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1858
1859 MachineFunction *MF = BB->getParent();
1863 DebugLoc DL = MI.getDebugLoc();
1864
1865 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1866 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1867 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1868 Register Dest = MI.getOperand(0).getReg();
1869 Register Ptr = MI.getOperand(1).getReg();
1870 Register OldVal = MI.getOperand(2).getReg();
1871 Register NewVal = MI.getOperand(3).getReg();
1872
1873 Register Scratch = MRI.createVirtualRegister(RC);
1875
1876 // We need to create copies of the various registers and kill them at the
1877 // atomic pseudo. If the copies are not made, when the atomic is expanded
1878 // after fast register allocation, the spills will end up outside of the
1879 // blocks that their values are defined in, causing livein errors.
1880
1881 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1882 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1883 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1884
1885 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1886 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1887 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1888
1889 // The purposes of the flags on the scratch registers is explained in
1890 // emitAtomicBinary. In summary, we need a scratch register which is going to
1891 // be undef, that is unique among registers chosen for the instruction.
1892
1893 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1895 .addReg(PtrCopy, RegState::Kill)
1896 .addReg(OldValCopy, RegState::Kill)
1897 .addReg(NewValCopy, RegState::Kill)
1900
1901 MI.eraseFromParent(); // The instruction is gone now.
1902
1903 return BB;
1904}
1905
1906MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1907 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1908 assert((Size == 1 || Size == 2) &&
1909 "Unsupported size for EmitAtomicCmpSwapPartial.");
1910
1911 MachineFunction *MF = BB->getParent();
1913 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1914 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1915 const TargetRegisterClass *RCp =
1916 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1918 DebugLoc DL = MI.getDebugLoc();
1919
1920 Register Dest = MI.getOperand(0).getReg();
1921 Register Ptr = MI.getOperand(1).getReg();
1922 Register CmpVal = MI.getOperand(2).getReg();
1923 Register NewVal = MI.getOperand(3).getReg();
1924
1925 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1926 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1927 Register Mask = RegInfo.createVirtualRegister(RC);
1928 Register Mask2 = RegInfo.createVirtualRegister(RC);
1929 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1930 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1931 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1932 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1933 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1934 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1935 Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1936 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1937 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1938 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1939
1940 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1941 // flags are used to coerce the register allocator and the machine verifier to
1942 // accept the usage of these registers.
1943 // The EarlyClobber flag has the semantic properties that the operand it is
1944 // attached to is clobbered before the rest of the inputs are read. Hence it
1945 // must be unique among the operands to the instruction.
1946 // The Define flag is needed to coerce the machine verifier that an Undef
1947 // value isn't a problem.
1948 // The Dead flag is needed as the value in scratch isn't used by any other
1949 // instruction. Kill isn't used as Dead is more precise.
1950 Register Scratch = RegInfo.createVirtualRegister(RC);
1951 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1952
1953 // insert new blocks after the current block
1954 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1955 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1957 MF->insert(It, exitMBB);
1958
1959 // Transfer the remainder of BB and its successor edges to exitMBB.
1960 exitMBB->splice(exitMBB->begin(), BB,
1961 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1963
1965
1966 // thisMBB:
1967 // addiu masklsb2,$0,-4 # 0xfffffffc
1968 // and alignedaddr,ptr,masklsb2
1969 // andi ptrlsb2,ptr,3
1970 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1971 // sll shiftamt,ptrlsb2,3
1972 // ori maskupper,$0,255 # 0xff
1973 // sll mask,maskupper,shiftamt
1974 // nor mask2,$0,mask
1975 // andi maskedcmpval,cmpval,255
1976 // sll shiftedcmpval,maskedcmpval,shiftamt
1977 // andi maskednewval,newval,255
1978 // sll shiftednewval,maskednewval,shiftamt
1979 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1980 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1981 .addReg(ABI.GetNullPtr()).addImm(-4);
1982 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1983 .addReg(Ptr).addReg(MaskLSB2);
1984 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1985 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1986 if (Subtarget.isLittle()) {
1987 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1988 } else {
1989 Register Off = RegInfo.createVirtualRegister(RC);
1990 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1991 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1992 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1993 }
1994 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1995 .addReg(Mips::ZERO).addImm(MaskImm);
1996 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1997 .addReg(MaskUpper).addReg(ShiftAmt);
1998 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1999 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
2000 .addReg(CmpVal).addImm(MaskImm);
2001 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
2002 .addReg(MaskedCmpVal).addReg(ShiftAmt);
2003 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
2004 .addReg(NewVal).addImm(MaskImm);
2005 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
2006 .addReg(MaskedNewVal).addReg(ShiftAmt);
2007
2008 // The purposes of the flags on the scratch registers are explained in
2009 // emitAtomicBinary. In summary, we need a scratch register which is going to
2010 // be undef, that is unique among the register chosen for the instruction.
2011
2012 BuildMI(BB, DL, TII->get(AtomicOp))
2014 .addReg(AlignedAddr)
2015 .addReg(Mask)
2016 .addReg(ShiftedCmpVal)
2017 .addReg(Mask2)
2018 .addReg(ShiftedNewVal)
2019 .addReg(ShiftAmt)
2024
2025 MI.eraseFromParent(); // The instruction is gone now.
2026
2027 return exitMBB;
2028}
2029
2030SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2031 // The first operand is the chain, the second is the condition, the third is
2032 // the block to branch to if the condition is true.
2033 SDValue Chain = Op.getOperand(0);
2034 SDValue Dest = Op.getOperand(2);
2035 SDLoc DL(Op);
2036
2038 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2039
2040 // Return if flag is not set by a floating point comparison.
2041 if (CondRes.getOpcode() != MipsISD::FPCmp)
2042 return Op;
2043
2044 SDValue CCNode = CondRes.getOperand(2);
2046 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2048 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2049 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2050 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2051 FCC0, Dest, CondRes);
2052}
2053
2054SDValue MipsTargetLowering::
2055lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2056{
2058 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2059
2060 // Return if flag is not set by a floating point comparison.
2061 if (Cond.getOpcode() != MipsISD::FPCmp)
2062 return Op;
2063
2064 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2065 SDLoc(Op));
2066}
2067
2068SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2070 SDValue Cond = createFPCmp(DAG, Op);
2071
2072 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2073 "Floating point operand expected.");
2074
2075 SDLoc DL(Op);
2076 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2077 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2078
2079 return createCMovFP(DAG, Cond, True, False, DL);
2080}
2081
2082SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2083 SelectionDAG &DAG) const {
2084 EVT Ty = Op.getValueType();
2085 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2086 const GlobalValue *GV = N->getGlobal();
2087
2088 if (!isPositionIndependent()) {
2089 const MipsTargetObjectFile *TLOF =
2090 static_cast<const MipsTargetObjectFile *>(
2092 const GlobalObject *GO = GV->getAliaseeObject();
2093 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2094 // %gp_rel relocation
2095 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2096
2097 // %hi/%lo relocation
2098 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2099 // %highest/%higher/%hi/%lo relocation
2100 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2101 }
2102
2103 // Every other architecture would use shouldAssumeDSOLocal in here, but
2104 // mips is special.
2105 // * In PIC code mips requires got loads even for local statics!
2106 // * To save on got entries, for local statics the got entry contains the
2107 // page and an additional add instruction takes care of the low bits.
2108 // * It is legal to access a hidden symbol with a non hidden undefined,
2109 // so one cannot guarantee that all access to a hidden symbol will know
2110 // it is hidden.
2111 // * Mips linkers don't support creating a page and a full got entry for
2112 // the same symbol.
2113 // * Given all that, we have to use a full got entry for hidden symbols :-(
2114 if (GV->hasLocalLinkage())
2115 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2116
2117 if (Subtarget.useXGOT())
2118 return getAddrGlobalLargeGOT(
2120 DAG.getEntryNode(),
2121 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2122
2123 return getAddrGlobal(
2124 N, SDLoc(N), Ty, DAG,
2126 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2127}
2128
2129SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2130 SelectionDAG &DAG) const {
2131 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2132 EVT Ty = Op.getValueType();
2133
2134 if (!isPositionIndependent())
2135 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2136 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2137
2138 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2139}
2140
2141SDValue MipsTargetLowering::
2142lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2143{
2144 // If the relocation model is PIC, use the General Dynamic TLS Model or
2145 // Local Dynamic TLS model, otherwise use the Initial Exec or
2146 // Local Exec TLS Model.
2147
2148 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2149 if (DAG.getTarget().useEmulatedTLS())
2150 return LowerToTLSEmulatedModel(GA, DAG);
2151
2152 SDLoc DL(GA);
2153 const GlobalValue *GV = GA->getGlobal();
2154 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2155
2157
2158 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2159 // General Dynamic and Local Dynamic TLS Model.
2160 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2162
2163 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2165 getGlobalReg(DAG, PtrVT), TGA);
2166 unsigned PtrSize = PtrVT.getSizeInBits();
2167 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2168
2169 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2170
2172 ArgListEntry Entry;
2173 Entry.Node = Argument;
2174 Entry.Ty = PtrTy;
2175 Args.push_back(Entry);
2176
2178 CLI.setDebugLoc(DL)
2179 .setChain(DAG.getEntryNode())
2180 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2181 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2182
2183 SDValue Ret = CallResult.first;
2184
2185 if (model != TLSModel::LocalDynamic)
2186 return Ret;
2187
2188 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2190 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2191 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2193 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2194 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2195 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2196 }
2197
2199 if (model == TLSModel::InitialExec) {
2200 // Initial Exec TLS Model
2201 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2203 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2204 TGA);
2205 Offset =
2206 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2207 } else {
2208 // Local Exec TLS Model
2209 assert(model == TLSModel::LocalExec);
2210 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2212 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2214 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2215 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2216 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2217 }
2218
2220 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2221}
2222
2223SDValue MipsTargetLowering::
2224lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2225{
2226 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2227 EVT Ty = Op.getValueType();
2228
2229 if (!isPositionIndependent())
2230 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2231 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2232
2233 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2234}
2235
2236SDValue MipsTargetLowering::
2237lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2238{
2239 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2240 EVT Ty = Op.getValueType();
2241
2242 if (!isPositionIndependent()) {
2243 const MipsTargetObjectFile *TLOF =
2244 static_cast<const MipsTargetObjectFile *>(
2246
2247 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2249 // %gp_rel relocation
2250 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2251
2252 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2253 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2254 }
2255
2256 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2257}
2258
2259SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2261 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2262
2263 SDLoc DL(Op);
2264 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2266
2267 // vastart just stores the address of the VarArgsFrameIndex slot into the
2268 // memory location argument.
2269 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2270 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2271 MachinePointerInfo(SV));
2272}
2273
2274SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2275 SDNode *Node = Op.getNode();
2276 EVT VT = Node->getValueType(0);
2277 SDValue Chain = Node->getOperand(0);
2278 SDValue VAListPtr = Node->getOperand(1);
2279 const Align Align =
2280 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2281 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2282 SDLoc DL(Node);
2283 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2284
2285 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2286 VAListPtr, MachinePointerInfo(SV));
2287 SDValue VAList = VAListLoad;
2288
2289 // Re-align the pointer if necessary.
2290 // It should only ever be necessary for 64-bit types on O32 since the minimum
2291 // argument alignment is the same as the maximum type alignment for N32/N64.
2292 //
2293 // FIXME: We currently align too often. The code generator doesn't notice
2294 // when the pointer is still aligned from the last va_arg (or pair of
2295 // va_args for the i64 on O32 case).
2297 VAList = DAG.getNode(
2298 ISD::ADD, DL, VAList.getValueType(), VAList,
2299 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2300
2301 VAList = DAG.getNode(
2302 ISD::AND, DL, VAList.getValueType(), VAList,
2303 DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2304 }
2305
2306 // Increment the pointer, VAList, to the next vaarg.
2307 auto &TD = DAG.getDataLayout();
2308 unsigned ArgSizeInBytes =
2310 SDValue Tmp3 =
2311 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2312 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2313 DL, VAList.getValueType()));
2314 // Store the incremented VAList to the legalized pointer
2315 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2316 MachinePointerInfo(SV));
2317
2318 // In big-endian mode we must adjust the pointer when the load size is smaller
2319 // than the argument slot size. We must also reduce the known alignment to
2320 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2321 // the correct half of the slot, and reduce the alignment from 8 (slot
2322 // alignment) down to 4 (type alignment).
2323 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2324 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2325 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2326 DAG.getIntPtrConstant(Adjustment, DL));
2327 }
2328 // Load the actual argument out of the pointer VAList
2329 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2330}
2331
2333 bool HasExtractInsert) {
2334 EVT TyX = Op.getOperand(0).getValueType();
2335 EVT TyY = Op.getOperand(1).getValueType();
2336 SDLoc DL(Op);
2337 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2338 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2339 SDValue Res;
2340
2341 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2342 // to i32.
2343 SDValue X = (TyX == MVT::f32) ?
2344 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2345 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2346 Const1);
2347 SDValue Y = (TyY == MVT::f32) ?
2348 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2349 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2350 Const1);
2351
2352 if (HasExtractInsert) {
2353 // ext E, Y, 31, 1 ; extract bit31 of Y
2354 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2355 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2356 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2357 } else {
2358 // sll SllX, X, 1
2359 // srl SrlX, SllX, 1
2360 // srl SrlY, Y, 31
2361 // sll SllY, SrlX, 31
2362 // or Or, SrlX, SllY
2363 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2364 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2365 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2366 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2367 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2368 }
2369
2370 if (TyX == MVT::f32)
2371 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2372
2373 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2374 Op.getOperand(0),
2375 DAG.getConstant(0, DL, MVT::i32));
2376 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2377}
2378
2380 bool HasExtractInsert) {
2381 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2382 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2383 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2384 SDLoc DL(Op);
2385 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2386
2387 // Bitcast to integer nodes.
2388 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2389 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2390
2391 if (HasExtractInsert) {
2392 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2393 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2394 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2395 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2396
2397 if (WidthX > WidthY)
2398 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2399 else if (WidthY > WidthX)
2400 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2401
2402 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2403 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2404 X);
2405 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2406 }
2407
2408 // (d)sll SllX, X, 1
2409 // (d)srl SrlX, SllX, 1
2410 // (d)srl SrlY, Y, width(Y)-1
2411 // (d)sll SllY, SrlX, width(Y)-1
2412 // or Or, SrlX, SllY
2413 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2414 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2415 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2416 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2417
2418 if (WidthX > WidthY)
2419 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2420 else if (WidthY > WidthX)
2421 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2422
2423 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2424 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2425 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2426 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2427}
2428
2429SDValue
2430MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2431 if (Subtarget.isGP64bit())
2433
2435}
2436
2437SDValue MipsTargetLowering::lowerFABS32(SDValue Op, SelectionDAG &DAG,
2438 bool HasExtractInsert) const {
2439 SDLoc DL(Op);
2440 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2441
2443 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2444
2445 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2446 // to i32.
2447 SDValue X = (Op.getValueType() == MVT::f32)
2448 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2449 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2450 Op.getOperand(0), Const1);
2451
2452 // Clear MSB.
2453 if (HasExtractInsert)
2454 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2455 DAG.getRegister(Mips::ZERO, MVT::i32),
2456 DAG.getConstant(31, DL, MVT::i32), Const1, X);
2457 else {
2458 // TODO: Provide DAG patterns which transform (and x, cst)
2459 // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2460 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2461 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2462 }
2463
2464 if (Op.getValueType() == MVT::f32)
2465 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2466
2467 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2468 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2469 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2470 // place.
2471 SDValue LowX =
2472 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2473 DAG.getConstant(0, DL, MVT::i32));
2474 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2475}
2476
2477SDValue MipsTargetLowering::lowerFABS64(SDValue Op, SelectionDAG &DAG,
2478 bool HasExtractInsert) const {
2479 SDLoc DL(Op);
2480 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2481
2483 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2484
2485 // Bitcast to integer node.
2486 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2487
2488 // Clear MSB.
2489 if (HasExtractInsert)
2490 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2491 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2492 DAG.getConstant(63, DL, MVT::i32), Const1, X);
2493 else {
2494 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2495 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2496 }
2497
2498 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2499}
2500
2501SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2502 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2503 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2504
2505 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2506}
2507
2508SDValue MipsTargetLowering::
2509lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2510 // check the depth
2511 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2512 DAG.getContext()->emitError(
2513 "return address can be determined only for current frame");
2514 return SDValue();
2515 }
2516
2518 MFI.setFrameAddressIsTaken(true);
2519 EVT VT = Op.getValueType();
2520 SDLoc DL(Op);
2521 SDValue FrameAddr = DAG.getCopyFromReg(
2522 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2523 return FrameAddr;
2524}
2525
2526SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2527 SelectionDAG &DAG) const {
2529 return SDValue();
2530
2531 // check the depth
2532 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2533 DAG.getContext()->emitError(
2534 "return address can be determined only for current frame");
2535 return SDValue();
2536 }
2537
2539 MachineFrameInfo &MFI = MF.getFrameInfo();
2540 MVT VT = Op.getSimpleValueType();
2541 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2542 MFI.setReturnAddressIsTaken(true);
2543
2544 // Return RA, which contains the return address. Mark it an implicit live-in.
2546 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2547}
2548
2549// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2550// generated from __builtin_eh_return (offset, handler)
2551// The effect of this is to adjust the stack pointer by "offset"
2552// and then branch to "handler".
2553SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2554 const {
2557
2558 MipsFI->setCallsEhReturn();
2559 SDValue Chain = Op.getOperand(0);
2560 SDValue Offset = Op.getOperand(1);
2561 SDValue Handler = Op.getOperand(2);
2562 SDLoc DL(Op);
2563 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2564
2565 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2566 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2567 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2568 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2569 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2570 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2571 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2572 DAG.getRegister(OffsetReg, Ty),
2573 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2574 Chain.getValue(1));
2575}
2576
2577SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2578 SelectionDAG &DAG) const {
2579 // FIXME: Need pseudo-fence for 'singlethread' fences
2580 // FIXME: Set SType for weaker fences where supported/appropriate.
2581 unsigned SType = 0;
2582 SDLoc DL(Op);
2583 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2584 DAG.getConstant(SType, DL, MVT::i32));
2585}
2586
2587SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2588 SelectionDAG &DAG) const {
2589 SDLoc DL(Op);
2590 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2591
2592 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2593 SDValue Shamt = Op.getOperand(2);
2594 // if shamt < (VT.bits):
2595 // lo = (shl lo, shamt)
2596 // hi = (or (shl hi, shamt) (srl (srl lo, 1), (xor shamt, (VT.bits-1))))
2597 // else:
2598 // lo = 0
2599 // hi = (shl lo, shamt[4:0])
2600 SDValue Not =
2601 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2602 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2603 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2604 DAG.getConstant(1, DL, VT));
2605 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2606 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2607 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2608 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2609 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2610 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2611 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2612 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2613 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2614
2615 SDValue Ops[2] = {Lo, Hi};
2616 return DAG.getMergeValues(Ops, DL);
2617}
2618
2619SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2620 bool IsSRA) const {
2621 SDLoc DL(Op);
2622 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2623 SDValue Shamt = Op.getOperand(2);
2624 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2625
2626 // if shamt < (VT.bits):
2627 // lo = (or (shl (shl hi, 1), (xor shamt, (VT.bits-1))) (srl lo, shamt))
2628 // if isSRA:
2629 // hi = (sra hi, shamt)
2630 // else:
2631 // hi = (srl hi, shamt)
2632 // else:
2633 // if isSRA:
2634 // lo = (sra hi, shamt[4:0])
2635 // hi = (sra hi, 31)
2636 // else:
2637 // lo = (srl hi, shamt[4:0])
2638 // hi = 0
2639 SDValue Not =
2640 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2641 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2642 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2643 DAG.getConstant(1, DL, VT));
2644 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2645 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2646 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2647 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2648 DL, VT, Hi, Shamt);
2649 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2650 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2651 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2652 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2653
2654 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2655 SDVTList VTList = DAG.getVTList(VT, VT);
2656 return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2657 : Mips::PseudoD_SELECT_I,
2658 DL, VTList, Cond, ShiftRightHi,
2659 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2660 ShiftRightHi);
2661 }
2662
2663 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2664 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2665 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2666
2667 SDValue Ops[2] = {Lo, Hi};
2668 return DAG.getMergeValues(Ops, DL);
2669}
2670
2671static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2672 SDValue Chain, SDValue Src, unsigned Offset) {
2673 SDValue Ptr = LD->getBasePtr();
2674 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2675 EVT BasePtrVT = Ptr.getValueType();
2676 SDLoc DL(LD);
2677 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2678
2679 if (Offset)
2680 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2681 DAG.getConstant(Offset, DL, BasePtrVT));
2682
2683 SDValue Ops[] = { Chain, Ptr, Src };
2684 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2685 LD->getMemOperand());
2686}
2687
2688// Expand an unaligned 32 or 64-bit integer load node.
2690 LoadSDNode *LD = cast<LoadSDNode>(Op);
2691 EVT MemVT = LD->getMemoryVT();
2692
2694 return Op;
2695
2696 // Return if load is aligned or if MemVT is neither i32 nor i64.
2697 if ((LD->getAlign().value() >= (MemVT.getSizeInBits() / 8)) ||
2698 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2699 return SDValue();
2700
2701 bool IsLittle = Subtarget.isLittle();
2702 EVT VT = Op.getValueType();
2703 ISD::LoadExtType ExtType = LD->getExtensionType();
2704 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2705
2706 assert((VT == MVT::i32) || (VT == MVT::i64));
2707
2708 // Expand
2709 // (set dst, (i64 (load baseptr)))
2710 // to
2711 // (set tmp, (ldl (add baseptr, 7), undef))
2712 // (set dst, (ldr baseptr, tmp))
2713 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2714 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2715 IsLittle ? 7 : 0);
2716 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2717 IsLittle ? 0 : 7);
2718 }
2719
2720 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2721 IsLittle ? 3 : 0);
2722 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2723 IsLittle ? 0 : 3);
2724
2725 // Expand
2726 // (set dst, (i32 (load baseptr))) or
2727 // (set dst, (i64 (sextload baseptr))) or
2728 // (set dst, (i64 (extload baseptr)))
2729 // to
2730 // (set tmp, (lwl (add baseptr, 3), undef))
2731 // (set dst, (lwr baseptr, tmp))
2732 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2733 (ExtType == ISD::EXTLOAD))
2734 return LWR;
2735
2736 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2737
2738 // Expand
2739 // (set dst, (i64 (zextload baseptr)))
2740 // to
2741 // (set tmp0, (lwl (add baseptr, 3), undef))
2742 // (set tmp1, (lwr baseptr, tmp0))
2743 // (set tmp2, (shl tmp1, 32))
2744 // (set dst, (srl tmp2, 32))
2745 SDLoc DL(LD);
2746 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2747 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2748 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2749 SDValue Ops[] = { SRL, LWR.getValue(1) };
2750 return DAG.getMergeValues(Ops, DL);
2751}
2752
2753static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2754 SDValue Chain, unsigned Offset) {
2755 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2756 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2757 SDLoc DL(SD);
2758 SDVTList VTList = DAG.getVTList(MVT::Other);
2759
2760 if (Offset)
2761 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2762 DAG.getConstant(Offset, DL, BasePtrVT));
2763
2764 SDValue Ops[] = { Chain, Value, Ptr };
2765 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2766 SD->getMemOperand());
2767}
2768
2769// Expand an unaligned 32 or 64-bit integer store node.
2771 bool IsLittle) {
2772 SDValue Value = SD->getValue(), Chain = SD->getChain();
2773 EVT VT = Value.getValueType();
2774
2775 // Expand
2776 // (store val, baseptr) or
2777 // (truncstore val, baseptr)
2778 // to
2779 // (swl val, (add baseptr, 3))
2780 // (swr val, baseptr)
2781 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2782 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2783 IsLittle ? 3 : 0);
2784 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2785 }
2786
2787 assert(VT == MVT::i64);
2788
2789 // Expand
2790 // (store val, baseptr)
2791 // to
2792 // (sdl val, (add baseptr, 7))
2793 // (sdr val, baseptr)
2794 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2795 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2796}
2797
2798// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2800 bool SingleFloat) {
2801 SDValue Val = SD->getValue();
2802
2803 if (Val.getOpcode() != ISD::FP_TO_SINT ||
2804 (Val.getValueSizeInBits() > 32 && SingleFloat))
2805 return SDValue();
2806
2808 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2809 Val.getOperand(0));
2810 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2811 SD->getPointerInfo(), SD->getAlign(),
2812 SD->getMemOperand()->getFlags());
2813}
2814
2816 StoreSDNode *SD = cast<StoreSDNode>(Op);
2817 EVT MemVT = SD->getMemoryVT();
2818
2819 // Lower unaligned integer stores.
2821 (SD->getAlign().value() < (MemVT.getSizeInBits() / 8)) &&
2822 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2823 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2824
2826}
2827
2828SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2829 SelectionDAG &DAG) const {
2830
2831 // Return a fixed StackObject with offset 0 which points to the old stack
2832 // pointer.
2834 EVT ValTy = Op->getValueType(0);
2835 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2836 return DAG.getFrameIndex(FI, ValTy);
2837}
2838
2839SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2840 SelectionDAG &DAG) const {
2841 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2842 return SDValue();
2843
2844 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2845 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2846 Op.getOperand(0));
2847 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2848}
2849
2850//===----------------------------------------------------------------------===//
2851// Calling Convention Implementation
2852//===----------------------------------------------------------------------===//
2853
2854//===----------------------------------------------------------------------===//
2855// TODO: Implement a generic logic using tblgen that can support this.
2856// Mips O32 ABI rules:
2857// ---
2858// i32 - Passed in A0, A1, A2, A3 and stack
2859// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2860// an argument. Otherwise, passed in A1, A2, A3 and stack.
2861// f64 - Only passed in two aliased f32 registers if no int reg has been used
2862// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2863// not used, it must be shadowed. If only A3 is available, shadow it and
2864// go to stack.
2865// vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2866// vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2867// with the remainder spilled to the stack.
2868// vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2869// spilling the remainder to the stack.
2870//
2871// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2872//===----------------------------------------------------------------------===//
2873
2874static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2875 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2876 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2877 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2879
2880 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2881
2882 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2883
2884 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2885
2886 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2887
2888 // Do not process byval args here.
2889 if (ArgFlags.isByVal())
2890 return true;
2891
2892 // Promote i8 and i16
2893 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2894 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2895 LocVT = MVT::i32;
2896 if (ArgFlags.isSExt())
2897 LocInfo = CCValAssign::SExtUpper;
2898 else if (ArgFlags.isZExt())
2899 LocInfo = CCValAssign::ZExtUpper;
2900 else
2901 LocInfo = CCValAssign::AExtUpper;
2902 }
2903 }
2904
2905 // Promote i8 and i16
2906 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2907 LocVT = MVT::i32;
2908 if (ArgFlags.isSExt())
2909 LocInfo = CCValAssign::SExt;
2910 else if (ArgFlags.isZExt())
2911 LocInfo = CCValAssign::ZExt;
2912 else
2913 LocInfo = CCValAssign::AExt;
2914 }
2915
2916 unsigned Reg;
2917
2918 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2919 // is true: function is vararg, argument is 3rd or higher, there is previous
2920 // argument which is not f32 or f64.
2921 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2922 State.getFirstUnallocated(F32Regs) != ValNo;
2923 Align OrigAlign = ArgFlags.getNonZeroOrigAlign();
2924 bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8));
2925 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2926
2927 // The MIPS vector ABI for floats passes them in a pair of registers
2928 if (ValVT == MVT::i32 && isVectorFloat) {
2929 // This is the start of an vector that was scalarized into an unknown number
2930 // of components. It doesn't matter how many there are. Allocate one of the
2931 // notional 8 byte aligned registers which map onto the argument stack, and
2932 // shadow the register lost to alignment requirements.
2933 if (ArgFlags.isSplit()) {
2934 Reg = State.AllocateReg(FloatVectorIntRegs);
2935 if (Reg == Mips::A2)
2936 State.AllocateReg(Mips::A1);
2937 else if (Reg == 0)
2938 State.AllocateReg(Mips::A3);
2939 } else {
2940 // If we're an intermediate component of the split, we can just attempt to
2941 // allocate a register directly.
2942 Reg = State.AllocateReg(IntRegs);
2943 }
2944 } else if (ValVT == MVT::i32 ||
2945 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2946 Reg = State.AllocateReg(IntRegs);
2947 // If this is the first part of an i64 arg,
2948 // the allocated register must be either A0 or A2.
2949 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2950 Reg = State.AllocateReg(IntRegs);
2951 LocVT = MVT::i32;
2952 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2953 // Allocate int register and shadow next int register. If first
2954 // available register is Mips::A1 or Mips::A3, shadow it too.
2955 Reg = State.AllocateReg(IntRegs);
2956 if (Reg == Mips::A1 || Reg == Mips::A3)
2957 Reg = State.AllocateReg(IntRegs);
2958
2959 if (Reg) {
2960 LocVT = MVT::i32;
2961
2962 State.addLoc(
2963 CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2964 MCRegister HiReg = State.AllocateReg(IntRegs);
2965 assert(HiReg);
2966 State.addLoc(
2967 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
2968 return false;
2969 }
2970 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2971 // we are guaranteed to find an available float register
2972 if (ValVT == MVT::f32) {
2973 Reg = State.AllocateReg(F32Regs);
2974 // Shadow int register
2975 State.AllocateReg(IntRegs);
2976 } else {
2977 Reg = State.AllocateReg(F64Regs);
2978 // Shadow int registers
2979 unsigned Reg2 = State.AllocateReg(IntRegs);
2980 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2981 State.AllocateReg(IntRegs);
2982 State.AllocateReg(IntRegs);
2983 }
2984 } else
2985 llvm_unreachable("Cannot handle this ValVT.");
2986
2987 if (!Reg) {
2988 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2989 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2990 } else
2991 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2992
2993 return false;
2994}
2995
2996static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2997 MVT LocVT, CCValAssign::LocInfo LocInfo,
2998 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2999 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
3000
3001 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
3002}
3003
3004static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
3005 MVT LocVT, CCValAssign::LocInfo LocInfo,
3006 ISD::ArgFlagsTy ArgFlags, CCState &State) {
3007 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
3008
3009 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
3010}
3011
3012static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
3013 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
3015
3016#include "MipsGenCallingConv.inc"
3017
3019 return CC_Mips_FixedArg;
3020 }
3021
3023 return RetCC_Mips;
3024 }
3025//===----------------------------------------------------------------------===//
3026// Call Calling Convention Implementation
3027//===----------------------------------------------------------------------===//
3028
3029SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3030 SDValue Chain, SDValue Arg,
3031 const SDLoc &DL, bool IsTailCall,
3032 SelectionDAG &DAG) const {
3033 if (!IsTailCall) {
3034 SDValue PtrOff =
3035 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3037 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3038 }
3039
3041 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3042 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3043 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(),
3045}
3046
3049 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3050 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3051 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3052 SDValue Chain) const {
3053 // Insert node "GP copy globalreg" before call to function.
3054 //
3055 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3056 // in PIC mode) allow symbols to be resolved via lazy binding.
3057 // The lazy binding stub requires GP to point to the GOT.
3058 // Note that we don't need GP to point to the GOT for indirect calls
3059 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3060 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3061 // used for the function (that is, Mips linker doesn't generate lazy binding
3062 // stub for a function whose address is taken in the program).
3063 if (IsPICCall && !InternalLinkage && IsCallReloc) {
3064 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3065 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3066 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3067 }
3068
3069 // Build a sequence of copy-to-reg nodes chained together with token
3070 // chain and flag operands which copy the outgoing args into registers.
3071 // The InGlue in necessary since all emitted instructions must be
3072 // stuck together.
3073 SDValue InGlue;
3074
3075 for (auto &R : RegsToPass) {
3076 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InGlue);
3077 InGlue = Chain.getValue(1);
3078 }
3079
3080 // Add argument registers to the end of the list so that they are
3081 // known live into the call.
3082 for (auto &R : RegsToPass)
3083 Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType()));
3084
3085 // Add a register mask operand representing the call-preserved registers.
3087 const uint32_t *Mask =
3088 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3089 assert(Mask && "Missing call preserved mask for calling convention");
3091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
3092 StringRef Sym = G->getGlobal()->getName();
3093 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3094 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3096 }
3097 }
3098 }
3099 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3100
3101 if (InGlue.getNode())
3102 Ops.push_back(InGlue);
3103}
3104
3106 SDNode *Node) const {
3107 switch (MI.getOpcode()) {
3108 default:
3109 return;
3110 case Mips::JALR:
3111 case Mips::JALRPseudo:
3112 case Mips::JALR64:
3113 case Mips::JALR64Pseudo:
3114 case Mips::JALR16_MM:
3115 case Mips::JALRC16_MMR6:
3116 case Mips::TAILCALLREG:
3117 case Mips::TAILCALLREG64:
3118 case Mips::TAILCALLR6REG:
3119 case Mips::TAILCALL64R6REG:
3120 case Mips::TAILCALLREG_MM:
3121 case Mips::TAILCALLREG_MMR6: {
3122 if (!EmitJalrReloc ||
3125 Node->getNumOperands() < 1 ||
3126 Node->getOperand(0).getNumOperands() < 2) {
3127 return;
3128 }
3129 // We are after the callee address, set by LowerCall().
3130 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3131 // symbol.
3132 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3133 StringRef Sym;
3134 if (const GlobalAddressSDNode *G =
3135 dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3136 // We must not emit the R_MIPS_JALR relocation against data symbols
3137 // since this will cause run-time crashes if the linker replaces the
3138 // call instruction with a relative branch to the data symbol.
3139 if (!isa<Function>(G->getGlobal())) {
3140 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "
3141 << G->getGlobal()->getName() << "\n");
3142 return;
3143 }
3144 Sym = G->getGlobal()->getName();
3145 }
3146 else if (const ExternalSymbolSDNode *ES =
3147 dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3148 Sym = ES->getSymbol();
3149 }
3150
3151 if (Sym.empty())
3152 return;
3153
3154 MachineFunction *MF = MI.getParent()->getParent();
3156 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n");
3158 }
3159 }
3160}
3161
3162/// LowerCall - functions arguments are copied from virtual regs to
3163/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3164SDValue
3165MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3166 SmallVectorImpl<SDValue> &InVals) const {
3167 SelectionDAG &DAG = CLI.DAG;
3168 SDLoc DL = CLI.DL;
3170 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3172 SDValue Chain = CLI.Chain;
3173 SDValue Callee = CLI.Callee;
3174 bool &IsTailCall = CLI.IsTailCall;
3175 CallingConv::ID CallConv = CLI.CallConv;
3176 bool IsVarArg = CLI.IsVarArg;
3177
3179 MachineFrameInfo &MFI = MF.getFrameInfo();
3181 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3182 bool IsPIC = isPositionIndependent();
3183
3184 // Analyze operands of the call, assigning locations to each operand.
3186 MipsCCState CCInfo(
3187 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3189
3190 const ExternalSymbolSDNode *ES =
3191 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
3192
3193 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3194 // is during the lowering of a call with a byval argument which produces
3195 // a call to memcpy. For the O32 case, this causes the caller to allocate
3196 // stack space for the reserved argument area for the callee, then recursively
3197 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3198 // ABIs mandate that the callee allocates the reserved argument area. We do
3199 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3200 //
3201 // If the callee has a byval argument and memcpy is used, we are mandated
3202 // to already have produced a reserved argument area for the callee for O32.
3203 // Therefore, the reserved argument area can be reused for both calls.
3204 //
3205 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3206 // present, as we have yet to hook that node onto the chain.
3207 //
3208 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3209 // case. GCC does a similar trick, in that wherever possible, it calculates
3210 // the maximum out going argument area (including the reserved area), and
3211 // preallocates the stack space on entrance to the caller.
3212 //
3213 // FIXME: We should do the same for efficiency and space.
3214
3215 // Note: The check on the calling convention below must match
3216 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3217 bool MemcpyInByVal = ES &&
3218 StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3219 CallConv != CallingConv::Fast &&
3220 Chain.getOpcode() == ISD::CALLSEQ_START;
3221
3222 // Allocate the reserved argument area. It seems strange to do this from the
3223 // caller side but removing it breaks the frame size calculation.
3224 unsigned ReservedArgArea =
3225 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3226 CCInfo.AllocateStack(ReservedArgArea, Align(1));
3227
3228 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3229 ES ? ES->getSymbol() : nullptr);
3230
3231 // Get a count of how many bytes are to be pushed on the stack.
3232 unsigned StackSize = CCInfo.getStackSize();
3233
3234 // Call site info for function parameters tracking.
3236
3237 // Check if it's really possible to do a tail call. Restrict it to functions
3238 // that are part of this compilation unit.
3239 bool InternalLinkage = false;
3240 if (IsTailCall) {
3241 IsTailCall = isEligibleForTailCallOptimization(
3242 CCInfo, StackSize, *MF.getInfo<MipsFunctionInfo>());
3243 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3244 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3245 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3246 G->getGlobal()->hasPrivateLinkage() ||
3247 G->getGlobal()->hasHiddenVisibility() ||
3248 G->getGlobal()->hasProtectedVisibility());
3249 }
3250 }
3251 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
3252 report_fatal_error("failed to perform tail call elimination on a call "
3253 "site marked musttail");
3254
3255 if (IsTailCall)
3256 ++NumTailCalls;
3257
3258 // Chain is the output chain of the last Load/Store or CopyToReg node.
3259 // ByValChain is the output chain of the last Memcpy node created for copying
3260 // byval arguments to the stack.
3261 unsigned StackAlignment = TFL->getStackAlignment();
3262 StackSize = alignTo(StackSize, StackAlignment);
3263
3264 if (!(IsTailCall || MemcpyInByVal))
3265 Chain = DAG.getCALLSEQ_START(Chain, StackSize, 0, DL);
3266
3268 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3270
3271 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3272 SmallVector<SDValue, 8> MemOpChains;
3273
3274 CCInfo.rewindByValRegsInfo();
3275
3276 // Walk the register/memloc assignments, inserting copies/loads.
3277 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
3278 SDValue Arg = OutVals[OutIdx];
3279 CCValAssign &VA = ArgLocs[i];
3280 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3281 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3282 bool UseUpperBits = false;
3283
3284 // ByVal Arg.
3285 if (Flags.isByVal()) {
3286 unsigned FirstByValReg, LastByValReg;
3287 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3288 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3289
3290 assert(Flags.getByValSize() &&
3291 "ByVal args of size 0 should have been ignored by front-end.");
3292 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3293 assert(!IsTailCall &&
3294 "Do not tail-call optimize if there is a byval argument.");
3295 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3296 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3297 VA);
3298 CCInfo.nextInRegsParam();
3299 continue;
3300 }
3301
3302 // Promote the value if needed.
3303 switch (VA.getLocInfo()) {
3304 default:
3305 llvm_unreachable("Unknown loc info!");
3306 case CCValAssign::Full:
3307 if (VA.isRegLoc()) {
3308 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3309 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3310 (ValVT == MVT::i64 && LocVT == MVT::f64))
3311 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3312 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3314 Arg, DAG.getConstant(0, DL, MVT::i32));
3316 Arg, DAG.getConstant(1, DL, MVT::i32));
3317 if (!Subtarget.isLittle())
3318 std::swap(Lo, Hi);
3319
3320 assert(VA.needsCustom());
3321
3322 Register LocRegLo = VA.getLocReg();
3323 Register LocRegHigh = ArgLocs[++i].getLocReg();
3324 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3325 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3326 continue;
3327 }
3328 }
3329 break;
3330 case CCValAssign::BCvt:
3331 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3332 break;
3334 UseUpperBits = true;
3335 [[fallthrough]];
3336 case CCValAssign::SExt:
3337 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3338 break;
3340 UseUpperBits = true;
3341 [[fallthrough]];
3342 case CCValAssign::ZExt:
3343 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3344 break;
3346 UseUpperBits = true;
3347 [[fallthrough]];
3348 case CCValAssign::AExt:
3349 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3350 break;
3351 }
3352
3353 if (UseUpperBits) {
3354 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3355 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3356 Arg = DAG.getNode(
3357 ISD::SHL, DL, VA.getLocVT(), Arg,
3358 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3359 }
3360
3361 // Arguments that can be passed on register must be kept at
3362 // RegsToPass vector
3363 if (VA.isRegLoc()) {
3364 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3365
3366 // If the parameter is passed through reg $D, which splits into
3367 // two physical registers, avoid creating call site info.
3368 if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3369 continue;
3370
3371 // Collect CSInfo about which register passes which parameter.
3372 const TargetOptions &Options = DAG.getTarget().Options;
3373 if (Options.SupportsDebugEntryValues)
3374 CSInfo.emplace_back(VA.getLocReg(), i);
3375
3376 continue;
3377 }
3378
3379 // Register can't get to this point...
3380 assert(VA.isMemLoc());
3381
3382 // emit ISD::STORE whichs stores the
3383 // parameter value to a stack Location
3384 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3385 Chain, Arg, DL, IsTailCall, DAG));
3386 }
3387
3388 // Transform all store nodes into one single node because all store
3389 // nodes are independent of each other.
3390 if (!MemOpChains.empty())
3391 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3392
3393 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3394 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3395 // node so that legalize doesn't hack it.
3396
3397 EVT Ty = Callee.getValueType();
3398 bool GlobalOrExternal = false, IsCallReloc = false;
3399
3400 // The long-calls feature is ignored in case of PIC.
3401 // While we do not support -mshared / -mno-shared properly,
3402 // ignore long-calls in case of -mabicalls too.
3403 if (!Subtarget.isABICalls() && !IsPIC) {
3404 // If the function should be called using "long call",
3405 // get its address into a register to prevent using
3406 // of the `jal` instruction for the direct call.
3407 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3408 if (Subtarget.useLongCalls())
3410 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3411 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3412 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3413 bool UseLongCalls = Subtarget.useLongCalls();
3414 // If the function has long-call/far/near attribute
3415 // it overrides command line switch pased to the backend.
3416 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3417 if (F->hasFnAttribute("long-call"))
3418 UseLongCalls = true;
3419 else if (F->hasFnAttribute("short-call"))
3420 UseLongCalls = false;
3421 }
3422 if (UseLongCalls)
3424 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3425 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3426 }
3427 }
3428
3429 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3430 if (IsPIC) {
3431 const GlobalValue *Val = G->getGlobal();
3432 InternalLinkage = Val->hasInternalLinkage();
3433
3434 if (InternalLinkage)
3435 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3436 else if (Subtarget.useXGOT()) {
3438 MipsII::MO_CALL_LO16, Chain,
3439 FuncInfo->callPtrInfo(MF, Val));
3440 IsCallReloc = true;
3441 } else {
3442 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3443 FuncInfo->callPtrInfo(MF, Val));
3444 IsCallReloc = true;
3445 }
3446 } else
3447 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3448 getPointerTy(DAG.getDataLayout()), 0,
3450 GlobalOrExternal = true;
3451 }
3452 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3453 const char *Sym = S->getSymbol();
3454
3455 if (!IsPIC) // static
3458 else if (Subtarget.useXGOT()) {
3460 MipsII::MO_CALL_LO16, Chain,
3461 FuncInfo->callPtrInfo(MF, Sym));
3462 IsCallReloc = true;
3463 } else { // PIC
3464 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3465 FuncInfo->callPtrInfo(MF, Sym));
3466 IsCallReloc = true;
3467 }
3468
3469 GlobalOrExternal = true;
3470 }
3471
3472 SmallVector<SDValue, 8> Ops(1, Chain);
3473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3474
3475 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3476 IsCallReloc, CLI, Callee, Chain);
3477
3478 if (IsTailCall) {
3480 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3481 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3482 return Ret;
3483 }
3484
3485 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3486 SDValue InGlue = Chain.getValue(1);
3487
3488 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3489
3490 // Create the CALLSEQ_END node in the case of where it is not a call to
3491 // memcpy.
3492 if (!(MemcpyInByVal)) {
3493 Chain = DAG.getCALLSEQ_END(Chain, StackSize, 0, InGlue, DL);
3494 InGlue = Chain.getValue(1);
3495 }
3496
3497 // Handle result values, copying them out of physregs into vregs that we
3498 // return.
3499 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3500 InVals, CLI);
3501}
3502
3503/// LowerCallResult - Lower the result values of a call into the
3504/// appropriate copies out of appropriate physical registers.
3505SDValue MipsTargetLowering::LowerCallResult(
3506 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3507 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3510 // Assign locations to each value returned by this call.
3512 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3513 *DAG.getContext());
3514
3515 const ExternalSymbolSDNode *ES =
3516 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3517 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3518 ES ? ES->getSymbol() : nullptr);
3519
3520 // Copy all of the result registers out of their specified physreg.
3521 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3522 CCValAssign &VA = RVLocs[i];
3523 assert(VA.isRegLoc() && "Can only return in registers!");
3524
3525 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3526 RVLocs[i].getLocVT(), InGlue);
3527 Chain = Val.getValue(1);
3528 InGlue = Val.getValue(2);
3529
3530 if (VA.isUpperBitsInLoc()) {
3531 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3532 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3533 unsigned Shift =
3535 Val = DAG.getNode(
3536 Shift, DL, VA.getLocVT(), Val,
3537 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3538 }
3539
3540 switch (VA.getLocInfo()) {
3541 default:
3542 llvm_unreachable("Unknown loc info!");
3543 case CCValAssign::Full:
3544 break;
3545 case CCValAssign::BCvt:
3546 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3547 break;
3548 case CCValAssign::AExt:
3550 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3551 break;
3552 case CCValAssign::ZExt:
3554 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3555 DAG.getValueType(VA.getValVT()));
3556 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3557 break;
3558 case CCValAssign::SExt:
3560 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3561 DAG.getValueType(VA.getValVT()));
3562 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3563 break;
3564 }
3565
3566 InVals.push_back(Val);
3567 }
3568
3569 return Chain;
3570}
3571
3573 EVT ArgVT, const SDLoc &DL,
3574 SelectionDAG &DAG) {
3575 MVT LocVT = VA.getLocVT();
3576 EVT ValVT = VA.getValVT();
3577
3578 // Shift into the upper bits if necessary.
3579 switch (VA.getLocInfo()) {
3580 default:
3581 break;
3585 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3586 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3587 unsigned Opcode =
3589 Val = DAG.getNode(
3590 Opcode, DL, VA.getLocVT(), Val,
3591 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3592 break;
3593 }
3594 }
3595
3596 // If this is an value smaller than the argument slot size (32-bit for O32,
3597 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3598 // size. Extract the value and insert any appropriate assertions regarding
3599 // sign/zero extension.
3600 switch (VA.getLocInfo()) {
3601 default:
3602 llvm_unreachable("Unknown loc info!");
3603 case CCValAssign::Full:
3604 break;
3606 case CCValAssign::AExt:
3607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3608 break;
3610 case CCValAssign::SExt:
3611 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3612 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3613 break;
3615 case CCValAssign::ZExt:
3616 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3617 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3618 break;
3619 case CCValAssign::BCvt:
3620 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3621 break;
3622 }
3623
3624 return Val;
3625}
3626
3627//===----------------------------------------------------------------------===//
3628// Formal Arguments Calling Convention Implementation
3629//===----------------------------------------------------------------------===//
3630/// LowerFormalArguments - transform physical registers into virtual registers
3631/// and generate load operations for arguments places on the stack.
3632SDValue MipsTargetLowering::LowerFormalArguments(
3633 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3634 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3635 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3637 MachineFrameInfo &MFI = MF.getFrameInfo();
3639
3640 MipsFI->setVarArgsFrameIndex(0);
3641
3642 // Used with vargs to acumulate store chains.
3643 std::vector<SDValue> OutChains;
3644
3645 // Assign locations to all of the incoming arguments.
3647 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3648 *DAG.getContext());
3649 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3651 Function::const_arg_iterator FuncArg = Func.arg_begin();
3652
3653 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3655 "Functions with the interrupt attribute cannot have arguments!");
3656
3657 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3658 MipsFI->setFormalArgInfo(CCInfo.getStackSize(),
3659 CCInfo.getInRegsParamsCount() > 0);
3660
3661 unsigned CurArgIdx = 0;
3662 CCInfo.rewindByValRegsInfo();
3663
3664 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3665 CCValAssign &VA = ArgLocs[i];
3666 if (Ins[InsIdx].isOrigArg()) {
3667 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3668 CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3669 }
3670 EVT ValVT = VA.getValVT();
3671 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3672 bool IsRegLoc = VA.isRegLoc();
3673
3674 if (Flags.isByVal()) {
3675 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit");
3676 unsigned FirstByValReg, LastByValReg;
3677 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3678 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3679
3680 assert(Flags.getByValSize() &&
3681 "ByVal args of size 0 should have been ignored by front-end.");
3682 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3683 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3684 FirstByValReg, LastByValReg, VA, CCInfo);
3685 CCInfo.nextInRegsParam();
3686 continue;
3687 }
3688
3689 // Arguments stored on registers
3690 if (IsRegLoc) {
3691 MVT RegVT = VA.getLocVT();
3692 Register ArgReg = VA.getLocReg();
3693 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3694
3695 // Transform the arguments stored on
3696 // physical registers into virtual ones
3697 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3698 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3699
3700 ArgValue =
3701 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3702
3703 // Handle floating point arguments passed in integer registers and
3704 // long double arguments passed in floating point registers.
3705 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3706 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3707 (RegVT == MVT::f64 && ValVT == MVT::i64))
3708 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3709 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3710 ValVT == MVT::f64) {
3711 assert(VA.needsCustom() && "Expected custom argument for f64 split");
3712 CCValAssign &NextVA = ArgLocs[++i];
3713 unsigned Reg2 =
3714 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3715 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3716 if (!Subtarget.isLittle())
3717 std::swap(ArgValue, ArgValue2);
3718 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3719 ArgValue, ArgValue2);
3720 }
3721
3722 InVals.push_back(ArgValue);
3723 } else { // VA.isRegLoc()
3724 MVT LocVT = VA.getLocVT();
3725
3726 assert(!VA.needsCustom() && "unexpected custom memory argument");
3727
3728 // Only arguments pased on the stack should make it here.
3729 assert(VA.isMemLoc());
3730
3731 // The stack pointer offset is relative to the caller stack frame.
3732 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3733 VA.getLocMemOffset(), true);
3734
3735 // Create load nodes to retrieve arguments from the stack
3736 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3737 SDValue ArgValue = DAG.getLoad(
3738 LocVT, DL, Chain, FIN,
3740 OutChains.push_back(ArgValue.getValue(1));
3741
3742 ArgValue =
3743 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3744
3745 InVals.push_back(ArgValue);
3746 }
3747 }
3748
3749 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3750
3751 if (ArgLocs[i].needsCustom()) {
3752 ++i;
3753 continue;
3754 }
3755
3756 // The mips ABIs for returning structs by value requires that we copy
3757 // the sret argument into $v0 for the return. Save the argument into
3758 // a virtual register so that we can access it from the return points.
3759 if (Ins[InsIdx].Flags.isSRet()) {
3760 unsigned Reg = MipsFI->getSRetReturnReg();
3761 if (!Reg) {
3763 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3764 MipsFI->setSRetReturnReg(Reg);
3765 }
3766 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3767 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3768 break;
3769 }
3770 }
3771
3772 if (IsVarArg)
3773 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3774
3775 // All stores are grouped in one node to allow the matching between
3776 // the size of Ins and InVals. This only happens when on varg functions
3777 if (!OutChains.empty()) {
3778 OutChains.push_back(Chain);
3779 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3780 }
3781
3782 return Chain;
3783}
3784
3785//===----------------------------------------------------------------------===//
3786// Return Value Calling Convention Implementation
3787//===----------------------------------------------------------------------===//
3788
3789bool
3790MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3791 MachineFunction &MF, bool IsVarArg,
3793 LLVMContext &Context) const {
3795 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3796 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3797}
3798
3799bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type,
3800 bool IsSigned) const {
3801 if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3802 return true;
3803
3804 return IsSigned;
3805}
3806
3807SDValue
3808MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3809 const SDLoc &DL,
3810 SelectionDAG &DAG) const {
3813
3814 MipsFI->setISR();
3815
3816 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3817}
3818
3819SDValue
3820MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3821 bool IsVarArg,
3823 const SmallVectorImpl<SDValue> &OutVals,
3824 const SDLoc &DL, SelectionDAG &DAG) const {
3825 // CCValAssign - represent the assignment of
3826 // the return value to a location
3829
3830 // CCState - Info about the registers and stack slot.
3831 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3832
3833 // Analyze return values.
3834 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3835
3836 SDValue Glue;
3837 SmallVector<SDValue, 4> RetOps(1, Chain);
3838
3839 // Copy the result values into the output registers.
3840 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3841 SDValue Val = OutVals[i];
3842 CCValAssign &VA = RVLocs[i];
3843 assert(VA.isRegLoc() && "Can only return in registers!");
3844 bool UseUpperBits = false;
3845
3846 switch (VA.getLocInfo()) {
3847 default:
3848 llvm_unreachable("Unknown loc info!");
3849 case CCValAssign::Full:
3850 break;
3851 case CCValAssign::BCvt:
3852 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3853 break;
3855 UseUpperBits = true;
3856 [[fallthrough]];
3857 case CCValAssign::AExt:
3858 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3859 break;
3861 UseUpperBits = true;
3862 [[fallthrough]];
3863 case CCValAssign::ZExt:
3864 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3865 break;
3867 UseUpperBits = true;
3868 [[fallthrough]];
3869 case CCValAssign::SExt:
3870 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3871 break;
3872 }
3873
3874 if (UseUpperBits) {
3875 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3876 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3877 Val = DAG.getNode(
3878 ISD::SHL, DL, VA.getLocVT(), Val,
3879 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3880 }
3881
3882 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
3883
3884 // Guarantee that all emitted copies are stuck together with flags.
3885 Glue = Chain.getValue(1);
3886 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3887 }
3888
3889 // The mips ABIs for returning structs by value requires that we copy
3890 // the sret argument into $v0 for the return. We saved the argument into
3891 // a virtual register in the entry block, so now we copy the value out
3892 // and into $v0.
3893 if (MF.getFunction().hasStructRetAttr()) {
3895 unsigned Reg = MipsFI->getSRetReturnReg();
3896
3897 if (!Reg)
3898 llvm_unreachable("sret virtual register not created in the entry block");
3899 SDValue Val =
3900 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3901 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3902
3903 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Glue);
3904 Glue = Chain.getValue(1);
3905 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3906 }
3907
3908 RetOps[0] = Chain; // Update chain.
3909
3910 // Add the glue if we have it.
3911 if (Glue.getNode())
3912 RetOps.push_back(Glue);
3913
3914 // ISRs must use "eret".
3915 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3916 return LowerInterruptReturn(RetOps, DL, DAG);
3917
3918 // Standard return on Mips is a "jr $ra"
3919 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3920}
3921
3922//===----------------------------------------------------------------------===//
3923// Mips Inline Assembly Support
3924//===----------------------------------------------------------------------===//
3925
3926/// getConstraintType - Given a constraint letter, return the type of
3927/// constraint it is for this target.
3929MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3930 // Mips specific constraints
3931 // GCC config/mips/constraints.md
3932 //
3933 // 'd' : An address register. Equivalent to r
3934 // unless generating MIPS16 code.
3935 // 'y' : Equivalent to r; retained for
3936 // backwards compatibility.
3937 // 'c' : A register suitable for use in an indirect
3938 // jump. This will always be $25 for -mabicalls.
3939 // 'l' : The lo register. 1 word storage.
3940 // 'x' : The hilo register pair. Double word storage.
3941 if (Constraint.size() == 1) {
3942 switch (Constraint[0]) {
3943 default : break;
3944 case 'd':
3945 case 'y':
3946 case 'f':
3947 case 'c':
3948 case 'l':
3949 case 'x':
3950 return C_RegisterClass;
3951 case 'R':
3952 return C_Memory;
3953 }
3954 }
3955
3956 if (Constraint == "ZC")
3957 return C_Memory;
3958
3959 return TargetLowering::getConstraintType(Constraint);
3960}
3961
3962/// Examine constraint type and operand type and determine a weight value.
3963/// This object must already have been set up with the operand type
3964/// and the current alternative constraint selected.
3966MipsTargetLowering::getSingleConstraintMatchWeight(
3967 AsmOperandInfo &info, const char *constraint) const {
3969 Value *CallOperandVal = info.CallOperandVal;
3970 // If we don't have a value, we can't do a match,
3971 // but allow it at the lowest weight.
3972 if (!CallOperandVal)
3973 return CW_Default;
3974 Type *type = CallOperandVal->getType();
3975 // Look at the constraint type.
3976 switch (*constraint) {
3977 default:
3979 break;
3980 case 'd':
3981 case 'y':
3982 if (type->isIntegerTy())
3983 weight = CW_Register;
3984 break;
3985 case 'f': // FPU or MSA register
3986 if (Subtarget.hasMSA() && type->isVectorTy() &&
3987 type->getPrimitiveSizeInBits().getFixedValue() == 128)
3988 weight = CW_Register;
3989 else if (type->isFloatTy())
3990 weight = CW_Register;
3991 break;