Deleted Added
full compact
MipsISelLowering.cpp (280031) MipsISelLowering.cpp (283526)
1//===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that Mips uses to lower LLVM code into a
11// selection DAG.
12//
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"
39#include <cctype>
40
41using namespace llvm;
42
43#define DEBUG_TYPE "mips-lower"
44
45STATISTIC(NumTailCalls, "Number of tail calls");
46
47static cl::opt<bool>
48LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
50
51static cl::opt<bool>
52NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
54 cl::init(false));
55
56cl::opt<bool>
57EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
59 cl::init(false));
60
61static 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
64};
65
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).
69static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
71 return false;
72
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
75 return true;
76}
77
78SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
81}
82
83SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
84 SelectionDAG &DAG,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
87}
88
89SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
90 SelectionDAG &DAG,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
93}
94
95SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
96 SelectionDAG &DAG,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
99}
100
101SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
102 SelectionDAG &DAG,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
105}
106
107SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
108 SelectionDAG &DAG,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
112}
113
114const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
115 switch (Opcode) {
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;
201 }
202}
203
204MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
205 const MipsSubtarget &STI)
206 : TargetLowering(TM), Subtarget(STI) {
207 // Mips does not have i1 type, so use i32 for
208 // setcc operations results (slt, sgt, ...).
209 setBooleanContents(ZeroOrOneBooleanContent);
210 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
211 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
212 // does. Integer booleans still use 0 and 1.
213 if (Subtarget.hasMips32r6())
214 setBooleanContents(ZeroOrOneBooleanContent,
215 ZeroOrNegativeOneBooleanContent);
216
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);
222 }
223
224 // MIPS doesn't have extending float->double load/store
225 for (MVT VT : MVT::fp_valuetypes())
226 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
228
229 // Used by legalize types to correctly generate the setcc result.
230 // Without this, every float setcc comes with a AND/OR with the result,
231 // we don't want this, since the fpcmp result goes to a flag register,
232 // which is used implicitly by brcond and select operations.
233 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
234
235 // Mips Custom Operations
236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
237 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
238 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
239 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
240 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
241 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT, MVT::f64, Custom);
244 setOperationAction(ISD::SELECT, MVT::i32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
246 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
247 setOperationAction(ISD::SETCC, MVT::f32, Custom);
248 setOperationAction(ISD::SETCC, MVT::f64, Custom);
249 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
253
254 if (Subtarget.isGP64bit()) {
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
264 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
267 }
268
269 if (!Subtarget.isGP64bit()) {
270 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 }
274
275 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 if (Subtarget.isGP64bit())
277 setOperationAction(ISD::ADD, MVT::i64, Custom);
278
279 setOperationAction(ISD::SDIV, MVT::i32, Expand);
280 setOperationAction(ISD::SREM, MVT::i32, Expand);
281 setOperationAction(ISD::UDIV, MVT::i32, Expand);
282 setOperationAction(ISD::UREM, MVT::i32, Expand);
283 setOperationAction(ISD::SDIV, MVT::i64, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIV, MVT::i64, Expand);
286 setOperationAction(ISD::UREM, MVT::i64, Expand);
287
288 // Operations not directly supported by Mips.
289 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
293 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
295 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
297 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
300 if (Subtarget.hasCnMips()) {
301 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
302 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
303 } else {
304 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
305 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
306 }
307 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
308 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
309 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
310 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
311 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
312 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
313 setOperationAction(ISD::ROTL, MVT::i32, Expand);
314 setOperationAction(ISD::ROTL, MVT::i64, Expand);
315 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
317
318 if (!Subtarget.hasMips32r2())
319 setOperationAction(ISD::ROTR, MVT::i32, Expand);
320
321 if (!Subtarget.hasMips64r2())
322 setOperationAction(ISD::ROTR, MVT::i64, Expand);
323
324 setOperationAction(ISD::FSIN, MVT::f32, Expand);
325 setOperationAction(ISD::FSIN, MVT::f64, Expand);
326 setOperationAction(ISD::FCOS, MVT::f32, Expand);
327 setOperationAction(ISD::FCOS, MVT::f64, Expand);
328 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
330 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
331 setOperationAction(ISD::FPOW, MVT::f32, Expand);
332 setOperationAction(ISD::FPOW, MVT::f64, Expand);
333 setOperationAction(ISD::FLOG, MVT::f32, Expand);
334 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
335 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
336 setOperationAction(ISD::FEXP, MVT::f32, Expand);
337 setOperationAction(ISD::FMA, MVT::f32, Expand);
338 setOperationAction(ISD::FMA, MVT::f64, Expand);
339 setOperationAction(ISD::FREM, MVT::f32, Expand);
340 setOperationAction(ISD::FREM, MVT::f64, Expand);
341
342 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
343
344 setOperationAction(ISD::VASTART, MVT::Other, Custom);
345 setOperationAction(ISD::VAARG, MVT::Other, Custom);
346 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
347 setOperationAction(ISD::VAEND, MVT::Other, Expand);
348
349 // Use the default for now
350 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
351 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
352
353 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
355 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
357
358 setInsertFencesForAtomic(true);
359
360 if (!Subtarget.hasMips32r2()) {
361 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
363 }
364
365 // MIPS16 lacks MIPS32's clz and clo instructions.
366 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
367 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
368 if (!Subtarget.hasMips64())
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
370
371 if (!Subtarget.hasMips32r2())
372 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
373 if (!Subtarget.hasMips64r2())
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
375
376 if (Subtarget.isGP64bit()) {
377 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
378 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
379 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
380 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
381 }
382
383 setOperationAction(ISD::TRAP, MVT::Other, Legal);
384
385 setTargetDAGCombine(ISD::SDIVREM);
386 setTargetDAGCombine(ISD::UDIVREM);
387 setTargetDAGCombine(ISD::SELECT);
388 setTargetDAGCombine(ISD::AND);
389 setTargetDAGCombine(ISD::OR);
390 setTargetDAGCombine(ISD::ADD);
391
392 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
393
394 // The arguments on the stack are defined in terms of 4-byte slots on O32
395 // and 8-byte slots on N32/N64.
396 setMinStackArgumentAlignment(
397 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
398
399 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
400 : Mips::SP);
401
402 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
403 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
404
405 MaxStoresPerMemcpy = 16;
406
407 isMicroMips = Subtarget.inMicroMipsMode();
408}
409
410const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
411 const MipsSubtarget &STI) {
412 if (STI.inMips16Mode())
413 return llvm::createMips16TargetLowering(TM, STI);
414
415 return llvm::createMipsSETargetLowering(TM, STI);
416}
417
418// Create a fast isel object.
419FastISel *
420MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
421 const TargetLibraryInfo *libInfo) const {
422 if (!EnableMipsFastISel)
423 return TargetLowering::createFastISel(funcInfo, libInfo);
424 return Mips::createFastISel(funcInfo, libInfo);
425}
426
427EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
428 if (!VT.isVector())
429 return MVT::i32;
430 return VT.changeVectorElementTypeToInteger();
431}
432
433static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
434 TargetLowering::DAGCombinerInfo &DCI,
435 const MipsSubtarget &Subtarget) {
436 if (DCI.isBeforeLegalizeOps())
437 return SDValue();
438
439 EVT Ty = N->getValueType(0);
440 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
441 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
442 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
443 MipsISD::DivRemU16;
444 SDLoc DL(N);
445
446 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
447 N->getOperand(0), N->getOperand(1));
448 SDValue InChain = DAG.getEntryNode();
449 SDValue InGlue = DivRem;
450
451 // insert MFLO
452 if (N->hasAnyUseOfValue(0)) {
453 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
454 InGlue);
455 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
456 InChain = CopyFromLo.getValue(1);
457 InGlue = CopyFromLo.getValue(2);
458 }
459
460 // insert MFHI
461 if (N->hasAnyUseOfValue(1)) {
462 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
463 HI, Ty, InGlue);
464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
465 }
466
467 return SDValue();
468}
469
470static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
471 switch (CC) {
472 default: llvm_unreachable("Unknown fp condition code!");
473 case ISD::SETEQ:
474 case ISD::SETOEQ: return Mips::FCOND_OEQ;
475 case ISD::SETUNE: return Mips::FCOND_UNE;
476 case ISD::SETLT:
477 case ISD::SETOLT: return Mips::FCOND_OLT;
478 case ISD::SETGT:
479 case ISD::SETOGT: return Mips::FCOND_OGT;
480 case ISD::SETLE:
481 case ISD::SETOLE: return Mips::FCOND_OLE;
482 case ISD::SETGE:
483 case ISD::SETOGE: return Mips::FCOND_OGE;
484 case ISD::SETULT: return Mips::FCOND_ULT;
485 case ISD::SETULE: return Mips::FCOND_ULE;
486 case ISD::SETUGT: return Mips::FCOND_UGT;
487 case ISD::SETUGE: return Mips::FCOND_UGE;
488 case ISD::SETUO: return Mips::FCOND_UN;
489 case ISD::SETO: return Mips::FCOND_OR;
490 case ISD::SETNE:
491 case ISD::SETONE: return Mips::FCOND_ONE;
492 case ISD::SETUEQ: return Mips::FCOND_UEQ;
493 }
494}
495
496
497/// This function returns true if the floating point conditional branches and
498/// conditional moves which use condition code CC should be inverted.
499static bool invertFPCondCodeUser(Mips::CondCode CC) {
500 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
501 return false;
502
503 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
504 "Illegal Condition Code");
505
506 return true;
507}
508
509// Creates and returns an FPCmp node from a setcc node.
510// Returns Op if setcc is not a floating point comparison.
511static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
512 // must be a SETCC node
513 if (Op.getOpcode() != ISD::SETCC)
514 return Op;
515
516 SDValue LHS = Op.getOperand(0);
517
518 if (!LHS.getValueType().isFloatingPoint())
519 return Op;
520
521 SDValue RHS = Op.getOperand(1);
522 SDLoc DL(Op);
523
524 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
525 // node if necessary.
526 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
527
528 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
529 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
530}
531
532// Creates and returns a CMovFPT/F node.
533static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
534 SDValue False, SDLoc DL) {
535 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
536 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
537 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
538
539 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
540 True.getValueType(), True, FCC0, False, Cond);
541}
542
543static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
544 TargetLowering::DAGCombinerInfo &DCI,
545 const MipsSubtarget &Subtarget) {
546 if (DCI.isBeforeLegalizeOps())
547 return SDValue();
548
549 SDValue SetCC = N->getOperand(0);
550
551 if ((SetCC.getOpcode() != ISD::SETCC) ||
552 !SetCC.getOperand(0).getValueType().isInteger())
553 return SDValue();
554
555 SDValue False = N->getOperand(2);
556 EVT FalseTy = False.getValueType();
557
558 if (!FalseTy.isInteger())
559 return SDValue();
560
561 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
562
563 // If the RHS (False) is 0, we swap the order of the operands
564 // of ISD::SELECT (obviously also inverting the condition) so that we can
565 // take advantage of conditional moves using the $0 register.
566 // Example:
567 // return (a != 0) ? x : 0;
568 // load $reg, x
569 // movz $reg, $0, a
570 if (!FalseC)
571 return SDValue();
572
573 const SDLoc DL(N);
574
575 if (!FalseC->getZExtValue()) {
576 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
577 SDValue True = N->getOperand(1);
578
579 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
580 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
581
582 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
583 }
584
585 // If both operands are integer constants there's a possibility that we
586 // can do some interesting optimizations.
587 SDValue True = N->getOperand(1);
588 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
589
590 if (!TrueC || !True.getValueType().isInteger())
591 return SDValue();
592
593 // We'll also ignore MVT::i64 operands as this optimizations proves
594 // to be ineffective because of the required sign extensions as the result
595 // of a SETCC operator is always MVT::i32 for non-vector types.
596 if (True.getValueType() == MVT::i64)
597 return SDValue();
598
599 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
600
601 // 1) (a < x) ? y : y-1
602 // slti $reg1, a, x
603 // addiu $reg2, $reg1, y-1
604 if (Diff == 1)
605 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
606
607 // 2) (a < x) ? y-1 : y
608 // slti $reg1, a, x
609 // xor $reg1, $reg1, 1
610 // addiu $reg2, $reg1, y-1
611 if (Diff == -1) {
612 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
613 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
614 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
615 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
616 }
617
618 // Couldn't optimize.
619 return SDValue();
620}
621
1//===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that Mips uses to lower LLVM code into a
11// selection DAG.
12//
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"
39#include <cctype>
40
41using namespace llvm;
42
43#define DEBUG_TYPE "mips-lower"
44
45STATISTIC(NumTailCalls, "Number of tail calls");
46
47static cl::opt<bool>
48LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
50
51static cl::opt<bool>
52NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
54 cl::init(false));
55
56cl::opt<bool>
57EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
59 cl::init(false));
60
61static 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
64};
65
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).
69static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
71 return false;
72
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
75 return true;
76}
77
78SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
81}
82
83SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
84 SelectionDAG &DAG,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
87}
88
89SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
90 SelectionDAG &DAG,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
93}
94
95SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
96 SelectionDAG &DAG,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
99}
100
101SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
102 SelectionDAG &DAG,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
105}
106
107SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
108 SelectionDAG &DAG,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
112}
113
114const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
115 switch (Opcode) {
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;
201 }
202}
203
204MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
205 const MipsSubtarget &STI)
206 : TargetLowering(TM), Subtarget(STI) {
207 // Mips does not have i1 type, so use i32 for
208 // setcc operations results (slt, sgt, ...).
209 setBooleanContents(ZeroOrOneBooleanContent);
210 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
211 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
212 // does. Integer booleans still use 0 and 1.
213 if (Subtarget.hasMips32r6())
214 setBooleanContents(ZeroOrOneBooleanContent,
215 ZeroOrNegativeOneBooleanContent);
216
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);
222 }
223
224 // MIPS doesn't have extending float->double load/store
225 for (MVT VT : MVT::fp_valuetypes())
226 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
228
229 // Used by legalize types to correctly generate the setcc result.
230 // Without this, every float setcc comes with a AND/OR with the result,
231 // we don't want this, since the fpcmp result goes to a flag register,
232 // which is used implicitly by brcond and select operations.
233 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
234
235 // Mips Custom Operations
236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
237 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
238 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
239 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
240 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
241 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT, MVT::f64, Custom);
244 setOperationAction(ISD::SELECT, MVT::i32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
246 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
247 setOperationAction(ISD::SETCC, MVT::f32, Custom);
248 setOperationAction(ISD::SETCC, MVT::f64, Custom);
249 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
253
254 if (Subtarget.isGP64bit()) {
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
264 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
267 }
268
269 if (!Subtarget.isGP64bit()) {
270 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 }
274
275 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 if (Subtarget.isGP64bit())
277 setOperationAction(ISD::ADD, MVT::i64, Custom);
278
279 setOperationAction(ISD::SDIV, MVT::i32, Expand);
280 setOperationAction(ISD::SREM, MVT::i32, Expand);
281 setOperationAction(ISD::UDIV, MVT::i32, Expand);
282 setOperationAction(ISD::UREM, MVT::i32, Expand);
283 setOperationAction(ISD::SDIV, MVT::i64, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIV, MVT::i64, Expand);
286 setOperationAction(ISD::UREM, MVT::i64, Expand);
287
288 // Operations not directly supported by Mips.
289 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
293 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
295 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
297 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
300 if (Subtarget.hasCnMips()) {
301 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
302 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
303 } else {
304 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
305 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
306 }
307 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
308 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
309 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
310 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
311 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
312 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
313 setOperationAction(ISD::ROTL, MVT::i32, Expand);
314 setOperationAction(ISD::ROTL, MVT::i64, Expand);
315 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
317
318 if (!Subtarget.hasMips32r2())
319 setOperationAction(ISD::ROTR, MVT::i32, Expand);
320
321 if (!Subtarget.hasMips64r2())
322 setOperationAction(ISD::ROTR, MVT::i64, Expand);
323
324 setOperationAction(ISD::FSIN, MVT::f32, Expand);
325 setOperationAction(ISD::FSIN, MVT::f64, Expand);
326 setOperationAction(ISD::FCOS, MVT::f32, Expand);
327 setOperationAction(ISD::FCOS, MVT::f64, Expand);
328 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
330 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
331 setOperationAction(ISD::FPOW, MVT::f32, Expand);
332 setOperationAction(ISD::FPOW, MVT::f64, Expand);
333 setOperationAction(ISD::FLOG, MVT::f32, Expand);
334 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
335 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
336 setOperationAction(ISD::FEXP, MVT::f32, Expand);
337 setOperationAction(ISD::FMA, MVT::f32, Expand);
338 setOperationAction(ISD::FMA, MVT::f64, Expand);
339 setOperationAction(ISD::FREM, MVT::f32, Expand);
340 setOperationAction(ISD::FREM, MVT::f64, Expand);
341
342 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
343
344 setOperationAction(ISD::VASTART, MVT::Other, Custom);
345 setOperationAction(ISD::VAARG, MVT::Other, Custom);
346 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
347 setOperationAction(ISD::VAEND, MVT::Other, Expand);
348
349 // Use the default for now
350 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
351 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
352
353 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
355 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
357
358 setInsertFencesForAtomic(true);
359
360 if (!Subtarget.hasMips32r2()) {
361 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
363 }
364
365 // MIPS16 lacks MIPS32's clz and clo instructions.
366 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
367 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
368 if (!Subtarget.hasMips64())
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
370
371 if (!Subtarget.hasMips32r2())
372 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
373 if (!Subtarget.hasMips64r2())
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
375
376 if (Subtarget.isGP64bit()) {
377 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
378 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
379 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
380 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
381 }
382
383 setOperationAction(ISD::TRAP, MVT::Other, Legal);
384
385 setTargetDAGCombine(ISD::SDIVREM);
386 setTargetDAGCombine(ISD::UDIVREM);
387 setTargetDAGCombine(ISD::SELECT);
388 setTargetDAGCombine(ISD::AND);
389 setTargetDAGCombine(ISD::OR);
390 setTargetDAGCombine(ISD::ADD);
391
392 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
393
394 // The arguments on the stack are defined in terms of 4-byte slots on O32
395 // and 8-byte slots on N32/N64.
396 setMinStackArgumentAlignment(
397 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
398
399 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
400 : Mips::SP);
401
402 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
403 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
404
405 MaxStoresPerMemcpy = 16;
406
407 isMicroMips = Subtarget.inMicroMipsMode();
408}
409
410const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
411 const MipsSubtarget &STI) {
412 if (STI.inMips16Mode())
413 return llvm::createMips16TargetLowering(TM, STI);
414
415 return llvm::createMipsSETargetLowering(TM, STI);
416}
417
418// Create a fast isel object.
419FastISel *
420MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
421 const TargetLibraryInfo *libInfo) const {
422 if (!EnableMipsFastISel)
423 return TargetLowering::createFastISel(funcInfo, libInfo);
424 return Mips::createFastISel(funcInfo, libInfo);
425}
426
427EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
428 if (!VT.isVector())
429 return MVT::i32;
430 return VT.changeVectorElementTypeToInteger();
431}
432
433static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
434 TargetLowering::DAGCombinerInfo &DCI,
435 const MipsSubtarget &Subtarget) {
436 if (DCI.isBeforeLegalizeOps())
437 return SDValue();
438
439 EVT Ty = N->getValueType(0);
440 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
441 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
442 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
443 MipsISD::DivRemU16;
444 SDLoc DL(N);
445
446 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
447 N->getOperand(0), N->getOperand(1));
448 SDValue InChain = DAG.getEntryNode();
449 SDValue InGlue = DivRem;
450
451 // insert MFLO
452 if (N->hasAnyUseOfValue(0)) {
453 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
454 InGlue);
455 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
456 InChain = CopyFromLo.getValue(1);
457 InGlue = CopyFromLo.getValue(2);
458 }
459
460 // insert MFHI
461 if (N->hasAnyUseOfValue(1)) {
462 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
463 HI, Ty, InGlue);
464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
465 }
466
467 return SDValue();
468}
469
470static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
471 switch (CC) {
472 default: llvm_unreachable("Unknown fp condition code!");
473 case ISD::SETEQ:
474 case ISD::SETOEQ: return Mips::FCOND_OEQ;
475 case ISD::SETUNE: return Mips::FCOND_UNE;
476 case ISD::SETLT:
477 case ISD::SETOLT: return Mips::FCOND_OLT;
478 case ISD::SETGT:
479 case ISD::SETOGT: return Mips::FCOND_OGT;
480 case ISD::SETLE:
481 case ISD::SETOLE: return Mips::FCOND_OLE;
482 case ISD::SETGE:
483 case ISD::SETOGE: return Mips::FCOND_OGE;
484 case ISD::SETULT: return Mips::FCOND_ULT;
485 case ISD::SETULE: return Mips::FCOND_ULE;
486 case ISD::SETUGT: return Mips::FCOND_UGT;
487 case ISD::SETUGE: return Mips::FCOND_UGE;
488 case ISD::SETUO: return Mips::FCOND_UN;
489 case ISD::SETO: return Mips::FCOND_OR;
490 case ISD::SETNE:
491 case ISD::SETONE: return Mips::FCOND_ONE;
492 case ISD::SETUEQ: return Mips::FCOND_UEQ;
493 }
494}
495
496
497/// This function returns true if the floating point conditional branches and
498/// conditional moves which use condition code CC should be inverted.
499static bool invertFPCondCodeUser(Mips::CondCode CC) {
500 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
501 return false;
502
503 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
504 "Illegal Condition Code");
505
506 return true;
507}
508
509// Creates and returns an FPCmp node from a setcc node.
510// Returns Op if setcc is not a floating point comparison.
511static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
512 // must be a SETCC node
513 if (Op.getOpcode() != ISD::SETCC)
514 return Op;
515
516 SDValue LHS = Op.getOperand(0);
517
518 if (!LHS.getValueType().isFloatingPoint())
519 return Op;
520
521 SDValue RHS = Op.getOperand(1);
522 SDLoc DL(Op);
523
524 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
525 // node if necessary.
526 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
527
528 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
529 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
530}
531
532// Creates and returns a CMovFPT/F node.
533static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
534 SDValue False, SDLoc DL) {
535 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
536 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
537 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
538
539 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
540 True.getValueType(), True, FCC0, False, Cond);
541}
542
543static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
544 TargetLowering::DAGCombinerInfo &DCI,
545 const MipsSubtarget &Subtarget) {
546 if (DCI.isBeforeLegalizeOps())
547 return SDValue();
548
549 SDValue SetCC = N->getOperand(0);
550
551 if ((SetCC.getOpcode() != ISD::SETCC) ||
552 !SetCC.getOperand(0).getValueType().isInteger())
553 return SDValue();
554
555 SDValue False = N->getOperand(2);
556 EVT FalseTy = False.getValueType();
557
558 if (!FalseTy.isInteger())
559 return SDValue();
560
561 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
562
563 // If the RHS (False) is 0, we swap the order of the operands
564 // of ISD::SELECT (obviously also inverting the condition) so that we can
565 // take advantage of conditional moves using the $0 register.
566 // Example:
567 // return (a != 0) ? x : 0;
568 // load $reg, x
569 // movz $reg, $0, a
570 if (!FalseC)
571 return SDValue();
572
573 const SDLoc DL(N);
574
575 if (!FalseC->getZExtValue()) {
576 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
577 SDValue True = N->getOperand(1);
578
579 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
580 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
581
582 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
583 }
584
585 // If both operands are integer constants there's a possibility that we
586 // can do some interesting optimizations.
587 SDValue True = N->getOperand(1);
588 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
589
590 if (!TrueC || !True.getValueType().isInteger())
591 return SDValue();
592
593 // We'll also ignore MVT::i64 operands as this optimizations proves
594 // to be ineffective because of the required sign extensions as the result
595 // of a SETCC operator is always MVT::i32 for non-vector types.
596 if (True.getValueType() == MVT::i64)
597 return SDValue();
598
599 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
600
601 // 1) (a < x) ? y : y-1
602 // slti $reg1, a, x
603 // addiu $reg2, $reg1, y-1
604 if (Diff == 1)
605 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
606
607 // 2) (a < x) ? y-1 : y
608 // slti $reg1, a, x
609 // xor $reg1, $reg1, 1
610 // addiu $reg2, $reg1, y-1
611 if (Diff == -1) {
612 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
613 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
614 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
615 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
616 }
617
618 // Couldn't optimize.
619 return SDValue();
620}
621
622static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
623 TargetLowering::DAGCombinerInfo &DCI,
624 const MipsSubtarget &Subtarget) {
625 if (DCI.isBeforeLegalizeOps())
626 return SDValue();
627
628 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
629
630 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
631 if (!FalseC || FalseC->getZExtValue())
632 return SDValue();
633
634 // Since RHS (False) is 0, we swap the order of the True/False operands
635 // (obviously also inverting the condition) so that we can
636 // take advantage of conditional moves using the $0 register.
637 // Example:
638 // return (a != 0) ? x : 0;
639 // load $reg, x
640 // movz $reg, $0, a
641 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
642 MipsISD::CMovFP_T;
643
644 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
645 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
646 ValueIfFalse, FCC, ValueIfTrue, Glue);
647}
648
622static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
623 TargetLowering::DAGCombinerInfo &DCI,
624 const MipsSubtarget &Subtarget) {
625 // Pattern match EXT.
626 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
627 // => ext $dst, $src, size, pos
628 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
629 return SDValue();
630
631 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
632 unsigned ShiftRightOpc = ShiftRight.getOpcode();
633
634 // Op's first operand must be a shift right.
635 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
636 return SDValue();
637
638 // The second operand of the shift must be an immediate.
639 ConstantSDNode *CN;
640 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
641 return SDValue();
642
643 uint64_t Pos = CN->getZExtValue();
644 uint64_t SMPos, SMSize;
645
646 // Op's second operand must be a shifted mask.
647 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
648 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
649 return SDValue();
650
651 // Return if the shifted mask does not start at bit 0 or the sum of its size
652 // and Pos exceeds the word's size.
653 EVT ValTy = N->getValueType(0);
654 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
655 return SDValue();
656
657 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
658 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
659 DAG.getConstant(SMSize, MVT::i32));
660}
661
662static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
663 TargetLowering::DAGCombinerInfo &DCI,
664 const MipsSubtarget &Subtarget) {
665 // Pattern match INS.
666 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
667 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
668 // => ins $dst, $src, size, pos, $src1
669 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
670 return SDValue();
671
672 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
673 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
674 ConstantSDNode *CN;
675
676 // See if Op's first operand matches (and $src1 , mask0).
677 if (And0.getOpcode() != ISD::AND)
678 return SDValue();
679
680 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
681 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
682 return SDValue();
683
684 // See if Op's second operand matches (and (shl $src, pos), mask1).
685 if (And1.getOpcode() != ISD::AND)
686 return SDValue();
687
688 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
689 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
690 return SDValue();
691
692 // The shift masks must have the same position and size.
693 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
694 return SDValue();
695
696 SDValue Shl = And1.getOperand(0);
697 if (Shl.getOpcode() != ISD::SHL)
698 return SDValue();
699
700 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
701 return SDValue();
702
703 unsigned Shamt = CN->getZExtValue();
704
705 // Return if the shift amount and the first bit position of mask are not the
706 // same.
707 EVT ValTy = N->getValueType(0);
708 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
709 return SDValue();
710
711 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
712 DAG.getConstant(SMPos0, MVT::i32),
713 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
714}
715
716static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
717 TargetLowering::DAGCombinerInfo &DCI,
718 const MipsSubtarget &Subtarget) {
719 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
720
721 if (DCI.isBeforeLegalizeOps())
722 return SDValue();
723
724 SDValue Add = N->getOperand(1);
725
726 if (Add.getOpcode() != ISD::ADD)
727 return SDValue();
728
729 SDValue Lo = Add.getOperand(1);
730
731 if ((Lo.getOpcode() != MipsISD::Lo) ||
732 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
733 return SDValue();
734
735 EVT ValTy = N->getValueType(0);
736 SDLoc DL(N);
737
738 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
739 Add.getOperand(0));
740 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
741}
742
743SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
744 const {
745 SelectionDAG &DAG = DCI.DAG;
746 unsigned Opc = N->getOpcode();
747
748 switch (Opc) {
749 default: break;
750 case ISD::SDIVREM:
751 case ISD::UDIVREM:
752 return performDivRemCombine(N, DAG, DCI, Subtarget);
753 case ISD::SELECT:
754 return performSELECTCombine(N, DAG, DCI, Subtarget);
649static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
650 TargetLowering::DAGCombinerInfo &DCI,
651 const MipsSubtarget &Subtarget) {
652 // Pattern match EXT.
653 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
654 // => ext $dst, $src, size, pos
655 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
656 return SDValue();
657
658 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
659 unsigned ShiftRightOpc = ShiftRight.getOpcode();
660
661 // Op's first operand must be a shift right.
662 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
663 return SDValue();
664
665 // The second operand of the shift must be an immediate.
666 ConstantSDNode *CN;
667 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
668 return SDValue();
669
670 uint64_t Pos = CN->getZExtValue();
671 uint64_t SMPos, SMSize;
672
673 // Op's second operand must be a shifted mask.
674 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
675 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
676 return SDValue();
677
678 // Return if the shifted mask does not start at bit 0 or the sum of its size
679 // and Pos exceeds the word's size.
680 EVT ValTy = N->getValueType(0);
681 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
682 return SDValue();
683
684 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
685 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
686 DAG.getConstant(SMSize, MVT::i32));
687}
688
689static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
690 TargetLowering::DAGCombinerInfo &DCI,
691 const MipsSubtarget &Subtarget) {
692 // Pattern match INS.
693 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
694 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
695 // => ins $dst, $src, size, pos, $src1
696 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
697 return SDValue();
698
699 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
700 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
701 ConstantSDNode *CN;
702
703 // See if Op's first operand matches (and $src1 , mask0).
704 if (And0.getOpcode() != ISD::AND)
705 return SDValue();
706
707 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
708 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
709 return SDValue();
710
711 // See if Op's second operand matches (and (shl $src, pos), mask1).
712 if (And1.getOpcode() != ISD::AND)
713 return SDValue();
714
715 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
716 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
717 return SDValue();
718
719 // The shift masks must have the same position and size.
720 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
721 return SDValue();
722
723 SDValue Shl = And1.getOperand(0);
724 if (Shl.getOpcode() != ISD::SHL)
725 return SDValue();
726
727 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
728 return SDValue();
729
730 unsigned Shamt = CN->getZExtValue();
731
732 // Return if the shift amount and the first bit position of mask are not the
733 // same.
734 EVT ValTy = N->getValueType(0);
735 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
736 return SDValue();
737
738 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
739 DAG.getConstant(SMPos0, MVT::i32),
740 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
741}
742
743static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
744 TargetLowering::DAGCombinerInfo &DCI,
745 const MipsSubtarget &Subtarget) {
746 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
747
748 if (DCI.isBeforeLegalizeOps())
749 return SDValue();
750
751 SDValue Add = N->getOperand(1);
752
753 if (Add.getOpcode() != ISD::ADD)
754 return SDValue();
755
756 SDValue Lo = Add.getOperand(1);
757
758 if ((Lo.getOpcode() != MipsISD::Lo) ||
759 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
760 return SDValue();
761
762 EVT ValTy = N->getValueType(0);
763 SDLoc DL(N);
764
765 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
766 Add.getOperand(0));
767 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
768}
769
770SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
771 const {
772 SelectionDAG &DAG = DCI.DAG;
773 unsigned Opc = N->getOpcode();
774
775 switch (Opc) {
776 default: break;
777 case ISD::SDIVREM:
778 case ISD::UDIVREM:
779 return performDivRemCombine(N, DAG, DCI, Subtarget);
780 case ISD::SELECT:
781 return performSELECTCombine(N, DAG, DCI, Subtarget);
782 case MipsISD::CMovFP_F:
783 case MipsISD::CMovFP_T:
784 return performCMovFPCombine(N, DAG, DCI, Subtarget);
755 case ISD::AND:
756 return performANDCombine(N, DAG, DCI, Subtarget);
757 case ISD::OR:
758 return performORCombine(N, DAG, DCI, Subtarget);
759 case ISD::ADD:
760 return performADDCombine(N, DAG, DCI, Subtarget);
761 }
762
763 return SDValue();
764}
765
766void
767MipsTargetLowering::LowerOperationWrapper(SDNode *N,
768 SmallVectorImpl<SDValue> &Results,
769 SelectionDAG &DAG) const {
770 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
771
772 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
773 Results.push_back(Res.getValue(I));
774}
775
776void
777MipsTargetLowering::ReplaceNodeResults(SDNode *N,
778 SmallVectorImpl<SDValue> &Results,
779 SelectionDAG &DAG) const {
780 return LowerOperationWrapper(N, Results, DAG);
781}
782
783SDValue MipsTargetLowering::
784LowerOperation(SDValue Op, SelectionDAG &DAG) const
785{
786 switch (Op.getOpcode())
787 {
788 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
789 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
790 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
791 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
792 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
793 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
794 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
795 case ISD::SELECT: return lowerSELECT(Op, DAG);
796 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
797 case ISD::SETCC: return lowerSETCC(Op, DAG);
798 case ISD::VASTART: return lowerVASTART(Op, DAG);
799 case ISD::VAARG: return lowerVAARG(Op, DAG);
800 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
801 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
802 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
803 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
804 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
805 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
806 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
807 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
808 case ISD::LOAD: return lowerLOAD(Op, DAG);
809 case ISD::STORE: return lowerSTORE(Op, DAG);
810 case ISD::ADD: return lowerADD(Op, DAG);
811 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
812 }
813 return SDValue();
814}
815
816//===----------------------------------------------------------------------===//
817// Lower helper functions
818//===----------------------------------------------------------------------===//
819
820// addLiveIn - This helper function adds the specified physical register to the
821// MachineFunction as a live in value. It also creates a corresponding
822// virtual register for it.
823static unsigned
824addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
825{
826 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
827 MF.getRegInfo().addLiveIn(PReg, VReg);
828 return VReg;
829}
830
831static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
832 MachineBasicBlock &MBB,
833 const TargetInstrInfo &TII,
834 bool Is64Bit) {
835 if (NoZeroDivCheck)
836 return &MBB;
837
838 // Insert instruction "teq $divisor_reg, $zero, 7".
839 MachineBasicBlock::iterator I(MI);
840 MachineInstrBuilder MIB;
841 MachineOperand &Divisor = MI->getOperand(2);
842 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
843 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
844 .addReg(Mips::ZERO).addImm(7);
845
846 // Use the 32-bit sub-register if this is a 64-bit division.
847 if (Is64Bit)
848 MIB->getOperand(0).setSubReg(Mips::sub_32);
849
850 // Clear Divisor's kill flag.
851 Divisor.setIsKill(false);
852
853 // We would normally delete the original instruction here but in this case
854 // we only needed to inject an additional instruction rather than replace it.
855
856 return &MBB;
857}
858
859MachineBasicBlock *
860MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
861 MachineBasicBlock *BB) const {
862 switch (MI->getOpcode()) {
863 default:
864 llvm_unreachable("Unexpected instr type to insert");
865 case Mips::ATOMIC_LOAD_ADD_I8:
866 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
867 case Mips::ATOMIC_LOAD_ADD_I16:
868 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
869 case Mips::ATOMIC_LOAD_ADD_I32:
870 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
871 case Mips::ATOMIC_LOAD_ADD_I64:
872 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
873
874 case Mips::ATOMIC_LOAD_AND_I8:
875 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
876 case Mips::ATOMIC_LOAD_AND_I16:
877 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
878 case Mips::ATOMIC_LOAD_AND_I32:
879 return emitAtomicBinary(MI, BB, 4, Mips::AND);
880 case Mips::ATOMIC_LOAD_AND_I64:
881 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
882
883 case Mips::ATOMIC_LOAD_OR_I8:
884 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
885 case Mips::ATOMIC_LOAD_OR_I16:
886 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
887 case Mips::ATOMIC_LOAD_OR_I32:
888 return emitAtomicBinary(MI, BB, 4, Mips::OR);
889 case Mips::ATOMIC_LOAD_OR_I64:
890 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
891
892 case Mips::ATOMIC_LOAD_XOR_I8:
893 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
894 case Mips::ATOMIC_LOAD_XOR_I16:
895 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
896 case Mips::ATOMIC_LOAD_XOR_I32:
897 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
898 case Mips::ATOMIC_LOAD_XOR_I64:
899 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
900
901 case Mips::ATOMIC_LOAD_NAND_I8:
902 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
903 case Mips::ATOMIC_LOAD_NAND_I16:
904 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
905 case Mips::ATOMIC_LOAD_NAND_I32:
906 return emitAtomicBinary(MI, BB, 4, 0, true);
907 case Mips::ATOMIC_LOAD_NAND_I64:
908 return emitAtomicBinary(MI, BB, 8, 0, true);
909
910 case Mips::ATOMIC_LOAD_SUB_I8:
911 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
912 case Mips::ATOMIC_LOAD_SUB_I16:
913 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
914 case Mips::ATOMIC_LOAD_SUB_I32:
915 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
916 case Mips::ATOMIC_LOAD_SUB_I64:
917 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
918
919 case Mips::ATOMIC_SWAP_I8:
920 return emitAtomicBinaryPartword(MI, BB, 1, 0);
921 case Mips::ATOMIC_SWAP_I16:
922 return emitAtomicBinaryPartword(MI, BB, 2, 0);
923 case Mips::ATOMIC_SWAP_I32:
924 return emitAtomicBinary(MI, BB, 4, 0);
925 case Mips::ATOMIC_SWAP_I64:
926 return emitAtomicBinary(MI, BB, 8, 0);
927
928 case Mips::ATOMIC_CMP_SWAP_I8:
929 return emitAtomicCmpSwapPartword(MI, BB, 1);
930 case Mips::ATOMIC_CMP_SWAP_I16:
931 return emitAtomicCmpSwapPartword(MI, BB, 2);
932 case Mips::ATOMIC_CMP_SWAP_I32:
933 return emitAtomicCmpSwap(MI, BB, 4);
934 case Mips::ATOMIC_CMP_SWAP_I64:
935 return emitAtomicCmpSwap(MI, BB, 8);
936 case Mips::PseudoSDIV:
937 case Mips::PseudoUDIV:
938 case Mips::DIV:
939 case Mips::DIVU:
940 case Mips::MOD:
941 case Mips::MODU:
942 return insertDivByZeroTrap(
943 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
944 case Mips::PseudoDSDIV:
945 case Mips::PseudoDUDIV:
946 case Mips::DDIV:
947 case Mips::DDIVU:
948 case Mips::DMOD:
949 case Mips::DMODU:
950 return insertDivByZeroTrap(
951 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
952 case Mips::SEL_D:
953 return emitSEL_D(MI, BB);
954
955 case Mips::PseudoSELECT_I:
956 case Mips::PseudoSELECT_I64:
957 case Mips::PseudoSELECT_S:
958 case Mips::PseudoSELECT_D32:
959 case Mips::PseudoSELECT_D64:
960 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
961 case Mips::PseudoSELECTFP_F_I:
962 case Mips::PseudoSELECTFP_F_I64:
963 case Mips::PseudoSELECTFP_F_S:
964 case Mips::PseudoSELECTFP_F_D32:
965 case Mips::PseudoSELECTFP_F_D64:
966 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
967 case Mips::PseudoSELECTFP_T_I:
968 case Mips::PseudoSELECTFP_T_I64:
969 case Mips::PseudoSELECTFP_T_S:
970 case Mips::PseudoSELECTFP_T_D32:
971 case Mips::PseudoSELECTFP_T_D64:
972 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
973 }
974}
975
976// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
977// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
978MachineBasicBlock *
979MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
980 unsigned Size, unsigned BinOpcode,
981 bool Nand) const {
982 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
983
984 MachineFunction *MF = BB->getParent();
985 MachineRegisterInfo &RegInfo = MF->getRegInfo();
986 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
987 const TargetInstrInfo *TII =
988 getTargetMachine().getSubtargetImpl()->getInstrInfo();
989 DebugLoc DL = MI->getDebugLoc();
990 unsigned LL, SC, AND, NOR, ZERO, BEQ;
991
992 if (Size == 4) {
993 if (isMicroMips) {
994 LL = Mips::LL_MM;
995 SC = Mips::SC_MM;
996 } else {
997 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
998 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
999 }
1000 AND = Mips::AND;
1001 NOR = Mips::NOR;
1002 ZERO = Mips::ZERO;
1003 BEQ = Mips::BEQ;
1004 } else {
1005 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1006 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1007 AND = Mips::AND64;
1008 NOR = Mips::NOR64;
1009 ZERO = Mips::ZERO_64;
1010 BEQ = Mips::BEQ64;
1011 }
1012
1013 unsigned OldVal = MI->getOperand(0).getReg();
1014 unsigned Ptr = MI->getOperand(1).getReg();
1015 unsigned Incr = MI->getOperand(2).getReg();
1016
1017 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1018 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1019 unsigned Success = RegInfo.createVirtualRegister(RC);
1020
1021 // insert new blocks after the current block
1022 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1023 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1024 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1025 MachineFunction::iterator It = BB;
1026 ++It;
1027 MF->insert(It, loopMBB);
1028 MF->insert(It, exitMBB);
1029
1030 // Transfer the remainder of BB and its successor edges to exitMBB.
1031 exitMBB->splice(exitMBB->begin(), BB,
1032 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1033 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1034
1035 // thisMBB:
1036 // ...
1037 // fallthrough --> loopMBB
1038 BB->addSuccessor(loopMBB);
1039 loopMBB->addSuccessor(loopMBB);
1040 loopMBB->addSuccessor(exitMBB);
1041
1042 // loopMBB:
1043 // ll oldval, 0(ptr)
1044 // <binop> storeval, oldval, incr
1045 // sc success, storeval, 0(ptr)
1046 // beq success, $0, loopMBB
1047 BB = loopMBB;
1048 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1049 if (Nand) {
1050 // and andres, oldval, incr
1051 // nor storeval, $0, andres
1052 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1053 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1054 } else if (BinOpcode) {
1055 // <binop> storeval, oldval, incr
1056 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1057 } else {
1058 StoreVal = Incr;
1059 }
1060 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1061 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1062
1063 MI->eraseFromParent(); // The instruction is gone now.
1064
1065 return exitMBB;
1066}
1067
1068MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1069 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1070 unsigned SrcReg) const {
1071 const TargetInstrInfo *TII =
1072 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1073 DebugLoc DL = MI->getDebugLoc();
1074
1075 if (Subtarget.hasMips32r2() && Size == 1) {
1076 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1077 return BB;
1078 }
1079
1080 if (Subtarget.hasMips32r2() && Size == 2) {
1081 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1082 return BB;
1083 }
1084
1085 MachineFunction *MF = BB->getParent();
1086 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1087 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1088 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1089
1090 assert(Size < 32);
1091 int64_t ShiftImm = 32 - (Size * 8);
1092
1093 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1094 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1095
1096 return BB;
1097}
1098
1099MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1100 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1101 bool Nand) const {
1102 assert((Size == 1 || Size == 2) &&
1103 "Unsupported size for EmitAtomicBinaryPartial.");
1104
1105 MachineFunction *MF = BB->getParent();
1106 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1107 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1108 const TargetInstrInfo *TII =
1109 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1110 DebugLoc DL = MI->getDebugLoc();
1111
1112 unsigned Dest = MI->getOperand(0).getReg();
1113 unsigned Ptr = MI->getOperand(1).getReg();
1114 unsigned Incr = MI->getOperand(2).getReg();
1115
1116 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1117 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1118 unsigned Mask = RegInfo.createVirtualRegister(RC);
1119 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1120 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1121 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1122 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1123 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1124 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1125 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1126 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1127 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1128 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1129 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1130 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1131 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1132 unsigned Success = RegInfo.createVirtualRegister(RC);
1133
1134 // insert new blocks after the current block
1135 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1136 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1137 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1138 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1139 MachineFunction::iterator It = BB;
1140 ++It;
1141 MF->insert(It, loopMBB);
1142 MF->insert(It, sinkMBB);
1143 MF->insert(It, exitMBB);
1144
1145 // Transfer the remainder of BB and its successor edges to exitMBB.
1146 exitMBB->splice(exitMBB->begin(), BB,
1147 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1148 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1149
1150 BB->addSuccessor(loopMBB);
1151 loopMBB->addSuccessor(loopMBB);
1152 loopMBB->addSuccessor(sinkMBB);
1153 sinkMBB->addSuccessor(exitMBB);
1154
1155 // thisMBB:
1156 // addiu masklsb2,$0,-4 # 0xfffffffc
1157 // and alignedaddr,ptr,masklsb2
1158 // andi ptrlsb2,ptr,3
1159 // sll shiftamt,ptrlsb2,3
1160 // ori maskupper,$0,255 # 0xff
1161 // sll mask,maskupper,shiftamt
1162 // nor mask2,$0,mask
1163 // sll incr2,incr,shiftamt
1164
1165 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1166 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1167 .addReg(Mips::ZERO).addImm(-4);
1168 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1169 .addReg(Ptr).addReg(MaskLSB2);
1170 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1171 if (Subtarget.isLittle()) {
1172 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1173 } else {
1174 unsigned Off = RegInfo.createVirtualRegister(RC);
1175 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1176 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1177 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1178 }
1179 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1180 .addReg(Mips::ZERO).addImm(MaskImm);
1181 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1182 .addReg(MaskUpper).addReg(ShiftAmt);
1183 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1184 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1185
1186 // atomic.load.binop
1187 // loopMBB:
1188 // ll oldval,0(alignedaddr)
1189 // binop binopres,oldval,incr2
1190 // and newval,binopres,mask
1191 // and maskedoldval0,oldval,mask2
1192 // or storeval,maskedoldval0,newval
1193 // sc success,storeval,0(alignedaddr)
1194 // beq success,$0,loopMBB
1195
1196 // atomic.swap
1197 // loopMBB:
1198 // ll oldval,0(alignedaddr)
1199 // and newval,incr2,mask
1200 // and maskedoldval0,oldval,mask2
1201 // or storeval,maskedoldval0,newval
1202 // sc success,storeval,0(alignedaddr)
1203 // beq success,$0,loopMBB
1204
1205 BB = loopMBB;
1206 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1207 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1208 if (Nand) {
1209 // and andres, oldval, incr2
1210 // nor binopres, $0, andres
1211 // and newval, binopres, mask
1212 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1213 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1214 .addReg(Mips::ZERO).addReg(AndRes);
1215 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1216 } else if (BinOpcode) {
1217 // <binop> binopres, oldval, incr2
1218 // and newval, binopres, mask
1219 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1220 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1221 } else { // atomic.swap
1222 // and newval, incr2, mask
1223 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1224 }
1225
1226 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1227 .addReg(OldVal).addReg(Mask2);
1228 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1229 .addReg(MaskedOldVal0).addReg(NewVal);
1230 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1231 BuildMI(BB, DL, TII->get(SC), Success)
1232 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1233 BuildMI(BB, DL, TII->get(Mips::BEQ))
1234 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1235
1236 // sinkMBB:
1237 // and maskedoldval1,oldval,mask
1238 // srl srlres,maskedoldval1,shiftamt
1239 // sign_extend dest,srlres
1240 BB = sinkMBB;
1241
1242 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1243 .addReg(OldVal).addReg(Mask);
1244 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1245 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1246 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1247
1248 MI->eraseFromParent(); // The instruction is gone now.
1249
1250 return exitMBB;
1251}
1252
1253MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1254 MachineBasicBlock *BB,
1255 unsigned Size) const {
1256 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1257
1258 MachineFunction *MF = BB->getParent();
1259 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1260 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1261 const TargetInstrInfo *TII =
1262 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1263 DebugLoc DL = MI->getDebugLoc();
1264 unsigned LL, SC, ZERO, BNE, BEQ;
1265
1266 if (Size == 4) {
1267 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1268 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1269 ZERO = Mips::ZERO;
1270 BNE = Mips::BNE;
1271 BEQ = Mips::BEQ;
1272 } else {
1273 LL = Mips::LLD;
1274 SC = Mips::SCD;
1275 ZERO = Mips::ZERO_64;
1276 BNE = Mips::BNE64;
1277 BEQ = Mips::BEQ64;
1278 }
1279
1280 unsigned Dest = MI->getOperand(0).getReg();
1281 unsigned Ptr = MI->getOperand(1).getReg();
1282 unsigned OldVal = MI->getOperand(2).getReg();
1283 unsigned NewVal = MI->getOperand(3).getReg();
1284
1285 unsigned Success = RegInfo.createVirtualRegister(RC);
1286
1287 // insert new blocks after the current block
1288 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1289 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1290 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1291 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1292 MachineFunction::iterator It = BB;
1293 ++It;
1294 MF->insert(It, loop1MBB);
1295 MF->insert(It, loop2MBB);
1296 MF->insert(It, exitMBB);
1297
1298 // Transfer the remainder of BB and its successor edges to exitMBB.
1299 exitMBB->splice(exitMBB->begin(), BB,
1300 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1301 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1302
1303 // thisMBB:
1304 // ...
1305 // fallthrough --> loop1MBB
1306 BB->addSuccessor(loop1MBB);
1307 loop1MBB->addSuccessor(exitMBB);
1308 loop1MBB->addSuccessor(loop2MBB);
1309 loop2MBB->addSuccessor(loop1MBB);
1310 loop2MBB->addSuccessor(exitMBB);
1311
1312 // loop1MBB:
1313 // ll dest, 0(ptr)
1314 // bne dest, oldval, exitMBB
1315 BB = loop1MBB;
1316 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1317 BuildMI(BB, DL, TII->get(BNE))
1318 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1319
1320 // loop2MBB:
1321 // sc success, newval, 0(ptr)
1322 // beq success, $0, loop1MBB
1323 BB = loop2MBB;
1324 BuildMI(BB, DL, TII->get(SC), Success)
1325 .addReg(NewVal).addReg(Ptr).addImm(0);
1326 BuildMI(BB, DL, TII->get(BEQ))
1327 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1328
1329 MI->eraseFromParent(); // The instruction is gone now.
1330
1331 return exitMBB;
1332}
1333
1334MachineBasicBlock *
1335MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1336 MachineBasicBlock *BB,
1337 unsigned Size) const {
1338 assert((Size == 1 || Size == 2) &&
1339 "Unsupported size for EmitAtomicCmpSwapPartial.");
1340
1341 MachineFunction *MF = BB->getParent();
1342 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1343 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1344 const TargetInstrInfo *TII =
1345 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1346 DebugLoc DL = MI->getDebugLoc();
1347
1348 unsigned Dest = MI->getOperand(0).getReg();
1349 unsigned Ptr = MI->getOperand(1).getReg();
1350 unsigned CmpVal = MI->getOperand(2).getReg();
1351 unsigned NewVal = MI->getOperand(3).getReg();
1352
1353 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1354 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1355 unsigned Mask = RegInfo.createVirtualRegister(RC);
1356 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1357 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1358 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1359 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1360 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1361 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1362 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1363 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1364 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1365 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1366 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1367 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1368 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1369 unsigned Success = RegInfo.createVirtualRegister(RC);
1370
1371 // insert new blocks after the current block
1372 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1373 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1374 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1375 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1376 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1377 MachineFunction::iterator It = BB;
1378 ++It;
1379 MF->insert(It, loop1MBB);
1380 MF->insert(It, loop2MBB);
1381 MF->insert(It, sinkMBB);
1382 MF->insert(It, exitMBB);
1383
1384 // Transfer the remainder of BB and its successor edges to exitMBB.
1385 exitMBB->splice(exitMBB->begin(), BB,
1386 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1387 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1388
1389 BB->addSuccessor(loop1MBB);
1390 loop1MBB->addSuccessor(sinkMBB);
1391 loop1MBB->addSuccessor(loop2MBB);
1392 loop2MBB->addSuccessor(loop1MBB);
1393 loop2MBB->addSuccessor(sinkMBB);
1394 sinkMBB->addSuccessor(exitMBB);
1395
1396 // FIXME: computation of newval2 can be moved to loop2MBB.
1397 // thisMBB:
1398 // addiu masklsb2,$0,-4 # 0xfffffffc
1399 // and alignedaddr,ptr,masklsb2
1400 // andi ptrlsb2,ptr,3
1401 // sll shiftamt,ptrlsb2,3
1402 // ori maskupper,$0,255 # 0xff
1403 // sll mask,maskupper,shiftamt
1404 // nor mask2,$0,mask
1405 // andi maskedcmpval,cmpval,255
1406 // sll shiftedcmpval,maskedcmpval,shiftamt
1407 // andi maskednewval,newval,255
1408 // sll shiftednewval,maskednewval,shiftamt
1409 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1410 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1411 .addReg(Mips::ZERO).addImm(-4);
1412 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1413 .addReg(Ptr).addReg(MaskLSB2);
1414 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1415 if (Subtarget.isLittle()) {
1416 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1417 } else {
1418 unsigned Off = RegInfo.createVirtualRegister(RC);
1419 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1420 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1421 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1422 }
1423 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1424 .addReg(Mips::ZERO).addImm(MaskImm);
1425 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1426 .addReg(MaskUpper).addReg(ShiftAmt);
1427 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1428 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1429 .addReg(CmpVal).addImm(MaskImm);
1430 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1431 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1432 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1433 .addReg(NewVal).addImm(MaskImm);
1434 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1435 .addReg(MaskedNewVal).addReg(ShiftAmt);
1436
1437 // loop1MBB:
1438 // ll oldval,0(alginedaddr)
1439 // and maskedoldval0,oldval,mask
1440 // bne maskedoldval0,shiftedcmpval,sinkMBB
1441 BB = loop1MBB;
1442 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1443 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1444 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1445 .addReg(OldVal).addReg(Mask);
1446 BuildMI(BB, DL, TII->get(Mips::BNE))
1447 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1448
1449 // loop2MBB:
1450 // and maskedoldval1,oldval,mask2
1451 // or storeval,maskedoldval1,shiftednewval
1452 // sc success,storeval,0(alignedaddr)
1453 // beq success,$0,loop1MBB
1454 BB = loop2MBB;
1455 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1456 .addReg(OldVal).addReg(Mask2);
1457 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1458 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1459 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1460 BuildMI(BB, DL, TII->get(SC), Success)
1461 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1462 BuildMI(BB, DL, TII->get(Mips::BEQ))
1463 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1464
1465 // sinkMBB:
1466 // srl srlres,maskedoldval0,shiftamt
1467 // sign_extend dest,srlres
1468 BB = sinkMBB;
1469
1470 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1471 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1472 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1473
1474 MI->eraseFromParent(); // The instruction is gone now.
1475
1476 return exitMBB;
1477}
1478
1479MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1480 MachineBasicBlock *BB) const {
1481 MachineFunction *MF = BB->getParent();
1482 const TargetRegisterInfo *TRI =
1483 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1484 const TargetInstrInfo *TII =
1485 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1486 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1487 DebugLoc DL = MI->getDebugLoc();
1488 MachineBasicBlock::iterator II(MI);
1489
1490 unsigned Fc = MI->getOperand(1).getReg();
1491 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1492
1493 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1494
1495 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1496 .addImm(0)
1497 .addReg(Fc)
1498 .addImm(Mips::sub_lo);
1499
1500 // We don't erase the original instruction, we just replace the condition
1501 // register with the 64-bit super-register.
1502 MI->getOperand(1).setReg(Fc2);
1503
1504 return BB;
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// Misc Lower Operation implementation
1509//===----------------------------------------------------------------------===//
1510SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1511 SDValue Chain = Op.getOperand(0);
1512 SDValue Table = Op.getOperand(1);
1513 SDValue Index = Op.getOperand(2);
1514 SDLoc DL(Op);
1515 EVT PTy = getPointerTy();
1516 unsigned EntrySize =
1517 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1518
1519 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1520 DAG.getConstant(EntrySize, PTy));
1521 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1522
1523 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1524 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1525 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1526 false, 0);
1527 Chain = Addr.getValue(1);
1528
1529 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1530 Subtarget.isABI_N64()) {
1531 // For PIC, the sequence is:
1532 // BRIND(load(Jumptable + index) + RelocBase)
1533 // RelocBase can be JumpTable, GOT or some sort of global base.
1534 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1535 getPICJumpTableRelocBase(Table, DAG));
1536 }
1537
1538 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1539}
1540
1541SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1542 // The first operand is the chain, the second is the condition, the third is
1543 // the block to branch to if the condition is true.
1544 SDValue Chain = Op.getOperand(0);
1545 SDValue Dest = Op.getOperand(2);
1546 SDLoc DL(Op);
1547
1548 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1549 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1550
1551 // Return if flag is not set by a floating point comparison.
1552 if (CondRes.getOpcode() != MipsISD::FPCmp)
1553 return Op;
1554
1555 SDValue CCNode = CondRes.getOperand(2);
1556 Mips::CondCode CC =
1557 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1558 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1559 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1560 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1561 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1562 FCC0, Dest, CondRes);
1563}
1564
1565SDValue MipsTargetLowering::
1566lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1567{
1568 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1569 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1570
1571 // Return if flag is not set by a floating point comparison.
1572 if (Cond.getOpcode() != MipsISD::FPCmp)
1573 return Op;
1574
1575 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1576 SDLoc(Op));
1577}
1578
1579SDValue MipsTargetLowering::
1580lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1581{
1582 SDLoc DL(Op);
1583 EVT Ty = Op.getOperand(0).getValueType();
1584 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1585 getSetCCResultType(*DAG.getContext(), Ty),
1586 Op.getOperand(0), Op.getOperand(1),
1587 Op.getOperand(4));
1588
1589 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1590 Op.getOperand(3));
1591}
1592
1593SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1594 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1595 SDValue Cond = createFPCmp(DAG, Op);
1596
1597 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1598 "Floating point operand expected.");
1599
1600 SDValue True = DAG.getConstant(1, MVT::i32);
1601 SDValue False = DAG.getConstant(0, MVT::i32);
1602
1603 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1604}
1605
1606SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1607 SelectionDAG &DAG) const {
1608 EVT Ty = Op.getValueType();
1609 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1610 const GlobalValue *GV = N->getGlobal();
1611
1612 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1613 !Subtarget.isABI_N64()) {
1614 const MipsTargetObjectFile &TLOF =
1615 (const MipsTargetObjectFile&)getObjFileLowering();
1616
1617 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1618 // %gp_rel relocation
1619 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1620
1621 // %hi/%lo relocation
1622 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1623 }
1624
1625 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1626 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1627 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1628
1629 if (LargeGOT)
1630 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1631 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1632 MachinePointerInfo::getGOT());
1633
1634 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1635 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1636 ? MipsII::MO_GOT_DISP
1637 : MipsII::MO_GOT16,
1638 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1639}
1640
1641SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1642 SelectionDAG &DAG) const {
1643 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1644 EVT Ty = Op.getValueType();
1645
1646 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1647 !Subtarget.isABI_N64())
1648 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1649
1650 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1651 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1652}
1653
1654SDValue MipsTargetLowering::
1655lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1656{
1657 // If the relocation model is PIC, use the General Dynamic TLS Model or
1658 // Local Dynamic TLS model, otherwise use the Initial Exec or
1659 // Local Exec TLS Model.
1660
1661 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1662 SDLoc DL(GA);
1663 const GlobalValue *GV = GA->getGlobal();
1664 EVT PtrVT = getPointerTy();
1665
1666 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1667
1668 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1669 // General Dynamic and Local Dynamic TLS Model.
1670 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1671 : MipsII::MO_TLSGD;
1672
1673 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1674 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1675 getGlobalReg(DAG, PtrVT), TGA);
1676 unsigned PtrSize = PtrVT.getSizeInBits();
1677 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1678
1679 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1680
1681 ArgListTy Args;
1682 ArgListEntry Entry;
1683 Entry.Node = Argument;
1684 Entry.Ty = PtrTy;
1685 Args.push_back(Entry);
1686
1687 TargetLowering::CallLoweringInfo CLI(DAG);
1688 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1689 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1690 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1691
1692 SDValue Ret = CallResult.first;
1693
1694 if (model != TLSModel::LocalDynamic)
1695 return Ret;
1696
1697 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1698 MipsII::MO_DTPREL_HI);
1699 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1700 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1701 MipsII::MO_DTPREL_LO);
1702 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1703 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1704 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1705 }
1706
1707 SDValue Offset;
1708 if (model == TLSModel::InitialExec) {
1709 // Initial Exec TLS Model
1710 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1711 MipsII::MO_GOTTPREL);
1712 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1713 TGA);
1714 Offset = DAG.getLoad(PtrVT, DL,
1715 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1716 false, false, false, 0);
1717 } else {
1718 // Local Exec TLS Model
1719 assert(model == TLSModel::LocalExec);
1720 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1721 MipsII::MO_TPREL_HI);
1722 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1723 MipsII::MO_TPREL_LO);
1724 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1725 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1726 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1727 }
1728
1729 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1730 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1731}
1732
1733SDValue MipsTargetLowering::
1734lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1735{
1736 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1737 EVT Ty = Op.getValueType();
1738
1739 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1740 !Subtarget.isABI_N64())
1741 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1742
1743 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1744 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1745}
1746
1747SDValue MipsTargetLowering::
1748lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1749{
1750 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1751 EVT Ty = Op.getValueType();
1752
1753 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1754 !Subtarget.isABI_N64()) {
1755 const MipsTargetObjectFile &TLOF =
1756 (const MipsTargetObjectFile&)getObjFileLowering();
1757
1758 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1759 // %gp_rel relocation
1760 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1761
1762 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1763 }
1764
1765 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1766 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1767}
1768
1769SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1770 MachineFunction &MF = DAG.getMachineFunction();
1771 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1772
1773 SDLoc DL(Op);
1774 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1775 getPointerTy());
1776
1777 // vastart just stores the address of the VarArgsFrameIndex slot into the
1778 // memory location argument.
1779 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1780 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1781 MachinePointerInfo(SV), false, false, 0);
1782}
1783
1784SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1785 SDNode *Node = Op.getNode();
1786 EVT VT = Node->getValueType(0);
1787 SDValue Chain = Node->getOperand(0);
1788 SDValue VAListPtr = Node->getOperand(1);
1789 unsigned Align = Node->getConstantOperandVal(3);
1790 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1791 SDLoc DL(Node);
1792 unsigned ArgSlotSizeInBytes =
1793 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1794
1795 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1796 MachinePointerInfo(SV), false, false, false,
1797 0);
1798 SDValue VAList = VAListLoad;
1799
1800 // Re-align the pointer if necessary.
1801 // It should only ever be necessary for 64-bit types on O32 since the minimum
1802 // argument alignment is the same as the maximum type alignment for N32/N64.
1803 //
1804 // FIXME: We currently align too often. The code generator doesn't notice
1805 // when the pointer is still aligned from the last va_arg (or pair of
1806 // va_args for the i64 on O32 case).
1807 if (Align > getMinStackArgumentAlignment()) {
1808 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1809
1810 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1811 DAG.getConstant(Align - 1,
1812 VAList.getValueType()));
1813
1814 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1815 DAG.getConstant(-(int64_t)Align,
1816 VAList.getValueType()));
1817 }
1818
1819 // Increment the pointer, VAList, to the next vaarg.
1820 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1821 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1822 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1823 VAList.getValueType()));
1824 // Store the incremented VAList to the legalized pointer
1825 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1826 MachinePointerInfo(SV), false, false, 0);
1827
1828 // In big-endian mode we must adjust the pointer when the load size is smaller
1829 // than the argument slot size. We must also reduce the known alignment to
1830 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1831 // the correct half of the slot, and reduce the alignment from 8 (slot
1832 // alignment) down to 4 (type alignment).
1833 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1834 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1835 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1836 DAG.getIntPtrConstant(Adjustment));
1837 }
1838 // Load the actual argument out of the pointer VAList
1839 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1840 false, 0);
1841}
1842
1843static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1844 bool HasExtractInsert) {
1845 EVT TyX = Op.getOperand(0).getValueType();
1846 EVT TyY = Op.getOperand(1).getValueType();
1847 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1848 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1849 SDLoc DL(Op);
1850 SDValue Res;
1851
1852 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1853 // to i32.
1854 SDValue X = (TyX == MVT::f32) ?
1855 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1856 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1857 Const1);
1858 SDValue Y = (TyY == MVT::f32) ?
1859 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1860 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1861 Const1);
1862
1863 if (HasExtractInsert) {
1864 // ext E, Y, 31, 1 ; extract bit31 of Y
1865 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1866 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1867 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1868 } else {
1869 // sll SllX, X, 1
1870 // srl SrlX, SllX, 1
1871 // srl SrlY, Y, 31
1872 // sll SllY, SrlX, 31
1873 // or Or, SrlX, SllY
1874 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1875 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1876 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1877 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1878 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1879 }
1880
1881 if (TyX == MVT::f32)
1882 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1883
1884 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1885 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1886 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1887}
1888
1889static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1890 bool HasExtractInsert) {
1891 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1892 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1893 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1894 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1895 SDLoc DL(Op);
1896
1897 // Bitcast to integer nodes.
1898 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1899 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1900
1901 if (HasExtractInsert) {
1902 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1903 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1904 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1905 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1906
1907 if (WidthX > WidthY)
1908 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1909 else if (WidthY > WidthX)
1910 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1911
1912 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1913 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1914 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1915 }
1916
1917 // (d)sll SllX, X, 1
1918 // (d)srl SrlX, SllX, 1
1919 // (d)srl SrlY, Y, width(Y)-1
1920 // (d)sll SllY, SrlX, width(Y)-1
1921 // or Or, SrlX, SllY
1922 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1923 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1924 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1925 DAG.getConstant(WidthY - 1, MVT::i32));
1926
1927 if (WidthX > WidthY)
1928 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1929 else if (WidthY > WidthX)
1930 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1931
1932 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1933 DAG.getConstant(WidthX - 1, MVT::i32));
1934 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1935 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1936}
1937
1938SDValue
1939MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1940 if (Subtarget.isGP64bit())
1941 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1942
1943 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1944}
1945
1946SDValue MipsTargetLowering::
1947lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1948 // check the depth
1949 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1950 "Frame address can only be determined for current frame.");
1951
1952 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1953 MFI->setFrameAddressIsTaken(true);
1954 EVT VT = Op.getValueType();
1955 SDLoc DL(Op);
1956 SDValue FrameAddr =
1957 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1958 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
1959 return FrameAddr;
1960}
1961
1962SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1963 SelectionDAG &DAG) const {
1964 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1965 return SDValue();
1966
1967 // check the depth
1968 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1969 "Return address can be determined only for current frame.");
1970
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 MachineFrameInfo *MFI = MF.getFrameInfo();
1973 MVT VT = Op.getSimpleValueType();
1974 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
1975 MFI->setReturnAddressIsTaken(true);
1976
1977 // Return RA, which contains the return address. Mark it an implicit live-in.
1978 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1979 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1980}
1981
1982// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1983// generated from __builtin_eh_return (offset, handler)
1984// The effect of this is to adjust the stack pointer by "offset"
1985// and then branch to "handler".
1986SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1987 const {
1988 MachineFunction &MF = DAG.getMachineFunction();
1989 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1990
1991 MipsFI->setCallsEhReturn();
1992 SDValue Chain = Op.getOperand(0);
1993 SDValue Offset = Op.getOperand(1);
1994 SDValue Handler = Op.getOperand(2);
1995 SDLoc DL(Op);
1996 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
1997
1998 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1999 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2000 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2001 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2002 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2003 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2004 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2005 DAG.getRegister(OffsetReg, Ty),
2006 DAG.getRegister(AddrReg, getPointerTy()),
2007 Chain.getValue(1));
2008}
2009
2010SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2011 SelectionDAG &DAG) const {
2012 // FIXME: Need pseudo-fence for 'singlethread' fences
2013 // FIXME: Set SType for weaker fences where supported/appropriate.
2014 unsigned SType = 0;
2015 SDLoc DL(Op);
2016 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2017 DAG.getConstant(SType, MVT::i32));
2018}
2019
2020SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2021 SelectionDAG &DAG) const {
2022 SDLoc DL(Op);
2023 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2024
2025 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2026 SDValue Shamt = Op.getOperand(2);
2027 // if shamt < (VT.bits):
2028 // lo = (shl lo, shamt)
2029 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2030 // else:
2031 // lo = 0
2032 // hi = (shl lo, shamt[4:0])
2033 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2034 DAG.getConstant(-1, MVT::i32));
2035 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2036 DAG.getConstant(1, VT));
2037 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2038 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2039 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2040 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2041 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
785 case ISD::AND:
786 return performANDCombine(N, DAG, DCI, Subtarget);
787 case ISD::OR:
788 return performORCombine(N, DAG, DCI, Subtarget);
789 case ISD::ADD:
790 return performADDCombine(N, DAG, DCI, Subtarget);
791 }
792
793 return SDValue();
794}
795
796void
797MipsTargetLowering::LowerOperationWrapper(SDNode *N,
798 SmallVectorImpl<SDValue> &Results,
799 SelectionDAG &DAG) const {
800 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
801
802 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
803 Results.push_back(Res.getValue(I));
804}
805
806void
807MipsTargetLowering::ReplaceNodeResults(SDNode *N,
808 SmallVectorImpl<SDValue> &Results,
809 SelectionDAG &DAG) const {
810 return LowerOperationWrapper(N, Results, DAG);
811}
812
813SDValue MipsTargetLowering::
814LowerOperation(SDValue Op, SelectionDAG &DAG) const
815{
816 switch (Op.getOpcode())
817 {
818 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
819 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
820 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
821 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
822 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
823 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
824 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
825 case ISD::SELECT: return lowerSELECT(Op, DAG);
826 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
827 case ISD::SETCC: return lowerSETCC(Op, DAG);
828 case ISD::VASTART: return lowerVASTART(Op, DAG);
829 case ISD::VAARG: return lowerVAARG(Op, DAG);
830 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
831 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
832 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
833 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
834 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
835 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
836 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
837 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
838 case ISD::LOAD: return lowerLOAD(Op, DAG);
839 case ISD::STORE: return lowerSTORE(Op, DAG);
840 case ISD::ADD: return lowerADD(Op, DAG);
841 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
842 }
843 return SDValue();
844}
845
846//===----------------------------------------------------------------------===//
847// Lower helper functions
848//===----------------------------------------------------------------------===//
849
850// addLiveIn - This helper function adds the specified physical register to the
851// MachineFunction as a live in value. It also creates a corresponding
852// virtual register for it.
853static unsigned
854addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
855{
856 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
857 MF.getRegInfo().addLiveIn(PReg, VReg);
858 return VReg;
859}
860
861static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
862 MachineBasicBlock &MBB,
863 const TargetInstrInfo &TII,
864 bool Is64Bit) {
865 if (NoZeroDivCheck)
866 return &MBB;
867
868 // Insert instruction "teq $divisor_reg, $zero, 7".
869 MachineBasicBlock::iterator I(MI);
870 MachineInstrBuilder MIB;
871 MachineOperand &Divisor = MI->getOperand(2);
872 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
873 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
874 .addReg(Mips::ZERO).addImm(7);
875
876 // Use the 32-bit sub-register if this is a 64-bit division.
877 if (Is64Bit)
878 MIB->getOperand(0).setSubReg(Mips::sub_32);
879
880 // Clear Divisor's kill flag.
881 Divisor.setIsKill(false);
882
883 // We would normally delete the original instruction here but in this case
884 // we only needed to inject an additional instruction rather than replace it.
885
886 return &MBB;
887}
888
889MachineBasicBlock *
890MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
891 MachineBasicBlock *BB) const {
892 switch (MI->getOpcode()) {
893 default:
894 llvm_unreachable("Unexpected instr type to insert");
895 case Mips::ATOMIC_LOAD_ADD_I8:
896 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
897 case Mips::ATOMIC_LOAD_ADD_I16:
898 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
899 case Mips::ATOMIC_LOAD_ADD_I32:
900 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
901 case Mips::ATOMIC_LOAD_ADD_I64:
902 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
903
904 case Mips::ATOMIC_LOAD_AND_I8:
905 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
906 case Mips::ATOMIC_LOAD_AND_I16:
907 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
908 case Mips::ATOMIC_LOAD_AND_I32:
909 return emitAtomicBinary(MI, BB, 4, Mips::AND);
910 case Mips::ATOMIC_LOAD_AND_I64:
911 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
912
913 case Mips::ATOMIC_LOAD_OR_I8:
914 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
915 case Mips::ATOMIC_LOAD_OR_I16:
916 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
917 case Mips::ATOMIC_LOAD_OR_I32:
918 return emitAtomicBinary(MI, BB, 4, Mips::OR);
919 case Mips::ATOMIC_LOAD_OR_I64:
920 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
921
922 case Mips::ATOMIC_LOAD_XOR_I8:
923 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
924 case Mips::ATOMIC_LOAD_XOR_I16:
925 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
926 case Mips::ATOMIC_LOAD_XOR_I32:
927 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
928 case Mips::ATOMIC_LOAD_XOR_I64:
929 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
930
931 case Mips::ATOMIC_LOAD_NAND_I8:
932 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
933 case Mips::ATOMIC_LOAD_NAND_I16:
934 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
935 case Mips::ATOMIC_LOAD_NAND_I32:
936 return emitAtomicBinary(MI, BB, 4, 0, true);
937 case Mips::ATOMIC_LOAD_NAND_I64:
938 return emitAtomicBinary(MI, BB, 8, 0, true);
939
940 case Mips::ATOMIC_LOAD_SUB_I8:
941 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
942 case Mips::ATOMIC_LOAD_SUB_I16:
943 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
944 case Mips::ATOMIC_LOAD_SUB_I32:
945 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
946 case Mips::ATOMIC_LOAD_SUB_I64:
947 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
948
949 case Mips::ATOMIC_SWAP_I8:
950 return emitAtomicBinaryPartword(MI, BB, 1, 0);
951 case Mips::ATOMIC_SWAP_I16:
952 return emitAtomicBinaryPartword(MI, BB, 2, 0);
953 case Mips::ATOMIC_SWAP_I32:
954 return emitAtomicBinary(MI, BB, 4, 0);
955 case Mips::ATOMIC_SWAP_I64:
956 return emitAtomicBinary(MI, BB, 8, 0);
957
958 case Mips::ATOMIC_CMP_SWAP_I8:
959 return emitAtomicCmpSwapPartword(MI, BB, 1);
960 case Mips::ATOMIC_CMP_SWAP_I16:
961 return emitAtomicCmpSwapPartword(MI, BB, 2);
962 case Mips::ATOMIC_CMP_SWAP_I32:
963 return emitAtomicCmpSwap(MI, BB, 4);
964 case Mips::ATOMIC_CMP_SWAP_I64:
965 return emitAtomicCmpSwap(MI, BB, 8);
966 case Mips::PseudoSDIV:
967 case Mips::PseudoUDIV:
968 case Mips::DIV:
969 case Mips::DIVU:
970 case Mips::MOD:
971 case Mips::MODU:
972 return insertDivByZeroTrap(
973 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
974 case Mips::PseudoDSDIV:
975 case Mips::PseudoDUDIV:
976 case Mips::DDIV:
977 case Mips::DDIVU:
978 case Mips::DMOD:
979 case Mips::DMODU:
980 return insertDivByZeroTrap(
981 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
982 case Mips::SEL_D:
983 return emitSEL_D(MI, BB);
984
985 case Mips::PseudoSELECT_I:
986 case Mips::PseudoSELECT_I64:
987 case Mips::PseudoSELECT_S:
988 case Mips::PseudoSELECT_D32:
989 case Mips::PseudoSELECT_D64:
990 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
991 case Mips::PseudoSELECTFP_F_I:
992 case Mips::PseudoSELECTFP_F_I64:
993 case Mips::PseudoSELECTFP_F_S:
994 case Mips::PseudoSELECTFP_F_D32:
995 case Mips::PseudoSELECTFP_F_D64:
996 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
997 case Mips::PseudoSELECTFP_T_I:
998 case Mips::PseudoSELECTFP_T_I64:
999 case Mips::PseudoSELECTFP_T_S:
1000 case Mips::PseudoSELECTFP_T_D32:
1001 case Mips::PseudoSELECTFP_T_D64:
1002 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1003 }
1004}
1005
1006// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1007// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1008MachineBasicBlock *
1009MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1010 unsigned Size, unsigned BinOpcode,
1011 bool Nand) const {
1012 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1013
1014 MachineFunction *MF = BB->getParent();
1015 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1016 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1017 const TargetInstrInfo *TII =
1018 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1019 DebugLoc DL = MI->getDebugLoc();
1020 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1021
1022 if (Size == 4) {
1023 if (isMicroMips) {
1024 LL = Mips::LL_MM;
1025 SC = Mips::SC_MM;
1026 } else {
1027 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1028 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1029 }
1030 AND = Mips::AND;
1031 NOR = Mips::NOR;
1032 ZERO = Mips::ZERO;
1033 BEQ = Mips::BEQ;
1034 } else {
1035 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1036 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1037 AND = Mips::AND64;
1038 NOR = Mips::NOR64;
1039 ZERO = Mips::ZERO_64;
1040 BEQ = Mips::BEQ64;
1041 }
1042
1043 unsigned OldVal = MI->getOperand(0).getReg();
1044 unsigned Ptr = MI->getOperand(1).getReg();
1045 unsigned Incr = MI->getOperand(2).getReg();
1046
1047 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1048 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1049 unsigned Success = RegInfo.createVirtualRegister(RC);
1050
1051 // insert new blocks after the current block
1052 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1053 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1055 MachineFunction::iterator It = BB;
1056 ++It;
1057 MF->insert(It, loopMBB);
1058 MF->insert(It, exitMBB);
1059
1060 // Transfer the remainder of BB and its successor edges to exitMBB.
1061 exitMBB->splice(exitMBB->begin(), BB,
1062 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1063 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1064
1065 // thisMBB:
1066 // ...
1067 // fallthrough --> loopMBB
1068 BB->addSuccessor(loopMBB);
1069 loopMBB->addSuccessor(loopMBB);
1070 loopMBB->addSuccessor(exitMBB);
1071
1072 // loopMBB:
1073 // ll oldval, 0(ptr)
1074 // <binop> storeval, oldval, incr
1075 // sc success, storeval, 0(ptr)
1076 // beq success, $0, loopMBB
1077 BB = loopMBB;
1078 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1079 if (Nand) {
1080 // and andres, oldval, incr
1081 // nor storeval, $0, andres
1082 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1083 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1084 } else if (BinOpcode) {
1085 // <binop> storeval, oldval, incr
1086 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1087 } else {
1088 StoreVal = Incr;
1089 }
1090 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1091 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1092
1093 MI->eraseFromParent(); // The instruction is gone now.
1094
1095 return exitMBB;
1096}
1097
1098MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1099 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1100 unsigned SrcReg) const {
1101 const TargetInstrInfo *TII =
1102 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1103 DebugLoc DL = MI->getDebugLoc();
1104
1105 if (Subtarget.hasMips32r2() && Size == 1) {
1106 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1107 return BB;
1108 }
1109
1110 if (Subtarget.hasMips32r2() && Size == 2) {
1111 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1112 return BB;
1113 }
1114
1115 MachineFunction *MF = BB->getParent();
1116 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1117 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1118 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1119
1120 assert(Size < 32);
1121 int64_t ShiftImm = 32 - (Size * 8);
1122
1123 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1124 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1125
1126 return BB;
1127}
1128
1129MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1130 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1131 bool Nand) const {
1132 assert((Size == 1 || Size == 2) &&
1133 "Unsupported size for EmitAtomicBinaryPartial.");
1134
1135 MachineFunction *MF = BB->getParent();
1136 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1137 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1138 const TargetInstrInfo *TII =
1139 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1140 DebugLoc DL = MI->getDebugLoc();
1141
1142 unsigned Dest = MI->getOperand(0).getReg();
1143 unsigned Ptr = MI->getOperand(1).getReg();
1144 unsigned Incr = MI->getOperand(2).getReg();
1145
1146 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1147 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1148 unsigned Mask = RegInfo.createVirtualRegister(RC);
1149 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1150 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1151 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1152 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1153 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1154 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1155 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1156 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1157 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1158 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1159 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1160 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1161 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1162 unsigned Success = RegInfo.createVirtualRegister(RC);
1163
1164 // insert new blocks after the current block
1165 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1166 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1167 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1168 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1169 MachineFunction::iterator It = BB;
1170 ++It;
1171 MF->insert(It, loopMBB);
1172 MF->insert(It, sinkMBB);
1173 MF->insert(It, exitMBB);
1174
1175 // Transfer the remainder of BB and its successor edges to exitMBB.
1176 exitMBB->splice(exitMBB->begin(), BB,
1177 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1178 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1179
1180 BB->addSuccessor(loopMBB);
1181 loopMBB->addSuccessor(loopMBB);
1182 loopMBB->addSuccessor(sinkMBB);
1183 sinkMBB->addSuccessor(exitMBB);
1184
1185 // thisMBB:
1186 // addiu masklsb2,$0,-4 # 0xfffffffc
1187 // and alignedaddr,ptr,masklsb2
1188 // andi ptrlsb2,ptr,3
1189 // sll shiftamt,ptrlsb2,3
1190 // ori maskupper,$0,255 # 0xff
1191 // sll mask,maskupper,shiftamt
1192 // nor mask2,$0,mask
1193 // sll incr2,incr,shiftamt
1194
1195 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1196 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1197 .addReg(Mips::ZERO).addImm(-4);
1198 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1199 .addReg(Ptr).addReg(MaskLSB2);
1200 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1201 if (Subtarget.isLittle()) {
1202 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1203 } else {
1204 unsigned Off = RegInfo.createVirtualRegister(RC);
1205 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1206 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1207 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1208 }
1209 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1210 .addReg(Mips::ZERO).addImm(MaskImm);
1211 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1212 .addReg(MaskUpper).addReg(ShiftAmt);
1213 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1214 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1215
1216 // atomic.load.binop
1217 // loopMBB:
1218 // ll oldval,0(alignedaddr)
1219 // binop binopres,oldval,incr2
1220 // and newval,binopres,mask
1221 // and maskedoldval0,oldval,mask2
1222 // or storeval,maskedoldval0,newval
1223 // sc success,storeval,0(alignedaddr)
1224 // beq success,$0,loopMBB
1225
1226 // atomic.swap
1227 // loopMBB:
1228 // ll oldval,0(alignedaddr)
1229 // and newval,incr2,mask
1230 // and maskedoldval0,oldval,mask2
1231 // or storeval,maskedoldval0,newval
1232 // sc success,storeval,0(alignedaddr)
1233 // beq success,$0,loopMBB
1234
1235 BB = loopMBB;
1236 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1237 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1238 if (Nand) {
1239 // and andres, oldval, incr2
1240 // nor binopres, $0, andres
1241 // and newval, binopres, mask
1242 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1243 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1244 .addReg(Mips::ZERO).addReg(AndRes);
1245 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1246 } else if (BinOpcode) {
1247 // <binop> binopres, oldval, incr2
1248 // and newval, binopres, mask
1249 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1250 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1251 } else { // atomic.swap
1252 // and newval, incr2, mask
1253 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1254 }
1255
1256 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1257 .addReg(OldVal).addReg(Mask2);
1258 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1259 .addReg(MaskedOldVal0).addReg(NewVal);
1260 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1261 BuildMI(BB, DL, TII->get(SC), Success)
1262 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1263 BuildMI(BB, DL, TII->get(Mips::BEQ))
1264 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1265
1266 // sinkMBB:
1267 // and maskedoldval1,oldval,mask
1268 // srl srlres,maskedoldval1,shiftamt
1269 // sign_extend dest,srlres
1270 BB = sinkMBB;
1271
1272 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1273 .addReg(OldVal).addReg(Mask);
1274 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1275 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1276 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1277
1278 MI->eraseFromParent(); // The instruction is gone now.
1279
1280 return exitMBB;
1281}
1282
1283MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1284 MachineBasicBlock *BB,
1285 unsigned Size) const {
1286 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1287
1288 MachineFunction *MF = BB->getParent();
1289 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1290 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1291 const TargetInstrInfo *TII =
1292 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1293 DebugLoc DL = MI->getDebugLoc();
1294 unsigned LL, SC, ZERO, BNE, BEQ;
1295
1296 if (Size == 4) {
1297 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1298 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1299 ZERO = Mips::ZERO;
1300 BNE = Mips::BNE;
1301 BEQ = Mips::BEQ;
1302 } else {
1303 LL = Mips::LLD;
1304 SC = Mips::SCD;
1305 ZERO = Mips::ZERO_64;
1306 BNE = Mips::BNE64;
1307 BEQ = Mips::BEQ64;
1308 }
1309
1310 unsigned Dest = MI->getOperand(0).getReg();
1311 unsigned Ptr = MI->getOperand(1).getReg();
1312 unsigned OldVal = MI->getOperand(2).getReg();
1313 unsigned NewVal = MI->getOperand(3).getReg();
1314
1315 unsigned Success = RegInfo.createVirtualRegister(RC);
1316
1317 // insert new blocks after the current block
1318 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1319 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1320 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1321 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1322 MachineFunction::iterator It = BB;
1323 ++It;
1324 MF->insert(It, loop1MBB);
1325 MF->insert(It, loop2MBB);
1326 MF->insert(It, exitMBB);
1327
1328 // Transfer the remainder of BB and its successor edges to exitMBB.
1329 exitMBB->splice(exitMBB->begin(), BB,
1330 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1331 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1332
1333 // thisMBB:
1334 // ...
1335 // fallthrough --> loop1MBB
1336 BB->addSuccessor(loop1MBB);
1337 loop1MBB->addSuccessor(exitMBB);
1338 loop1MBB->addSuccessor(loop2MBB);
1339 loop2MBB->addSuccessor(loop1MBB);
1340 loop2MBB->addSuccessor(exitMBB);
1341
1342 // loop1MBB:
1343 // ll dest, 0(ptr)
1344 // bne dest, oldval, exitMBB
1345 BB = loop1MBB;
1346 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1347 BuildMI(BB, DL, TII->get(BNE))
1348 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1349
1350 // loop2MBB:
1351 // sc success, newval, 0(ptr)
1352 // beq success, $0, loop1MBB
1353 BB = loop2MBB;
1354 BuildMI(BB, DL, TII->get(SC), Success)
1355 .addReg(NewVal).addReg(Ptr).addImm(0);
1356 BuildMI(BB, DL, TII->get(BEQ))
1357 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1358
1359 MI->eraseFromParent(); // The instruction is gone now.
1360
1361 return exitMBB;
1362}
1363
1364MachineBasicBlock *
1365MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1366 MachineBasicBlock *BB,
1367 unsigned Size) const {
1368 assert((Size == 1 || Size == 2) &&
1369 "Unsupported size for EmitAtomicCmpSwapPartial.");
1370
1371 MachineFunction *MF = BB->getParent();
1372 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1373 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1374 const TargetInstrInfo *TII =
1375 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1376 DebugLoc DL = MI->getDebugLoc();
1377
1378 unsigned Dest = MI->getOperand(0).getReg();
1379 unsigned Ptr = MI->getOperand(1).getReg();
1380 unsigned CmpVal = MI->getOperand(2).getReg();
1381 unsigned NewVal = MI->getOperand(3).getReg();
1382
1383 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1384 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1385 unsigned Mask = RegInfo.createVirtualRegister(RC);
1386 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1387 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1388 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1389 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1390 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1391 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1392 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1393 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1394 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1395 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1396 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1397 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1398 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1399 unsigned Success = RegInfo.createVirtualRegister(RC);
1400
1401 // insert new blocks after the current block
1402 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1403 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1404 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1405 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1406 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1407 MachineFunction::iterator It = BB;
1408 ++It;
1409 MF->insert(It, loop1MBB);
1410 MF->insert(It, loop2MBB);
1411 MF->insert(It, sinkMBB);
1412 MF->insert(It, exitMBB);
1413
1414 // Transfer the remainder of BB and its successor edges to exitMBB.
1415 exitMBB->splice(exitMBB->begin(), BB,
1416 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1417 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1418
1419 BB->addSuccessor(loop1MBB);
1420 loop1MBB->addSuccessor(sinkMBB);
1421 loop1MBB->addSuccessor(loop2MBB);
1422 loop2MBB->addSuccessor(loop1MBB);
1423 loop2MBB->addSuccessor(sinkMBB);
1424 sinkMBB->addSuccessor(exitMBB);
1425
1426 // FIXME: computation of newval2 can be moved to loop2MBB.
1427 // thisMBB:
1428 // addiu masklsb2,$0,-4 # 0xfffffffc
1429 // and alignedaddr,ptr,masklsb2
1430 // andi ptrlsb2,ptr,3
1431 // sll shiftamt,ptrlsb2,3
1432 // ori maskupper,$0,255 # 0xff
1433 // sll mask,maskupper,shiftamt
1434 // nor mask2,$0,mask
1435 // andi maskedcmpval,cmpval,255
1436 // sll shiftedcmpval,maskedcmpval,shiftamt
1437 // andi maskednewval,newval,255
1438 // sll shiftednewval,maskednewval,shiftamt
1439 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1440 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1441 .addReg(Mips::ZERO).addImm(-4);
1442 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1443 .addReg(Ptr).addReg(MaskLSB2);
1444 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1445 if (Subtarget.isLittle()) {
1446 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1447 } else {
1448 unsigned Off = RegInfo.createVirtualRegister(RC);
1449 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1450 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1451 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1452 }
1453 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1454 .addReg(Mips::ZERO).addImm(MaskImm);
1455 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1456 .addReg(MaskUpper).addReg(ShiftAmt);
1457 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1458 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1459 .addReg(CmpVal).addImm(MaskImm);
1460 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1461 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1462 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1463 .addReg(NewVal).addImm(MaskImm);
1464 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1465 .addReg(MaskedNewVal).addReg(ShiftAmt);
1466
1467 // loop1MBB:
1468 // ll oldval,0(alginedaddr)
1469 // and maskedoldval0,oldval,mask
1470 // bne maskedoldval0,shiftedcmpval,sinkMBB
1471 BB = loop1MBB;
1472 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1473 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1474 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1475 .addReg(OldVal).addReg(Mask);
1476 BuildMI(BB, DL, TII->get(Mips::BNE))
1477 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1478
1479 // loop2MBB:
1480 // and maskedoldval1,oldval,mask2
1481 // or storeval,maskedoldval1,shiftednewval
1482 // sc success,storeval,0(alignedaddr)
1483 // beq success,$0,loop1MBB
1484 BB = loop2MBB;
1485 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1486 .addReg(OldVal).addReg(Mask2);
1487 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1488 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1489 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1490 BuildMI(BB, DL, TII->get(SC), Success)
1491 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1492 BuildMI(BB, DL, TII->get(Mips::BEQ))
1493 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1494
1495 // sinkMBB:
1496 // srl srlres,maskedoldval0,shiftamt
1497 // sign_extend dest,srlres
1498 BB = sinkMBB;
1499
1500 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1501 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1502 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1503
1504 MI->eraseFromParent(); // The instruction is gone now.
1505
1506 return exitMBB;
1507}
1508
1509MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1510 MachineBasicBlock *BB) const {
1511 MachineFunction *MF = BB->getParent();
1512 const TargetRegisterInfo *TRI =
1513 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1514 const TargetInstrInfo *TII =
1515 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1516 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1517 DebugLoc DL = MI->getDebugLoc();
1518 MachineBasicBlock::iterator II(MI);
1519
1520 unsigned Fc = MI->getOperand(1).getReg();
1521 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1522
1523 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1524
1525 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1526 .addImm(0)
1527 .addReg(Fc)
1528 .addImm(Mips::sub_lo);
1529
1530 // We don't erase the original instruction, we just replace the condition
1531 // register with the 64-bit super-register.
1532 MI->getOperand(1).setReg(Fc2);
1533
1534 return BB;
1535}
1536
1537//===----------------------------------------------------------------------===//
1538// Misc Lower Operation implementation
1539//===----------------------------------------------------------------------===//
1540SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1541 SDValue Chain = Op.getOperand(0);
1542 SDValue Table = Op.getOperand(1);
1543 SDValue Index = Op.getOperand(2);
1544 SDLoc DL(Op);
1545 EVT PTy = getPointerTy();
1546 unsigned EntrySize =
1547 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1548
1549 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1550 DAG.getConstant(EntrySize, PTy));
1551 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1552
1553 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1554 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1555 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1556 false, 0);
1557 Chain = Addr.getValue(1);
1558
1559 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1560 Subtarget.isABI_N64()) {
1561 // For PIC, the sequence is:
1562 // BRIND(load(Jumptable + index) + RelocBase)
1563 // RelocBase can be JumpTable, GOT or some sort of global base.
1564 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1565 getPICJumpTableRelocBase(Table, DAG));
1566 }
1567
1568 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1569}
1570
1571SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1572 // The first operand is the chain, the second is the condition, the third is
1573 // the block to branch to if the condition is true.
1574 SDValue Chain = Op.getOperand(0);
1575 SDValue Dest = Op.getOperand(2);
1576 SDLoc DL(Op);
1577
1578 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1579 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1580
1581 // Return if flag is not set by a floating point comparison.
1582 if (CondRes.getOpcode() != MipsISD::FPCmp)
1583 return Op;
1584
1585 SDValue CCNode = CondRes.getOperand(2);
1586 Mips::CondCode CC =
1587 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1588 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1589 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1590 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1591 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1592 FCC0, Dest, CondRes);
1593}
1594
1595SDValue MipsTargetLowering::
1596lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1597{
1598 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1599 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1600
1601 // Return if flag is not set by a floating point comparison.
1602 if (Cond.getOpcode() != MipsISD::FPCmp)
1603 return Op;
1604
1605 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1606 SDLoc(Op));
1607}
1608
1609SDValue MipsTargetLowering::
1610lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1611{
1612 SDLoc DL(Op);
1613 EVT Ty = Op.getOperand(0).getValueType();
1614 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1615 getSetCCResultType(*DAG.getContext(), Ty),
1616 Op.getOperand(0), Op.getOperand(1),
1617 Op.getOperand(4));
1618
1619 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1620 Op.getOperand(3));
1621}
1622
1623SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1624 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1625 SDValue Cond = createFPCmp(DAG, Op);
1626
1627 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1628 "Floating point operand expected.");
1629
1630 SDValue True = DAG.getConstant(1, MVT::i32);
1631 SDValue False = DAG.getConstant(0, MVT::i32);
1632
1633 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1634}
1635
1636SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1637 SelectionDAG &DAG) const {
1638 EVT Ty = Op.getValueType();
1639 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1640 const GlobalValue *GV = N->getGlobal();
1641
1642 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1643 !Subtarget.isABI_N64()) {
1644 const MipsTargetObjectFile &TLOF =
1645 (const MipsTargetObjectFile&)getObjFileLowering();
1646
1647 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1648 // %gp_rel relocation
1649 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1650
1651 // %hi/%lo relocation
1652 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1653 }
1654
1655 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1656 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1657 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1658
1659 if (LargeGOT)
1660 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1661 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1662 MachinePointerInfo::getGOT());
1663
1664 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1665 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1666 ? MipsII::MO_GOT_DISP
1667 : MipsII::MO_GOT16,
1668 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1669}
1670
1671SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1672 SelectionDAG &DAG) const {
1673 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1674 EVT Ty = Op.getValueType();
1675
1676 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1677 !Subtarget.isABI_N64())
1678 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1679
1680 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1681 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1682}
1683
1684SDValue MipsTargetLowering::
1685lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1686{
1687 // If the relocation model is PIC, use the General Dynamic TLS Model or
1688 // Local Dynamic TLS model, otherwise use the Initial Exec or
1689 // Local Exec TLS Model.
1690
1691 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1692 SDLoc DL(GA);
1693 const GlobalValue *GV = GA->getGlobal();
1694 EVT PtrVT = getPointerTy();
1695
1696 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1697
1698 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1699 // General Dynamic and Local Dynamic TLS Model.
1700 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1701 : MipsII::MO_TLSGD;
1702
1703 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1704 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1705 getGlobalReg(DAG, PtrVT), TGA);
1706 unsigned PtrSize = PtrVT.getSizeInBits();
1707 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1708
1709 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1710
1711 ArgListTy Args;
1712 ArgListEntry Entry;
1713 Entry.Node = Argument;
1714 Entry.Ty = PtrTy;
1715 Args.push_back(Entry);
1716
1717 TargetLowering::CallLoweringInfo CLI(DAG);
1718 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1719 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1720 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1721
1722 SDValue Ret = CallResult.first;
1723
1724 if (model != TLSModel::LocalDynamic)
1725 return Ret;
1726
1727 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1728 MipsII::MO_DTPREL_HI);
1729 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1730 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1731 MipsII::MO_DTPREL_LO);
1732 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1733 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1734 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1735 }
1736
1737 SDValue Offset;
1738 if (model == TLSModel::InitialExec) {
1739 // Initial Exec TLS Model
1740 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1741 MipsII::MO_GOTTPREL);
1742 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1743 TGA);
1744 Offset = DAG.getLoad(PtrVT, DL,
1745 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1746 false, false, false, 0);
1747 } else {
1748 // Local Exec TLS Model
1749 assert(model == TLSModel::LocalExec);
1750 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1751 MipsII::MO_TPREL_HI);
1752 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1753 MipsII::MO_TPREL_LO);
1754 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1755 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1756 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1757 }
1758
1759 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1760 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1761}
1762
1763SDValue MipsTargetLowering::
1764lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1765{
1766 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1767 EVT Ty = Op.getValueType();
1768
1769 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1770 !Subtarget.isABI_N64())
1771 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1772
1773 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1774 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1775}
1776
1777SDValue MipsTargetLowering::
1778lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1779{
1780 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1781 EVT Ty = Op.getValueType();
1782
1783 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1784 !Subtarget.isABI_N64()) {
1785 const MipsTargetObjectFile &TLOF =
1786 (const MipsTargetObjectFile&)getObjFileLowering();
1787
1788 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1789 // %gp_rel relocation
1790 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1791
1792 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1793 }
1794
1795 return getAddrLocal(N, SDLoc(N), Ty, DAG,
1796 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1797}
1798
1799SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1800 MachineFunction &MF = DAG.getMachineFunction();
1801 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1802
1803 SDLoc DL(Op);
1804 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1805 getPointerTy());
1806
1807 // vastart just stores the address of the VarArgsFrameIndex slot into the
1808 // memory location argument.
1809 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1810 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1811 MachinePointerInfo(SV), false, false, 0);
1812}
1813
1814SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1815 SDNode *Node = Op.getNode();
1816 EVT VT = Node->getValueType(0);
1817 SDValue Chain = Node->getOperand(0);
1818 SDValue VAListPtr = Node->getOperand(1);
1819 unsigned Align = Node->getConstantOperandVal(3);
1820 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1821 SDLoc DL(Node);
1822 unsigned ArgSlotSizeInBytes =
1823 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1824
1825 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1826 MachinePointerInfo(SV), false, false, false,
1827 0);
1828 SDValue VAList = VAListLoad;
1829
1830 // Re-align the pointer if necessary.
1831 // It should only ever be necessary for 64-bit types on O32 since the minimum
1832 // argument alignment is the same as the maximum type alignment for N32/N64.
1833 //
1834 // FIXME: We currently align too often. The code generator doesn't notice
1835 // when the pointer is still aligned from the last va_arg (or pair of
1836 // va_args for the i64 on O32 case).
1837 if (Align > getMinStackArgumentAlignment()) {
1838 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1839
1840 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1841 DAG.getConstant(Align - 1,
1842 VAList.getValueType()));
1843
1844 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1845 DAG.getConstant(-(int64_t)Align,
1846 VAList.getValueType()));
1847 }
1848
1849 // Increment the pointer, VAList, to the next vaarg.
1850 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1851 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1852 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1853 VAList.getValueType()));
1854 // Store the incremented VAList to the legalized pointer
1855 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1856 MachinePointerInfo(SV), false, false, 0);
1857
1858 // In big-endian mode we must adjust the pointer when the load size is smaller
1859 // than the argument slot size. We must also reduce the known alignment to
1860 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1861 // the correct half of the slot, and reduce the alignment from 8 (slot
1862 // alignment) down to 4 (type alignment).
1863 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1864 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1865 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1866 DAG.getIntPtrConstant(Adjustment));
1867 }
1868 // Load the actual argument out of the pointer VAList
1869 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1870 false, 0);
1871}
1872
1873static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1874 bool HasExtractInsert) {
1875 EVT TyX = Op.getOperand(0).getValueType();
1876 EVT TyY = Op.getOperand(1).getValueType();
1877 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1878 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1879 SDLoc DL(Op);
1880 SDValue Res;
1881
1882 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1883 // to i32.
1884 SDValue X = (TyX == MVT::f32) ?
1885 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1886 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1887 Const1);
1888 SDValue Y = (TyY == MVT::f32) ?
1889 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1890 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1891 Const1);
1892
1893 if (HasExtractInsert) {
1894 // ext E, Y, 31, 1 ; extract bit31 of Y
1895 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1896 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1897 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1898 } else {
1899 // sll SllX, X, 1
1900 // srl SrlX, SllX, 1
1901 // srl SrlY, Y, 31
1902 // sll SllY, SrlX, 31
1903 // or Or, SrlX, SllY
1904 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1905 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1906 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1907 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1908 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1909 }
1910
1911 if (TyX == MVT::f32)
1912 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1913
1914 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1915 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1916 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1917}
1918
1919static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1920 bool HasExtractInsert) {
1921 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1922 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1923 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1924 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1925 SDLoc DL(Op);
1926
1927 // Bitcast to integer nodes.
1928 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1929 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1930
1931 if (HasExtractInsert) {
1932 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1933 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1934 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1935 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1936
1937 if (WidthX > WidthY)
1938 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1939 else if (WidthY > WidthX)
1940 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1941
1942 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1943 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1944 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1945 }
1946
1947 // (d)sll SllX, X, 1
1948 // (d)srl SrlX, SllX, 1
1949 // (d)srl SrlY, Y, width(Y)-1
1950 // (d)sll SllY, SrlX, width(Y)-1
1951 // or Or, SrlX, SllY
1952 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1953 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1954 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1955 DAG.getConstant(WidthY - 1, MVT::i32));
1956
1957 if (WidthX > WidthY)
1958 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1959 else if (WidthY > WidthX)
1960 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1961
1962 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1963 DAG.getConstant(WidthX - 1, MVT::i32));
1964 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1965 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1966}
1967
1968SDValue
1969MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1970 if (Subtarget.isGP64bit())
1971 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1972
1973 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1974}
1975
1976SDValue MipsTargetLowering::
1977lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1978 // check the depth
1979 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1980 "Frame address can only be determined for current frame.");
1981
1982 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1983 MFI->setFrameAddressIsTaken(true);
1984 EVT VT = Op.getValueType();
1985 SDLoc DL(Op);
1986 SDValue FrameAddr =
1987 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1988 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
1989 return FrameAddr;
1990}
1991
1992SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1993 SelectionDAG &DAG) const {
1994 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1995 return SDValue();
1996
1997 // check the depth
1998 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1999 "Return address can be determined only for current frame.");
2000
2001 MachineFunction &MF = DAG.getMachineFunction();
2002 MachineFrameInfo *MFI = MF.getFrameInfo();
2003 MVT VT = Op.getSimpleValueType();
2004 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
2005 MFI->setReturnAddressIsTaken(true);
2006
2007 // Return RA, which contains the return address. Mark it an implicit live-in.
2008 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2009 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2010}
2011
2012// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2013// generated from __builtin_eh_return (offset, handler)
2014// The effect of this is to adjust the stack pointer by "offset"
2015// and then branch to "handler".
2016SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2017 const {
2018 MachineFunction &MF = DAG.getMachineFunction();
2019 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2020
2021 MipsFI->setCallsEhReturn();
2022 SDValue Chain = Op.getOperand(0);
2023 SDValue Offset = Op.getOperand(1);
2024 SDValue Handler = Op.getOperand(2);
2025 SDLoc DL(Op);
2026 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2027
2028 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2029 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2030 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2031 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2032 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2033 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2034 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2035 DAG.getRegister(OffsetReg, Ty),
2036 DAG.getRegister(AddrReg, getPointerTy()),
2037 Chain.getValue(1));
2038}
2039
2040SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2041 SelectionDAG &DAG) const {
2042 // FIXME: Need pseudo-fence for 'singlethread' fences
2043 // FIXME: Set SType for weaker fences where supported/appropriate.
2044 unsigned SType = 0;
2045 SDLoc DL(Op);
2046 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2047 DAG.getConstant(SType, MVT::i32));
2048}
2049
2050SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2051 SelectionDAG &DAG) const {
2052 SDLoc DL(Op);
2053 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2054
2055 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2056 SDValue Shamt = Op.getOperand(2);
2057 // if shamt < (VT.bits):
2058 // lo = (shl lo, shamt)
2059 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2060 // else:
2061 // lo = 0
2062 // hi = (shl lo, shamt[4:0])
2063 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2064 DAG.getConstant(-1, MVT::i32));
2065 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2066 DAG.getConstant(1, VT));
2067 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2068 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2069 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2070 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2071 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2042 DAG.getConstant(0x20, MVT::i32));
2072 DAG.getConstant(VT.getSizeInBits(), MVT::i32));
2043 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2044 DAG.getConstant(0, VT), ShiftLeftLo);
2045 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2046
2047 SDValue Ops[2] = {Lo, Hi};
2048 return DAG.getMergeValues(Ops, DL);
2049}
2050
2051SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2052 bool IsSRA) const {
2053 SDLoc DL(Op);
2054 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2055 SDValue Shamt = Op.getOperand(2);
2056 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2057
2058 // if shamt < (VT.bits):
2059 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2060 // if isSRA:
2061 // hi = (sra hi, shamt)
2062 // else:
2063 // hi = (srl hi, shamt)
2064 // else:
2065 // if isSRA:
2066 // lo = (sra hi, shamt[4:0])
2067 // hi = (sra hi, 31)
2068 // else:
2069 // lo = (srl hi, shamt[4:0])
2070 // hi = 0
2071 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2072 DAG.getConstant(-1, MVT::i32));
2073 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2074 DAG.getConstant(1, VT));
2075 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2076 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2077 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2078 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2079 DL, VT, Hi, Shamt);
2080 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2073 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2074 DAG.getConstant(0, VT), ShiftLeftLo);
2075 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2076
2077 SDValue Ops[2] = {Lo, Hi};
2078 return DAG.getMergeValues(Ops, DL);
2079}
2080
2081SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2082 bool IsSRA) const {
2083 SDLoc DL(Op);
2084 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2085 SDValue Shamt = Op.getOperand(2);
2086 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2087
2088 // if shamt < (VT.bits):
2089 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2090 // if isSRA:
2091 // hi = (sra hi, shamt)
2092 // else:
2093 // hi = (srl hi, shamt)
2094 // else:
2095 // if isSRA:
2096 // lo = (sra hi, shamt[4:0])
2097 // hi = (sra hi, 31)
2098 // else:
2099 // lo = (srl hi, shamt[4:0])
2100 // hi = 0
2101 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2102 DAG.getConstant(-1, MVT::i32));
2103 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2104 DAG.getConstant(1, VT));
2105 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2106 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2107 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2108 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2109 DL, VT, Hi, Shamt);
2110 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2081 DAG.getConstant(0x20, MVT::i32));
2082 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, VT, Hi, DAG.getConstant(31, VT));
2111 DAG.getConstant(VT.getSizeInBits(), MVT::i32));
2112 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2113 DAG.getConstant(VT.getSizeInBits() - 1, VT));
2083 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2084 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2114 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2115 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2085 IsSRA ? Shift31 : DAG.getConstant(0, VT), ShiftRightHi);
2116 IsSRA ? Ext : DAG.getConstant(0, VT), ShiftRightHi);
2086
2087 SDValue Ops[2] = {Lo, Hi};
2088 return DAG.getMergeValues(Ops, DL);
2089}
2090
2091static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2092 SDValue Chain, SDValue Src, unsigned Offset) {
2093 SDValue Ptr = LD->getBasePtr();
2094 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2095 EVT BasePtrVT = Ptr.getValueType();
2096 SDLoc DL(LD);
2097 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2098
2099 if (Offset)
2100 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2101 DAG.getConstant(Offset, BasePtrVT));
2102
2103 SDValue Ops[] = { Chain, Ptr, Src };
2104 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2105 LD->getMemOperand());
2106}
2107
2108// Expand an unaligned 32 or 64-bit integer load node.
2109SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2110 LoadSDNode *LD = cast<LoadSDNode>(Op);
2111 EVT MemVT = LD->getMemoryVT();
2112
2113 if (Subtarget.systemSupportsUnalignedAccess())
2114 return Op;
2115
2116 // Return if load is aligned or if MemVT is neither i32 nor i64.
2117 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2118 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2119 return SDValue();
2120
2121 bool IsLittle = Subtarget.isLittle();
2122 EVT VT = Op.getValueType();
2123 ISD::LoadExtType ExtType = LD->getExtensionType();
2124 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2125
2126 assert((VT == MVT::i32) || (VT == MVT::i64));
2127
2128 // Expand
2129 // (set dst, (i64 (load baseptr)))
2130 // to
2131 // (set tmp, (ldl (add baseptr, 7), undef))
2132 // (set dst, (ldr baseptr, tmp))
2133 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2134 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2135 IsLittle ? 7 : 0);
2136 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2137 IsLittle ? 0 : 7);
2138 }
2139
2140 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2141 IsLittle ? 3 : 0);
2142 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2143 IsLittle ? 0 : 3);
2144
2145 // Expand
2146 // (set dst, (i32 (load baseptr))) or
2147 // (set dst, (i64 (sextload baseptr))) or
2148 // (set dst, (i64 (extload baseptr)))
2149 // to
2150 // (set tmp, (lwl (add baseptr, 3), undef))
2151 // (set dst, (lwr baseptr, tmp))
2152 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2153 (ExtType == ISD::EXTLOAD))
2154 return LWR;
2155
2156 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2157
2158 // Expand
2159 // (set dst, (i64 (zextload baseptr)))
2160 // to
2161 // (set tmp0, (lwl (add baseptr, 3), undef))
2162 // (set tmp1, (lwr baseptr, tmp0))
2163 // (set tmp2, (shl tmp1, 32))
2164 // (set dst, (srl tmp2, 32))
2165 SDLoc DL(LD);
2166 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2167 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2168 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2169 SDValue Ops[] = { SRL, LWR.getValue(1) };
2170 return DAG.getMergeValues(Ops, DL);
2171}
2172
2173static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2174 SDValue Chain, unsigned Offset) {
2175 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2176 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2177 SDLoc DL(SD);
2178 SDVTList VTList = DAG.getVTList(MVT::Other);
2179
2180 if (Offset)
2181 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2182 DAG.getConstant(Offset, BasePtrVT));
2183
2184 SDValue Ops[] = { Chain, Value, Ptr };
2185 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2186 SD->getMemOperand());
2187}
2188
2189// Expand an unaligned 32 or 64-bit integer store node.
2190static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2191 bool IsLittle) {
2192 SDValue Value = SD->getValue(), Chain = SD->getChain();
2193 EVT VT = Value.getValueType();
2194
2195 // Expand
2196 // (store val, baseptr) or
2197 // (truncstore val, baseptr)
2198 // to
2199 // (swl val, (add baseptr, 3))
2200 // (swr val, baseptr)
2201 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2202 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2203 IsLittle ? 3 : 0);
2204 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2205 }
2206
2207 assert(VT == MVT::i64);
2208
2209 // Expand
2210 // (store val, baseptr)
2211 // to
2212 // (sdl val, (add baseptr, 7))
2213 // (sdr val, baseptr)
2214 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2215 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2216}
2217
2218// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2219static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2220 SDValue Val = SD->getValue();
2221
2222 if (Val.getOpcode() != ISD::FP_TO_SINT)
2223 return SDValue();
2224
2225 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2226 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2227 Val.getOperand(0));
2228
2229 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2230 SD->getPointerInfo(), SD->isVolatile(),
2231 SD->isNonTemporal(), SD->getAlignment());
2232}
2233
2234SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2235 StoreSDNode *SD = cast<StoreSDNode>(Op);
2236 EVT MemVT = SD->getMemoryVT();
2237
2238 // Lower unaligned integer stores.
2239 if (!Subtarget.systemSupportsUnalignedAccess() &&
2240 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2241 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2242 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2243
2244 return lowerFP_TO_SINT_STORE(SD, DAG);
2245}
2246
2247SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2248 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2249 || cast<ConstantSDNode>
2250 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2251 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2252 return SDValue();
2253
2254 // The pattern
2255 // (add (frameaddr 0), (frame_to_args_offset))
2256 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2257 // (add FrameObject, 0)
2258 // where FrameObject is a fixed StackObject with offset 0 which points to
2259 // the old stack pointer.
2260 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2261 EVT ValTy = Op->getValueType(0);
2262 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2263 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2264 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2265 DAG.getConstant(0, ValTy));
2266}
2267
2268SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2269 SelectionDAG &DAG) const {
2270 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2271 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2272 Op.getOperand(0));
2273 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2274}
2275
2276//===----------------------------------------------------------------------===//
2277// Calling Convention Implementation
2278//===----------------------------------------------------------------------===//
2279
2280//===----------------------------------------------------------------------===//
2281// TODO: Implement a generic logic using tblgen that can support this.
2282// Mips O32 ABI rules:
2283// ---
2284// i32 - Passed in A0, A1, A2, A3 and stack
2285// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2286// an argument. Otherwise, passed in A1, A2, A3 and stack.
2287// f64 - Only passed in two aliased f32 registers if no int reg has been used
2288// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2289// not used, it must be shadowed. If only A3 is available, shadow it and
2290// go to stack.
2291//
2292// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2293//===----------------------------------------------------------------------===//
2294
2295static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2296 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2297 CCState &State, const MCPhysReg *F64Regs) {
2298 const MipsSubtarget &Subtarget =
2299 State.getMachineFunction().getTarget()
2300 .getSubtarget<const MipsSubtarget>();
2301
2302 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2303
2304 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2305 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2306
2307 // Do not process byval args here.
2308 if (ArgFlags.isByVal())
2309 return true;
2310
2311 // Promote i8 and i16
2312 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2313 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2314 LocVT = MVT::i32;
2315 if (ArgFlags.isSExt())
2316 LocInfo = CCValAssign::SExtUpper;
2317 else if (ArgFlags.isZExt())
2318 LocInfo = CCValAssign::ZExtUpper;
2319 else
2320 LocInfo = CCValAssign::AExtUpper;
2321 }
2322 }
2323
2324 // Promote i8 and i16
2325 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2326 LocVT = MVT::i32;
2327 if (ArgFlags.isSExt())
2328 LocInfo = CCValAssign::SExt;
2329 else if (ArgFlags.isZExt())
2330 LocInfo = CCValAssign::ZExt;
2331 else
2332 LocInfo = CCValAssign::AExt;
2333 }
2334
2335 unsigned Reg;
2336
2337 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2338 // is true: function is vararg, argument is 3rd or higher, there is previous
2339 // argument which is not f32 or f64.
2340 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2341 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2342 unsigned OrigAlign = ArgFlags.getOrigAlign();
2343 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2344
2345 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2346 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2347 // If this is the first part of an i64 arg,
2348 // the allocated register must be either A0 or A2.
2349 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2350 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2351 LocVT = MVT::i32;
2352 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2353 // Allocate int register and shadow next int register. If first
2354 // available register is Mips::A1 or Mips::A3, shadow it too.
2355 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2356 if (Reg == Mips::A1 || Reg == Mips::A3)
2357 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2358 State.AllocateReg(IntRegs, IntRegsSize);
2359 LocVT = MVT::i32;
2360 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2361 // we are guaranteed to find an available float register
2362 if (ValVT == MVT::f32) {
2363 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2364 // Shadow int register
2365 State.AllocateReg(IntRegs, IntRegsSize);
2366 } else {
2367 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2368 // Shadow int registers
2369 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2370 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2371 State.AllocateReg(IntRegs, IntRegsSize);
2372 State.AllocateReg(IntRegs, IntRegsSize);
2373 }
2374 } else
2375 llvm_unreachable("Cannot handle this ValVT.");
2376
2377 if (!Reg) {
2378 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2379 OrigAlign);
2380 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2381 } else
2382 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2383
2384 return false;
2385}
2386
2387static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2388 MVT LocVT, CCValAssign::LocInfo LocInfo,
2389 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2390 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2391
2392 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2393}
2394
2395static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2396 MVT LocVT, CCValAssign::LocInfo LocInfo,
2397 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2398 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2399
2400 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2401}
2402
2403static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2404 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2405 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2406
2407#include "MipsGenCallingConv.inc"
2408
2409//===----------------------------------------------------------------------===//
2410// Call Calling Convention Implementation
2411//===----------------------------------------------------------------------===//
2412
2413// Return next O32 integer argument register.
2414static unsigned getNextIntArgReg(unsigned Reg) {
2415 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2416 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2417}
2418
2419SDValue
2420MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2421 SDValue Chain, SDValue Arg, SDLoc DL,
2422 bool IsTailCall, SelectionDAG &DAG) const {
2423 if (!IsTailCall) {
2424 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2425 DAG.getIntPtrConstant(Offset));
2426 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2427 false, 0);
2428 }
2429
2430 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2431 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2432 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2433 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2434 /*isVolatile=*/ true, false, 0);
2435}
2436
2437void MipsTargetLowering::
2438getOpndList(SmallVectorImpl<SDValue> &Ops,
2439 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2440 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2441 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2442 SDValue Chain) const {
2443 // Insert node "GP copy globalreg" before call to function.
2444 //
2445 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2446 // in PIC mode) allow symbols to be resolved via lazy binding.
2447 // The lazy binding stub requires GP to point to the GOT.
2448 // Note that we don't need GP to point to the GOT for indirect calls
2449 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2450 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2451 // used for the function (that is, Mips linker doesn't generate lazy binding
2452 // stub for a function whose address is taken in the program).
2453 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2454 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2455 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2456 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2457 }
2458
2459 // Build a sequence of copy-to-reg nodes chained together with token
2460 // chain and flag operands which copy the outgoing args into registers.
2461 // The InFlag in necessary since all emitted instructions must be
2462 // stuck together.
2463 SDValue InFlag;
2464
2465 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2466 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2467 RegsToPass[i].second, InFlag);
2468 InFlag = Chain.getValue(1);
2469 }
2470
2471 // Add argument registers to the end of the list so that they are
2472 // known live into the call.
2473 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2474 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2475 RegsToPass[i].second.getValueType()));
2476
2477 // Add a register mask operand representing the call-preserved registers.
2478 const TargetRegisterInfo *TRI =
2479 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2480 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2481 assert(Mask && "Missing call preserved mask for calling convention");
2482 if (Subtarget.inMips16HardFloat()) {
2483 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2484 llvm::StringRef Sym = G->getGlobal()->getName();
2485 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2486 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2487 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2488 }
2489 }
2490 }
2491 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2492
2493 if (InFlag.getNode())
2494 Ops.push_back(InFlag);
2495}
2496
2497/// LowerCall - functions arguments are copied from virtual regs to
2498/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2499SDValue
2500MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2501 SmallVectorImpl<SDValue> &InVals) const {
2502 SelectionDAG &DAG = CLI.DAG;
2503 SDLoc DL = CLI.DL;
2504 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2505 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2506 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2507 SDValue Chain = CLI.Chain;
2508 SDValue Callee = CLI.Callee;
2509 bool &IsTailCall = CLI.IsTailCall;
2510 CallingConv::ID CallConv = CLI.CallConv;
2511 bool IsVarArg = CLI.IsVarArg;
2512
2513 MachineFunction &MF = DAG.getMachineFunction();
2514 MachineFrameInfo *MFI = MF.getFrameInfo();
2515 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2516 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2517 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2518
2519 // Analyze operands of the call, assigning locations to each operand.
2520 SmallVector<CCValAssign, 16> ArgLocs;
2521 MipsCCState CCInfo(
2522 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2523 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2524
2525 // Allocate the reserved argument area. It seems strange to do this from the
2526 // caller side but removing it breaks the frame size calculation.
2527 const MipsABIInfo &ABI = Subtarget.getABI();
2528 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2529
2530 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2531
2532 // Get a count of how many bytes are to be pushed on the stack.
2533 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2534
2535 // Check if it's really possible to do a tail call.
2536 if (IsTailCall)
2537 IsTailCall = isEligibleForTailCallOptimization(
2538 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2539
2540 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2541 report_fatal_error("failed to perform tail call elimination on a call "
2542 "site marked musttail");
2543
2544 if (IsTailCall)
2545 ++NumTailCalls;
2546
2547 // Chain is the output chain of the last Load/Store or CopyToReg node.
2548 // ByValChain is the output chain of the last Memcpy node created for copying
2549 // byval arguments to the stack.
2550 unsigned StackAlignment = TFL->getStackAlignment();
2551 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2552 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2553
2554 if (!IsTailCall)
2555 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2556
2557 SDValue StackPtr = DAG.getCopyFromReg(
2558 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2559 getPointerTy());
2560
2561 // With EABI is it possible to have 16 args on registers.
2562 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2563 SmallVector<SDValue, 8> MemOpChains;
2564
2565 CCInfo.rewindByValRegsInfo();
2566
2567 // Walk the register/memloc assignments, inserting copies/loads.
2568 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2569 SDValue Arg = OutVals[i];
2570 CCValAssign &VA = ArgLocs[i];
2571 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2572 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2573 bool UseUpperBits = false;
2574
2575 // ByVal Arg.
2576 if (Flags.isByVal()) {
2577 unsigned FirstByValReg, LastByValReg;
2578 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2579 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2580
2581 assert(Flags.getByValSize() &&
2582 "ByVal args of size 0 should have been ignored by front-end.");
2583 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2584 assert(!IsTailCall &&
2585 "Do not tail-call optimize if there is a byval argument.");
2586 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2587 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2588 VA);
2589 CCInfo.nextInRegsParam();
2590 continue;
2591 }
2592
2593 // Promote the value if needed.
2594 switch (VA.getLocInfo()) {
2595 default:
2596 llvm_unreachable("Unknown loc info!");
2597 case CCValAssign::Full:
2598 if (VA.isRegLoc()) {
2599 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2600 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2601 (ValVT == MVT::i64 && LocVT == MVT::f64))
2602 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2603 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2604 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2605 Arg, DAG.getConstant(0, MVT::i32));
2606 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2607 Arg, DAG.getConstant(1, MVT::i32));
2608 if (!Subtarget.isLittle())
2609 std::swap(Lo, Hi);
2610 unsigned LocRegLo = VA.getLocReg();
2611 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2612 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2613 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2614 continue;
2615 }
2616 }
2617 break;
2618 case CCValAssign::BCvt:
2619 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2620 break;
2621 case CCValAssign::SExtUpper:
2622 UseUpperBits = true;
2623 // Fallthrough
2624 case CCValAssign::SExt:
2625 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2626 break;
2627 case CCValAssign::ZExtUpper:
2628 UseUpperBits = true;
2629 // Fallthrough
2630 case CCValAssign::ZExt:
2631 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2632 break;
2633 case CCValAssign::AExtUpper:
2634 UseUpperBits = true;
2635 // Fallthrough
2636 case CCValAssign::AExt:
2637 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2638 break;
2639 }
2640
2641 if (UseUpperBits) {
2642 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2643 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2644 Arg = DAG.getNode(
2645 ISD::SHL, DL, VA.getLocVT(), Arg,
2646 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2647 }
2648
2649 // Arguments that can be passed on register must be kept at
2650 // RegsToPass vector
2651 if (VA.isRegLoc()) {
2652 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2653 continue;
2654 }
2655
2656 // Register can't get to this point...
2657 assert(VA.isMemLoc());
2658
2659 // emit ISD::STORE whichs stores the
2660 // parameter value to a stack Location
2661 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2662 Chain, Arg, DL, IsTailCall, DAG));
2663 }
2664
2665 // Transform all store nodes into one single node because all store
2666 // nodes are independent of each other.
2667 if (!MemOpChains.empty())
2668 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2669
2670 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2671 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2672 // node so that legalize doesn't hack it.
2673 bool IsPICCall =
2674 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2675 // jalr $25
2676 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2677 SDValue CalleeLo;
2678 EVT Ty = Callee.getValueType();
2679
2680 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2681 if (IsPICCall) {
2682 const GlobalValue *Val = G->getGlobal();
2683 InternalLinkage = Val->hasInternalLinkage();
2684
2685 if (InternalLinkage)
2686 Callee = getAddrLocal(G, DL, Ty, DAG,
2687 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2688 else if (LargeGOT) {
2689 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2690 MipsII::MO_CALL_LO16, Chain,
2691 FuncInfo->callPtrInfo(Val));
2692 IsCallReloc = true;
2693 } else {
2694 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2695 FuncInfo->callPtrInfo(Val));
2696 IsCallReloc = true;
2697 }
2698 } else
2699 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2700 MipsII::MO_NO_FLAG);
2701 GlobalOrExternal = true;
2702 }
2703 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2704 const char *Sym = S->getSymbol();
2705
2706 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2707 Callee =
2708 DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2709 else if (LargeGOT) {
2710 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2711 MipsII::MO_CALL_LO16, Chain,
2712 FuncInfo->callPtrInfo(Sym));
2713 IsCallReloc = true;
2714 } else { // N64 || PIC
2715 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2716 FuncInfo->callPtrInfo(Sym));
2717 IsCallReloc = true;
2718 }
2719
2720 GlobalOrExternal = true;
2721 }
2722
2723 SmallVector<SDValue, 8> Ops(1, Chain);
2724 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2725
2726 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2727 IsCallReloc, CLI, Callee, Chain);
2728
2729 if (IsTailCall)
2730 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2731
2732 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2733 SDValue InFlag = Chain.getValue(1);
2734
2735 // Create the CALLSEQ_END node.
2736 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2737 DAG.getIntPtrConstant(0, true), InFlag, DL);
2738 InFlag = Chain.getValue(1);
2739
2740 // Handle result values, copying them out of physregs into vregs that we
2741 // return.
2742 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2743 InVals, CLI);
2744}
2745
2746/// LowerCallResult - Lower the result values of a call into the
2747/// appropriate copies out of appropriate physical registers.
2748SDValue MipsTargetLowering::LowerCallResult(
2749 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2750 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2751 SmallVectorImpl<SDValue> &InVals,
2752 TargetLowering::CallLoweringInfo &CLI) const {
2753 // Assign locations to each value returned by this call.
2754 SmallVector<CCValAssign, 16> RVLocs;
2755 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2756 *DAG.getContext());
2757 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2758
2759 // Copy all of the result registers out of their specified physreg.
2760 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761 CCValAssign &VA = RVLocs[i];
2762 assert(VA.isRegLoc() && "Can only return in registers!");
2763
2764 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2765 RVLocs[i].getLocVT(), InFlag);
2766 Chain = Val.getValue(1);
2767 InFlag = Val.getValue(2);
2768
2769 if (VA.isUpperBitsInLoc()) {
2770 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2771 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2772 unsigned Shift =
2773 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2774 Val = DAG.getNode(
2775 Shift, DL, VA.getLocVT(), Val,
2776 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2777 }
2778
2779 switch (VA.getLocInfo()) {
2780 default:
2781 llvm_unreachable("Unknown loc info!");
2782 case CCValAssign::Full:
2783 break;
2784 case CCValAssign::BCvt:
2785 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2786 break;
2787 case CCValAssign::AExt:
2788 case CCValAssign::AExtUpper:
2789 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2790 break;
2791 case CCValAssign::ZExt:
2792 case CCValAssign::ZExtUpper:
2793 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2794 DAG.getValueType(VA.getValVT()));
2795 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2796 break;
2797 case CCValAssign::SExt:
2798 case CCValAssign::SExtUpper:
2799 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2800 DAG.getValueType(VA.getValVT()));
2801 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2802 break;
2803 }
2804
2805 InVals.push_back(Val);
2806 }
2807
2808 return Chain;
2809}
2810
2811static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2812 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2813 MVT LocVT = VA.getLocVT();
2814 EVT ValVT = VA.getValVT();
2815
2816 // Shift into the upper bits if necessary.
2817 switch (VA.getLocInfo()) {
2818 default:
2819 break;
2820 case CCValAssign::AExtUpper:
2821 case CCValAssign::SExtUpper:
2822 case CCValAssign::ZExtUpper: {
2823 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2824 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2825 unsigned Opcode =
2826 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2827 Val = DAG.getNode(
2828 Opcode, DL, VA.getLocVT(), Val,
2829 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2830 break;
2831 }
2832 }
2833
2834 // If this is an value smaller than the argument slot size (32-bit for O32,
2835 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2836 // size. Extract the value and insert any appropriate assertions regarding
2837 // sign/zero extension.
2838 switch (VA.getLocInfo()) {
2839 default:
2840 llvm_unreachable("Unknown loc info!");
2841 case CCValAssign::Full:
2842 break;
2843 case CCValAssign::AExtUpper:
2844 case CCValAssign::AExt:
2845 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2846 break;
2847 case CCValAssign::SExtUpper:
2848 case CCValAssign::SExt:
2849 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2850 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2851 break;
2852 case CCValAssign::ZExtUpper:
2853 case CCValAssign::ZExt:
2854 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2855 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2856 break;
2857 case CCValAssign::BCvt:
2858 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2859 break;
2860 }
2861
2862 return Val;
2863}
2864
2865//===----------------------------------------------------------------------===//
2866// Formal Arguments Calling Convention Implementation
2867//===----------------------------------------------------------------------===//
2868/// LowerFormalArguments - transform physical registers into virtual registers
2869/// and generate load operations for arguments places on the stack.
2870SDValue
2871MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2872 CallingConv::ID CallConv,
2873 bool IsVarArg,
2874 const SmallVectorImpl<ISD::InputArg> &Ins,
2875 SDLoc DL, SelectionDAG &DAG,
2876 SmallVectorImpl<SDValue> &InVals)
2877 const {
2878 MachineFunction &MF = DAG.getMachineFunction();
2879 MachineFrameInfo *MFI = MF.getFrameInfo();
2880 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2881
2882 MipsFI->setVarArgsFrameIndex(0);
2883
2884 // Used with vargs to acumulate store chains.
2885 std::vector<SDValue> OutChains;
2886
2887 // Assign locations to all of the incoming arguments.
2888 SmallVector<CCValAssign, 16> ArgLocs;
2889 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2890 *DAG.getContext());
2891 const MipsABIInfo &ABI = Subtarget.getABI();
2892 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2893 Function::const_arg_iterator FuncArg =
2894 DAG.getMachineFunction().getFunction()->arg_begin();
2895
2896 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2897 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2898 CCInfo.getInRegsParamsCount() > 0);
2899
2900 unsigned CurArgIdx = 0;
2901 CCInfo.rewindByValRegsInfo();
2902
2903 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2904 CCValAssign &VA = ArgLocs[i];
2117
2118 SDValue Ops[2] = {Lo, Hi};
2119 return DAG.getMergeValues(Ops, DL);
2120}
2121
2122static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2123 SDValue Chain, SDValue Src, unsigned Offset) {
2124 SDValue Ptr = LD->getBasePtr();
2125 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2126 EVT BasePtrVT = Ptr.getValueType();
2127 SDLoc DL(LD);
2128 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2129
2130 if (Offset)
2131 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2132 DAG.getConstant(Offset, BasePtrVT));
2133
2134 SDValue Ops[] = { Chain, Ptr, Src };
2135 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2136 LD->getMemOperand());
2137}
2138
2139// Expand an unaligned 32 or 64-bit integer load node.
2140SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2141 LoadSDNode *LD = cast<LoadSDNode>(Op);
2142 EVT MemVT = LD->getMemoryVT();
2143
2144 if (Subtarget.systemSupportsUnalignedAccess())
2145 return Op;
2146
2147 // Return if load is aligned or if MemVT is neither i32 nor i64.
2148 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2149 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2150 return SDValue();
2151
2152 bool IsLittle = Subtarget.isLittle();
2153 EVT VT = Op.getValueType();
2154 ISD::LoadExtType ExtType = LD->getExtensionType();
2155 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2156
2157 assert((VT == MVT::i32) || (VT == MVT::i64));
2158
2159 // Expand
2160 // (set dst, (i64 (load baseptr)))
2161 // to
2162 // (set tmp, (ldl (add baseptr, 7), undef))
2163 // (set dst, (ldr baseptr, tmp))
2164 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2165 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2166 IsLittle ? 7 : 0);
2167 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2168 IsLittle ? 0 : 7);
2169 }
2170
2171 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2172 IsLittle ? 3 : 0);
2173 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2174 IsLittle ? 0 : 3);
2175
2176 // Expand
2177 // (set dst, (i32 (load baseptr))) or
2178 // (set dst, (i64 (sextload baseptr))) or
2179 // (set dst, (i64 (extload baseptr)))
2180 // to
2181 // (set tmp, (lwl (add baseptr, 3), undef))
2182 // (set dst, (lwr baseptr, tmp))
2183 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2184 (ExtType == ISD::EXTLOAD))
2185 return LWR;
2186
2187 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2188
2189 // Expand
2190 // (set dst, (i64 (zextload baseptr)))
2191 // to
2192 // (set tmp0, (lwl (add baseptr, 3), undef))
2193 // (set tmp1, (lwr baseptr, tmp0))
2194 // (set tmp2, (shl tmp1, 32))
2195 // (set dst, (srl tmp2, 32))
2196 SDLoc DL(LD);
2197 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2198 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2199 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2200 SDValue Ops[] = { SRL, LWR.getValue(1) };
2201 return DAG.getMergeValues(Ops, DL);
2202}
2203
2204static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2205 SDValue Chain, unsigned Offset) {
2206 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2207 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2208 SDLoc DL(SD);
2209 SDVTList VTList = DAG.getVTList(MVT::Other);
2210
2211 if (Offset)
2212 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2213 DAG.getConstant(Offset, BasePtrVT));
2214
2215 SDValue Ops[] = { Chain, Value, Ptr };
2216 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2217 SD->getMemOperand());
2218}
2219
2220// Expand an unaligned 32 or 64-bit integer store node.
2221static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2222 bool IsLittle) {
2223 SDValue Value = SD->getValue(), Chain = SD->getChain();
2224 EVT VT = Value.getValueType();
2225
2226 // Expand
2227 // (store val, baseptr) or
2228 // (truncstore val, baseptr)
2229 // to
2230 // (swl val, (add baseptr, 3))
2231 // (swr val, baseptr)
2232 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2233 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2234 IsLittle ? 3 : 0);
2235 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2236 }
2237
2238 assert(VT == MVT::i64);
2239
2240 // Expand
2241 // (store val, baseptr)
2242 // to
2243 // (sdl val, (add baseptr, 7))
2244 // (sdr val, baseptr)
2245 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2246 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2247}
2248
2249// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2250static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2251 SDValue Val = SD->getValue();
2252
2253 if (Val.getOpcode() != ISD::FP_TO_SINT)
2254 return SDValue();
2255
2256 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2257 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2258 Val.getOperand(0));
2259
2260 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2261 SD->getPointerInfo(), SD->isVolatile(),
2262 SD->isNonTemporal(), SD->getAlignment());
2263}
2264
2265SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2266 StoreSDNode *SD = cast<StoreSDNode>(Op);
2267 EVT MemVT = SD->getMemoryVT();
2268
2269 // Lower unaligned integer stores.
2270 if (!Subtarget.systemSupportsUnalignedAccess() &&
2271 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2272 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2273 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2274
2275 return lowerFP_TO_SINT_STORE(SD, DAG);
2276}
2277
2278SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2279 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2280 || cast<ConstantSDNode>
2281 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2282 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2283 return SDValue();
2284
2285 // The pattern
2286 // (add (frameaddr 0), (frame_to_args_offset))
2287 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2288 // (add FrameObject, 0)
2289 // where FrameObject is a fixed StackObject with offset 0 which points to
2290 // the old stack pointer.
2291 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2292 EVT ValTy = Op->getValueType(0);
2293 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2294 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2295 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2296 DAG.getConstant(0, ValTy));
2297}
2298
2299SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2300 SelectionDAG &DAG) const {
2301 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2302 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2303 Op.getOperand(0));
2304 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2305}
2306
2307//===----------------------------------------------------------------------===//
2308// Calling Convention Implementation
2309//===----------------------------------------------------------------------===//
2310
2311//===----------------------------------------------------------------------===//
2312// TODO: Implement a generic logic using tblgen that can support this.
2313// Mips O32 ABI rules:
2314// ---
2315// i32 - Passed in A0, A1, A2, A3 and stack
2316// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2317// an argument. Otherwise, passed in A1, A2, A3 and stack.
2318// f64 - Only passed in two aliased f32 registers if no int reg has been used
2319// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2320// not used, it must be shadowed. If only A3 is available, shadow it and
2321// go to stack.
2322//
2323// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2324//===----------------------------------------------------------------------===//
2325
2326static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2327 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2328 CCState &State, const MCPhysReg *F64Regs) {
2329 const MipsSubtarget &Subtarget =
2330 State.getMachineFunction().getTarget()
2331 .getSubtarget<const MipsSubtarget>();
2332
2333 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2334
2335 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2336 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2337
2338 // Do not process byval args here.
2339 if (ArgFlags.isByVal())
2340 return true;
2341
2342 // Promote i8 and i16
2343 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2344 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2345 LocVT = MVT::i32;
2346 if (ArgFlags.isSExt())
2347 LocInfo = CCValAssign::SExtUpper;
2348 else if (ArgFlags.isZExt())
2349 LocInfo = CCValAssign::ZExtUpper;
2350 else
2351 LocInfo = CCValAssign::AExtUpper;
2352 }
2353 }
2354
2355 // Promote i8 and i16
2356 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2357 LocVT = MVT::i32;
2358 if (ArgFlags.isSExt())
2359 LocInfo = CCValAssign::SExt;
2360 else if (ArgFlags.isZExt())
2361 LocInfo = CCValAssign::ZExt;
2362 else
2363 LocInfo = CCValAssign::AExt;
2364 }
2365
2366 unsigned Reg;
2367
2368 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2369 // is true: function is vararg, argument is 3rd or higher, there is previous
2370 // argument which is not f32 or f64.
2371 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2372 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2373 unsigned OrigAlign = ArgFlags.getOrigAlign();
2374 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2375
2376 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2377 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2378 // If this is the first part of an i64 arg,
2379 // the allocated register must be either A0 or A2.
2380 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2381 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2382 LocVT = MVT::i32;
2383 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2384 // Allocate int register and shadow next int register. If first
2385 // available register is Mips::A1 or Mips::A3, shadow it too.
2386 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2387 if (Reg == Mips::A1 || Reg == Mips::A3)
2388 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2389 State.AllocateReg(IntRegs, IntRegsSize);
2390 LocVT = MVT::i32;
2391 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2392 // we are guaranteed to find an available float register
2393 if (ValVT == MVT::f32) {
2394 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2395 // Shadow int register
2396 State.AllocateReg(IntRegs, IntRegsSize);
2397 } else {
2398 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2399 // Shadow int registers
2400 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2401 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2402 State.AllocateReg(IntRegs, IntRegsSize);
2403 State.AllocateReg(IntRegs, IntRegsSize);
2404 }
2405 } else
2406 llvm_unreachable("Cannot handle this ValVT.");
2407
2408 if (!Reg) {
2409 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2410 OrigAlign);
2411 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2412 } else
2413 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2414
2415 return false;
2416}
2417
2418static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2419 MVT LocVT, CCValAssign::LocInfo LocInfo,
2420 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2421 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2422
2423 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2424}
2425
2426static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2427 MVT LocVT, CCValAssign::LocInfo LocInfo,
2428 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2429 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2430
2431 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2432}
2433
2434static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2435 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2436 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2437
2438#include "MipsGenCallingConv.inc"
2439
2440//===----------------------------------------------------------------------===//
2441// Call Calling Convention Implementation
2442//===----------------------------------------------------------------------===//
2443
2444// Return next O32 integer argument register.
2445static unsigned getNextIntArgReg(unsigned Reg) {
2446 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2447 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2448}
2449
2450SDValue
2451MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2452 SDValue Chain, SDValue Arg, SDLoc DL,
2453 bool IsTailCall, SelectionDAG &DAG) const {
2454 if (!IsTailCall) {
2455 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2456 DAG.getIntPtrConstant(Offset));
2457 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2458 false, 0);
2459 }
2460
2461 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2462 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2463 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2464 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2465 /*isVolatile=*/ true, false, 0);
2466}
2467
2468void MipsTargetLowering::
2469getOpndList(SmallVectorImpl<SDValue> &Ops,
2470 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2471 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2472 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2473 SDValue Chain) const {
2474 // Insert node "GP copy globalreg" before call to function.
2475 //
2476 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2477 // in PIC mode) allow symbols to be resolved via lazy binding.
2478 // The lazy binding stub requires GP to point to the GOT.
2479 // Note that we don't need GP to point to the GOT for indirect calls
2480 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2481 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2482 // used for the function (that is, Mips linker doesn't generate lazy binding
2483 // stub for a function whose address is taken in the program).
2484 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2485 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2486 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2487 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2488 }
2489
2490 // Build a sequence of copy-to-reg nodes chained together with token
2491 // chain and flag operands which copy the outgoing args into registers.
2492 // The InFlag in necessary since all emitted instructions must be
2493 // stuck together.
2494 SDValue InFlag;
2495
2496 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2497 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2498 RegsToPass[i].second, InFlag);
2499 InFlag = Chain.getValue(1);
2500 }
2501
2502 // Add argument registers to the end of the list so that they are
2503 // known live into the call.
2504 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2505 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2506 RegsToPass[i].second.getValueType()));
2507
2508 // Add a register mask operand representing the call-preserved registers.
2509 const TargetRegisterInfo *TRI =
2510 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2511 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2512 assert(Mask && "Missing call preserved mask for calling convention");
2513 if (Subtarget.inMips16HardFloat()) {
2514 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2515 llvm::StringRef Sym = G->getGlobal()->getName();
2516 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2517 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2518 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2519 }
2520 }
2521 }
2522 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2523
2524 if (InFlag.getNode())
2525 Ops.push_back(InFlag);
2526}
2527
2528/// LowerCall - functions arguments are copied from virtual regs to
2529/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2530SDValue
2531MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2532 SmallVectorImpl<SDValue> &InVals) const {
2533 SelectionDAG &DAG = CLI.DAG;
2534 SDLoc DL = CLI.DL;
2535 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2536 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2537 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2538 SDValue Chain = CLI.Chain;
2539 SDValue Callee = CLI.Callee;
2540 bool &IsTailCall = CLI.IsTailCall;
2541 CallingConv::ID CallConv = CLI.CallConv;
2542 bool IsVarArg = CLI.IsVarArg;
2543
2544 MachineFunction &MF = DAG.getMachineFunction();
2545 MachineFrameInfo *MFI = MF.getFrameInfo();
2546 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2547 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2548 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2549
2550 // Analyze operands of the call, assigning locations to each operand.
2551 SmallVector<CCValAssign, 16> ArgLocs;
2552 MipsCCState CCInfo(
2553 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2554 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2555
2556 // Allocate the reserved argument area. It seems strange to do this from the
2557 // caller side but removing it breaks the frame size calculation.
2558 const MipsABIInfo &ABI = Subtarget.getABI();
2559 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2560
2561 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2562
2563 // Get a count of how many bytes are to be pushed on the stack.
2564 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2565
2566 // Check if it's really possible to do a tail call.
2567 if (IsTailCall)
2568 IsTailCall = isEligibleForTailCallOptimization(
2569 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2570
2571 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2572 report_fatal_error("failed to perform tail call elimination on a call "
2573 "site marked musttail");
2574
2575 if (IsTailCall)
2576 ++NumTailCalls;
2577
2578 // Chain is the output chain of the last Load/Store or CopyToReg node.
2579 // ByValChain is the output chain of the last Memcpy node created for copying
2580 // byval arguments to the stack.
2581 unsigned StackAlignment = TFL->getStackAlignment();
2582 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2583 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2584
2585 if (!IsTailCall)
2586 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2587
2588 SDValue StackPtr = DAG.getCopyFromReg(
2589 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2590 getPointerTy());
2591
2592 // With EABI is it possible to have 16 args on registers.
2593 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2594 SmallVector<SDValue, 8> MemOpChains;
2595
2596 CCInfo.rewindByValRegsInfo();
2597
2598 // Walk the register/memloc assignments, inserting copies/loads.
2599 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2600 SDValue Arg = OutVals[i];
2601 CCValAssign &VA = ArgLocs[i];
2602 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2603 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2604 bool UseUpperBits = false;
2605
2606 // ByVal Arg.
2607 if (Flags.isByVal()) {
2608 unsigned FirstByValReg, LastByValReg;
2609 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2610 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2611
2612 assert(Flags.getByValSize() &&
2613 "ByVal args of size 0 should have been ignored by front-end.");
2614 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2615 assert(!IsTailCall &&
2616 "Do not tail-call optimize if there is a byval argument.");
2617 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2618 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2619 VA);
2620 CCInfo.nextInRegsParam();
2621 continue;
2622 }
2623
2624 // Promote the value if needed.
2625 switch (VA.getLocInfo()) {
2626 default:
2627 llvm_unreachable("Unknown loc info!");
2628 case CCValAssign::Full:
2629 if (VA.isRegLoc()) {
2630 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2631 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2632 (ValVT == MVT::i64 && LocVT == MVT::f64))
2633 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2634 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2635 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2636 Arg, DAG.getConstant(0, MVT::i32));
2637 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2638 Arg, DAG.getConstant(1, MVT::i32));
2639 if (!Subtarget.isLittle())
2640 std::swap(Lo, Hi);
2641 unsigned LocRegLo = VA.getLocReg();
2642 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2643 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2644 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2645 continue;
2646 }
2647 }
2648 break;
2649 case CCValAssign::BCvt:
2650 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2651 break;
2652 case CCValAssign::SExtUpper:
2653 UseUpperBits = true;
2654 // Fallthrough
2655 case CCValAssign::SExt:
2656 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2657 break;
2658 case CCValAssign::ZExtUpper:
2659 UseUpperBits = true;
2660 // Fallthrough
2661 case CCValAssign::ZExt:
2662 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2663 break;
2664 case CCValAssign::AExtUpper:
2665 UseUpperBits = true;
2666 // Fallthrough
2667 case CCValAssign::AExt:
2668 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2669 break;
2670 }
2671
2672 if (UseUpperBits) {
2673 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2674 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2675 Arg = DAG.getNode(
2676 ISD::SHL, DL, VA.getLocVT(), Arg,
2677 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2678 }
2679
2680 // Arguments that can be passed on register must be kept at
2681 // RegsToPass vector
2682 if (VA.isRegLoc()) {
2683 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2684 continue;
2685 }
2686
2687 // Register can't get to this point...
2688 assert(VA.isMemLoc());
2689
2690 // emit ISD::STORE whichs stores the
2691 // parameter value to a stack Location
2692 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2693 Chain, Arg, DL, IsTailCall, DAG));
2694 }
2695
2696 // Transform all store nodes into one single node because all store
2697 // nodes are independent of each other.
2698 if (!MemOpChains.empty())
2699 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2700
2701 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2702 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2703 // node so that legalize doesn't hack it.
2704 bool IsPICCall =
2705 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2706 // jalr $25
2707 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2708 SDValue CalleeLo;
2709 EVT Ty = Callee.getValueType();
2710
2711 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2712 if (IsPICCall) {
2713 const GlobalValue *Val = G->getGlobal();
2714 InternalLinkage = Val->hasInternalLinkage();
2715
2716 if (InternalLinkage)
2717 Callee = getAddrLocal(G, DL, Ty, DAG,
2718 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2719 else if (LargeGOT) {
2720 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2721 MipsII::MO_CALL_LO16, Chain,
2722 FuncInfo->callPtrInfo(Val));
2723 IsCallReloc = true;
2724 } else {
2725 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2726 FuncInfo->callPtrInfo(Val));
2727 IsCallReloc = true;
2728 }
2729 } else
2730 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2731 MipsII::MO_NO_FLAG);
2732 GlobalOrExternal = true;
2733 }
2734 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2735 const char *Sym = S->getSymbol();
2736
2737 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2738 Callee =
2739 DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2740 else if (LargeGOT) {
2741 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2742 MipsII::MO_CALL_LO16, Chain,
2743 FuncInfo->callPtrInfo(Sym));
2744 IsCallReloc = true;
2745 } else { // N64 || PIC
2746 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2747 FuncInfo->callPtrInfo(Sym));
2748 IsCallReloc = true;
2749 }
2750
2751 GlobalOrExternal = true;
2752 }
2753
2754 SmallVector<SDValue, 8> Ops(1, Chain);
2755 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2756
2757 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2758 IsCallReloc, CLI, Callee, Chain);
2759
2760 if (IsTailCall)
2761 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2762
2763 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2764 SDValue InFlag = Chain.getValue(1);
2765
2766 // Create the CALLSEQ_END node.
2767 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2768 DAG.getIntPtrConstant(0, true), InFlag, DL);
2769 InFlag = Chain.getValue(1);
2770
2771 // Handle result values, copying them out of physregs into vregs that we
2772 // return.
2773 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2774 InVals, CLI);
2775}
2776
2777/// LowerCallResult - Lower the result values of a call into the
2778/// appropriate copies out of appropriate physical registers.
2779SDValue MipsTargetLowering::LowerCallResult(
2780 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2781 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2782 SmallVectorImpl<SDValue> &InVals,
2783 TargetLowering::CallLoweringInfo &CLI) const {
2784 // Assign locations to each value returned by this call.
2785 SmallVector<CCValAssign, 16> RVLocs;
2786 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2787 *DAG.getContext());
2788 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2789
2790 // Copy all of the result registers out of their specified physreg.
2791 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2792 CCValAssign &VA = RVLocs[i];
2793 assert(VA.isRegLoc() && "Can only return in registers!");
2794
2795 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2796 RVLocs[i].getLocVT(), InFlag);
2797 Chain = Val.getValue(1);
2798 InFlag = Val.getValue(2);
2799
2800 if (VA.isUpperBitsInLoc()) {
2801 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2802 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2803 unsigned Shift =
2804 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2805 Val = DAG.getNode(
2806 Shift, DL, VA.getLocVT(), Val,
2807 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2808 }
2809
2810 switch (VA.getLocInfo()) {
2811 default:
2812 llvm_unreachable("Unknown loc info!");
2813 case CCValAssign::Full:
2814 break;
2815 case CCValAssign::BCvt:
2816 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2817 break;
2818 case CCValAssign::AExt:
2819 case CCValAssign::AExtUpper:
2820 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2821 break;
2822 case CCValAssign::ZExt:
2823 case CCValAssign::ZExtUpper:
2824 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2825 DAG.getValueType(VA.getValVT()));
2826 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2827 break;
2828 case CCValAssign::SExt:
2829 case CCValAssign::SExtUpper:
2830 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2831 DAG.getValueType(VA.getValVT()));
2832 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2833 break;
2834 }
2835
2836 InVals.push_back(Val);
2837 }
2838
2839 return Chain;
2840}
2841
2842static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2843 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2844 MVT LocVT = VA.getLocVT();
2845 EVT ValVT = VA.getValVT();
2846
2847 // Shift into the upper bits if necessary.
2848 switch (VA.getLocInfo()) {
2849 default:
2850 break;
2851 case CCValAssign::AExtUpper:
2852 case CCValAssign::SExtUpper:
2853 case CCValAssign::ZExtUpper: {
2854 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2855 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2856 unsigned Opcode =
2857 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2858 Val = DAG.getNode(
2859 Opcode, DL, VA.getLocVT(), Val,
2860 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2861 break;
2862 }
2863 }
2864
2865 // If this is an value smaller than the argument slot size (32-bit for O32,
2866 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2867 // size. Extract the value and insert any appropriate assertions regarding
2868 // sign/zero extension.
2869 switch (VA.getLocInfo()) {
2870 default:
2871 llvm_unreachable("Unknown loc info!");
2872 case CCValAssign::Full:
2873 break;
2874 case CCValAssign::AExtUpper:
2875 case CCValAssign::AExt:
2876 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2877 break;
2878 case CCValAssign::SExtUpper:
2879 case CCValAssign::SExt:
2880 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2881 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2882 break;
2883 case CCValAssign::ZExtUpper:
2884 case CCValAssign::ZExt:
2885 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2886 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2887 break;
2888 case CCValAssign::BCvt:
2889 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2890 break;
2891 }
2892
2893 return Val;
2894}
2895
2896//===----------------------------------------------------------------------===//
2897// Formal Arguments Calling Convention Implementation
2898//===----------------------------------------------------------------------===//
2899/// LowerFormalArguments - transform physical registers into virtual registers
2900/// and generate load operations for arguments places on the stack.
2901SDValue
2902MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2903 CallingConv::ID CallConv,
2904 bool IsVarArg,
2905 const SmallVectorImpl<ISD::InputArg> &Ins,
2906 SDLoc DL, SelectionDAG &DAG,
2907 SmallVectorImpl<SDValue> &InVals)
2908 const {
2909 MachineFunction &MF = DAG.getMachineFunction();
2910 MachineFrameInfo *MFI = MF.getFrameInfo();
2911 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2912
2913 MipsFI->setVarArgsFrameIndex(0);
2914
2915 // Used with vargs to acumulate store chains.
2916 std::vector<SDValue> OutChains;
2917
2918 // Assign locations to all of the incoming arguments.
2919 SmallVector<CCValAssign, 16> ArgLocs;
2920 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2921 *DAG.getContext());
2922 const MipsABIInfo &ABI = Subtarget.getABI();
2923 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2924 Function::const_arg_iterator FuncArg =
2925 DAG.getMachineFunction().getFunction()->arg_begin();
2926
2927 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2928 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2929 CCInfo.getInRegsParamsCount() > 0);
2930
2931 unsigned CurArgIdx = 0;
2932 CCInfo.rewindByValRegsInfo();
2933
2934 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2935 CCValAssign &VA = ArgLocs[i];
2905 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2906 CurArgIdx = Ins[i].OrigArgIndex;
2936 if (Ins[i].isOrigArg()) {
2937 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2938 CurArgIdx = Ins[i].getOrigArgIndex();
2939 }
2907 EVT ValVT = VA.getValVT();
2908 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2909 bool IsRegLoc = VA.isRegLoc();
2910
2911 if (Flags.isByVal()) {
2940 EVT ValVT = VA.getValVT();
2941 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2942 bool IsRegLoc = VA.isRegLoc();
2943
2944 if (Flags.isByVal()) {
2945 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2912 unsigned FirstByValReg, LastByValReg;
2913 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2914 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2915
2916 assert(Flags.getByValSize() &&
2917 "ByVal args of size 0 should have been ignored by front-end.");
2918 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2919 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2920 FirstByValReg, LastByValReg, VA, CCInfo);
2921 CCInfo.nextInRegsParam();
2922 continue;
2923 }
2924
2925 // Arguments stored on registers
2926 if (IsRegLoc) {
2927 MVT RegVT = VA.getLocVT();
2928 unsigned ArgReg = VA.getLocReg();
2929 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2930
2931 // Transform the arguments stored on
2932 // physical registers into virtual ones
2933 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2934 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2935
2936 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2937
2938 // Handle floating point arguments passed in integer registers and
2939 // long double arguments passed in floating point registers.
2940 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2941 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2942 (RegVT == MVT::f64 && ValVT == MVT::i64))
2943 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2944 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2945 ValVT == MVT::f64) {
2946 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2947 getNextIntArgReg(ArgReg), RC);
2948 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2949 if (!Subtarget.isLittle())
2950 std::swap(ArgValue, ArgValue2);
2951 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2952 ArgValue, ArgValue2);
2953 }
2954
2955 InVals.push_back(ArgValue);
2956 } else { // VA.isRegLoc()
2957 MVT LocVT = VA.getLocVT();
2958
2959 if (Subtarget.isABI_O32()) {
2960 // We ought to be able to use LocVT directly but O32 sets it to i32
2961 // when allocating floating point values to integer registers.
2962 // This shouldn't influence how we load the value into registers unless
2963 // we are targetting softfloat.
2964 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2965 LocVT = VA.getValVT();
2966 }
2967
2968 // sanity check
2969 assert(VA.isMemLoc());
2970
2971 // The stack pointer offset is relative to the caller stack frame.
2972 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
2973 VA.getLocMemOffset(), true);
2974
2975 // Create load nodes to retrieve arguments from the stack
2976 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2977 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2978 MachinePointerInfo::getFixedStack(FI),
2979 false, false, false, 0);
2980 OutChains.push_back(ArgValue.getValue(1));
2981
2982 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2983
2984 InVals.push_back(ArgValue);
2985 }
2986 }
2987
2988 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989 // The mips ABIs for returning structs by value requires that we copy
2990 // the sret argument into $v0 for the return. Save the argument into
2991 // a virtual register so that we can access it from the return points.
2992 if (Ins[i].Flags.isSRet()) {
2993 unsigned Reg = MipsFI->getSRetReturnReg();
2994 if (!Reg) {
2995 Reg = MF.getRegInfo().createVirtualRegister(
2996 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2997 MipsFI->setSRetReturnReg(Reg);
2998 }
2999 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3000 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3001 break;
3002 }
3003 }
3004
3005 if (IsVarArg)
3006 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3007
3008 // All stores are grouped in one node to allow the matching between
3009 // the size of Ins and InVals. This only happens when on varg functions
3010 if (!OutChains.empty()) {
3011 OutChains.push_back(Chain);
3012 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3013 }
3014
3015 return Chain;
3016}
3017
3018//===----------------------------------------------------------------------===//
3019// Return Value Calling Convention Implementation
3020//===----------------------------------------------------------------------===//
3021
3022bool
3023MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3024 MachineFunction &MF, bool IsVarArg,
3025 const SmallVectorImpl<ISD::OutputArg> &Outs,
3026 LLVMContext &Context) const {
3027 SmallVector<CCValAssign, 16> RVLocs;
3028 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3029 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3030}
3031
2946 unsigned FirstByValReg, LastByValReg;
2947 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2948 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2949
2950 assert(Flags.getByValSize() &&
2951 "ByVal args of size 0 should have been ignored by front-end.");
2952 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2953 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2954 FirstByValReg, LastByValReg, VA, CCInfo);
2955 CCInfo.nextInRegsParam();
2956 continue;
2957 }
2958
2959 // Arguments stored on registers
2960 if (IsRegLoc) {
2961 MVT RegVT = VA.getLocVT();
2962 unsigned ArgReg = VA.getLocReg();
2963 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2964
2965 // Transform the arguments stored on
2966 // physical registers into virtual ones
2967 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2968 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2969
2970 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2971
2972 // Handle floating point arguments passed in integer registers and
2973 // long double arguments passed in floating point registers.
2974 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2975 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2976 (RegVT == MVT::f64 && ValVT == MVT::i64))
2977 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2978 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2979 ValVT == MVT::f64) {
2980 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2981 getNextIntArgReg(ArgReg), RC);
2982 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2983 if (!Subtarget.isLittle())
2984 std::swap(ArgValue, ArgValue2);
2985 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2986 ArgValue, ArgValue2);
2987 }
2988
2989 InVals.push_back(ArgValue);
2990 } else { // VA.isRegLoc()
2991 MVT LocVT = VA.getLocVT();
2992
2993 if (Subtarget.isABI_O32()) {
2994 // We ought to be able to use LocVT directly but O32 sets it to i32
2995 // when allocating floating point values to integer registers.
2996 // This shouldn't influence how we load the value into registers unless
2997 // we are targetting softfloat.
2998 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2999 LocVT = VA.getValVT();
3000 }
3001
3002 // sanity check
3003 assert(VA.isMemLoc());
3004
3005 // The stack pointer offset is relative to the caller stack frame.
3006 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3007 VA.getLocMemOffset(), true);
3008
3009 // Create load nodes to retrieve arguments from the stack
3010 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3011 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
3012 MachinePointerInfo::getFixedStack(FI),
3013 false, false, false, 0);
3014 OutChains.push_back(ArgValue.getValue(1));
3015
3016 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3017
3018 InVals.push_back(ArgValue);
3019 }
3020 }
3021
3022 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3023 // The mips ABIs for returning structs by value requires that we copy
3024 // the sret argument into $v0 for the return. Save the argument into
3025 // a virtual register so that we can access it from the return points.
3026 if (Ins[i].Flags.isSRet()) {
3027 unsigned Reg = MipsFI->getSRetReturnReg();
3028 if (!Reg) {
3029 Reg = MF.getRegInfo().createVirtualRegister(
3030 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
3031 MipsFI->setSRetReturnReg(Reg);
3032 }
3033 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3034 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3035 break;
3036 }
3037 }
3038
3039 if (IsVarArg)
3040 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3041
3042 // All stores are grouped in one node to allow the matching between
3043 // the size of Ins and InVals. This only happens when on varg functions
3044 if (!OutChains.empty()) {
3045 OutChains.push_back(Chain);
3046 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3047 }
3048
3049 return Chain;
3050}
3051
3052//===----------------------------------------------------------------------===//
3053// Return Value Calling Convention Implementation
3054//===----------------------------------------------------------------------===//
3055
3056bool
3057MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3058 MachineFunction &MF, bool IsVarArg,
3059 const SmallVectorImpl<ISD::OutputArg> &Outs,
3060 LLVMContext &Context) const {
3061 SmallVector<CCValAssign, 16> RVLocs;
3062 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3063 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3064}
3065
3066bool
3067MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3068 if (Subtarget.hasMips3() && Subtarget.abiUsesSoftFloat()) {
3069 if (Type == MVT::i32)
3070 return true;
3071 }
3072 return IsSigned;
3073}
3074
3032SDValue
3033MipsTargetLowering::LowerReturn(SDValue Chain,
3034 CallingConv::ID CallConv, bool IsVarArg,
3035 const SmallVectorImpl<ISD::OutputArg> &Outs,
3036 const SmallVectorImpl<SDValue> &OutVals,
3037 SDLoc DL, SelectionDAG &DAG) const {
3038 // CCValAssign - represent the assignment of
3039 // the return value to a location
3040 SmallVector<CCValAssign, 16> RVLocs;
3041 MachineFunction &MF = DAG.getMachineFunction();
3042
3043 // CCState - Info about the registers and stack slot.
3044 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3045
3046 // Analyze return values.
3047 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3048
3049 SDValue Flag;
3050 SmallVector<SDValue, 4> RetOps(1, Chain);
3051
3052 // Copy the result values into the output registers.
3053 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3054 SDValue Val = OutVals[i];
3055 CCValAssign &VA = RVLocs[i];
3056 assert(VA.isRegLoc() && "Can only return in registers!");
3057 bool UseUpperBits = false;
3058
3059 switch (VA.getLocInfo()) {
3060 default:
3061 llvm_unreachable("Unknown loc info!");
3062 case CCValAssign::Full:
3063 break;
3064 case CCValAssign::BCvt:
3065 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3066 break;
3067 case CCValAssign::AExtUpper:
3068 UseUpperBits = true;
3069 // Fallthrough
3070 case CCValAssign::AExt:
3071 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3072 break;
3073 case CCValAssign::ZExtUpper:
3074 UseUpperBits = true;
3075 // Fallthrough
3076 case CCValAssign::ZExt:
3077 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3078 break;
3079 case CCValAssign::SExtUpper:
3080 UseUpperBits = true;
3081 // Fallthrough
3082 case CCValAssign::SExt:
3083 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3084 break;
3085 }
3086
3087 if (UseUpperBits) {
3088 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3089 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3090 Val = DAG.getNode(
3091 ISD::SHL, DL, VA.getLocVT(), Val,
3092 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3093 }
3094
3095 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3096
3097 // Guarantee that all emitted copies are stuck together with flags.
3098 Flag = Chain.getValue(1);
3099 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3100 }
3101
3102 // The mips ABIs for returning structs by value requires that we copy
3103 // the sret argument into $v0 for the return. We saved the argument into
3104 // a virtual register in the entry block, so now we copy the value out
3105 // and into $v0.
3106 if (MF.getFunction()->hasStructRetAttr()) {
3107 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3108 unsigned Reg = MipsFI->getSRetReturnReg();
3109
3110 if (!Reg)
3111 llvm_unreachable("sret virtual register not created in the entry block");
3112 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3113 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3114
3115 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3116 Flag = Chain.getValue(1);
3117 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3118 }
3119
3120 RetOps[0] = Chain; // Update chain.
3121
3122 // Add the flag if we have it.
3123 if (Flag.getNode())
3124 RetOps.push_back(Flag);
3125
3126 // Return on Mips is always a "jr $ra"
3127 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3128}
3129
3130//===----------------------------------------------------------------------===//
3131// Mips Inline Assembly Support
3132//===----------------------------------------------------------------------===//
3133
3134/// getConstraintType - Given a constraint letter, return the type of
3135/// constraint it is for this target.
3136MipsTargetLowering::ConstraintType MipsTargetLowering::
3137getConstraintType(const std::string &Constraint) const
3138{
3139 // Mips specific constraints
3140 // GCC config/mips/constraints.md
3141 //
3142 // 'd' : An address register. Equivalent to r
3143 // unless generating MIPS16 code.
3144 // 'y' : Equivalent to r; retained for
3145 // backwards compatibility.
3146 // 'c' : A register suitable for use in an indirect
3147 // jump. This will always be $25 for -mabicalls.
3148 // 'l' : The lo register. 1 word storage.
3149 // 'x' : The hilo register pair. Double word storage.
3150 if (Constraint.size() == 1) {
3151 switch (Constraint[0]) {
3152 default : break;
3153 case 'd':
3154 case 'y':
3155 case 'f':
3156 case 'c':
3157 case 'l':
3158 case 'x':
3159 return C_RegisterClass;
3160 case 'R':
3161 return C_Memory;
3162 }
3163 }
3164 return TargetLowering::getConstraintType(Constraint);
3165}
3166
3167/// Examine constraint type and operand type and determine a weight value.
3168/// This object must already have been set up with the operand type
3169/// and the current alternative constraint selected.
3170TargetLowering::ConstraintWeight
3171MipsTargetLowering::getSingleConstraintMatchWeight(
3172 AsmOperandInfo &info, const char *constraint) const {
3173 ConstraintWeight weight = CW_Invalid;
3174 Value *CallOperandVal = info.CallOperandVal;
3175 // If we don't have a value, we can't do a match,
3176 // but allow it at the lowest weight.
3177 if (!CallOperandVal)
3178 return CW_Default;
3179 Type *type = CallOperandVal->getType();
3180 // Look at the constraint type.
3181 switch (*constraint) {
3182 default:
3183 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3184 break;
3185 case 'd':
3186 case 'y':
3187 if (type->isIntegerTy())
3188 weight = CW_Register;
3189 break;
3190 case 'f': // FPU or MSA register
3191 if (Subtarget.hasMSA() && type->isVectorTy() &&
3192 cast<VectorType>(type)->getBitWidth() == 128)
3193 weight = CW_Register;
3194 else if (type->isFloatTy())
3195 weight = CW_Register;
3196 break;
3197 case 'c': // $25 for indirect jumps
3198 case 'l': // lo register
3199 case 'x': // hilo register pair
3200 if (type->isIntegerTy())
3201 weight = CW_SpecificReg;
3202 break;
3203 case 'I': // signed 16 bit immediate
3204 case 'J': // integer zero
3205 case 'K': // unsigned 16 bit immediate
3206 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3207 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3208 case 'O': // signed 15 bit immediate (+- 16383)
3209 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3210 if (isa<ConstantInt>(CallOperandVal))
3211 weight = CW_Constant;
3212 break;
3213 case 'R':
3214 weight = CW_Memory;
3215 break;
3216 }
3217 return weight;
3218}
3219
3220/// This is a helper function to parse a physical register string and split it
3221/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3222/// that is returned indicates whether parsing was successful. The second flag
3223/// is true if the numeric part exists.
3224static std::pair<bool, bool>
3225parsePhysicalReg(StringRef C, std::string &Prefix,
3226 unsigned long long &Reg) {
3227 if (C.front() != '{' || C.back() != '}')
3228 return std::make_pair(false, false);
3229
3230 // Search for the first numeric character.
3231 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3232 I = std::find_if(B, E, std::ptr_fun(isdigit));
3233
3234 Prefix.assign(B, I - B);
3235
3236 // The second flag is set to false if no numeric characters were found.
3237 if (I == E)
3238 return std::make_pair(true, false);
3239
3240 // Parse the numeric characters.
3241 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3242 true);
3243}
3244
3245std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3246parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3247 const TargetRegisterInfo *TRI =
3248 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3249 const TargetRegisterClass *RC;
3250 std::string Prefix;
3251 unsigned long long Reg;
3252
3253 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3254
3255 if (!R.first)
3256 return std::make_pair(0U, nullptr);
3257
3258 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3259 // No numeric characters follow "hi" or "lo".
3260 if (R.second)
3261 return std::make_pair(0U, nullptr);
3262
3263 RC = TRI->getRegClass(Prefix == "hi" ?
3264 Mips::HI32RegClassID : Mips::LO32RegClassID);
3265 return std::make_pair(*(RC->begin()), RC);
3266 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3267 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3268
3269 // No numeric characters follow the name.
3270 if (R.second)
3271 return std::make_pair(0U, nullptr);
3272
3273 Reg = StringSwitch<unsigned long long>(Prefix)
3274 .Case("$msair", Mips::MSAIR)
3275 .Case("$msacsr", Mips::MSACSR)
3276 .Case("$msaaccess", Mips::MSAAccess)
3277 .Case("$msasave", Mips::MSASave)
3278 .Case("$msamodify", Mips::MSAModify)
3279 .Case("$msarequest", Mips::MSARequest)
3280 .Case("$msamap", Mips::MSAMap)
3281 .Case("$msaunmap", Mips::MSAUnmap)
3282 .Default(0);
3283
3284 if (!Reg)
3285 return std::make_pair(0U, nullptr);
3286
3287 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3288 return std::make_pair(Reg, RC);
3289 }
3290
3291 if (!R.second)
3292 return std::make_pair(0U, nullptr);
3293
3294 if (Prefix == "$f") { // Parse $f0-$f31.
3295 // If the size of FP registers is 64-bit or Reg is an even number, select
3296 // the 64-bit register class. Otherwise, select the 32-bit register class.
3297 if (VT == MVT::Other)
3298 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3299
3300 RC = getRegClassFor(VT);
3301
3302 if (RC == &Mips::AFGR64RegClass) {
3303 assert(Reg % 2 == 0);
3304 Reg >>= 1;
3305 }
3306 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3307 RC = TRI->getRegClass(Mips::FCCRegClassID);
3308 else if (Prefix == "$w") { // Parse $w0-$w31.
3309 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3310 } else { // Parse $0-$31.
3311 assert(Prefix == "$");
3312 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3313 }
3314
3315 assert(Reg < RC->getNumRegs());
3316 return std::make_pair(*(RC->begin() + Reg), RC);
3317}
3318
3319/// Given a register class constraint, like 'r', if this corresponds directly
3320/// to an LLVM register class, return a register of 0 and the register class
3321/// pointer.
3322std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3323getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3324{
3325 if (Constraint.size() == 1) {
3326 switch (Constraint[0]) {
3327 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3328 case 'y': // Same as 'r'. Exists for compatibility.
3329 case 'r':
3330 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3331 if (Subtarget.inMips16Mode())
3332 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3333 return std::make_pair(0U, &Mips::GPR32RegClass);
3334 }
3335 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3336 return std::make_pair(0U, &Mips::GPR32RegClass);
3337 if (VT == MVT::i64 && Subtarget.isGP64bit())
3338 return std::make_pair(0U, &Mips::GPR64RegClass);
3339 // This will generate an error message
3340 return std::make_pair(0U, nullptr);
3341 case 'f': // FPU or MSA register
3342 if (VT == MVT::v16i8)
3343 return std::make_pair(0U, &Mips::MSA128BRegClass);
3344 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3345 return std::make_pair(0U, &Mips::MSA128HRegClass);
3346 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3347 return std::make_pair(0U, &Mips::MSA128WRegClass);
3348 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3349 return std::make_pair(0U, &Mips::MSA128DRegClass);
3350 else if (VT == MVT::f32)
3351 return std::make_pair(0U, &Mips::FGR32RegClass);
3352 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3353 if (Subtarget.isFP64bit())
3354 return std::make_pair(0U, &Mips::FGR64RegClass);
3355 return std::make_pair(0U, &Mips::AFGR64RegClass);
3356 }
3357 break;
3358 case 'c': // register suitable for indirect jump
3359 if (VT == MVT::i32)
3360 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3361 assert(VT == MVT::i64 && "Unexpected type.");
3362 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3363 case 'l': // register suitable for indirect jump
3364 if (VT == MVT::i32)
3365 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3366 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3367 case 'x': // register suitable for indirect jump
3368 // Fixme: Not triggering the use of both hi and low
3369 // This will generate an error message
3370 return std::make_pair(0U, nullptr);
3371 }
3372 }
3373
3374 std::pair<unsigned, const TargetRegisterClass *> R;
3375 R = parseRegForInlineAsmConstraint(Constraint, VT);
3376
3377 if (R.second)
3378 return R;
3379
3380 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3381}
3382
3383/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3384/// vector. If it is invalid, don't add anything to Ops.
3385void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3386 std::string &Constraint,
3387 std::vector<SDValue>&Ops,
3388 SelectionDAG &DAG) const {
3389 SDValue Result;
3390
3391 // Only support length 1 constraints for now.
3392 if (Constraint.length() > 1) return;
3393
3394 char ConstraintLetter = Constraint[0];
3395 switch (ConstraintLetter) {
3396 default: break; // This will fall through to the generic implementation
3397 case 'I': // Signed 16 bit constant
3398 // If this fails, the parent routine will give an error
3399 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3400 EVT Type = Op.getValueType();
3401 int64_t Val = C->getSExtValue();
3402 if (isInt<16>(Val)) {
3403 Result = DAG.getTargetConstant(Val, Type);
3404 break;
3405 }
3406 }
3407 return;
3408 case 'J': // integer zero
3409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3410 EVT Type = Op.getValueType();
3411 int64_t Val = C->getZExtValue();
3412 if (Val == 0) {
3413 Result = DAG.getTargetConstant(0, Type);
3414 break;
3415 }
3416 }
3417 return;
3418 case 'K': // unsigned 16 bit immediate
3419 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3420 EVT Type = Op.getValueType();
3421 uint64_t Val = (uint64_t)C->getZExtValue();
3422 if (isUInt<16>(Val)) {
3423 Result = DAG.getTargetConstant(Val, Type);
3424 break;
3425 }
3426 }
3427 return;
3428 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3429 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3430 EVT Type = Op.getValueType();
3431 int64_t Val = C->getSExtValue();
3432 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3433 Result = DAG.getTargetConstant(Val, Type);
3434 break;
3435 }
3436 }
3437 return;
3438 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3439 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3440 EVT Type = Op.getValueType();
3441 int64_t Val = C->getSExtValue();
3442 if ((Val >= -65535) && (Val <= -1)) {
3443 Result = DAG.getTargetConstant(Val, Type);
3444 break;
3445 }
3446 }
3447 return;
3448 case 'O': // signed 15 bit immediate
3449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3450 EVT Type = Op.getValueType();
3451 int64_t Val = C->getSExtValue();
3452 if ((isInt<15>(Val))) {
3453 Result = DAG.getTargetConstant(Val, Type);
3454 break;
3455 }
3456 }
3457 return;
3458 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3460 EVT Type = Op.getValueType();
3461 int64_t Val = C->getSExtValue();
3462 if ((Val <= 65535) && (Val >= 1)) {
3463 Result = DAG.getTargetConstant(Val, Type);
3464 break;
3465 }
3466 }
3467 return;
3468 }
3469
3470 if (Result.getNode()) {
3471 Ops.push_back(Result);
3472 return;
3473 }
3474
3475 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3476}
3477
3478bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3479 Type *Ty) const {
3480 // No global is ever allowed as a base.
3481 if (AM.BaseGV)
3482 return false;
3483
3484 switch (AM.Scale) {
3485 case 0: // "r+i" or just "i", depending on HasBaseReg.
3486 break;
3487 case 1:
3488 if (!AM.HasBaseReg) // allow "r+i".
3489 break;
3490 return false; // disallow "r+r" or "r+r+i".
3491 default:
3492 return false;
3493 }
3494
3495 return true;
3496}
3497
3498bool
3499MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3500 // The Mips target isn't yet aware of offsets.
3501 return false;
3502}
3503
3504EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3505 unsigned SrcAlign,
3506 bool IsMemset, bool ZeroMemset,
3507 bool MemcpyStrSrc,
3508 MachineFunction &MF) const {
3509 if (Subtarget.hasMips64())
3510 return MVT::i64;
3511
3512 return MVT::i32;
3513}
3514
3515bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3516 if (VT != MVT::f32 && VT != MVT::f64)
3517 return false;
3518 if (Imm.isNegZero())
3519 return false;
3520 return Imm.isZero();
3521}
3522
3523unsigned MipsTargetLowering::getJumpTableEncoding() const {
3524 if (Subtarget.isABI_N64())
3525 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3526
3527 return TargetLowering::getJumpTableEncoding();
3528}
3529
3530void MipsTargetLowering::copyByValRegs(
3531 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3532 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3533 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3534 const CCValAssign &VA, MipsCCState &State) const {
3535 MachineFunction &MF = DAG.getMachineFunction();
3536 MachineFrameInfo *MFI = MF.getFrameInfo();
3537 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3538 unsigned NumRegs = LastReg - FirstReg;
3539 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3540 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3541 int FrameObjOffset;
3542 const MipsABIInfo &ABI = Subtarget.getABI();
3543 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3544
3545 if (RegAreaSize)
3546 FrameObjOffset =
3547 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3548 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3549 else
3550 FrameObjOffset = VA.getLocMemOffset();
3551
3552 // Create frame object.
3553 EVT PtrTy = getPointerTy();
3554 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3555 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3556 InVals.push_back(FIN);
3557
3558 if (!NumRegs)
3559 return;
3560
3561 // Copy arg registers.
3562 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3563 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3564
3565 for (unsigned I = 0; I < NumRegs; ++I) {
3566 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3567 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3568 unsigned Offset = I * GPRSizeInBytes;
3569 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3570 DAG.getConstant(Offset, PtrTy));
3571 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3572 StorePtr, MachinePointerInfo(FuncArg, Offset),
3573 false, false, 0);
3574 OutChains.push_back(Store);
3575 }
3576}
3577
3578// Copy byVal arg to registers and stack.
3579void MipsTargetLowering::passByValArg(
3580 SDValue Chain, SDLoc DL,
3581 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3582 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3583 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3584 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3585 const CCValAssign &VA) const {
3586 unsigned ByValSizeInBytes = Flags.getByValSize();
3587 unsigned OffsetInBytes = 0; // From beginning of struct
3588 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3589 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3590 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3591 unsigned NumRegs = LastReg - FirstReg;
3592
3593 if (NumRegs) {
3594 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetByValArgRegs();
3595 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3596 unsigned I = 0;
3597
3598 // Copy words to registers.
3599 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3600 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3601 DAG.getConstant(OffsetInBytes, PtrTy));
3602 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3603 MachinePointerInfo(), false, false, false,
3604 Alignment);
3605 MemOpChains.push_back(LoadVal.getValue(1));
3606 unsigned ArgReg = ArgRegs[FirstReg + I];
3607 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3608 }
3609
3610 // Return if the struct has been fully copied.
3611 if (ByValSizeInBytes == OffsetInBytes)
3612 return;
3613
3614 // Copy the remainder of the byval argument with sub-word loads and shifts.
3615 if (LeftoverBytes) {
3616 SDValue Val;
3617
3618 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3619 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3620 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3621
3622 if (RemainingSizeInBytes < LoadSizeInBytes)
3623 continue;
3624
3625 // Load subword.
3626 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3627 DAG.getConstant(OffsetInBytes, PtrTy));
3628 SDValue LoadVal = DAG.getExtLoad(
3629 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3630 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3631 Alignment);
3632 MemOpChains.push_back(LoadVal.getValue(1));
3633
3634 // Shift the loaded value.
3635 unsigned Shamt;
3636
3637 if (isLittle)
3638 Shamt = TotalBytesLoaded * 8;
3639 else
3640 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3641
3642 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3643 DAG.getConstant(Shamt, MVT::i32));
3644
3645 if (Val.getNode())
3646 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3647 else
3648 Val = Shift;
3649
3650 OffsetInBytes += LoadSizeInBytes;
3651 TotalBytesLoaded += LoadSizeInBytes;
3652 Alignment = std::min(Alignment, LoadSizeInBytes);
3653 }
3654
3655 unsigned ArgReg = ArgRegs[FirstReg + I];
3656 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3657 return;
3658 }
3659 }
3660
3661 // Copy remainder of byval arg to it with memcpy.
3662 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3663 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3664 DAG.getConstant(OffsetInBytes, PtrTy));
3665 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3666 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3667 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3668 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3669 MachinePointerInfo(), MachinePointerInfo());
3670 MemOpChains.push_back(Chain);
3671}
3672
3673void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3674 SDValue Chain, SDLoc DL,
3675 SelectionDAG &DAG,
3676 CCState &State) const {
3677 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetVarArgRegs();
3678 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3679 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3680 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3681 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3682 MachineFunction &MF = DAG.getMachineFunction();
3683 MachineFrameInfo *MFI = MF.getFrameInfo();
3684 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3685
3686 // Offset of the first variable argument from stack pointer.
3687 int VaArgOffset;
3688
3689 if (ArgRegs.size() == Idx)
3690 VaArgOffset =
3691 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3692 else {
3693 const MipsABIInfo &ABI = Subtarget.getABI();
3694 VaArgOffset =
3695 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3696 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3697 }
3698
3699 // Record the frame index of the first variable argument
3700 // which is a value necessary to VASTART.
3701 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3702 MipsFI->setVarArgsFrameIndex(FI);
3703
3704 // Copy the integer registers that have not been used for argument passing
3705 // to the argument register save area. For O32, the save area is allocated
3706 // in the caller's stack frame, while for N32/64, it is allocated in the
3707 // callee's stack frame.
3708 for (unsigned I = Idx; I < ArgRegs.size();
3709 ++I, VaArgOffset += RegSizeInBytes) {
3710 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3711 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3712 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3713 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3714 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3715 MachinePointerInfo(), false, false, 0);
3716 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3717 (Value *)nullptr);
3718 OutChains.push_back(Store);
3719 }
3720}
3721
3722void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3723 unsigned Align) const {
3724 MachineFunction &MF = State->getMachineFunction();
3725 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3726
3727 assert(Size && "Byval argument's size shouldn't be 0.");
3728
3729 Align = std::min(Align, TFL->getStackAlignment());
3730
3731 unsigned FirstReg = 0;
3732 unsigned NumRegs = 0;
3733
3734 if (State->getCallingConv() != CallingConv::Fast) {
3735 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3736 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3737 // FIXME: The O32 case actually describes no shadow registers.
3738 const MCPhysReg *ShadowRegs =
3739 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3740
3741 // We used to check the size as well but we can't do that anymore since
3742 // CCState::HandleByVal() rounds up the size after calling this function.
3743 assert(!(Align % RegSizeInBytes) &&
3744 "Byval argument's alignment should be a multiple of"
3745 "RegSizeInBytes.");
3746
3747 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3748
3749 // If Align > RegSizeInBytes, the first arg register must be even.
3750 // FIXME: This condition happens to do the right thing but it's not the
3751 // right way to test it. We want to check that the stack frame offset
3752 // of the register is aligned.
3753 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3754 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3755 ++FirstReg;
3756 }
3757
3758 // Mark the registers allocated.
3759 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3760 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3761 Size -= RegSizeInBytes, ++I, ++NumRegs)
3762 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3763 }
3764
3765 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3766}
3767
3768MachineBasicBlock *
3769MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3770 bool isFPCmp, unsigned Opc) const {
3771 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3772 "Subtarget already supports SELECT nodes with the use of"
3773 "conditional-move instructions.");
3774
3775 const TargetInstrInfo *TII =
3776 getTargetMachine().getSubtargetImpl()->getInstrInfo();
3777 DebugLoc DL = MI->getDebugLoc();
3778
3779 // To "insert" a SELECT instruction, we actually have to insert the
3780 // diamond control-flow pattern. The incoming instruction knows the
3781 // destination vreg to set, the condition code register to branch on, the
3782 // true/false values to select between, and a branch opcode to use.
3783 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3784 MachineFunction::iterator It = BB;
3785 ++It;
3786
3787 // thisMBB:
3788 // ...
3789 // TrueVal = ...
3790 // setcc r1, r2, r3
3791 // bNE r1, r0, copy1MBB
3792 // fallthrough --> copy0MBB
3793 MachineBasicBlock *thisMBB = BB;
3794 MachineFunction *F = BB->getParent();
3795 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3796 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3797 F->insert(It, copy0MBB);
3798 F->insert(It, sinkMBB);
3799
3800 // Transfer the remainder of BB and its successor edges to sinkMBB.
3801 sinkMBB->splice(sinkMBB->begin(), BB,
3802 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3803 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3804
3805 // Next, add the true and fallthrough blocks as its successors.
3806 BB->addSuccessor(copy0MBB);
3807 BB->addSuccessor(sinkMBB);
3808
3809 if (isFPCmp) {
3810 // bc1[tf] cc, sinkMBB
3811 BuildMI(BB, DL, TII->get(Opc))
3812 .addReg(MI->getOperand(1).getReg())
3813 .addMBB(sinkMBB);
3814 } else {
3815 // bne rs, $0, sinkMBB
3816 BuildMI(BB, DL, TII->get(Opc))
3817 .addReg(MI->getOperand(1).getReg())
3818 .addReg(Mips::ZERO)
3819 .addMBB(sinkMBB);
3820 }
3821
3822 // copy0MBB:
3823 // %FalseValue = ...
3824 // # fallthrough to sinkMBB
3825 BB = copy0MBB;
3826
3827 // Update machine-CFG edges
3828 BB->addSuccessor(sinkMBB);
3829
3830 // sinkMBB:
3831 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3832 // ...
3833 BB = sinkMBB;
3834
3835 BuildMI(*BB, BB->begin(), DL,
3836 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3837 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3838 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3839
3840 MI->eraseFromParent(); // The pseudo instruction is gone now.
3841
3842 return BB;
3843}
3844
3845// FIXME? Maybe this could be a TableGen attribute on some registers and
3846// this table could be generated automatically from RegInfo.
3847unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3848 EVT VT) const {
3849 // Named registers is expected to be fairly rare. For now, just support $28
3850 // since the linux kernel uses it.
3851 if (Subtarget.isGP64bit()) {
3852 unsigned Reg = StringSwitch<unsigned>(RegName)
3853 .Case("$28", Mips::GP_64)
3854 .Default(0);
3855 if (Reg)
3856 return Reg;
3857 } else {
3858 unsigned Reg = StringSwitch<unsigned>(RegName)
3859 .Case("$28", Mips::GP)
3860 .Default(0);
3861 if (Reg)
3862 return Reg;
3863 }
3864 report_fatal_error("Invalid register name global variable");
3865}
3075SDValue
3076MipsTargetLowering::LowerReturn(SDValue Chain,
3077 CallingConv::ID CallConv, bool IsVarArg,
3078 const SmallVectorImpl<ISD::OutputArg> &Outs,
3079 const SmallVectorImpl<SDValue> &OutVals,
3080 SDLoc DL, SelectionDAG &DAG) const {
3081 // CCValAssign - represent the assignment of
3082 // the return value to a location
3083 SmallVector<CCValAssign, 16> RVLocs;
3084 MachineFunction &MF = DAG.getMachineFunction();
3085
3086 // CCState - Info about the registers and stack slot.
3087 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3088
3089 // Analyze return values.
3090 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3091
3092 SDValue Flag;
3093 SmallVector<SDValue, 4> RetOps(1, Chain);
3094
3095 // Copy the result values into the output registers.
3096 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3097 SDValue Val = OutVals[i];
3098 CCValAssign &VA = RVLocs[i];
3099 assert(VA.isRegLoc() && "Can only return in registers!");
3100 bool UseUpperBits = false;
3101
3102 switch (VA.getLocInfo()) {
3103 default:
3104 llvm_unreachable("Unknown loc info!");
3105 case CCValAssign::Full:
3106 break;
3107 case CCValAssign::BCvt:
3108 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3109 break;
3110 case CCValAssign::AExtUpper:
3111 UseUpperBits = true;
3112 // Fallthrough
3113 case CCValAssign::AExt:
3114 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3115 break;
3116 case CCValAssign::ZExtUpper:
3117 UseUpperBits = true;
3118 // Fallthrough
3119 case CCValAssign::ZExt:
3120 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3121 break;
3122 case CCValAssign::SExtUpper:
3123 UseUpperBits = true;
3124 // Fallthrough
3125 case CCValAssign::SExt:
3126 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3127 break;
3128 }
3129
3130 if (UseUpperBits) {
3131 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3132 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3133 Val = DAG.getNode(
3134 ISD::SHL, DL, VA.getLocVT(), Val,
3135 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3136 }
3137
3138 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3139
3140 // Guarantee that all emitted copies are stuck together with flags.
3141 Flag = Chain.getValue(1);
3142 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3143 }
3144
3145 // The mips ABIs for returning structs by value requires that we copy
3146 // the sret argument into $v0 for the return. We saved the argument into
3147 // a virtual register in the entry block, so now we copy the value out
3148 // and into $v0.
3149 if (MF.getFunction()->hasStructRetAttr()) {
3150 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3151 unsigned Reg = MipsFI->getSRetReturnReg();
3152
3153 if (!Reg)
3154 llvm_unreachable("sret virtual register not created in the entry block");
3155 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3156 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3157
3158 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3159 Flag = Chain.getValue(1);
3160 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3161 }
3162
3163 RetOps[0] = Chain; // Update chain.
3164
3165 // Add the flag if we have it.
3166 if (Flag.getNode())
3167 RetOps.push_back(Flag);
3168
3169 // Return on Mips is always a "jr $ra"
3170 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3171}
3172
3173//===----------------------------------------------------------------------===//
3174// Mips Inline Assembly Support
3175//===----------------------------------------------------------------------===//
3176
3177/// getConstraintType - Given a constraint letter, return the type of
3178/// constraint it is for this target.
3179MipsTargetLowering::ConstraintType MipsTargetLowering::
3180getConstraintType(const std::string &Constraint) const
3181{
3182 // Mips specific constraints
3183 // GCC config/mips/constraints.md
3184 //
3185 // 'd' : An address register. Equivalent to r
3186 // unless generating MIPS16 code.
3187 // 'y' : Equivalent to r; retained for
3188 // backwards compatibility.
3189 // 'c' : A register suitable for use in an indirect
3190 // jump. This will always be $25 for -mabicalls.
3191 // 'l' : The lo register. 1 word storage.
3192 // 'x' : The hilo register pair. Double word storage.
3193 if (Constraint.size() == 1) {
3194 switch (Constraint[0]) {
3195 default : break;
3196 case 'd':
3197 case 'y':
3198 case 'f':
3199 case 'c':
3200 case 'l':
3201 case 'x':
3202 return C_RegisterClass;
3203 case 'R':
3204 return C_Memory;
3205 }
3206 }
3207 return TargetLowering::getConstraintType(Constraint);
3208}
3209
3210/// Examine constraint type and operand type and determine a weight value.
3211/// This object must already have been set up with the operand type
3212/// and the current alternative constraint selected.
3213TargetLowering::ConstraintWeight
3214MipsTargetLowering::getSingleConstraintMatchWeight(
3215 AsmOperandInfo &info, const char *constraint) const {
3216 ConstraintWeight weight = CW_Invalid;
3217 Value *CallOperandVal = info.CallOperandVal;
3218 // If we don't have a value, we can't do a match,
3219 // but allow it at the lowest weight.
3220 if (!CallOperandVal)
3221 return CW_Default;
3222 Type *type = CallOperandVal->getType();
3223 // Look at the constraint type.
3224 switch (*constraint) {
3225 default:
3226 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3227 break;
3228 case 'd':
3229 case 'y':
3230 if (type->isIntegerTy())
3231 weight = CW_Register;
3232 break;
3233 case 'f': // FPU or MSA register
3234 if (Subtarget.hasMSA() && type->isVectorTy() &&
3235 cast<VectorType>(type)->getBitWidth() == 128)
3236 weight = CW_Register;
3237 else if (type->isFloatTy())
3238 weight = CW_Register;
3239 break;
3240 case 'c': // $25 for indirect jumps
3241 case 'l': // lo register
3242 case 'x': // hilo register pair
3243 if (type->isIntegerTy())
3244 weight = CW_SpecificReg;
3245 break;
3246 case 'I': // signed 16 bit immediate
3247 case 'J': // integer zero
3248 case 'K': // unsigned 16 bit immediate
3249 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3250 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3251 case 'O': // signed 15 bit immediate (+- 16383)
3252 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3253 if (isa<ConstantInt>(CallOperandVal))
3254 weight = CW_Constant;
3255 break;
3256 case 'R':
3257 weight = CW_Memory;
3258 break;
3259 }
3260 return weight;
3261}
3262
3263/// This is a helper function to parse a physical register string and split it
3264/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3265/// that is returned indicates whether parsing was successful. The second flag
3266/// is true if the numeric part exists.
3267static std::pair<bool, bool>
3268parsePhysicalReg(StringRef C, std::string &Prefix,
3269 unsigned long long &Reg) {
3270 if (C.front() != '{' || C.back() != '}')
3271 return std::make_pair(false, false);
3272
3273 // Search for the first numeric character.
3274 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3275 I = std::find_if(B, E, std::ptr_fun(isdigit));
3276
3277 Prefix.assign(B, I - B);
3278
3279 // The second flag is set to false if no numeric characters were found.
3280 if (I == E)
3281 return std::make_pair(true, false);
3282
3283 // Parse the numeric characters.
3284 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3285 true);
3286}
3287
3288std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3289parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3290 const TargetRegisterInfo *TRI =
3291 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3292 const TargetRegisterClass *RC;
3293 std::string Prefix;
3294 unsigned long long Reg;
3295
3296 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3297
3298 if (!R.first)
3299 return std::make_pair(0U, nullptr);
3300
3301 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3302 // No numeric characters follow "hi" or "lo".
3303 if (R.second)
3304 return std::make_pair(0U, nullptr);
3305
3306 RC = TRI->getRegClass(Prefix == "hi" ?
3307 Mips::HI32RegClassID : Mips::LO32RegClassID);
3308 return std::make_pair(*(RC->begin()), RC);
3309 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3310 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3311
3312 // No numeric characters follow the name.
3313 if (R.second)
3314 return std::make_pair(0U, nullptr);
3315
3316 Reg = StringSwitch<unsigned long long>(Prefix)
3317 .Case("$msair", Mips::MSAIR)
3318 .Case("$msacsr", Mips::MSACSR)
3319 .Case("$msaaccess", Mips::MSAAccess)
3320 .Case("$msasave", Mips::MSASave)
3321 .Case("$msamodify", Mips::MSAModify)
3322 .Case("$msarequest", Mips::MSARequest)
3323 .Case("$msamap", Mips::MSAMap)
3324 .Case("$msaunmap", Mips::MSAUnmap)
3325 .Default(0);
3326
3327 if (!Reg)
3328 return std::make_pair(0U, nullptr);
3329
3330 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3331 return std::make_pair(Reg, RC);
3332 }
3333
3334 if (!R.second)
3335 return std::make_pair(0U, nullptr);
3336
3337 if (Prefix == "$f") { // Parse $f0-$f31.
3338 // If the size of FP registers is 64-bit or Reg is an even number, select
3339 // the 64-bit register class. Otherwise, select the 32-bit register class.
3340 if (VT == MVT::Other)
3341 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3342
3343 RC = getRegClassFor(VT);
3344
3345 if (RC == &Mips::AFGR64RegClass) {
3346 assert(Reg % 2 == 0);
3347 Reg >>= 1;
3348 }
3349 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3350 RC = TRI->getRegClass(Mips::FCCRegClassID);
3351 else if (Prefix == "$w") { // Parse $w0-$w31.
3352 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3353 } else { // Parse $0-$31.
3354 assert(Prefix == "$");
3355 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3356 }
3357
3358 assert(Reg < RC->getNumRegs());
3359 return std::make_pair(*(RC->begin() + Reg), RC);
3360}
3361
3362/// Given a register class constraint, like 'r', if this corresponds directly
3363/// to an LLVM register class, return a register of 0 and the register class
3364/// pointer.
3365std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3366getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3367{
3368 if (Constraint.size() == 1) {
3369 switch (Constraint[0]) {
3370 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3371 case 'y': // Same as 'r'. Exists for compatibility.
3372 case 'r':
3373 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3374 if (Subtarget.inMips16Mode())
3375 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3376 return std::make_pair(0U, &Mips::GPR32RegClass);
3377 }
3378 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3379 return std::make_pair(0U, &Mips::GPR32RegClass);
3380 if (VT == MVT::i64 && Subtarget.isGP64bit())
3381 return std::make_pair(0U, &Mips::GPR64RegClass);
3382 // This will generate an error message
3383 return std::make_pair(0U, nullptr);
3384 case 'f': // FPU or MSA register
3385 if (VT == MVT::v16i8)
3386 return std::make_pair(0U, &Mips::MSA128BRegClass);
3387 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3388 return std::make_pair(0U, &Mips::MSA128HRegClass);
3389 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3390 return std::make_pair(0U, &Mips::MSA128WRegClass);
3391 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3392 return std::make_pair(0U, &Mips::MSA128DRegClass);
3393 else if (VT == MVT::f32)
3394 return std::make_pair(0U, &Mips::FGR32RegClass);
3395 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3396 if (Subtarget.isFP64bit())
3397 return std::make_pair(0U, &Mips::FGR64RegClass);
3398 return std::make_pair(0U, &Mips::AFGR64RegClass);
3399 }
3400 break;
3401 case 'c': // register suitable for indirect jump
3402 if (VT == MVT::i32)
3403 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3404 assert(VT == MVT::i64 && "Unexpected type.");
3405 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3406 case 'l': // register suitable for indirect jump
3407 if (VT == MVT::i32)
3408 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3409 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3410 case 'x': // register suitable for indirect jump
3411 // Fixme: Not triggering the use of both hi and low
3412 // This will generate an error message
3413 return std::make_pair(0U, nullptr);
3414 }
3415 }
3416
3417 std::pair<unsigned, const TargetRegisterClass *> R;
3418 R = parseRegForInlineAsmConstraint(Constraint, VT);
3419
3420 if (R.second)
3421 return R;
3422
3423 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3424}
3425
3426/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3427/// vector. If it is invalid, don't add anything to Ops.
3428void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3429 std::string &Constraint,
3430 std::vector<SDValue>&Ops,
3431 SelectionDAG &DAG) const {
3432 SDValue Result;
3433
3434 // Only support length 1 constraints for now.
3435 if (Constraint.length() > 1) return;
3436
3437 char ConstraintLetter = Constraint[0];
3438 switch (ConstraintLetter) {
3439 default: break; // This will fall through to the generic implementation
3440 case 'I': // Signed 16 bit constant
3441 // If this fails, the parent routine will give an error
3442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3443 EVT Type = Op.getValueType();
3444 int64_t Val = C->getSExtValue();
3445 if (isInt<16>(Val)) {
3446 Result = DAG.getTargetConstant(Val, Type);
3447 break;
3448 }
3449 }
3450 return;
3451 case 'J': // integer zero
3452 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3453 EVT Type = Op.getValueType();
3454 int64_t Val = C->getZExtValue();
3455 if (Val == 0) {
3456 Result = DAG.getTargetConstant(0, Type);
3457 break;
3458 }
3459 }
3460 return;
3461 case 'K': // unsigned 16 bit immediate
3462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3463 EVT Type = Op.getValueType();
3464 uint64_t Val = (uint64_t)C->getZExtValue();
3465 if (isUInt<16>(Val)) {
3466 Result = DAG.getTargetConstant(Val, Type);
3467 break;
3468 }
3469 }
3470 return;
3471 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3473 EVT Type = Op.getValueType();
3474 int64_t Val = C->getSExtValue();
3475 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3476 Result = DAG.getTargetConstant(Val, Type);
3477 break;
3478 }
3479 }
3480 return;
3481 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3482 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3483 EVT Type = Op.getValueType();
3484 int64_t Val = C->getSExtValue();
3485 if ((Val >= -65535) && (Val <= -1)) {
3486 Result = DAG.getTargetConstant(Val, Type);
3487 break;
3488 }
3489 }
3490 return;
3491 case 'O': // signed 15 bit immediate
3492 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3493 EVT Type = Op.getValueType();
3494 int64_t Val = C->getSExtValue();
3495 if ((isInt<15>(Val))) {
3496 Result = DAG.getTargetConstant(Val, Type);
3497 break;
3498 }
3499 }
3500 return;
3501 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3503 EVT Type = Op.getValueType();
3504 int64_t Val = C->getSExtValue();
3505 if ((Val <= 65535) && (Val >= 1)) {
3506 Result = DAG.getTargetConstant(Val, Type);
3507 break;
3508 }
3509 }
3510 return;
3511 }
3512
3513 if (Result.getNode()) {
3514 Ops.push_back(Result);
3515 return;
3516 }
3517
3518 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3519}
3520
3521bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3522 Type *Ty) const {
3523 // No global is ever allowed as a base.
3524 if (AM.BaseGV)
3525 return false;
3526
3527 switch (AM.Scale) {
3528 case 0: // "r+i" or just "i", depending on HasBaseReg.
3529 break;
3530 case 1:
3531 if (!AM.HasBaseReg) // allow "r+i".
3532 break;
3533 return false; // disallow "r+r" or "r+r+i".
3534 default:
3535 return false;
3536 }
3537
3538 return true;
3539}
3540
3541bool
3542MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3543 // The Mips target isn't yet aware of offsets.
3544 return false;
3545}
3546
3547EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3548 unsigned SrcAlign,
3549 bool IsMemset, bool ZeroMemset,
3550 bool MemcpyStrSrc,
3551 MachineFunction &MF) const {
3552 if (Subtarget.hasMips64())
3553 return MVT::i64;
3554
3555 return MVT::i32;
3556}
3557
3558bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3559 if (VT != MVT::f32 && VT != MVT::f64)
3560 return false;
3561 if (Imm.isNegZero())
3562 return false;
3563 return Imm.isZero();
3564}
3565
3566unsigned MipsTargetLowering::getJumpTableEncoding() const {
3567 if (Subtarget.isABI_N64())
3568 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3569
3570 return TargetLowering::getJumpTableEncoding();
3571}
3572
3573void MipsTargetLowering::copyByValRegs(
3574 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3575 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3576 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3577 const CCValAssign &VA, MipsCCState &State) const {
3578 MachineFunction &MF = DAG.getMachineFunction();
3579 MachineFrameInfo *MFI = MF.getFrameInfo();
3580 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3581 unsigned NumRegs = LastReg - FirstReg;
3582 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3583 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3584 int FrameObjOffset;
3585 const MipsABIInfo &ABI = Subtarget.getABI();
3586 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3587
3588 if (RegAreaSize)
3589 FrameObjOffset =
3590 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3591 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3592 else
3593 FrameObjOffset = VA.getLocMemOffset();
3594
3595 // Create frame object.
3596 EVT PtrTy = getPointerTy();
3597 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3598 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3599 InVals.push_back(FIN);
3600
3601 if (!NumRegs)
3602 return;
3603
3604 // Copy arg registers.
3605 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3606 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3607
3608 for (unsigned I = 0; I < NumRegs; ++I) {
3609 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3610 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3611 unsigned Offset = I * GPRSizeInBytes;
3612 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3613 DAG.getConstant(Offset, PtrTy));
3614 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3615 StorePtr, MachinePointerInfo(FuncArg, Offset),
3616 false, false, 0);
3617 OutChains.push_back(Store);
3618 }
3619}
3620
3621// Copy byVal arg to registers and stack.
3622void MipsTargetLowering::passByValArg(
3623 SDValue Chain, SDLoc DL,
3624 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3625 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3626 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3627 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3628 const CCValAssign &VA) const {
3629 unsigned ByValSizeInBytes = Flags.getByValSize();
3630 unsigned OffsetInBytes = 0; // From beginning of struct
3631 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3632 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3633 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3634 unsigned NumRegs = LastReg - FirstReg;
3635
3636 if (NumRegs) {
3637 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetByValArgRegs();
3638 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3639 unsigned I = 0;
3640
3641 // Copy words to registers.
3642 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3643 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3644 DAG.getConstant(OffsetInBytes, PtrTy));
3645 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3646 MachinePointerInfo(), false, false, false,
3647 Alignment);
3648 MemOpChains.push_back(LoadVal.getValue(1));
3649 unsigned ArgReg = ArgRegs[FirstReg + I];
3650 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3651 }
3652
3653 // Return if the struct has been fully copied.
3654 if (ByValSizeInBytes == OffsetInBytes)
3655 return;
3656
3657 // Copy the remainder of the byval argument with sub-word loads and shifts.
3658 if (LeftoverBytes) {
3659 SDValue Val;
3660
3661 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3662 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3663 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3664
3665 if (RemainingSizeInBytes < LoadSizeInBytes)
3666 continue;
3667
3668 // Load subword.
3669 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3670 DAG.getConstant(OffsetInBytes, PtrTy));
3671 SDValue LoadVal = DAG.getExtLoad(
3672 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3673 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3674 Alignment);
3675 MemOpChains.push_back(LoadVal.getValue(1));
3676
3677 // Shift the loaded value.
3678 unsigned Shamt;
3679
3680 if (isLittle)
3681 Shamt = TotalBytesLoaded * 8;
3682 else
3683 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3684
3685 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3686 DAG.getConstant(Shamt, MVT::i32));
3687
3688 if (Val.getNode())
3689 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3690 else
3691 Val = Shift;
3692
3693 OffsetInBytes += LoadSizeInBytes;
3694 TotalBytesLoaded += LoadSizeInBytes;
3695 Alignment = std::min(Alignment, LoadSizeInBytes);
3696 }
3697
3698 unsigned ArgReg = ArgRegs[FirstReg + I];
3699 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3700 return;
3701 }
3702 }
3703
3704 // Copy remainder of byval arg to it with memcpy.
3705 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3706 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3707 DAG.getConstant(OffsetInBytes, PtrTy));
3708 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3709 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3710 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3711 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3712 MachinePointerInfo(), MachinePointerInfo());
3713 MemOpChains.push_back(Chain);
3714}
3715
3716void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3717 SDValue Chain, SDLoc DL,
3718 SelectionDAG &DAG,
3719 CCState &State) const {
3720 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetVarArgRegs();
3721 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3722 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3723 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3724 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3725 MachineFunction &MF = DAG.getMachineFunction();
3726 MachineFrameInfo *MFI = MF.getFrameInfo();
3727 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3728
3729 // Offset of the first variable argument from stack pointer.
3730 int VaArgOffset;
3731
3732 if (ArgRegs.size() == Idx)
3733 VaArgOffset =
3734 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3735 else {
3736 const MipsABIInfo &ABI = Subtarget.getABI();
3737 VaArgOffset =
3738 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3739 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3740 }
3741
3742 // Record the frame index of the first variable argument
3743 // which is a value necessary to VASTART.
3744 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3745 MipsFI->setVarArgsFrameIndex(FI);
3746
3747 // Copy the integer registers that have not been used for argument passing
3748 // to the argument register save area. For O32, the save area is allocated
3749 // in the caller's stack frame, while for N32/64, it is allocated in the
3750 // callee's stack frame.
3751 for (unsigned I = Idx; I < ArgRegs.size();
3752 ++I, VaArgOffset += RegSizeInBytes) {
3753 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3754 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3755 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3756 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3757 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3758 MachinePointerInfo(), false, false, 0);
3759 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3760 (Value *)nullptr);
3761 OutChains.push_back(Store);
3762 }
3763}
3764
3765void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3766 unsigned Align) const {
3767 MachineFunction &MF = State->getMachineFunction();
3768 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3769
3770 assert(Size && "Byval argument's size shouldn't be 0.");
3771
3772 Align = std::min(Align, TFL->getStackAlignment());
3773
3774 unsigned FirstReg = 0;
3775 unsigned NumRegs = 0;
3776
3777 if (State->getCallingConv() != CallingConv::Fast) {
3778 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3779 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3780 // FIXME: The O32 case actually describes no shadow registers.
3781 const MCPhysReg *ShadowRegs =
3782 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3783
3784 // We used to check the size as well but we can't do that anymore since
3785 // CCState::HandleByVal() rounds up the size after calling this function.
3786 assert(!(Align % RegSizeInBytes) &&
3787 "Byval argument's alignment should be a multiple of"
3788 "RegSizeInBytes.");
3789
3790 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3791
3792 // If Align > RegSizeInBytes, the first arg register must be even.
3793 // FIXME: This condition happens to do the right thing but it's not the
3794 // right way to test it. We want to check that the stack frame offset
3795 // of the register is aligned.
3796 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3797 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3798 ++FirstReg;
3799 }
3800
3801 // Mark the registers allocated.
3802 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3803 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3804 Size -= RegSizeInBytes, ++I, ++NumRegs)
3805 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3806 }
3807
3808 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3809}
3810
3811MachineBasicBlock *
3812MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3813 bool isFPCmp, unsigned Opc) const {
3814 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3815 "Subtarget already supports SELECT nodes with the use of"
3816 "conditional-move instructions.");
3817
3818 const TargetInstrInfo *TII =
3819 getTargetMachine().getSubtargetImpl()->getInstrInfo();
3820 DebugLoc DL = MI->getDebugLoc();
3821
3822 // To "insert" a SELECT instruction, we actually have to insert the
3823 // diamond control-flow pattern. The incoming instruction knows the
3824 // destination vreg to set, the condition code register to branch on, the
3825 // true/false values to select between, and a branch opcode to use.
3826 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3827 MachineFunction::iterator It = BB;
3828 ++It;
3829
3830 // thisMBB:
3831 // ...
3832 // TrueVal = ...
3833 // setcc r1, r2, r3
3834 // bNE r1, r0, copy1MBB
3835 // fallthrough --> copy0MBB
3836 MachineBasicBlock *thisMBB = BB;
3837 MachineFunction *F = BB->getParent();
3838 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3839 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3840 F->insert(It, copy0MBB);
3841 F->insert(It, sinkMBB);
3842
3843 // Transfer the remainder of BB and its successor edges to sinkMBB.
3844 sinkMBB->splice(sinkMBB->begin(), BB,
3845 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3846 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3847
3848 // Next, add the true and fallthrough blocks as its successors.
3849 BB->addSuccessor(copy0MBB);
3850 BB->addSuccessor(sinkMBB);
3851
3852 if (isFPCmp) {
3853 // bc1[tf] cc, sinkMBB
3854 BuildMI(BB, DL, TII->get(Opc))
3855 .addReg(MI->getOperand(1).getReg())
3856 .addMBB(sinkMBB);
3857 } else {
3858 // bne rs, $0, sinkMBB
3859 BuildMI(BB, DL, TII->get(Opc))
3860 .addReg(MI->getOperand(1).getReg())
3861 .addReg(Mips::ZERO)
3862 .addMBB(sinkMBB);
3863 }
3864
3865 // copy0MBB:
3866 // %FalseValue = ...
3867 // # fallthrough to sinkMBB
3868 BB = copy0MBB;
3869
3870 // Update machine-CFG edges
3871 BB->addSuccessor(sinkMBB);
3872
3873 // sinkMBB:
3874 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3875 // ...
3876 BB = sinkMBB;
3877
3878 BuildMI(*BB, BB->begin(), DL,
3879 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3880 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3881 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3882
3883 MI->eraseFromParent(); // The pseudo instruction is gone now.
3884
3885 return BB;
3886}
3887
3888// FIXME? Maybe this could be a TableGen attribute on some registers and
3889// this table could be generated automatically from RegInfo.
3890unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3891 EVT VT) const {
3892 // Named registers is expected to be fairly rare. For now, just support $28
3893 // since the linux kernel uses it.
3894 if (Subtarget.isGP64bit()) {
3895 unsigned Reg = StringSwitch<unsigned>(RegName)
3896 .Case("$28", Mips::GP_64)
3897 .Default(0);
3898 if (Reg)
3899 return Reg;
3900 } else {
3901 unsigned Reg = StringSwitch<unsigned>(RegName)
3902 .Case("$28", Mips::GP)
3903 .Default(0);
3904 if (Reg)
3905 return Reg;
3906 }
3907 report_fatal_error("Invalid register name global variable");
3908}