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