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 "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGISel.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "mips-lower"
45 STATISTIC(NumTailCalls, "Number of tail calls");
48 LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
57 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
61 static const MCPhysReg Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
89 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
95 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
107 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
114 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
116 case MipsISD::JmpLink: return "MipsISD::JmpLink";
117 case MipsISD::TailCall: return "MipsISD::TailCall";
118 case MipsISD::Hi: return "MipsISD::Hi";
119 case MipsISD::Lo: return "MipsISD::Lo";
120 case MipsISD::GPRel: return "MipsISD::GPRel";
121 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
122 case MipsISD::Ret: return "MipsISD::Ret";
123 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
124 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
125 case MipsISD::FPCmp: return "MipsISD::FPCmp";
126 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
127 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
128 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
129 case MipsISD::MFHI: return "MipsISD::MFHI";
130 case MipsISD::MFLO: return "MipsISD::MFLO";
131 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
132 case MipsISD::Mult: return "MipsISD::Mult";
133 case MipsISD::Multu: return "MipsISD::Multu";
134 case MipsISD::MAdd: return "MipsISD::MAdd";
135 case MipsISD::MAddu: return "MipsISD::MAddu";
136 case MipsISD::MSub: return "MipsISD::MSub";
137 case MipsISD::MSubu: return "MipsISD::MSubu";
138 case MipsISD::DivRem: return "MipsISD::DivRem";
139 case MipsISD::DivRemU: return "MipsISD::DivRemU";
140 case MipsISD::DivRem16: return "MipsISD::DivRem16";
141 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
142 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
143 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
144 case MipsISD::Wrapper: return "MipsISD::Wrapper";
145 case MipsISD::Sync: return "MipsISD::Sync";
146 case MipsISD::Ext: return "MipsISD::Ext";
147 case MipsISD::Ins: return "MipsISD::Ins";
148 case MipsISD::LWL: return "MipsISD::LWL";
149 case MipsISD::LWR: return "MipsISD::LWR";
150 case MipsISD::SWL: return "MipsISD::SWL";
151 case MipsISD::SWR: return "MipsISD::SWR";
152 case MipsISD::LDL: return "MipsISD::LDL";
153 case MipsISD::LDR: return "MipsISD::LDR";
154 case MipsISD::SDL: return "MipsISD::SDL";
155 case MipsISD::SDR: return "MipsISD::SDR";
156 case MipsISD::EXTP: return "MipsISD::EXTP";
157 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
158 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
159 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
160 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
161 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
162 case MipsISD::SHILO: return "MipsISD::SHILO";
163 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
164 case MipsISD::MULT: return "MipsISD::MULT";
165 case MipsISD::MULTU: return "MipsISD::MULTU";
166 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
167 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
168 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
169 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
170 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
171 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
172 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
173 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
174 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
175 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
176 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
177 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
178 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
179 case MipsISD::VCEQ: return "MipsISD::VCEQ";
180 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
181 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
182 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
183 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
184 case MipsISD::VSMAX: return "MipsISD::VSMAX";
185 case MipsISD::VSMIN: return "MipsISD::VSMIN";
186 case MipsISD::VUMAX: return "MipsISD::VUMAX";
187 case MipsISD::VUMIN: return "MipsISD::VUMIN";
188 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
189 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
190 case MipsISD::VNOR: return "MipsISD::VNOR";
191 case MipsISD::VSHF: return "MipsISD::VSHF";
192 case MipsISD::SHF: return "MipsISD::SHF";
193 case MipsISD::ILVEV: return "MipsISD::ILVEV";
194 case MipsISD::ILVOD: return "MipsISD::ILVOD";
195 case MipsISD::ILVL: return "MipsISD::ILVL";
196 case MipsISD::ILVR: return "MipsISD::ILVR";
197 case MipsISD::PCKEV: return "MipsISD::PCKEV";
198 case MipsISD::PCKOD: return "MipsISD::PCKOD";
199 case MipsISD::INSVE: return "MipsISD::INSVE";
200 default: return nullptr;
204 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
205 const MipsSubtarget &STI)
206 : TargetLowering(TM), Subtarget(STI) {
207 // Mips does not have i1 type, so use i32 for
208 // setcc operations results (slt, sgt, ...).
209 setBooleanContents(ZeroOrOneBooleanContent);
210 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
211 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
212 // does. Integer booleans still use 0 and 1.
213 if (Subtarget.hasMips32r6())
214 setBooleanContents(ZeroOrOneBooleanContent,
215 ZeroOrNegativeOneBooleanContent);
217 // Load extented operations for i1 types must be promoted
218 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
219 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
220 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
222 // MIPS doesn't have extending float->double load/store
223 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
224 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
226 // Used by legalize types to correctly generate the setcc result.
227 // Without this, every float setcc comes with a AND/OR with the result,
228 // we don't want this, since the fpcmp result goes to a flag register,
229 // which is used implicitly by brcond and select operations.
230 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
232 // Mips Custom Operations
233 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
234 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
235 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
236 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
237 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
238 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
239 setOperationAction(ISD::SELECT, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT, MVT::f64, Custom);
241 setOperationAction(ISD::SELECT, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
244 setOperationAction(ISD::SETCC, MVT::f32, Custom);
245 setOperationAction(ISD::SETCC, MVT::f64, Custom);
246 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
248 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
249 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 if (Subtarget.isGP64bit()) {
252 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
253 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
254 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
255 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
256 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
257 setOperationAction(ISD::SELECT, MVT::i64, Custom);
258 setOperationAction(ISD::LOAD, MVT::i64, Custom);
259 setOperationAction(ISD::STORE, MVT::i64, Custom);
260 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
263 if (!Subtarget.isGP64bit()) {
264 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::ADD, MVT::i32, Custom);
270 if (Subtarget.isGP64bit())
271 setOperationAction(ISD::ADD, MVT::i64, Custom);
273 setOperationAction(ISD::SDIV, MVT::i32, Expand);
274 setOperationAction(ISD::SREM, MVT::i32, Expand);
275 setOperationAction(ISD::UDIV, MVT::i32, Expand);
276 setOperationAction(ISD::UREM, MVT::i32, Expand);
277 setOperationAction(ISD::SDIV, MVT::i64, Expand);
278 setOperationAction(ISD::SREM, MVT::i64, Expand);
279 setOperationAction(ISD::UDIV, MVT::i64, Expand);
280 setOperationAction(ISD::UREM, MVT::i64, Expand);
282 // Operations not directly supported by Mips.
283 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
284 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
285 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
286 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
287 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
288 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
289 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
290 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
291 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
292 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
293 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
294 if (Subtarget.hasCnMips()) {
295 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
296 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
298 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
299 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
303 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
306 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
307 setOperationAction(ISD::ROTL, MVT::i32, Expand);
308 setOperationAction(ISD::ROTL, MVT::i64, Expand);
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
312 if (!Subtarget.hasMips32r2())
313 setOperationAction(ISD::ROTR, MVT::i32, Expand);
315 if (!Subtarget.hasMips64r2())
316 setOperationAction(ISD::ROTR, MVT::i64, Expand);
318 setOperationAction(ISD::FSIN, MVT::f32, Expand);
319 setOperationAction(ISD::FSIN, MVT::f64, Expand);
320 setOperationAction(ISD::FCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
323 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
324 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
325 setOperationAction(ISD::FPOW, MVT::f32, Expand);
326 setOperationAction(ISD::FPOW, MVT::f64, Expand);
327 setOperationAction(ISD::FLOG, MVT::f32, Expand);
328 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
329 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
330 setOperationAction(ISD::FEXP, MVT::f32, Expand);
331 setOperationAction(ISD::FMA, MVT::f32, Expand);
332 setOperationAction(ISD::FMA, MVT::f64, Expand);
333 setOperationAction(ISD::FREM, MVT::f32, Expand);
334 setOperationAction(ISD::FREM, MVT::f64, Expand);
336 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
338 setOperationAction(ISD::VASTART, MVT::Other, Custom);
339 setOperationAction(ISD::VAARG, MVT::Other, Custom);
340 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
341 setOperationAction(ISD::VAEND, MVT::Other, Expand);
343 // Use the default for now
344 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
345 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
347 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
349 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
352 setInsertFencesForAtomic(true);
354 if (!Subtarget.hasMips32r2()) {
355 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
359 // MIPS16 lacks MIPS32's clz and clo instructions.
360 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
361 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
362 if (!Subtarget.hasMips64())
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
365 if (!Subtarget.hasMips32r2())
366 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
367 if (!Subtarget.hasMips64r2())
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
370 if (Subtarget.isGP64bit()) {
371 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
372 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
374 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
377 setOperationAction(ISD::TRAP, MVT::Other, Legal);
379 setTargetDAGCombine(ISD::SDIVREM);
380 setTargetDAGCombine(ISD::UDIVREM);
381 setTargetDAGCombine(ISD::SELECT);
382 setTargetDAGCombine(ISD::AND);
383 setTargetDAGCombine(ISD::OR);
384 setTargetDAGCombine(ISD::ADD);
386 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
388 // The arguments on the stack are defined in terms of 4-byte slots on O32
389 // and 8-byte slots on N32/N64.
390 setMinStackArgumentAlignment(
391 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
393 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
396 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
397 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
399 MaxStoresPerMemcpy = 16;
401 isMicroMips = Subtarget.inMicroMipsMode();
404 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
405 const MipsSubtarget &STI) {
406 if (STI.inMips16Mode())
407 return llvm::createMips16TargetLowering(TM, STI);
409 return llvm::createMipsSETargetLowering(TM, STI);
412 // Create a fast isel object.
414 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
415 const TargetLibraryInfo *libInfo) const {
416 if (!EnableMipsFastISel)
417 return TargetLowering::createFastISel(funcInfo, libInfo);
418 return Mips::createFastISel(funcInfo, libInfo);
421 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
424 return VT.changeVectorElementTypeToInteger();
427 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
428 TargetLowering::DAGCombinerInfo &DCI,
429 const MipsSubtarget &Subtarget) {
430 if (DCI.isBeforeLegalizeOps())
433 EVT Ty = N->getValueType(0);
434 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
435 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
436 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
440 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
441 N->getOperand(0), N->getOperand(1));
442 SDValue InChain = DAG.getEntryNode();
443 SDValue InGlue = DivRem;
446 if (N->hasAnyUseOfValue(0)) {
447 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
450 InChain = CopyFromLo.getValue(1);
451 InGlue = CopyFromLo.getValue(2);
455 if (N->hasAnyUseOfValue(1)) {
456 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
464 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
466 default: llvm_unreachable("Unknown fp condition code!");
468 case ISD::SETOEQ: return Mips::FCOND_OEQ;
469 case ISD::SETUNE: return Mips::FCOND_UNE;
471 case ISD::SETOLT: return Mips::FCOND_OLT;
473 case ISD::SETOGT: return Mips::FCOND_OGT;
475 case ISD::SETOLE: return Mips::FCOND_OLE;
477 case ISD::SETOGE: return Mips::FCOND_OGE;
478 case ISD::SETULT: return Mips::FCOND_ULT;
479 case ISD::SETULE: return Mips::FCOND_ULE;
480 case ISD::SETUGT: return Mips::FCOND_UGT;
481 case ISD::SETUGE: return Mips::FCOND_UGE;
482 case ISD::SETUO: return Mips::FCOND_UN;
483 case ISD::SETO: return Mips::FCOND_OR;
485 case ISD::SETONE: return Mips::FCOND_ONE;
486 case ISD::SETUEQ: return Mips::FCOND_UEQ;
491 /// This function returns true if the floating point conditional branches and
492 /// conditional moves which use condition code CC should be inverted.
493 static bool invertFPCondCodeUser(Mips::CondCode CC) {
494 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
497 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
498 "Illegal Condition Code");
503 // Creates and returns an FPCmp node from a setcc node.
504 // Returns Op if setcc is not a floating point comparison.
505 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
506 // must be a SETCC node
507 if (Op.getOpcode() != ISD::SETCC)
510 SDValue LHS = Op.getOperand(0);
512 if (!LHS.getValueType().isFloatingPoint())
515 SDValue RHS = Op.getOperand(1);
518 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
519 // node if necessary.
520 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
522 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
523 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
526 // Creates and returns a CMovFPT/F node.
527 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
528 SDValue False, SDLoc DL) {
529 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
530 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
531 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
533 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
534 True.getValueType(), True, FCC0, False, Cond);
537 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
538 TargetLowering::DAGCombinerInfo &DCI,
539 const MipsSubtarget &Subtarget) {
540 if (DCI.isBeforeLegalizeOps())
543 SDValue SetCC = N->getOperand(0);
545 if ((SetCC.getOpcode() != ISD::SETCC) ||
546 !SetCC.getOperand(0).getValueType().isInteger())
549 SDValue False = N->getOperand(2);
550 EVT FalseTy = False.getValueType();
552 if (!FalseTy.isInteger())
555 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
557 // If the RHS (False) is 0, we swap the order of the operands
558 // of ISD::SELECT (obviously also inverting the condition) so that we can
559 // take advantage of conditional moves using the $0 register.
561 // return (a != 0) ? x : 0;
569 if (!FalseC->getZExtValue()) {
570 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
571 SDValue True = N->getOperand(1);
573 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
574 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
576 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
579 // If both operands are integer constants there's a possibility that we
580 // can do some interesting optimizations.
581 SDValue True = N->getOperand(1);
582 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
584 if (!TrueC || !True.getValueType().isInteger())
587 // We'll also ignore MVT::i64 operands as this optimizations proves
588 // to be ineffective because of the required sign extensions as the result
589 // of a SETCC operator is always MVT::i32 for non-vector types.
590 if (True.getValueType() == MVT::i64)
593 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
595 // 1) (a < x) ? y : y-1
597 // addiu $reg2, $reg1, y-1
599 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
601 // 2) (a < x) ? y-1 : y
603 // xor $reg1, $reg1, 1
604 // addiu $reg2, $reg1, y-1
606 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
607 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
608 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
609 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
612 // Couldn't optimize.
616 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
617 TargetLowering::DAGCombinerInfo &DCI,
618 const MipsSubtarget &Subtarget) {
619 // Pattern match EXT.
620 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
621 // => ext $dst, $src, size, pos
622 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
625 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
626 unsigned ShiftRightOpc = ShiftRight.getOpcode();
628 // Op's first operand must be a shift right.
629 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
632 // The second operand of the shift must be an immediate.
634 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
637 uint64_t Pos = CN->getZExtValue();
638 uint64_t SMPos, SMSize;
640 // Op's second operand must be a shifted mask.
641 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
642 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
645 // Return if the shifted mask does not start at bit 0 or the sum of its size
646 // and Pos exceeds the word's size.
647 EVT ValTy = N->getValueType(0);
648 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
651 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
652 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
653 DAG.getConstant(SMSize, MVT::i32));
656 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
657 TargetLowering::DAGCombinerInfo &DCI,
658 const MipsSubtarget &Subtarget) {
659 // Pattern match INS.
660 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
661 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
662 // => ins $dst, $src, size, pos, $src1
663 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
666 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
667 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
670 // See if Op's first operand matches (and $src1 , mask0).
671 if (And0.getOpcode() != ISD::AND)
674 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
675 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
678 // See if Op's second operand matches (and (shl $src, pos), mask1).
679 if (And1.getOpcode() != ISD::AND)
682 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
683 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
686 // The shift masks must have the same position and size.
687 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
690 SDValue Shl = And1.getOperand(0);
691 if (Shl.getOpcode() != ISD::SHL)
694 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
697 unsigned Shamt = CN->getZExtValue();
699 // Return if the shift amount and the first bit position of mask are not the
701 EVT ValTy = N->getValueType(0);
702 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
705 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
706 DAG.getConstant(SMPos0, MVT::i32),
707 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
710 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
711 TargetLowering::DAGCombinerInfo &DCI,
712 const MipsSubtarget &Subtarget) {
713 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
715 if (DCI.isBeforeLegalizeOps())
718 SDValue Add = N->getOperand(1);
720 if (Add.getOpcode() != ISD::ADD)
723 SDValue Lo = Add.getOperand(1);
725 if ((Lo.getOpcode() != MipsISD::Lo) ||
726 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
729 EVT ValTy = N->getValueType(0);
732 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
734 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
737 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
739 SelectionDAG &DAG = DCI.DAG;
740 unsigned Opc = N->getOpcode();
746 return performDivRemCombine(N, DAG, DCI, Subtarget);
748 return performSELECTCombine(N, DAG, DCI, Subtarget);
750 return performANDCombine(N, DAG, DCI, Subtarget);
752 return performORCombine(N, DAG, DCI, Subtarget);
754 return performADDCombine(N, DAG, DCI, Subtarget);
761 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
762 SmallVectorImpl<SDValue> &Results,
763 SelectionDAG &DAG) const {
764 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
766 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
767 Results.push_back(Res.getValue(I));
771 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
772 SmallVectorImpl<SDValue> &Results,
773 SelectionDAG &DAG) const {
774 return LowerOperationWrapper(N, Results, DAG);
777 SDValue MipsTargetLowering::
778 LowerOperation(SDValue Op, SelectionDAG &DAG) const
780 switch (Op.getOpcode())
782 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
783 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
784 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
785 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
786 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
787 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
788 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
789 case ISD::SELECT: return lowerSELECT(Op, DAG);
790 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
791 case ISD::SETCC: return lowerSETCC(Op, DAG);
792 case ISD::VASTART: return lowerVASTART(Op, DAG);
793 case ISD::VAARG: return lowerVAARG(Op, DAG);
794 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
795 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
796 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
797 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
798 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
799 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
800 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
801 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
802 case ISD::LOAD: return lowerLOAD(Op, DAG);
803 case ISD::STORE: return lowerSTORE(Op, DAG);
804 case ISD::ADD: return lowerADD(Op, DAG);
805 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
810 //===----------------------------------------------------------------------===//
811 // Lower helper functions
812 //===----------------------------------------------------------------------===//
814 // addLiveIn - This helper function adds the specified physical register to the
815 // MachineFunction as a live in value. It also creates a corresponding
816 // virtual register for it.
818 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
820 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
821 MF.getRegInfo().addLiveIn(PReg, VReg);
825 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
826 MachineBasicBlock &MBB,
827 const TargetInstrInfo &TII,
832 // Insert instruction "teq $divisor_reg, $zero, 7".
833 MachineBasicBlock::iterator I(MI);
834 MachineInstrBuilder MIB;
835 MachineOperand &Divisor = MI->getOperand(2);
836 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
837 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
838 .addReg(Mips::ZERO).addImm(7);
840 // Use the 32-bit sub-register if this is a 64-bit division.
842 MIB->getOperand(0).setSubReg(Mips::sub_32);
844 // Clear Divisor's kill flag.
845 Divisor.setIsKill(false);
847 // We would normally delete the original instruction here but in this case
848 // we only needed to inject an additional instruction rather than replace it.
854 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
855 MachineBasicBlock *BB) const {
856 switch (MI->getOpcode()) {
858 llvm_unreachable("Unexpected instr type to insert");
859 case Mips::ATOMIC_LOAD_ADD_I8:
860 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
861 case Mips::ATOMIC_LOAD_ADD_I16:
862 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
863 case Mips::ATOMIC_LOAD_ADD_I32:
864 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
865 case Mips::ATOMIC_LOAD_ADD_I64:
866 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
868 case Mips::ATOMIC_LOAD_AND_I8:
869 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
870 case Mips::ATOMIC_LOAD_AND_I16:
871 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
872 case Mips::ATOMIC_LOAD_AND_I32:
873 return emitAtomicBinary(MI, BB, 4, Mips::AND);
874 case Mips::ATOMIC_LOAD_AND_I64:
875 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
877 case Mips::ATOMIC_LOAD_OR_I8:
878 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
879 case Mips::ATOMIC_LOAD_OR_I16:
880 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
881 case Mips::ATOMIC_LOAD_OR_I32:
882 return emitAtomicBinary(MI, BB, 4, Mips::OR);
883 case Mips::ATOMIC_LOAD_OR_I64:
884 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
886 case Mips::ATOMIC_LOAD_XOR_I8:
887 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
888 case Mips::ATOMIC_LOAD_XOR_I16:
889 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
890 case Mips::ATOMIC_LOAD_XOR_I32:
891 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
892 case Mips::ATOMIC_LOAD_XOR_I64:
893 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
895 case Mips::ATOMIC_LOAD_NAND_I8:
896 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
897 case Mips::ATOMIC_LOAD_NAND_I16:
898 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
899 case Mips::ATOMIC_LOAD_NAND_I32:
900 return emitAtomicBinary(MI, BB, 4, 0, true);
901 case Mips::ATOMIC_LOAD_NAND_I64:
902 return emitAtomicBinary(MI, BB, 8, 0, true);
904 case Mips::ATOMIC_LOAD_SUB_I8:
905 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
906 case Mips::ATOMIC_LOAD_SUB_I16:
907 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
908 case Mips::ATOMIC_LOAD_SUB_I32:
909 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
910 case Mips::ATOMIC_LOAD_SUB_I64:
911 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
913 case Mips::ATOMIC_SWAP_I8:
914 return emitAtomicBinaryPartword(MI, BB, 1, 0);
915 case Mips::ATOMIC_SWAP_I16:
916 return emitAtomicBinaryPartword(MI, BB, 2, 0);
917 case Mips::ATOMIC_SWAP_I32:
918 return emitAtomicBinary(MI, BB, 4, 0);
919 case Mips::ATOMIC_SWAP_I64:
920 return emitAtomicBinary(MI, BB, 8, 0);
922 case Mips::ATOMIC_CMP_SWAP_I8:
923 return emitAtomicCmpSwapPartword(MI, BB, 1);
924 case Mips::ATOMIC_CMP_SWAP_I16:
925 return emitAtomicCmpSwapPartword(MI, BB, 2);
926 case Mips::ATOMIC_CMP_SWAP_I32:
927 return emitAtomicCmpSwap(MI, BB, 4);
928 case Mips::ATOMIC_CMP_SWAP_I64:
929 return emitAtomicCmpSwap(MI, BB, 8);
930 case Mips::PseudoSDIV:
931 case Mips::PseudoUDIV:
936 return insertDivByZeroTrap(
937 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
938 case Mips::PseudoDSDIV:
939 case Mips::PseudoDUDIV:
944 return insertDivByZeroTrap(
945 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
947 return emitSEL_D(MI, BB);
949 case Mips::PseudoSELECT_I:
950 case Mips::PseudoSELECT_S:
951 case Mips::PseudoSELECT_D32:
952 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
953 case Mips::PseudoSELECTFP_F_I:
954 case Mips::PseudoSELECTFP_F_S:
955 case Mips::PseudoSELECTFP_F_D32:
956 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
957 case Mips::PseudoSELECTFP_T_I:
958 case Mips::PseudoSELECTFP_T_S:
959 case Mips::PseudoSELECTFP_T_D32:
960 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
964 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
965 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
967 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
968 unsigned Size, unsigned BinOpcode,
970 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
972 MachineFunction *MF = BB->getParent();
973 MachineRegisterInfo &RegInfo = MF->getRegInfo();
974 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
975 const TargetInstrInfo *TII =
976 getTargetMachine().getSubtargetImpl()->getInstrInfo();
977 DebugLoc DL = MI->getDebugLoc();
978 unsigned LL, SC, AND, NOR, ZERO, BEQ;
985 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
986 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
993 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
994 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
997 ZERO = Mips::ZERO_64;
1001 unsigned OldVal = MI->getOperand(0).getReg();
1002 unsigned Ptr = MI->getOperand(1).getReg();
1003 unsigned Incr = MI->getOperand(2).getReg();
1005 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1006 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1007 unsigned Success = RegInfo.createVirtualRegister(RC);
1009 // insert new blocks after the current block
1010 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1011 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1012 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1013 MachineFunction::iterator It = BB;
1015 MF->insert(It, loopMBB);
1016 MF->insert(It, exitMBB);
1018 // Transfer the remainder of BB and its successor edges to exitMBB.
1019 exitMBB->splice(exitMBB->begin(), BB,
1020 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1021 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1025 // fallthrough --> loopMBB
1026 BB->addSuccessor(loopMBB);
1027 loopMBB->addSuccessor(loopMBB);
1028 loopMBB->addSuccessor(exitMBB);
1031 // ll oldval, 0(ptr)
1032 // <binop> storeval, oldval, incr
1033 // sc success, storeval, 0(ptr)
1034 // beq success, $0, loopMBB
1036 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1038 // and andres, oldval, incr
1039 // nor storeval, $0, andres
1040 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1041 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1042 } else if (BinOpcode) {
1043 // <binop> storeval, oldval, incr
1044 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1048 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1049 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1051 MI->eraseFromParent(); // The instruction is gone now.
1056 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1057 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1058 unsigned SrcReg) const {
1059 const TargetInstrInfo *TII =
1060 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1061 DebugLoc DL = MI->getDebugLoc();
1063 if (Subtarget.hasMips32r2() && Size == 1) {
1064 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1068 if (Subtarget.hasMips32r2() && Size == 2) {
1069 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1073 MachineFunction *MF = BB->getParent();
1074 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1075 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1076 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1079 int64_t ShiftImm = 32 - (Size * 8);
1081 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1082 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1087 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1088 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1090 assert((Size == 1 || Size == 2) &&
1091 "Unsupported size for EmitAtomicBinaryPartial.");
1093 MachineFunction *MF = BB->getParent();
1094 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1095 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1096 const TargetInstrInfo *TII =
1097 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1098 DebugLoc DL = MI->getDebugLoc();
1100 unsigned Dest = MI->getOperand(0).getReg();
1101 unsigned Ptr = MI->getOperand(1).getReg();
1102 unsigned Incr = MI->getOperand(2).getReg();
1104 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1105 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1106 unsigned Mask = RegInfo.createVirtualRegister(RC);
1107 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1108 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1109 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1110 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1111 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1112 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1113 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1114 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1115 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1116 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1117 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1118 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1119 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1120 unsigned Success = RegInfo.createVirtualRegister(RC);
1122 // insert new blocks after the current block
1123 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1124 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1125 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1126 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1127 MachineFunction::iterator It = BB;
1129 MF->insert(It, loopMBB);
1130 MF->insert(It, sinkMBB);
1131 MF->insert(It, exitMBB);
1133 // Transfer the remainder of BB and its successor edges to exitMBB.
1134 exitMBB->splice(exitMBB->begin(), BB,
1135 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1136 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1138 BB->addSuccessor(loopMBB);
1139 loopMBB->addSuccessor(loopMBB);
1140 loopMBB->addSuccessor(sinkMBB);
1141 sinkMBB->addSuccessor(exitMBB);
1144 // addiu masklsb2,$0,-4 # 0xfffffffc
1145 // and alignedaddr,ptr,masklsb2
1146 // andi ptrlsb2,ptr,3
1147 // sll shiftamt,ptrlsb2,3
1148 // ori maskupper,$0,255 # 0xff
1149 // sll mask,maskupper,shiftamt
1150 // nor mask2,$0,mask
1151 // sll incr2,incr,shiftamt
1153 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1154 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1155 .addReg(Mips::ZERO).addImm(-4);
1156 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1157 .addReg(Ptr).addReg(MaskLSB2);
1158 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1159 if (Subtarget.isLittle()) {
1160 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1162 unsigned Off = RegInfo.createVirtualRegister(RC);
1163 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1164 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1165 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1167 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1168 .addReg(Mips::ZERO).addImm(MaskImm);
1169 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1170 .addReg(MaskUpper).addReg(ShiftAmt);
1171 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1172 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1174 // atomic.load.binop
1176 // ll oldval,0(alignedaddr)
1177 // binop binopres,oldval,incr2
1178 // and newval,binopres,mask
1179 // and maskedoldval0,oldval,mask2
1180 // or storeval,maskedoldval0,newval
1181 // sc success,storeval,0(alignedaddr)
1182 // beq success,$0,loopMBB
1186 // ll oldval,0(alignedaddr)
1187 // and newval,incr2,mask
1188 // and maskedoldval0,oldval,mask2
1189 // or storeval,maskedoldval0,newval
1190 // sc success,storeval,0(alignedaddr)
1191 // beq success,$0,loopMBB
1194 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1196 // and andres, oldval, incr2
1197 // nor binopres, $0, andres
1198 // and newval, binopres, mask
1199 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1200 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1201 .addReg(Mips::ZERO).addReg(AndRes);
1202 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1203 } else if (BinOpcode) {
1204 // <binop> binopres, oldval, incr2
1205 // and newval, binopres, mask
1206 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1207 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1208 } else { // atomic.swap
1209 // and newval, incr2, mask
1210 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1213 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1214 .addReg(OldVal).addReg(Mask2);
1215 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1216 .addReg(MaskedOldVal0).addReg(NewVal);
1217 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1218 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1219 BuildMI(BB, DL, TII->get(Mips::BEQ))
1220 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1223 // and maskedoldval1,oldval,mask
1224 // srl srlres,maskedoldval1,shiftamt
1225 // sign_extend dest,srlres
1228 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1229 .addReg(OldVal).addReg(Mask);
1230 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1231 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1232 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1234 MI->eraseFromParent(); // The instruction is gone now.
1239 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1240 MachineBasicBlock *BB,
1241 unsigned Size) const {
1242 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1244 MachineFunction *MF = BB->getParent();
1245 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1246 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1247 const TargetInstrInfo *TII =
1248 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1249 DebugLoc DL = MI->getDebugLoc();
1250 unsigned LL, SC, ZERO, BNE, BEQ;
1253 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1254 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1261 ZERO = Mips::ZERO_64;
1266 unsigned Dest = MI->getOperand(0).getReg();
1267 unsigned Ptr = MI->getOperand(1).getReg();
1268 unsigned OldVal = MI->getOperand(2).getReg();
1269 unsigned NewVal = MI->getOperand(3).getReg();
1271 unsigned Success = RegInfo.createVirtualRegister(RC);
1273 // insert new blocks after the current block
1274 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1275 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1278 MachineFunction::iterator It = BB;
1280 MF->insert(It, loop1MBB);
1281 MF->insert(It, loop2MBB);
1282 MF->insert(It, exitMBB);
1284 // Transfer the remainder of BB and its successor edges to exitMBB.
1285 exitMBB->splice(exitMBB->begin(), BB,
1286 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1287 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1291 // fallthrough --> loop1MBB
1292 BB->addSuccessor(loop1MBB);
1293 loop1MBB->addSuccessor(exitMBB);
1294 loop1MBB->addSuccessor(loop2MBB);
1295 loop2MBB->addSuccessor(loop1MBB);
1296 loop2MBB->addSuccessor(exitMBB);
1300 // bne dest, oldval, exitMBB
1302 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1303 BuildMI(BB, DL, TII->get(BNE))
1304 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1307 // sc success, newval, 0(ptr)
1308 // beq success, $0, loop1MBB
1310 BuildMI(BB, DL, TII->get(SC), Success)
1311 .addReg(NewVal).addReg(Ptr).addImm(0);
1312 BuildMI(BB, DL, TII->get(BEQ))
1313 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1315 MI->eraseFromParent(); // The instruction is gone now.
1321 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1322 MachineBasicBlock *BB,
1323 unsigned Size) const {
1324 assert((Size == 1 || Size == 2) &&
1325 "Unsupported size for EmitAtomicCmpSwapPartial.");
1327 MachineFunction *MF = BB->getParent();
1328 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1329 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1330 const TargetInstrInfo *TII =
1331 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1332 DebugLoc DL = MI->getDebugLoc();
1334 unsigned Dest = MI->getOperand(0).getReg();
1335 unsigned Ptr = MI->getOperand(1).getReg();
1336 unsigned CmpVal = MI->getOperand(2).getReg();
1337 unsigned NewVal = MI->getOperand(3).getReg();
1339 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1340 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1341 unsigned Mask = RegInfo.createVirtualRegister(RC);
1342 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1343 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1344 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1345 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1346 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1347 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1348 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1349 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1350 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1351 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1352 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1353 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1354 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1355 unsigned Success = RegInfo.createVirtualRegister(RC);
1357 // insert new blocks after the current block
1358 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1359 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1360 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1361 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1362 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1363 MachineFunction::iterator It = BB;
1365 MF->insert(It, loop1MBB);
1366 MF->insert(It, loop2MBB);
1367 MF->insert(It, sinkMBB);
1368 MF->insert(It, exitMBB);
1370 // Transfer the remainder of BB and its successor edges to exitMBB.
1371 exitMBB->splice(exitMBB->begin(), BB,
1372 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1373 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1375 BB->addSuccessor(loop1MBB);
1376 loop1MBB->addSuccessor(sinkMBB);
1377 loop1MBB->addSuccessor(loop2MBB);
1378 loop2MBB->addSuccessor(loop1MBB);
1379 loop2MBB->addSuccessor(sinkMBB);
1380 sinkMBB->addSuccessor(exitMBB);
1382 // FIXME: computation of newval2 can be moved to loop2MBB.
1384 // addiu masklsb2,$0,-4 # 0xfffffffc
1385 // and alignedaddr,ptr,masklsb2
1386 // andi ptrlsb2,ptr,3
1387 // sll shiftamt,ptrlsb2,3
1388 // ori maskupper,$0,255 # 0xff
1389 // sll mask,maskupper,shiftamt
1390 // nor mask2,$0,mask
1391 // andi maskedcmpval,cmpval,255
1392 // sll shiftedcmpval,maskedcmpval,shiftamt
1393 // andi maskednewval,newval,255
1394 // sll shiftednewval,maskednewval,shiftamt
1395 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1396 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1397 .addReg(Mips::ZERO).addImm(-4);
1398 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1399 .addReg(Ptr).addReg(MaskLSB2);
1400 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1401 if (Subtarget.isLittle()) {
1402 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1404 unsigned Off = RegInfo.createVirtualRegister(RC);
1405 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1406 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1407 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1409 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1410 .addReg(Mips::ZERO).addImm(MaskImm);
1411 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1412 .addReg(MaskUpper).addReg(ShiftAmt);
1413 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1414 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1415 .addReg(CmpVal).addImm(MaskImm);
1416 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1417 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1418 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1419 .addReg(NewVal).addImm(MaskImm);
1420 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1421 .addReg(MaskedNewVal).addReg(ShiftAmt);
1424 // ll oldval,0(alginedaddr)
1425 // and maskedoldval0,oldval,mask
1426 // bne maskedoldval0,shiftedcmpval,sinkMBB
1428 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1429 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1430 .addReg(OldVal).addReg(Mask);
1431 BuildMI(BB, DL, TII->get(Mips::BNE))
1432 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1435 // and maskedoldval1,oldval,mask2
1436 // or storeval,maskedoldval1,shiftednewval
1437 // sc success,storeval,0(alignedaddr)
1438 // beq success,$0,loop1MBB
1440 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1441 .addReg(OldVal).addReg(Mask2);
1442 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1443 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1444 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1445 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1446 BuildMI(BB, DL, TII->get(Mips::BEQ))
1447 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1450 // srl srlres,maskedoldval0,shiftamt
1451 // sign_extend dest,srlres
1454 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1455 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1456 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1458 MI->eraseFromParent(); // The instruction is gone now.
1463 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1464 MachineBasicBlock *BB) const {
1465 MachineFunction *MF = BB->getParent();
1466 const TargetRegisterInfo *TRI =
1467 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1468 const TargetInstrInfo *TII =
1469 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1470 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1471 DebugLoc DL = MI->getDebugLoc();
1472 MachineBasicBlock::iterator II(MI);
1474 unsigned Fc = MI->getOperand(1).getReg();
1475 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1477 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1479 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1482 .addImm(Mips::sub_lo);
1484 // We don't erase the original instruction, we just replace the condition
1485 // register with the 64-bit super-register.
1486 MI->getOperand(1).setReg(Fc2);
1491 //===----------------------------------------------------------------------===//
1492 // Misc Lower Operation implementation
1493 //===----------------------------------------------------------------------===//
1494 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1495 SDValue Chain = Op.getOperand(0);
1496 SDValue Table = Op.getOperand(1);
1497 SDValue Index = Op.getOperand(2);
1499 EVT PTy = getPointerTy();
1500 unsigned EntrySize =
1501 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1503 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1504 DAG.getConstant(EntrySize, PTy));
1505 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1507 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1508 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1509 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1511 Chain = Addr.getValue(1);
1513 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1514 Subtarget.isABI_N64()) {
1515 // For PIC, the sequence is:
1516 // BRIND(load(Jumptable + index) + RelocBase)
1517 // RelocBase can be JumpTable, GOT or some sort of global base.
1518 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1519 getPICJumpTableRelocBase(Table, DAG));
1522 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1525 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1526 // The first operand is the chain, the second is the condition, the third is
1527 // the block to branch to if the condition is true.
1528 SDValue Chain = Op.getOperand(0);
1529 SDValue Dest = Op.getOperand(2);
1532 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1533 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1535 // Return if flag is not set by a floating point comparison.
1536 if (CondRes.getOpcode() != MipsISD::FPCmp)
1539 SDValue CCNode = CondRes.getOperand(2);
1541 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1542 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1543 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1544 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1545 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1546 FCC0, Dest, CondRes);
1549 SDValue MipsTargetLowering::
1550 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1552 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1553 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1555 // Return if flag is not set by a floating point comparison.
1556 if (Cond.getOpcode() != MipsISD::FPCmp)
1559 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1563 SDValue MipsTargetLowering::
1564 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1567 EVT Ty = Op.getOperand(0).getValueType();
1568 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1569 getSetCCResultType(*DAG.getContext(), Ty),
1570 Op.getOperand(0), Op.getOperand(1),
1573 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1577 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1578 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1579 SDValue Cond = createFPCmp(DAG, Op);
1581 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1582 "Floating point operand expected.");
1584 SDValue True = DAG.getConstant(1, MVT::i32);
1585 SDValue False = DAG.getConstant(0, MVT::i32);
1587 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1590 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1591 SelectionDAG &DAG) const {
1592 EVT Ty = Op.getValueType();
1593 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1594 const GlobalValue *GV = N->getGlobal();
1596 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1597 !Subtarget.isABI_N64()) {
1598 const MipsTargetObjectFile &TLOF =
1599 (const MipsTargetObjectFile&)getObjFileLowering();
1601 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1602 // %gp_rel relocation
1603 return getAddrGPRel(N, Ty, DAG);
1605 // %hi/%lo relocation
1606 return getAddrNonPIC(N, Ty, DAG);
1609 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1610 return getAddrLocal(N, Ty, DAG,
1611 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1614 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1615 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1616 MachinePointerInfo::getGOT());
1618 return getAddrGlobal(N, Ty, DAG,
1619 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1620 ? MipsII::MO_GOT_DISP
1622 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1625 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1626 SelectionDAG &DAG) const {
1627 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1628 EVT Ty = Op.getValueType();
1630 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1631 !Subtarget.isABI_N64())
1632 return getAddrNonPIC(N, Ty, DAG);
1634 return getAddrLocal(N, Ty, DAG,
1635 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1638 SDValue MipsTargetLowering::
1639 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1641 // If the relocation model is PIC, use the General Dynamic TLS Model or
1642 // Local Dynamic TLS model, otherwise use the Initial Exec or
1643 // Local Exec TLS Model.
1645 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1647 const GlobalValue *GV = GA->getGlobal();
1648 EVT PtrVT = getPointerTy();
1650 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1652 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1653 // General Dynamic and Local Dynamic TLS Model.
1654 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1657 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1658 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1659 getGlobalReg(DAG, PtrVT), TGA);
1660 unsigned PtrSize = PtrVT.getSizeInBits();
1661 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1663 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1667 Entry.Node = Argument;
1669 Args.push_back(Entry);
1671 TargetLowering::CallLoweringInfo CLI(DAG);
1672 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1673 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1674 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1676 SDValue Ret = CallResult.first;
1678 if (model != TLSModel::LocalDynamic)
1681 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1682 MipsII::MO_DTPREL_HI);
1683 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1684 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1685 MipsII::MO_DTPREL_LO);
1686 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1687 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1688 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1692 if (model == TLSModel::InitialExec) {
1693 // Initial Exec TLS Model
1694 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1695 MipsII::MO_GOTTPREL);
1696 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1698 Offset = DAG.getLoad(PtrVT, DL,
1699 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1700 false, false, false, 0);
1702 // Local Exec TLS Model
1703 assert(model == TLSModel::LocalExec);
1704 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1705 MipsII::MO_TPREL_HI);
1706 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1707 MipsII::MO_TPREL_LO);
1708 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1709 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1710 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1713 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1714 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1717 SDValue MipsTargetLowering::
1718 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1720 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1721 EVT Ty = Op.getValueType();
1723 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1724 !Subtarget.isABI_N64())
1725 return getAddrNonPIC(N, Ty, DAG);
1727 return getAddrLocal(N, Ty, DAG,
1728 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1731 SDValue MipsTargetLowering::
1732 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1734 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1735 EVT Ty = Op.getValueType();
1737 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1738 !Subtarget.isABI_N64()) {
1739 const MipsTargetObjectFile &TLOF =
1740 (const MipsTargetObjectFile&)getObjFileLowering();
1742 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1743 // %gp_rel relocation
1744 return getAddrGPRel(N, Ty, DAG);
1746 return getAddrNonPIC(N, Ty, DAG);
1749 return getAddrLocal(N, Ty, DAG,
1750 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1753 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1754 MachineFunction &MF = DAG.getMachineFunction();
1755 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1758 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1761 // vastart just stores the address of the VarArgsFrameIndex slot into the
1762 // memory location argument.
1763 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1764 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1765 MachinePointerInfo(SV), false, false, 0);
1768 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1769 SDNode *Node = Op.getNode();
1770 EVT VT = Node->getValueType(0);
1771 SDValue Chain = Node->getOperand(0);
1772 SDValue VAListPtr = Node->getOperand(1);
1773 unsigned Align = Node->getConstantOperandVal(3);
1774 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1776 unsigned ArgSlotSizeInBytes =
1777 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1779 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1780 MachinePointerInfo(SV), false, false, false,
1782 SDValue VAList = VAListLoad;
1784 // Re-align the pointer if necessary.
1785 // It should only ever be necessary for 64-bit types on O32 since the minimum
1786 // argument alignment is the same as the maximum type alignment for N32/N64.
1788 // FIXME: We currently align too often. The code generator doesn't notice
1789 // when the pointer is still aligned from the last va_arg (or pair of
1790 // va_args for the i64 on O32 case).
1791 if (Align > getMinStackArgumentAlignment()) {
1792 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1794 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1795 DAG.getConstant(Align - 1,
1796 VAList.getValueType()));
1798 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1799 DAG.getConstant(-(int64_t)Align,
1800 VAList.getValueType()));
1803 // Increment the pointer, VAList, to the next vaarg.
1804 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1805 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1806 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1807 VAList.getValueType()));
1808 // Store the incremented VAList to the legalized pointer
1809 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1810 MachinePointerInfo(SV), false, false, 0);
1812 // In big-endian mode we must adjust the pointer when the load size is smaller
1813 // than the argument slot size. We must also reduce the known alignment to
1814 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1815 // the correct half of the slot, and reduce the alignment from 8 (slot
1816 // alignment) down to 4 (type alignment).
1817 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1818 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1819 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1820 DAG.getIntPtrConstant(Adjustment));
1822 // Load the actual argument out of the pointer VAList
1823 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1827 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1828 bool HasExtractInsert) {
1829 EVT TyX = Op.getOperand(0).getValueType();
1830 EVT TyY = Op.getOperand(1).getValueType();
1831 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1832 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1836 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1838 SDValue X = (TyX == MVT::f32) ?
1839 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1840 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1842 SDValue Y = (TyY == MVT::f32) ?
1843 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1844 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1847 if (HasExtractInsert) {
1848 // ext E, Y, 31, 1 ; extract bit31 of Y
1849 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1850 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1851 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1854 // srl SrlX, SllX, 1
1856 // sll SllY, SrlX, 31
1857 // or Or, SrlX, SllY
1858 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1859 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1860 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1861 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1862 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1865 if (TyX == MVT::f32)
1866 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1868 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1869 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1870 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1873 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1874 bool HasExtractInsert) {
1875 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1876 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1877 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1878 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1881 // Bitcast to integer nodes.
1882 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1883 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1885 if (HasExtractInsert) {
1886 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1887 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1888 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1889 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1891 if (WidthX > WidthY)
1892 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1893 else if (WidthY > WidthX)
1894 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1896 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1897 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1898 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1901 // (d)sll SllX, X, 1
1902 // (d)srl SrlX, SllX, 1
1903 // (d)srl SrlY, Y, width(Y)-1
1904 // (d)sll SllY, SrlX, width(Y)-1
1905 // or Or, SrlX, SllY
1906 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1907 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1908 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1909 DAG.getConstant(WidthY - 1, MVT::i32));
1911 if (WidthX > WidthY)
1912 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1913 else if (WidthY > WidthX)
1914 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1916 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1917 DAG.getConstant(WidthX - 1, MVT::i32));
1918 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1919 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1923 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1924 if (Subtarget.isGP64bit())
1925 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1927 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1930 SDValue MipsTargetLowering::
1931 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1933 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1934 "Frame address can only be determined for current frame.");
1936 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1937 MFI->setFrameAddressIsTaken(true);
1938 EVT VT = Op.getValueType();
1941 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1942 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
1946 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1947 SelectionDAG &DAG) const {
1948 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1952 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1953 "Return address can be determined only for current frame.");
1955 MachineFunction &MF = DAG.getMachineFunction();
1956 MachineFrameInfo *MFI = MF.getFrameInfo();
1957 MVT VT = Op.getSimpleValueType();
1958 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
1959 MFI->setReturnAddressIsTaken(true);
1961 // Return RA, which contains the return address. Mark it an implicit live-in.
1962 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1963 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1966 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1967 // generated from __builtin_eh_return (offset, handler)
1968 // The effect of this is to adjust the stack pointer by "offset"
1969 // and then branch to "handler".
1970 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1972 MachineFunction &MF = DAG.getMachineFunction();
1973 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1975 MipsFI->setCallsEhReturn();
1976 SDValue Chain = Op.getOperand(0);
1977 SDValue Offset = Op.getOperand(1);
1978 SDValue Handler = Op.getOperand(2);
1980 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
1982 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1983 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1984 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
1985 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
1986 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1987 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1988 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1989 DAG.getRegister(OffsetReg, Ty),
1990 DAG.getRegister(AddrReg, getPointerTy()),
1994 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1995 SelectionDAG &DAG) const {
1996 // FIXME: Need pseudo-fence for 'singlethread' fences
1997 // FIXME: Set SType for weaker fences where supported/appropriate.
2000 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2001 DAG.getConstant(SType, MVT::i32));
2004 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2005 SelectionDAG &DAG) const {
2007 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2008 SDValue Shamt = Op.getOperand(2);
2011 // lo = (shl lo, shamt)
2012 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2015 // hi = (shl lo, shamt[4:0])
2016 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2017 DAG.getConstant(-1, MVT::i32));
2018 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2019 DAG.getConstant(1, MVT::i32));
2020 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2022 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2023 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2024 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2025 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2026 DAG.getConstant(0x20, MVT::i32));
2027 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2028 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2029 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2031 SDValue Ops[2] = {Lo, Hi};
2032 return DAG.getMergeValues(Ops, DL);
2035 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2038 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2039 SDValue Shamt = Op.getOperand(2);
2042 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2044 // hi = (sra hi, shamt)
2046 // hi = (srl hi, shamt)
2049 // lo = (sra hi, shamt[4:0])
2050 // hi = (sra hi, 31)
2052 // lo = (srl hi, shamt[4:0])
2054 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2055 DAG.getConstant(-1, MVT::i32));
2056 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2057 DAG.getConstant(1, MVT::i32));
2058 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2059 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2060 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2061 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2063 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2064 DAG.getConstant(0x20, MVT::i32));
2065 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2066 DAG.getConstant(31, MVT::i32));
2067 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2068 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2069 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2072 SDValue Ops[2] = {Lo, Hi};
2073 return DAG.getMergeValues(Ops, DL);
2076 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2077 SDValue Chain, SDValue Src, unsigned Offset) {
2078 SDValue Ptr = LD->getBasePtr();
2079 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2080 EVT BasePtrVT = Ptr.getValueType();
2082 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2085 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2086 DAG.getConstant(Offset, BasePtrVT));
2088 SDValue Ops[] = { Chain, Ptr, Src };
2089 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2090 LD->getMemOperand());
2093 // Expand an unaligned 32 or 64-bit integer load node.
2094 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2095 LoadSDNode *LD = cast<LoadSDNode>(Op);
2096 EVT MemVT = LD->getMemoryVT();
2098 if (Subtarget.systemSupportsUnalignedAccess())
2101 // Return if load is aligned or if MemVT is neither i32 nor i64.
2102 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2103 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2106 bool IsLittle = Subtarget.isLittle();
2107 EVT VT = Op.getValueType();
2108 ISD::LoadExtType ExtType = LD->getExtensionType();
2109 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2111 assert((VT == MVT::i32) || (VT == MVT::i64));
2114 // (set dst, (i64 (load baseptr)))
2116 // (set tmp, (ldl (add baseptr, 7), undef))
2117 // (set dst, (ldr baseptr, tmp))
2118 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2119 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2121 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2125 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2127 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2131 // (set dst, (i32 (load baseptr))) or
2132 // (set dst, (i64 (sextload baseptr))) or
2133 // (set dst, (i64 (extload baseptr)))
2135 // (set tmp, (lwl (add baseptr, 3), undef))
2136 // (set dst, (lwr baseptr, tmp))
2137 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2138 (ExtType == ISD::EXTLOAD))
2141 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2144 // (set dst, (i64 (zextload baseptr)))
2146 // (set tmp0, (lwl (add baseptr, 3), undef))
2147 // (set tmp1, (lwr baseptr, tmp0))
2148 // (set tmp2, (shl tmp1, 32))
2149 // (set dst, (srl tmp2, 32))
2151 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2152 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2153 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2154 SDValue Ops[] = { SRL, LWR.getValue(1) };
2155 return DAG.getMergeValues(Ops, DL);
2158 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2159 SDValue Chain, unsigned Offset) {
2160 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2161 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2163 SDVTList VTList = DAG.getVTList(MVT::Other);
2166 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2167 DAG.getConstant(Offset, BasePtrVT));
2169 SDValue Ops[] = { Chain, Value, Ptr };
2170 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2171 SD->getMemOperand());
2174 // Expand an unaligned 32 or 64-bit integer store node.
2175 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2177 SDValue Value = SD->getValue(), Chain = SD->getChain();
2178 EVT VT = Value.getValueType();
2181 // (store val, baseptr) or
2182 // (truncstore val, baseptr)
2184 // (swl val, (add baseptr, 3))
2185 // (swr val, baseptr)
2186 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2187 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2189 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2192 assert(VT == MVT::i64);
2195 // (store val, baseptr)
2197 // (sdl val, (add baseptr, 7))
2198 // (sdr val, baseptr)
2199 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2200 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2203 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2204 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2205 SDValue Val = SD->getValue();
2207 if (Val.getOpcode() != ISD::FP_TO_SINT)
2210 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2211 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2214 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2215 SD->getPointerInfo(), SD->isVolatile(),
2216 SD->isNonTemporal(), SD->getAlignment());
2219 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2220 StoreSDNode *SD = cast<StoreSDNode>(Op);
2221 EVT MemVT = SD->getMemoryVT();
2223 // Lower unaligned integer stores.
2224 if (!Subtarget.systemSupportsUnalignedAccess() &&
2225 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2226 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2227 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2229 return lowerFP_TO_SINT_STORE(SD, DAG);
2232 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2233 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2234 || cast<ConstantSDNode>
2235 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2236 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2240 // (add (frameaddr 0), (frame_to_args_offset))
2241 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2242 // (add FrameObject, 0)
2243 // where FrameObject is a fixed StackObject with offset 0 which points to
2244 // the old stack pointer.
2245 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2246 EVT ValTy = Op->getValueType(0);
2247 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2248 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2249 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2250 DAG.getConstant(0, ValTy));
2253 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2254 SelectionDAG &DAG) const {
2255 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2256 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2258 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2261 //===----------------------------------------------------------------------===//
2262 // Calling Convention Implementation
2263 //===----------------------------------------------------------------------===//
2265 //===----------------------------------------------------------------------===//
2266 // TODO: Implement a generic logic using tblgen that can support this.
2267 // Mips O32 ABI rules:
2269 // i32 - Passed in A0, A1, A2, A3 and stack
2270 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2271 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2272 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2273 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2274 // not used, it must be shadowed. If only A3 is available, shadow it and
2277 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2278 //===----------------------------------------------------------------------===//
2280 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2281 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2282 CCState &State, const MCPhysReg *F64Regs) {
2283 const MipsSubtarget &Subtarget =
2284 State.getMachineFunction().getTarget()
2285 .getSubtarget<const MipsSubtarget>();
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 (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2298 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2300 if (ArgFlags.isSExt())
2301 LocInfo = CCValAssign::SExtUpper;
2302 else if (ArgFlags.isZExt())
2303 LocInfo = CCValAssign::ZExtUpper;
2305 LocInfo = CCValAssign::AExtUpper;
2309 // Promote i8 and i16
2310 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2312 if (ArgFlags.isSExt())
2313 LocInfo = CCValAssign::SExt;
2314 else if (ArgFlags.isZExt())
2315 LocInfo = CCValAssign::ZExt;
2317 LocInfo = CCValAssign::AExt;
2322 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2323 // is true: function is vararg, argument is 3rd or higher, there is previous
2324 // argument which is not f32 or f64.
2325 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2326 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2327 unsigned OrigAlign = ArgFlags.getOrigAlign();
2328 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2330 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2331 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2332 // If this is the first part of an i64 arg,
2333 // the allocated register must be either A0 or A2.
2334 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2335 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2337 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2338 // Allocate int register and shadow next int register. If first
2339 // available register is Mips::A1 or Mips::A3, shadow it too.
2340 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2341 if (Reg == Mips::A1 || Reg == Mips::A3)
2342 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2343 State.AllocateReg(IntRegs, IntRegsSize);
2345 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2346 // we are guaranteed to find an available float register
2347 if (ValVT == MVT::f32) {
2348 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2349 // Shadow int register
2350 State.AllocateReg(IntRegs, IntRegsSize);
2352 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2353 // Shadow int registers
2354 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2355 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2356 State.AllocateReg(IntRegs, IntRegsSize);
2357 State.AllocateReg(IntRegs, IntRegsSize);
2360 llvm_unreachable("Cannot handle this ValVT.");
2363 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2365 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2367 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2372 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2373 MVT LocVT, CCValAssign::LocInfo LocInfo,
2374 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2375 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2377 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2380 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2381 MVT LocVT, CCValAssign::LocInfo LocInfo,
2382 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2383 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2385 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2388 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2389 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2390 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2392 #include "MipsGenCallingConv.inc"
2394 //===----------------------------------------------------------------------===//
2395 // Call Calling Convention Implementation
2396 //===----------------------------------------------------------------------===//
2398 // Return next O32 integer argument register.
2399 static unsigned getNextIntArgReg(unsigned Reg) {
2400 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2401 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2405 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2406 SDValue Chain, SDValue Arg, SDLoc DL,
2407 bool IsTailCall, SelectionDAG &DAG) const {
2409 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2410 DAG.getIntPtrConstant(Offset));
2411 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2415 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2416 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2417 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2418 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2419 /*isVolatile=*/ true, false, 0);
2422 void MipsTargetLowering::
2423 getOpndList(SmallVectorImpl<SDValue> &Ops,
2424 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2425 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2426 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2427 SDValue Chain) const {
2428 // Insert node "GP copy globalreg" before call to function.
2430 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2431 // in PIC mode) allow symbols to be resolved via lazy binding.
2432 // The lazy binding stub requires GP to point to the GOT.
2433 // Note that we don't need GP to point to the GOT for indirect calls
2434 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2435 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2436 // used for the function (that is, Mips linker doesn't generate lazy binding
2437 // stub for a function whose address is taken in the program).
2438 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2439 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2440 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2441 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2444 // Build a sequence of copy-to-reg nodes chained together with token
2445 // chain and flag operands which copy the outgoing args into registers.
2446 // The InFlag in necessary since all emitted instructions must be
2450 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2451 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2452 RegsToPass[i].second, InFlag);
2453 InFlag = Chain.getValue(1);
2456 // Add argument registers to the end of the list so that they are
2457 // known live into the call.
2458 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2459 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2460 RegsToPass[i].second.getValueType()));
2462 // Add a register mask operand representing the call-preserved registers.
2463 const TargetRegisterInfo *TRI =
2464 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2465 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2466 assert(Mask && "Missing call preserved mask for calling convention");
2467 if (Subtarget.inMips16HardFloat()) {
2468 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2469 llvm::StringRef Sym = G->getGlobal()->getName();
2470 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2471 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2472 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2476 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2478 if (InFlag.getNode())
2479 Ops.push_back(InFlag);
2482 /// LowerCall - functions arguments are copied from virtual regs to
2483 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2485 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2486 SmallVectorImpl<SDValue> &InVals) const {
2487 SelectionDAG &DAG = CLI.DAG;
2489 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2490 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2491 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2492 SDValue Chain = CLI.Chain;
2493 SDValue Callee = CLI.Callee;
2494 bool &IsTailCall = CLI.IsTailCall;
2495 CallingConv::ID CallConv = CLI.CallConv;
2496 bool IsVarArg = CLI.IsVarArg;
2498 MachineFunction &MF = DAG.getMachineFunction();
2499 MachineFrameInfo *MFI = MF.getFrameInfo();
2500 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2501 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2502 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2504 // Analyze operands of the call, assigning locations to each operand.
2505 SmallVector<CCValAssign, 16> ArgLocs;
2507 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2508 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2510 // Allocate the reserved argument area. It seems strange to do this from the
2511 // caller side but removing it breaks the frame size calculation.
2512 const MipsABIInfo &ABI = Subtarget.getABI();
2513 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2515 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2517 // Get a count of how many bytes are to be pushed on the stack.
2518 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2520 // Check if it's really possible to do a tail call.
2522 IsTailCall = isEligibleForTailCallOptimization(
2523 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2525 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2526 report_fatal_error("failed to perform tail call elimination on a call "
2527 "site marked musttail");
2532 // Chain is the output chain of the last Load/Store or CopyToReg node.
2533 // ByValChain is the output chain of the last Memcpy node created for copying
2534 // byval arguments to the stack.
2535 unsigned StackAlignment = TFL->getStackAlignment();
2536 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2537 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2540 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2542 SDValue StackPtr = DAG.getCopyFromReg(
2543 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2546 // With EABI is it possible to have 16 args on registers.
2547 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2548 SmallVector<SDValue, 8> MemOpChains;
2550 CCInfo.rewindByValRegsInfo();
2552 // Walk the register/memloc assignments, inserting copies/loads.
2553 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2554 SDValue Arg = OutVals[i];
2555 CCValAssign &VA = ArgLocs[i];
2556 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2557 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2558 bool UseUpperBits = false;
2561 if (Flags.isByVal()) {
2562 unsigned FirstByValReg, LastByValReg;
2563 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2564 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2566 assert(Flags.getByValSize() &&
2567 "ByVal args of size 0 should have been ignored by front-end.");
2568 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2569 assert(!IsTailCall &&
2570 "Do not tail-call optimize if there is a byval argument.");
2571 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2572 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2574 CCInfo.nextInRegsParam();
2578 // Promote the value if needed.
2579 switch (VA.getLocInfo()) {
2581 llvm_unreachable("Unknown loc info!");
2582 case CCValAssign::Full:
2583 if (VA.isRegLoc()) {
2584 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2585 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2586 (ValVT == MVT::i64 && LocVT == MVT::f64))
2587 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2588 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2589 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2590 Arg, DAG.getConstant(0, MVT::i32));
2591 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2592 Arg, DAG.getConstant(1, MVT::i32));
2593 if (!Subtarget.isLittle())
2595 unsigned LocRegLo = VA.getLocReg();
2596 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2597 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2598 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2603 case CCValAssign::BCvt:
2604 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2606 case CCValAssign::SExtUpper:
2607 UseUpperBits = true;
2609 case CCValAssign::SExt:
2610 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2612 case CCValAssign::ZExtUpper:
2613 UseUpperBits = true;
2615 case CCValAssign::ZExt:
2616 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2618 case CCValAssign::AExtUpper:
2619 UseUpperBits = true;
2621 case CCValAssign::AExt:
2622 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2627 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2628 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2630 ISD::SHL, DL, VA.getLocVT(), Arg,
2631 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2634 // Arguments that can be passed on register must be kept at
2635 // RegsToPass vector
2636 if (VA.isRegLoc()) {
2637 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2641 // Register can't get to this point...
2642 assert(VA.isMemLoc());
2644 // emit ISD::STORE whichs stores the
2645 // parameter value to a stack Location
2646 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2647 Chain, Arg, DL, IsTailCall, DAG));
2650 // Transform all store nodes into one single node because all store
2651 // nodes are independent of each other.
2652 if (!MemOpChains.empty())
2653 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2655 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2656 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2657 // node so that legalize doesn't hack it.
2659 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2661 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2663 EVT Ty = Callee.getValueType();
2665 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2667 const GlobalValue *Val = G->getGlobal();
2668 InternalLinkage = Val->hasInternalLinkage();
2670 if (InternalLinkage)
2671 Callee = getAddrLocal(G, Ty, DAG,
2672 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2673 else if (LargeGOT) {
2674 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2675 MipsII::MO_CALL_LO16, Chain,
2676 FuncInfo->callPtrInfo(Val));
2679 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2680 FuncInfo->callPtrInfo(Val));
2684 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2685 MipsII::MO_NO_FLAG);
2686 GlobalOrExternal = true;
2688 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2689 const char *Sym = S->getSymbol();
2691 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2692 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2693 MipsII::MO_NO_FLAG);
2694 else if (LargeGOT) {
2695 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2696 MipsII::MO_CALL_LO16, Chain,
2697 FuncInfo->callPtrInfo(Sym));
2699 } else { // N64 || PIC
2700 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2701 FuncInfo->callPtrInfo(Sym));
2705 GlobalOrExternal = true;
2708 SmallVector<SDValue, 8> Ops(1, Chain);
2709 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2711 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2712 IsCallReloc, CLI, Callee, Chain);
2715 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2717 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2718 SDValue InFlag = Chain.getValue(1);
2720 // Create the CALLSEQ_END node.
2721 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2722 DAG.getIntPtrConstant(0, true), InFlag, DL);
2723 InFlag = Chain.getValue(1);
2725 // Handle result values, copying them out of physregs into vregs that we
2727 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2731 /// LowerCallResult - Lower the result values of a call into the
2732 /// appropriate copies out of appropriate physical registers.
2733 SDValue MipsTargetLowering::LowerCallResult(
2734 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2735 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2736 SmallVectorImpl<SDValue> &InVals,
2737 TargetLowering::CallLoweringInfo &CLI) const {
2738 // Assign locations to each value returned by this call.
2739 SmallVector<CCValAssign, 16> RVLocs;
2740 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2742 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2744 // Copy all of the result registers out of their specified physreg.
2745 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2746 CCValAssign &VA = RVLocs[i];
2747 assert(VA.isRegLoc() && "Can only return in registers!");
2749 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2750 RVLocs[i].getLocVT(), InFlag);
2751 Chain = Val.getValue(1);
2752 InFlag = Val.getValue(2);
2754 if (VA.isUpperBitsInLoc()) {
2755 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2756 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2758 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2760 Shift, DL, VA.getLocVT(), Val,
2761 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2764 switch (VA.getLocInfo()) {
2766 llvm_unreachable("Unknown loc info!");
2767 case CCValAssign::Full:
2769 case CCValAssign::BCvt:
2770 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2772 case CCValAssign::AExt:
2773 case CCValAssign::AExtUpper:
2774 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2776 case CCValAssign::ZExt:
2777 case CCValAssign::ZExtUpper:
2778 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2779 DAG.getValueType(VA.getValVT()));
2780 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2782 case CCValAssign::SExt:
2783 case CCValAssign::SExtUpper:
2784 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2785 DAG.getValueType(VA.getValVT()));
2786 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2790 InVals.push_back(Val);
2796 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2797 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2798 MVT LocVT = VA.getLocVT();
2799 EVT ValVT = VA.getValVT();
2801 // Shift into the upper bits if necessary.
2802 switch (VA.getLocInfo()) {
2805 case CCValAssign::AExtUpper:
2806 case CCValAssign::SExtUpper:
2807 case CCValAssign::ZExtUpper: {
2808 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2809 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2811 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2813 Opcode, DL, VA.getLocVT(), Val,
2814 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2819 // If this is an value smaller than the argument slot size (32-bit for O32,
2820 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2821 // size. Extract the value and insert any appropriate assertions regarding
2822 // sign/zero extension.
2823 switch (VA.getLocInfo()) {
2825 llvm_unreachable("Unknown loc info!");
2826 case CCValAssign::Full:
2828 case CCValAssign::AExtUpper:
2829 case CCValAssign::AExt:
2830 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2832 case CCValAssign::SExtUpper:
2833 case CCValAssign::SExt:
2834 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2835 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2837 case CCValAssign::ZExtUpper:
2838 case CCValAssign::ZExt:
2839 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2840 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2842 case CCValAssign::BCvt:
2843 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2850 //===----------------------------------------------------------------------===//
2851 // Formal Arguments Calling Convention Implementation
2852 //===----------------------------------------------------------------------===//
2853 /// LowerFormalArguments - transform physical registers into virtual registers
2854 /// and generate load operations for arguments places on the stack.
2856 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2857 CallingConv::ID CallConv,
2859 const SmallVectorImpl<ISD::InputArg> &Ins,
2860 SDLoc DL, SelectionDAG &DAG,
2861 SmallVectorImpl<SDValue> &InVals)
2863 MachineFunction &MF = DAG.getMachineFunction();
2864 MachineFrameInfo *MFI = MF.getFrameInfo();
2865 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2867 MipsFI->setVarArgsFrameIndex(0);
2869 // Used with vargs to acumulate store chains.
2870 std::vector<SDValue> OutChains;
2872 // Assign locations to all of the incoming arguments.
2873 SmallVector<CCValAssign, 16> ArgLocs;
2874 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2876 const MipsABIInfo &ABI = Subtarget.getABI();
2877 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2878 Function::const_arg_iterator FuncArg =
2879 DAG.getMachineFunction().getFunction()->arg_begin();
2881 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2882 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2883 CCInfo.getInRegsParamsCount() > 0);
2885 unsigned CurArgIdx = 0;
2886 CCInfo.rewindByValRegsInfo();
2888 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2889 CCValAssign &VA = ArgLocs[i];
2890 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2891 CurArgIdx = Ins[i].OrigArgIndex;
2892 EVT ValVT = VA.getValVT();
2893 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2894 bool IsRegLoc = VA.isRegLoc();
2896 if (Flags.isByVal()) {
2897 unsigned FirstByValReg, LastByValReg;
2898 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2899 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2901 assert(Flags.getByValSize() &&
2902 "ByVal args of size 0 should have been ignored by front-end.");
2903 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2904 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2905 FirstByValReg, LastByValReg, VA, CCInfo);
2906 CCInfo.nextInRegsParam();
2910 // Arguments stored on registers
2912 MVT RegVT = VA.getLocVT();
2913 unsigned ArgReg = VA.getLocReg();
2914 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2916 // Transform the arguments stored on
2917 // physical registers into virtual ones
2918 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2919 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2921 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2923 // Handle floating point arguments passed in integer registers and
2924 // long double arguments passed in floating point registers.
2925 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2926 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2927 (RegVT == MVT::f64 && ValVT == MVT::i64))
2928 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2929 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2930 ValVT == MVT::f64) {
2931 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2932 getNextIntArgReg(ArgReg), RC);
2933 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2934 if (!Subtarget.isLittle())
2935 std::swap(ArgValue, ArgValue2);
2936 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2937 ArgValue, ArgValue2);
2940 InVals.push_back(ArgValue);
2941 } else { // VA.isRegLoc()
2942 MVT LocVT = VA.getLocVT();
2944 if (Subtarget.isABI_O32()) {
2945 // We ought to be able to use LocVT directly but O32 sets it to i32
2946 // when allocating floating point values to integer registers.
2947 // This shouldn't influence how we load the value into registers unless
2948 // we are targetting softfloat.
2949 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2950 LocVT = VA.getValVT();
2954 assert(VA.isMemLoc());
2956 // The stack pointer offset is relative to the caller stack frame.
2957 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
2958 VA.getLocMemOffset(), true);
2960 // Create load nodes to retrieve arguments from the stack
2961 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2962 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2963 MachinePointerInfo::getFixedStack(FI),
2964 false, false, false, 0);
2965 OutChains.push_back(ArgValue.getValue(1));
2967 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2969 InVals.push_back(ArgValue);
2973 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2974 // The mips ABIs for returning structs by value requires that we copy
2975 // the sret argument into $v0 for the return. Save the argument into
2976 // a virtual register so that we can access it from the return points.
2977 if (Ins[i].Flags.isSRet()) {
2978 unsigned Reg = MipsFI->getSRetReturnReg();
2980 Reg = MF.getRegInfo().createVirtualRegister(
2981 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2982 MipsFI->setSRetReturnReg(Reg);
2984 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2985 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2991 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
2993 // All stores are grouped in one node to allow the matching between
2994 // the size of Ins and InVals. This only happens when on varg functions
2995 if (!OutChains.empty()) {
2996 OutChains.push_back(Chain);
2997 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3003 //===----------------------------------------------------------------------===//
3004 // Return Value Calling Convention Implementation
3005 //===----------------------------------------------------------------------===//
3008 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3009 MachineFunction &MF, bool IsVarArg,
3010 const SmallVectorImpl<ISD::OutputArg> &Outs,
3011 LLVMContext &Context) const {
3012 SmallVector<CCValAssign, 16> RVLocs;
3013 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3014 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3018 MipsTargetLowering::LowerReturn(SDValue Chain,
3019 CallingConv::ID CallConv, bool IsVarArg,
3020 const SmallVectorImpl<ISD::OutputArg> &Outs,
3021 const SmallVectorImpl<SDValue> &OutVals,
3022 SDLoc DL, SelectionDAG &DAG) const {
3023 // CCValAssign - represent the assignment of
3024 // the return value to a location
3025 SmallVector<CCValAssign, 16> RVLocs;
3026 MachineFunction &MF = DAG.getMachineFunction();
3028 // CCState - Info about the registers and stack slot.
3029 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3031 // Analyze return values.
3032 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3035 SmallVector<SDValue, 4> RetOps(1, Chain);
3037 // Copy the result values into the output registers.
3038 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3039 SDValue Val = OutVals[i];
3040 CCValAssign &VA = RVLocs[i];
3041 assert(VA.isRegLoc() && "Can only return in registers!");
3042 bool UseUpperBits = false;
3044 switch (VA.getLocInfo()) {
3046 llvm_unreachable("Unknown loc info!");
3047 case CCValAssign::Full:
3049 case CCValAssign::BCvt:
3050 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3052 case CCValAssign::AExtUpper:
3053 UseUpperBits = true;
3055 case CCValAssign::AExt:
3056 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3058 case CCValAssign::ZExtUpper:
3059 UseUpperBits = true;
3061 case CCValAssign::ZExt:
3062 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3064 case CCValAssign::SExtUpper:
3065 UseUpperBits = true;
3067 case CCValAssign::SExt:
3068 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3073 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3074 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3076 ISD::SHL, DL, VA.getLocVT(), Val,
3077 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3080 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3082 // Guarantee that all emitted copies are stuck together with flags.
3083 Flag = Chain.getValue(1);
3084 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3087 // The mips ABIs for returning structs by value requires that we copy
3088 // the sret argument into $v0 for the return. We saved the argument into
3089 // a virtual register in the entry block, so now we copy the value out
3091 if (MF.getFunction()->hasStructRetAttr()) {
3092 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3093 unsigned Reg = MipsFI->getSRetReturnReg();
3096 llvm_unreachable("sret virtual register not created in the entry block");
3097 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3098 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3100 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3101 Flag = Chain.getValue(1);
3102 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3105 RetOps[0] = Chain; // Update chain.
3107 // Add the flag if we have it.
3109 RetOps.push_back(Flag);
3111 // Return on Mips is always a "jr $ra"
3112 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3115 //===----------------------------------------------------------------------===//
3116 // Mips Inline Assembly Support
3117 //===----------------------------------------------------------------------===//
3119 /// getConstraintType - Given a constraint letter, return the type of
3120 /// constraint it is for this target.
3121 MipsTargetLowering::ConstraintType MipsTargetLowering::
3122 getConstraintType(const std::string &Constraint) const
3124 // Mips specific constraints
3125 // GCC config/mips/constraints.md
3127 // 'd' : An address register. Equivalent to r
3128 // unless generating MIPS16 code.
3129 // 'y' : Equivalent to r; retained for
3130 // backwards compatibility.
3131 // 'c' : A register suitable for use in an indirect
3132 // jump. This will always be $25 for -mabicalls.
3133 // 'l' : The lo register. 1 word storage.
3134 // 'x' : The hilo register pair. Double word storage.
3135 if (Constraint.size() == 1) {
3136 switch (Constraint[0]) {
3144 return C_RegisterClass;
3149 return TargetLowering::getConstraintType(Constraint);
3152 /// Examine constraint type and operand type and determine a weight value.
3153 /// This object must already have been set up with the operand type
3154 /// and the current alternative constraint selected.
3155 TargetLowering::ConstraintWeight
3156 MipsTargetLowering::getSingleConstraintMatchWeight(
3157 AsmOperandInfo &info, const char *constraint) const {
3158 ConstraintWeight weight = CW_Invalid;
3159 Value *CallOperandVal = info.CallOperandVal;
3160 // If we don't have a value, we can't do a match,
3161 // but allow it at the lowest weight.
3162 if (!CallOperandVal)
3164 Type *type = CallOperandVal->getType();
3165 // Look at the constraint type.
3166 switch (*constraint) {
3168 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3172 if (type->isIntegerTy())
3173 weight = CW_Register;
3175 case 'f': // FPU or MSA register
3176 if (Subtarget.hasMSA() && type->isVectorTy() &&
3177 cast<VectorType>(type)->getBitWidth() == 128)
3178 weight = CW_Register;
3179 else if (type->isFloatTy())
3180 weight = CW_Register;
3182 case 'c': // $25 for indirect jumps
3183 case 'l': // lo register
3184 case 'x': // hilo register pair
3185 if (type->isIntegerTy())
3186 weight = CW_SpecificReg;
3188 case 'I': // signed 16 bit immediate
3189 case 'J': // integer zero
3190 case 'K': // unsigned 16 bit immediate
3191 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3192 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3193 case 'O': // signed 15 bit immediate (+- 16383)
3194 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3195 if (isa<ConstantInt>(CallOperandVal))
3196 weight = CW_Constant;
3205 /// This is a helper function to parse a physical register string and split it
3206 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3207 /// that is returned indicates whether parsing was successful. The second flag
3208 /// is true if the numeric part exists.
3209 static std::pair<bool, bool>
3210 parsePhysicalReg(StringRef C, std::string &Prefix,
3211 unsigned long long &Reg) {
3212 if (C.front() != '{' || C.back() != '}')
3213 return std::make_pair(false, false);
3215 // Search for the first numeric character.
3216 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3217 I = std::find_if(B, E, std::ptr_fun(isdigit));
3219 Prefix.assign(B, I - B);
3221 // The second flag is set to false if no numeric characters were found.
3223 return std::make_pair(true, false);
3225 // Parse the numeric characters.
3226 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3230 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3231 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3232 const TargetRegisterInfo *TRI =
3233 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3234 const TargetRegisterClass *RC;
3236 unsigned long long Reg;
3238 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3241 return std::make_pair(0U, nullptr);
3243 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3244 // No numeric characters follow "hi" or "lo".
3246 return std::make_pair(0U, nullptr);
3248 RC = TRI->getRegClass(Prefix == "hi" ?
3249 Mips::HI32RegClassID : Mips::LO32RegClassID);
3250 return std::make_pair(*(RC->begin()), RC);
3251 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3252 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3254 // No numeric characters follow the name.
3256 return std::make_pair(0U, nullptr);
3258 Reg = StringSwitch<unsigned long long>(Prefix)
3259 .Case("$msair", Mips::MSAIR)
3260 .Case("$msacsr", Mips::MSACSR)
3261 .Case("$msaaccess", Mips::MSAAccess)
3262 .Case("$msasave", Mips::MSASave)
3263 .Case("$msamodify", Mips::MSAModify)
3264 .Case("$msarequest", Mips::MSARequest)
3265 .Case("$msamap", Mips::MSAMap)
3266 .Case("$msaunmap", Mips::MSAUnmap)
3270 return std::make_pair(0U, nullptr);
3272 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3273 return std::make_pair(Reg, RC);
3277 return std::make_pair(0U, nullptr);
3279 if (Prefix == "$f") { // Parse $f0-$f31.
3280 // If the size of FP registers is 64-bit or Reg is an even number, select
3281 // the 64-bit register class. Otherwise, select the 32-bit register class.
3282 if (VT == MVT::Other)
3283 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3285 RC = getRegClassFor(VT);
3287 if (RC == &Mips::AFGR64RegClass) {
3288 assert(Reg % 2 == 0);
3291 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3292 RC = TRI->getRegClass(Mips::FCCRegClassID);
3293 else if (Prefix == "$w") { // Parse $w0-$w31.
3294 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3295 } else { // Parse $0-$31.
3296 assert(Prefix == "$");
3297 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3300 assert(Reg < RC->getNumRegs());
3301 return std::make_pair(*(RC->begin() + Reg), RC);
3304 /// Given a register class constraint, like 'r', if this corresponds directly
3305 /// to an LLVM register class, return a register of 0 and the register class
3307 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3308 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3310 if (Constraint.size() == 1) {
3311 switch (Constraint[0]) {
3312 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3313 case 'y': // Same as 'r'. Exists for compatibility.
3315 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3316 if (Subtarget.inMips16Mode())
3317 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3318 return std::make_pair(0U, &Mips::GPR32RegClass);
3320 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3321 return std::make_pair(0U, &Mips::GPR32RegClass);
3322 if (VT == MVT::i64 && Subtarget.isGP64bit())
3323 return std::make_pair(0U, &Mips::GPR64RegClass);
3324 // This will generate an error message
3325 return std::make_pair(0U, nullptr);
3326 case 'f': // FPU or MSA register
3327 if (VT == MVT::v16i8)
3328 return std::make_pair(0U, &Mips::MSA128BRegClass);
3329 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3330 return std::make_pair(0U, &Mips::MSA128HRegClass);
3331 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3332 return std::make_pair(0U, &Mips::MSA128WRegClass);
3333 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3334 return std::make_pair(0U, &Mips::MSA128DRegClass);
3335 else if (VT == MVT::f32)
3336 return std::make_pair(0U, &Mips::FGR32RegClass);
3337 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3338 if (Subtarget.isFP64bit())
3339 return std::make_pair(0U, &Mips::FGR64RegClass);
3340 return std::make_pair(0U, &Mips::AFGR64RegClass);
3343 case 'c': // register suitable for indirect jump
3345 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3346 assert(VT == MVT::i64 && "Unexpected type.");
3347 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3348 case 'l': // register suitable for indirect jump
3350 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3351 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3352 case 'x': // register suitable for indirect jump
3353 // Fixme: Not triggering the use of both hi and low
3354 // This will generate an error message
3355 return std::make_pair(0U, nullptr);
3359 std::pair<unsigned, const TargetRegisterClass *> R;
3360 R = parseRegForInlineAsmConstraint(Constraint, VT);
3365 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3368 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3369 /// vector. If it is invalid, don't add anything to Ops.
3370 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3371 std::string &Constraint,
3372 std::vector<SDValue>&Ops,
3373 SelectionDAG &DAG) const {
3376 // Only support length 1 constraints for now.
3377 if (Constraint.length() > 1) return;
3379 char ConstraintLetter = Constraint[0];
3380 switch (ConstraintLetter) {
3381 default: break; // This will fall through to the generic implementation
3382 case 'I': // Signed 16 bit constant
3383 // If this fails, the parent routine will give an error
3384 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3385 EVT Type = Op.getValueType();
3386 int64_t Val = C->getSExtValue();
3387 if (isInt<16>(Val)) {
3388 Result = DAG.getTargetConstant(Val, Type);
3393 case 'J': // integer zero
3394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3395 EVT Type = Op.getValueType();
3396 int64_t Val = C->getZExtValue();
3398 Result = DAG.getTargetConstant(0, Type);
3403 case 'K': // unsigned 16 bit immediate
3404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3405 EVT Type = Op.getValueType();
3406 uint64_t Val = (uint64_t)C->getZExtValue();
3407 if (isUInt<16>(Val)) {
3408 Result = DAG.getTargetConstant(Val, Type);
3413 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3415 EVT Type = Op.getValueType();
3416 int64_t Val = C->getSExtValue();
3417 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3418 Result = DAG.getTargetConstant(Val, Type);
3423 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3425 EVT Type = Op.getValueType();
3426 int64_t Val = C->getSExtValue();
3427 if ((Val >= -65535) && (Val <= -1)) {
3428 Result = DAG.getTargetConstant(Val, Type);
3433 case 'O': // signed 15 bit immediate
3434 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3435 EVT Type = Op.getValueType();
3436 int64_t Val = C->getSExtValue();
3437 if ((isInt<15>(Val))) {
3438 Result = DAG.getTargetConstant(Val, Type);
3443 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3445 EVT Type = Op.getValueType();
3446 int64_t Val = C->getSExtValue();
3447 if ((Val <= 65535) && (Val >= 1)) {
3448 Result = DAG.getTargetConstant(Val, Type);
3455 if (Result.getNode()) {
3456 Ops.push_back(Result);
3460 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3463 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3465 // No global is ever allowed as a base.
3470 case 0: // "r+i" or just "i", depending on HasBaseReg.
3473 if (!AM.HasBaseReg) // allow "r+i".
3475 return false; // disallow "r+r" or "r+r+i".
3484 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3485 // The Mips target isn't yet aware of offsets.
3489 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3491 bool IsMemset, bool ZeroMemset,
3493 MachineFunction &MF) const {
3494 if (Subtarget.hasMips64())
3500 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3501 if (VT != MVT::f32 && VT != MVT::f64)
3503 if (Imm.isNegZero())
3505 return Imm.isZero();
3508 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3509 if (Subtarget.isABI_N64())
3510 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3512 return TargetLowering::getJumpTableEncoding();
3515 void MipsTargetLowering::copyByValRegs(
3516 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3517 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3518 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3519 const CCValAssign &VA, MipsCCState &State) const {
3520 MachineFunction &MF = DAG.getMachineFunction();
3521 MachineFrameInfo *MFI = MF.getFrameInfo();
3522 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3523 unsigned NumRegs = LastReg - FirstReg;
3524 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3525 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3527 const MipsABIInfo &ABI = Subtarget.getABI();
3528 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3532 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3533 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3535 FrameObjOffset = VA.getLocMemOffset();
3537 // Create frame object.
3538 EVT PtrTy = getPointerTy();
3539 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3540 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3541 InVals.push_back(FIN);
3546 // Copy arg registers.
3547 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3548 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3550 for (unsigned I = 0; I < NumRegs; ++I) {
3551 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3552 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3553 unsigned Offset = I * GPRSizeInBytes;
3554 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3555 DAG.getConstant(Offset, PtrTy));
3556 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3557 StorePtr, MachinePointerInfo(FuncArg, Offset),
3559 OutChains.push_back(Store);
3563 // Copy byVal arg to registers and stack.
3564 void MipsTargetLowering::passByValArg(
3565 SDValue Chain, SDLoc DL,
3566 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3567 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3568 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3569 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3570 const CCValAssign &VA) const {
3571 unsigned ByValSizeInBytes = Flags.getByValSize();
3572 unsigned OffsetInBytes = 0; // From beginning of struct
3573 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3574 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3575 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3576 unsigned NumRegs = LastReg - FirstReg;
3579 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetByValArgRegs();
3580 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3583 // Copy words to registers.
3584 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3585 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3586 DAG.getConstant(OffsetInBytes, PtrTy));
3587 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3588 MachinePointerInfo(), false, false, false,
3590 MemOpChains.push_back(LoadVal.getValue(1));
3591 unsigned ArgReg = ArgRegs[FirstReg + I];
3592 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3595 // Return if the struct has been fully copied.
3596 if (ByValSizeInBytes == OffsetInBytes)
3599 // Copy the remainder of the byval argument with sub-word loads and shifts.
3600 if (LeftoverBytes) {
3603 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3604 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3605 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3607 if (RemainingSizeInBytes < LoadSizeInBytes)
3611 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3612 DAG.getConstant(OffsetInBytes, PtrTy));
3613 SDValue LoadVal = DAG.getExtLoad(
3614 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3615 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3617 MemOpChains.push_back(LoadVal.getValue(1));
3619 // Shift the loaded value.
3623 Shamt = TotalBytesLoaded * 8;
3625 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3627 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3628 DAG.getConstant(Shamt, MVT::i32));
3631 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3635 OffsetInBytes += LoadSizeInBytes;
3636 TotalBytesLoaded += LoadSizeInBytes;
3637 Alignment = std::min(Alignment, LoadSizeInBytes);
3640 unsigned ArgReg = ArgRegs[FirstReg + I];
3641 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3646 // Copy remainder of byval arg to it with memcpy.
3647 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3648 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3649 DAG.getConstant(OffsetInBytes, PtrTy));
3650 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3651 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3652 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3653 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3654 MachinePointerInfo(), MachinePointerInfo());
3655 MemOpChains.push_back(Chain);
3658 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3659 SDValue Chain, SDLoc DL,
3661 CCState &State) const {
3662 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetVarArgRegs();
3663 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3664 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3665 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3666 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3667 MachineFunction &MF = DAG.getMachineFunction();
3668 MachineFrameInfo *MFI = MF.getFrameInfo();
3669 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3671 // Offset of the first variable argument from stack pointer.
3674 if (ArgRegs.size() == Idx)
3676 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3678 const MipsABIInfo &ABI = Subtarget.getABI();
3680 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3681 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3684 // Record the frame index of the first variable argument
3685 // which is a value necessary to VASTART.
3686 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3687 MipsFI->setVarArgsFrameIndex(FI);
3689 // Copy the integer registers that have not been used for argument passing
3690 // to the argument register save area. For O32, the save area is allocated
3691 // in the caller's stack frame, while for N32/64, it is allocated in the
3692 // callee's stack frame.
3693 for (unsigned I = Idx; I < ArgRegs.size();
3694 ++I, VaArgOffset += RegSizeInBytes) {
3695 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3696 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3697 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3698 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3699 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3700 MachinePointerInfo(), false, false, 0);
3701 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3703 OutChains.push_back(Store);
3707 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3708 unsigned Align) const {
3709 MachineFunction &MF = State->getMachineFunction();
3710 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3712 assert(Size && "Byval argument's size shouldn't be 0.");
3714 Align = std::min(Align, TFL->getStackAlignment());
3716 unsigned FirstReg = 0;
3717 unsigned NumRegs = 0;
3719 if (State->getCallingConv() != CallingConv::Fast) {
3720 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3721 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3722 // FIXME: The O32 case actually describes no shadow registers.
3723 const MCPhysReg *ShadowRegs =
3724 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3726 // We used to check the size as well but we can't do that anymore since
3727 // CCState::HandleByVal() rounds up the size after calling this function.
3728 assert(!(Align % RegSizeInBytes) &&
3729 "Byval argument's alignment should be a multiple of"
3732 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3734 // If Align > RegSizeInBytes, the first arg register must be even.
3735 // FIXME: This condition happens to do the right thing but it's not the
3736 // right way to test it. We want to check that the stack frame offset
3737 // of the register is aligned.
3738 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3739 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3743 // Mark the registers allocated.
3744 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3745 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3746 Size -= RegSizeInBytes, ++I, ++NumRegs)
3747 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3750 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3754 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3755 bool isFPCmp, unsigned Opc) const {
3756 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3757 "Subtarget already supports SELECT nodes with the use of"
3758 "conditional-move instructions.");
3760 const TargetInstrInfo *TII =
3761 getTargetMachine().getSubtargetImpl()->getInstrInfo();
3762 DebugLoc DL = MI->getDebugLoc();
3764 // To "insert" a SELECT instruction, we actually have to insert the
3765 // diamond control-flow pattern. The incoming instruction knows the
3766 // destination vreg to set, the condition code register to branch on, the
3767 // true/false values to select between, and a branch opcode to use.
3768 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3769 MachineFunction::iterator It = BB;
3776 // bNE r1, r0, copy1MBB
3777 // fallthrough --> copy0MBB
3778 MachineBasicBlock *thisMBB = BB;
3779 MachineFunction *F = BB->getParent();
3780 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3781 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3782 F->insert(It, copy0MBB);
3783 F->insert(It, sinkMBB);
3785 // Transfer the remainder of BB and its successor edges to sinkMBB.
3786 sinkMBB->splice(sinkMBB->begin(), BB,
3787 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3788 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3790 // Next, add the true and fallthrough blocks as its successors.
3791 BB->addSuccessor(copy0MBB);
3792 BB->addSuccessor(sinkMBB);
3795 // bc1[tf] cc, sinkMBB
3796 BuildMI(BB, DL, TII->get(Opc))
3797 .addReg(MI->getOperand(1).getReg())
3800 // bne rs, $0, sinkMBB
3801 BuildMI(BB, DL, TII->get(Opc))
3802 .addReg(MI->getOperand(1).getReg())
3808 // %FalseValue = ...
3809 // # fallthrough to sinkMBB
3812 // Update machine-CFG edges
3813 BB->addSuccessor(sinkMBB);
3816 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3820 BuildMI(*BB, BB->begin(), DL,
3821 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3822 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3823 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3825 MI->eraseFromParent(); // The pseudo instruction is gone now.