1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "mips-lower"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 LargeGOT("mxgot", cl::Hidden,
47 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
50 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
51 cl::desc("MIPS: Don't trap on integer division by zero."),
55 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
56 cl::desc("Allow mips-fast-isel to be used"),
59 static const MCPhysReg O32IntRegs[4] = {
60 Mips::A0, Mips::A1, Mips::A2, Mips::A3
63 static const MCPhysReg Mips64IntRegs[8] = {
64 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
65 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
68 static const MCPhysReg Mips64DPRegs[8] = {
69 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
70 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
73 // If I is a shifted mask, set the size (Size) and the first bit of the
74 // mask (Pos), and return true.
75 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
76 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
77 if (!isShiftedMask_64(I))
80 Size = CountPopulation_64(I);
81 Pos = countTrailingZeros(I);
85 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
86 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
87 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
90 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
96 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
102 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
108 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
114 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
116 unsigned Flag) const {
117 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
118 N->getOffset(), Flag);
121 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
123 case MipsISD::JmpLink: return "MipsISD::JmpLink";
124 case MipsISD::TailCall: return "MipsISD::TailCall";
125 case MipsISD::Hi: return "MipsISD::Hi";
126 case MipsISD::Lo: return "MipsISD::Lo";
127 case MipsISD::GPRel: return "MipsISD::GPRel";
128 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
129 case MipsISD::Ret: return "MipsISD::Ret";
130 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
131 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
132 case MipsISD::FPCmp: return "MipsISD::FPCmp";
133 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
134 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
135 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
136 case MipsISD::MFHI: return "MipsISD::MFHI";
137 case MipsISD::MFLO: return "MipsISD::MFLO";
138 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
139 case MipsISD::Mult: return "MipsISD::Mult";
140 case MipsISD::Multu: return "MipsISD::Multu";
141 case MipsISD::MAdd: return "MipsISD::MAdd";
142 case MipsISD::MAddu: return "MipsISD::MAddu";
143 case MipsISD::MSub: return "MipsISD::MSub";
144 case MipsISD::MSubu: return "MipsISD::MSubu";
145 case MipsISD::DivRem: return "MipsISD::DivRem";
146 case MipsISD::DivRemU: return "MipsISD::DivRemU";
147 case MipsISD::DivRem16: return "MipsISD::DivRem16";
148 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
149 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
150 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
151 case MipsISD::Wrapper: return "MipsISD::Wrapper";
152 case MipsISD::Sync: return "MipsISD::Sync";
153 case MipsISD::Ext: return "MipsISD::Ext";
154 case MipsISD::Ins: return "MipsISD::Ins";
155 case MipsISD::LWL: return "MipsISD::LWL";
156 case MipsISD::LWR: return "MipsISD::LWR";
157 case MipsISD::SWL: return "MipsISD::SWL";
158 case MipsISD::SWR: return "MipsISD::SWR";
159 case MipsISD::LDL: return "MipsISD::LDL";
160 case MipsISD::LDR: return "MipsISD::LDR";
161 case MipsISD::SDL: return "MipsISD::SDL";
162 case MipsISD::SDR: return "MipsISD::SDR";
163 case MipsISD::EXTP: return "MipsISD::EXTP";
164 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
165 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
166 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
167 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
168 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
169 case MipsISD::SHILO: return "MipsISD::SHILO";
170 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
171 case MipsISD::MULT: return "MipsISD::MULT";
172 case MipsISD::MULTU: return "MipsISD::MULTU";
173 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
174 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
175 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
176 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
177 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
178 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
179 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
180 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
181 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
182 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
183 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
184 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
185 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
186 case MipsISD::VCEQ: return "MipsISD::VCEQ";
187 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
188 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
189 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
190 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
191 case MipsISD::VSMAX: return "MipsISD::VSMAX";
192 case MipsISD::VSMIN: return "MipsISD::VSMIN";
193 case MipsISD::VUMAX: return "MipsISD::VUMAX";
194 case MipsISD::VUMIN: return "MipsISD::VUMIN";
195 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
196 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
197 case MipsISD::VNOR: return "MipsISD::VNOR";
198 case MipsISD::VSHF: return "MipsISD::VSHF";
199 case MipsISD::SHF: return "MipsISD::SHF";
200 case MipsISD::ILVEV: return "MipsISD::ILVEV";
201 case MipsISD::ILVOD: return "MipsISD::ILVOD";
202 case MipsISD::ILVL: return "MipsISD::ILVL";
203 case MipsISD::ILVR: return "MipsISD::ILVR";
204 case MipsISD::PCKEV: return "MipsISD::PCKEV";
205 case MipsISD::PCKOD: return "MipsISD::PCKOD";
206 case MipsISD::INSVE: return "MipsISD::INSVE";
207 default: return nullptr;
211 MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM,
212 const MipsSubtarget &STI)
213 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
214 // Mips does not have i1 type, so use i32 for
215 // setcc operations results (slt, sgt, ...).
216 setBooleanContents(ZeroOrOneBooleanContent);
217 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
218 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
219 // does. Integer booleans still use 0 and 1.
220 if (Subtarget.hasMips32r6())
221 setBooleanContents(ZeroOrOneBooleanContent,
222 ZeroOrNegativeOneBooleanContent);
224 // Load extented operations for i1 types must be promoted
225 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
226 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
227 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
229 // MIPS doesn't have extending float->double load/store
230 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
231 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
233 // Used by legalize types to correctly generate the setcc result.
234 // Without this, every float setcc comes with a AND/OR with the result,
235 // we don't want this, since the fpcmp result goes to a flag register,
236 // which is used implicitly by brcond and select operations.
237 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
239 // Mips Custom Operations
240 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
241 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
242 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
243 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
244 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
245 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
246 setOperationAction(ISD::SELECT, MVT::f32, Custom);
247 setOperationAction(ISD::SELECT, MVT::f64, Custom);
248 setOperationAction(ISD::SELECT, MVT::i32, Custom);
249 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
250 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
251 setOperationAction(ISD::SETCC, MVT::f32, Custom);
252 setOperationAction(ISD::SETCC, MVT::f64, Custom);
253 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
254 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
255 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
256 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
258 if (Subtarget.isGP64bit()) {
259 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
260 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
261 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
262 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
263 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
264 setOperationAction(ISD::SELECT, MVT::i64, Custom);
265 setOperationAction(ISD::LOAD, MVT::i64, Custom);
266 setOperationAction(ISD::STORE, MVT::i64, Custom);
267 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
270 if (!Subtarget.isGP64bit()) {
271 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
276 setOperationAction(ISD::ADD, MVT::i32, Custom);
277 if (Subtarget.isGP64bit())
278 setOperationAction(ISD::ADD, MVT::i64, Custom);
280 setOperationAction(ISD::SDIV, MVT::i32, Expand);
281 setOperationAction(ISD::SREM, MVT::i32, Expand);
282 setOperationAction(ISD::UDIV, MVT::i32, Expand);
283 setOperationAction(ISD::UREM, MVT::i32, Expand);
284 setOperationAction(ISD::SDIV, MVT::i64, Expand);
285 setOperationAction(ISD::SREM, MVT::i64, Expand);
286 setOperationAction(ISD::UDIV, MVT::i64, Expand);
287 setOperationAction(ISD::UREM, MVT::i64, Expand);
289 // Operations not directly supported by Mips.
290 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
291 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
295 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
297 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
299 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
300 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
301 if (Subtarget.hasCnMips()) {
302 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
303 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
305 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
306 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
308 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
309 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
310 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
311 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
312 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
313 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
314 setOperationAction(ISD::ROTL, MVT::i32, Expand);
315 setOperationAction(ISD::ROTL, MVT::i64, Expand);
316 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
317 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
319 if (!Subtarget.hasMips32r2())
320 setOperationAction(ISD::ROTR, MVT::i32, Expand);
322 if (!Subtarget.hasMips64r2())
323 setOperationAction(ISD::ROTR, MVT::i64, Expand);
325 setOperationAction(ISD::FSIN, MVT::f32, Expand);
326 setOperationAction(ISD::FSIN, MVT::f64, Expand);
327 setOperationAction(ISD::FCOS, MVT::f32, Expand);
328 setOperationAction(ISD::FCOS, MVT::f64, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
330 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
331 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
332 setOperationAction(ISD::FPOW, MVT::f32, Expand);
333 setOperationAction(ISD::FPOW, MVT::f64, Expand);
334 setOperationAction(ISD::FLOG, MVT::f32, Expand);
335 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
336 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
337 setOperationAction(ISD::FEXP, MVT::f32, Expand);
338 setOperationAction(ISD::FMA, MVT::f32, Expand);
339 setOperationAction(ISD::FMA, MVT::f64, Expand);
340 setOperationAction(ISD::FREM, MVT::f32, Expand);
341 setOperationAction(ISD::FREM, MVT::f64, Expand);
343 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
345 setOperationAction(ISD::VASTART, MVT::Other, Custom);
346 setOperationAction(ISD::VAARG, MVT::Other, Custom);
347 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
348 setOperationAction(ISD::VAEND, MVT::Other, Expand);
350 // Use the default for now
351 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
352 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
355 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
356 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
357 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
359 setInsertFencesForAtomic(true);
361 if (!Subtarget.hasMips32r2()) {
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
363 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
366 // MIPS16 lacks MIPS32's clz and clo instructions.
367 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
368 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
369 if (!Subtarget.hasMips64())
370 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
372 if (!Subtarget.hasMips32r2())
373 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
374 if (!Subtarget.hasMips64r2())
375 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
377 if (Subtarget.isGP64bit()) {
378 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
379 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
380 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
381 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
384 setOperationAction(ISD::TRAP, MVT::Other, Legal);
386 setTargetDAGCombine(ISD::SDIVREM);
387 setTargetDAGCombine(ISD::UDIVREM);
388 setTargetDAGCombine(ISD::SELECT);
389 setTargetDAGCombine(ISD::AND);
390 setTargetDAGCombine(ISD::OR);
391 setTargetDAGCombine(ISD::ADD);
393 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
395 // The arguments on the stack are defined in terms of 4-byte slots on O32
396 // and 8-byte slots on N32/N64.
397 setMinStackArgumentAlignment(
398 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
400 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
403 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
404 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
406 MaxStoresPerMemcpy = 16;
408 isMicroMips = Subtarget.inMicroMipsMode();
411 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM,
412 const MipsSubtarget &STI) {
413 if (STI.inMips16Mode())
414 return llvm::createMips16TargetLowering(TM, STI);
416 return llvm::createMipsSETargetLowering(TM, STI);
419 // Create a fast isel object.
421 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
422 const TargetLibraryInfo *libInfo) const {
423 if (!EnableMipsFastISel)
424 return TargetLowering::createFastISel(funcInfo, libInfo);
425 return Mips::createFastISel(funcInfo, libInfo);
428 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
431 return VT.changeVectorElementTypeToInteger();
434 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
435 TargetLowering::DAGCombinerInfo &DCI,
436 const MipsSubtarget &Subtarget) {
437 if (DCI.isBeforeLegalizeOps())
440 EVT Ty = N->getValueType(0);
441 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
442 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
443 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
447 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
448 N->getOperand(0), N->getOperand(1));
449 SDValue InChain = DAG.getEntryNode();
450 SDValue InGlue = DivRem;
453 if (N->hasAnyUseOfValue(0)) {
454 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
456 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
457 InChain = CopyFromLo.getValue(1);
458 InGlue = CopyFromLo.getValue(2);
462 if (N->hasAnyUseOfValue(1)) {
463 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
465 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
471 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
473 default: llvm_unreachable("Unknown fp condition code!");
475 case ISD::SETOEQ: return Mips::FCOND_OEQ;
476 case ISD::SETUNE: return Mips::FCOND_UNE;
478 case ISD::SETOLT: return Mips::FCOND_OLT;
480 case ISD::SETOGT: return Mips::FCOND_OGT;
482 case ISD::SETOLE: return Mips::FCOND_OLE;
484 case ISD::SETOGE: return Mips::FCOND_OGE;
485 case ISD::SETULT: return Mips::FCOND_ULT;
486 case ISD::SETULE: return Mips::FCOND_ULE;
487 case ISD::SETUGT: return Mips::FCOND_UGT;
488 case ISD::SETUGE: return Mips::FCOND_UGE;
489 case ISD::SETUO: return Mips::FCOND_UN;
490 case ISD::SETO: return Mips::FCOND_OR;
492 case ISD::SETONE: return Mips::FCOND_ONE;
493 case ISD::SETUEQ: return Mips::FCOND_UEQ;
498 /// This function returns true if the floating point conditional branches and
499 /// conditional moves which use condition code CC should be inverted.
500 static bool invertFPCondCodeUser(Mips::CondCode CC) {
501 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
504 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
505 "Illegal Condition Code");
510 // Creates and returns an FPCmp node from a setcc node.
511 // Returns Op if setcc is not a floating point comparison.
512 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
513 // must be a SETCC node
514 if (Op.getOpcode() != ISD::SETCC)
517 SDValue LHS = Op.getOperand(0);
519 if (!LHS.getValueType().isFloatingPoint())
522 SDValue RHS = Op.getOperand(1);
525 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
526 // node if necessary.
527 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
529 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
530 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
533 // Creates and returns a CMovFPT/F node.
534 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
535 SDValue False, SDLoc DL) {
536 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
537 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
538 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
540 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
541 True.getValueType(), True, FCC0, False, Cond);
544 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
545 TargetLowering::DAGCombinerInfo &DCI,
546 const MipsSubtarget &Subtarget) {
547 if (DCI.isBeforeLegalizeOps())
550 SDValue SetCC = N->getOperand(0);
552 if ((SetCC.getOpcode() != ISD::SETCC) ||
553 !SetCC.getOperand(0).getValueType().isInteger())
556 SDValue False = N->getOperand(2);
557 EVT FalseTy = False.getValueType();
559 if (!FalseTy.isInteger())
562 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
564 // If the RHS (False) is 0, we swap the order of the operands
565 // of ISD::SELECT (obviously also inverting the condition) so that we can
566 // take advantage of conditional moves using the $0 register.
568 // return (a != 0) ? x : 0;
576 if (!FalseC->getZExtValue()) {
577 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
578 SDValue True = N->getOperand(1);
580 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
581 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
583 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
586 // If both operands are integer constants there's a possibility that we
587 // can do some interesting optimizations.
588 SDValue True = N->getOperand(1);
589 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
591 if (!TrueC || !True.getValueType().isInteger())
594 // We'll also ignore MVT::i64 operands as this optimizations proves
595 // to be ineffective because of the required sign extensions as the result
596 // of a SETCC operator is always MVT::i32 for non-vector types.
597 if (True.getValueType() == MVT::i64)
600 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
602 // 1) (a < x) ? y : y-1
604 // addiu $reg2, $reg1, y-1
606 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
608 // 2) (a < x) ? y-1 : y
610 // xor $reg1, $reg1, 1
611 // addiu $reg2, $reg1, y-1
613 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
614 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
615 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
616 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
619 // Couldn't optimize.
623 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
624 TargetLowering::DAGCombinerInfo &DCI,
625 const MipsSubtarget &Subtarget) {
626 // Pattern match EXT.
627 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
628 // => ext $dst, $src, size, pos
629 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
632 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
633 unsigned ShiftRightOpc = ShiftRight.getOpcode();
635 // Op's first operand must be a shift right.
636 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
639 // The second operand of the shift must be an immediate.
641 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
644 uint64_t Pos = CN->getZExtValue();
645 uint64_t SMPos, SMSize;
647 // Op's second operand must be a shifted mask.
648 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
649 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
652 // Return if the shifted mask does not start at bit 0 or the sum of its size
653 // and Pos exceeds the word's size.
654 EVT ValTy = N->getValueType(0);
655 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
658 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
659 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
660 DAG.getConstant(SMSize, MVT::i32));
663 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
664 TargetLowering::DAGCombinerInfo &DCI,
665 const MipsSubtarget &Subtarget) {
666 // Pattern match INS.
667 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
668 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
669 // => ins $dst, $src, size, pos, $src1
670 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
673 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
674 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
677 // See if Op's first operand matches (and $src1 , mask0).
678 if (And0.getOpcode() != ISD::AND)
681 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
682 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
685 // See if Op's second operand matches (and (shl $src, pos), mask1).
686 if (And1.getOpcode() != ISD::AND)
689 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
690 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
693 // The shift masks must have the same position and size.
694 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
697 SDValue Shl = And1.getOperand(0);
698 if (Shl.getOpcode() != ISD::SHL)
701 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
704 unsigned Shamt = CN->getZExtValue();
706 // Return if the shift amount and the first bit position of mask are not the
708 EVT ValTy = N->getValueType(0);
709 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
712 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
713 DAG.getConstant(SMPos0, MVT::i32),
714 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
717 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
718 TargetLowering::DAGCombinerInfo &DCI,
719 const MipsSubtarget &Subtarget) {
720 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
722 if (DCI.isBeforeLegalizeOps())
725 SDValue Add = N->getOperand(1);
727 if (Add.getOpcode() != ISD::ADD)
730 SDValue Lo = Add.getOperand(1);
732 if ((Lo.getOpcode() != MipsISD::Lo) ||
733 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
736 EVT ValTy = N->getValueType(0);
739 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
741 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
744 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
746 SelectionDAG &DAG = DCI.DAG;
747 unsigned Opc = N->getOpcode();
753 return performDivRemCombine(N, DAG, DCI, Subtarget);
755 return performSELECTCombine(N, DAG, DCI, Subtarget);
757 return performANDCombine(N, DAG, DCI, Subtarget);
759 return performORCombine(N, DAG, DCI, Subtarget);
761 return performADDCombine(N, DAG, DCI, Subtarget);
768 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
769 SmallVectorImpl<SDValue> &Results,
770 SelectionDAG &DAG) const {
771 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
773 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
774 Results.push_back(Res.getValue(I));
778 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
779 SmallVectorImpl<SDValue> &Results,
780 SelectionDAG &DAG) const {
781 return LowerOperationWrapper(N, Results, DAG);
784 SDValue MipsTargetLowering::
785 LowerOperation(SDValue Op, SelectionDAG &DAG) const
787 switch (Op.getOpcode())
789 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
790 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
791 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
792 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
793 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
794 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
795 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
796 case ISD::SELECT: return lowerSELECT(Op, DAG);
797 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
798 case ISD::SETCC: return lowerSETCC(Op, DAG);
799 case ISD::VASTART: return lowerVASTART(Op, DAG);
800 case ISD::VAARG: return lowerVAARG(Op, DAG);
801 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
802 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
803 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
804 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
805 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
806 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
807 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
808 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
809 case ISD::LOAD: return lowerLOAD(Op, DAG);
810 case ISD::STORE: return lowerSTORE(Op, DAG);
811 case ISD::ADD: return lowerADD(Op, DAG);
812 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
817 //===----------------------------------------------------------------------===//
818 // Lower helper functions
819 //===----------------------------------------------------------------------===//
821 // addLiveIn - This helper function adds the specified physical register to the
822 // MachineFunction as a live in value. It also creates a corresponding
823 // virtual register for it.
825 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
827 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
828 MF.getRegInfo().addLiveIn(PReg, VReg);
832 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
833 MachineBasicBlock &MBB,
834 const TargetInstrInfo &TII,
839 // Insert instruction "teq $divisor_reg, $zero, 7".
840 MachineBasicBlock::iterator I(MI);
841 MachineInstrBuilder MIB;
842 MachineOperand &Divisor = MI->getOperand(2);
843 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
844 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
845 .addReg(Mips::ZERO).addImm(7);
847 // Use the 32-bit sub-register if this is a 64-bit division.
849 MIB->getOperand(0).setSubReg(Mips::sub_32);
851 // Clear Divisor's kill flag.
852 Divisor.setIsKill(false);
854 // We would normally delete the original instruction here but in this case
855 // we only needed to inject an additional instruction rather than replace it.
861 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
862 MachineBasicBlock *BB) const {
863 switch (MI->getOpcode()) {
865 llvm_unreachable("Unexpected instr type to insert");
866 case Mips::ATOMIC_LOAD_ADD_I8:
867 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
868 case Mips::ATOMIC_LOAD_ADD_I16:
869 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
870 case Mips::ATOMIC_LOAD_ADD_I32:
871 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
872 case Mips::ATOMIC_LOAD_ADD_I64:
873 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
875 case Mips::ATOMIC_LOAD_AND_I8:
876 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
877 case Mips::ATOMIC_LOAD_AND_I16:
878 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
879 case Mips::ATOMIC_LOAD_AND_I32:
880 return emitAtomicBinary(MI, BB, 4, Mips::AND);
881 case Mips::ATOMIC_LOAD_AND_I64:
882 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
884 case Mips::ATOMIC_LOAD_OR_I8:
885 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
886 case Mips::ATOMIC_LOAD_OR_I16:
887 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
888 case Mips::ATOMIC_LOAD_OR_I32:
889 return emitAtomicBinary(MI, BB, 4, Mips::OR);
890 case Mips::ATOMIC_LOAD_OR_I64:
891 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
893 case Mips::ATOMIC_LOAD_XOR_I8:
894 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
895 case Mips::ATOMIC_LOAD_XOR_I16:
896 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
897 case Mips::ATOMIC_LOAD_XOR_I32:
898 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
899 case Mips::ATOMIC_LOAD_XOR_I64:
900 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
902 case Mips::ATOMIC_LOAD_NAND_I8:
903 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
904 case Mips::ATOMIC_LOAD_NAND_I16:
905 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
906 case Mips::ATOMIC_LOAD_NAND_I32:
907 return emitAtomicBinary(MI, BB, 4, 0, true);
908 case Mips::ATOMIC_LOAD_NAND_I64:
909 return emitAtomicBinary(MI, BB, 8, 0, true);
911 case Mips::ATOMIC_LOAD_SUB_I8:
912 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
913 case Mips::ATOMIC_LOAD_SUB_I16:
914 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
915 case Mips::ATOMIC_LOAD_SUB_I32:
916 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
917 case Mips::ATOMIC_LOAD_SUB_I64:
918 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
920 case Mips::ATOMIC_SWAP_I8:
921 return emitAtomicBinaryPartword(MI, BB, 1, 0);
922 case Mips::ATOMIC_SWAP_I16:
923 return emitAtomicBinaryPartword(MI, BB, 2, 0);
924 case Mips::ATOMIC_SWAP_I32:
925 return emitAtomicBinary(MI, BB, 4, 0);
926 case Mips::ATOMIC_SWAP_I64:
927 return emitAtomicBinary(MI, BB, 8, 0);
929 case Mips::ATOMIC_CMP_SWAP_I8:
930 return emitAtomicCmpSwapPartword(MI, BB, 1);
931 case Mips::ATOMIC_CMP_SWAP_I16:
932 return emitAtomicCmpSwapPartword(MI, BB, 2);
933 case Mips::ATOMIC_CMP_SWAP_I32:
934 return emitAtomicCmpSwap(MI, BB, 4);
935 case Mips::ATOMIC_CMP_SWAP_I64:
936 return emitAtomicCmpSwap(MI, BB, 8);
937 case Mips::PseudoSDIV:
938 case Mips::PseudoUDIV:
943 return insertDivByZeroTrap(
944 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
945 case Mips::PseudoDSDIV:
946 case Mips::PseudoDUDIV:
951 return insertDivByZeroTrap(
952 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
954 return emitSEL_D(MI, BB);
958 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
959 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
961 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
962 unsigned Size, unsigned BinOpcode,
964 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
966 MachineFunction *MF = BB->getParent();
967 MachineRegisterInfo &RegInfo = MF->getRegInfo();
968 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
969 const TargetInstrInfo *TII =
970 getTargetMachine().getSubtargetImpl()->getInstrInfo();
971 DebugLoc DL = MI->getDebugLoc();
972 unsigned LL, SC, AND, NOR, ZERO, BEQ;
979 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
980 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
987 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
988 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
991 ZERO = Mips::ZERO_64;
995 unsigned OldVal = MI->getOperand(0).getReg();
996 unsigned Ptr = MI->getOperand(1).getReg();
997 unsigned Incr = MI->getOperand(2).getReg();
999 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1000 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1001 unsigned Success = RegInfo.createVirtualRegister(RC);
1003 // insert new blocks after the current block
1004 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1005 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1006 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1007 MachineFunction::iterator It = BB;
1009 MF->insert(It, loopMBB);
1010 MF->insert(It, exitMBB);
1012 // Transfer the remainder of BB and its successor edges to exitMBB.
1013 exitMBB->splice(exitMBB->begin(), BB,
1014 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1015 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1019 // fallthrough --> loopMBB
1020 BB->addSuccessor(loopMBB);
1021 loopMBB->addSuccessor(loopMBB);
1022 loopMBB->addSuccessor(exitMBB);
1025 // ll oldval, 0(ptr)
1026 // <binop> storeval, oldval, incr
1027 // sc success, storeval, 0(ptr)
1028 // beq success, $0, loopMBB
1030 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1032 // and andres, oldval, incr
1033 // nor storeval, $0, andres
1034 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1035 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1036 } else if (BinOpcode) {
1037 // <binop> storeval, oldval, incr
1038 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1042 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1043 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1045 MI->eraseFromParent(); // The instruction is gone now.
1050 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1051 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1052 unsigned SrcReg) const {
1053 const TargetInstrInfo *TII =
1054 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1055 DebugLoc DL = MI->getDebugLoc();
1057 if (Subtarget.hasMips32r2() && Size == 1) {
1058 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1062 if (Subtarget.hasMips32r2() && Size == 2) {
1063 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1067 MachineFunction *MF = BB->getParent();
1068 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1069 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1070 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1073 int64_t ShiftImm = 32 - (Size * 8);
1075 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1076 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1081 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1082 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1084 assert((Size == 1 || Size == 2) &&
1085 "Unsupported size for EmitAtomicBinaryPartial.");
1087 MachineFunction *MF = BB->getParent();
1088 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1089 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1090 const TargetInstrInfo *TII =
1091 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1092 DebugLoc DL = MI->getDebugLoc();
1094 unsigned Dest = MI->getOperand(0).getReg();
1095 unsigned Ptr = MI->getOperand(1).getReg();
1096 unsigned Incr = MI->getOperand(2).getReg();
1098 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1099 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1100 unsigned Mask = RegInfo.createVirtualRegister(RC);
1101 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1102 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1103 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1104 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1105 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1106 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1107 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1108 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1109 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1110 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1111 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1112 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1113 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1114 unsigned Success = RegInfo.createVirtualRegister(RC);
1116 // insert new blocks after the current block
1117 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1118 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1119 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1120 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1121 MachineFunction::iterator It = BB;
1123 MF->insert(It, loopMBB);
1124 MF->insert(It, sinkMBB);
1125 MF->insert(It, exitMBB);
1127 // Transfer the remainder of BB and its successor edges to exitMBB.
1128 exitMBB->splice(exitMBB->begin(), BB,
1129 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1130 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1132 BB->addSuccessor(loopMBB);
1133 loopMBB->addSuccessor(loopMBB);
1134 loopMBB->addSuccessor(sinkMBB);
1135 sinkMBB->addSuccessor(exitMBB);
1138 // addiu masklsb2,$0,-4 # 0xfffffffc
1139 // and alignedaddr,ptr,masklsb2
1140 // andi ptrlsb2,ptr,3
1141 // sll shiftamt,ptrlsb2,3
1142 // ori maskupper,$0,255 # 0xff
1143 // sll mask,maskupper,shiftamt
1144 // nor mask2,$0,mask
1145 // sll incr2,incr,shiftamt
1147 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1148 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1149 .addReg(Mips::ZERO).addImm(-4);
1150 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1151 .addReg(Ptr).addReg(MaskLSB2);
1152 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1153 if (Subtarget.isLittle()) {
1154 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1156 unsigned Off = RegInfo.createVirtualRegister(RC);
1157 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1158 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1159 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1161 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1162 .addReg(Mips::ZERO).addImm(MaskImm);
1163 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1164 .addReg(MaskUpper).addReg(ShiftAmt);
1165 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1166 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1168 // atomic.load.binop
1170 // ll oldval,0(alignedaddr)
1171 // binop binopres,oldval,incr2
1172 // and newval,binopres,mask
1173 // and maskedoldval0,oldval,mask2
1174 // or storeval,maskedoldval0,newval
1175 // sc success,storeval,0(alignedaddr)
1176 // beq success,$0,loopMBB
1180 // ll oldval,0(alignedaddr)
1181 // and newval,incr2,mask
1182 // and maskedoldval0,oldval,mask2
1183 // or storeval,maskedoldval0,newval
1184 // sc success,storeval,0(alignedaddr)
1185 // beq success,$0,loopMBB
1188 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1190 // and andres, oldval, incr2
1191 // nor binopres, $0, andres
1192 // and newval, binopres, mask
1193 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1194 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1195 .addReg(Mips::ZERO).addReg(AndRes);
1196 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1197 } else if (BinOpcode) {
1198 // <binop> binopres, oldval, incr2
1199 // and newval, binopres, mask
1200 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1201 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1202 } else { // atomic.swap
1203 // and newval, incr2, mask
1204 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1207 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1208 .addReg(OldVal).addReg(Mask2);
1209 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1210 .addReg(MaskedOldVal0).addReg(NewVal);
1211 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1212 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1213 BuildMI(BB, DL, TII->get(Mips::BEQ))
1214 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1217 // and maskedoldval1,oldval,mask
1218 // srl srlres,maskedoldval1,shiftamt
1219 // sign_extend dest,srlres
1222 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1223 .addReg(OldVal).addReg(Mask);
1224 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1225 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1226 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1228 MI->eraseFromParent(); // The instruction is gone now.
1233 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1234 MachineBasicBlock *BB,
1235 unsigned Size) const {
1236 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1238 MachineFunction *MF = BB->getParent();
1239 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1240 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1241 const TargetInstrInfo *TII =
1242 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1243 DebugLoc DL = MI->getDebugLoc();
1244 unsigned LL, SC, ZERO, BNE, BEQ;
1247 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1248 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1255 ZERO = Mips::ZERO_64;
1260 unsigned Dest = MI->getOperand(0).getReg();
1261 unsigned Ptr = MI->getOperand(1).getReg();
1262 unsigned OldVal = MI->getOperand(2).getReg();
1263 unsigned NewVal = MI->getOperand(3).getReg();
1265 unsigned Success = RegInfo.createVirtualRegister(RC);
1267 // insert new blocks after the current block
1268 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1269 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1270 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1271 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1272 MachineFunction::iterator It = BB;
1274 MF->insert(It, loop1MBB);
1275 MF->insert(It, loop2MBB);
1276 MF->insert(It, exitMBB);
1278 // Transfer the remainder of BB and its successor edges to exitMBB.
1279 exitMBB->splice(exitMBB->begin(), BB,
1280 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1281 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1285 // fallthrough --> loop1MBB
1286 BB->addSuccessor(loop1MBB);
1287 loop1MBB->addSuccessor(exitMBB);
1288 loop1MBB->addSuccessor(loop2MBB);
1289 loop2MBB->addSuccessor(loop1MBB);
1290 loop2MBB->addSuccessor(exitMBB);
1294 // bne dest, oldval, exitMBB
1296 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1297 BuildMI(BB, DL, TII->get(BNE))
1298 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1301 // sc success, newval, 0(ptr)
1302 // beq success, $0, loop1MBB
1304 BuildMI(BB, DL, TII->get(SC), Success)
1305 .addReg(NewVal).addReg(Ptr).addImm(0);
1306 BuildMI(BB, DL, TII->get(BEQ))
1307 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1309 MI->eraseFromParent(); // The instruction is gone now.
1315 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1316 MachineBasicBlock *BB,
1317 unsigned Size) const {
1318 assert((Size == 1 || Size == 2) &&
1319 "Unsupported size for EmitAtomicCmpSwapPartial.");
1321 MachineFunction *MF = BB->getParent();
1322 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1323 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1324 const TargetInstrInfo *TII =
1325 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1326 DebugLoc DL = MI->getDebugLoc();
1328 unsigned Dest = MI->getOperand(0).getReg();
1329 unsigned Ptr = MI->getOperand(1).getReg();
1330 unsigned CmpVal = MI->getOperand(2).getReg();
1331 unsigned NewVal = MI->getOperand(3).getReg();
1333 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1334 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1335 unsigned Mask = RegInfo.createVirtualRegister(RC);
1336 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1337 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1338 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1339 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1340 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1341 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1342 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1343 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1344 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1345 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1346 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1347 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1348 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1349 unsigned Success = RegInfo.createVirtualRegister(RC);
1351 // insert new blocks after the current block
1352 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1353 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1354 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1355 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1356 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1357 MachineFunction::iterator It = BB;
1359 MF->insert(It, loop1MBB);
1360 MF->insert(It, loop2MBB);
1361 MF->insert(It, sinkMBB);
1362 MF->insert(It, exitMBB);
1364 // Transfer the remainder of BB and its successor edges to exitMBB.
1365 exitMBB->splice(exitMBB->begin(), BB,
1366 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1367 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1369 BB->addSuccessor(loop1MBB);
1370 loop1MBB->addSuccessor(sinkMBB);
1371 loop1MBB->addSuccessor(loop2MBB);
1372 loop2MBB->addSuccessor(loop1MBB);
1373 loop2MBB->addSuccessor(sinkMBB);
1374 sinkMBB->addSuccessor(exitMBB);
1376 // FIXME: computation of newval2 can be moved to loop2MBB.
1378 // addiu masklsb2,$0,-4 # 0xfffffffc
1379 // and alignedaddr,ptr,masklsb2
1380 // andi ptrlsb2,ptr,3
1381 // sll shiftamt,ptrlsb2,3
1382 // ori maskupper,$0,255 # 0xff
1383 // sll mask,maskupper,shiftamt
1384 // nor mask2,$0,mask
1385 // andi maskedcmpval,cmpval,255
1386 // sll shiftedcmpval,maskedcmpval,shiftamt
1387 // andi maskednewval,newval,255
1388 // sll shiftednewval,maskednewval,shiftamt
1389 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1390 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1391 .addReg(Mips::ZERO).addImm(-4);
1392 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1393 .addReg(Ptr).addReg(MaskLSB2);
1394 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1395 if (Subtarget.isLittle()) {
1396 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1398 unsigned Off = RegInfo.createVirtualRegister(RC);
1399 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1400 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1401 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1403 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1404 .addReg(Mips::ZERO).addImm(MaskImm);
1405 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1406 .addReg(MaskUpper).addReg(ShiftAmt);
1407 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1408 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1409 .addReg(CmpVal).addImm(MaskImm);
1410 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1411 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1412 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1413 .addReg(NewVal).addImm(MaskImm);
1414 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1415 .addReg(MaskedNewVal).addReg(ShiftAmt);
1418 // ll oldval,0(alginedaddr)
1419 // and maskedoldval0,oldval,mask
1420 // bne maskedoldval0,shiftedcmpval,sinkMBB
1422 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1423 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1424 .addReg(OldVal).addReg(Mask);
1425 BuildMI(BB, DL, TII->get(Mips::BNE))
1426 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1429 // and maskedoldval1,oldval,mask2
1430 // or storeval,maskedoldval1,shiftednewval
1431 // sc success,storeval,0(alignedaddr)
1432 // beq success,$0,loop1MBB
1434 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1435 .addReg(OldVal).addReg(Mask2);
1436 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1437 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1438 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1439 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1440 BuildMI(BB, DL, TII->get(Mips::BEQ))
1441 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1444 // srl srlres,maskedoldval0,shiftamt
1445 // sign_extend dest,srlres
1448 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1449 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1450 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1452 MI->eraseFromParent(); // The instruction is gone now.
1457 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1458 MachineBasicBlock *BB) const {
1459 MachineFunction *MF = BB->getParent();
1460 const TargetRegisterInfo *TRI =
1461 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1462 const TargetInstrInfo *TII =
1463 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1464 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1465 DebugLoc DL = MI->getDebugLoc();
1466 MachineBasicBlock::iterator II(MI);
1468 unsigned Fc = MI->getOperand(1).getReg();
1469 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1471 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1473 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1476 .addImm(Mips::sub_lo);
1478 // We don't erase the original instruction, we just replace the condition
1479 // register with the 64-bit super-register.
1480 MI->getOperand(1).setReg(Fc2);
1485 //===----------------------------------------------------------------------===//
1486 // Misc Lower Operation implementation
1487 //===----------------------------------------------------------------------===//
1488 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1489 SDValue Chain = Op.getOperand(0);
1490 SDValue Table = Op.getOperand(1);
1491 SDValue Index = Op.getOperand(2);
1493 EVT PTy = getPointerTy();
1494 unsigned EntrySize =
1495 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1497 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1498 DAG.getConstant(EntrySize, PTy));
1499 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1501 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1502 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1503 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1505 Chain = Addr.getValue(1);
1507 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1508 Subtarget.isABI_N64()) {
1509 // For PIC, the sequence is:
1510 // BRIND(load(Jumptable + index) + RelocBase)
1511 // RelocBase can be JumpTable, GOT or some sort of global base.
1512 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1513 getPICJumpTableRelocBase(Table, DAG));
1516 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1519 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1520 // The first operand is the chain, the second is the condition, the third is
1521 // the block to branch to if the condition is true.
1522 SDValue Chain = Op.getOperand(0);
1523 SDValue Dest = Op.getOperand(2);
1526 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1527 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1529 // Return if flag is not set by a floating point comparison.
1530 if (CondRes.getOpcode() != MipsISD::FPCmp)
1533 SDValue CCNode = CondRes.getOperand(2);
1535 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1536 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1537 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1538 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1539 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1540 FCC0, Dest, CondRes);
1543 SDValue MipsTargetLowering::
1544 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1546 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1547 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1549 // Return if flag is not set by a floating point comparison.
1550 if (Cond.getOpcode() != MipsISD::FPCmp)
1553 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1557 SDValue MipsTargetLowering::
1558 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1561 EVT Ty = Op.getOperand(0).getValueType();
1562 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1563 getSetCCResultType(*DAG.getContext(), Ty),
1564 Op.getOperand(0), Op.getOperand(1),
1567 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1571 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1572 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1573 SDValue Cond = createFPCmp(DAG, Op);
1575 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1576 "Floating point operand expected.");
1578 SDValue True = DAG.getConstant(1, MVT::i32);
1579 SDValue False = DAG.getConstant(0, MVT::i32);
1581 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1584 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1585 SelectionDAG &DAG) const {
1586 // FIXME there isn't actually debug info here
1588 EVT Ty = Op.getValueType();
1589 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1590 const GlobalValue *GV = N->getGlobal();
1592 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1593 !Subtarget.isABI_N64()) {
1594 const MipsTargetObjectFile &TLOF =
1595 (const MipsTargetObjectFile&)getObjFileLowering();
1597 // %gp_rel relocation
1598 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1599 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1601 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1602 DAG.getVTList(MVT::i32), GA);
1603 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1604 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1607 // %hi/%lo relocation
1608 return getAddrNonPIC(N, Ty, DAG);
1611 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1612 return getAddrLocal(N, Ty, DAG,
1613 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1616 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1617 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1618 MachinePointerInfo::getGOT());
1620 return getAddrGlobal(N, Ty, DAG,
1621 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1622 ? MipsII::MO_GOT_DISP
1624 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1627 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1628 SelectionDAG &DAG) const {
1629 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1630 EVT Ty = Op.getValueType();
1632 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1633 !Subtarget.isABI_N64())
1634 return getAddrNonPIC(N, Ty, DAG);
1636 return getAddrLocal(N, Ty, DAG,
1637 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1640 SDValue MipsTargetLowering::
1641 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1643 // If the relocation model is PIC, use the General Dynamic TLS Model or
1644 // Local Dynamic TLS model, otherwise use the Initial Exec or
1645 // Local Exec TLS Model.
1647 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1649 const GlobalValue *GV = GA->getGlobal();
1650 EVT PtrVT = getPointerTy();
1652 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1654 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1655 // General Dynamic and Local Dynamic TLS Model.
1656 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1659 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1660 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1661 getGlobalReg(DAG, PtrVT), TGA);
1662 unsigned PtrSize = PtrVT.getSizeInBits();
1663 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1665 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1669 Entry.Node = Argument;
1671 Args.push_back(Entry);
1673 TargetLowering::CallLoweringInfo CLI(DAG);
1674 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1675 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1676 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1678 SDValue Ret = CallResult.first;
1680 if (model != TLSModel::LocalDynamic)
1683 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1684 MipsII::MO_DTPREL_HI);
1685 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1686 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1687 MipsII::MO_DTPREL_LO);
1688 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1689 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1690 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1694 if (model == TLSModel::InitialExec) {
1695 // Initial Exec TLS Model
1696 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1697 MipsII::MO_GOTTPREL);
1698 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1700 Offset = DAG.getLoad(PtrVT, DL,
1701 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1702 false, false, false, 0);
1704 // Local Exec TLS Model
1705 assert(model == TLSModel::LocalExec);
1706 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1707 MipsII::MO_TPREL_HI);
1708 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1709 MipsII::MO_TPREL_LO);
1710 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1711 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1712 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1715 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1716 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1719 SDValue MipsTargetLowering::
1720 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1722 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1723 EVT Ty = Op.getValueType();
1725 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1726 !Subtarget.isABI_N64())
1727 return getAddrNonPIC(N, Ty, DAG);
1729 return getAddrLocal(N, Ty, DAG,
1730 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1733 SDValue MipsTargetLowering::
1734 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1736 // gp_rel relocation
1737 // FIXME: we should reference the constant pool using small data sections,
1738 // but the asm printer currently doesn't support this feature without
1739 // hacking it. This feature should come soon so we can uncomment the
1741 //if (IsInSmallSection(C->getType())) {
1742 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1743 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1744 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1745 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1746 EVT Ty = Op.getValueType();
1748 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1749 !Subtarget.isABI_N64())
1750 return getAddrNonPIC(N, Ty, DAG);
1752 return getAddrLocal(N, Ty, DAG,
1753 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1756 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1757 MachineFunction &MF = DAG.getMachineFunction();
1758 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1761 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1764 // vastart just stores the address of the VarArgsFrameIndex slot into the
1765 // memory location argument.
1766 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1767 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1768 MachinePointerInfo(SV), false, false, 0);
1771 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1772 SDNode *Node = Op.getNode();
1773 EVT VT = Node->getValueType(0);
1774 SDValue Chain = Node->getOperand(0);
1775 SDValue VAListPtr = Node->getOperand(1);
1776 unsigned Align = Node->getConstantOperandVal(3);
1777 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1779 unsigned ArgSlotSizeInBytes =
1780 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1782 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1783 MachinePointerInfo(SV), false, false, false,
1785 SDValue VAList = VAListLoad;
1787 // Re-align the pointer if necessary.
1788 // It should only ever be necessary for 64-bit types on O32 since the minimum
1789 // argument alignment is the same as the maximum type alignment for N32/N64.
1791 // FIXME: We currently align too often. The code generator doesn't notice
1792 // when the pointer is still aligned from the last va_arg (or pair of
1793 // va_args for the i64 on O32 case).
1794 if (Align > getMinStackArgumentAlignment()) {
1795 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1797 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1798 DAG.getConstant(Align - 1,
1799 VAList.getValueType()));
1801 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1802 DAG.getConstant(-(int64_t)Align,
1803 VAList.getValueType()));
1806 // Increment the pointer, VAList, to the next vaarg.
1807 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1808 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1809 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1810 VAList.getValueType()));
1811 // Store the incremented VAList to the legalized pointer
1812 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1813 MachinePointerInfo(SV), false, false, 0);
1815 // In big-endian mode we must adjust the pointer when the load size is smaller
1816 // than the argument slot size. We must also reduce the known alignment to
1817 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1818 // the correct half of the slot, and reduce the alignment from 8 (slot
1819 // alignment) down to 4 (type alignment).
1820 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1821 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1822 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1823 DAG.getIntPtrConstant(Adjustment));
1825 // Load the actual argument out of the pointer VAList
1826 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1830 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1831 bool HasExtractInsert) {
1832 EVT TyX = Op.getOperand(0).getValueType();
1833 EVT TyY = Op.getOperand(1).getValueType();
1834 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1835 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1839 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1841 SDValue X = (TyX == MVT::f32) ?
1842 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1843 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1845 SDValue Y = (TyY == MVT::f32) ?
1846 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1847 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1850 if (HasExtractInsert) {
1851 // ext E, Y, 31, 1 ; extract bit31 of Y
1852 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1853 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1854 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1857 // srl SrlX, SllX, 1
1859 // sll SllY, SrlX, 31
1860 // or Or, SrlX, SllY
1861 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1862 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1863 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1864 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1865 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1868 if (TyX == MVT::f32)
1869 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1871 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1872 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1873 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1876 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1877 bool HasExtractInsert) {
1878 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1879 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1880 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1881 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1884 // Bitcast to integer nodes.
1885 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1886 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1888 if (HasExtractInsert) {
1889 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1890 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1891 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1892 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1894 if (WidthX > WidthY)
1895 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1896 else if (WidthY > WidthX)
1897 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1899 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1900 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1901 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1904 // (d)sll SllX, X, 1
1905 // (d)srl SrlX, SllX, 1
1906 // (d)srl SrlY, Y, width(Y)-1
1907 // (d)sll SllY, SrlX, width(Y)-1
1908 // or Or, SrlX, SllY
1909 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1910 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1911 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1912 DAG.getConstant(WidthY - 1, MVT::i32));
1914 if (WidthX > WidthY)
1915 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1916 else if (WidthY > WidthX)
1917 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1919 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1920 DAG.getConstant(WidthX - 1, MVT::i32));
1921 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1922 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1926 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1927 if (Subtarget.isGP64bit())
1928 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1930 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1933 SDValue MipsTargetLowering::
1934 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1936 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1937 "Frame address can only be determined for current frame.");
1939 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1940 MFI->setFrameAddressIsTaken(true);
1941 EVT VT = Op.getValueType();
1944 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1945 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
1949 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1950 SelectionDAG &DAG) const {
1951 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1955 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1956 "Return address can be determined only for current frame.");
1958 MachineFunction &MF = DAG.getMachineFunction();
1959 MachineFrameInfo *MFI = MF.getFrameInfo();
1960 MVT VT = Op.getSimpleValueType();
1961 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
1962 MFI->setReturnAddressIsTaken(true);
1964 // Return RA, which contains the return address. Mark it an implicit live-in.
1965 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1966 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1969 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1970 // generated from __builtin_eh_return (offset, handler)
1971 // The effect of this is to adjust the stack pointer by "offset"
1972 // and then branch to "handler".
1973 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1975 MachineFunction &MF = DAG.getMachineFunction();
1976 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1978 MipsFI->setCallsEhReturn();
1979 SDValue Chain = Op.getOperand(0);
1980 SDValue Offset = Op.getOperand(1);
1981 SDValue Handler = Op.getOperand(2);
1983 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
1985 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1986 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1987 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
1988 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
1989 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1990 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1991 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1992 DAG.getRegister(OffsetReg, Ty),
1993 DAG.getRegister(AddrReg, getPointerTy()),
1997 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1998 SelectionDAG &DAG) const {
1999 // FIXME: Need pseudo-fence for 'singlethread' fences
2000 // FIXME: Set SType for weaker fences where supported/appropriate.
2003 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2004 DAG.getConstant(SType, MVT::i32));
2007 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2008 SelectionDAG &DAG) const {
2010 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2011 SDValue Shamt = Op.getOperand(2);
2014 // lo = (shl lo, shamt)
2015 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2018 // hi = (shl lo, shamt[4:0])
2019 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2020 DAG.getConstant(-1, MVT::i32));
2021 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2022 DAG.getConstant(1, MVT::i32));
2023 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2025 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2026 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2027 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2028 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2029 DAG.getConstant(0x20, MVT::i32));
2030 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2031 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2032 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2034 SDValue Ops[2] = {Lo, Hi};
2035 return DAG.getMergeValues(Ops, DL);
2038 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2041 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2042 SDValue Shamt = Op.getOperand(2);
2045 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2047 // hi = (sra hi, shamt)
2049 // hi = (srl hi, shamt)
2052 // lo = (sra hi, shamt[4:0])
2053 // hi = (sra hi, 31)
2055 // lo = (srl hi, shamt[4:0])
2057 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2058 DAG.getConstant(-1, MVT::i32));
2059 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2060 DAG.getConstant(1, MVT::i32));
2061 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2062 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2063 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2064 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2066 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2067 DAG.getConstant(0x20, MVT::i32));
2068 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2069 DAG.getConstant(31, MVT::i32));
2070 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2071 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2072 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2075 SDValue Ops[2] = {Lo, Hi};
2076 return DAG.getMergeValues(Ops, DL);
2079 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2080 SDValue Chain, SDValue Src, unsigned Offset) {
2081 SDValue Ptr = LD->getBasePtr();
2082 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2083 EVT BasePtrVT = Ptr.getValueType();
2085 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2088 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2089 DAG.getConstant(Offset, BasePtrVT));
2091 SDValue Ops[] = { Chain, Ptr, Src };
2092 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2093 LD->getMemOperand());
2096 // Expand an unaligned 32 or 64-bit integer load node.
2097 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2098 LoadSDNode *LD = cast<LoadSDNode>(Op);
2099 EVT MemVT = LD->getMemoryVT();
2101 if (Subtarget.systemSupportsUnalignedAccess())
2104 // Return if load is aligned or if MemVT is neither i32 nor i64.
2105 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2106 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2109 bool IsLittle = Subtarget.isLittle();
2110 EVT VT = Op.getValueType();
2111 ISD::LoadExtType ExtType = LD->getExtensionType();
2112 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2114 assert((VT == MVT::i32) || (VT == MVT::i64));
2117 // (set dst, (i64 (load baseptr)))
2119 // (set tmp, (ldl (add baseptr, 7), undef))
2120 // (set dst, (ldr baseptr, tmp))
2121 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2122 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2124 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2128 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2130 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2134 // (set dst, (i32 (load baseptr))) or
2135 // (set dst, (i64 (sextload baseptr))) or
2136 // (set dst, (i64 (extload baseptr)))
2138 // (set tmp, (lwl (add baseptr, 3), undef))
2139 // (set dst, (lwr baseptr, tmp))
2140 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2141 (ExtType == ISD::EXTLOAD))
2144 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2147 // (set dst, (i64 (zextload baseptr)))
2149 // (set tmp0, (lwl (add baseptr, 3), undef))
2150 // (set tmp1, (lwr baseptr, tmp0))
2151 // (set tmp2, (shl tmp1, 32))
2152 // (set dst, (srl tmp2, 32))
2154 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2155 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2156 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2157 SDValue Ops[] = { SRL, LWR.getValue(1) };
2158 return DAG.getMergeValues(Ops, DL);
2161 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2162 SDValue Chain, unsigned Offset) {
2163 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2164 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2166 SDVTList VTList = DAG.getVTList(MVT::Other);
2169 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2170 DAG.getConstant(Offset, BasePtrVT));
2172 SDValue Ops[] = { Chain, Value, Ptr };
2173 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2174 SD->getMemOperand());
2177 // Expand an unaligned 32 or 64-bit integer store node.
2178 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2180 SDValue Value = SD->getValue(), Chain = SD->getChain();
2181 EVT VT = Value.getValueType();
2184 // (store val, baseptr) or
2185 // (truncstore val, baseptr)
2187 // (swl val, (add baseptr, 3))
2188 // (swr val, baseptr)
2189 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2190 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2192 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2195 assert(VT == MVT::i64);
2198 // (store val, baseptr)
2200 // (sdl val, (add baseptr, 7))
2201 // (sdr val, baseptr)
2202 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2203 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2206 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2207 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2208 SDValue Val = SD->getValue();
2210 if (Val.getOpcode() != ISD::FP_TO_SINT)
2213 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2214 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2217 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2218 SD->getPointerInfo(), SD->isVolatile(),
2219 SD->isNonTemporal(), SD->getAlignment());
2222 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2223 StoreSDNode *SD = cast<StoreSDNode>(Op);
2224 EVT MemVT = SD->getMemoryVT();
2226 // Lower unaligned integer stores.
2227 if (!Subtarget.systemSupportsUnalignedAccess() &&
2228 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2229 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2230 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2232 return lowerFP_TO_SINT_STORE(SD, DAG);
2235 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2236 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2237 || cast<ConstantSDNode>
2238 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2239 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2243 // (add (frameaddr 0), (frame_to_args_offset))
2244 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2245 // (add FrameObject, 0)
2246 // where FrameObject is a fixed StackObject with offset 0 which points to
2247 // the old stack pointer.
2248 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2249 EVT ValTy = Op->getValueType(0);
2250 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2251 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2252 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2253 DAG.getConstant(0, ValTy));
2256 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2257 SelectionDAG &DAG) const {
2258 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2259 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2261 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2264 //===----------------------------------------------------------------------===//
2265 // Calling Convention Implementation
2266 //===----------------------------------------------------------------------===//
2268 //===----------------------------------------------------------------------===//
2269 // TODO: Implement a generic logic using tblgen that can support this.
2270 // Mips O32 ABI rules:
2272 // i32 - Passed in A0, A1, A2, A3 and stack
2273 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2274 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2275 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2276 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2277 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2280 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2281 //===----------------------------------------------------------------------===//
2283 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2284 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2285 CCState &State, const MCPhysReg *F64Regs) {
2287 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2289 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2290 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2292 // Do not process byval args here.
2293 if (ArgFlags.isByVal())
2296 // Promote i8 and i16
2297 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2299 if (ArgFlags.isSExt())
2300 LocInfo = CCValAssign::SExt;
2301 else if (ArgFlags.isZExt())
2302 LocInfo = CCValAssign::ZExt;
2304 LocInfo = CCValAssign::AExt;
2309 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2310 // is true: function is vararg, argument is 3rd or higher, there is previous
2311 // argument which is not f32 or f64.
2312 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2313 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2314 unsigned OrigAlign = ArgFlags.getOrigAlign();
2315 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2317 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2318 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2319 // If this is the first part of an i64 arg,
2320 // the allocated register must be either A0 or A2.
2321 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2322 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2324 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2325 // Allocate int register and shadow next int register. If first
2326 // available register is Mips::A1 or Mips::A3, shadow it too.
2327 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2328 if (Reg == Mips::A1 || Reg == Mips::A3)
2329 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2330 State.AllocateReg(IntRegs, IntRegsSize);
2332 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2333 // we are guaranteed to find an available float register
2334 if (ValVT == MVT::f32) {
2335 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2336 // Shadow int register
2337 State.AllocateReg(IntRegs, IntRegsSize);
2339 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2340 // Shadow int registers
2341 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2342 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2343 State.AllocateReg(IntRegs, IntRegsSize);
2344 State.AllocateReg(IntRegs, IntRegsSize);
2347 llvm_unreachable("Cannot handle this ValVT.");
2350 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2352 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2354 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2359 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2360 MVT LocVT, CCValAssign::LocInfo LocInfo,
2361 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2362 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2364 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2367 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2368 MVT LocVT, CCValAssign::LocInfo LocInfo,
2369 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2370 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2372 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2375 #include "MipsGenCallingConv.inc"
2377 //===----------------------------------------------------------------------===//
2378 // Call Calling Convention Implementation
2379 //===----------------------------------------------------------------------===//
2381 // Return next O32 integer argument register.
2382 static unsigned getNextIntArgReg(unsigned Reg) {
2383 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2384 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2388 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2389 SDValue Chain, SDValue Arg, SDLoc DL,
2390 bool IsTailCall, SelectionDAG &DAG) const {
2392 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2393 DAG.getIntPtrConstant(Offset));
2394 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2398 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2399 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2400 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2401 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2402 /*isVolatile=*/ true, false, 0);
2405 void MipsTargetLowering::
2406 getOpndList(SmallVectorImpl<SDValue> &Ops,
2407 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2408 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2409 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2410 // Insert node "GP copy globalreg" before call to function.
2412 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2413 // in PIC mode) allow symbols to be resolved via lazy binding.
2414 // The lazy binding stub requires GP to point to the GOT.
2415 if (IsPICCall && !InternalLinkage) {
2416 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2417 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2418 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2421 // Build a sequence of copy-to-reg nodes chained together with token
2422 // chain and flag operands which copy the outgoing args into registers.
2423 // The InFlag in necessary since all emitted instructions must be
2427 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2428 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2429 RegsToPass[i].second, InFlag);
2430 InFlag = Chain.getValue(1);
2433 // Add argument registers to the end of the list so that they are
2434 // known live into the call.
2435 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2436 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2437 RegsToPass[i].second.getValueType()));
2439 // Add a register mask operand representing the call-preserved registers.
2440 const TargetRegisterInfo *TRI =
2441 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2442 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2443 assert(Mask && "Missing call preserved mask for calling convention");
2444 if (Subtarget.inMips16HardFloat()) {
2445 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2446 llvm::StringRef Sym = G->getGlobal()->getName();
2447 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2448 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2449 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2453 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2455 if (InFlag.getNode())
2456 Ops.push_back(InFlag);
2459 /// LowerCall - functions arguments are copied from virtual regs to
2460 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2462 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2463 SmallVectorImpl<SDValue> &InVals) const {
2464 SelectionDAG &DAG = CLI.DAG;
2466 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2467 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2468 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2469 SDValue Chain = CLI.Chain;
2470 SDValue Callee = CLI.Callee;
2471 bool &IsTailCall = CLI.IsTailCall;
2472 CallingConv::ID CallConv = CLI.CallConv;
2473 bool IsVarArg = CLI.IsVarArg;
2475 MachineFunction &MF = DAG.getMachineFunction();
2476 MachineFrameInfo *MFI = MF.getFrameInfo();
2477 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2478 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2479 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2481 // Analyze operands of the call, assigning locations to each operand.
2482 SmallVector<CCValAssign, 16> ArgLocs;
2483 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2484 getTargetMachine(), ArgLocs, *DAG.getContext());
2485 MipsCC::SpecialCallingConvType SpecialCallingConv =
2486 getSpecialCallingConv(Callee);
2487 MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
2488 CCInfo, SpecialCallingConv);
2490 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2491 Subtarget.abiUsesSoftFloat(),
2492 Callee.getNode(), CLI.getArgs());
2494 // Get a count of how many bytes are to be pushed on the stack.
2495 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2497 // Check if it's really possible to do a tail call.
2500 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2501 *MF.getInfo<MipsFunctionInfo>());
2503 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2504 report_fatal_error("failed to perform tail call elimination on a call "
2505 "site marked musttail");
2510 // Chain is the output chain of the last Load/Store or CopyToReg node.
2511 // ByValChain is the output chain of the last Memcpy node created for copying
2512 // byval arguments to the stack.
2513 unsigned StackAlignment = TFL->getStackAlignment();
2514 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2515 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2518 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2520 SDValue StackPtr = DAG.getCopyFromReg(
2521 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2524 // With EABI is it possible to have 16 args on registers.
2525 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2526 SmallVector<SDValue, 8> MemOpChains;
2527 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2529 // Walk the register/memloc assignments, inserting copies/loads.
2530 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2531 SDValue Arg = OutVals[i];
2532 CCValAssign &VA = ArgLocs[i];
2533 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2534 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2537 if (Flags.isByVal()) {
2538 assert(Flags.getByValSize() &&
2539 "ByVal args of size 0 should have been ignored by front-end.");
2540 assert(ByValArg != MipsCCInfo.byval_end());
2541 assert(!IsTailCall &&
2542 "Do not tail-call optimize if there is a byval argument.");
2543 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2544 MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
2549 // Promote the value if needed.
2550 switch (VA.getLocInfo()) {
2551 default: llvm_unreachable("Unknown loc info!");
2552 case CCValAssign::Full:
2553 if (VA.isRegLoc()) {
2554 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2555 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2556 (ValVT == MVT::i64 && LocVT == MVT::f64))
2557 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2558 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2559 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2560 Arg, DAG.getConstant(0, MVT::i32));
2561 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2562 Arg, DAG.getConstant(1, MVT::i32));
2563 if (!Subtarget.isLittle())
2565 unsigned LocRegLo = VA.getLocReg();
2566 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2567 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2568 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2573 case CCValAssign::SExt:
2574 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2576 case CCValAssign::ZExt:
2577 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2579 case CCValAssign::AExt:
2580 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2584 // Arguments that can be passed on register must be kept at
2585 // RegsToPass vector
2586 if (VA.isRegLoc()) {
2587 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2591 // Register can't get to this point...
2592 assert(VA.isMemLoc());
2594 // emit ISD::STORE whichs stores the
2595 // parameter value to a stack Location
2596 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2597 Chain, Arg, DL, IsTailCall, DAG));
2600 // Transform all store nodes into one single node because all store
2601 // nodes are independent of each other.
2602 if (!MemOpChains.empty())
2603 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2605 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2606 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2607 // node so that legalize doesn't hack it.
2609 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2611 bool GlobalOrExternal = false, InternalLinkage = false;
2613 EVT Ty = Callee.getValueType();
2615 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2617 const GlobalValue *Val = G->getGlobal();
2618 InternalLinkage = Val->hasInternalLinkage();
2620 if (InternalLinkage)
2621 Callee = getAddrLocal(G, Ty, DAG,
2622 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2624 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2625 MipsII::MO_CALL_LO16, Chain,
2626 FuncInfo->callPtrInfo(Val));
2628 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2629 FuncInfo->callPtrInfo(Val));
2631 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2632 MipsII::MO_NO_FLAG);
2633 GlobalOrExternal = true;
2635 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2636 const char *Sym = S->getSymbol();
2638 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2639 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2640 MipsII::MO_NO_FLAG);
2642 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2643 MipsII::MO_CALL_LO16, Chain,
2644 FuncInfo->callPtrInfo(Sym));
2646 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2647 FuncInfo->callPtrInfo(Sym));
2649 GlobalOrExternal = true;
2652 SmallVector<SDValue, 8> Ops(1, Chain);
2653 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2655 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2656 CLI, Callee, Chain);
2659 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2661 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2662 SDValue InFlag = Chain.getValue(1);
2664 // Create the CALLSEQ_END node.
2665 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2666 DAG.getIntPtrConstant(0, true), InFlag, DL);
2667 InFlag = Chain.getValue(1);
2669 // Handle result values, copying them out of physregs into vregs that we
2671 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2672 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2675 /// LowerCallResult - Lower the result values of a call into the
2676 /// appropriate copies out of appropriate physical registers.
2678 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2679 CallingConv::ID CallConv, bool IsVarArg,
2680 const SmallVectorImpl<ISD::InputArg> &Ins,
2681 SDLoc DL, SelectionDAG &DAG,
2682 SmallVectorImpl<SDValue> &InVals,
2683 const SDNode *CallNode,
2684 const Type *RetTy) const {
2685 // Assign locations to each value returned by this call.
2686 SmallVector<CCValAssign, 16> RVLocs;
2687 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2688 getTargetMachine(), RVLocs, *DAG.getContext());
2689 MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
2692 MipsCCInfo.analyzeCallResult(Ins, Subtarget.abiUsesSoftFloat(),
2695 // Copy all of the result registers out of their specified physreg.
2696 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2697 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2698 RVLocs[i].getLocVT(), InFlag);
2699 Chain = Val.getValue(1);
2700 InFlag = Val.getValue(2);
2702 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2703 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2705 InVals.push_back(Val);
2711 //===----------------------------------------------------------------------===//
2712 // Formal Arguments Calling Convention Implementation
2713 //===----------------------------------------------------------------------===//
2714 /// LowerFormalArguments - transform physical registers into virtual registers
2715 /// and generate load operations for arguments places on the stack.
2717 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2718 CallingConv::ID CallConv,
2720 const SmallVectorImpl<ISD::InputArg> &Ins,
2721 SDLoc DL, SelectionDAG &DAG,
2722 SmallVectorImpl<SDValue> &InVals)
2724 MachineFunction &MF = DAG.getMachineFunction();
2725 MachineFrameInfo *MFI = MF.getFrameInfo();
2726 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2728 MipsFI->setVarArgsFrameIndex(0);
2730 // Used with vargs to acumulate store chains.
2731 std::vector<SDValue> OutChains;
2733 // Assign locations to all of the incoming arguments.
2734 SmallVector<CCValAssign, 16> ArgLocs;
2735 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2736 getTargetMachine(), ArgLocs, *DAG.getContext());
2737 MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
2739 Function::const_arg_iterator FuncArg =
2740 DAG.getMachineFunction().getFunction()->arg_begin();
2741 bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
2743 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2744 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2745 MipsCCInfo.hasByValArg());
2747 unsigned CurArgIdx = 0;
2748 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2750 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2751 CCValAssign &VA = ArgLocs[i];
2752 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2753 CurArgIdx = Ins[i].OrigArgIndex;
2754 EVT ValVT = VA.getValVT();
2755 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2756 bool IsRegLoc = VA.isRegLoc();
2758 if (Flags.isByVal()) {
2759 assert(Flags.getByValSize() &&
2760 "ByVal args of size 0 should have been ignored by front-end.");
2761 assert(ByValArg != MipsCCInfo.byval_end());
2762 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2763 MipsCCInfo, *ByValArg);
2768 // Arguments stored on registers
2770 MVT RegVT = VA.getLocVT();
2771 unsigned ArgReg = VA.getLocReg();
2772 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2774 // Transform the arguments stored on
2775 // physical registers into virtual ones
2776 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2777 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2779 // If this is an 8 or 16-bit value, it has been passed promoted
2780 // to 32 bits. Insert an assert[sz]ext to capture this, then
2781 // truncate to the right size.
2782 if (VA.getLocInfo() != CCValAssign::Full) {
2783 unsigned Opcode = 0;
2784 if (VA.getLocInfo() == CCValAssign::SExt)
2785 Opcode = ISD::AssertSext;
2786 else if (VA.getLocInfo() == CCValAssign::ZExt)
2787 Opcode = ISD::AssertZext;
2789 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2790 DAG.getValueType(ValVT));
2791 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2794 // Handle floating point arguments passed in integer registers and
2795 // long double arguments passed in floating point registers.
2796 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2797 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2798 (RegVT == MVT::f64 && ValVT == MVT::i64))
2799 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2800 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2801 ValVT == MVT::f64) {
2802 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2803 getNextIntArgReg(ArgReg), RC);
2804 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2805 if (!Subtarget.isLittle())
2806 std::swap(ArgValue, ArgValue2);
2807 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2808 ArgValue, ArgValue2);
2811 InVals.push_back(ArgValue);
2812 } else { // VA.isRegLoc()
2815 assert(VA.isMemLoc());
2817 // The stack pointer offset is relative to the caller stack frame.
2818 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2819 VA.getLocMemOffset(), true);
2821 // Create load nodes to retrieve arguments from the stack
2822 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2823 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2824 MachinePointerInfo::getFixedStack(FI),
2825 false, false, false, 0);
2826 InVals.push_back(Load);
2827 OutChains.push_back(Load.getValue(1));
2831 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2832 // The mips ABIs for returning structs by value requires that we copy
2833 // the sret argument into $v0 for the return. Save the argument into
2834 // a virtual register so that we can access it from the return points.
2835 if (Ins[i].Flags.isSRet()) {
2836 unsigned Reg = MipsFI->getSRetReturnReg();
2838 Reg = MF.getRegInfo().createVirtualRegister(
2839 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2840 MipsFI->setSRetReturnReg(Reg);
2842 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2843 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2849 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2851 // All stores are grouped in one node to allow the matching between
2852 // the size of Ins and InVals. This only happens when on varg functions
2853 if (!OutChains.empty()) {
2854 OutChains.push_back(Chain);
2855 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2861 //===----------------------------------------------------------------------===//
2862 // Return Value Calling Convention Implementation
2863 //===----------------------------------------------------------------------===//
2866 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2867 MachineFunction &MF, bool IsVarArg,
2868 const SmallVectorImpl<ISD::OutputArg> &Outs,
2869 LLVMContext &Context) const {
2870 SmallVector<CCValAssign, 16> RVLocs;
2871 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2873 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2877 MipsTargetLowering::LowerReturn(SDValue Chain,
2878 CallingConv::ID CallConv, bool IsVarArg,
2879 const SmallVectorImpl<ISD::OutputArg> &Outs,
2880 const SmallVectorImpl<SDValue> &OutVals,
2881 SDLoc DL, SelectionDAG &DAG) const {
2882 // CCValAssign - represent the assignment of
2883 // the return value to a location
2884 SmallVector<CCValAssign, 16> RVLocs;
2885 MachineFunction &MF = DAG.getMachineFunction();
2887 // CCState - Info about the registers and stack slot.
2888 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2890 MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
2893 // Analyze return values.
2894 MipsCCInfo.analyzeReturn(Outs, Subtarget.abiUsesSoftFloat(),
2895 MF.getFunction()->getReturnType());
2898 SmallVector<SDValue, 4> RetOps(1, Chain);
2900 // Copy the result values into the output registers.
2901 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2902 SDValue Val = OutVals[i];
2903 CCValAssign &VA = RVLocs[i];
2904 assert(VA.isRegLoc() && "Can only return in registers!");
2906 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2907 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2909 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2911 // Guarantee that all emitted copies are stuck together with flags.
2912 Flag = Chain.getValue(1);
2913 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2916 // The mips ABIs for returning structs by value requires that we copy
2917 // the sret argument into $v0 for the return. We saved the argument into
2918 // a virtual register in the entry block, so now we copy the value out
2920 if (MF.getFunction()->hasStructRetAttr()) {
2921 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2922 unsigned Reg = MipsFI->getSRetReturnReg();
2925 llvm_unreachable("sret virtual register not created in the entry block");
2926 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2927 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2929 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2930 Flag = Chain.getValue(1);
2931 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2934 RetOps[0] = Chain; // Update chain.
2936 // Add the flag if we have it.
2938 RetOps.push_back(Flag);
2940 // Return on Mips is always a "jr $ra"
2941 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
2944 //===----------------------------------------------------------------------===//
2945 // Mips Inline Assembly Support
2946 //===----------------------------------------------------------------------===//
2948 /// getConstraintType - Given a constraint letter, return the type of
2949 /// constraint it is for this target.
2950 MipsTargetLowering::ConstraintType MipsTargetLowering::
2951 getConstraintType(const std::string &Constraint) const
2953 // Mips specific constraints
2954 // GCC config/mips/constraints.md
2956 // 'd' : An address register. Equivalent to r
2957 // unless generating MIPS16 code.
2958 // 'y' : Equivalent to r; retained for
2959 // backwards compatibility.
2960 // 'c' : A register suitable for use in an indirect
2961 // jump. This will always be $25 for -mabicalls.
2962 // 'l' : The lo register. 1 word storage.
2963 // 'x' : The hilo register pair. Double word storage.
2964 if (Constraint.size() == 1) {
2965 switch (Constraint[0]) {
2973 return C_RegisterClass;
2978 return TargetLowering::getConstraintType(Constraint);
2981 /// Examine constraint type and operand type and determine a weight value.
2982 /// This object must already have been set up with the operand type
2983 /// and the current alternative constraint selected.
2984 TargetLowering::ConstraintWeight
2985 MipsTargetLowering::getSingleConstraintMatchWeight(
2986 AsmOperandInfo &info, const char *constraint) const {
2987 ConstraintWeight weight = CW_Invalid;
2988 Value *CallOperandVal = info.CallOperandVal;
2989 // If we don't have a value, we can't do a match,
2990 // but allow it at the lowest weight.
2991 if (!CallOperandVal)
2993 Type *type = CallOperandVal->getType();
2994 // Look at the constraint type.
2995 switch (*constraint) {
2997 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3001 if (type->isIntegerTy())
3002 weight = CW_Register;
3004 case 'f': // FPU or MSA register
3005 if (Subtarget.hasMSA() && type->isVectorTy() &&
3006 cast<VectorType>(type)->getBitWidth() == 128)
3007 weight = CW_Register;
3008 else if (type->isFloatTy())
3009 weight = CW_Register;
3011 case 'c': // $25 for indirect jumps
3012 case 'l': // lo register
3013 case 'x': // hilo register pair
3014 if (type->isIntegerTy())
3015 weight = CW_SpecificReg;
3017 case 'I': // signed 16 bit immediate
3018 case 'J': // integer zero
3019 case 'K': // unsigned 16 bit immediate
3020 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3021 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3022 case 'O': // signed 15 bit immediate (+- 16383)
3023 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3024 if (isa<ConstantInt>(CallOperandVal))
3025 weight = CW_Constant;
3034 /// This is a helper function to parse a physical register string and split it
3035 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3036 /// that is returned indicates whether parsing was successful. The second flag
3037 /// is true if the numeric part exists.
3038 static std::pair<bool, bool>
3039 parsePhysicalReg(const StringRef &C, std::string &Prefix,
3040 unsigned long long &Reg) {
3041 if (C.front() != '{' || C.back() != '}')
3042 return std::make_pair(false, false);
3044 // Search for the first numeric character.
3045 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3046 I = std::find_if(B, E, std::ptr_fun(isdigit));
3048 Prefix.assign(B, I - B);
3050 // The second flag is set to false if no numeric characters were found.
3052 return std::make_pair(true, false);
3054 // Parse the numeric characters.
3055 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3059 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3060 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
3061 const TargetRegisterInfo *TRI =
3062 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3063 const TargetRegisterClass *RC;
3065 unsigned long long Reg;
3067 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3070 return std::make_pair(0U, nullptr);
3072 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3073 // No numeric characters follow "hi" or "lo".
3075 return std::make_pair(0U, nullptr);
3077 RC = TRI->getRegClass(Prefix == "hi" ?
3078 Mips::HI32RegClassID : Mips::LO32RegClassID);
3079 return std::make_pair(*(RC->begin()), RC);
3080 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3081 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3083 // No numeric characters follow the name.
3085 return std::make_pair(0U, nullptr);
3087 Reg = StringSwitch<unsigned long long>(Prefix)
3088 .Case("$msair", Mips::MSAIR)
3089 .Case("$msacsr", Mips::MSACSR)
3090 .Case("$msaaccess", Mips::MSAAccess)
3091 .Case("$msasave", Mips::MSASave)
3092 .Case("$msamodify", Mips::MSAModify)
3093 .Case("$msarequest", Mips::MSARequest)
3094 .Case("$msamap", Mips::MSAMap)
3095 .Case("$msaunmap", Mips::MSAUnmap)
3099 return std::make_pair(0U, nullptr);
3101 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3102 return std::make_pair(Reg, RC);
3106 return std::make_pair(0U, nullptr);
3108 if (Prefix == "$f") { // Parse $f0-$f31.
3109 // If the size of FP registers is 64-bit or Reg is an even number, select
3110 // the 64-bit register class. Otherwise, select the 32-bit register class.
3111 if (VT == MVT::Other)
3112 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3114 RC = getRegClassFor(VT);
3116 if (RC == &Mips::AFGR64RegClass) {
3117 assert(Reg % 2 == 0);
3120 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3121 RC = TRI->getRegClass(Mips::FCCRegClassID);
3122 else if (Prefix == "$w") { // Parse $w0-$w31.
3123 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3124 } else { // Parse $0-$31.
3125 assert(Prefix == "$");
3126 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3129 assert(Reg < RC->getNumRegs());
3130 return std::make_pair(*(RC->begin() + Reg), RC);
3133 /// Given a register class constraint, like 'r', if this corresponds directly
3134 /// to an LLVM register class, return a register of 0 and the register class
3136 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3137 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3139 if (Constraint.size() == 1) {
3140 switch (Constraint[0]) {
3141 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3142 case 'y': // Same as 'r'. Exists for compatibility.
3144 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3145 if (Subtarget.inMips16Mode())
3146 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3147 return std::make_pair(0U, &Mips::GPR32RegClass);
3149 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3150 return std::make_pair(0U, &Mips::GPR32RegClass);
3151 if (VT == MVT::i64 && Subtarget.isGP64bit())
3152 return std::make_pair(0U, &Mips::GPR64RegClass);
3153 // This will generate an error message
3154 return std::make_pair(0U, nullptr);
3155 case 'f': // FPU or MSA register
3156 if (VT == MVT::v16i8)
3157 return std::make_pair(0U, &Mips::MSA128BRegClass);
3158 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3159 return std::make_pair(0U, &Mips::MSA128HRegClass);
3160 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3161 return std::make_pair(0U, &Mips::MSA128WRegClass);
3162 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3163 return std::make_pair(0U, &Mips::MSA128DRegClass);
3164 else if (VT == MVT::f32)
3165 return std::make_pair(0U, &Mips::FGR32RegClass);
3166 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3167 if (Subtarget.isFP64bit())
3168 return std::make_pair(0U, &Mips::FGR64RegClass);
3169 return std::make_pair(0U, &Mips::AFGR64RegClass);
3172 case 'c': // register suitable for indirect jump
3174 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3175 assert(VT == MVT::i64 && "Unexpected type.");
3176 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3177 case 'l': // register suitable for indirect jump
3179 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3180 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3181 case 'x': // register suitable for indirect jump
3182 // Fixme: Not triggering the use of both hi and low
3183 // This will generate an error message
3184 return std::make_pair(0U, nullptr);
3188 std::pair<unsigned, const TargetRegisterClass *> R;
3189 R = parseRegForInlineAsmConstraint(Constraint, VT);
3194 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3197 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3198 /// vector. If it is invalid, don't add anything to Ops.
3199 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3200 std::string &Constraint,
3201 std::vector<SDValue>&Ops,
3202 SelectionDAG &DAG) const {
3205 // Only support length 1 constraints for now.
3206 if (Constraint.length() > 1) return;
3208 char ConstraintLetter = Constraint[0];
3209 switch (ConstraintLetter) {
3210 default: break; // This will fall through to the generic implementation
3211 case 'I': // Signed 16 bit constant
3212 // If this fails, the parent routine will give an error
3213 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3214 EVT Type = Op.getValueType();
3215 int64_t Val = C->getSExtValue();
3216 if (isInt<16>(Val)) {
3217 Result = DAG.getTargetConstant(Val, Type);
3222 case 'J': // integer zero
3223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3224 EVT Type = Op.getValueType();
3225 int64_t Val = C->getZExtValue();
3227 Result = DAG.getTargetConstant(0, Type);
3232 case 'K': // unsigned 16 bit immediate
3233 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3234 EVT Type = Op.getValueType();
3235 uint64_t Val = (uint64_t)C->getZExtValue();
3236 if (isUInt<16>(Val)) {
3237 Result = DAG.getTargetConstant(Val, Type);
3242 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3243 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3244 EVT Type = Op.getValueType();
3245 int64_t Val = C->getSExtValue();
3246 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3247 Result = DAG.getTargetConstant(Val, Type);
3252 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3254 EVT Type = Op.getValueType();
3255 int64_t Val = C->getSExtValue();
3256 if ((Val >= -65535) && (Val <= -1)) {
3257 Result = DAG.getTargetConstant(Val, Type);
3262 case 'O': // signed 15 bit immediate
3263 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3264 EVT Type = Op.getValueType();
3265 int64_t Val = C->getSExtValue();
3266 if ((isInt<15>(Val))) {
3267 Result = DAG.getTargetConstant(Val, Type);
3272 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3274 EVT Type = Op.getValueType();
3275 int64_t Val = C->getSExtValue();
3276 if ((Val <= 65535) && (Val >= 1)) {
3277 Result = DAG.getTargetConstant(Val, Type);
3284 if (Result.getNode()) {
3285 Ops.push_back(Result);
3289 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3292 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3294 // No global is ever allowed as a base.
3299 case 0: // "r+i" or just "i", depending on HasBaseReg.
3302 if (!AM.HasBaseReg) // allow "r+i".
3304 return false; // disallow "r+r" or "r+r+i".
3313 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3314 // The Mips target isn't yet aware of offsets.
3318 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3320 bool IsMemset, bool ZeroMemset,
3322 MachineFunction &MF) const {
3323 if (Subtarget.hasMips64())
3329 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3330 if (VT != MVT::f32 && VT != MVT::f64)
3332 if (Imm.isNegZero())
3334 return Imm.isZero();
3337 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3338 if (Subtarget.isABI_N64())
3339 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3341 return TargetLowering::getJumpTableEncoding();
3344 /// This function returns true if CallSym is a long double emulation routine.
3345 static bool isF128SoftLibCall(const char *CallSym) {
3346 const char *const LibCalls[] =
3347 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3348 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3349 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3350 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3351 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3352 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3353 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3354 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3357 const char *const *End = LibCalls + array_lengthof(LibCalls);
3359 // Check that LibCalls is sorted alphabetically.
3360 MipsTargetLowering::LTStr Comp;
3363 for (const char *const *I = LibCalls; I < End - 1; ++I)
3364 assert(Comp(*I, *(I + 1)));
3367 return std::binary_search(LibCalls, End, CallSym, Comp);
3370 /// This function returns true if Ty is fp128 or i128 which was originally a
3372 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3373 if (Ty->isFP128Ty())
3376 const ExternalSymbolSDNode *ES =
3377 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3379 // If the Ty is i128 and the function being called is a long double emulation
3380 // routine, then the original type is f128.
3381 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3384 MipsTargetLowering::MipsCC::SpecialCallingConvType
3385 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3386 MipsCC::SpecialCallingConvType SpecialCallingConv =
3387 MipsCC::NoSpecialCallingConv;
3388 if (Subtarget.inMips16HardFloat()) {
3389 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3390 llvm::StringRef Sym = G->getGlobal()->getName();
3391 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3392 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3393 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3397 return SpecialCallingConv;
3400 MipsTargetLowering::MipsCC::MipsCC(
3401 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3402 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3403 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3404 SpecialCallingConv(SpecialCallingConv_){
3405 // Pre-allocate reserved argument area.
3406 CCInfo.AllocateStack(reservedArgArea(), 1);
3410 void MipsTargetLowering::MipsCC::
3411 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3412 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3413 std::vector<ArgListEntry> &FuncArgs) {
3414 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3415 "CallingConv::Fast shouldn't be used for vararg functions.");
3417 unsigned NumOpnds = Args.size();
3418 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3420 for (unsigned I = 0; I != NumOpnds; ++I) {
3421 MVT ArgVT = Args[I].VT;
3422 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3425 if (ArgFlags.isByVal()) {
3426 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3430 if (IsVarArg && !Args[I].IsFixed)
3431 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3433 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3435 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3440 dbgs() << "Call operand #" << I << " has unhandled type "
3441 << EVT(ArgVT).getEVTString();
3443 llvm_unreachable(nullptr);
3448 void MipsTargetLowering::MipsCC::
3449 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3450 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3451 unsigned NumArgs = Args.size();
3452 llvm::CCAssignFn *FixedFn = fixedArgFn();
3453 unsigned CurArgIdx = 0;
3455 for (unsigned I = 0; I != NumArgs; ++I) {
3456 MVT ArgVT = Args[I].VT;
3457 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3458 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3459 CurArgIdx = Args[I].OrigArgIndex;
3461 if (ArgFlags.isByVal()) {
3462 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3466 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3468 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3472 dbgs() << "Formal Arg #" << I << " has unhandled type "
3473 << EVT(ArgVT).getEVTString();
3475 llvm_unreachable(nullptr);
3479 template<typename Ty>
3480 void MipsTargetLowering::MipsCC::
3481 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3482 const SDNode *CallNode, const Type *RetTy) const {
3485 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3486 Fn = RetCC_F128Soft;
3490 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3491 MVT VT = RetVals[I].VT;
3492 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3493 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3495 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3497 dbgs() << "Call result #" << I << " has unhandled type "
3498 << EVT(VT).getEVTString() << '\n';
3500 llvm_unreachable(nullptr);
3505 void MipsTargetLowering::MipsCC::
3506 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3507 const SDNode *CallNode, const Type *RetTy) const {
3508 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3511 void MipsTargetLowering::MipsCC::
3512 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3513 const Type *RetTy) const {
3514 analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
3517 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3519 CCValAssign::LocInfo LocInfo,
3520 ISD::ArgFlagsTy ArgFlags) {
3521 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3523 struct ByValArgInfo ByVal;
3524 unsigned RegSize = regSize();
3525 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3526 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3529 if (useRegsForByval())
3530 allocateRegs(ByVal, ByValSize, Align);
3532 // Allocate space on caller's stack.
3533 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3535 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3537 ByValArgs.push_back(ByVal);
3540 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3541 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3544 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3545 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3548 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3549 return IsO32 ? O32IntRegs : Mips64IntRegs;
3552 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3553 if (CallConv == CallingConv::Fast)
3554 return CC_Mips_FastCC;
3556 if (SpecialCallingConv == Mips16RetHelperConv)
3557 return CC_Mips16RetHelper;
3558 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3561 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3562 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3565 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3566 return IsO32 ? O32IntRegs : Mips64DPRegs;
3569 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3572 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3573 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3574 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3575 "Byval argument's size and alignment should be a multiple of"
3578 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3580 // If Align > RegSize, the first arg register must be even.
3581 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3582 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3586 // Mark the registers allocated.
3587 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3588 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3589 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3592 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3593 const SDNode *CallNode,
3594 bool IsSoftFloat) const {
3595 if (IsSoftFloat || IsO32)
3598 // Check if the original type was fp128.
3599 if (originalTypeIsF128(OrigTy, CallNode)) {
3600 assert(VT == MVT::i64);
3607 void MipsTargetLowering::
3608 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3609 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3610 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3611 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3612 MachineFunction &MF = DAG.getMachineFunction();
3613 MachineFrameInfo *MFI = MF.getFrameInfo();
3614 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3615 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3619 FrameObjOffset = (int)CC.reservedArgArea() -
3620 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3622 FrameObjOffset = ByVal.Address;
3624 // Create frame object.
3625 EVT PtrTy = getPointerTy();
3626 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3627 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3628 InVals.push_back(FIN);
3633 // Copy arg registers.
3634 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3635 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3637 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3638 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3639 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3640 unsigned Offset = I * CC.regSize();
3641 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3642 DAG.getConstant(Offset, PtrTy));
3643 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3644 StorePtr, MachinePointerInfo(FuncArg, Offset),
3646 OutChains.push_back(Store);
3650 // Copy byVal arg to registers and stack.
3651 void MipsTargetLowering::
3652 passByValArg(SDValue Chain, SDLoc DL,
3653 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3654 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3655 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3656 const MipsCC &CC, const ByValArgInfo &ByVal,
3657 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3658 unsigned ByValSizeInBytes = Flags.getByValSize();
3659 unsigned OffsetInBytes = 0; // From beginning of struct
3660 unsigned RegSizeInBytes = CC.regSize();
3661 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3662 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3664 if (ByVal.NumRegs) {
3665 const MCPhysReg *ArgRegs = CC.intArgRegs();
3666 bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3669 // Copy words to registers.
3670 for (; I < ByVal.NumRegs - LeftoverBytes;
3671 ++I, OffsetInBytes += RegSizeInBytes) {
3672 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3673 DAG.getConstant(OffsetInBytes, PtrTy));
3674 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3675 MachinePointerInfo(), false, false, false,
3677 MemOpChains.push_back(LoadVal.getValue(1));
3678 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3679 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3682 // Return if the struct has been fully copied.
3683 if (ByValSizeInBytes == OffsetInBytes)
3686 // Copy the remainder of the byval argument with sub-word loads and shifts.
3687 if (LeftoverBytes) {
3688 assert((ByValSizeInBytes > OffsetInBytes) &&
3689 (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3690 "Size of the remainder should be smaller than RegSizeInBytes.");
3693 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3694 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3695 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3697 if (RemainingSizeInBytes < LoadSizeInBytes)
3701 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3702 DAG.getConstant(OffsetInBytes, PtrTy));
3703 SDValue LoadVal = DAG.getExtLoad(
3704 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3705 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3707 MemOpChains.push_back(LoadVal.getValue(1));
3709 // Shift the loaded value.
3713 Shamt = TotalBytesLoaded * 8;
3715 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3717 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3718 DAG.getConstant(Shamt, MVT::i32));
3721 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3725 OffsetInBytes += LoadSizeInBytes;
3726 TotalBytesLoaded += LoadSizeInBytes;
3727 Alignment = std::min(Alignment, LoadSizeInBytes);
3730 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3731 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3736 // Copy remainder of byval arg to it with memcpy.
3737 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3738 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3739 DAG.getConstant(OffsetInBytes, PtrTy));
3740 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3741 DAG.getIntPtrConstant(ByVal.Address));
3742 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3743 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3744 MachinePointerInfo(), MachinePointerInfo());
3745 MemOpChains.push_back(Chain);
3748 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3749 const MipsCC &CC, SDValue Chain,
3750 SDLoc DL, SelectionDAG &DAG) const {
3751 unsigned NumRegs = CC.numIntArgRegs();
3752 const MCPhysReg *ArgRegs = CC.intArgRegs();
3753 const CCState &CCInfo = CC.getCCInfo();
3754 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3755 unsigned RegSize = CC.regSize();
3756 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3757 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3758 MachineFunction &MF = DAG.getMachineFunction();
3759 MachineFrameInfo *MFI = MF.getFrameInfo();
3760 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3762 // Offset of the first variable argument from stack pointer.
3766 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3768 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3770 // Record the frame index of the first variable argument
3771 // which is a value necessary to VASTART.
3772 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3773 MipsFI->setVarArgsFrameIndex(FI);
3775 // Copy the integer registers that have not been used for argument passing
3776 // to the argument register save area. For O32, the save area is allocated
3777 // in the caller's stack frame, while for N32/64, it is allocated in the
3778 // callee's stack frame.
3779 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3780 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3781 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3782 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3783 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3784 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3785 MachinePointerInfo(), false, false, 0);
3786 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3788 OutChains.push_back(Store);