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. Set LoadExtAction
226 for (MVT VT : MVT::fp_valuetypes()) {
227 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
228 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
231 // Set LoadExtAction for f16 vectors to Expand
232 for (MVT VT : MVT::fp_vector_valuetypes()) {
233 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
235 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
238 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
239 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
241 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
243 // Used by legalize types to correctly generate the setcc result.
244 // Without this, every float setcc comes with a AND/OR with the result,
245 // we don't want this, since the fpcmp result goes to a flag register,
246 // which is used implicitly by brcond and select operations.
247 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 // Mips Custom Operations
250 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
251 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
252 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
253 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
254 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
255 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
256 setOperationAction(ISD::SELECT, MVT::f32, Custom);
257 setOperationAction(ISD::SELECT, MVT::f64, Custom);
258 setOperationAction(ISD::SELECT, MVT::i32, Custom);
259 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
260 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
261 setOperationAction(ISD::SETCC, MVT::f32, Custom);
262 setOperationAction(ISD::SETCC, MVT::f64, Custom);
263 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
264 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
265 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
266 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
268 if (Subtarget.isGP64bit()) {
269 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
270 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
271 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
272 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
273 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
274 setOperationAction(ISD::SELECT, MVT::i64, Custom);
275 setOperationAction(ISD::LOAD, MVT::i64, Custom);
276 setOperationAction(ISD::STORE, MVT::i64, Custom);
277 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
278 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
279 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
280 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
283 if (!Subtarget.isGP64bit()) {
284 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
285 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
286 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
289 setOperationAction(ISD::ADD, MVT::i32, Custom);
290 if (Subtarget.isGP64bit())
291 setOperationAction(ISD::ADD, MVT::i64, Custom);
293 setOperationAction(ISD::SDIV, MVT::i32, Expand);
294 setOperationAction(ISD::SREM, MVT::i32, Expand);
295 setOperationAction(ISD::UDIV, MVT::i32, Expand);
296 setOperationAction(ISD::UREM, MVT::i32, Expand);
297 setOperationAction(ISD::SDIV, MVT::i64, Expand);
298 setOperationAction(ISD::SREM, MVT::i64, Expand);
299 setOperationAction(ISD::UDIV, MVT::i64, Expand);
300 setOperationAction(ISD::UREM, MVT::i64, Expand);
302 // Operations not directly supported by Mips.
303 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
304 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
305 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
306 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
307 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
308 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
309 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
310 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
311 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
312 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
314 if (Subtarget.hasCnMips()) {
315 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
316 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
318 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
319 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
321 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
322 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
323 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
325 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
326 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
327 setOperationAction(ISD::ROTL, MVT::i32, Expand);
328 setOperationAction(ISD::ROTL, MVT::i64, Expand);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
330 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
332 if (!Subtarget.hasMips32r2())
333 setOperationAction(ISD::ROTR, MVT::i32, Expand);
335 if (!Subtarget.hasMips64r2())
336 setOperationAction(ISD::ROTR, MVT::i64, Expand);
338 setOperationAction(ISD::FSIN, MVT::f32, Expand);
339 setOperationAction(ISD::FSIN, MVT::f64, Expand);
340 setOperationAction(ISD::FCOS, MVT::f32, Expand);
341 setOperationAction(ISD::FCOS, MVT::f64, Expand);
342 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
343 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
344 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
345 setOperationAction(ISD::FPOW, MVT::f32, Expand);
346 setOperationAction(ISD::FPOW, MVT::f64, Expand);
347 setOperationAction(ISD::FLOG, MVT::f32, Expand);
348 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
349 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
350 setOperationAction(ISD::FEXP, MVT::f32, Expand);
351 setOperationAction(ISD::FMA, MVT::f32, Expand);
352 setOperationAction(ISD::FMA, MVT::f64, Expand);
353 setOperationAction(ISD::FREM, MVT::f32, Expand);
354 setOperationAction(ISD::FREM, MVT::f64, Expand);
356 // Lower f16 conversion operations into library calls
357 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
358 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
359 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
360 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
362 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
364 setOperationAction(ISD::VASTART, MVT::Other, Custom);
365 setOperationAction(ISD::VAARG, MVT::Other, Custom);
366 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
367 setOperationAction(ISD::VAEND, MVT::Other, Expand);
369 // Use the default for now
370 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
371 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
373 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
374 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
375 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
376 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
378 setInsertFencesForAtomic(true);
380 if (!Subtarget.hasMips32r2()) {
381 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
382 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
385 // MIPS16 lacks MIPS32's clz and clo instructions.
386 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
387 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
388 if (!Subtarget.hasMips64())
389 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
391 if (!Subtarget.hasMips32r2())
392 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
393 if (!Subtarget.hasMips64r2())
394 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
396 if (Subtarget.isGP64bit()) {
397 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
398 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
399 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
400 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
403 setOperationAction(ISD::TRAP, MVT::Other, Legal);
405 setTargetDAGCombine(ISD::SDIVREM);
406 setTargetDAGCombine(ISD::UDIVREM);
407 setTargetDAGCombine(ISD::SELECT);
408 setTargetDAGCombine(ISD::AND);
409 setTargetDAGCombine(ISD::OR);
410 setTargetDAGCombine(ISD::ADD);
412 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
414 // The arguments on the stack are defined in terms of 4-byte slots on O32
415 // and 8-byte slots on N32/N64.
416 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
418 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
420 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
421 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
423 MaxStoresPerMemcpy = 16;
425 isMicroMips = Subtarget.inMicroMipsMode();
428 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
429 const MipsSubtarget &STI) {
430 if (STI.inMips16Mode())
431 return llvm::createMips16TargetLowering(TM, STI);
433 return llvm::createMipsSETargetLowering(TM, STI);
436 // Create a fast isel object.
438 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
439 const TargetLibraryInfo *libInfo) const {
440 if (!EnableMipsFastISel)
441 return TargetLowering::createFastISel(funcInfo, libInfo);
442 return Mips::createFastISel(funcInfo, libInfo);
445 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
448 return VT.changeVectorElementTypeToInteger();
451 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
452 TargetLowering::DAGCombinerInfo &DCI,
453 const MipsSubtarget &Subtarget) {
454 if (DCI.isBeforeLegalizeOps())
457 EVT Ty = N->getValueType(0);
458 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
459 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
460 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
464 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
465 N->getOperand(0), N->getOperand(1));
466 SDValue InChain = DAG.getEntryNode();
467 SDValue InGlue = DivRem;
470 if (N->hasAnyUseOfValue(0)) {
471 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
473 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
474 InChain = CopyFromLo.getValue(1);
475 InGlue = CopyFromLo.getValue(2);
479 if (N->hasAnyUseOfValue(1)) {
480 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
482 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
488 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
490 default: llvm_unreachable("Unknown fp condition code!");
492 case ISD::SETOEQ: return Mips::FCOND_OEQ;
493 case ISD::SETUNE: return Mips::FCOND_UNE;
495 case ISD::SETOLT: return Mips::FCOND_OLT;
497 case ISD::SETOGT: return Mips::FCOND_OGT;
499 case ISD::SETOLE: return Mips::FCOND_OLE;
501 case ISD::SETOGE: return Mips::FCOND_OGE;
502 case ISD::SETULT: return Mips::FCOND_ULT;
503 case ISD::SETULE: return Mips::FCOND_ULE;
504 case ISD::SETUGT: return Mips::FCOND_UGT;
505 case ISD::SETUGE: return Mips::FCOND_UGE;
506 case ISD::SETUO: return Mips::FCOND_UN;
507 case ISD::SETO: return Mips::FCOND_OR;
509 case ISD::SETONE: return Mips::FCOND_ONE;
510 case ISD::SETUEQ: return Mips::FCOND_UEQ;
515 /// This function returns true if the floating point conditional branches and
516 /// conditional moves which use condition code CC should be inverted.
517 static bool invertFPCondCodeUser(Mips::CondCode CC) {
518 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
521 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
522 "Illegal Condition Code");
527 // Creates and returns an FPCmp node from a setcc node.
528 // Returns Op if setcc is not a floating point comparison.
529 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
530 // must be a SETCC node
531 if (Op.getOpcode() != ISD::SETCC)
534 SDValue LHS = Op.getOperand(0);
536 if (!LHS.getValueType().isFloatingPoint())
539 SDValue RHS = Op.getOperand(1);
542 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
543 // node if necessary.
544 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
546 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
547 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
550 // Creates and returns a CMovFPT/F node.
551 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
552 SDValue False, SDLoc DL) {
553 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
554 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
555 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
557 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
558 True.getValueType(), True, FCC0, False, Cond);
561 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
562 TargetLowering::DAGCombinerInfo &DCI,
563 const MipsSubtarget &Subtarget) {
564 if (DCI.isBeforeLegalizeOps())
567 SDValue SetCC = N->getOperand(0);
569 if ((SetCC.getOpcode() != ISD::SETCC) ||
570 !SetCC.getOperand(0).getValueType().isInteger())
573 SDValue False = N->getOperand(2);
574 EVT FalseTy = False.getValueType();
576 if (!FalseTy.isInteger())
579 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
581 // If the RHS (False) is 0, we swap the order of the operands
582 // of ISD::SELECT (obviously also inverting the condition) so that we can
583 // take advantage of conditional moves using the $0 register.
585 // return (a != 0) ? x : 0;
593 if (!FalseC->getZExtValue()) {
594 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
595 SDValue True = N->getOperand(1);
597 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
598 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
600 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
603 // If both operands are integer constants there's a possibility that we
604 // can do some interesting optimizations.
605 SDValue True = N->getOperand(1);
606 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
608 if (!TrueC || !True.getValueType().isInteger())
611 // We'll also ignore MVT::i64 operands as this optimizations proves
612 // to be ineffective because of the required sign extensions as the result
613 // of a SETCC operator is always MVT::i32 for non-vector types.
614 if (True.getValueType() == MVT::i64)
617 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
619 // 1) (a < x) ? y : y-1
621 // addiu $reg2, $reg1, y-1
623 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
625 // 2) (a < x) ? y-1 : y
627 // xor $reg1, $reg1, 1
628 // addiu $reg2, $reg1, y-1
630 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
631 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
632 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
633 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
636 // Couldn't optimize.
640 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
641 TargetLowering::DAGCombinerInfo &DCI,
642 const MipsSubtarget &Subtarget) {
643 if (DCI.isBeforeLegalizeOps())
646 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
648 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
649 if (!FalseC || FalseC->getZExtValue())
652 // Since RHS (False) is 0, we swap the order of the True/False operands
653 // (obviously also inverting the condition) so that we can
654 // take advantage of conditional moves using the $0 register.
656 // return (a != 0) ? x : 0;
659 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
662 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
663 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
664 ValueIfFalse, FCC, ValueIfTrue, Glue);
667 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
668 TargetLowering::DAGCombinerInfo &DCI,
669 const MipsSubtarget &Subtarget) {
670 // Pattern match EXT.
671 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
672 // => ext $dst, $src, size, pos
673 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
676 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
677 unsigned ShiftRightOpc = ShiftRight.getOpcode();
679 // Op's first operand must be a shift right.
680 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
683 // The second operand of the shift must be an immediate.
685 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
688 uint64_t Pos = CN->getZExtValue();
689 uint64_t SMPos, SMSize;
691 // Op's second operand must be a shifted mask.
692 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
693 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
696 // Return if the shifted mask does not start at bit 0 or the sum of its size
697 // and Pos exceeds the word's size.
698 EVT ValTy = N->getValueType(0);
699 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
703 return DAG.getNode(MipsISD::Ext, DL, ValTy,
704 ShiftRight.getOperand(0),
705 DAG.getConstant(Pos, DL, MVT::i32),
706 DAG.getConstant(SMSize, DL, MVT::i32));
709 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
710 TargetLowering::DAGCombinerInfo &DCI,
711 const MipsSubtarget &Subtarget) {
712 // Pattern match INS.
713 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
714 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
715 // => ins $dst, $src, size, pos, $src1
716 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
719 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
720 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
723 // See if Op's first operand matches (and $src1 , mask0).
724 if (And0.getOpcode() != ISD::AND)
727 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
728 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
731 // See if Op's second operand matches (and (shl $src, pos), mask1).
732 if (And1.getOpcode() != ISD::AND)
735 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
736 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
739 // The shift masks must have the same position and size.
740 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
743 SDValue Shl = And1.getOperand(0);
744 if (Shl.getOpcode() != ISD::SHL)
747 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
750 unsigned Shamt = CN->getZExtValue();
752 // Return if the shift amount and the first bit position of mask are not the
754 EVT ValTy = N->getValueType(0);
755 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
759 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
760 DAG.getConstant(SMPos0, DL, MVT::i32),
761 DAG.getConstant(SMSize0, DL, MVT::i32),
765 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
766 TargetLowering::DAGCombinerInfo &DCI,
767 const MipsSubtarget &Subtarget) {
768 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
770 if (DCI.isBeforeLegalizeOps())
773 SDValue Add = N->getOperand(1);
775 if (Add.getOpcode() != ISD::ADD)
778 SDValue Lo = Add.getOperand(1);
780 if ((Lo.getOpcode() != MipsISD::Lo) ||
781 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
784 EVT ValTy = N->getValueType(0);
787 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
789 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
792 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
794 SelectionDAG &DAG = DCI.DAG;
795 unsigned Opc = N->getOpcode();
801 return performDivRemCombine(N, DAG, DCI, Subtarget);
803 return performSELECTCombine(N, DAG, DCI, Subtarget);
804 case MipsISD::CMovFP_F:
805 case MipsISD::CMovFP_T:
806 return performCMovFPCombine(N, DAG, DCI, Subtarget);
808 return performANDCombine(N, DAG, DCI, Subtarget);
810 return performORCombine(N, DAG, DCI, Subtarget);
812 return performADDCombine(N, DAG, DCI, Subtarget);
819 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
820 SmallVectorImpl<SDValue> &Results,
821 SelectionDAG &DAG) const {
822 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
824 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
825 Results.push_back(Res.getValue(I));
829 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
830 SmallVectorImpl<SDValue> &Results,
831 SelectionDAG &DAG) const {
832 return LowerOperationWrapper(N, Results, DAG);
835 SDValue MipsTargetLowering::
836 LowerOperation(SDValue Op, SelectionDAG &DAG) const
838 switch (Op.getOpcode())
840 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
841 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
842 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
843 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
844 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
845 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
846 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
847 case ISD::SELECT: return lowerSELECT(Op, DAG);
848 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
849 case ISD::SETCC: return lowerSETCC(Op, DAG);
850 case ISD::VASTART: return lowerVASTART(Op, DAG);
851 case ISD::VAARG: return lowerVAARG(Op, DAG);
852 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
853 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
854 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
855 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
856 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
857 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
858 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
859 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
860 case ISD::LOAD: return lowerLOAD(Op, DAG);
861 case ISD::STORE: return lowerSTORE(Op, DAG);
862 case ISD::ADD: return lowerADD(Op, DAG);
863 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
868 //===----------------------------------------------------------------------===//
869 // Lower helper functions
870 //===----------------------------------------------------------------------===//
872 // addLiveIn - This helper function adds the specified physical register to the
873 // MachineFunction as a live in value. It also creates a corresponding
874 // virtual register for it.
876 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
878 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
879 MF.getRegInfo().addLiveIn(PReg, VReg);
883 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
884 MachineBasicBlock &MBB,
885 const TargetInstrInfo &TII,
890 // Insert instruction "teq $divisor_reg, $zero, 7".
891 MachineBasicBlock::iterator I(MI);
892 MachineInstrBuilder MIB;
893 MachineOperand &Divisor = MI->getOperand(2);
894 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
895 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
896 .addReg(Mips::ZERO).addImm(7);
898 // Use the 32-bit sub-register if this is a 64-bit division.
900 MIB->getOperand(0).setSubReg(Mips::sub_32);
902 // Clear Divisor's kill flag.
903 Divisor.setIsKill(false);
905 // We would normally delete the original instruction here but in this case
906 // we only needed to inject an additional instruction rather than replace it.
912 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
913 MachineBasicBlock *BB) const {
914 switch (MI->getOpcode()) {
916 llvm_unreachable("Unexpected instr type to insert");
917 case Mips::ATOMIC_LOAD_ADD_I8:
918 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
919 case Mips::ATOMIC_LOAD_ADD_I16:
920 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
921 case Mips::ATOMIC_LOAD_ADD_I32:
922 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
923 case Mips::ATOMIC_LOAD_ADD_I64:
924 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
926 case Mips::ATOMIC_LOAD_AND_I8:
927 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
928 case Mips::ATOMIC_LOAD_AND_I16:
929 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
930 case Mips::ATOMIC_LOAD_AND_I32:
931 return emitAtomicBinary(MI, BB, 4, Mips::AND);
932 case Mips::ATOMIC_LOAD_AND_I64:
933 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
935 case Mips::ATOMIC_LOAD_OR_I8:
936 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
937 case Mips::ATOMIC_LOAD_OR_I16:
938 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
939 case Mips::ATOMIC_LOAD_OR_I32:
940 return emitAtomicBinary(MI, BB, 4, Mips::OR);
941 case Mips::ATOMIC_LOAD_OR_I64:
942 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
944 case Mips::ATOMIC_LOAD_XOR_I8:
945 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
946 case Mips::ATOMIC_LOAD_XOR_I16:
947 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
948 case Mips::ATOMIC_LOAD_XOR_I32:
949 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
950 case Mips::ATOMIC_LOAD_XOR_I64:
951 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
953 case Mips::ATOMIC_LOAD_NAND_I8:
954 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
955 case Mips::ATOMIC_LOAD_NAND_I16:
956 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
957 case Mips::ATOMIC_LOAD_NAND_I32:
958 return emitAtomicBinary(MI, BB, 4, 0, true);
959 case Mips::ATOMIC_LOAD_NAND_I64:
960 return emitAtomicBinary(MI, BB, 8, 0, true);
962 case Mips::ATOMIC_LOAD_SUB_I8:
963 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
964 case Mips::ATOMIC_LOAD_SUB_I16:
965 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
966 case Mips::ATOMIC_LOAD_SUB_I32:
967 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
968 case Mips::ATOMIC_LOAD_SUB_I64:
969 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
971 case Mips::ATOMIC_SWAP_I8:
972 return emitAtomicBinaryPartword(MI, BB, 1, 0);
973 case Mips::ATOMIC_SWAP_I16:
974 return emitAtomicBinaryPartword(MI, BB, 2, 0);
975 case Mips::ATOMIC_SWAP_I32:
976 return emitAtomicBinary(MI, BB, 4, 0);
977 case Mips::ATOMIC_SWAP_I64:
978 return emitAtomicBinary(MI, BB, 8, 0);
980 case Mips::ATOMIC_CMP_SWAP_I8:
981 return emitAtomicCmpSwapPartword(MI, BB, 1);
982 case Mips::ATOMIC_CMP_SWAP_I16:
983 return emitAtomicCmpSwapPartword(MI, BB, 2);
984 case Mips::ATOMIC_CMP_SWAP_I32:
985 return emitAtomicCmpSwap(MI, BB, 4);
986 case Mips::ATOMIC_CMP_SWAP_I64:
987 return emitAtomicCmpSwap(MI, BB, 8);
988 case Mips::PseudoSDIV:
989 case Mips::PseudoUDIV:
994 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
995 case Mips::PseudoDSDIV:
996 case Mips::PseudoDUDIV:
1001 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
1003 return emitSEL_D(MI, BB);
1005 case Mips::PseudoSELECT_I:
1006 case Mips::PseudoSELECT_I64:
1007 case Mips::PseudoSELECT_S:
1008 case Mips::PseudoSELECT_D32:
1009 case Mips::PseudoSELECT_D64:
1010 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1011 case Mips::PseudoSELECTFP_F_I:
1012 case Mips::PseudoSELECTFP_F_I64:
1013 case Mips::PseudoSELECTFP_F_S:
1014 case Mips::PseudoSELECTFP_F_D32:
1015 case Mips::PseudoSELECTFP_F_D64:
1016 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1017 case Mips::PseudoSELECTFP_T_I:
1018 case Mips::PseudoSELECTFP_T_I64:
1019 case Mips::PseudoSELECTFP_T_S:
1020 case Mips::PseudoSELECTFP_T_D32:
1021 case Mips::PseudoSELECTFP_T_D64:
1022 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1026 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1027 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1029 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1030 unsigned Size, unsigned BinOpcode,
1032 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1034 MachineFunction *MF = BB->getParent();
1035 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1036 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1037 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1038 DebugLoc DL = MI->getDebugLoc();
1039 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1046 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1047 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1054 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1055 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1058 ZERO = Mips::ZERO_64;
1062 unsigned OldVal = MI->getOperand(0).getReg();
1063 unsigned Ptr = MI->getOperand(1).getReg();
1064 unsigned Incr = MI->getOperand(2).getReg();
1066 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1067 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1068 unsigned Success = RegInfo.createVirtualRegister(RC);
1070 // insert new blocks after the current block
1071 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1072 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1073 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1074 MachineFunction::iterator It = BB;
1076 MF->insert(It, loopMBB);
1077 MF->insert(It, exitMBB);
1079 // Transfer the remainder of BB and its successor edges to exitMBB.
1080 exitMBB->splice(exitMBB->begin(), BB,
1081 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1082 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1086 // fallthrough --> loopMBB
1087 BB->addSuccessor(loopMBB);
1088 loopMBB->addSuccessor(loopMBB);
1089 loopMBB->addSuccessor(exitMBB);
1092 // ll oldval, 0(ptr)
1093 // <binop> storeval, oldval, incr
1094 // sc success, storeval, 0(ptr)
1095 // beq success, $0, loopMBB
1097 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1099 // and andres, oldval, incr
1100 // nor storeval, $0, andres
1101 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1102 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1103 } else if (BinOpcode) {
1104 // <binop> storeval, oldval, incr
1105 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1109 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1110 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1112 MI->eraseFromParent(); // The instruction is gone now.
1117 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1118 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1119 unsigned SrcReg) const {
1120 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1121 DebugLoc DL = MI->getDebugLoc();
1123 if (Subtarget.hasMips32r2() && Size == 1) {
1124 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1128 if (Subtarget.hasMips32r2() && Size == 2) {
1129 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1133 MachineFunction *MF = BB->getParent();
1134 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1135 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1136 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1139 int64_t ShiftImm = 32 - (Size * 8);
1141 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1142 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1147 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1148 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1150 assert((Size == 1 || Size == 2) &&
1151 "Unsupported size for EmitAtomicBinaryPartial.");
1153 MachineFunction *MF = BB->getParent();
1154 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1155 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1156 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1157 DebugLoc DL = MI->getDebugLoc();
1159 unsigned Dest = MI->getOperand(0).getReg();
1160 unsigned Ptr = MI->getOperand(1).getReg();
1161 unsigned Incr = MI->getOperand(2).getReg();
1163 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1164 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1165 unsigned Mask = RegInfo.createVirtualRegister(RC);
1166 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1167 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1168 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1169 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1170 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1171 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1172 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1173 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1174 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1175 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1176 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1177 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1178 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1179 unsigned Success = RegInfo.createVirtualRegister(RC);
1181 // insert new blocks after the current block
1182 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1183 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1184 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1185 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1186 MachineFunction::iterator It = BB;
1188 MF->insert(It, loopMBB);
1189 MF->insert(It, sinkMBB);
1190 MF->insert(It, exitMBB);
1192 // Transfer the remainder of BB and its successor edges to exitMBB.
1193 exitMBB->splice(exitMBB->begin(), BB,
1194 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1195 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1197 BB->addSuccessor(loopMBB);
1198 loopMBB->addSuccessor(loopMBB);
1199 loopMBB->addSuccessor(sinkMBB);
1200 sinkMBB->addSuccessor(exitMBB);
1203 // addiu masklsb2,$0,-4 # 0xfffffffc
1204 // and alignedaddr,ptr,masklsb2
1205 // andi ptrlsb2,ptr,3
1206 // sll shiftamt,ptrlsb2,3
1207 // ori maskupper,$0,255 # 0xff
1208 // sll mask,maskupper,shiftamt
1209 // nor mask2,$0,mask
1210 // sll incr2,incr,shiftamt
1212 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1213 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1214 .addReg(Mips::ZERO).addImm(-4);
1215 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1216 .addReg(Ptr).addReg(MaskLSB2);
1217 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1218 if (Subtarget.isLittle()) {
1219 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1221 unsigned Off = RegInfo.createVirtualRegister(RC);
1222 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1223 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1224 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1226 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1227 .addReg(Mips::ZERO).addImm(MaskImm);
1228 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1229 .addReg(MaskUpper).addReg(ShiftAmt);
1230 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1231 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1233 // atomic.load.binop
1235 // ll oldval,0(alignedaddr)
1236 // binop binopres,oldval,incr2
1237 // and newval,binopres,mask
1238 // and maskedoldval0,oldval,mask2
1239 // or storeval,maskedoldval0,newval
1240 // sc success,storeval,0(alignedaddr)
1241 // beq success,$0,loopMBB
1245 // ll oldval,0(alignedaddr)
1246 // and newval,incr2,mask
1247 // and maskedoldval0,oldval,mask2
1248 // or storeval,maskedoldval0,newval
1249 // sc success,storeval,0(alignedaddr)
1250 // beq success,$0,loopMBB
1253 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1254 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1256 // and andres, oldval, incr2
1257 // nor binopres, $0, andres
1258 // and newval, binopres, mask
1259 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1260 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1261 .addReg(Mips::ZERO).addReg(AndRes);
1262 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1263 } else if (BinOpcode) {
1264 // <binop> binopres, oldval, incr2
1265 // and newval, binopres, mask
1266 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1267 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1268 } else { // atomic.swap
1269 // and newval, incr2, mask
1270 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1273 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1274 .addReg(OldVal).addReg(Mask2);
1275 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1276 .addReg(MaskedOldVal0).addReg(NewVal);
1277 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1278 BuildMI(BB, DL, TII->get(SC), Success)
1279 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1280 BuildMI(BB, DL, TII->get(Mips::BEQ))
1281 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1284 // and maskedoldval1,oldval,mask
1285 // srl srlres,maskedoldval1,shiftamt
1286 // sign_extend dest,srlres
1289 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1290 .addReg(OldVal).addReg(Mask);
1291 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1292 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1293 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1295 MI->eraseFromParent(); // The instruction is gone now.
1300 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1301 MachineBasicBlock *BB,
1302 unsigned Size) const {
1303 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1305 MachineFunction *MF = BB->getParent();
1306 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1307 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1308 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1309 DebugLoc DL = MI->getDebugLoc();
1310 unsigned LL, SC, ZERO, BNE, BEQ;
1313 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1314 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1321 ZERO = Mips::ZERO_64;
1326 unsigned Dest = MI->getOperand(0).getReg();
1327 unsigned Ptr = MI->getOperand(1).getReg();
1328 unsigned OldVal = MI->getOperand(2).getReg();
1329 unsigned NewVal = MI->getOperand(3).getReg();
1331 unsigned Success = RegInfo.createVirtualRegister(RC);
1333 // insert new blocks after the current block
1334 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1335 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1336 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1337 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1338 MachineFunction::iterator It = BB;
1340 MF->insert(It, loop1MBB);
1341 MF->insert(It, loop2MBB);
1342 MF->insert(It, exitMBB);
1344 // Transfer the remainder of BB and its successor edges to exitMBB.
1345 exitMBB->splice(exitMBB->begin(), BB,
1346 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1347 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1351 // fallthrough --> loop1MBB
1352 BB->addSuccessor(loop1MBB);
1353 loop1MBB->addSuccessor(exitMBB);
1354 loop1MBB->addSuccessor(loop2MBB);
1355 loop2MBB->addSuccessor(loop1MBB);
1356 loop2MBB->addSuccessor(exitMBB);
1360 // bne dest, oldval, exitMBB
1362 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1363 BuildMI(BB, DL, TII->get(BNE))
1364 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1367 // sc success, newval, 0(ptr)
1368 // beq success, $0, loop1MBB
1370 BuildMI(BB, DL, TII->get(SC), Success)
1371 .addReg(NewVal).addReg(Ptr).addImm(0);
1372 BuildMI(BB, DL, TII->get(BEQ))
1373 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1375 MI->eraseFromParent(); // The instruction is gone now.
1381 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1382 MachineBasicBlock *BB,
1383 unsigned Size) const {
1384 assert((Size == 1 || Size == 2) &&
1385 "Unsupported size for EmitAtomicCmpSwapPartial.");
1387 MachineFunction *MF = BB->getParent();
1388 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1389 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1390 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1391 DebugLoc DL = MI->getDebugLoc();
1393 unsigned Dest = MI->getOperand(0).getReg();
1394 unsigned Ptr = MI->getOperand(1).getReg();
1395 unsigned CmpVal = MI->getOperand(2).getReg();
1396 unsigned NewVal = MI->getOperand(3).getReg();
1398 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1399 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1400 unsigned Mask = RegInfo.createVirtualRegister(RC);
1401 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1402 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1403 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1404 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1405 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1406 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1407 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1408 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1409 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1410 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1411 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1412 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1413 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1414 unsigned Success = RegInfo.createVirtualRegister(RC);
1416 // insert new blocks after the current block
1417 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1418 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1419 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1420 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1421 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1422 MachineFunction::iterator It = BB;
1424 MF->insert(It, loop1MBB);
1425 MF->insert(It, loop2MBB);
1426 MF->insert(It, sinkMBB);
1427 MF->insert(It, exitMBB);
1429 // Transfer the remainder of BB and its successor edges to exitMBB.
1430 exitMBB->splice(exitMBB->begin(), BB,
1431 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1432 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1434 BB->addSuccessor(loop1MBB);
1435 loop1MBB->addSuccessor(sinkMBB);
1436 loop1MBB->addSuccessor(loop2MBB);
1437 loop2MBB->addSuccessor(loop1MBB);
1438 loop2MBB->addSuccessor(sinkMBB);
1439 sinkMBB->addSuccessor(exitMBB);
1441 // FIXME: computation of newval2 can be moved to loop2MBB.
1443 // addiu masklsb2,$0,-4 # 0xfffffffc
1444 // and alignedaddr,ptr,masklsb2
1445 // andi ptrlsb2,ptr,3
1446 // sll shiftamt,ptrlsb2,3
1447 // ori maskupper,$0,255 # 0xff
1448 // sll mask,maskupper,shiftamt
1449 // nor mask2,$0,mask
1450 // andi maskedcmpval,cmpval,255
1451 // sll shiftedcmpval,maskedcmpval,shiftamt
1452 // andi maskednewval,newval,255
1453 // sll shiftednewval,maskednewval,shiftamt
1454 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1455 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1456 .addReg(Mips::ZERO).addImm(-4);
1457 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1458 .addReg(Ptr).addReg(MaskLSB2);
1459 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1460 if (Subtarget.isLittle()) {
1461 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1463 unsigned Off = RegInfo.createVirtualRegister(RC);
1464 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1465 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1466 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1468 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1469 .addReg(Mips::ZERO).addImm(MaskImm);
1470 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1471 .addReg(MaskUpper).addReg(ShiftAmt);
1472 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1473 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1474 .addReg(CmpVal).addImm(MaskImm);
1475 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1476 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1477 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1478 .addReg(NewVal).addImm(MaskImm);
1479 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1480 .addReg(MaskedNewVal).addReg(ShiftAmt);
1483 // ll oldval,0(alginedaddr)
1484 // and maskedoldval0,oldval,mask
1485 // bne maskedoldval0,shiftedcmpval,sinkMBB
1487 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1488 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1489 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1490 .addReg(OldVal).addReg(Mask);
1491 BuildMI(BB, DL, TII->get(Mips::BNE))
1492 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1495 // and maskedoldval1,oldval,mask2
1496 // or storeval,maskedoldval1,shiftednewval
1497 // sc success,storeval,0(alignedaddr)
1498 // beq success,$0,loop1MBB
1500 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1501 .addReg(OldVal).addReg(Mask2);
1502 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1503 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1504 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1505 BuildMI(BB, DL, TII->get(SC), Success)
1506 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1507 BuildMI(BB, DL, TII->get(Mips::BEQ))
1508 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1511 // srl srlres,maskedoldval0,shiftamt
1512 // sign_extend dest,srlres
1515 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1516 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1517 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1519 MI->eraseFromParent(); // The instruction is gone now.
1524 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1525 MachineBasicBlock *BB) const {
1526 MachineFunction *MF = BB->getParent();
1527 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1528 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1529 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1530 DebugLoc DL = MI->getDebugLoc();
1531 MachineBasicBlock::iterator II(MI);
1533 unsigned Fc = MI->getOperand(1).getReg();
1534 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1536 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1538 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1541 .addImm(Mips::sub_lo);
1543 // We don't erase the original instruction, we just replace the condition
1544 // register with the 64-bit super-register.
1545 MI->getOperand(1).setReg(Fc2);
1550 //===----------------------------------------------------------------------===//
1551 // Misc Lower Operation implementation
1552 //===----------------------------------------------------------------------===//
1553 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1554 SDValue Chain = Op.getOperand(0);
1555 SDValue Table = Op.getOperand(1);
1556 SDValue Index = Op.getOperand(2);
1558 EVT PTy = getPointerTy();
1559 unsigned EntrySize =
1560 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1562 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1563 DAG.getConstant(EntrySize, DL, PTy));
1564 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1566 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1567 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1568 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1570 Chain = Addr.getValue(1);
1572 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1573 // For PIC, the sequence is:
1574 // BRIND(load(Jumptable + index) + RelocBase)
1575 // RelocBase can be JumpTable, GOT or some sort of global base.
1576 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1577 getPICJumpTableRelocBase(Table, DAG));
1580 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1583 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1584 // The first operand is the chain, the second is the condition, the third is
1585 // the block to branch to if the condition is true.
1586 SDValue Chain = Op.getOperand(0);
1587 SDValue Dest = Op.getOperand(2);
1590 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1591 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1593 // Return if flag is not set by a floating point comparison.
1594 if (CondRes.getOpcode() != MipsISD::FPCmp)
1597 SDValue CCNode = CondRes.getOperand(2);
1599 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1600 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1601 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1602 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1603 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1604 FCC0, Dest, CondRes);
1607 SDValue MipsTargetLowering::
1608 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1610 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1611 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1613 // Return if flag is not set by a floating point comparison.
1614 if (Cond.getOpcode() != MipsISD::FPCmp)
1617 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1621 SDValue MipsTargetLowering::
1622 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1625 EVT Ty = Op.getOperand(0).getValueType();
1626 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1627 getSetCCResultType(*DAG.getContext(), Ty),
1628 Op.getOperand(0), Op.getOperand(1),
1631 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1635 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1636 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1637 SDValue Cond = createFPCmp(DAG, Op);
1639 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1640 "Floating point operand expected.");
1643 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1644 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1646 return createCMovFP(DAG, Cond, True, False, DL);
1649 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1650 SelectionDAG &DAG) const {
1651 EVT Ty = Op.getValueType();
1652 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1653 const GlobalValue *GV = N->getGlobal();
1655 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1656 const MipsTargetObjectFile *TLOF =
1657 static_cast<const MipsTargetObjectFile *>(
1658 getTargetMachine().getObjFileLowering());
1659 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1660 // %gp_rel relocation
1661 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1663 // %hi/%lo relocation
1664 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1667 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1668 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1671 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1672 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1673 MachinePointerInfo::getGOT());
1675 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1676 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP
1678 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1681 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1682 SelectionDAG &DAG) const {
1683 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1684 EVT Ty = Op.getValueType();
1686 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1687 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1689 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1692 SDValue MipsTargetLowering::
1693 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1695 // If the relocation model is PIC, use the General Dynamic TLS Model or
1696 // Local Dynamic TLS model, otherwise use the Initial Exec or
1697 // Local Exec TLS Model.
1699 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1701 const GlobalValue *GV = GA->getGlobal();
1702 EVT PtrVT = getPointerTy();
1704 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1706 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1707 // General Dynamic and Local Dynamic TLS Model.
1708 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1711 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1712 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1713 getGlobalReg(DAG, PtrVT), TGA);
1714 unsigned PtrSize = PtrVT.getSizeInBits();
1715 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1717 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1721 Entry.Node = Argument;
1723 Args.push_back(Entry);
1725 TargetLowering::CallLoweringInfo CLI(DAG);
1726 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1727 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1728 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1730 SDValue Ret = CallResult.first;
1732 if (model != TLSModel::LocalDynamic)
1735 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1736 MipsII::MO_DTPREL_HI);
1737 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1738 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1739 MipsII::MO_DTPREL_LO);
1740 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1741 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1742 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1746 if (model == TLSModel::InitialExec) {
1747 // Initial Exec TLS Model
1748 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1749 MipsII::MO_GOTTPREL);
1750 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1752 Offset = DAG.getLoad(PtrVT, DL,
1753 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1754 false, false, false, 0);
1756 // Local Exec TLS Model
1757 assert(model == TLSModel::LocalExec);
1758 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1759 MipsII::MO_TPREL_HI);
1760 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1761 MipsII::MO_TPREL_LO);
1762 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1763 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1764 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1767 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1768 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1771 SDValue MipsTargetLowering::
1772 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1774 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1775 EVT Ty = Op.getValueType();
1777 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1778 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1780 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1783 SDValue MipsTargetLowering::
1784 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1786 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1787 EVT Ty = Op.getValueType();
1789 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1790 const MipsTargetObjectFile *TLOF =
1791 static_cast<const MipsTargetObjectFile *>(
1792 getTargetMachine().getObjFileLowering());
1794 if (TLOF->IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1795 // %gp_rel relocation
1796 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1798 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1801 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1804 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1805 MachineFunction &MF = DAG.getMachineFunction();
1806 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1809 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1812 // vastart just stores the address of the VarArgsFrameIndex slot into the
1813 // memory location argument.
1814 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1815 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1816 MachinePointerInfo(SV), false, false, 0);
1819 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1820 SDNode *Node = Op.getNode();
1821 EVT VT = Node->getValueType(0);
1822 SDValue Chain = Node->getOperand(0);
1823 SDValue VAListPtr = Node->getOperand(1);
1824 unsigned Align = Node->getConstantOperandVal(3);
1825 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1827 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1829 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1830 MachinePointerInfo(SV), false, false, false,
1832 SDValue VAList = VAListLoad;
1834 // Re-align the pointer if necessary.
1835 // It should only ever be necessary for 64-bit types on O32 since the minimum
1836 // argument alignment is the same as the maximum type alignment for N32/N64.
1838 // FIXME: We currently align too often. The code generator doesn't notice
1839 // when the pointer is still aligned from the last va_arg (or pair of
1840 // va_args for the i64 on O32 case).
1841 if (Align > getMinStackArgumentAlignment()) {
1842 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1844 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1845 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1847 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1848 DAG.getConstant(-(int64_t)Align, DL,
1849 VAList.getValueType()));
1852 // Increment the pointer, VAList, to the next vaarg.
1853 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1854 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1855 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1856 ArgSlotSizeInBytes),
1857 DL, VAList.getValueType()));
1858 // Store the incremented VAList to the legalized pointer
1859 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1860 MachinePointerInfo(SV), false, false, 0);
1862 // In big-endian mode we must adjust the pointer when the load size is smaller
1863 // than the argument slot size. We must also reduce the known alignment to
1864 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1865 // the correct half of the slot, and reduce the alignment from 8 (slot
1866 // alignment) down to 4 (type alignment).
1867 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1868 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1869 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1870 DAG.getIntPtrConstant(Adjustment, DL));
1872 // Load the actual argument out of the pointer VAList
1873 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1877 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1878 bool HasExtractInsert) {
1879 EVT TyX = Op.getOperand(0).getValueType();
1880 EVT TyY = Op.getOperand(1).getValueType();
1882 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1883 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1886 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1888 SDValue X = (TyX == MVT::f32) ?
1889 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1890 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1892 SDValue Y = (TyY == MVT::f32) ?
1893 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1894 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1897 if (HasExtractInsert) {
1898 // ext E, Y, 31, 1 ; extract bit31 of Y
1899 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1900 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1901 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1904 // srl SrlX, SllX, 1
1906 // sll SllY, SrlX, 31
1907 // or Or, SrlX, SllY
1908 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1909 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1910 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1911 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1912 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1915 if (TyX == MVT::f32)
1916 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1918 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1920 DAG.getConstant(0, DL, MVT::i32));
1921 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1924 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1925 bool HasExtractInsert) {
1926 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1927 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1928 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1930 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1932 // Bitcast to integer nodes.
1933 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1934 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1936 if (HasExtractInsert) {
1937 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1938 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1939 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1940 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1942 if (WidthX > WidthY)
1943 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1944 else if (WidthY > WidthX)
1945 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1947 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1948 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1950 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1953 // (d)sll SllX, X, 1
1954 // (d)srl SrlX, SllX, 1
1955 // (d)srl SrlY, Y, width(Y)-1
1956 // (d)sll SllY, SrlX, width(Y)-1
1957 // or Or, SrlX, SllY
1958 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1959 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1960 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1961 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1963 if (WidthX > WidthY)
1964 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1965 else if (WidthY > WidthX)
1966 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1968 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1969 DAG.getConstant(WidthX - 1, DL, MVT::i32));
1970 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1971 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1975 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1976 if (Subtarget.isGP64bit())
1977 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1979 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1982 SDValue MipsTargetLowering::
1983 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1985 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1986 "Frame address can only be determined for current frame.");
1988 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1989 MFI->setFrameAddressIsTaken(true);
1990 EVT VT = Op.getValueType();
1992 SDValue FrameAddr = DAG.getCopyFromReg(
1993 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
1997 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1998 SelectionDAG &DAG) const {
1999 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2003 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2004 "Return address can be determined only for current frame.");
2006 MachineFunction &MF = DAG.getMachineFunction();
2007 MachineFrameInfo *MFI = MF.getFrameInfo();
2008 MVT VT = Op.getSimpleValueType();
2009 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2010 MFI->setReturnAddressIsTaken(true);
2012 // Return RA, which contains the return address. Mark it an implicit live-in.
2013 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2014 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2017 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2018 // generated from __builtin_eh_return (offset, handler)
2019 // The effect of this is to adjust the stack pointer by "offset"
2020 // and then branch to "handler".
2021 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2023 MachineFunction &MF = DAG.getMachineFunction();
2024 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2026 MipsFI->setCallsEhReturn();
2027 SDValue Chain = Op.getOperand(0);
2028 SDValue Offset = Op.getOperand(1);
2029 SDValue Handler = Op.getOperand(2);
2031 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2033 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2034 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2035 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2036 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2037 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2038 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2039 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2040 DAG.getRegister(OffsetReg, Ty),
2041 DAG.getRegister(AddrReg, getPointerTy()),
2045 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2046 SelectionDAG &DAG) const {
2047 // FIXME: Need pseudo-fence for 'singlethread' fences
2048 // FIXME: Set SType for weaker fences where supported/appropriate.
2051 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2052 DAG.getConstant(SType, DL, MVT::i32));
2055 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2056 SelectionDAG &DAG) const {
2058 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2060 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2061 SDValue Shamt = Op.getOperand(2);
2062 // if shamt < (VT.bits):
2063 // lo = (shl lo, shamt)
2064 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2067 // hi = (shl lo, shamt[4:0])
2068 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2069 DAG.getConstant(-1, DL, MVT::i32));
2070 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2071 DAG.getConstant(1, DL, VT));
2072 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2073 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2074 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2075 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2076 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2077 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2078 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2079 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2080 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2082 SDValue Ops[2] = {Lo, Hi};
2083 return DAG.getMergeValues(Ops, DL);
2086 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2089 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2090 SDValue Shamt = Op.getOperand(2);
2091 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2093 // if shamt < (VT.bits):
2094 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2096 // hi = (sra hi, shamt)
2098 // hi = (srl hi, shamt)
2101 // lo = (sra hi, shamt[4:0])
2102 // hi = (sra hi, 31)
2104 // lo = (srl hi, shamt[4:0])
2106 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2107 DAG.getConstant(-1, DL, MVT::i32));
2108 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2109 DAG.getConstant(1, DL, VT));
2110 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2111 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2112 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2113 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2115 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2116 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2117 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2118 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2119 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2120 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2121 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2123 SDValue Ops[2] = {Lo, Hi};
2124 return DAG.getMergeValues(Ops, DL);
2127 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2128 SDValue Chain, SDValue Src, unsigned Offset) {
2129 SDValue Ptr = LD->getBasePtr();
2130 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2131 EVT BasePtrVT = Ptr.getValueType();
2133 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2136 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2137 DAG.getConstant(Offset, DL, BasePtrVT));
2139 SDValue Ops[] = { Chain, Ptr, Src };
2140 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2141 LD->getMemOperand());
2144 // Expand an unaligned 32 or 64-bit integer load node.
2145 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2146 LoadSDNode *LD = cast<LoadSDNode>(Op);
2147 EVT MemVT = LD->getMemoryVT();
2149 if (Subtarget.systemSupportsUnalignedAccess())
2152 // Return if load is aligned or if MemVT is neither i32 nor i64.
2153 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2154 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2157 bool IsLittle = Subtarget.isLittle();
2158 EVT VT = Op.getValueType();
2159 ISD::LoadExtType ExtType = LD->getExtensionType();
2160 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2162 assert((VT == MVT::i32) || (VT == MVT::i64));
2165 // (set dst, (i64 (load baseptr)))
2167 // (set tmp, (ldl (add baseptr, 7), undef))
2168 // (set dst, (ldr baseptr, tmp))
2169 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2170 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2172 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2176 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2178 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2182 // (set dst, (i32 (load baseptr))) or
2183 // (set dst, (i64 (sextload baseptr))) or
2184 // (set dst, (i64 (extload baseptr)))
2186 // (set tmp, (lwl (add baseptr, 3), undef))
2187 // (set dst, (lwr baseptr, tmp))
2188 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2189 (ExtType == ISD::EXTLOAD))
2192 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2195 // (set dst, (i64 (zextload baseptr)))
2197 // (set tmp0, (lwl (add baseptr, 3), undef))
2198 // (set tmp1, (lwr baseptr, tmp0))
2199 // (set tmp2, (shl tmp1, 32))
2200 // (set dst, (srl tmp2, 32))
2202 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2203 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2204 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2205 SDValue Ops[] = { SRL, LWR.getValue(1) };
2206 return DAG.getMergeValues(Ops, DL);
2209 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2210 SDValue Chain, unsigned Offset) {
2211 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2212 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2214 SDVTList VTList = DAG.getVTList(MVT::Other);
2217 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2218 DAG.getConstant(Offset, DL, BasePtrVT));
2220 SDValue Ops[] = { Chain, Value, Ptr };
2221 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2222 SD->getMemOperand());
2225 // Expand an unaligned 32 or 64-bit integer store node.
2226 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2228 SDValue Value = SD->getValue(), Chain = SD->getChain();
2229 EVT VT = Value.getValueType();
2232 // (store val, baseptr) or
2233 // (truncstore val, baseptr)
2235 // (swl val, (add baseptr, 3))
2236 // (swr val, baseptr)
2237 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2238 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2240 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2243 assert(VT == MVT::i64);
2246 // (store val, baseptr)
2248 // (sdl val, (add baseptr, 7))
2249 // (sdr val, baseptr)
2250 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2251 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2254 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2255 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2256 SDValue Val = SD->getValue();
2258 if (Val.getOpcode() != ISD::FP_TO_SINT)
2261 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2262 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2265 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2266 SD->getPointerInfo(), SD->isVolatile(),
2267 SD->isNonTemporal(), SD->getAlignment());
2270 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2271 StoreSDNode *SD = cast<StoreSDNode>(Op);
2272 EVT MemVT = SD->getMemoryVT();
2274 // Lower unaligned integer stores.
2275 if (!Subtarget.systemSupportsUnalignedAccess() &&
2276 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2277 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2278 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2280 return lowerFP_TO_SINT_STORE(SD, DAG);
2283 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2284 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2285 || cast<ConstantSDNode>
2286 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2287 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2291 // (add (frameaddr 0), (frame_to_args_offset))
2292 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2293 // (add FrameObject, 0)
2294 // where FrameObject is a fixed StackObject with offset 0 which points to
2295 // the old stack pointer.
2296 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2297 EVT ValTy = Op->getValueType(0);
2298 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2299 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2301 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2302 DAG.getConstant(0, DL, ValTy));
2305 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2306 SelectionDAG &DAG) const {
2307 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2308 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2310 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2313 //===----------------------------------------------------------------------===//
2314 // Calling Convention Implementation
2315 //===----------------------------------------------------------------------===//
2317 //===----------------------------------------------------------------------===//
2318 // TODO: Implement a generic logic using tblgen that can support this.
2319 // Mips O32 ABI rules:
2321 // i32 - Passed in A0, A1, A2, A3 and stack
2322 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2323 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2324 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2325 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2326 // not used, it must be shadowed. If only A3 is available, shadow it and
2329 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2330 //===----------------------------------------------------------------------===//
2332 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2333 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2334 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2335 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2336 State.getMachineFunction().getSubtarget());
2338 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2339 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2341 // Do not process byval args here.
2342 if (ArgFlags.isByVal())
2345 // Promote i8 and i16
2346 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2347 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2349 if (ArgFlags.isSExt())
2350 LocInfo = CCValAssign::SExtUpper;
2351 else if (ArgFlags.isZExt())
2352 LocInfo = CCValAssign::ZExtUpper;
2354 LocInfo = CCValAssign::AExtUpper;
2358 // Promote i8 and i16
2359 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2361 if (ArgFlags.isSExt())
2362 LocInfo = CCValAssign::SExt;
2363 else if (ArgFlags.isZExt())
2364 LocInfo = CCValAssign::ZExt;
2366 LocInfo = CCValAssign::AExt;
2371 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2372 // is true: function is vararg, argument is 3rd or higher, there is previous
2373 // argument which is not f32 or f64.
2374 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2375 State.getFirstUnallocated(F32Regs) != ValNo;
2376 unsigned OrigAlign = ArgFlags.getOrigAlign();
2377 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2379 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2380 Reg = State.AllocateReg(IntRegs);
2381 // If this is the first part of an i64 arg,
2382 // the allocated register must be either A0 or A2.
2383 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2384 Reg = State.AllocateReg(IntRegs);
2386 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2387 // Allocate int register and shadow next int register. If first
2388 // available register is Mips::A1 or Mips::A3, shadow it too.
2389 Reg = State.AllocateReg(IntRegs);
2390 if (Reg == Mips::A1 || Reg == Mips::A3)
2391 Reg = State.AllocateReg(IntRegs);
2392 State.AllocateReg(IntRegs);
2394 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2395 // we are guaranteed to find an available float register
2396 if (ValVT == MVT::f32) {
2397 Reg = State.AllocateReg(F32Regs);
2398 // Shadow int register
2399 State.AllocateReg(IntRegs);
2401 Reg = State.AllocateReg(F64Regs);
2402 // Shadow int registers
2403 unsigned Reg2 = State.AllocateReg(IntRegs);
2404 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2405 State.AllocateReg(IntRegs);
2406 State.AllocateReg(IntRegs);
2409 llvm_unreachable("Cannot handle this ValVT.");
2412 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2414 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2416 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2421 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2422 MVT LocVT, CCValAssign::LocInfo LocInfo,
2423 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2424 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2426 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2429 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2430 MVT LocVT, CCValAssign::LocInfo LocInfo,
2431 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2432 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2434 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2437 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2438 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2439 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2441 #include "MipsGenCallingConv.inc"
2443 //===----------------------------------------------------------------------===//
2444 // Call Calling Convention Implementation
2445 //===----------------------------------------------------------------------===//
2447 // Return next O32 integer argument register.
2448 static unsigned getNextIntArgReg(unsigned Reg) {
2449 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2450 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2454 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2455 SDValue Chain, SDValue Arg, SDLoc DL,
2456 bool IsTailCall, SelectionDAG &DAG) const {
2458 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2459 DAG.getIntPtrConstant(Offset, DL));
2460 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2464 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2465 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2466 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2467 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2468 /*isVolatile=*/ true, false, 0);
2471 void MipsTargetLowering::
2472 getOpndList(SmallVectorImpl<SDValue> &Ops,
2473 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2474 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2475 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2476 SDValue Chain) const {
2477 // Insert node "GP copy globalreg" before call to function.
2479 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2480 // in PIC mode) allow symbols to be resolved via lazy binding.
2481 // The lazy binding stub requires GP to point to the GOT.
2482 // Note that we don't need GP to point to the GOT for indirect calls
2483 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2484 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2485 // used for the function (that is, Mips linker doesn't generate lazy binding
2486 // stub for a function whose address is taken in the program).
2487 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2488 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2489 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2490 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2493 // Build a sequence of copy-to-reg nodes chained together with token
2494 // chain and flag operands which copy the outgoing args into registers.
2495 // The InFlag in necessary since all emitted instructions must be
2499 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2500 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2501 RegsToPass[i].second, InFlag);
2502 InFlag = Chain.getValue(1);
2505 // Add argument registers to the end of the list so that they are
2506 // known live into the call.
2507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2508 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2509 RegsToPass[i].second.getValueType()));
2511 // Add a register mask operand representing the call-preserved registers.
2512 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2513 const uint32_t *Mask =
2514 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2515 assert(Mask && "Missing call preserved mask for calling convention");
2516 if (Subtarget.inMips16HardFloat()) {
2517 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2518 llvm::StringRef Sym = G->getGlobal()->getName();
2519 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2520 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2521 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2525 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2527 if (InFlag.getNode())
2528 Ops.push_back(InFlag);
2531 /// LowerCall - functions arguments are copied from virtual regs to
2532 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2534 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2535 SmallVectorImpl<SDValue> &InVals) const {
2536 SelectionDAG &DAG = CLI.DAG;
2538 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2539 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2540 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2541 SDValue Chain = CLI.Chain;
2542 SDValue Callee = CLI.Callee;
2543 bool &IsTailCall = CLI.IsTailCall;
2544 CallingConv::ID CallConv = CLI.CallConv;
2545 bool IsVarArg = CLI.IsVarArg;
2547 MachineFunction &MF = DAG.getMachineFunction();
2548 MachineFrameInfo *MFI = MF.getFrameInfo();
2549 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2550 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2551 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2553 // Analyze operands of the call, assigning locations to each operand.
2554 SmallVector<CCValAssign, 16> ArgLocs;
2556 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2557 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2559 // Allocate the reserved argument area. It seems strange to do this from the
2560 // caller side but removing it breaks the frame size calculation.
2561 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2563 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2565 // Get a count of how many bytes are to be pushed on the stack.
2566 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2568 // Check if it's really possible to do a tail call.
2570 IsTailCall = isEligibleForTailCallOptimization(
2571 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2573 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2574 report_fatal_error("failed to perform tail call elimination on a call "
2575 "site marked musttail");
2580 // Chain is the output chain of the last Load/Store or CopyToReg node.
2581 // ByValChain is the output chain of the last Memcpy node created for copying
2582 // byval arguments to the stack.
2583 unsigned StackAlignment = TFL->getStackAlignment();
2584 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2585 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2588 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2590 SDValue StackPtr = DAG.getCopyFromReg(
2591 Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2593 // With EABI is it possible to have 16 args on registers.
2594 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2595 SmallVector<SDValue, 8> MemOpChains;
2597 CCInfo.rewindByValRegsInfo();
2599 // Walk the register/memloc assignments, inserting copies/loads.
2600 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2601 SDValue Arg = OutVals[i];
2602 CCValAssign &VA = ArgLocs[i];
2603 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2604 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2605 bool UseUpperBits = false;
2608 if (Flags.isByVal()) {
2609 unsigned FirstByValReg, LastByValReg;
2610 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2611 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2613 assert(Flags.getByValSize() &&
2614 "ByVal args of size 0 should have been ignored by front-end.");
2615 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2616 assert(!IsTailCall &&
2617 "Do not tail-call optimize if there is a byval argument.");
2618 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2619 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2621 CCInfo.nextInRegsParam();
2625 // Promote the value if needed.
2626 switch (VA.getLocInfo()) {
2628 llvm_unreachable("Unknown loc info!");
2629 case CCValAssign::Full:
2630 if (VA.isRegLoc()) {
2631 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2632 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2633 (ValVT == MVT::i64 && LocVT == MVT::f64))
2634 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2635 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2636 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2637 Arg, DAG.getConstant(0, DL, MVT::i32));
2638 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2639 Arg, DAG.getConstant(1, DL, MVT::i32));
2640 if (!Subtarget.isLittle())
2642 unsigned LocRegLo = VA.getLocReg();
2643 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2644 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2645 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2650 case CCValAssign::BCvt:
2651 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2653 case CCValAssign::SExtUpper:
2654 UseUpperBits = true;
2656 case CCValAssign::SExt:
2657 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2659 case CCValAssign::ZExtUpper:
2660 UseUpperBits = true;
2662 case CCValAssign::ZExt:
2663 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2665 case CCValAssign::AExtUpper:
2666 UseUpperBits = true;
2668 case CCValAssign::AExt:
2669 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2674 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2675 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2677 ISD::SHL, DL, VA.getLocVT(), Arg,
2678 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2681 // Arguments that can be passed on register must be kept at
2682 // RegsToPass vector
2683 if (VA.isRegLoc()) {
2684 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2688 // Register can't get to this point...
2689 assert(VA.isMemLoc());
2691 // emit ISD::STORE whichs stores the
2692 // parameter value to a stack Location
2693 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2694 Chain, Arg, DL, IsTailCall, DAG));
2697 // Transform all store nodes into one single node because all store
2698 // nodes are independent of each other.
2699 if (!MemOpChains.empty())
2700 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2702 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2703 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2704 // node so that legalize doesn't hack it.
2705 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2707 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2709 EVT Ty = Callee.getValueType();
2711 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2713 const GlobalValue *Val = G->getGlobal();
2714 InternalLinkage = Val->hasInternalLinkage();
2716 if (InternalLinkage)
2717 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2718 else if (LargeGOT) {
2719 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2720 MipsII::MO_CALL_LO16, Chain,
2721 FuncInfo->callPtrInfo(Val));
2724 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2725 FuncInfo->callPtrInfo(Val));
2729 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2730 MipsII::MO_NO_FLAG);
2731 GlobalOrExternal = true;
2733 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2734 const char *Sym = S->getSymbol();
2736 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2738 DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2739 else if (LargeGOT) {
2740 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2741 MipsII::MO_CALL_LO16, Chain,
2742 FuncInfo->callPtrInfo(Sym));
2744 } else { // N64 || PIC
2745 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2746 FuncInfo->callPtrInfo(Sym));
2750 GlobalOrExternal = true;
2753 SmallVector<SDValue, 8> Ops(1, Chain);
2754 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2756 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2757 IsCallReloc, CLI, Callee, Chain);
2760 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2762 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2763 SDValue InFlag = Chain.getValue(1);
2765 // Create the CALLSEQ_END node.
2766 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2767 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2768 InFlag = Chain.getValue(1);
2770 // Handle result values, copying them out of physregs into vregs that we
2772 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2776 /// LowerCallResult - Lower the result values of a call into the
2777 /// appropriate copies out of appropriate physical registers.
2778 SDValue MipsTargetLowering::LowerCallResult(
2779 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2780 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2781 SmallVectorImpl<SDValue> &InVals,
2782 TargetLowering::CallLoweringInfo &CLI) const {
2783 // Assign locations to each value returned by this call.
2784 SmallVector<CCValAssign, 16> RVLocs;
2785 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2787 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2789 // Copy all of the result registers out of their specified physreg.
2790 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2791 CCValAssign &VA = RVLocs[i];
2792 assert(VA.isRegLoc() && "Can only return in registers!");
2794 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2795 RVLocs[i].getLocVT(), InFlag);
2796 Chain = Val.getValue(1);
2797 InFlag = Val.getValue(2);
2799 if (VA.isUpperBitsInLoc()) {
2800 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2801 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2803 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2805 Shift, DL, VA.getLocVT(), Val,
2806 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2809 switch (VA.getLocInfo()) {
2811 llvm_unreachable("Unknown loc info!");
2812 case CCValAssign::Full:
2814 case CCValAssign::BCvt:
2815 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2817 case CCValAssign::AExt:
2818 case CCValAssign::AExtUpper:
2819 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2821 case CCValAssign::ZExt:
2822 case CCValAssign::ZExtUpper:
2823 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2824 DAG.getValueType(VA.getValVT()));
2825 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2827 case CCValAssign::SExt:
2828 case CCValAssign::SExtUpper:
2829 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2830 DAG.getValueType(VA.getValVT()));
2831 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2835 InVals.push_back(Val);
2841 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2842 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2843 MVT LocVT = VA.getLocVT();
2844 EVT ValVT = VA.getValVT();
2846 // Shift into the upper bits if necessary.
2847 switch (VA.getLocInfo()) {
2850 case CCValAssign::AExtUpper:
2851 case CCValAssign::SExtUpper:
2852 case CCValAssign::ZExtUpper: {
2853 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2854 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2856 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2858 Opcode, DL, VA.getLocVT(), Val,
2859 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2864 // If this is an value smaller than the argument slot size (32-bit for O32,
2865 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2866 // size. Extract the value and insert any appropriate assertions regarding
2867 // sign/zero extension.
2868 switch (VA.getLocInfo()) {
2870 llvm_unreachable("Unknown loc info!");
2871 case CCValAssign::Full:
2873 case CCValAssign::AExtUpper:
2874 case CCValAssign::AExt:
2875 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2877 case CCValAssign::SExtUpper:
2878 case CCValAssign::SExt:
2879 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2880 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2882 case CCValAssign::ZExtUpper:
2883 case CCValAssign::ZExt:
2884 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2885 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2887 case CCValAssign::BCvt:
2888 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2895 //===----------------------------------------------------------------------===//
2896 // Formal Arguments Calling Convention Implementation
2897 //===----------------------------------------------------------------------===//
2898 /// LowerFormalArguments - transform physical registers into virtual registers
2899 /// and generate load operations for arguments places on the stack.
2901 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2902 CallingConv::ID CallConv,
2904 const SmallVectorImpl<ISD::InputArg> &Ins,
2905 SDLoc DL, SelectionDAG &DAG,
2906 SmallVectorImpl<SDValue> &InVals)
2908 MachineFunction &MF = DAG.getMachineFunction();
2909 MachineFrameInfo *MFI = MF.getFrameInfo();
2910 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2912 MipsFI->setVarArgsFrameIndex(0);
2914 // Used with vargs to acumulate store chains.
2915 std::vector<SDValue> OutChains;
2917 // Assign locations to all of the incoming arguments.
2918 SmallVector<CCValAssign, 16> ArgLocs;
2919 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2921 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2922 Function::const_arg_iterator FuncArg =
2923 DAG.getMachineFunction().getFunction()->arg_begin();
2925 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2926 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2927 CCInfo.getInRegsParamsCount() > 0);
2929 unsigned CurArgIdx = 0;
2930 CCInfo.rewindByValRegsInfo();
2932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2933 CCValAssign &VA = ArgLocs[i];
2934 if (Ins[i].isOrigArg()) {
2935 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2936 CurArgIdx = Ins[i].getOrigArgIndex();
2938 EVT ValVT = VA.getValVT();
2939 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2940 bool IsRegLoc = VA.isRegLoc();
2942 if (Flags.isByVal()) {
2943 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2944 unsigned FirstByValReg, LastByValReg;
2945 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2946 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2948 assert(Flags.getByValSize() &&
2949 "ByVal args of size 0 should have been ignored by front-end.");
2950 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2951 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2952 FirstByValReg, LastByValReg, VA, CCInfo);
2953 CCInfo.nextInRegsParam();
2957 // Arguments stored on registers
2959 MVT RegVT = VA.getLocVT();
2960 unsigned ArgReg = VA.getLocReg();
2961 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2963 // Transform the arguments stored on
2964 // physical registers into virtual ones
2965 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2966 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2968 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2970 // Handle floating point arguments passed in integer registers and
2971 // long double arguments passed in floating point registers.
2972 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2973 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2974 (RegVT == MVT::f64 && ValVT == MVT::i64))
2975 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2976 else if (ABI.IsO32() && RegVT == MVT::i32 &&
2977 ValVT == MVT::f64) {
2978 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2979 getNextIntArgReg(ArgReg), RC);
2980 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2981 if (!Subtarget.isLittle())
2982 std::swap(ArgValue, ArgValue2);
2983 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2984 ArgValue, ArgValue2);
2987 InVals.push_back(ArgValue);
2988 } else { // VA.isRegLoc()
2989 MVT LocVT = VA.getLocVT();
2992 // We ought to be able to use LocVT directly but O32 sets it to i32
2993 // when allocating floating point values to integer registers.
2994 // This shouldn't influence how we load the value into registers unless
2995 // we are targetting softfloat.
2996 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2997 LocVT = VA.getValVT();
3001 assert(VA.isMemLoc());
3003 // The stack pointer offset is relative to the caller stack frame.
3004 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3005 VA.getLocMemOffset(), true);
3007 // Create load nodes to retrieve arguments from the stack
3008 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3009 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
3010 MachinePointerInfo::getFixedStack(FI),
3011 false, false, false, 0);
3012 OutChains.push_back(ArgValue.getValue(1));
3014 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3016 InVals.push_back(ArgValue);
3020 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021 // The mips ABIs for returning structs by value requires that we copy
3022 // the sret argument into $v0 for the return. Save the argument into
3023 // a virtual register so that we can access it from the return points.
3024 if (Ins[i].Flags.isSRet()) {
3025 unsigned Reg = MipsFI->getSRetReturnReg();
3027 Reg = MF.getRegInfo().createVirtualRegister(
3028 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3029 MipsFI->setSRetReturnReg(Reg);
3031 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3032 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3038 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3040 // All stores are grouped in one node to allow the matching between
3041 // the size of Ins and InVals. This only happens when on varg functions
3042 if (!OutChains.empty()) {
3043 OutChains.push_back(Chain);
3044 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3050 //===----------------------------------------------------------------------===//
3051 // Return Value Calling Convention Implementation
3052 //===----------------------------------------------------------------------===//
3055 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3056 MachineFunction &MF, bool IsVarArg,
3057 const SmallVectorImpl<ISD::OutputArg> &Outs,
3058 LLVMContext &Context) const {
3059 SmallVector<CCValAssign, 16> RVLocs;
3060 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3061 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3065 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3066 if (Subtarget.hasMips3() && Subtarget.abiUsesSoftFloat()) {
3067 if (Type == MVT::i32)
3074 MipsTargetLowering::LowerReturn(SDValue Chain,
3075 CallingConv::ID CallConv, bool IsVarArg,
3076 const SmallVectorImpl<ISD::OutputArg> &Outs,
3077 const SmallVectorImpl<SDValue> &OutVals,
3078 SDLoc DL, SelectionDAG &DAG) const {
3079 // CCValAssign - represent the assignment of
3080 // the return value to a location
3081 SmallVector<CCValAssign, 16> RVLocs;
3082 MachineFunction &MF = DAG.getMachineFunction();
3084 // CCState - Info about the registers and stack slot.
3085 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3087 // Analyze return values.
3088 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3091 SmallVector<SDValue, 4> RetOps(1, Chain);
3093 // Copy the result values into the output registers.
3094 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3095 SDValue Val = OutVals[i];
3096 CCValAssign &VA = RVLocs[i];
3097 assert(VA.isRegLoc() && "Can only return in registers!");
3098 bool UseUpperBits = false;
3100 switch (VA.getLocInfo()) {
3102 llvm_unreachable("Unknown loc info!");
3103 case CCValAssign::Full:
3105 case CCValAssign::BCvt:
3106 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3108 case CCValAssign::AExtUpper:
3109 UseUpperBits = true;
3111 case CCValAssign::AExt:
3112 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3114 case CCValAssign::ZExtUpper:
3115 UseUpperBits = true;
3117 case CCValAssign::ZExt:
3118 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3120 case CCValAssign::SExtUpper:
3121 UseUpperBits = true;
3123 case CCValAssign::SExt:
3124 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3129 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3130 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3132 ISD::SHL, DL, VA.getLocVT(), Val,
3133 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3136 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3138 // Guarantee that all emitted copies are stuck together with flags.
3139 Flag = Chain.getValue(1);
3140 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3143 // The mips ABIs for returning structs by value requires that we copy
3144 // the sret argument into $v0 for the return. We saved the argument into
3145 // a virtual register in the entry block, so now we copy the value out
3147 if (MF.getFunction()->hasStructRetAttr()) {
3148 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3149 unsigned Reg = MipsFI->getSRetReturnReg();
3152 llvm_unreachable("sret virtual register not created in the entry block");
3153 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3154 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3156 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3157 Flag = Chain.getValue(1);
3158 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3161 RetOps[0] = Chain; // Update chain.
3163 // Add the flag if we have it.
3165 RetOps.push_back(Flag);
3167 // Return on Mips is always a "jr $ra"
3168 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3171 //===----------------------------------------------------------------------===//
3172 // Mips Inline Assembly Support
3173 //===----------------------------------------------------------------------===//
3175 /// getConstraintType - Given a constraint letter, return the type of
3176 /// constraint it is for this target.
3177 MipsTargetLowering::ConstraintType MipsTargetLowering::
3178 getConstraintType(const std::string &Constraint) const
3180 // Mips specific constraints
3181 // GCC config/mips/constraints.md
3183 // 'd' : An address register. Equivalent to r
3184 // unless generating MIPS16 code.
3185 // 'y' : Equivalent to r; retained for
3186 // backwards compatibility.
3187 // 'c' : A register suitable for use in an indirect
3188 // jump. This will always be $25 for -mabicalls.
3189 // 'l' : The lo register. 1 word storage.
3190 // 'x' : The hilo register pair. Double word storage.
3191 if (Constraint.size() == 1) {
3192 switch (Constraint[0]) {
3200 return C_RegisterClass;
3206 if (Constraint == "ZC")
3209 return TargetLowering::getConstraintType(Constraint);
3212 /// Examine constraint type and operand type and determine a weight value.
3213 /// This object must already have been set up with the operand type
3214 /// and the current alternative constraint selected.
3215 TargetLowering::ConstraintWeight
3216 MipsTargetLowering::getSingleConstraintMatchWeight(
3217 AsmOperandInfo &info, const char *constraint) const {
3218 ConstraintWeight weight = CW_Invalid;
3219 Value *CallOperandVal = info.CallOperandVal;
3220 // If we don't have a value, we can't do a match,
3221 // but allow it at the lowest weight.
3222 if (!CallOperandVal)
3224 Type *type = CallOperandVal->getType();
3225 // Look at the constraint type.
3226 switch (*constraint) {
3228 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3232 if (type->isIntegerTy())
3233 weight = CW_Register;
3235 case 'f': // FPU or MSA register
3236 if (Subtarget.hasMSA() && type->isVectorTy() &&
3237 cast<VectorType>(type)->getBitWidth() == 128)
3238 weight = CW_Register;
3239 else if (type->isFloatTy())
3240 weight = CW_Register;
3242 case 'c': // $25 for indirect jumps
3243 case 'l': // lo register
3244 case 'x': // hilo register pair
3245 if (type->isIntegerTy())
3246 weight = CW_SpecificReg;
3248 case 'I': // signed 16 bit immediate
3249 case 'J': // integer zero
3250 case 'K': // unsigned 16 bit immediate
3251 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3252 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3253 case 'O': // signed 15 bit immediate (+- 16383)
3254 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3255 if (isa<ConstantInt>(CallOperandVal))
3256 weight = CW_Constant;
3265 /// This is a helper function to parse a physical register string and split it
3266 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3267 /// that is returned indicates whether parsing was successful. The second flag
3268 /// is true if the numeric part exists.
3269 static std::pair<bool, bool>
3270 parsePhysicalReg(StringRef C, std::string &Prefix,
3271 unsigned long long &Reg) {
3272 if (C.front() != '{' || C.back() != '}')
3273 return std::make_pair(false, false);
3275 // Search for the first numeric character.
3276 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3277 I = std::find_if(B, E, std::ptr_fun(isdigit));
3279 Prefix.assign(B, I - B);
3281 // The second flag is set to false if no numeric characters were found.
3283 return std::make_pair(true, false);
3285 // Parse the numeric characters.
3286 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3290 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3291 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3292 const TargetRegisterInfo *TRI =
3293 Subtarget.getRegisterInfo();
3294 const TargetRegisterClass *RC;
3296 unsigned long long Reg;
3298 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3301 return std::make_pair(0U, nullptr);
3303 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3304 // No numeric characters follow "hi" or "lo".
3306 return std::make_pair(0U, nullptr);
3308 RC = TRI->getRegClass(Prefix == "hi" ?
3309 Mips::HI32RegClassID : Mips::LO32RegClassID);
3310 return std::make_pair(*(RC->begin()), RC);
3311 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3312 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3314 // No numeric characters follow the name.
3316 return std::make_pair(0U, nullptr);
3318 Reg = StringSwitch<unsigned long long>(Prefix)
3319 .Case("$msair", Mips::MSAIR)
3320 .Case("$msacsr", Mips::MSACSR)
3321 .Case("$msaaccess", Mips::MSAAccess)
3322 .Case("$msasave", Mips::MSASave)
3323 .Case("$msamodify", Mips::MSAModify)
3324 .Case("$msarequest", Mips::MSARequest)
3325 .Case("$msamap", Mips::MSAMap)
3326 .Case("$msaunmap", Mips::MSAUnmap)
3330 return std::make_pair(0U, nullptr);
3332 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3333 return std::make_pair(Reg, RC);
3337 return std::make_pair(0U, nullptr);
3339 if (Prefix == "$f") { // Parse $f0-$f31.
3340 // If the size of FP registers is 64-bit or Reg is an even number, select
3341 // the 64-bit register class. Otherwise, select the 32-bit register class.
3342 if (VT == MVT::Other)
3343 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3345 RC = getRegClassFor(VT);
3347 if (RC == &Mips::AFGR64RegClass) {
3348 assert(Reg % 2 == 0);
3351 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3352 RC = TRI->getRegClass(Mips::FCCRegClassID);
3353 else if (Prefix == "$w") { // Parse $w0-$w31.
3354 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3355 } else { // Parse $0-$31.
3356 assert(Prefix == "$");
3357 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3360 assert(Reg < RC->getNumRegs());
3361 return std::make_pair(*(RC->begin() + Reg), RC);
3364 /// Given a register class constraint, like 'r', if this corresponds directly
3365 /// to an LLVM register class, return a register of 0 and the register class
3367 std::pair<unsigned, const TargetRegisterClass *>
3368 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3369 const std::string &Constraint,
3371 if (Constraint.size() == 1) {
3372 switch (Constraint[0]) {
3373 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3374 case 'y': // Same as 'r'. Exists for compatibility.
3376 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3377 if (Subtarget.inMips16Mode())
3378 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3379 return std::make_pair(0U, &Mips::GPR32RegClass);
3381 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3382 return std::make_pair(0U, &Mips::GPR32RegClass);
3383 if (VT == MVT::i64 && Subtarget.isGP64bit())
3384 return std::make_pair(0U, &Mips::GPR64RegClass);
3385 // This will generate an error message
3386 return std::make_pair(0U, nullptr);
3387 case 'f': // FPU or MSA register
3388 if (VT == MVT::v16i8)
3389 return std::make_pair(0U, &Mips::MSA128BRegClass);
3390 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3391 return std::make_pair(0U, &Mips::MSA128HRegClass);
3392 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3393 return std::make_pair(0U, &Mips::MSA128WRegClass);
3394 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3395 return std::make_pair(0U, &Mips::MSA128DRegClass);
3396 else if (VT == MVT::f32)
3397 return std::make_pair(0U, &Mips::FGR32RegClass);
3398 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3399 if (Subtarget.isFP64bit())
3400 return std::make_pair(0U, &Mips::FGR64RegClass);
3401 return std::make_pair(0U, &Mips::AFGR64RegClass);
3404 case 'c': // register suitable for indirect jump
3406 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3407 assert(VT == MVT::i64 && "Unexpected type.");
3408 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3409 case 'l': // register suitable for indirect jump
3411 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3412 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3413 case 'x': // register suitable for indirect jump
3414 // Fixme: Not triggering the use of both hi and low
3415 // This will generate an error message
3416 return std::make_pair(0U, nullptr);
3420 std::pair<unsigned, const TargetRegisterClass *> R;
3421 R = parseRegForInlineAsmConstraint(Constraint, VT);
3426 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3429 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3430 /// vector. If it is invalid, don't add anything to Ops.
3431 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3432 std::string &Constraint,
3433 std::vector<SDValue>&Ops,
3434 SelectionDAG &DAG) const {
3438 // Only support length 1 constraints for now.
3439 if (Constraint.length() > 1) return;
3441 char ConstraintLetter = Constraint[0];
3442 switch (ConstraintLetter) {
3443 default: break; // This will fall through to the generic implementation
3444 case 'I': // Signed 16 bit constant
3445 // If this fails, the parent routine will give an error
3446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3447 EVT Type = Op.getValueType();
3448 int64_t Val = C->getSExtValue();
3449 if (isInt<16>(Val)) {
3450 Result = DAG.getTargetConstant(Val, DL, Type);
3455 case 'J': // integer zero
3456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3457 EVT Type = Op.getValueType();
3458 int64_t Val = C->getZExtValue();
3460 Result = DAG.getTargetConstant(0, DL, Type);
3465 case 'K': // unsigned 16 bit immediate
3466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3467 EVT Type = Op.getValueType();
3468 uint64_t Val = (uint64_t)C->getZExtValue();
3469 if (isUInt<16>(Val)) {
3470 Result = DAG.getTargetConstant(Val, DL, Type);
3475 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3477 EVT Type = Op.getValueType();
3478 int64_t Val = C->getSExtValue();
3479 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3480 Result = DAG.getTargetConstant(Val, DL, Type);
3485 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3487 EVT Type = Op.getValueType();
3488 int64_t Val = C->getSExtValue();
3489 if ((Val >= -65535) && (Val <= -1)) {
3490 Result = DAG.getTargetConstant(Val, DL, Type);
3495 case 'O': // signed 15 bit immediate
3496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3497 EVT Type = Op.getValueType();
3498 int64_t Val = C->getSExtValue();
3499 if ((isInt<15>(Val))) {
3500 Result = DAG.getTargetConstant(Val, DL, Type);
3505 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3507 EVT Type = Op.getValueType();
3508 int64_t Val = C->getSExtValue();
3509 if ((Val <= 65535) && (Val >= 1)) {
3510 Result = DAG.getTargetConstant(Val, DL, Type);
3517 if (Result.getNode()) {
3518 Ops.push_back(Result);
3522 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3525 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3527 // No global is ever allowed as a base.
3532 case 0: // "r+i" or just "i", depending on HasBaseReg.
3535 if (!AM.HasBaseReg) // allow "r+i".
3537 return false; // disallow "r+r" or "r+r+i".
3546 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3547 // The Mips target isn't yet aware of offsets.
3551 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3553 bool IsMemset, bool ZeroMemset,
3555 MachineFunction &MF) const {
3556 if (Subtarget.hasMips64())
3562 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3563 if (VT != MVT::f32 && VT != MVT::f64)
3565 if (Imm.isNegZero())
3567 return Imm.isZero();
3570 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3572 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3574 return TargetLowering::getJumpTableEncoding();
3577 void MipsTargetLowering::copyByValRegs(
3578 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3579 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3580 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3581 const CCValAssign &VA, MipsCCState &State) const {
3582 MachineFunction &MF = DAG.getMachineFunction();
3583 MachineFrameInfo *MFI = MF.getFrameInfo();
3584 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3585 unsigned NumRegs = LastReg - FirstReg;
3586 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3587 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3589 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3593 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3594 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3596 FrameObjOffset = VA.getLocMemOffset();
3598 // Create frame object.
3599 EVT PtrTy = getPointerTy();
3600 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3601 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3602 InVals.push_back(FIN);
3607 // Copy arg registers.
3608 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3609 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3611 for (unsigned I = 0; I < NumRegs; ++I) {
3612 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3613 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3614 unsigned Offset = I * GPRSizeInBytes;
3615 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3616 DAG.getConstant(Offset, DL, PtrTy));
3617 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3618 StorePtr, MachinePointerInfo(FuncArg, Offset),
3620 OutChains.push_back(Store);
3624 // Copy byVal arg to registers and stack.
3625 void MipsTargetLowering::passByValArg(
3626 SDValue Chain, SDLoc DL,
3627 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3628 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3629 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3630 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3631 const CCValAssign &VA) const {
3632 unsigned ByValSizeInBytes = Flags.getByValSize();
3633 unsigned OffsetInBytes = 0; // From beginning of struct
3634 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3635 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3636 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3637 unsigned NumRegs = LastReg - FirstReg;
3640 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3641 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3644 // Copy words to registers.
3645 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3646 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3647 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3648 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3649 MachinePointerInfo(), false, false, false,
3651 MemOpChains.push_back(LoadVal.getValue(1));
3652 unsigned ArgReg = ArgRegs[FirstReg + I];
3653 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3656 // Return if the struct has been fully copied.
3657 if (ByValSizeInBytes == OffsetInBytes)
3660 // Copy the remainder of the byval argument with sub-word loads and shifts.
3661 if (LeftoverBytes) {
3664 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3665 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3666 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3668 if (RemainingSizeInBytes < LoadSizeInBytes)
3672 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3673 DAG.getConstant(OffsetInBytes, DL,
3675 SDValue LoadVal = DAG.getExtLoad(
3676 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3677 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3679 MemOpChains.push_back(LoadVal.getValue(1));
3681 // Shift the loaded value.
3685 Shamt = TotalBytesLoaded * 8;
3687 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3689 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3690 DAG.getConstant(Shamt, DL, MVT::i32));
3693 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3697 OffsetInBytes += LoadSizeInBytes;
3698 TotalBytesLoaded += LoadSizeInBytes;
3699 Alignment = std::min(Alignment, LoadSizeInBytes);
3702 unsigned ArgReg = ArgRegs[FirstReg + I];
3703 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3708 // Copy remainder of byval arg to it with memcpy.
3709 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3710 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3711 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3712 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3713 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3714 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3715 DAG.getConstant(MemCpySize, DL, PtrTy),
3716 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3717 /*isTailCall=*/false,
3718 MachinePointerInfo(), MachinePointerInfo());
3719 MemOpChains.push_back(Chain);
3722 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3723 SDValue Chain, SDLoc DL,
3725 CCState &State) const {
3726 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3727 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3728 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3729 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3730 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3731 MachineFunction &MF = DAG.getMachineFunction();
3732 MachineFrameInfo *MFI = MF.getFrameInfo();
3733 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3735 // Offset of the first variable argument from stack pointer.
3738 if (ArgRegs.size() == Idx)
3740 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3743 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3744 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3747 // Record the frame index of the first variable argument
3748 // which is a value necessary to VASTART.
3749 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3750 MipsFI->setVarArgsFrameIndex(FI);
3752 // Copy the integer registers that have not been used for argument passing
3753 // to the argument register save area. For O32, the save area is allocated
3754 // in the caller's stack frame, while for N32/64, it is allocated in the
3755 // callee's stack frame.
3756 for (unsigned I = Idx; I < ArgRegs.size();
3757 ++I, VaArgOffset += RegSizeInBytes) {
3758 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3759 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3760 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3761 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3762 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3763 MachinePointerInfo(), false, false, 0);
3764 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3766 OutChains.push_back(Store);
3770 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3771 unsigned Align) const {
3772 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3774 assert(Size && "Byval argument's size shouldn't be 0.");
3776 Align = std::min(Align, TFL->getStackAlignment());
3778 unsigned FirstReg = 0;
3779 unsigned NumRegs = 0;
3781 if (State->getCallingConv() != CallingConv::Fast) {
3782 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3783 const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3784 // FIXME: The O32 case actually describes no shadow registers.
3785 const MCPhysReg *ShadowRegs =
3786 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3788 // We used to check the size as well but we can't do that anymore since
3789 // CCState::HandleByVal() rounds up the size after calling this function.
3790 assert(!(Align % RegSizeInBytes) &&
3791 "Byval argument's alignment should be a multiple of"
3794 FirstReg = State->getFirstUnallocated(IntArgRegs);
3796 // If Align > RegSizeInBytes, the first arg register must be even.
3797 // FIXME: This condition happens to do the right thing but it's not the
3798 // right way to test it. We want to check that the stack frame offset
3799 // of the register is aligned.
3800 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3801 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3805 // Mark the registers allocated.
3806 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3807 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3808 Size -= RegSizeInBytes, ++I, ++NumRegs)
3809 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3812 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3816 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3817 bool isFPCmp, unsigned Opc) const {
3818 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3819 "Subtarget already supports SELECT nodes with the use of"
3820 "conditional-move instructions.");
3822 const TargetInstrInfo *TII =
3823 Subtarget.getInstrInfo();
3824 DebugLoc DL = MI->getDebugLoc();
3826 // To "insert" a SELECT instruction, we actually have to insert the
3827 // diamond control-flow pattern. The incoming instruction knows the
3828 // destination vreg to set, the condition code register to branch on, the
3829 // true/false values to select between, and a branch opcode to use.
3830 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3831 MachineFunction::iterator It = BB;
3838 // bNE r1, r0, copy1MBB
3839 // fallthrough --> copy0MBB
3840 MachineBasicBlock *thisMBB = BB;
3841 MachineFunction *F = BB->getParent();
3842 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3843 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3844 F->insert(It, copy0MBB);
3845 F->insert(It, sinkMBB);
3847 // Transfer the remainder of BB and its successor edges to sinkMBB.
3848 sinkMBB->splice(sinkMBB->begin(), BB,
3849 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3850 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3852 // Next, add the true and fallthrough blocks as its successors.
3853 BB->addSuccessor(copy0MBB);
3854 BB->addSuccessor(sinkMBB);
3857 // bc1[tf] cc, sinkMBB
3858 BuildMI(BB, DL, TII->get(Opc))
3859 .addReg(MI->getOperand(1).getReg())
3862 // bne rs, $0, sinkMBB
3863 BuildMI(BB, DL, TII->get(Opc))
3864 .addReg(MI->getOperand(1).getReg())
3870 // %FalseValue = ...
3871 // # fallthrough to sinkMBB
3874 // Update machine-CFG edges
3875 BB->addSuccessor(sinkMBB);
3878 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3882 BuildMI(*BB, BB->begin(), DL,
3883 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3884 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3885 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3887 MI->eraseFromParent(); // The pseudo instruction is gone now.
3892 // FIXME? Maybe this could be a TableGen attribute on some registers and
3893 // this table could be generated automatically from RegInfo.
3894 unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3896 // Named registers is expected to be fairly rare. For now, just support $28
3897 // since the linux kernel uses it.
3898 if (Subtarget.isGP64bit()) {
3899 unsigned Reg = StringSwitch<unsigned>(RegName)
3900 .Case("$28", Mips::GP_64)
3905 unsigned Reg = StringSwitch<unsigned>(RegName)
3906 .Case("$28", Mips::GP)
3911 report_fatal_error("Invalid register name global variable");