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(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), ABI(TM.getABI()) {
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 for (MVT VT : MVT::integer_valuetypes()) {
219 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
221 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224 // MIPS doesn't have extending float->double load/store
225 for (MVT VT : MVT::fp_valuetypes())
226 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
229 // Used by legalize types to correctly generate the setcc result.
230 // Without this, every float setcc comes with a AND/OR with the result,
231 // we don't want this, since the fpcmp result goes to a flag register,
232 // which is used implicitly by brcond and select operations.
233 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
235 // Mips Custom Operations
236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
237 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
238 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
239 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
240 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
241 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT, MVT::f64, Custom);
244 setOperationAction(ISD::SELECT, MVT::i32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
246 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
247 setOperationAction(ISD::SETCC, MVT::f32, Custom);
248 setOperationAction(ISD::SETCC, MVT::f64, Custom);
249 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254 if (Subtarget.isGP64bit()) {
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
264 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
269 if (!Subtarget.isGP64bit()) {
270 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 if (Subtarget.isGP64bit())
277 setOperationAction(ISD::ADD, MVT::i64, Custom);
279 setOperationAction(ISD::SDIV, MVT::i32, Expand);
280 setOperationAction(ISD::SREM, MVT::i32, Expand);
281 setOperationAction(ISD::UDIV, MVT::i32, Expand);
282 setOperationAction(ISD::UREM, MVT::i32, Expand);
283 setOperationAction(ISD::SDIV, MVT::i64, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIV, MVT::i64, Expand);
286 setOperationAction(ISD::UREM, MVT::i64, Expand);
288 // Operations not directly supported by Mips.
289 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
293 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
295 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
297 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
300 if (Subtarget.hasCnMips()) {
301 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
302 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
304 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
305 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
307 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
308 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
309 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
310 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
311 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
312 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
313 setOperationAction(ISD::ROTL, MVT::i32, Expand);
314 setOperationAction(ISD::ROTL, MVT::i64, Expand);
315 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
318 if (!Subtarget.hasMips32r2())
319 setOperationAction(ISD::ROTR, MVT::i32, Expand);
321 if (!Subtarget.hasMips64r2())
322 setOperationAction(ISD::ROTR, MVT::i64, Expand);
324 setOperationAction(ISD::FSIN, MVT::f32, Expand);
325 setOperationAction(ISD::FSIN, MVT::f64, Expand);
326 setOperationAction(ISD::FCOS, MVT::f32, Expand);
327 setOperationAction(ISD::FCOS, MVT::f64, Expand);
328 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
330 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
331 setOperationAction(ISD::FPOW, MVT::f32, Expand);
332 setOperationAction(ISD::FPOW, MVT::f64, Expand);
333 setOperationAction(ISD::FLOG, MVT::f32, Expand);
334 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
335 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
336 setOperationAction(ISD::FEXP, MVT::f32, Expand);
337 setOperationAction(ISD::FMA, MVT::f32, Expand);
338 setOperationAction(ISD::FMA, MVT::f64, Expand);
339 setOperationAction(ISD::FREM, MVT::f32, Expand);
340 setOperationAction(ISD::FREM, MVT::f64, Expand);
342 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
344 setOperationAction(ISD::VASTART, MVT::Other, Custom);
345 setOperationAction(ISD::VAARG, MVT::Other, Custom);
346 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
347 setOperationAction(ISD::VAEND, MVT::Other, Expand);
349 // Use the default for now
350 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
351 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
353 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
355 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
358 setInsertFencesForAtomic(true);
360 if (!Subtarget.hasMips32r2()) {
361 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
365 // MIPS16 lacks MIPS32's clz and clo instructions.
366 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
367 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
368 if (!Subtarget.hasMips64())
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
371 if (!Subtarget.hasMips32r2())
372 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
373 if (!Subtarget.hasMips64r2())
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
376 if (Subtarget.isGP64bit()) {
377 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
378 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
379 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
380 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
383 setOperationAction(ISD::TRAP, MVT::Other, Legal);
385 setTargetDAGCombine(ISD::SDIVREM);
386 setTargetDAGCombine(ISD::UDIVREM);
387 setTargetDAGCombine(ISD::SELECT);
388 setTargetDAGCombine(ISD::AND);
389 setTargetDAGCombine(ISD::OR);
390 setTargetDAGCombine(ISD::ADD);
392 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
394 // The arguments on the stack are defined in terms of 4-byte slots on O32
395 // and 8-byte slots on N32/N64.
396 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
398 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
400 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
401 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
403 MaxStoresPerMemcpy = 16;
405 isMicroMips = Subtarget.inMicroMipsMode();
408 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
409 const MipsSubtarget &STI) {
410 if (STI.inMips16Mode())
411 return llvm::createMips16TargetLowering(TM, STI);
413 return llvm::createMipsSETargetLowering(TM, STI);
416 // Create a fast isel object.
418 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
419 const TargetLibraryInfo *libInfo) const {
420 if (!EnableMipsFastISel)
421 return TargetLowering::createFastISel(funcInfo, libInfo);
422 return Mips::createFastISel(funcInfo, libInfo);
425 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
428 return VT.changeVectorElementTypeToInteger();
431 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
432 TargetLowering::DAGCombinerInfo &DCI,
433 const MipsSubtarget &Subtarget) {
434 if (DCI.isBeforeLegalizeOps())
437 EVT Ty = N->getValueType(0);
438 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
439 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
440 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
444 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
445 N->getOperand(0), N->getOperand(1));
446 SDValue InChain = DAG.getEntryNode();
447 SDValue InGlue = DivRem;
450 if (N->hasAnyUseOfValue(0)) {
451 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
454 InChain = CopyFromLo.getValue(1);
455 InGlue = CopyFromLo.getValue(2);
459 if (N->hasAnyUseOfValue(1)) {
460 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
462 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
468 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
470 default: llvm_unreachable("Unknown fp condition code!");
472 case ISD::SETOEQ: return Mips::FCOND_OEQ;
473 case ISD::SETUNE: return Mips::FCOND_UNE;
475 case ISD::SETOLT: return Mips::FCOND_OLT;
477 case ISD::SETOGT: return Mips::FCOND_OGT;
479 case ISD::SETOLE: return Mips::FCOND_OLE;
481 case ISD::SETOGE: return Mips::FCOND_OGE;
482 case ISD::SETULT: return Mips::FCOND_ULT;
483 case ISD::SETULE: return Mips::FCOND_ULE;
484 case ISD::SETUGT: return Mips::FCOND_UGT;
485 case ISD::SETUGE: return Mips::FCOND_UGE;
486 case ISD::SETUO: return Mips::FCOND_UN;
487 case ISD::SETO: return Mips::FCOND_OR;
489 case ISD::SETONE: return Mips::FCOND_ONE;
490 case ISD::SETUEQ: return Mips::FCOND_UEQ;
495 /// This function returns true if the floating point conditional branches and
496 /// conditional moves which use condition code CC should be inverted.
497 static bool invertFPCondCodeUser(Mips::CondCode CC) {
498 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
501 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
502 "Illegal Condition Code");
507 // Creates and returns an FPCmp node from a setcc node.
508 // Returns Op if setcc is not a floating point comparison.
509 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
510 // must be a SETCC node
511 if (Op.getOpcode() != ISD::SETCC)
514 SDValue LHS = Op.getOperand(0);
516 if (!LHS.getValueType().isFloatingPoint())
519 SDValue RHS = Op.getOperand(1);
522 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
523 // node if necessary.
524 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
526 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
527 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
530 // Creates and returns a CMovFPT/F node.
531 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
532 SDValue False, SDLoc DL) {
533 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
534 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
535 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
537 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
538 True.getValueType(), True, FCC0, False, Cond);
541 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
542 TargetLowering::DAGCombinerInfo &DCI,
543 const MipsSubtarget &Subtarget) {
544 if (DCI.isBeforeLegalizeOps())
547 SDValue SetCC = N->getOperand(0);
549 if ((SetCC.getOpcode() != ISD::SETCC) ||
550 !SetCC.getOperand(0).getValueType().isInteger())
553 SDValue False = N->getOperand(2);
554 EVT FalseTy = False.getValueType();
556 if (!FalseTy.isInteger())
559 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
561 // If the RHS (False) is 0, we swap the order of the operands
562 // of ISD::SELECT (obviously also inverting the condition) so that we can
563 // take advantage of conditional moves using the $0 register.
565 // return (a != 0) ? x : 0;
573 if (!FalseC->getZExtValue()) {
574 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
575 SDValue True = N->getOperand(1);
577 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
578 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
580 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
583 // If both operands are integer constants there's a possibility that we
584 // can do some interesting optimizations.
585 SDValue True = N->getOperand(1);
586 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
588 if (!TrueC || !True.getValueType().isInteger())
591 // We'll also ignore MVT::i64 operands as this optimizations proves
592 // to be ineffective because of the required sign extensions as the result
593 // of a SETCC operator is always MVT::i32 for non-vector types.
594 if (True.getValueType() == MVT::i64)
597 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
599 // 1) (a < x) ? y : y-1
601 // addiu $reg2, $reg1, y-1
603 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
605 // 2) (a < x) ? y-1 : y
607 // xor $reg1, $reg1, 1
608 // addiu $reg2, $reg1, y-1
610 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
611 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
612 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
613 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
616 // Couldn't optimize.
620 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
621 TargetLowering::DAGCombinerInfo &DCI,
622 const MipsSubtarget &Subtarget) {
623 // Pattern match EXT.
624 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
625 // => ext $dst, $src, size, pos
626 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
629 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
630 unsigned ShiftRightOpc = ShiftRight.getOpcode();
632 // Op's first operand must be a shift right.
633 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
636 // The second operand of the shift must be an immediate.
638 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
641 uint64_t Pos = CN->getZExtValue();
642 uint64_t SMPos, SMSize;
644 // Op's second operand must be a shifted mask.
645 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
646 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
649 // Return if the shifted mask does not start at bit 0 or the sum of its size
650 // and Pos exceeds the word's size.
651 EVT ValTy = N->getValueType(0);
652 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
655 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
656 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
657 DAG.getConstant(SMSize, MVT::i32));
660 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
661 TargetLowering::DAGCombinerInfo &DCI,
662 const MipsSubtarget &Subtarget) {
663 // Pattern match INS.
664 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
665 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
666 // => ins $dst, $src, size, pos, $src1
667 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
670 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
671 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
674 // See if Op's first operand matches (and $src1 , mask0).
675 if (And0.getOpcode() != ISD::AND)
678 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
679 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
682 // See if Op's second operand matches (and (shl $src, pos), mask1).
683 if (And1.getOpcode() != ISD::AND)
686 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
687 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
690 // The shift masks must have the same position and size.
691 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
694 SDValue Shl = And1.getOperand(0);
695 if (Shl.getOpcode() != ISD::SHL)
698 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
701 unsigned Shamt = CN->getZExtValue();
703 // Return if the shift amount and the first bit position of mask are not the
705 EVT ValTy = N->getValueType(0);
706 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
709 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
710 DAG.getConstant(SMPos0, MVT::i32),
711 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
714 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
715 TargetLowering::DAGCombinerInfo &DCI,
716 const MipsSubtarget &Subtarget) {
717 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
719 if (DCI.isBeforeLegalizeOps())
722 SDValue Add = N->getOperand(1);
724 if (Add.getOpcode() != ISD::ADD)
727 SDValue Lo = Add.getOperand(1);
729 if ((Lo.getOpcode() != MipsISD::Lo) ||
730 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
733 EVT ValTy = N->getValueType(0);
736 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
738 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
741 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
743 SelectionDAG &DAG = DCI.DAG;
744 unsigned Opc = N->getOpcode();
750 return performDivRemCombine(N, DAG, DCI, Subtarget);
752 return performSELECTCombine(N, DAG, DCI, Subtarget);
754 return performANDCombine(N, DAG, DCI, Subtarget);
756 return performORCombine(N, DAG, DCI, Subtarget);
758 return performADDCombine(N, DAG, DCI, Subtarget);
765 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
766 SmallVectorImpl<SDValue> &Results,
767 SelectionDAG &DAG) const {
768 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
770 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
771 Results.push_back(Res.getValue(I));
775 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
776 SmallVectorImpl<SDValue> &Results,
777 SelectionDAG &DAG) const {
778 return LowerOperationWrapper(N, Results, DAG);
781 SDValue MipsTargetLowering::
782 LowerOperation(SDValue Op, SelectionDAG &DAG) const
784 switch (Op.getOpcode())
786 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
787 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
788 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
789 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
790 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
791 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
792 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
793 case ISD::SELECT: return lowerSELECT(Op, DAG);
794 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
795 case ISD::SETCC: return lowerSETCC(Op, DAG);
796 case ISD::VASTART: return lowerVASTART(Op, DAG);
797 case ISD::VAARG: return lowerVAARG(Op, DAG);
798 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
799 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
800 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
801 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
802 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
803 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
804 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
805 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
806 case ISD::LOAD: return lowerLOAD(Op, DAG);
807 case ISD::STORE: return lowerSTORE(Op, DAG);
808 case ISD::ADD: return lowerADD(Op, DAG);
809 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
814 //===----------------------------------------------------------------------===//
815 // Lower helper functions
816 //===----------------------------------------------------------------------===//
818 // addLiveIn - This helper function adds the specified physical register to the
819 // MachineFunction as a live in value. It also creates a corresponding
820 // virtual register for it.
822 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
824 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
825 MF.getRegInfo().addLiveIn(PReg, VReg);
829 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
830 MachineBasicBlock &MBB,
831 const TargetInstrInfo &TII,
836 // Insert instruction "teq $divisor_reg, $zero, 7".
837 MachineBasicBlock::iterator I(MI);
838 MachineInstrBuilder MIB;
839 MachineOperand &Divisor = MI->getOperand(2);
840 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
841 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
842 .addReg(Mips::ZERO).addImm(7);
844 // Use the 32-bit sub-register if this is a 64-bit division.
846 MIB->getOperand(0).setSubReg(Mips::sub_32);
848 // Clear Divisor's kill flag.
849 Divisor.setIsKill(false);
851 // We would normally delete the original instruction here but in this case
852 // we only needed to inject an additional instruction rather than replace it.
858 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
859 MachineBasicBlock *BB) const {
860 switch (MI->getOpcode()) {
862 llvm_unreachable("Unexpected instr type to insert");
863 case Mips::ATOMIC_LOAD_ADD_I8:
864 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
865 case Mips::ATOMIC_LOAD_ADD_I16:
866 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
867 case Mips::ATOMIC_LOAD_ADD_I32:
868 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
869 case Mips::ATOMIC_LOAD_ADD_I64:
870 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
872 case Mips::ATOMIC_LOAD_AND_I8:
873 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
874 case Mips::ATOMIC_LOAD_AND_I16:
875 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
876 case Mips::ATOMIC_LOAD_AND_I32:
877 return emitAtomicBinary(MI, BB, 4, Mips::AND);
878 case Mips::ATOMIC_LOAD_AND_I64:
879 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
881 case Mips::ATOMIC_LOAD_OR_I8:
882 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
883 case Mips::ATOMIC_LOAD_OR_I16:
884 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
885 case Mips::ATOMIC_LOAD_OR_I32:
886 return emitAtomicBinary(MI, BB, 4, Mips::OR);
887 case Mips::ATOMIC_LOAD_OR_I64:
888 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
890 case Mips::ATOMIC_LOAD_XOR_I8:
891 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
892 case Mips::ATOMIC_LOAD_XOR_I16:
893 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
894 case Mips::ATOMIC_LOAD_XOR_I32:
895 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
896 case Mips::ATOMIC_LOAD_XOR_I64:
897 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
899 case Mips::ATOMIC_LOAD_NAND_I8:
900 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
901 case Mips::ATOMIC_LOAD_NAND_I16:
902 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
903 case Mips::ATOMIC_LOAD_NAND_I32:
904 return emitAtomicBinary(MI, BB, 4, 0, true);
905 case Mips::ATOMIC_LOAD_NAND_I64:
906 return emitAtomicBinary(MI, BB, 8, 0, true);
908 case Mips::ATOMIC_LOAD_SUB_I8:
909 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
910 case Mips::ATOMIC_LOAD_SUB_I16:
911 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
912 case Mips::ATOMIC_LOAD_SUB_I32:
913 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
914 case Mips::ATOMIC_LOAD_SUB_I64:
915 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
917 case Mips::ATOMIC_SWAP_I8:
918 return emitAtomicBinaryPartword(MI, BB, 1, 0);
919 case Mips::ATOMIC_SWAP_I16:
920 return emitAtomicBinaryPartword(MI, BB, 2, 0);
921 case Mips::ATOMIC_SWAP_I32:
922 return emitAtomicBinary(MI, BB, 4, 0);
923 case Mips::ATOMIC_SWAP_I64:
924 return emitAtomicBinary(MI, BB, 8, 0);
926 case Mips::ATOMIC_CMP_SWAP_I8:
927 return emitAtomicCmpSwapPartword(MI, BB, 1);
928 case Mips::ATOMIC_CMP_SWAP_I16:
929 return emitAtomicCmpSwapPartword(MI, BB, 2);
930 case Mips::ATOMIC_CMP_SWAP_I32:
931 return emitAtomicCmpSwap(MI, BB, 4);
932 case Mips::ATOMIC_CMP_SWAP_I64:
933 return emitAtomicCmpSwap(MI, BB, 8);
934 case Mips::PseudoSDIV:
935 case Mips::PseudoUDIV:
940 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
941 case Mips::PseudoDSDIV:
942 case Mips::PseudoDUDIV:
947 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
949 return emitSEL_D(MI, BB);
951 case Mips::PseudoSELECT_I:
952 case Mips::PseudoSELECT_I64:
953 case Mips::PseudoSELECT_S:
954 case Mips::PseudoSELECT_D32:
955 case Mips::PseudoSELECT_D64:
956 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
957 case Mips::PseudoSELECTFP_F_I:
958 case Mips::PseudoSELECTFP_F_I64:
959 case Mips::PseudoSELECTFP_F_S:
960 case Mips::PseudoSELECTFP_F_D32:
961 case Mips::PseudoSELECTFP_F_D64:
962 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
963 case Mips::PseudoSELECTFP_T_I:
964 case Mips::PseudoSELECTFP_T_I64:
965 case Mips::PseudoSELECTFP_T_S:
966 case Mips::PseudoSELECTFP_T_D32:
967 case Mips::PseudoSELECTFP_T_D64:
968 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
972 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
973 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
975 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
976 unsigned Size, unsigned BinOpcode,
978 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
980 MachineFunction *MF = BB->getParent();
981 MachineRegisterInfo &RegInfo = MF->getRegInfo();
982 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
983 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
984 DebugLoc DL = MI->getDebugLoc();
985 unsigned LL, SC, AND, NOR, ZERO, BEQ;
992 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
993 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1000 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1001 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1004 ZERO = Mips::ZERO_64;
1008 unsigned OldVal = MI->getOperand(0).getReg();
1009 unsigned Ptr = MI->getOperand(1).getReg();
1010 unsigned Incr = MI->getOperand(2).getReg();
1012 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1013 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1014 unsigned Success = RegInfo.createVirtualRegister(RC);
1016 // insert new blocks after the current block
1017 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1018 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1019 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1020 MachineFunction::iterator It = BB;
1022 MF->insert(It, loopMBB);
1023 MF->insert(It, exitMBB);
1025 // Transfer the remainder of BB and its successor edges to exitMBB.
1026 exitMBB->splice(exitMBB->begin(), BB,
1027 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1028 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1032 // fallthrough --> loopMBB
1033 BB->addSuccessor(loopMBB);
1034 loopMBB->addSuccessor(loopMBB);
1035 loopMBB->addSuccessor(exitMBB);
1038 // ll oldval, 0(ptr)
1039 // <binop> storeval, oldval, incr
1040 // sc success, storeval, 0(ptr)
1041 // beq success, $0, loopMBB
1043 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1045 // and andres, oldval, incr
1046 // nor storeval, $0, andres
1047 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1048 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1049 } else if (BinOpcode) {
1050 // <binop> storeval, oldval, incr
1051 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1055 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1056 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1058 MI->eraseFromParent(); // The instruction is gone now.
1063 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1064 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1065 unsigned SrcReg) const {
1066 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1067 DebugLoc DL = MI->getDebugLoc();
1069 if (Subtarget.hasMips32r2() && Size == 1) {
1070 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1074 if (Subtarget.hasMips32r2() && Size == 2) {
1075 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1079 MachineFunction *MF = BB->getParent();
1080 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1081 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1082 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1085 int64_t ShiftImm = 32 - (Size * 8);
1087 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1088 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1093 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1094 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1096 assert((Size == 1 || Size == 2) &&
1097 "Unsupported size for EmitAtomicBinaryPartial.");
1099 MachineFunction *MF = BB->getParent();
1100 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1101 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1102 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1103 DebugLoc DL = MI->getDebugLoc();
1105 unsigned Dest = MI->getOperand(0).getReg();
1106 unsigned Ptr = MI->getOperand(1).getReg();
1107 unsigned Incr = MI->getOperand(2).getReg();
1109 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1110 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1111 unsigned Mask = RegInfo.createVirtualRegister(RC);
1112 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1113 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1114 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1115 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1116 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1117 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1118 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1119 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1120 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1121 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1122 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1123 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1124 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1125 unsigned Success = RegInfo.createVirtualRegister(RC);
1127 // insert new blocks after the current block
1128 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1129 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1130 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1131 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1132 MachineFunction::iterator It = BB;
1134 MF->insert(It, loopMBB);
1135 MF->insert(It, sinkMBB);
1136 MF->insert(It, exitMBB);
1138 // Transfer the remainder of BB and its successor edges to exitMBB.
1139 exitMBB->splice(exitMBB->begin(), BB,
1140 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1141 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1143 BB->addSuccessor(loopMBB);
1144 loopMBB->addSuccessor(loopMBB);
1145 loopMBB->addSuccessor(sinkMBB);
1146 sinkMBB->addSuccessor(exitMBB);
1149 // addiu masklsb2,$0,-4 # 0xfffffffc
1150 // and alignedaddr,ptr,masklsb2
1151 // andi ptrlsb2,ptr,3
1152 // sll shiftamt,ptrlsb2,3
1153 // ori maskupper,$0,255 # 0xff
1154 // sll mask,maskupper,shiftamt
1155 // nor mask2,$0,mask
1156 // sll incr2,incr,shiftamt
1158 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1159 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1160 .addReg(Mips::ZERO).addImm(-4);
1161 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1162 .addReg(Ptr).addReg(MaskLSB2);
1163 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1164 if (Subtarget.isLittle()) {
1165 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1167 unsigned Off = RegInfo.createVirtualRegister(RC);
1168 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1169 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1170 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1172 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1173 .addReg(Mips::ZERO).addImm(MaskImm);
1174 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1175 .addReg(MaskUpper).addReg(ShiftAmt);
1176 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1177 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1179 // atomic.load.binop
1181 // ll oldval,0(alignedaddr)
1182 // binop binopres,oldval,incr2
1183 // and newval,binopres,mask
1184 // and maskedoldval0,oldval,mask2
1185 // or storeval,maskedoldval0,newval
1186 // sc success,storeval,0(alignedaddr)
1187 // beq success,$0,loopMBB
1191 // ll oldval,0(alignedaddr)
1192 // and newval,incr2,mask
1193 // and maskedoldval0,oldval,mask2
1194 // or storeval,maskedoldval0,newval
1195 // sc success,storeval,0(alignedaddr)
1196 // beq success,$0,loopMBB
1199 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1200 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1202 // and andres, oldval, incr2
1203 // nor binopres, $0, andres
1204 // and newval, binopres, mask
1205 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1206 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1207 .addReg(Mips::ZERO).addReg(AndRes);
1208 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1209 } else if (BinOpcode) {
1210 // <binop> binopres, oldval, incr2
1211 // and newval, binopres, mask
1212 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1213 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1214 } else { // atomic.swap
1215 // and newval, incr2, mask
1216 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1219 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1220 .addReg(OldVal).addReg(Mask2);
1221 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1222 .addReg(MaskedOldVal0).addReg(NewVal);
1223 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1224 BuildMI(BB, DL, TII->get(SC), Success)
1225 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1226 BuildMI(BB, DL, TII->get(Mips::BEQ))
1227 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1230 // and maskedoldval1,oldval,mask
1231 // srl srlres,maskedoldval1,shiftamt
1232 // sign_extend dest,srlres
1235 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1236 .addReg(OldVal).addReg(Mask);
1237 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1238 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1239 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1241 MI->eraseFromParent(); // The instruction is gone now.
1246 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1247 MachineBasicBlock *BB,
1248 unsigned Size) const {
1249 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1251 MachineFunction *MF = BB->getParent();
1252 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1253 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1254 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1255 DebugLoc DL = MI->getDebugLoc();
1256 unsigned LL, SC, ZERO, BNE, BEQ;
1259 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1260 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1267 ZERO = Mips::ZERO_64;
1272 unsigned Dest = MI->getOperand(0).getReg();
1273 unsigned Ptr = MI->getOperand(1).getReg();
1274 unsigned OldVal = MI->getOperand(2).getReg();
1275 unsigned NewVal = MI->getOperand(3).getReg();
1277 unsigned Success = RegInfo.createVirtualRegister(RC);
1279 // insert new blocks after the current block
1280 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1281 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1282 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1283 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284 MachineFunction::iterator It = BB;
1286 MF->insert(It, loop1MBB);
1287 MF->insert(It, loop2MBB);
1288 MF->insert(It, exitMBB);
1290 // Transfer the remainder of BB and its successor edges to exitMBB.
1291 exitMBB->splice(exitMBB->begin(), BB,
1292 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1293 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1297 // fallthrough --> loop1MBB
1298 BB->addSuccessor(loop1MBB);
1299 loop1MBB->addSuccessor(exitMBB);
1300 loop1MBB->addSuccessor(loop2MBB);
1301 loop2MBB->addSuccessor(loop1MBB);
1302 loop2MBB->addSuccessor(exitMBB);
1306 // bne dest, oldval, exitMBB
1308 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1309 BuildMI(BB, DL, TII->get(BNE))
1310 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1313 // sc success, newval, 0(ptr)
1314 // beq success, $0, loop1MBB
1316 BuildMI(BB, DL, TII->get(SC), Success)
1317 .addReg(NewVal).addReg(Ptr).addImm(0);
1318 BuildMI(BB, DL, TII->get(BEQ))
1319 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1321 MI->eraseFromParent(); // The instruction is gone now.
1327 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1328 MachineBasicBlock *BB,
1329 unsigned Size) const {
1330 assert((Size == 1 || Size == 2) &&
1331 "Unsupported size for EmitAtomicCmpSwapPartial.");
1333 MachineFunction *MF = BB->getParent();
1334 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1335 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1336 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1337 DebugLoc DL = MI->getDebugLoc();
1339 unsigned Dest = MI->getOperand(0).getReg();
1340 unsigned Ptr = MI->getOperand(1).getReg();
1341 unsigned CmpVal = MI->getOperand(2).getReg();
1342 unsigned NewVal = MI->getOperand(3).getReg();
1344 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1345 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1346 unsigned Mask = RegInfo.createVirtualRegister(RC);
1347 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1348 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1349 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1350 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1351 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1352 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1353 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1354 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1355 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1356 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1357 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1358 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1359 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1360 unsigned Success = RegInfo.createVirtualRegister(RC);
1362 // insert new blocks after the current block
1363 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1364 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1365 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1366 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1367 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1368 MachineFunction::iterator It = BB;
1370 MF->insert(It, loop1MBB);
1371 MF->insert(It, loop2MBB);
1372 MF->insert(It, sinkMBB);
1373 MF->insert(It, exitMBB);
1375 // Transfer the remainder of BB and its successor edges to exitMBB.
1376 exitMBB->splice(exitMBB->begin(), BB,
1377 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1378 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1380 BB->addSuccessor(loop1MBB);
1381 loop1MBB->addSuccessor(sinkMBB);
1382 loop1MBB->addSuccessor(loop2MBB);
1383 loop2MBB->addSuccessor(loop1MBB);
1384 loop2MBB->addSuccessor(sinkMBB);
1385 sinkMBB->addSuccessor(exitMBB);
1387 // FIXME: computation of newval2 can be moved to loop2MBB.
1389 // addiu masklsb2,$0,-4 # 0xfffffffc
1390 // and alignedaddr,ptr,masklsb2
1391 // andi ptrlsb2,ptr,3
1392 // sll shiftamt,ptrlsb2,3
1393 // ori maskupper,$0,255 # 0xff
1394 // sll mask,maskupper,shiftamt
1395 // nor mask2,$0,mask
1396 // andi maskedcmpval,cmpval,255
1397 // sll shiftedcmpval,maskedcmpval,shiftamt
1398 // andi maskednewval,newval,255
1399 // sll shiftednewval,maskednewval,shiftamt
1400 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1401 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1402 .addReg(Mips::ZERO).addImm(-4);
1403 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1404 .addReg(Ptr).addReg(MaskLSB2);
1405 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1406 if (Subtarget.isLittle()) {
1407 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1409 unsigned Off = RegInfo.createVirtualRegister(RC);
1410 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1411 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1412 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1414 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1415 .addReg(Mips::ZERO).addImm(MaskImm);
1416 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1417 .addReg(MaskUpper).addReg(ShiftAmt);
1418 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1419 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1420 .addReg(CmpVal).addImm(MaskImm);
1421 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1422 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1423 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1424 .addReg(NewVal).addImm(MaskImm);
1425 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1426 .addReg(MaskedNewVal).addReg(ShiftAmt);
1429 // ll oldval,0(alginedaddr)
1430 // and maskedoldval0,oldval,mask
1431 // bne maskedoldval0,shiftedcmpval,sinkMBB
1433 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1434 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1435 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1436 .addReg(OldVal).addReg(Mask);
1437 BuildMI(BB, DL, TII->get(Mips::BNE))
1438 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1441 // and maskedoldval1,oldval,mask2
1442 // or storeval,maskedoldval1,shiftednewval
1443 // sc success,storeval,0(alignedaddr)
1444 // beq success,$0,loop1MBB
1446 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1447 .addReg(OldVal).addReg(Mask2);
1448 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1449 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1450 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1451 BuildMI(BB, DL, TII->get(SC), Success)
1452 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1453 BuildMI(BB, DL, TII->get(Mips::BEQ))
1454 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1457 // srl srlres,maskedoldval0,shiftamt
1458 // sign_extend dest,srlres
1461 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1462 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1463 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1465 MI->eraseFromParent(); // The instruction is gone now.
1470 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1471 MachineBasicBlock *BB) const {
1472 MachineFunction *MF = BB->getParent();
1473 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1474 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1475 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1476 DebugLoc DL = MI->getDebugLoc();
1477 MachineBasicBlock::iterator II(MI);
1479 unsigned Fc = MI->getOperand(1).getReg();
1480 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1482 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1484 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1487 .addImm(Mips::sub_lo);
1489 // We don't erase the original instruction, we just replace the condition
1490 // register with the 64-bit super-register.
1491 MI->getOperand(1).setReg(Fc2);
1496 //===----------------------------------------------------------------------===//
1497 // Misc Lower Operation implementation
1498 //===----------------------------------------------------------------------===//
1499 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1500 SDValue Chain = Op.getOperand(0);
1501 SDValue Table = Op.getOperand(1);
1502 SDValue Index = Op.getOperand(2);
1504 EVT PTy = getPointerTy();
1505 unsigned EntrySize =
1506 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1508 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1509 DAG.getConstant(EntrySize, PTy));
1510 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1512 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1513 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1514 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1516 Chain = Addr.getValue(1);
1518 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1519 // For PIC, the sequence is:
1520 // BRIND(load(Jumptable + index) + RelocBase)
1521 // RelocBase can be JumpTable, GOT or some sort of global base.
1522 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1523 getPICJumpTableRelocBase(Table, DAG));
1526 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1529 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1530 // The first operand is the chain, the second is the condition, the third is
1531 // the block to branch to if the condition is true.
1532 SDValue Chain = Op.getOperand(0);
1533 SDValue Dest = Op.getOperand(2);
1536 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1537 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1539 // Return if flag is not set by a floating point comparison.
1540 if (CondRes.getOpcode() != MipsISD::FPCmp)
1543 SDValue CCNode = CondRes.getOperand(2);
1545 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1546 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1547 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1548 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1549 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1550 FCC0, Dest, CondRes);
1553 SDValue MipsTargetLowering::
1554 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1556 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1557 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1559 // Return if flag is not set by a floating point comparison.
1560 if (Cond.getOpcode() != MipsISD::FPCmp)
1563 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1567 SDValue MipsTargetLowering::
1568 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1571 EVT Ty = Op.getOperand(0).getValueType();
1572 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1573 getSetCCResultType(*DAG.getContext(), Ty),
1574 Op.getOperand(0), Op.getOperand(1),
1577 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1581 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1582 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1583 SDValue Cond = createFPCmp(DAG, Op);
1585 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1586 "Floating point operand expected.");
1588 SDValue True = DAG.getConstant(1, MVT::i32);
1589 SDValue False = DAG.getConstant(0, MVT::i32);
1591 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1594 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1595 SelectionDAG &DAG) const {
1596 EVT Ty = Op.getValueType();
1597 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1598 const GlobalValue *GV = N->getGlobal();
1600 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1601 const MipsTargetObjectFile *TLOF =
1602 static_cast<const MipsTargetObjectFile *>(
1603 getTargetMachine().getObjFileLowering());
1604 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1605 // %gp_rel relocation
1606 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1608 // %hi/%lo relocation
1609 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1612 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1613 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1616 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1617 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1618 MachinePointerInfo::getGOT());
1620 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1621 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP
1623 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1626 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1627 SelectionDAG &DAG) const {
1628 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1629 EVT Ty = Op.getValueType();
1631 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1632 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1634 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1637 SDValue MipsTargetLowering::
1638 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1640 // If the relocation model is PIC, use the General Dynamic TLS Model or
1641 // Local Dynamic TLS model, otherwise use the Initial Exec or
1642 // Local Exec TLS Model.
1644 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1646 const GlobalValue *GV = GA->getGlobal();
1647 EVT PtrVT = getPointerTy();
1649 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1651 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1652 // General Dynamic and Local Dynamic TLS Model.
1653 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1656 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1657 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1658 getGlobalReg(DAG, PtrVT), TGA);
1659 unsigned PtrSize = PtrVT.getSizeInBits();
1660 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1662 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1666 Entry.Node = Argument;
1668 Args.push_back(Entry);
1670 TargetLowering::CallLoweringInfo CLI(DAG);
1671 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1672 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1673 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1675 SDValue Ret = CallResult.first;
1677 if (model != TLSModel::LocalDynamic)
1680 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1681 MipsII::MO_DTPREL_HI);
1682 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1683 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1684 MipsII::MO_DTPREL_LO);
1685 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1686 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1687 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1691 if (model == TLSModel::InitialExec) {
1692 // Initial Exec TLS Model
1693 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1694 MipsII::MO_GOTTPREL);
1695 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1697 Offset = DAG.getLoad(PtrVT, DL,
1698 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1699 false, false, false, 0);
1701 // Local Exec TLS Model
1702 assert(model == TLSModel::LocalExec);
1703 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1704 MipsII::MO_TPREL_HI);
1705 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1706 MipsII::MO_TPREL_LO);
1707 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1708 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1709 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1712 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1713 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1716 SDValue MipsTargetLowering::
1717 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1719 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1720 EVT Ty = Op.getValueType();
1722 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1723 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1725 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1728 SDValue MipsTargetLowering::
1729 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1731 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1732 EVT Ty = Op.getValueType();
1734 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1735 const MipsTargetObjectFile *TLOF =
1736 static_cast<const MipsTargetObjectFile *>(
1737 getTargetMachine().getObjFileLowering());
1739 if (TLOF->IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1740 // %gp_rel relocation
1741 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1743 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1746 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1749 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1750 MachineFunction &MF = DAG.getMachineFunction();
1751 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1754 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1757 // vastart just stores the address of the VarArgsFrameIndex slot into the
1758 // memory location argument.
1759 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1760 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1761 MachinePointerInfo(SV), false, false, 0);
1764 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1765 SDNode *Node = Op.getNode();
1766 EVT VT = Node->getValueType(0);
1767 SDValue Chain = Node->getOperand(0);
1768 SDValue VAListPtr = Node->getOperand(1);
1769 unsigned Align = Node->getConstantOperandVal(3);
1770 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1772 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1774 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1775 MachinePointerInfo(SV), false, false, false,
1777 SDValue VAList = VAListLoad;
1779 // Re-align the pointer if necessary.
1780 // It should only ever be necessary for 64-bit types on O32 since the minimum
1781 // argument alignment is the same as the maximum type alignment for N32/N64.
1783 // FIXME: We currently align too often. The code generator doesn't notice
1784 // when the pointer is still aligned from the last va_arg (or pair of
1785 // va_args for the i64 on O32 case).
1786 if (Align > getMinStackArgumentAlignment()) {
1787 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1789 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1790 DAG.getConstant(Align - 1,
1791 VAList.getValueType()));
1793 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1794 DAG.getConstant(-(int64_t)Align,
1795 VAList.getValueType()));
1798 // Increment the pointer, VAList, to the next vaarg.
1799 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1800 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1801 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1802 VAList.getValueType()));
1803 // Store the incremented VAList to the legalized pointer
1804 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1805 MachinePointerInfo(SV), false, false, 0);
1807 // In big-endian mode we must adjust the pointer when the load size is smaller
1808 // than the argument slot size. We must also reduce the known alignment to
1809 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1810 // the correct half of the slot, and reduce the alignment from 8 (slot
1811 // alignment) down to 4 (type alignment).
1812 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1813 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1814 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1815 DAG.getIntPtrConstant(Adjustment));
1817 // Load the actual argument out of the pointer VAList
1818 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1822 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1823 bool HasExtractInsert) {
1824 EVT TyX = Op.getOperand(0).getValueType();
1825 EVT TyY = Op.getOperand(1).getValueType();
1826 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1827 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1831 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1833 SDValue X = (TyX == MVT::f32) ?
1834 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1835 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1837 SDValue Y = (TyY == MVT::f32) ?
1838 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1839 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1842 if (HasExtractInsert) {
1843 // ext E, Y, 31, 1 ; extract bit31 of Y
1844 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1845 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1846 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1849 // srl SrlX, SllX, 1
1851 // sll SllY, SrlX, 31
1852 // or Or, SrlX, SllY
1853 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1854 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1855 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1856 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1857 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1860 if (TyX == MVT::f32)
1861 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1863 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1864 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1865 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1868 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1869 bool HasExtractInsert) {
1870 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1871 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1872 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1873 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1876 // Bitcast to integer nodes.
1877 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1878 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1880 if (HasExtractInsert) {
1881 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1882 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1883 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1884 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1886 if (WidthX > WidthY)
1887 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1888 else if (WidthY > WidthX)
1889 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1891 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1892 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1893 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1896 // (d)sll SllX, X, 1
1897 // (d)srl SrlX, SllX, 1
1898 // (d)srl SrlY, Y, width(Y)-1
1899 // (d)sll SllY, SrlX, width(Y)-1
1900 // or Or, SrlX, SllY
1901 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1902 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1903 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1904 DAG.getConstant(WidthY - 1, MVT::i32));
1906 if (WidthX > WidthY)
1907 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1908 else if (WidthY > WidthX)
1909 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1911 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1912 DAG.getConstant(WidthX - 1, MVT::i32));
1913 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1914 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1918 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1919 if (Subtarget.isGP64bit())
1920 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1922 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1925 SDValue MipsTargetLowering::
1926 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1928 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1929 "Frame address can only be determined for current frame.");
1931 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1932 MFI->setFrameAddressIsTaken(true);
1933 EVT VT = Op.getValueType();
1935 SDValue FrameAddr = DAG.getCopyFromReg(
1936 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
1940 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1941 SelectionDAG &DAG) const {
1942 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1946 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1947 "Return address can be determined only for current frame.");
1949 MachineFunction &MF = DAG.getMachineFunction();
1950 MachineFrameInfo *MFI = MF.getFrameInfo();
1951 MVT VT = Op.getSimpleValueType();
1952 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
1953 MFI->setReturnAddressIsTaken(true);
1955 // Return RA, which contains the return address. Mark it an implicit live-in.
1956 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1957 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1960 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1961 // generated from __builtin_eh_return (offset, handler)
1962 // The effect of this is to adjust the stack pointer by "offset"
1963 // and then branch to "handler".
1964 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1966 MachineFunction &MF = DAG.getMachineFunction();
1967 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1969 MipsFI->setCallsEhReturn();
1970 SDValue Chain = Op.getOperand(0);
1971 SDValue Offset = Op.getOperand(1);
1972 SDValue Handler = Op.getOperand(2);
1974 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
1976 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1977 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1978 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
1979 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
1980 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1981 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1982 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1983 DAG.getRegister(OffsetReg, Ty),
1984 DAG.getRegister(AddrReg, getPointerTy()),
1988 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1989 SelectionDAG &DAG) const {
1990 // FIXME: Need pseudo-fence for 'singlethread' fences
1991 // FIXME: Set SType for weaker fences where supported/appropriate.
1994 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1995 DAG.getConstant(SType, MVT::i32));
1998 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1999 SelectionDAG &DAG) const {
2001 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2003 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2004 SDValue Shamt = Op.getOperand(2);
2005 // if shamt < (VT.bits):
2006 // lo = (shl lo, shamt)
2007 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2010 // hi = (shl lo, shamt[4:0])
2011 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2012 DAG.getConstant(-1, MVT::i32));
2013 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2014 DAG.getConstant(1, VT));
2015 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2016 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2017 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2018 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2019 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2020 DAG.getConstant(0x20, MVT::i32));
2021 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2022 DAG.getConstant(0, VT), ShiftLeftLo);
2023 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2025 SDValue Ops[2] = {Lo, Hi};
2026 return DAG.getMergeValues(Ops, DL);
2029 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2032 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2033 SDValue Shamt = Op.getOperand(2);
2034 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2036 // if shamt < (VT.bits):
2037 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2039 // hi = (sra hi, shamt)
2041 // hi = (srl hi, shamt)
2044 // lo = (sra hi, shamt[4:0])
2045 // hi = (sra hi, 31)
2047 // lo = (srl hi, shamt[4:0])
2049 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2050 DAG.getConstant(-1, MVT::i32));
2051 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2052 DAG.getConstant(1, VT));
2053 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2054 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2055 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2056 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2058 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2059 DAG.getConstant(0x20, MVT::i32));
2060 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, VT, Hi, DAG.getConstant(31, VT));
2061 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2062 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2063 IsSRA ? Shift31 : DAG.getConstant(0, VT), ShiftRightHi);
2065 SDValue Ops[2] = {Lo, Hi};
2066 return DAG.getMergeValues(Ops, DL);
2069 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2070 SDValue Chain, SDValue Src, unsigned Offset) {
2071 SDValue Ptr = LD->getBasePtr();
2072 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2073 EVT BasePtrVT = Ptr.getValueType();
2075 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2078 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2079 DAG.getConstant(Offset, BasePtrVT));
2081 SDValue Ops[] = { Chain, Ptr, Src };
2082 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2083 LD->getMemOperand());
2086 // Expand an unaligned 32 or 64-bit integer load node.
2087 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2088 LoadSDNode *LD = cast<LoadSDNode>(Op);
2089 EVT MemVT = LD->getMemoryVT();
2091 if (Subtarget.systemSupportsUnalignedAccess())
2094 // Return if load is aligned or if MemVT is neither i32 nor i64.
2095 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2096 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2099 bool IsLittle = Subtarget.isLittle();
2100 EVT VT = Op.getValueType();
2101 ISD::LoadExtType ExtType = LD->getExtensionType();
2102 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2104 assert((VT == MVT::i32) || (VT == MVT::i64));
2107 // (set dst, (i64 (load baseptr)))
2109 // (set tmp, (ldl (add baseptr, 7), undef))
2110 // (set dst, (ldr baseptr, tmp))
2111 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2112 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2114 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2118 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2120 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2124 // (set dst, (i32 (load baseptr))) or
2125 // (set dst, (i64 (sextload baseptr))) or
2126 // (set dst, (i64 (extload baseptr)))
2128 // (set tmp, (lwl (add baseptr, 3), undef))
2129 // (set dst, (lwr baseptr, tmp))
2130 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2131 (ExtType == ISD::EXTLOAD))
2134 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2137 // (set dst, (i64 (zextload baseptr)))
2139 // (set tmp0, (lwl (add baseptr, 3), undef))
2140 // (set tmp1, (lwr baseptr, tmp0))
2141 // (set tmp2, (shl tmp1, 32))
2142 // (set dst, (srl tmp2, 32))
2144 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2145 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2146 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2147 SDValue Ops[] = { SRL, LWR.getValue(1) };
2148 return DAG.getMergeValues(Ops, DL);
2151 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2152 SDValue Chain, unsigned Offset) {
2153 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2154 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2156 SDVTList VTList = DAG.getVTList(MVT::Other);
2159 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2160 DAG.getConstant(Offset, BasePtrVT));
2162 SDValue Ops[] = { Chain, Value, Ptr };
2163 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2164 SD->getMemOperand());
2167 // Expand an unaligned 32 or 64-bit integer store node.
2168 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2170 SDValue Value = SD->getValue(), Chain = SD->getChain();
2171 EVT VT = Value.getValueType();
2174 // (store val, baseptr) or
2175 // (truncstore val, baseptr)
2177 // (swl val, (add baseptr, 3))
2178 // (swr val, baseptr)
2179 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2180 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2182 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2185 assert(VT == MVT::i64);
2188 // (store val, baseptr)
2190 // (sdl val, (add baseptr, 7))
2191 // (sdr val, baseptr)
2192 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2193 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2196 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2197 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2198 SDValue Val = SD->getValue();
2200 if (Val.getOpcode() != ISD::FP_TO_SINT)
2203 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2204 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2207 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2208 SD->getPointerInfo(), SD->isVolatile(),
2209 SD->isNonTemporal(), SD->getAlignment());
2212 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2213 StoreSDNode *SD = cast<StoreSDNode>(Op);
2214 EVT MemVT = SD->getMemoryVT();
2216 // Lower unaligned integer stores.
2217 if (!Subtarget.systemSupportsUnalignedAccess() &&
2218 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2219 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2220 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2222 return lowerFP_TO_SINT_STORE(SD, DAG);
2225 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2226 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2227 || cast<ConstantSDNode>
2228 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2229 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2233 // (add (frameaddr 0), (frame_to_args_offset))
2234 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2235 // (add FrameObject, 0)
2236 // where FrameObject is a fixed StackObject with offset 0 which points to
2237 // the old stack pointer.
2238 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2239 EVT ValTy = Op->getValueType(0);
2240 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2241 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2242 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2243 DAG.getConstant(0, ValTy));
2246 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2247 SelectionDAG &DAG) const {
2248 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2249 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2251 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2254 //===----------------------------------------------------------------------===//
2255 // Calling Convention Implementation
2256 //===----------------------------------------------------------------------===//
2258 //===----------------------------------------------------------------------===//
2259 // TODO: Implement a generic logic using tblgen that can support this.
2260 // Mips O32 ABI rules:
2262 // i32 - Passed in A0, A1, A2, A3 and stack
2263 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2264 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2265 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2266 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2267 // not used, it must be shadowed. If only A3 is available, shadow it and
2270 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2271 //===----------------------------------------------------------------------===//
2273 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2274 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2275 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2276 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2277 State.getMachineFunction().getSubtarget());
2279 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2280 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2282 // Do not process byval args here.
2283 if (ArgFlags.isByVal())
2286 // Promote i8 and i16
2287 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2288 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2290 if (ArgFlags.isSExt())
2291 LocInfo = CCValAssign::SExtUpper;
2292 else if (ArgFlags.isZExt())
2293 LocInfo = CCValAssign::ZExtUpper;
2295 LocInfo = CCValAssign::AExtUpper;
2299 // Promote i8 and i16
2300 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2302 if (ArgFlags.isSExt())
2303 LocInfo = CCValAssign::SExt;
2304 else if (ArgFlags.isZExt())
2305 LocInfo = CCValAssign::ZExt;
2307 LocInfo = CCValAssign::AExt;
2312 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2313 // is true: function is vararg, argument is 3rd or higher, there is previous
2314 // argument which is not f32 or f64.
2315 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2316 State.getFirstUnallocated(F32Regs) != ValNo;
2317 unsigned OrigAlign = ArgFlags.getOrigAlign();
2318 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2320 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2321 Reg = State.AllocateReg(IntRegs);
2322 // If this is the first part of an i64 arg,
2323 // the allocated register must be either A0 or A2.
2324 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2325 Reg = State.AllocateReg(IntRegs);
2327 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2328 // Allocate int register and shadow next int register. If first
2329 // available register is Mips::A1 or Mips::A3, shadow it too.
2330 Reg = State.AllocateReg(IntRegs);
2331 if (Reg == Mips::A1 || Reg == Mips::A3)
2332 Reg = State.AllocateReg(IntRegs);
2333 State.AllocateReg(IntRegs);
2335 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2336 // we are guaranteed to find an available float register
2337 if (ValVT == MVT::f32) {
2338 Reg = State.AllocateReg(F32Regs);
2339 // Shadow int register
2340 State.AllocateReg(IntRegs);
2342 Reg = State.AllocateReg(F64Regs);
2343 // Shadow int registers
2344 unsigned Reg2 = State.AllocateReg(IntRegs);
2345 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2346 State.AllocateReg(IntRegs);
2347 State.AllocateReg(IntRegs);
2350 llvm_unreachable("Cannot handle this ValVT.");
2353 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2355 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2357 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2362 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2363 MVT LocVT, CCValAssign::LocInfo LocInfo,
2364 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2365 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2367 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2370 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2371 MVT LocVT, CCValAssign::LocInfo LocInfo,
2372 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2373 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2375 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2378 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2379 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2380 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2382 #include "MipsGenCallingConv.inc"
2384 //===----------------------------------------------------------------------===//
2385 // Call Calling Convention Implementation
2386 //===----------------------------------------------------------------------===//
2388 // Return next O32 integer argument register.
2389 static unsigned getNextIntArgReg(unsigned Reg) {
2390 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2391 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2395 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2396 SDValue Chain, SDValue Arg, SDLoc DL,
2397 bool IsTailCall, SelectionDAG &DAG) const {
2399 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2400 DAG.getIntPtrConstant(Offset));
2401 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2405 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2406 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2407 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2408 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2409 /*isVolatile=*/ true, false, 0);
2412 void MipsTargetLowering::
2413 getOpndList(SmallVectorImpl<SDValue> &Ops,
2414 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2415 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2416 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2417 SDValue Chain) const {
2418 // Insert node "GP copy globalreg" before call to function.
2420 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2421 // in PIC mode) allow symbols to be resolved via lazy binding.
2422 // The lazy binding stub requires GP to point to the GOT.
2423 // Note that we don't need GP to point to the GOT for indirect calls
2424 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2425 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2426 // used for the function (that is, Mips linker doesn't generate lazy binding
2427 // stub for a function whose address is taken in the program).
2428 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2429 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2430 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2431 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2434 // Build a sequence of copy-to-reg nodes chained together with token
2435 // chain and flag operands which copy the outgoing args into registers.
2436 // The InFlag in necessary since all emitted instructions must be
2440 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2441 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2442 RegsToPass[i].second, InFlag);
2443 InFlag = Chain.getValue(1);
2446 // Add argument registers to the end of the list so that they are
2447 // known live into the call.
2448 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2449 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2450 RegsToPass[i].second.getValueType()));
2452 // Add a register mask operand representing the call-preserved registers.
2453 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2454 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2455 assert(Mask && "Missing call preserved mask for calling convention");
2456 if (Subtarget.inMips16HardFloat()) {
2457 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2458 llvm::StringRef Sym = G->getGlobal()->getName();
2459 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2460 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2461 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2465 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2467 if (InFlag.getNode())
2468 Ops.push_back(InFlag);
2471 /// LowerCall - functions arguments are copied from virtual regs to
2472 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2474 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2475 SmallVectorImpl<SDValue> &InVals) const {
2476 SelectionDAG &DAG = CLI.DAG;
2478 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2479 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2480 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2481 SDValue Chain = CLI.Chain;
2482 SDValue Callee = CLI.Callee;
2483 bool &IsTailCall = CLI.IsTailCall;
2484 CallingConv::ID CallConv = CLI.CallConv;
2485 bool IsVarArg = CLI.IsVarArg;
2487 MachineFunction &MF = DAG.getMachineFunction();
2488 MachineFrameInfo *MFI = MF.getFrameInfo();
2489 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2490 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2491 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2493 // Analyze operands of the call, assigning locations to each operand.
2494 SmallVector<CCValAssign, 16> ArgLocs;
2496 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2497 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2499 // Allocate the reserved argument area. It seems strange to do this from the
2500 // caller side but removing it breaks the frame size calculation.
2501 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2503 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2505 // Get a count of how many bytes are to be pushed on the stack.
2506 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2508 // Check if it's really possible to do a tail call.
2510 IsTailCall = isEligibleForTailCallOptimization(
2511 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2513 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2514 report_fatal_error("failed to perform tail call elimination on a call "
2515 "site marked musttail");
2520 // Chain is the output chain of the last Load/Store or CopyToReg node.
2521 // ByValChain is the output chain of the last Memcpy node created for copying
2522 // byval arguments to the stack.
2523 unsigned StackAlignment = TFL->getStackAlignment();
2524 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2525 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2528 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2530 SDValue StackPtr = DAG.getCopyFromReg(
2531 Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2533 // With EABI is it possible to have 16 args on registers.
2534 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2535 SmallVector<SDValue, 8> MemOpChains;
2537 CCInfo.rewindByValRegsInfo();
2539 // Walk the register/memloc assignments, inserting copies/loads.
2540 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2541 SDValue Arg = OutVals[i];
2542 CCValAssign &VA = ArgLocs[i];
2543 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2544 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2545 bool UseUpperBits = false;
2548 if (Flags.isByVal()) {
2549 unsigned FirstByValReg, LastByValReg;
2550 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2551 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2553 assert(Flags.getByValSize() &&
2554 "ByVal args of size 0 should have been ignored by front-end.");
2555 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2556 assert(!IsTailCall &&
2557 "Do not tail-call optimize if there is a byval argument.");
2558 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2559 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2561 CCInfo.nextInRegsParam();
2565 // Promote the value if needed.
2566 switch (VA.getLocInfo()) {
2568 llvm_unreachable("Unknown loc info!");
2569 case CCValAssign::Full:
2570 if (VA.isRegLoc()) {
2571 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2572 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2573 (ValVT == MVT::i64 && LocVT == MVT::f64))
2574 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2575 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2576 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2577 Arg, DAG.getConstant(0, MVT::i32));
2578 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2579 Arg, DAG.getConstant(1, MVT::i32));
2580 if (!Subtarget.isLittle())
2582 unsigned LocRegLo = VA.getLocReg();
2583 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2584 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2585 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2590 case CCValAssign::BCvt:
2591 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2593 case CCValAssign::SExtUpper:
2594 UseUpperBits = true;
2596 case CCValAssign::SExt:
2597 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2599 case CCValAssign::ZExtUpper:
2600 UseUpperBits = true;
2602 case CCValAssign::ZExt:
2603 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2605 case CCValAssign::AExtUpper:
2606 UseUpperBits = true;
2608 case CCValAssign::AExt:
2609 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2614 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2615 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2617 ISD::SHL, DL, VA.getLocVT(), Arg,
2618 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2621 // Arguments that can be passed on register must be kept at
2622 // RegsToPass vector
2623 if (VA.isRegLoc()) {
2624 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2628 // Register can't get to this point...
2629 assert(VA.isMemLoc());
2631 // emit ISD::STORE whichs stores the
2632 // parameter value to a stack Location
2633 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2634 Chain, Arg, DL, IsTailCall, DAG));
2637 // Transform all store nodes into one single node because all store
2638 // nodes are independent of each other.
2639 if (!MemOpChains.empty())
2640 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2642 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2643 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2644 // node so that legalize doesn't hack it.
2645 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2647 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2649 EVT Ty = Callee.getValueType();
2651 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2653 const GlobalValue *Val = G->getGlobal();
2654 InternalLinkage = Val->hasInternalLinkage();
2656 if (InternalLinkage)
2657 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2658 else if (LargeGOT) {
2659 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2660 MipsII::MO_CALL_LO16, Chain,
2661 FuncInfo->callPtrInfo(Val));
2664 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2665 FuncInfo->callPtrInfo(Val));
2669 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2670 MipsII::MO_NO_FLAG);
2671 GlobalOrExternal = true;
2673 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2674 const char *Sym = S->getSymbol();
2676 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2678 DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2679 else if (LargeGOT) {
2680 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2681 MipsII::MO_CALL_LO16, Chain,
2682 FuncInfo->callPtrInfo(Sym));
2684 } else { // N64 || PIC
2685 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2686 FuncInfo->callPtrInfo(Sym));
2690 GlobalOrExternal = true;
2693 SmallVector<SDValue, 8> Ops(1, Chain);
2694 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2696 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2697 IsCallReloc, CLI, Callee, Chain);
2700 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2702 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2703 SDValue InFlag = Chain.getValue(1);
2705 // Create the CALLSEQ_END node.
2706 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2707 DAG.getIntPtrConstant(0, true), InFlag, DL);
2708 InFlag = Chain.getValue(1);
2710 // Handle result values, copying them out of physregs into vregs that we
2712 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2716 /// LowerCallResult - Lower the result values of a call into the
2717 /// appropriate copies out of appropriate physical registers.
2718 SDValue MipsTargetLowering::LowerCallResult(
2719 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2720 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2721 SmallVectorImpl<SDValue> &InVals,
2722 TargetLowering::CallLoweringInfo &CLI) const {
2723 // Assign locations to each value returned by this call.
2724 SmallVector<CCValAssign, 16> RVLocs;
2725 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2727 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2729 // Copy all of the result registers out of their specified physreg.
2730 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2731 CCValAssign &VA = RVLocs[i];
2732 assert(VA.isRegLoc() && "Can only return in registers!");
2734 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2735 RVLocs[i].getLocVT(), InFlag);
2736 Chain = Val.getValue(1);
2737 InFlag = Val.getValue(2);
2739 if (VA.isUpperBitsInLoc()) {
2740 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2741 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2743 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2745 Shift, DL, VA.getLocVT(), Val,
2746 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2749 switch (VA.getLocInfo()) {
2751 llvm_unreachable("Unknown loc info!");
2752 case CCValAssign::Full:
2754 case CCValAssign::BCvt:
2755 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2757 case CCValAssign::AExt:
2758 case CCValAssign::AExtUpper:
2759 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2761 case CCValAssign::ZExt:
2762 case CCValAssign::ZExtUpper:
2763 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2764 DAG.getValueType(VA.getValVT()));
2765 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2767 case CCValAssign::SExt:
2768 case CCValAssign::SExtUpper:
2769 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2770 DAG.getValueType(VA.getValVT()));
2771 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2775 InVals.push_back(Val);
2781 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2782 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2783 MVT LocVT = VA.getLocVT();
2784 EVT ValVT = VA.getValVT();
2786 // Shift into the upper bits if necessary.
2787 switch (VA.getLocInfo()) {
2790 case CCValAssign::AExtUpper:
2791 case CCValAssign::SExtUpper:
2792 case CCValAssign::ZExtUpper: {
2793 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2794 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2796 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2798 Opcode, DL, VA.getLocVT(), Val,
2799 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2804 // If this is an value smaller than the argument slot size (32-bit for O32,
2805 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2806 // size. Extract the value and insert any appropriate assertions regarding
2807 // sign/zero extension.
2808 switch (VA.getLocInfo()) {
2810 llvm_unreachable("Unknown loc info!");
2811 case CCValAssign::Full:
2813 case CCValAssign::AExtUpper:
2814 case CCValAssign::AExt:
2815 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2817 case CCValAssign::SExtUpper:
2818 case CCValAssign::SExt:
2819 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2820 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2822 case CCValAssign::ZExtUpper:
2823 case CCValAssign::ZExt:
2824 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2825 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2827 case CCValAssign::BCvt:
2828 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2835 //===----------------------------------------------------------------------===//
2836 // Formal Arguments Calling Convention Implementation
2837 //===----------------------------------------------------------------------===//
2838 /// LowerFormalArguments - transform physical registers into virtual registers
2839 /// and generate load operations for arguments places on the stack.
2841 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2842 CallingConv::ID CallConv,
2844 const SmallVectorImpl<ISD::InputArg> &Ins,
2845 SDLoc DL, SelectionDAG &DAG,
2846 SmallVectorImpl<SDValue> &InVals)
2848 MachineFunction &MF = DAG.getMachineFunction();
2849 MachineFrameInfo *MFI = MF.getFrameInfo();
2850 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2852 MipsFI->setVarArgsFrameIndex(0);
2854 // Used with vargs to acumulate store chains.
2855 std::vector<SDValue> OutChains;
2857 // Assign locations to all of the incoming arguments.
2858 SmallVector<CCValAssign, 16> ArgLocs;
2859 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2861 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2862 Function::const_arg_iterator FuncArg =
2863 DAG.getMachineFunction().getFunction()->arg_begin();
2865 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2866 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2867 CCInfo.getInRegsParamsCount() > 0);
2869 unsigned CurArgIdx = 0;
2870 CCInfo.rewindByValRegsInfo();
2872 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2873 CCValAssign &VA = ArgLocs[i];
2874 if (Ins[i].isOrigArg()) {
2875 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2876 CurArgIdx = Ins[i].getOrigArgIndex();
2878 EVT ValVT = VA.getValVT();
2879 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2880 bool IsRegLoc = VA.isRegLoc();
2882 if (Flags.isByVal()) {
2883 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2884 unsigned FirstByValReg, LastByValReg;
2885 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2886 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2888 assert(Flags.getByValSize() &&
2889 "ByVal args of size 0 should have been ignored by front-end.");
2890 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2891 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2892 FirstByValReg, LastByValReg, VA, CCInfo);
2893 CCInfo.nextInRegsParam();
2897 // Arguments stored on registers
2899 MVT RegVT = VA.getLocVT();
2900 unsigned ArgReg = VA.getLocReg();
2901 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2903 // Transform the arguments stored on
2904 // physical registers into virtual ones
2905 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2906 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2908 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2910 // Handle floating point arguments passed in integer registers and
2911 // long double arguments passed in floating point registers.
2912 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2913 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2914 (RegVT == MVT::f64 && ValVT == MVT::i64))
2915 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2916 else if (ABI.IsO32() && RegVT == MVT::i32 &&
2917 ValVT == MVT::f64) {
2918 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2919 getNextIntArgReg(ArgReg), RC);
2920 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2921 if (!Subtarget.isLittle())
2922 std::swap(ArgValue, ArgValue2);
2923 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2924 ArgValue, ArgValue2);
2927 InVals.push_back(ArgValue);
2928 } else { // VA.isRegLoc()
2929 MVT LocVT = VA.getLocVT();
2932 // We ought to be able to use LocVT directly but O32 sets it to i32
2933 // when allocating floating point values to integer registers.
2934 // This shouldn't influence how we load the value into registers unless
2935 // we are targetting softfloat.
2936 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2937 LocVT = VA.getValVT();
2941 assert(VA.isMemLoc());
2943 // The stack pointer offset is relative to the caller stack frame.
2944 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
2945 VA.getLocMemOffset(), true);
2947 // Create load nodes to retrieve arguments from the stack
2948 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2949 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2950 MachinePointerInfo::getFixedStack(FI),
2951 false, false, false, 0);
2952 OutChains.push_back(ArgValue.getValue(1));
2954 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2956 InVals.push_back(ArgValue);
2960 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2961 // The mips ABIs for returning structs by value requires that we copy
2962 // the sret argument into $v0 for the return. Save the argument into
2963 // a virtual register so that we can access it from the return points.
2964 if (Ins[i].Flags.isSRet()) {
2965 unsigned Reg = MipsFI->getSRetReturnReg();
2967 Reg = MF.getRegInfo().createVirtualRegister(
2968 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
2969 MipsFI->setSRetReturnReg(Reg);
2971 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2972 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2978 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
2980 // All stores are grouped in one node to allow the matching between
2981 // the size of Ins and InVals. This only happens when on varg functions
2982 if (!OutChains.empty()) {
2983 OutChains.push_back(Chain);
2984 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2990 //===----------------------------------------------------------------------===//
2991 // Return Value Calling Convention Implementation
2992 //===----------------------------------------------------------------------===//
2995 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2996 MachineFunction &MF, bool IsVarArg,
2997 const SmallVectorImpl<ISD::OutputArg> &Outs,
2998 LLVMContext &Context) const {
2999 SmallVector<CCValAssign, 16> RVLocs;
3000 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3001 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3005 MipsTargetLowering::LowerReturn(SDValue Chain,
3006 CallingConv::ID CallConv, bool IsVarArg,
3007 const SmallVectorImpl<ISD::OutputArg> &Outs,
3008 const SmallVectorImpl<SDValue> &OutVals,
3009 SDLoc DL, SelectionDAG &DAG) const {
3010 // CCValAssign - represent the assignment of
3011 // the return value to a location
3012 SmallVector<CCValAssign, 16> RVLocs;
3013 MachineFunction &MF = DAG.getMachineFunction();
3015 // CCState - Info about the registers and stack slot.
3016 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3018 // Analyze return values.
3019 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3022 SmallVector<SDValue, 4> RetOps(1, Chain);
3024 // Copy the result values into the output registers.
3025 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3026 SDValue Val = OutVals[i];
3027 CCValAssign &VA = RVLocs[i];
3028 assert(VA.isRegLoc() && "Can only return in registers!");
3029 bool UseUpperBits = false;
3031 switch (VA.getLocInfo()) {
3033 llvm_unreachable("Unknown loc info!");
3034 case CCValAssign::Full:
3036 case CCValAssign::BCvt:
3037 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3039 case CCValAssign::AExtUpper:
3040 UseUpperBits = true;
3042 case CCValAssign::AExt:
3043 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3045 case CCValAssign::ZExtUpper:
3046 UseUpperBits = true;
3048 case CCValAssign::ZExt:
3049 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3051 case CCValAssign::SExtUpper:
3052 UseUpperBits = true;
3054 case CCValAssign::SExt:
3055 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3060 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3061 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3063 ISD::SHL, DL, VA.getLocVT(), Val,
3064 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3067 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3069 // Guarantee that all emitted copies are stuck together with flags.
3070 Flag = Chain.getValue(1);
3071 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3074 // The mips ABIs for returning structs by value requires that we copy
3075 // the sret argument into $v0 for the return. We saved the argument into
3076 // a virtual register in the entry block, so now we copy the value out
3078 if (MF.getFunction()->hasStructRetAttr()) {
3079 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3080 unsigned Reg = MipsFI->getSRetReturnReg();
3083 llvm_unreachable("sret virtual register not created in the entry block");
3084 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3085 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3087 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3088 Flag = Chain.getValue(1);
3089 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3092 RetOps[0] = Chain; // Update chain.
3094 // Add the flag if we have it.
3096 RetOps.push_back(Flag);
3098 // Return on Mips is always a "jr $ra"
3099 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3102 //===----------------------------------------------------------------------===//
3103 // Mips Inline Assembly Support
3104 //===----------------------------------------------------------------------===//
3106 /// getConstraintType - Given a constraint letter, return the type of
3107 /// constraint it is for this target.
3108 MipsTargetLowering::ConstraintType MipsTargetLowering::
3109 getConstraintType(const std::string &Constraint) const
3111 // Mips specific constraints
3112 // GCC config/mips/constraints.md
3114 // 'd' : An address register. Equivalent to r
3115 // unless generating MIPS16 code.
3116 // 'y' : Equivalent to r; retained for
3117 // backwards compatibility.
3118 // 'c' : A register suitable for use in an indirect
3119 // jump. This will always be $25 for -mabicalls.
3120 // 'l' : The lo register. 1 word storage.
3121 // 'x' : The hilo register pair. Double word storage.
3122 if (Constraint.size() == 1) {
3123 switch (Constraint[0]) {
3131 return C_RegisterClass;
3136 return TargetLowering::getConstraintType(Constraint);
3139 /// Examine constraint type and operand type and determine a weight value.
3140 /// This object must already have been set up with the operand type
3141 /// and the current alternative constraint selected.
3142 TargetLowering::ConstraintWeight
3143 MipsTargetLowering::getSingleConstraintMatchWeight(
3144 AsmOperandInfo &info, const char *constraint) const {
3145 ConstraintWeight weight = CW_Invalid;
3146 Value *CallOperandVal = info.CallOperandVal;
3147 // If we don't have a value, we can't do a match,
3148 // but allow it at the lowest weight.
3149 if (!CallOperandVal)
3151 Type *type = CallOperandVal->getType();
3152 // Look at the constraint type.
3153 switch (*constraint) {
3155 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3159 if (type->isIntegerTy())
3160 weight = CW_Register;
3162 case 'f': // FPU or MSA register
3163 if (Subtarget.hasMSA() && type->isVectorTy() &&
3164 cast<VectorType>(type)->getBitWidth() == 128)
3165 weight = CW_Register;
3166 else if (type->isFloatTy())
3167 weight = CW_Register;
3169 case 'c': // $25 for indirect jumps
3170 case 'l': // lo register
3171 case 'x': // hilo register pair
3172 if (type->isIntegerTy())
3173 weight = CW_SpecificReg;
3175 case 'I': // signed 16 bit immediate
3176 case 'J': // integer zero
3177 case 'K': // unsigned 16 bit immediate
3178 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3179 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3180 case 'O': // signed 15 bit immediate (+- 16383)
3181 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3182 if (isa<ConstantInt>(CallOperandVal))
3183 weight = CW_Constant;
3192 /// This is a helper function to parse a physical register string and split it
3193 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3194 /// that is returned indicates whether parsing was successful. The second flag
3195 /// is true if the numeric part exists.
3196 static std::pair<bool, bool>
3197 parsePhysicalReg(StringRef C, std::string &Prefix,
3198 unsigned long long &Reg) {
3199 if (C.front() != '{' || C.back() != '}')
3200 return std::make_pair(false, false);
3202 // Search for the first numeric character.
3203 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3204 I = std::find_if(B, E, std::ptr_fun(isdigit));
3206 Prefix.assign(B, I - B);
3208 // The second flag is set to false if no numeric characters were found.
3210 return std::make_pair(true, false);
3212 // Parse the numeric characters.
3213 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3217 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3218 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3219 const TargetRegisterInfo *TRI =
3220 Subtarget.getRegisterInfo();
3221 const TargetRegisterClass *RC;
3223 unsigned long long Reg;
3225 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3228 return std::make_pair(0U, nullptr);
3230 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3231 // No numeric characters follow "hi" or "lo".
3233 return std::make_pair(0U, nullptr);
3235 RC = TRI->getRegClass(Prefix == "hi" ?
3236 Mips::HI32RegClassID : Mips::LO32RegClassID);
3237 return std::make_pair(*(RC->begin()), RC);
3238 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3239 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3241 // No numeric characters follow the name.
3243 return std::make_pair(0U, nullptr);
3245 Reg = StringSwitch<unsigned long long>(Prefix)
3246 .Case("$msair", Mips::MSAIR)
3247 .Case("$msacsr", Mips::MSACSR)
3248 .Case("$msaaccess", Mips::MSAAccess)
3249 .Case("$msasave", Mips::MSASave)
3250 .Case("$msamodify", Mips::MSAModify)
3251 .Case("$msarequest", Mips::MSARequest)
3252 .Case("$msamap", Mips::MSAMap)
3253 .Case("$msaunmap", Mips::MSAUnmap)
3257 return std::make_pair(0U, nullptr);
3259 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3260 return std::make_pair(Reg, RC);
3264 return std::make_pair(0U, nullptr);
3266 if (Prefix == "$f") { // Parse $f0-$f31.
3267 // If the size of FP registers is 64-bit or Reg is an even number, select
3268 // the 64-bit register class. Otherwise, select the 32-bit register class.
3269 if (VT == MVT::Other)
3270 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3272 RC = getRegClassFor(VT);
3274 if (RC == &Mips::AFGR64RegClass) {
3275 assert(Reg % 2 == 0);
3278 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3279 RC = TRI->getRegClass(Mips::FCCRegClassID);
3280 else if (Prefix == "$w") { // Parse $w0-$w31.
3281 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3282 } else { // Parse $0-$31.
3283 assert(Prefix == "$");
3284 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3287 assert(Reg < RC->getNumRegs());
3288 return std::make_pair(*(RC->begin() + Reg), RC);
3291 /// Given a register class constraint, like 'r', if this corresponds directly
3292 /// to an LLVM register class, return a register of 0 and the register class
3294 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3295 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3297 if (Constraint.size() == 1) {
3298 switch (Constraint[0]) {
3299 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3300 case 'y': // Same as 'r'. Exists for compatibility.
3302 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3303 if (Subtarget.inMips16Mode())
3304 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3305 return std::make_pair(0U, &Mips::GPR32RegClass);
3307 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3308 return std::make_pair(0U, &Mips::GPR32RegClass);
3309 if (VT == MVT::i64 && Subtarget.isGP64bit())
3310 return std::make_pair(0U, &Mips::GPR64RegClass);
3311 // This will generate an error message
3312 return std::make_pair(0U, nullptr);
3313 case 'f': // FPU or MSA register
3314 if (VT == MVT::v16i8)
3315 return std::make_pair(0U, &Mips::MSA128BRegClass);
3316 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3317 return std::make_pair(0U, &Mips::MSA128HRegClass);
3318 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3319 return std::make_pair(0U, &Mips::MSA128WRegClass);
3320 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3321 return std::make_pair(0U, &Mips::MSA128DRegClass);
3322 else if (VT == MVT::f32)
3323 return std::make_pair(0U, &Mips::FGR32RegClass);
3324 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3325 if (Subtarget.isFP64bit())
3326 return std::make_pair(0U, &Mips::FGR64RegClass);
3327 return std::make_pair(0U, &Mips::AFGR64RegClass);
3330 case 'c': // register suitable for indirect jump
3332 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3333 assert(VT == MVT::i64 && "Unexpected type.");
3334 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3335 case 'l': // register suitable for indirect jump
3337 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3338 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3339 case 'x': // register suitable for indirect jump
3340 // Fixme: Not triggering the use of both hi and low
3341 // This will generate an error message
3342 return std::make_pair(0U, nullptr);
3346 std::pair<unsigned, const TargetRegisterClass *> R;
3347 R = parseRegForInlineAsmConstraint(Constraint, VT);
3352 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3355 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3356 /// vector. If it is invalid, don't add anything to Ops.
3357 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3358 std::string &Constraint,
3359 std::vector<SDValue>&Ops,
3360 SelectionDAG &DAG) const {
3363 // Only support length 1 constraints for now.
3364 if (Constraint.length() > 1) return;
3366 char ConstraintLetter = Constraint[0];
3367 switch (ConstraintLetter) {
3368 default: break; // This will fall through to the generic implementation
3369 case 'I': // Signed 16 bit constant
3370 // If this fails, the parent routine will give an error
3371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3372 EVT Type = Op.getValueType();
3373 int64_t Val = C->getSExtValue();
3374 if (isInt<16>(Val)) {
3375 Result = DAG.getTargetConstant(Val, Type);
3380 case 'J': // integer zero
3381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3382 EVT Type = Op.getValueType();
3383 int64_t Val = C->getZExtValue();
3385 Result = DAG.getTargetConstant(0, Type);
3390 case 'K': // unsigned 16 bit immediate
3391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3392 EVT Type = Op.getValueType();
3393 uint64_t Val = (uint64_t)C->getZExtValue();
3394 if (isUInt<16>(Val)) {
3395 Result = DAG.getTargetConstant(Val, Type);
3400 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3402 EVT Type = Op.getValueType();
3403 int64_t Val = C->getSExtValue();
3404 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3405 Result = DAG.getTargetConstant(Val, Type);
3410 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3411 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3412 EVT Type = Op.getValueType();
3413 int64_t Val = C->getSExtValue();
3414 if ((Val >= -65535) && (Val <= -1)) {
3415 Result = DAG.getTargetConstant(Val, Type);
3420 case 'O': // signed 15 bit immediate
3421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3422 EVT Type = Op.getValueType();
3423 int64_t Val = C->getSExtValue();
3424 if ((isInt<15>(Val))) {
3425 Result = DAG.getTargetConstant(Val, Type);
3430 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3431 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3432 EVT Type = Op.getValueType();
3433 int64_t Val = C->getSExtValue();
3434 if ((Val <= 65535) && (Val >= 1)) {
3435 Result = DAG.getTargetConstant(Val, Type);
3442 if (Result.getNode()) {
3443 Ops.push_back(Result);
3447 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3450 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3452 // No global is ever allowed as a base.
3457 case 0: // "r+i" or just "i", depending on HasBaseReg.
3460 if (!AM.HasBaseReg) // allow "r+i".
3462 return false; // disallow "r+r" or "r+r+i".
3471 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3472 // The Mips target isn't yet aware of offsets.
3476 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3478 bool IsMemset, bool ZeroMemset,
3480 MachineFunction &MF) const {
3481 if (Subtarget.hasMips64())
3487 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3488 if (VT != MVT::f32 && VT != MVT::f64)
3490 if (Imm.isNegZero())
3492 return Imm.isZero();
3495 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3497 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3499 return TargetLowering::getJumpTableEncoding();
3502 void MipsTargetLowering::copyByValRegs(
3503 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3504 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3505 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3506 const CCValAssign &VA, MipsCCState &State) const {
3507 MachineFunction &MF = DAG.getMachineFunction();
3508 MachineFrameInfo *MFI = MF.getFrameInfo();
3509 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3510 unsigned NumRegs = LastReg - FirstReg;
3511 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3512 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3514 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3518 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3519 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3521 FrameObjOffset = VA.getLocMemOffset();
3523 // Create frame object.
3524 EVT PtrTy = getPointerTy();
3525 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3526 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3527 InVals.push_back(FIN);
3532 // Copy arg registers.
3533 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3534 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3536 for (unsigned I = 0; I < NumRegs; ++I) {
3537 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3538 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3539 unsigned Offset = I * GPRSizeInBytes;
3540 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3541 DAG.getConstant(Offset, PtrTy));
3542 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3543 StorePtr, MachinePointerInfo(FuncArg, Offset),
3545 OutChains.push_back(Store);
3549 // Copy byVal arg to registers and stack.
3550 void MipsTargetLowering::passByValArg(
3551 SDValue Chain, SDLoc DL,
3552 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3553 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3554 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3555 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3556 const CCValAssign &VA) const {
3557 unsigned ByValSizeInBytes = Flags.getByValSize();
3558 unsigned OffsetInBytes = 0; // From beginning of struct
3559 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3560 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3561 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3562 unsigned NumRegs = LastReg - FirstReg;
3565 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3566 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3569 // Copy words to registers.
3570 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3571 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3572 DAG.getConstant(OffsetInBytes, PtrTy));
3573 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3574 MachinePointerInfo(), false, false, false,
3576 MemOpChains.push_back(LoadVal.getValue(1));
3577 unsigned ArgReg = ArgRegs[FirstReg + I];
3578 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3581 // Return if the struct has been fully copied.
3582 if (ByValSizeInBytes == OffsetInBytes)
3585 // Copy the remainder of the byval argument with sub-word loads and shifts.
3586 if (LeftoverBytes) {
3589 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3590 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3591 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3593 if (RemainingSizeInBytes < LoadSizeInBytes)
3597 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3598 DAG.getConstant(OffsetInBytes, PtrTy));
3599 SDValue LoadVal = DAG.getExtLoad(
3600 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3601 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3603 MemOpChains.push_back(LoadVal.getValue(1));
3605 // Shift the loaded value.
3609 Shamt = TotalBytesLoaded * 8;
3611 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3613 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3614 DAG.getConstant(Shamt, MVT::i32));
3617 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3621 OffsetInBytes += LoadSizeInBytes;
3622 TotalBytesLoaded += LoadSizeInBytes;
3623 Alignment = std::min(Alignment, LoadSizeInBytes);
3626 unsigned ArgReg = ArgRegs[FirstReg + I];
3627 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3632 // Copy remainder of byval arg to it with memcpy.
3633 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3634 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3635 DAG.getConstant(OffsetInBytes, PtrTy));
3636 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3637 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3638 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3639 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3640 MachinePointerInfo(), MachinePointerInfo());
3641 MemOpChains.push_back(Chain);
3644 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3645 SDValue Chain, SDLoc DL,
3647 CCState &State) const {
3648 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3649 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3650 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3651 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3652 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3653 MachineFunction &MF = DAG.getMachineFunction();
3654 MachineFrameInfo *MFI = MF.getFrameInfo();
3655 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3657 // Offset of the first variable argument from stack pointer.
3660 if (ArgRegs.size() == Idx)
3662 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3665 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3666 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3669 // Record the frame index of the first variable argument
3670 // which is a value necessary to VASTART.
3671 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3672 MipsFI->setVarArgsFrameIndex(FI);
3674 // Copy the integer registers that have not been used for argument passing
3675 // to the argument register save area. For O32, the save area is allocated
3676 // in the caller's stack frame, while for N32/64, it is allocated in the
3677 // callee's stack frame.
3678 for (unsigned I = Idx; I < ArgRegs.size();
3679 ++I, VaArgOffset += RegSizeInBytes) {
3680 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3681 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3682 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3683 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3684 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3685 MachinePointerInfo(), false, false, 0);
3686 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3688 OutChains.push_back(Store);
3692 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3693 unsigned Align) const {
3694 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3696 assert(Size && "Byval argument's size shouldn't be 0.");
3698 Align = std::min(Align, TFL->getStackAlignment());
3700 unsigned FirstReg = 0;
3701 unsigned NumRegs = 0;
3703 if (State->getCallingConv() != CallingConv::Fast) {
3704 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3705 const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3706 // FIXME: The O32 case actually describes no shadow registers.
3707 const MCPhysReg *ShadowRegs =
3708 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3710 // We used to check the size as well but we can't do that anymore since
3711 // CCState::HandleByVal() rounds up the size after calling this function.
3712 assert(!(Align % RegSizeInBytes) &&
3713 "Byval argument's alignment should be a multiple of"
3716 FirstReg = State->getFirstUnallocated(IntArgRegs);
3718 // If Align > RegSizeInBytes, the first arg register must be even.
3719 // FIXME: This condition happens to do the right thing but it's not the
3720 // right way to test it. We want to check that the stack frame offset
3721 // of the register is aligned.
3722 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3723 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3727 // Mark the registers allocated.
3728 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3729 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3730 Size -= RegSizeInBytes, ++I, ++NumRegs)
3731 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3734 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3738 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3739 bool isFPCmp, unsigned Opc) const {
3740 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3741 "Subtarget already supports SELECT nodes with the use of"
3742 "conditional-move instructions.");
3744 const TargetInstrInfo *TII =
3745 Subtarget.getInstrInfo();
3746 DebugLoc DL = MI->getDebugLoc();
3748 // To "insert" a SELECT instruction, we actually have to insert the
3749 // diamond control-flow pattern. The incoming instruction knows the
3750 // destination vreg to set, the condition code register to branch on, the
3751 // true/false values to select between, and a branch opcode to use.
3752 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3753 MachineFunction::iterator It = BB;
3760 // bNE r1, r0, copy1MBB
3761 // fallthrough --> copy0MBB
3762 MachineBasicBlock *thisMBB = BB;
3763 MachineFunction *F = BB->getParent();
3764 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3765 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3766 F->insert(It, copy0MBB);
3767 F->insert(It, sinkMBB);
3769 // Transfer the remainder of BB and its successor edges to sinkMBB.
3770 sinkMBB->splice(sinkMBB->begin(), BB,
3771 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3772 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3774 // Next, add the true and fallthrough blocks as its successors.
3775 BB->addSuccessor(copy0MBB);
3776 BB->addSuccessor(sinkMBB);
3779 // bc1[tf] cc, sinkMBB
3780 BuildMI(BB, DL, TII->get(Opc))
3781 .addReg(MI->getOperand(1).getReg())
3784 // bne rs, $0, sinkMBB
3785 BuildMI(BB, DL, TII->get(Opc))
3786 .addReg(MI->getOperand(1).getReg())
3792 // %FalseValue = ...
3793 // # fallthrough to sinkMBB
3796 // Update machine-CFG edges
3797 BB->addSuccessor(sinkMBB);
3800 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3804 BuildMI(*BB, BB->begin(), DL,
3805 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3806 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3807 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3809 MI->eraseFromParent(); // The pseudo instruction is gone now.
3814 // FIXME? Maybe this could be a TableGen attribute on some registers and
3815 // this table could be generated automatically from RegInfo.
3816 unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3818 // Named registers is expected to be fairly rare. For now, just support $28
3819 // since the linux kernel uses it.
3820 if (Subtarget.isGP64bit()) {
3821 unsigned Reg = StringSwitch<unsigned>(RegName)
3822 .Case("$28", Mips::GP_64)
3827 unsigned Reg = StringSwitch<unsigned>(RegName)
3828 .Case("$28", Mips::GP)
3833 report_fatal_error("Invalid register name global variable");