MipsISelLowering.cpp revision fd89e6ffdab95ae6b4568b8a4153064952f61ea6
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
15#define DEBUG_TYPE "mips-lower"
16#include "MipsISelLowering.h"
17#include "MipsMachineFunction.h"
18#include "MipsTargetMachine.h"
19#include "MipsTargetObjectFile.h"
20#include "MipsSubtarget.h"
21#include "InstPrinter/MipsInstPrinter.h"
22#include "MCTargetDesc/MipsBaseInfo.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/CallingConv.h"
28#include "llvm/CodeGen/CallingConvLower.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/SelectionDAGISel.h"
34#include "llvm/CodeGen/ValueTypes.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace llvm;
40
41// If I is a shifted mask, set the size (Size) and the first bit of the
42// mask (Pos), and return true.
43// For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
44static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
45  if (!isShiftedMask_64(I))
46     return false;
47
48  Size = CountPopulation_64(I);
49  Pos = CountTrailingZeros_64(I);
50  return true;
51}
52
53static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
54  MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
55  return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
56}
57
58const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
59  switch (Opcode) {
60  case MipsISD::JmpLink:           return "MipsISD::JmpLink";
61  case MipsISD::Hi:                return "MipsISD::Hi";
62  case MipsISD::Lo:                return "MipsISD::Lo";
63  case MipsISD::GPRel:             return "MipsISD::GPRel";
64  case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
65  case MipsISD::Ret:               return "MipsISD::Ret";
66  case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
67  case MipsISD::FPCmp:             return "MipsISD::FPCmp";
68  case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
69  case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
70  case MipsISD::FPRound:           return "MipsISD::FPRound";
71  case MipsISD::MAdd:              return "MipsISD::MAdd";
72  case MipsISD::MAddu:             return "MipsISD::MAddu";
73  case MipsISD::MSub:              return "MipsISD::MSub";
74  case MipsISD::MSubu:             return "MipsISD::MSubu";
75  case MipsISD::DivRem:            return "MipsISD::DivRem";
76  case MipsISD::DivRemU:           return "MipsISD::DivRemU";
77  case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
78  case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
79  case MipsISD::Wrapper:           return "MipsISD::Wrapper";
80  case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
81  case MipsISD::Sync:              return "MipsISD::Sync";
82  case MipsISD::Ext:               return "MipsISD::Ext";
83  case MipsISD::Ins:               return "MipsISD::Ins";
84  case MipsISD::LWL:               return "MipsISD::LWL";
85  case MipsISD::LWR:               return "MipsISD::LWR";
86  case MipsISD::SWL:               return "MipsISD::SWL";
87  case MipsISD::SWR:               return "MipsISD::SWR";
88  case MipsISD::LDL:               return "MipsISD::LDL";
89  case MipsISD::LDR:               return "MipsISD::LDR";
90  case MipsISD::SDL:               return "MipsISD::SDL";
91  case MipsISD::SDR:               return "MipsISD::SDR";
92  case MipsISD::EXTP:              return "MipsISD::EXTP";
93  case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
94  case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
95  case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
96  case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
97  case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
98  case MipsISD::SHILO:             return "MipsISD::SHILO";
99  case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
100  case MipsISD::MULT:              return "MipsISD::MULT";
101  case MipsISD::MULTU:             return "MipsISD::MULTU";
102  case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSPDSP";
103  case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
104  case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
105  case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
106  default:                         return NULL;
107  }
108}
109
110MipsTargetLowering::
111MipsTargetLowering(MipsTargetMachine &TM)
112  : TargetLowering(TM, new MipsTargetObjectFile()),
113    Subtarget(&TM.getSubtarget<MipsSubtarget>()),
114    HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
115    IsO32(Subtarget->isABI_O32()) {
116
117  // Mips does not have i1 type, so use i32 for
118  // setcc operations results (slt, sgt, ...).
119  setBooleanContents(ZeroOrOneBooleanContent);
120  setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
121
122  // Set up the register classes
123  addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
124
125  if (HasMips64)
126    addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
127
128  if (Subtarget->inMips16Mode()) {
129    addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
130  }
131
132  if (Subtarget->hasDSP()) {
133    MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
134
135    for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
136      addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
137
138      // Expand all builtin opcodes.
139      for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
140        setOperationAction(Opc, VecTys[i], Expand);
141
142      setOperationAction(ISD::LOAD, VecTys[i], Legal);
143      setOperationAction(ISD::STORE, VecTys[i], Legal);
144      setOperationAction(ISD::BITCAST, VecTys[i], Legal);
145    }
146  }
147
148  if (!TM.Options.UseSoftFloat) {
149    addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
150
151    // When dealing with single precision only, use libcalls
152    if (!Subtarget->isSingleFloat()) {
153      if (HasMips64)
154        addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
155      else
156        addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
157    }
158  }
159
160  // Load extented operations for i1 types must be promoted
161  setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
162  setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
163  setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
164
165  // MIPS doesn't have extending float->double load/store
166  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
167  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169  // Used by legalize types to correctly generate the setcc result.
170  // Without this, every float setcc comes with a AND/OR with the result,
171  // we don't want this, since the fpcmp result goes to a flag register,
172  // which is used implicitly by brcond and select operations.
173  AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
174
175  // Mips Custom Operations
176  setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
177  setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
178  setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
179  setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
180  setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
181  setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
182  setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
183  setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
184  setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
185  setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
186  setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
187  setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
188  setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
189  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
190  setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
191  setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
192  setOperationAction(ISD::MEMBARRIER,         MVT::Other, Custom);
193  setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
194  if (!Subtarget->inMips16Mode()) {
195    setOperationAction(ISD::LOAD,               MVT::i32, Custom);
196    setOperationAction(ISD::STORE,              MVT::i32, Custom);
197  }
198
199  if (!TM.Options.NoNaNsFPMath) {
200    setOperationAction(ISD::FABS,             MVT::f32,   Custom);
201    setOperationAction(ISD::FABS,             MVT::f64,   Custom);
202  }
203
204  if (HasMips64) {
205    setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
206    setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
207    setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
208    setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
209    setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
210    setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
211    setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
212    setOperationAction(ISD::STORE,              MVT::i64,   Custom);
213  }
214
215  if (!HasMips64) {
216    setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
217    setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
218    setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
219  }
220
221  setOperationAction(ISD::SDIV, MVT::i32, Expand);
222  setOperationAction(ISD::SREM, MVT::i32, Expand);
223  setOperationAction(ISD::UDIV, MVT::i32, Expand);
224  setOperationAction(ISD::UREM, MVT::i32, Expand);
225  setOperationAction(ISD::SDIV, MVT::i64, Expand);
226  setOperationAction(ISD::SREM, MVT::i64, Expand);
227  setOperationAction(ISD::UDIV, MVT::i64, Expand);
228  setOperationAction(ISD::UREM, MVT::i64, Expand);
229
230  // Operations not directly supported by Mips.
231  setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
232  setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
233  setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
234  setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
235  setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
236  setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
237  setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
238  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
239  setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
240  setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
241  setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
242  setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
243  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
244  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
245  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
246  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
247  setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
248  setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
249  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
250  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
251
252  if (!Subtarget->hasMips32r2())
253    setOperationAction(ISD::ROTR, MVT::i32,   Expand);
254
255  if (!Subtarget->hasMips64r2())
256    setOperationAction(ISD::ROTR, MVT::i64,   Expand);
257
258  setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
259  setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
260  setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
261  setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
262  setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
263  setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
264  setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
265  setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
266  setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
267  setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
268  setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
269  setOperationAction(ISD::FMA,               MVT::f32,   Expand);
270  setOperationAction(ISD::FMA,               MVT::f64,   Expand);
271  setOperationAction(ISD::FREM,              MVT::f32,   Expand);
272  setOperationAction(ISD::FREM,              MVT::f64,   Expand);
273
274  if (!TM.Options.NoNaNsFPMath) {
275    setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
276    setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
277  }
278
279  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
280  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i64, Expand);
281  setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
282  setOperationAction(ISD::EHSELECTION,       MVT::i64, Expand);
283
284  setOperationAction(ISD::VAARG,             MVT::Other, Expand);
285  setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
286  setOperationAction(ISD::VAEND,             MVT::Other, Expand);
287
288  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
289  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
290
291  // Use the default for now
292  setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
293  setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
294
295  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
296  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
297  setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
298  setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
299
300  setInsertFencesForAtomic(true);
301
302  if (!Subtarget->hasSEInReg()) {
303    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
304    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
305  }
306
307  if (!Subtarget->hasBitCount()) {
308    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
309    setOperationAction(ISD::CTLZ, MVT::i64, Expand);
310  }
311
312  if (!Subtarget->hasSwap()) {
313    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
314    setOperationAction(ISD::BSWAP, MVT::i64, Expand);
315  }
316
317  if (HasMips64) {
318    setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
319    setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
320    setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
321    setTruncStoreAction(MVT::i64, MVT::i32, Custom);
322  }
323
324  setTargetDAGCombine(ISD::ADDE);
325  setTargetDAGCombine(ISD::SUBE);
326  setTargetDAGCombine(ISD::SDIVREM);
327  setTargetDAGCombine(ISD::UDIVREM);
328  setTargetDAGCombine(ISD::SELECT);
329  setTargetDAGCombine(ISD::AND);
330  setTargetDAGCombine(ISD::OR);
331  setTargetDAGCombine(ISD::ADD);
332
333  setMinFunctionAlignment(HasMips64 ? 3 : 2);
334
335  setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
336  computeRegisterProperties();
337
338  setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
339  setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
340
341  maxStoresPerMemcpy = 16;
342}
343
344bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
345  MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
346
347  if (Subtarget->inMips16Mode())
348    return false;
349
350  switch (SVT) {
351  case MVT::i64:
352  case MVT::i32:
353    return true;
354  default:
355    return false;
356  }
357}
358
359EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
360  return MVT::i32;
361}
362
363// SelectMadd -
364// Transforms a subgraph in CurDAG if the following pattern is found:
365//  (addc multLo, Lo0), (adde multHi, Hi0),
366// where,
367//  multHi/Lo: product of multiplication
368//  Lo0: initial value of Lo register
369//  Hi0: initial value of Hi register
370// Return true if pattern matching was successful.
371static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
372  // ADDENode's second operand must be a flag output of an ADDC node in order
373  // for the matching to be successful.
374  SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
375
376  if (ADDCNode->getOpcode() != ISD::ADDC)
377    return false;
378
379  SDValue MultHi = ADDENode->getOperand(0);
380  SDValue MultLo = ADDCNode->getOperand(0);
381  SDNode *MultNode = MultHi.getNode();
382  unsigned MultOpc = MultHi.getOpcode();
383
384  // MultHi and MultLo must be generated by the same node,
385  if (MultLo.getNode() != MultNode)
386    return false;
387
388  // and it must be a multiplication.
389  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
390    return false;
391
392  // MultLo amd MultHi must be the first and second output of MultNode
393  // respectively.
394  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
395    return false;
396
397  // Transform this to a MADD only if ADDENode and ADDCNode are the only users
398  // of the values of MultNode, in which case MultNode will be removed in later
399  // phases.
400  // If there exist users other than ADDENode or ADDCNode, this function returns
401  // here, which will result in MultNode being mapped to a single MULT
402  // instruction node rather than a pair of MULT and MADD instructions being
403  // produced.
404  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
405    return false;
406
407  SDValue Chain = CurDAG->getEntryNode();
408  DebugLoc dl = ADDENode->getDebugLoc();
409
410  // create MipsMAdd(u) node
411  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
412
413  SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
414                                 MultNode->getOperand(0),// Factor 0
415                                 MultNode->getOperand(1),// Factor 1
416                                 ADDCNode->getOperand(1),// Lo0
417                                 ADDENode->getOperand(1));// Hi0
418
419  // create CopyFromReg nodes
420  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
421                                              MAdd);
422  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
423                                              Mips::HI, MVT::i32,
424                                              CopyFromLo.getValue(2));
425
426  // replace uses of adde and addc here
427  if (!SDValue(ADDCNode, 0).use_empty())
428    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
429
430  if (!SDValue(ADDENode, 0).use_empty())
431    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
432
433  return true;
434}
435
436// SelectMsub -
437// Transforms a subgraph in CurDAG if the following pattern is found:
438//  (addc Lo0, multLo), (sube Hi0, multHi),
439// where,
440//  multHi/Lo: product of multiplication
441//  Lo0: initial value of Lo register
442//  Hi0: initial value of Hi register
443// Return true if pattern matching was successful.
444static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
445  // SUBENode's second operand must be a flag output of an SUBC node in order
446  // for the matching to be successful.
447  SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
448
449  if (SUBCNode->getOpcode() != ISD::SUBC)
450    return false;
451
452  SDValue MultHi = SUBENode->getOperand(1);
453  SDValue MultLo = SUBCNode->getOperand(1);
454  SDNode *MultNode = MultHi.getNode();
455  unsigned MultOpc = MultHi.getOpcode();
456
457  // MultHi and MultLo must be generated by the same node,
458  if (MultLo.getNode() != MultNode)
459    return false;
460
461  // and it must be a multiplication.
462  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
463    return false;
464
465  // MultLo amd MultHi must be the first and second output of MultNode
466  // respectively.
467  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
468    return false;
469
470  // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
471  // of the values of MultNode, in which case MultNode will be removed in later
472  // phases.
473  // If there exist users other than SUBENode or SUBCNode, this function returns
474  // here, which will result in MultNode being mapped to a single MULT
475  // instruction node rather than a pair of MULT and MSUB instructions being
476  // produced.
477  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
478    return false;
479
480  SDValue Chain = CurDAG->getEntryNode();
481  DebugLoc dl = SUBENode->getDebugLoc();
482
483  // create MipsSub(u) node
484  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
485
486  SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
487                                 MultNode->getOperand(0),// Factor 0
488                                 MultNode->getOperand(1),// Factor 1
489                                 SUBCNode->getOperand(0),// Lo0
490                                 SUBENode->getOperand(0));// Hi0
491
492  // create CopyFromReg nodes
493  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
494                                              MSub);
495  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
496                                              Mips::HI, MVT::i32,
497                                              CopyFromLo.getValue(2));
498
499  // replace uses of sube and subc here
500  if (!SDValue(SUBCNode, 0).use_empty())
501    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
502
503  if (!SDValue(SUBENode, 0).use_empty())
504    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
505
506  return true;
507}
508
509static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
510                                  TargetLowering::DAGCombinerInfo &DCI,
511                                  const MipsSubtarget *Subtarget) {
512  if (DCI.isBeforeLegalize())
513    return SDValue();
514
515  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
516      SelectMadd(N, &DAG))
517    return SDValue(N, 0);
518
519  return SDValue();
520}
521
522static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
523                                  TargetLowering::DAGCombinerInfo &DCI,
524                                  const MipsSubtarget *Subtarget) {
525  if (DCI.isBeforeLegalize())
526    return SDValue();
527
528  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
529      SelectMsub(N, &DAG))
530    return SDValue(N, 0);
531
532  return SDValue();
533}
534
535static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
536                                    TargetLowering::DAGCombinerInfo &DCI,
537                                    const MipsSubtarget *Subtarget) {
538  if (DCI.isBeforeLegalizeOps())
539    return SDValue();
540
541  EVT Ty = N->getValueType(0);
542  unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
543  unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
544  unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
545                                                  MipsISD::DivRemU;
546  DebugLoc dl = N->getDebugLoc();
547
548  SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
549                               N->getOperand(0), N->getOperand(1));
550  SDValue InChain = DAG.getEntryNode();
551  SDValue InGlue = DivRem;
552
553  // insert MFLO
554  if (N->hasAnyUseOfValue(0)) {
555    SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
556                                            InGlue);
557    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
558    InChain = CopyFromLo.getValue(1);
559    InGlue = CopyFromLo.getValue(2);
560  }
561
562  // insert MFHI
563  if (N->hasAnyUseOfValue(1)) {
564    SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
565                                            HI, Ty, InGlue);
566    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
567  }
568
569  return SDValue();
570}
571
572static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
573  switch (CC) {
574  default: llvm_unreachable("Unknown fp condition code!");
575  case ISD::SETEQ:
576  case ISD::SETOEQ: return Mips::FCOND_OEQ;
577  case ISD::SETUNE: return Mips::FCOND_UNE;
578  case ISD::SETLT:
579  case ISD::SETOLT: return Mips::FCOND_OLT;
580  case ISD::SETGT:
581  case ISD::SETOGT: return Mips::FCOND_OGT;
582  case ISD::SETLE:
583  case ISD::SETOLE: return Mips::FCOND_OLE;
584  case ISD::SETGE:
585  case ISD::SETOGE: return Mips::FCOND_OGE;
586  case ISD::SETULT: return Mips::FCOND_ULT;
587  case ISD::SETULE: return Mips::FCOND_ULE;
588  case ISD::SETUGT: return Mips::FCOND_UGT;
589  case ISD::SETUGE: return Mips::FCOND_UGE;
590  case ISD::SETUO:  return Mips::FCOND_UN;
591  case ISD::SETO:   return Mips::FCOND_OR;
592  case ISD::SETNE:
593  case ISD::SETONE: return Mips::FCOND_ONE;
594  case ISD::SETUEQ: return Mips::FCOND_UEQ;
595  }
596}
597
598
599// Returns true if condition code has to be inverted.
600static bool InvertFPCondCode(Mips::CondCode CC) {
601  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
602    return false;
603
604  assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
605         "Illegal Condition Code");
606
607  return true;
608}
609
610// Creates and returns an FPCmp node from a setcc node.
611// Returns Op if setcc is not a floating point comparison.
612static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
613  // must be a SETCC node
614  if (Op.getOpcode() != ISD::SETCC)
615    return Op;
616
617  SDValue LHS = Op.getOperand(0);
618
619  if (!LHS.getValueType().isFloatingPoint())
620    return Op;
621
622  SDValue RHS = Op.getOperand(1);
623  DebugLoc dl = Op.getDebugLoc();
624
625  // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
626  // node if necessary.
627  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
628
629  return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
630                     DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
631}
632
633// Creates and returns a CMovFPT/F node.
634static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
635                            SDValue False, DebugLoc DL) {
636  bool invert = InvertFPCondCode((Mips::CondCode)
637                                 cast<ConstantSDNode>(Cond.getOperand(2))
638                                 ->getSExtValue());
639
640  return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
641                     True.getValueType(), True, False, Cond);
642}
643
644static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
645                                    TargetLowering::DAGCombinerInfo &DCI,
646                                    const MipsSubtarget *Subtarget) {
647  if (DCI.isBeforeLegalizeOps())
648    return SDValue();
649
650  SDValue SetCC = N->getOperand(0);
651
652  if ((SetCC.getOpcode() != ISD::SETCC) ||
653      !SetCC.getOperand(0).getValueType().isInteger())
654    return SDValue();
655
656  SDValue False = N->getOperand(2);
657  EVT FalseTy = False.getValueType();
658
659  if (!FalseTy.isInteger())
660    return SDValue();
661
662  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
663
664  if (!CN || CN->getZExtValue())
665    return SDValue();
666
667  const DebugLoc DL = N->getDebugLoc();
668  ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
669  SDValue True = N->getOperand(1);
670
671  SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
672                       SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
673
674  return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
675}
676
677static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
678                                 TargetLowering::DAGCombinerInfo &DCI,
679                                 const MipsSubtarget *Subtarget) {
680  // Pattern match EXT.
681  //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
682  //  => ext $dst, $src, size, pos
683  if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
684    return SDValue();
685
686  SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
687  unsigned ShiftRightOpc = ShiftRight.getOpcode();
688
689  // Op's first operand must be a shift right.
690  if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
691    return SDValue();
692
693  // The second operand of the shift must be an immediate.
694  ConstantSDNode *CN;
695  if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
696    return SDValue();
697
698  uint64_t Pos = CN->getZExtValue();
699  uint64_t SMPos, SMSize;
700
701  // Op's second operand must be a shifted mask.
702  if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
703      !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
704    return SDValue();
705
706  // Return if the shifted mask does not start at bit 0 or the sum of its size
707  // and Pos exceeds the word's size.
708  EVT ValTy = N->getValueType(0);
709  if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
710    return SDValue();
711
712  return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
713                     ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
714                     DAG.getConstant(SMSize, MVT::i32));
715}
716
717static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
718                                TargetLowering::DAGCombinerInfo &DCI,
719                                const MipsSubtarget *Subtarget) {
720  // Pattern match INS.
721  //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
722  //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
723  //  => ins $dst, $src, size, pos, $src1
724  if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
725    return SDValue();
726
727  SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
728  uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
729  ConstantSDNode *CN;
730
731  // See if Op's first operand matches (and $src1 , mask0).
732  if (And0.getOpcode() != ISD::AND)
733    return SDValue();
734
735  if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
736      !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
737    return SDValue();
738
739  // See if Op's second operand matches (and (shl $src, pos), mask1).
740  if (And1.getOpcode() != ISD::AND)
741    return SDValue();
742
743  if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
744      !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
745    return SDValue();
746
747  // The shift masks must have the same position and size.
748  if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
749    return SDValue();
750
751  SDValue Shl = And1.getOperand(0);
752  if (Shl.getOpcode() != ISD::SHL)
753    return SDValue();
754
755  if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
756    return SDValue();
757
758  unsigned Shamt = CN->getZExtValue();
759
760  // Return if the shift amount and the first bit position of mask are not the
761  // same.
762  EVT ValTy = N->getValueType(0);
763  if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
764    return SDValue();
765
766  return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
767                     DAG.getConstant(SMPos0, MVT::i32),
768                     DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
769}
770
771static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
772                                 TargetLowering::DAGCombinerInfo &DCI,
773                                 const MipsSubtarget *Subtarget) {
774  // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
775
776  if (DCI.isBeforeLegalizeOps())
777    return SDValue();
778
779  SDValue Add = N->getOperand(1);
780
781  if (Add.getOpcode() != ISD::ADD)
782    return SDValue();
783
784  SDValue Lo = Add.getOperand(1);
785
786  if ((Lo.getOpcode() != MipsISD::Lo) ||
787      (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
788    return SDValue();
789
790  EVT ValTy = N->getValueType(0);
791  DebugLoc DL = N->getDebugLoc();
792
793  SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
794                             Add.getOperand(0));
795  return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
796}
797
798SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
799  const {
800  SelectionDAG &DAG = DCI.DAG;
801  unsigned opc = N->getOpcode();
802
803  switch (opc) {
804  default: break;
805  case ISD::ADDE:
806    return PerformADDECombine(N, DAG, DCI, Subtarget);
807  case ISD::SUBE:
808    return PerformSUBECombine(N, DAG, DCI, Subtarget);
809  case ISD::SDIVREM:
810  case ISD::UDIVREM:
811    return PerformDivRemCombine(N, DAG, DCI, Subtarget);
812  case ISD::SELECT:
813    return PerformSELECTCombine(N, DAG, DCI, Subtarget);
814  case ISD::AND:
815    return PerformANDCombine(N, DAG, DCI, Subtarget);
816  case ISD::OR:
817    return PerformORCombine(N, DAG, DCI, Subtarget);
818  case ISD::ADD:
819    return PerformADDCombine(N, DAG, DCI, Subtarget);
820  }
821
822  return SDValue();
823}
824
825void
826MipsTargetLowering::LowerOperationWrapper(SDNode *N,
827                                          SmallVectorImpl<SDValue> &Results,
828                                          SelectionDAG &DAG) const {
829  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
830
831  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
832    Results.push_back(Res.getValue(I));
833}
834
835void
836MipsTargetLowering::ReplaceNodeResults(SDNode *N,
837                                       SmallVectorImpl<SDValue> &Results,
838                                       SelectionDAG &DAG) const {
839  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
840
841  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
842    Results.push_back(Res.getValue(I));
843}
844
845SDValue MipsTargetLowering::
846LowerOperation(SDValue Op, SelectionDAG &DAG) const
847{
848  switch (Op.getOpcode())
849  {
850    case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
851    case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
852    case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
853    case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
854    case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
855    case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
856    case ISD::SELECT:             return LowerSELECT(Op, DAG);
857    case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
858    case ISD::SETCC:              return LowerSETCC(Op, DAG);
859    case ISD::VASTART:            return LowerVASTART(Op, DAG);
860    case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
861    case ISD::FABS:               return LowerFABS(Op, DAG);
862    case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
863    case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
864    case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
865    case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
866    case ISD::SHL_PARTS:          return LowerShiftLeftParts(Op, DAG);
867    case ISD::SRA_PARTS:          return LowerShiftRightParts(Op, DAG, true);
868    case ISD::SRL_PARTS:          return LowerShiftRightParts(Op, DAG, false);
869    case ISD::LOAD:               return LowerLOAD(Op, DAG);
870    case ISD::STORE:              return LowerSTORE(Op, DAG);
871    case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
872    case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
873  }
874  return SDValue();
875}
876
877//===----------------------------------------------------------------------===//
878//  Lower helper functions
879//===----------------------------------------------------------------------===//
880
881// AddLiveIn - This helper function adds the specified physical register to the
882// MachineFunction as a live in value.  It also creates a corresponding
883// virtual register for it.
884static unsigned
885AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
886{
887  assert(RC->contains(PReg) && "Not the correct regclass!");
888  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
889  MF.getRegInfo().addLiveIn(PReg, VReg);
890  return VReg;
891}
892
893// Get fp branch code (not opcode) from condition code.
894static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
895  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
896    return Mips::BRANCH_T;
897
898  assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
899         "Invalid CondCode.");
900
901  return Mips::BRANCH_F;
902}
903
904/*
905static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
906                                        DebugLoc dl,
907                                        const MipsSubtarget *Subtarget,
908                                        const TargetInstrInfo *TII,
909                                        bool isFPCmp, unsigned Opc) {
910  // There is no need to expand CMov instructions if target has
911  // conditional moves.
912  if (Subtarget->hasCondMov())
913    return BB;
914
915  // To "insert" a SELECT_CC instruction, we actually have to insert the
916  // diamond control-flow pattern.  The incoming instruction knows the
917  // destination vreg to set, the condition code register to branch on, the
918  // true/false values to select between, and a branch opcode to use.
919  const BasicBlock *LLVM_BB = BB->getBasicBlock();
920  MachineFunction::iterator It = BB;
921  ++It;
922
923  //  thisMBB:
924  //  ...
925  //   TrueVal = ...
926  //   setcc r1, r2, r3
927  //   bNE   r1, r0, copy1MBB
928  //   fallthrough --> copy0MBB
929  MachineBasicBlock *thisMBB  = BB;
930  MachineFunction *F = BB->getParent();
931  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
932  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
933  F->insert(It, copy0MBB);
934  F->insert(It, sinkMBB);
935
936  // Transfer the remainder of BB and its successor edges to sinkMBB.
937  sinkMBB->splice(sinkMBB->begin(), BB,
938                  llvm::next(MachineBasicBlock::iterator(MI)),
939                  BB->end());
940  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
941
942  // Next, add the true and fallthrough blocks as its successors.
943  BB->addSuccessor(copy0MBB);
944  BB->addSuccessor(sinkMBB);
945
946  // Emit the right instruction according to the type of the operands compared
947  if (isFPCmp)
948    BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
949  else
950    BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
951      .addReg(Mips::ZERO).addMBB(sinkMBB);
952
953  //  copy0MBB:
954  //   %FalseValue = ...
955  //   # fallthrough to sinkMBB
956  BB = copy0MBB;
957
958  // Update machine-CFG edges
959  BB->addSuccessor(sinkMBB);
960
961  //  sinkMBB:
962  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
963  //  ...
964  BB = sinkMBB;
965
966  if (isFPCmp)
967    BuildMI(*BB, BB->begin(), dl,
968            TII->get(Mips::PHI), MI->getOperand(0).getReg())
969      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
970      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
971  else
972    BuildMI(*BB, BB->begin(), dl,
973            TII->get(Mips::PHI), MI->getOperand(0).getReg())
974      .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
975      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
976
977  MI->eraseFromParent();   // The pseudo instruction is gone now.
978  return BB;
979}
980*/
981MachineBasicBlock *
982MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
983                                                MachineBasicBlock *BB) const {
984  switch (MI->getOpcode()) {
985  default: llvm_unreachable("Unexpected instr type to insert");
986  case Mips::ATOMIC_LOAD_ADD_I8:
987  case Mips::ATOMIC_LOAD_ADD_I8_P8:
988    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
989  case Mips::ATOMIC_LOAD_ADD_I16:
990  case Mips::ATOMIC_LOAD_ADD_I16_P8:
991    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
992  case Mips::ATOMIC_LOAD_ADD_I32:
993  case Mips::ATOMIC_LOAD_ADD_I32_P8:
994    return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
995  case Mips::ATOMIC_LOAD_ADD_I64:
996  case Mips::ATOMIC_LOAD_ADD_I64_P8:
997    return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
998
999  case Mips::ATOMIC_LOAD_AND_I8:
1000  case Mips::ATOMIC_LOAD_AND_I8_P8:
1001    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1002  case Mips::ATOMIC_LOAD_AND_I16:
1003  case Mips::ATOMIC_LOAD_AND_I16_P8:
1004    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1005  case Mips::ATOMIC_LOAD_AND_I32:
1006  case Mips::ATOMIC_LOAD_AND_I32_P8:
1007    return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1008  case Mips::ATOMIC_LOAD_AND_I64:
1009  case Mips::ATOMIC_LOAD_AND_I64_P8:
1010    return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1011
1012  case Mips::ATOMIC_LOAD_OR_I8:
1013  case Mips::ATOMIC_LOAD_OR_I8_P8:
1014    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1015  case Mips::ATOMIC_LOAD_OR_I16:
1016  case Mips::ATOMIC_LOAD_OR_I16_P8:
1017    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1018  case Mips::ATOMIC_LOAD_OR_I32:
1019  case Mips::ATOMIC_LOAD_OR_I32_P8:
1020    return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1021  case Mips::ATOMIC_LOAD_OR_I64:
1022  case Mips::ATOMIC_LOAD_OR_I64_P8:
1023    return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1024
1025  case Mips::ATOMIC_LOAD_XOR_I8:
1026  case Mips::ATOMIC_LOAD_XOR_I8_P8:
1027    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1028  case Mips::ATOMIC_LOAD_XOR_I16:
1029  case Mips::ATOMIC_LOAD_XOR_I16_P8:
1030    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1031  case Mips::ATOMIC_LOAD_XOR_I32:
1032  case Mips::ATOMIC_LOAD_XOR_I32_P8:
1033    return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1034  case Mips::ATOMIC_LOAD_XOR_I64:
1035  case Mips::ATOMIC_LOAD_XOR_I64_P8:
1036    return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1037
1038  case Mips::ATOMIC_LOAD_NAND_I8:
1039  case Mips::ATOMIC_LOAD_NAND_I8_P8:
1040    return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1041  case Mips::ATOMIC_LOAD_NAND_I16:
1042  case Mips::ATOMIC_LOAD_NAND_I16_P8:
1043    return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1044  case Mips::ATOMIC_LOAD_NAND_I32:
1045  case Mips::ATOMIC_LOAD_NAND_I32_P8:
1046    return EmitAtomicBinary(MI, BB, 4, 0, true);
1047  case Mips::ATOMIC_LOAD_NAND_I64:
1048  case Mips::ATOMIC_LOAD_NAND_I64_P8:
1049    return EmitAtomicBinary(MI, BB, 8, 0, true);
1050
1051  case Mips::ATOMIC_LOAD_SUB_I8:
1052  case Mips::ATOMIC_LOAD_SUB_I8_P8:
1053    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1054  case Mips::ATOMIC_LOAD_SUB_I16:
1055  case Mips::ATOMIC_LOAD_SUB_I16_P8:
1056    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1057  case Mips::ATOMIC_LOAD_SUB_I32:
1058  case Mips::ATOMIC_LOAD_SUB_I32_P8:
1059    return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1060  case Mips::ATOMIC_LOAD_SUB_I64:
1061  case Mips::ATOMIC_LOAD_SUB_I64_P8:
1062    return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1063
1064  case Mips::ATOMIC_SWAP_I8:
1065  case Mips::ATOMIC_SWAP_I8_P8:
1066    return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1067  case Mips::ATOMIC_SWAP_I16:
1068  case Mips::ATOMIC_SWAP_I16_P8:
1069    return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1070  case Mips::ATOMIC_SWAP_I32:
1071  case Mips::ATOMIC_SWAP_I32_P8:
1072    return EmitAtomicBinary(MI, BB, 4, 0);
1073  case Mips::ATOMIC_SWAP_I64:
1074  case Mips::ATOMIC_SWAP_I64_P8:
1075    return EmitAtomicBinary(MI, BB, 8, 0);
1076
1077  case Mips::ATOMIC_CMP_SWAP_I8:
1078  case Mips::ATOMIC_CMP_SWAP_I8_P8:
1079    return EmitAtomicCmpSwapPartword(MI, BB, 1);
1080  case Mips::ATOMIC_CMP_SWAP_I16:
1081  case Mips::ATOMIC_CMP_SWAP_I16_P8:
1082    return EmitAtomicCmpSwapPartword(MI, BB, 2);
1083  case Mips::ATOMIC_CMP_SWAP_I32:
1084  case Mips::ATOMIC_CMP_SWAP_I32_P8:
1085    return EmitAtomicCmpSwap(MI, BB, 4);
1086  case Mips::ATOMIC_CMP_SWAP_I64:
1087  case Mips::ATOMIC_CMP_SWAP_I64_P8:
1088    return EmitAtomicCmpSwap(MI, BB, 8);
1089  }
1090}
1091
1092// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1093// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1094MachineBasicBlock *
1095MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1096                                     unsigned Size, unsigned BinOpcode,
1097                                     bool Nand) const {
1098  assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1099
1100  MachineFunction *MF = BB->getParent();
1101  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1102  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1103  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1104  DebugLoc dl = MI->getDebugLoc();
1105  unsigned LL, SC, AND, NOR, ZERO, BEQ;
1106
1107  if (Size == 4) {
1108    LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1109    SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1110    AND = Mips::AND;
1111    NOR = Mips::NOR;
1112    ZERO = Mips::ZERO;
1113    BEQ = Mips::BEQ;
1114  }
1115  else {
1116    LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1117    SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1118    AND = Mips::AND64;
1119    NOR = Mips::NOR64;
1120    ZERO = Mips::ZERO_64;
1121    BEQ = Mips::BEQ64;
1122  }
1123
1124  unsigned OldVal = MI->getOperand(0).getReg();
1125  unsigned Ptr = MI->getOperand(1).getReg();
1126  unsigned Incr = MI->getOperand(2).getReg();
1127
1128  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1129  unsigned AndRes = RegInfo.createVirtualRegister(RC);
1130  unsigned Success = RegInfo.createVirtualRegister(RC);
1131
1132  // insert new blocks after the current block
1133  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1134  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1135  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1136  MachineFunction::iterator It = BB;
1137  ++It;
1138  MF->insert(It, loopMBB);
1139  MF->insert(It, exitMBB);
1140
1141  // Transfer the remainder of BB and its successor edges to exitMBB.
1142  exitMBB->splice(exitMBB->begin(), BB,
1143                  llvm::next(MachineBasicBlock::iterator(MI)),
1144                  BB->end());
1145  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1146
1147  //  thisMBB:
1148  //    ...
1149  //    fallthrough --> loopMBB
1150  BB->addSuccessor(loopMBB);
1151  loopMBB->addSuccessor(loopMBB);
1152  loopMBB->addSuccessor(exitMBB);
1153
1154  //  loopMBB:
1155  //    ll oldval, 0(ptr)
1156  //    <binop> storeval, oldval, incr
1157  //    sc success, storeval, 0(ptr)
1158  //    beq success, $0, loopMBB
1159  BB = loopMBB;
1160  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1161  if (Nand) {
1162    //  and andres, oldval, incr
1163    //  nor storeval, $0, andres
1164    BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1165    BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1166  } else if (BinOpcode) {
1167    //  <binop> storeval, oldval, incr
1168    BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1169  } else {
1170    StoreVal = Incr;
1171  }
1172  BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1173  BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1174
1175  MI->eraseFromParent();   // The instruction is gone now.
1176
1177  return exitMBB;
1178}
1179
1180MachineBasicBlock *
1181MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1182                                             MachineBasicBlock *BB,
1183                                             unsigned Size, unsigned BinOpcode,
1184                                             bool Nand) const {
1185  assert((Size == 1 || Size == 2) &&
1186      "Unsupported size for EmitAtomicBinaryPartial.");
1187
1188  MachineFunction *MF = BB->getParent();
1189  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1190  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1191  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1192  DebugLoc dl = MI->getDebugLoc();
1193  unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1194  unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1195
1196  unsigned Dest = MI->getOperand(0).getReg();
1197  unsigned Ptr = MI->getOperand(1).getReg();
1198  unsigned Incr = MI->getOperand(2).getReg();
1199
1200  unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1201  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1202  unsigned Mask = RegInfo.createVirtualRegister(RC);
1203  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1204  unsigned NewVal = RegInfo.createVirtualRegister(RC);
1205  unsigned OldVal = RegInfo.createVirtualRegister(RC);
1206  unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1207  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1208  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1209  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1210  unsigned AndRes = RegInfo.createVirtualRegister(RC);
1211  unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1212  unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1213  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1214  unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1215  unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1216  unsigned SllRes = RegInfo.createVirtualRegister(RC);
1217  unsigned Success = RegInfo.createVirtualRegister(RC);
1218
1219  // insert new blocks after the current block
1220  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1221  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1222  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1223  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1224  MachineFunction::iterator It = BB;
1225  ++It;
1226  MF->insert(It, loopMBB);
1227  MF->insert(It, sinkMBB);
1228  MF->insert(It, exitMBB);
1229
1230  // Transfer the remainder of BB and its successor edges to exitMBB.
1231  exitMBB->splice(exitMBB->begin(), BB,
1232                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1233  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1234
1235  BB->addSuccessor(loopMBB);
1236  loopMBB->addSuccessor(loopMBB);
1237  loopMBB->addSuccessor(sinkMBB);
1238  sinkMBB->addSuccessor(exitMBB);
1239
1240  //  thisMBB:
1241  //    addiu   masklsb2,$0,-4                # 0xfffffffc
1242  //    and     alignedaddr,ptr,masklsb2
1243  //    andi    ptrlsb2,ptr,3
1244  //    sll     shiftamt,ptrlsb2,3
1245  //    ori     maskupper,$0,255               # 0xff
1246  //    sll     mask,maskupper,shiftamt
1247  //    nor     mask2,$0,mask
1248  //    sll     incr2,incr,shiftamt
1249
1250  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1251  BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1252    .addReg(Mips::ZERO).addImm(-4);
1253  BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1254    .addReg(Ptr).addReg(MaskLSB2);
1255  BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1256  BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1257  BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1258    .addReg(Mips::ZERO).addImm(MaskImm);
1259  BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1260    .addReg(ShiftAmt).addReg(MaskUpper);
1261  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1262  BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1263
1264  // atomic.load.binop
1265  // loopMBB:
1266  //   ll      oldval,0(alignedaddr)
1267  //   binop   binopres,oldval,incr2
1268  //   and     newval,binopres,mask
1269  //   and     maskedoldval0,oldval,mask2
1270  //   or      storeval,maskedoldval0,newval
1271  //   sc      success,storeval,0(alignedaddr)
1272  //   beq     success,$0,loopMBB
1273
1274  // atomic.swap
1275  // loopMBB:
1276  //   ll      oldval,0(alignedaddr)
1277  //   and     newval,incr2,mask
1278  //   and     maskedoldval0,oldval,mask2
1279  //   or      storeval,maskedoldval0,newval
1280  //   sc      success,storeval,0(alignedaddr)
1281  //   beq     success,$0,loopMBB
1282
1283  BB = loopMBB;
1284  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1285  if (Nand) {
1286    //  and andres, oldval, incr2
1287    //  nor binopres, $0, andres
1288    //  and newval, binopres, mask
1289    BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1290    BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1291      .addReg(Mips::ZERO).addReg(AndRes);
1292    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1293  } else if (BinOpcode) {
1294    //  <binop> binopres, oldval, incr2
1295    //  and newval, binopres, mask
1296    BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1297    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1298  } else {// atomic.swap
1299    //  and newval, incr2, mask
1300    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1301  }
1302
1303  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1304    .addReg(OldVal).addReg(Mask2);
1305  BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1306    .addReg(MaskedOldVal0).addReg(NewVal);
1307  BuildMI(BB, dl, TII->get(SC), Success)
1308    .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1309  BuildMI(BB, dl, TII->get(Mips::BEQ))
1310    .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1311
1312  //  sinkMBB:
1313  //    and     maskedoldval1,oldval,mask
1314  //    srl     srlres,maskedoldval1,shiftamt
1315  //    sll     sllres,srlres,24
1316  //    sra     dest,sllres,24
1317  BB = sinkMBB;
1318  int64_t ShiftImm = (Size == 1) ? 24 : 16;
1319
1320  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1321    .addReg(OldVal).addReg(Mask);
1322  BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1323      .addReg(ShiftAmt).addReg(MaskedOldVal1);
1324  BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1325      .addReg(SrlRes).addImm(ShiftImm);
1326  BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1327      .addReg(SllRes).addImm(ShiftImm);
1328
1329  MI->eraseFromParent();   // The instruction is gone now.
1330
1331  return exitMBB;
1332}
1333
1334MachineBasicBlock *
1335MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1336                                      MachineBasicBlock *BB,
1337                                      unsigned Size) const {
1338  assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1339
1340  MachineFunction *MF = BB->getParent();
1341  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1342  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1343  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1344  DebugLoc dl = MI->getDebugLoc();
1345  unsigned LL, SC, ZERO, BNE, BEQ;
1346
1347  if (Size == 4) {
1348    LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1349    SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1350    ZERO = Mips::ZERO;
1351    BNE = Mips::BNE;
1352    BEQ = Mips::BEQ;
1353  }
1354  else {
1355    LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1356    SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1357    ZERO = Mips::ZERO_64;
1358    BNE = Mips::BNE64;
1359    BEQ = Mips::BEQ64;
1360  }
1361
1362  unsigned Dest    = MI->getOperand(0).getReg();
1363  unsigned Ptr     = MI->getOperand(1).getReg();
1364  unsigned OldVal  = MI->getOperand(2).getReg();
1365  unsigned NewVal  = MI->getOperand(3).getReg();
1366
1367  unsigned Success = RegInfo.createVirtualRegister(RC);
1368
1369  // insert new blocks after the current block
1370  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1371  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1372  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1373  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1374  MachineFunction::iterator It = BB;
1375  ++It;
1376  MF->insert(It, loop1MBB);
1377  MF->insert(It, loop2MBB);
1378  MF->insert(It, exitMBB);
1379
1380  // Transfer the remainder of BB and its successor edges to exitMBB.
1381  exitMBB->splice(exitMBB->begin(), BB,
1382                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1383  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1384
1385  //  thisMBB:
1386  //    ...
1387  //    fallthrough --> loop1MBB
1388  BB->addSuccessor(loop1MBB);
1389  loop1MBB->addSuccessor(exitMBB);
1390  loop1MBB->addSuccessor(loop2MBB);
1391  loop2MBB->addSuccessor(loop1MBB);
1392  loop2MBB->addSuccessor(exitMBB);
1393
1394  // loop1MBB:
1395  //   ll dest, 0(ptr)
1396  //   bne dest, oldval, exitMBB
1397  BB = loop1MBB;
1398  BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1399  BuildMI(BB, dl, TII->get(BNE))
1400    .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1401
1402  // loop2MBB:
1403  //   sc success, newval, 0(ptr)
1404  //   beq success, $0, loop1MBB
1405  BB = loop2MBB;
1406  BuildMI(BB, dl, TII->get(SC), Success)
1407    .addReg(NewVal).addReg(Ptr).addImm(0);
1408  BuildMI(BB, dl, TII->get(BEQ))
1409    .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1410
1411  MI->eraseFromParent();   // The instruction is gone now.
1412
1413  return exitMBB;
1414}
1415
1416MachineBasicBlock *
1417MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1418                                              MachineBasicBlock *BB,
1419                                              unsigned Size) const {
1420  assert((Size == 1 || Size == 2) &&
1421      "Unsupported size for EmitAtomicCmpSwapPartial.");
1422
1423  MachineFunction *MF = BB->getParent();
1424  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1425  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1426  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1427  DebugLoc dl = MI->getDebugLoc();
1428  unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1429  unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1430
1431  unsigned Dest    = MI->getOperand(0).getReg();
1432  unsigned Ptr     = MI->getOperand(1).getReg();
1433  unsigned CmpVal  = MI->getOperand(2).getReg();
1434  unsigned NewVal  = MI->getOperand(3).getReg();
1435
1436  unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1437  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1438  unsigned Mask = RegInfo.createVirtualRegister(RC);
1439  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1440  unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1441  unsigned OldVal = RegInfo.createVirtualRegister(RC);
1442  unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1443  unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1444  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1445  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1446  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1447  unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1448  unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1449  unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1450  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1451  unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1452  unsigned SllRes = RegInfo.createVirtualRegister(RC);
1453  unsigned Success = RegInfo.createVirtualRegister(RC);
1454
1455  // insert new blocks after the current block
1456  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1457  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1458  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1459  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1460  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1461  MachineFunction::iterator It = BB;
1462  ++It;
1463  MF->insert(It, loop1MBB);
1464  MF->insert(It, loop2MBB);
1465  MF->insert(It, sinkMBB);
1466  MF->insert(It, exitMBB);
1467
1468  // Transfer the remainder of BB and its successor edges to exitMBB.
1469  exitMBB->splice(exitMBB->begin(), BB,
1470                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1471  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1472
1473  BB->addSuccessor(loop1MBB);
1474  loop1MBB->addSuccessor(sinkMBB);
1475  loop1MBB->addSuccessor(loop2MBB);
1476  loop2MBB->addSuccessor(loop1MBB);
1477  loop2MBB->addSuccessor(sinkMBB);
1478  sinkMBB->addSuccessor(exitMBB);
1479
1480  // FIXME: computation of newval2 can be moved to loop2MBB.
1481  //  thisMBB:
1482  //    addiu   masklsb2,$0,-4                # 0xfffffffc
1483  //    and     alignedaddr,ptr,masklsb2
1484  //    andi    ptrlsb2,ptr,3
1485  //    sll     shiftamt,ptrlsb2,3
1486  //    ori     maskupper,$0,255               # 0xff
1487  //    sll     mask,maskupper,shiftamt
1488  //    nor     mask2,$0,mask
1489  //    andi    maskedcmpval,cmpval,255
1490  //    sll     shiftedcmpval,maskedcmpval,shiftamt
1491  //    andi    maskednewval,newval,255
1492  //    sll     shiftednewval,maskednewval,shiftamt
1493  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1494  BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1495    .addReg(Mips::ZERO).addImm(-4);
1496  BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1497    .addReg(Ptr).addReg(MaskLSB2);
1498  BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1499  BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1500  BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1501    .addReg(Mips::ZERO).addImm(MaskImm);
1502  BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1503    .addReg(ShiftAmt).addReg(MaskUpper);
1504  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1505  BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1506    .addReg(CmpVal).addImm(MaskImm);
1507  BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1508    .addReg(ShiftAmt).addReg(MaskedCmpVal);
1509  BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1510    .addReg(NewVal).addImm(MaskImm);
1511  BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1512    .addReg(ShiftAmt).addReg(MaskedNewVal);
1513
1514  //  loop1MBB:
1515  //    ll      oldval,0(alginedaddr)
1516  //    and     maskedoldval0,oldval,mask
1517  //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1518  BB = loop1MBB;
1519  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1520  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1521    .addReg(OldVal).addReg(Mask);
1522  BuildMI(BB, dl, TII->get(Mips::BNE))
1523    .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1524
1525  //  loop2MBB:
1526  //    and     maskedoldval1,oldval,mask2
1527  //    or      storeval,maskedoldval1,shiftednewval
1528  //    sc      success,storeval,0(alignedaddr)
1529  //    beq     success,$0,loop1MBB
1530  BB = loop2MBB;
1531  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1532    .addReg(OldVal).addReg(Mask2);
1533  BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1534    .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1535  BuildMI(BB, dl, TII->get(SC), Success)
1536      .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1537  BuildMI(BB, dl, TII->get(Mips::BEQ))
1538      .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1539
1540  //  sinkMBB:
1541  //    srl     srlres,maskedoldval0,shiftamt
1542  //    sll     sllres,srlres,24
1543  //    sra     dest,sllres,24
1544  BB = sinkMBB;
1545  int64_t ShiftImm = (Size == 1) ? 24 : 16;
1546
1547  BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1548      .addReg(ShiftAmt).addReg(MaskedOldVal0);
1549  BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1550      .addReg(SrlRes).addImm(ShiftImm);
1551  BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1552      .addReg(SllRes).addImm(ShiftImm);
1553
1554  MI->eraseFromParent();   // The instruction is gone now.
1555
1556  return exitMBB;
1557}
1558
1559//===----------------------------------------------------------------------===//
1560//  Misc Lower Operation implementation
1561//===----------------------------------------------------------------------===//
1562SDValue MipsTargetLowering::
1563LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1564{
1565  // The first operand is the chain, the second is the condition, the third is
1566  // the block to branch to if the condition is true.
1567  SDValue Chain = Op.getOperand(0);
1568  SDValue Dest = Op.getOperand(2);
1569  DebugLoc dl = Op.getDebugLoc();
1570
1571  SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1572
1573  // Return if flag is not set by a floating point comparison.
1574  if (CondRes.getOpcode() != MipsISD::FPCmp)
1575    return Op;
1576
1577  SDValue CCNode  = CondRes.getOperand(2);
1578  Mips::CondCode CC =
1579    (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1580  SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1581
1582  return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1583                     Dest, CondRes);
1584}
1585
1586SDValue MipsTargetLowering::
1587LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1588{
1589  SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1590
1591  // Return if flag is not set by a floating point comparison.
1592  if (Cond.getOpcode() != MipsISD::FPCmp)
1593    return Op;
1594
1595  return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1596                      Op.getDebugLoc());
1597}
1598
1599SDValue MipsTargetLowering::
1600LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1601{
1602  DebugLoc DL = Op.getDebugLoc();
1603  EVT Ty = Op.getOperand(0).getValueType();
1604  SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1605                             Op.getOperand(0), Op.getOperand(1),
1606                             Op.getOperand(4));
1607
1608  return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1609                     Op.getOperand(3));
1610}
1611
1612SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1613  SDValue Cond = CreateFPCmp(DAG, Op);
1614
1615  assert(Cond.getOpcode() == MipsISD::FPCmp &&
1616         "Floating point operand expected.");
1617
1618  SDValue True  = DAG.getConstant(1, MVT::i32);
1619  SDValue False = DAG.getConstant(0, MVT::i32);
1620
1621  return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1622}
1623
1624SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1625                                               SelectionDAG &DAG) const {
1626  // FIXME there isn't actually debug info here
1627  DebugLoc dl = Op.getDebugLoc();
1628  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1629
1630  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1631    SDVTList VTs = DAG.getVTList(MVT::i32);
1632
1633    const MipsTargetObjectFile &TLOF =
1634      (const MipsTargetObjectFile&)getObjFileLowering();
1635
1636    // %gp_rel relocation
1637    if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1638      SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1639                                              MipsII::MO_GPREL);
1640      SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1641      SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1642      return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1643    }
1644    // %hi/%lo relocation
1645    SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1646                                              MipsII::MO_ABS_HI);
1647    SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1648                                              MipsII::MO_ABS_LO);
1649    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1650    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1651    return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1652  }
1653
1654  EVT ValTy = Op.getValueType();
1655  bool HasGotOfst = (GV->hasInternalLinkage() ||
1656                     (GV->hasLocalLinkage() && !isa<Function>(GV)));
1657  unsigned GotFlag = HasMips64 ?
1658                     (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1659                     (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1660  SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1661  GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1662  SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1663                                MachinePointerInfo(), false, false, false, 0);
1664  // On functions and global targets not internal linked only
1665  // a load from got/GP is necessary for PIC to work.
1666  if (!HasGotOfst)
1667    return ResNode;
1668  SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1669                                            HasMips64 ? MipsII::MO_GOT_OFST :
1670                                                        MipsII::MO_ABS_LO);
1671  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1672  return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1673}
1674
1675SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1676                                              SelectionDAG &DAG) const {
1677  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1678  // FIXME there isn't actually debug info here
1679  DebugLoc dl = Op.getDebugLoc();
1680
1681  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1682    // %hi/%lo relocation
1683    SDValue BAHi = DAG.getTargetBlockAddress(BA, MVT::i32, 0, MipsII::MO_ABS_HI);
1684    SDValue BALo = DAG.getTargetBlockAddress(BA, MVT::i32, 0, MipsII::MO_ABS_LO);
1685    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1686    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1687    return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1688  }
1689
1690  EVT ValTy = Op.getValueType();
1691  unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1692  unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1693  SDValue BAGOTOffset = DAG.getTargetBlockAddress(BA, ValTy, 0, GOTFlag);
1694  BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1695                            GetGlobalReg(DAG, ValTy), BAGOTOffset);
1696  SDValue BALOOffset = DAG.getTargetBlockAddress(BA, ValTy, 0, OFSTFlag);
1697  SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1698                             MachinePointerInfo(), false, false, false, 0);
1699  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1700  return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1701}
1702
1703SDValue MipsTargetLowering::
1704LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1705{
1706  // If the relocation model is PIC, use the General Dynamic TLS Model or
1707  // Local Dynamic TLS model, otherwise use the Initial Exec or
1708  // Local Exec TLS Model.
1709
1710  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1711  DebugLoc dl = GA->getDebugLoc();
1712  const GlobalValue *GV = GA->getGlobal();
1713  EVT PtrVT = getPointerTy();
1714
1715  TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1716
1717  if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1718    // General Dynamic and Local Dynamic TLS Model.
1719    unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1720                                                      : MipsII::MO_TLSGD;
1721
1722    SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1723    SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1724                                   GetGlobalReg(DAG, PtrVT), TGA);
1725    unsigned PtrSize = PtrVT.getSizeInBits();
1726    IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1727
1728    SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1729
1730    ArgListTy Args;
1731    ArgListEntry Entry;
1732    Entry.Node = Argument;
1733    Entry.Ty = PtrTy;
1734    Args.push_back(Entry);
1735
1736    TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1737                  false, false, false, false, 0, CallingConv::C,
1738                  /*isTailCall=*/false, /*doesNotRet=*/false,
1739                  /*isReturnValueUsed=*/true,
1740                  TlsGetAddr, Args, DAG, dl);
1741    std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1742
1743    SDValue Ret = CallResult.first;
1744
1745    if (model != TLSModel::LocalDynamic)
1746      return Ret;
1747
1748    SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1749                                               MipsII::MO_DTPREL_HI);
1750    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1751    SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1752                                               MipsII::MO_DTPREL_LO);
1753    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1754    SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1755    return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1756  }
1757
1758  SDValue Offset;
1759  if (model == TLSModel::InitialExec) {
1760    // Initial Exec TLS Model
1761    SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1762                                             MipsII::MO_GOTTPREL);
1763    TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1764                      TGA);
1765    Offset = DAG.getLoad(PtrVT, dl,
1766                         DAG.getEntryNode(), TGA, MachinePointerInfo(),
1767                         false, false, false, 0);
1768  } else {
1769    // Local Exec TLS Model
1770    assert(model == TLSModel::LocalExec);
1771    SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1772                                               MipsII::MO_TPREL_HI);
1773    SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1774                                               MipsII::MO_TPREL_LO);
1775    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1776    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1777    Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1778  }
1779
1780  SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1781  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1782}
1783
1784SDValue MipsTargetLowering::
1785LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1786{
1787  SDValue HiPart, JTI, JTILo;
1788  // FIXME there isn't actually debug info here
1789  DebugLoc dl = Op.getDebugLoc();
1790  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1791  EVT PtrVT = Op.getValueType();
1792  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1793
1794  if (!IsPIC && !IsN64) {
1795    JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1796    HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1797    JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1798  } else {// Emit Load from Global Pointer
1799    unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1800    unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1801    JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1802    JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1803                      JTI);
1804    HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1805                         MachinePointerInfo(), false, false, false, 0);
1806    JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1807  }
1808
1809  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1810  return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1811}
1812
1813SDValue MipsTargetLowering::
1814LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1815{
1816  SDValue ResNode;
1817  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1818  const Constant *C = N->getConstVal();
1819  // FIXME there isn't actually debug info here
1820  DebugLoc dl = Op.getDebugLoc();
1821
1822  // gp_rel relocation
1823  // FIXME: we should reference the constant pool using small data sections,
1824  // but the asm printer currently doesn't support this feature without
1825  // hacking it. This feature should come soon so we can uncomment the
1826  // stuff below.
1827  //if (IsInSmallSection(C->getType())) {
1828  //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1829  //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1830  //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1831
1832  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1833    SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1834                                             N->getOffset(), MipsII::MO_ABS_HI);
1835    SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1836                                             N->getOffset(), MipsII::MO_ABS_LO);
1837    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1838    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1839    ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1840  } else {
1841    EVT ValTy = Op.getValueType();
1842    unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1843    unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1844    SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1845                                           N->getOffset(), GOTFlag);
1846    CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1847    SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1848                               MachinePointerInfo::getConstantPool(), false,
1849                               false, false, 0);
1850    SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1851                                             N->getOffset(), OFSTFlag);
1852    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1853    ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1854  }
1855
1856  return ResNode;
1857}
1858
1859SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1860  MachineFunction &MF = DAG.getMachineFunction();
1861  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1862
1863  DebugLoc dl = Op.getDebugLoc();
1864  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1865                                 getPointerTy());
1866
1867  // vastart just stores the address of the VarArgsFrameIndex slot into the
1868  // memory location argument.
1869  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1870  return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1871                      MachinePointerInfo(SV), false, false, 0);
1872}
1873
1874static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
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  DebugLoc DL = Op.getDebugLoc();
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 (HasR2) {
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, bool HasR2) {
1920  unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1921  unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1922  EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1923  SDValue Const1 = DAG.getConstant(1, MVT::i32);
1924  DebugLoc DL = Op.getDebugLoc();
1925
1926  // Bitcast to integer nodes.
1927  SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1928  SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1929
1930  if (HasR2) {
1931    // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
1932    // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
1933    SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1934                            DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1935
1936    if (WidthX > WidthY)
1937      E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1938    else if (WidthY > WidthX)
1939      E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1940
1941    SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1942                            DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1943    return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1944  }
1945
1946  // (d)sll SllX, X, 1
1947  // (d)srl SrlX, SllX, 1
1948  // (d)srl SrlY, Y, width(Y)-1
1949  // (d)sll SllY, SrlX, width(Y)-1
1950  // or     Or, SrlX, SllY
1951  SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1952  SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1953  SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1954                             DAG.getConstant(WidthY - 1, MVT::i32));
1955
1956  if (WidthX > WidthY)
1957    SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1958  else if (WidthY > WidthX)
1959    SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1960
1961  SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1962                             DAG.getConstant(WidthX - 1, MVT::i32));
1963  SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1964  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1965}
1966
1967SDValue
1968MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1969  if (Subtarget->hasMips64())
1970    return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1971
1972  return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1973}
1974
1975static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1976  SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1977  DebugLoc DL = Op.getDebugLoc();
1978
1979  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1980  // to i32.
1981  SDValue X = (Op.getValueType() == MVT::f32) ?
1982    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1983    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1984                Const1);
1985
1986  // Clear MSB.
1987  if (HasR2)
1988    Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1989                      DAG.getRegister(Mips::ZERO, MVT::i32),
1990                      DAG.getConstant(31, MVT::i32), Const1, X);
1991  else {
1992    SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1993    Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1994  }
1995
1996  if (Op.getValueType() == MVT::f32)
1997    return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1998
1999  SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2000                             Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2001  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2002}
2003
2004static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2005  SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2006  DebugLoc DL = Op.getDebugLoc();
2007
2008  // Bitcast to integer node.
2009  SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2010
2011  // Clear MSB.
2012  if (HasR2)
2013    Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2014                      DAG.getRegister(Mips::ZERO_64, MVT::i64),
2015                      DAG.getConstant(63, MVT::i32), Const1, X);
2016  else {
2017    SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2018    Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2019  }
2020
2021  return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2022}
2023
2024SDValue
2025MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2026  if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2027    return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2028
2029  return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2030}
2031
2032SDValue MipsTargetLowering::
2033LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2034  // check the depth
2035  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2036         "Frame address can only be determined for current frame.");
2037
2038  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2039  MFI->setFrameAddressIsTaken(true);
2040  EVT VT = Op.getValueType();
2041  DebugLoc dl = Op.getDebugLoc();
2042  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2043                                         IsN64 ? Mips::FP_64 : Mips::FP, VT);
2044  return FrameAddr;
2045}
2046
2047SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2048                                            SelectionDAG &DAG) const {
2049  // check the depth
2050  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2051         "Return address can be determined only for current frame.");
2052
2053  MachineFunction &MF = DAG.getMachineFunction();
2054  MachineFrameInfo *MFI = MF.getFrameInfo();
2055  EVT VT = Op.getValueType();
2056  unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2057  MFI->setReturnAddressIsTaken(true);
2058
2059  // Return RA, which contains the return address. Mark it an implicit live-in.
2060  unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2061  return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2062}
2063
2064// TODO: set SType according to the desired memory barrier behavior.
2065SDValue
2066MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2067  unsigned SType = 0;
2068  DebugLoc dl = Op.getDebugLoc();
2069  return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2070                     DAG.getConstant(SType, MVT::i32));
2071}
2072
2073SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2074                                              SelectionDAG &DAG) const {
2075  // FIXME: Need pseudo-fence for 'singlethread' fences
2076  // FIXME: Set SType for weaker fences where supported/appropriate.
2077  unsigned SType = 0;
2078  DebugLoc dl = Op.getDebugLoc();
2079  return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2080                     DAG.getConstant(SType, MVT::i32));
2081}
2082
2083SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2084                                                SelectionDAG &DAG) const {
2085  DebugLoc DL = Op.getDebugLoc();
2086  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2087  SDValue Shamt = Op.getOperand(2);
2088
2089  // if shamt < 32:
2090  //  lo = (shl lo, shamt)
2091  //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2092  // else:
2093  //  lo = 0
2094  //  hi = (shl lo, shamt[4:0])
2095  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2096                            DAG.getConstant(-1, MVT::i32));
2097  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2098                                      DAG.getConstant(1, MVT::i32));
2099  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2100                                     Not);
2101  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2102  SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2103  SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2104  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2105                             DAG.getConstant(0x20, MVT::i32));
2106  Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2107                   DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2108  Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2109
2110  SDValue Ops[2] = {Lo, Hi};
2111  return DAG.getMergeValues(Ops, 2, DL);
2112}
2113
2114SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2115                                                 bool IsSRA) const {
2116  DebugLoc DL = Op.getDebugLoc();
2117  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2118  SDValue Shamt = Op.getOperand(2);
2119
2120  // if shamt < 32:
2121  //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2122  //  if isSRA:
2123  //    hi = (sra hi, shamt)
2124  //  else:
2125  //    hi = (srl hi, shamt)
2126  // else:
2127  //  if isSRA:
2128  //   lo = (sra hi, shamt[4:0])
2129  //   hi = (sra hi, 31)
2130  //  else:
2131  //   lo = (srl hi, shamt[4:0])
2132  //   hi = 0
2133  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2134                            DAG.getConstant(-1, MVT::i32));
2135  SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2136                                     DAG.getConstant(1, MVT::i32));
2137  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2138  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2139  SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2140  SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2141                                     Hi, Shamt);
2142  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2143                             DAG.getConstant(0x20, MVT::i32));
2144  SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2145                                DAG.getConstant(31, MVT::i32));
2146  Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2147  Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2148                   IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2149                   ShiftRightHi);
2150
2151  SDValue Ops[2] = {Lo, Hi};
2152  return DAG.getMergeValues(Ops, 2, DL);
2153}
2154
2155static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2156                            SDValue Chain, SDValue Src, unsigned Offset) {
2157  SDValue Ptr = LD->getBasePtr();
2158  EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2159  EVT BasePtrVT = Ptr.getValueType();
2160  DebugLoc DL = LD->getDebugLoc();
2161  SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2162
2163  if (Offset)
2164    Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2165                      DAG.getConstant(Offset, BasePtrVT));
2166
2167  SDValue Ops[] = { Chain, Ptr, Src };
2168  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2169                                 LD->getMemOperand());
2170}
2171
2172// Expand an unaligned 32 or 64-bit integer load node.
2173SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2174  LoadSDNode *LD = cast<LoadSDNode>(Op);
2175  EVT MemVT = LD->getMemoryVT();
2176
2177  // Return if load is aligned or if MemVT is neither i32 nor i64.
2178  if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2179      ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2180    return SDValue();
2181
2182  bool IsLittle = Subtarget->isLittle();
2183  EVT VT = Op.getValueType();
2184  ISD::LoadExtType ExtType = LD->getExtensionType();
2185  SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2186
2187  assert((VT == MVT::i32) || (VT == MVT::i64));
2188
2189  // Expand
2190  //  (set dst, (i64 (load baseptr)))
2191  // to
2192  //  (set tmp, (ldl (add baseptr, 7), undef))
2193  //  (set dst, (ldr baseptr, tmp))
2194  if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2195    SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2196                               IsLittle ? 7 : 0);
2197    return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2198                        IsLittle ? 0 : 7);
2199  }
2200
2201  SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2202                             IsLittle ? 3 : 0);
2203  SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2204                             IsLittle ? 0 : 3);
2205
2206  // Expand
2207  //  (set dst, (i32 (load baseptr))) or
2208  //  (set dst, (i64 (sextload baseptr))) or
2209  //  (set dst, (i64 (extload baseptr)))
2210  // to
2211  //  (set tmp, (lwl (add baseptr, 3), undef))
2212  //  (set dst, (lwr baseptr, tmp))
2213  if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2214      (ExtType == ISD::EXTLOAD))
2215    return LWR;
2216
2217  assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2218
2219  // Expand
2220  //  (set dst, (i64 (zextload baseptr)))
2221  // to
2222  //  (set tmp0, (lwl (add baseptr, 3), undef))
2223  //  (set tmp1, (lwr baseptr, tmp0))
2224  //  (set tmp2, (shl tmp1, 32))
2225  //  (set dst, (srl tmp2, 32))
2226  DebugLoc DL = LD->getDebugLoc();
2227  SDValue Const32 = DAG.getConstant(32, MVT::i32);
2228  SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2229  SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2230  SDValue Ops[] = { SRL, LWR.getValue(1) };
2231  return DAG.getMergeValues(Ops, 2, DL);
2232}
2233
2234static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2235                             SDValue Chain, unsigned Offset) {
2236  SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2237  EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2238  DebugLoc DL = SD->getDebugLoc();
2239  SDVTList VTList = DAG.getVTList(MVT::Other);
2240
2241  if (Offset)
2242    Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2243                      DAG.getConstant(Offset, BasePtrVT));
2244
2245  SDValue Ops[] = { Chain, Value, Ptr };
2246  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2247                                 SD->getMemOperand());
2248}
2249
2250// Expand an unaligned 32 or 64-bit integer store node.
2251SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2252  StoreSDNode *SD = cast<StoreSDNode>(Op);
2253  EVT MemVT = SD->getMemoryVT();
2254
2255  // Return if store is aligned or if MemVT is neither i32 nor i64.
2256  if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2257      ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2258    return SDValue();
2259
2260  bool IsLittle = Subtarget->isLittle();
2261  SDValue Value = SD->getValue(), Chain = SD->getChain();
2262  EVT VT = Value.getValueType();
2263
2264  // Expand
2265  //  (store val, baseptr) or
2266  //  (truncstore val, baseptr)
2267  // to
2268  //  (swl val, (add baseptr, 3))
2269  //  (swr val, baseptr)
2270  if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2271    SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2272                                IsLittle ? 3 : 0);
2273    return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2274  }
2275
2276  assert(VT == MVT::i64);
2277
2278  // Expand
2279  //  (store val, baseptr)
2280  // to
2281  //  (sdl val, (add baseptr, 7))
2282  //  (sdr val, baseptr)
2283  SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2284  return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2285}
2286
2287// This function expands mips intrinsic nodes which have 64-bit input operands
2288// or output values.
2289//
2290// out64 = intrinsic-node in64
2291// =>
2292// lo = copy (extract-element (in64, 0))
2293// hi = copy (extract-element (in64, 1))
2294// mips-specific-node
2295// v0 = copy lo
2296// v1 = copy hi
2297// out64 = merge-values (v0, v1)
2298//
2299static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2300                            unsigned Opc, bool HasI64In, bool HasI64Out) {
2301  DebugLoc DL = Op.getDebugLoc();
2302  bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2303  SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2304  SmallVector<SDValue, 3> Ops;
2305
2306  if (HasI64In) {
2307    SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2308                               Op->getOperand(1 + HasChainIn),
2309                               DAG.getConstant(0, MVT::i32));
2310    SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2311                               Op->getOperand(1 + HasChainIn),
2312                               DAG.getConstant(1, MVT::i32));
2313
2314    Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2315    Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2316
2317    Ops.push_back(Chain);
2318    Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2319    Ops.push_back(Chain.getValue(1));
2320  } else {
2321    Ops.push_back(Chain);
2322    Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2323  }
2324
2325  if (!HasI64Out)
2326    return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2327                       Ops.begin(), Ops.size());
2328
2329  SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2330                             Ops.begin(), Ops.size());
2331  SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2332                                     Intr.getValue(1));
2333  SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2334                                     OutLo.getValue(2));
2335  SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2336
2337  if (!HasChainIn)
2338    return Out;
2339
2340  SDValue Vals[] = { Out, OutHi.getValue(1) };
2341  return DAG.getMergeValues(Vals, 2, DL);
2342}
2343
2344SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2345                                                    SelectionDAG &DAG) const {
2346  switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2347  default:
2348    return SDValue();
2349  }
2350}
2351
2352SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2353                                                   SelectionDAG &DAG) const {
2354  switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2355  default:
2356    return SDValue();
2357  case Intrinsic::mips_extp:
2358    return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2359  case Intrinsic::mips_extpdp:
2360    return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2361  case Intrinsic::mips_extr_w:
2362    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2363  case Intrinsic::mips_extr_r_w:
2364    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2365  case Intrinsic::mips_extr_rs_w:
2366    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2367  case Intrinsic::mips_extr_s_h:
2368    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2369  }
2370}
2371
2372//===----------------------------------------------------------------------===//
2373//                      Calling Convention Implementation
2374//===----------------------------------------------------------------------===//
2375
2376//===----------------------------------------------------------------------===//
2377// TODO: Implement a generic logic using tblgen that can support this.
2378// Mips O32 ABI rules:
2379// ---
2380// i32 - Passed in A0, A1, A2, A3 and stack
2381// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2382//       an argument. Otherwise, passed in A1, A2, A3 and stack.
2383// f64 - Only passed in two aliased f32 registers if no int reg has been used
2384//       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2385//       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2386//       go to stack.
2387//
2388//  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2389//===----------------------------------------------------------------------===//
2390
2391static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2392                       MVT LocVT, CCValAssign::LocInfo LocInfo,
2393                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
2394
2395  static const unsigned IntRegsSize=4, FloatRegsSize=2;
2396
2397  static const uint16_t IntRegs[] = {
2398      Mips::A0, Mips::A1, Mips::A2, Mips::A3
2399  };
2400  static const uint16_t F32Regs[] = {
2401      Mips::F12, Mips::F14
2402  };
2403  static const uint16_t F64Regs[] = {
2404      Mips::D6, Mips::D7
2405  };
2406
2407  // ByVal Args
2408  if (ArgFlags.isByVal()) {
2409    State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2410                      1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2411    unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2412    for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2413         r < std::min(IntRegsSize, NextReg); ++r)
2414      State.AllocateReg(IntRegs[r]);
2415    return false;
2416  }
2417
2418  // Promote i8 and i16
2419  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2420    LocVT = MVT::i32;
2421    if (ArgFlags.isSExt())
2422      LocInfo = CCValAssign::SExt;
2423    else if (ArgFlags.isZExt())
2424      LocInfo = CCValAssign::ZExt;
2425    else
2426      LocInfo = CCValAssign::AExt;
2427  }
2428
2429  unsigned Reg;
2430
2431  // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2432  // is true: function is vararg, argument is 3rd or higher, there is previous
2433  // argument which is not f32 or f64.
2434  bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2435      || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2436  unsigned OrigAlign = ArgFlags.getOrigAlign();
2437  bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2438
2439  if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2440    Reg = State.AllocateReg(IntRegs, IntRegsSize);
2441    // If this is the first part of an i64 arg,
2442    // the allocated register must be either A0 or A2.
2443    if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2444      Reg = State.AllocateReg(IntRegs, IntRegsSize);
2445    LocVT = MVT::i32;
2446  } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2447    // Allocate int register and shadow next int register. If first
2448    // available register is Mips::A1 or Mips::A3, shadow it too.
2449    Reg = State.AllocateReg(IntRegs, IntRegsSize);
2450    if (Reg == Mips::A1 || Reg == Mips::A3)
2451      Reg = State.AllocateReg(IntRegs, IntRegsSize);
2452    State.AllocateReg(IntRegs, IntRegsSize);
2453    LocVT = MVT::i32;
2454  } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2455    // we are guaranteed to find an available float register
2456    if (ValVT == MVT::f32) {
2457      Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2458      // Shadow int register
2459      State.AllocateReg(IntRegs, IntRegsSize);
2460    } else {
2461      Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2462      // Shadow int registers
2463      unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2464      if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2465        State.AllocateReg(IntRegs, IntRegsSize);
2466      State.AllocateReg(IntRegs, IntRegsSize);
2467    }
2468  } else
2469    llvm_unreachable("Cannot handle this ValVT.");
2470
2471  unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2472  unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2473
2474  if (!Reg)
2475    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2476  else
2477    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2478
2479  return false; // CC must always match
2480}
2481
2482static const uint16_t Mips64IntRegs[8] =
2483  {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2484   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2485static const uint16_t Mips64DPRegs[8] =
2486  {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2487   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2488
2489static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2490                           CCValAssign::LocInfo LocInfo,
2491                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
2492  unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2493  unsigned Size  = (ArgFlags.getByValSize() + 7) / 8 * 8;
2494  unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2495
2496  assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2497
2498  // If byval is 16-byte aligned, the first arg register must be even.
2499  if ((Align == 16) && (FirstIdx % 2)) {
2500    State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2501    ++FirstIdx;
2502  }
2503
2504  // Mark the registers allocated.
2505  for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2506    State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2507
2508  // Allocate space on caller's stack.
2509  unsigned Offset = State.AllocateStack(Size, Align);
2510
2511  if (FirstIdx < 8)
2512    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2513                                     LocVT, LocInfo));
2514  else
2515    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2516
2517  return true;
2518}
2519
2520#include "MipsGenCallingConv.inc"
2521
2522static void
2523AnalyzeMips64CallOperands(CCState &CCInfo,
2524                          const SmallVectorImpl<ISD::OutputArg> &Outs) {
2525  unsigned NumOps = Outs.size();
2526  for (unsigned i = 0; i != NumOps; ++i) {
2527    MVT ArgVT = Outs[i].VT;
2528    ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2529    bool R;
2530
2531    if (Outs[i].IsFixed)
2532      R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2533    else
2534      R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2535
2536    if (R) {
2537#ifndef NDEBUG
2538      dbgs() << "Call operand #" << i << " has unhandled type "
2539             << EVT(ArgVT).getEVTString();
2540#endif
2541      llvm_unreachable(0);
2542    }
2543  }
2544}
2545
2546//===----------------------------------------------------------------------===//
2547//                  Call Calling Convention Implementation
2548//===----------------------------------------------------------------------===//
2549
2550static const unsigned O32IntRegsSize = 4;
2551
2552static const uint16_t O32IntRegs[] = {
2553  Mips::A0, Mips::A1, Mips::A2, Mips::A3
2554};
2555
2556// Return next O32 integer argument register.
2557static unsigned getNextIntArgReg(unsigned Reg) {
2558  assert((Reg == Mips::A0) || (Reg == Mips::A2));
2559  return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2560}
2561
2562// Write ByVal Arg to arg registers and stack.
2563static void
2564WriteByValArg(SDValue Chain, DebugLoc dl,
2565              SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2566              SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
2567              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2568              const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2569              MVT PtrType, bool isLittle) {
2570  unsigned LocMemOffset = VA.getLocMemOffset();
2571  unsigned Offset = 0;
2572  uint32_t RemainingSize = Flags.getByValSize();
2573  unsigned ByValAlign = Flags.getByValAlign();
2574
2575  // Copy the first 4 words of byval arg to registers A0 - A3.
2576  // FIXME: Use a stricter alignment if it enables better optimization in passes
2577  //        run later.
2578  for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2579       Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2580    SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2581                                  DAG.getConstant(Offset, MVT::i32));
2582    SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2583                                  MachinePointerInfo(), false, false, false,
2584                                  std::min(ByValAlign, (unsigned )4));
2585    MemOpChains.push_back(LoadVal.getValue(1));
2586    unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2587    RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2588  }
2589
2590  if (RemainingSize == 0)
2591    return;
2592
2593  // If there still is a register available for argument passing, write the
2594  // remaining part of the structure to it using subword loads and shifts.
2595  if (LocMemOffset < 4 * 4) {
2596    assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2597           "There must be one to three bytes remaining.");
2598    unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2599    SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2600                                  DAG.getConstant(Offset, MVT::i32));
2601    unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2602    SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2603                                     LoadPtr, MachinePointerInfo(),
2604                                     MVT::getIntegerVT(LoadSize * 8), false,
2605                                     false, Alignment);
2606    MemOpChains.push_back(LoadVal.getValue(1));
2607
2608    // If target is big endian, shift it to the most significant half-word or
2609    // byte.
2610    if (!isLittle)
2611      LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2612                            DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2613
2614    Offset += LoadSize;
2615    RemainingSize -= LoadSize;
2616
2617    // Read second subword if necessary.
2618    if (RemainingSize != 0)  {
2619      assert(RemainingSize == 1 && "There must be one byte remaining.");
2620      LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2621                            DAG.getConstant(Offset, MVT::i32));
2622      unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2623      SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2624                                       LoadPtr, MachinePointerInfo(),
2625                                       MVT::i8, false, false, Alignment);
2626      MemOpChains.push_back(Subword.getValue(1));
2627      // Insert the loaded byte to LoadVal.
2628      // FIXME: Use INS if supported by target.
2629      unsigned ShiftAmt = isLittle ? 16 : 8;
2630      SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2631                                  DAG.getConstant(ShiftAmt, MVT::i32));
2632      LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2633    }
2634
2635    unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2636    RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2637    return;
2638  }
2639
2640  // Copy remaining part of byval arg using memcpy.
2641  SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2642                            DAG.getConstant(Offset, MVT::i32));
2643  SDValue Dst = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr,
2644                            DAG.getIntPtrConstant(LocMemOffset));
2645  Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
2646                        DAG.getConstant(RemainingSize, MVT::i32),
2647                        std::min(ByValAlign, (unsigned)4),
2648                        /*isVolatile=*/false, /*AlwaysInline=*/false,
2649                        MachinePointerInfo(0), MachinePointerInfo(0));
2650  MemOpChains.push_back(Chain);
2651}
2652
2653// Copy Mips64 byVal arg to registers and stack.
2654void static
2655PassByValArg64(SDValue Chain, DebugLoc dl,
2656               SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2657               SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
2658               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2659               const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2660               EVT PtrTy, bool isLittle) {
2661  unsigned ByValSize = Flags.getByValSize();
2662  unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2663  bool IsRegLoc = VA.isRegLoc();
2664  unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2665  unsigned LocMemOffset = 0;
2666  unsigned MemCpySize = ByValSize;
2667
2668  if (!IsRegLoc)
2669    LocMemOffset = VA.getLocMemOffset();
2670  else {
2671    const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2672                                    VA.getLocReg());
2673    const uint16_t *RegEnd = Mips64IntRegs + 8;
2674
2675    // Copy double words to registers.
2676    for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2677      SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2678                                    DAG.getConstant(Offset, PtrTy));
2679      SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2680                                    MachinePointerInfo(), false, false, false,
2681                                    Alignment);
2682      MemOpChains.push_back(LoadVal.getValue(1));
2683      RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2684    }
2685
2686    // Return if the struct has been fully copied.
2687    if (!(MemCpySize = ByValSize - Offset))
2688      return;
2689
2690    // If there is an argument register available, copy the remainder of the
2691    // byval argument with sub-doubleword loads and shifts.
2692    if (Reg != RegEnd) {
2693      assert((ByValSize < Offset + 8) &&
2694             "Size of the remainder should be smaller than 8-byte.");
2695      SDValue Val;
2696      for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2697        unsigned RemSize = ByValSize - Offset;
2698
2699        if (RemSize < LoadSize)
2700          continue;
2701
2702        SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2703                                      DAG.getConstant(Offset, PtrTy));
2704        SDValue LoadVal =
2705          DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2706                         MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2707                         false, false, Alignment);
2708        MemOpChains.push_back(LoadVal.getValue(1));
2709
2710        // Offset in number of bits from double word boundary.
2711        unsigned OffsetDW = (Offset % 8) * 8;
2712        unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2713        SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2714                                    DAG.getConstant(Shamt, MVT::i32));
2715
2716        Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2717                              Shift;
2718        Offset += LoadSize;
2719        Alignment = std::min(Alignment, LoadSize);
2720      }
2721
2722      RegsToPass.push_back(std::make_pair(*Reg, Val));
2723      return;
2724    }
2725  }
2726
2727  assert(MemCpySize && "MemCpySize must not be zero.");
2728
2729  // Copy remainder of byval arg to it with memcpy.
2730  SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2731                            DAG.getConstant(Offset, PtrTy));
2732  SDValue Dst = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr,
2733                            DAG.getIntPtrConstant(LocMemOffset));
2734  Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
2735                        DAG.getConstant(MemCpySize, PtrTy), Alignment,
2736                        /*isVolatile=*/false, /*AlwaysInline=*/false,
2737                        MachinePointerInfo(0), MachinePointerInfo(0));
2738  MemOpChains.push_back(Chain);
2739}
2740
2741/// LowerCall - functions arguments are copied from virtual regs to
2742/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2743/// TODO: isTailCall.
2744SDValue
2745MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2746                              SmallVectorImpl<SDValue> &InVals) const {
2747  SelectionDAG &DAG                     = CLI.DAG;
2748  DebugLoc &dl                          = CLI.DL;
2749  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2750  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2751  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2752  SDValue Chain                         = CLI.Chain;
2753  SDValue Callee                        = CLI.Callee;
2754  bool &isTailCall                      = CLI.IsTailCall;
2755  CallingConv::ID CallConv              = CLI.CallConv;
2756  bool isVarArg                         = CLI.IsVarArg;
2757
2758  // MIPs target does not yet support tail call optimization.
2759  isTailCall = false;
2760
2761  MachineFunction &MF = DAG.getMachineFunction();
2762  MachineFrameInfo *MFI = MF.getFrameInfo();
2763  const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2764  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2765  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2766
2767  // Analyze operands of the call, assigning locations to each operand.
2768  SmallVector<CCValAssign, 16> ArgLocs;
2769  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2770                 getTargetMachine(), ArgLocs, *DAG.getContext());
2771
2772  if (CallConv == CallingConv::Fast)
2773    CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2774  else if (IsO32)
2775    CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2776  else if (HasMips64)
2777    AnalyzeMips64CallOperands(CCInfo, Outs);
2778  else
2779    CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2780
2781  // Get a count of how many bytes are to be pushed on the stack.
2782  unsigned NextStackOffset = CCInfo.getNextStackOffset();
2783  unsigned StackAlignment = TFL->getStackAlignment();
2784  NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2785
2786  // Update size of the maximum argument space.
2787  // For O32, a minimum of four words (16 bytes) of argument space is
2788  // allocated.
2789  if (IsO32 && (CallConv != CallingConv::Fast))
2790    NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2791
2792  // Chain is the output chain of the last Load/Store or CopyToReg node.
2793  // ByValChain is the output chain of the last Memcpy node created for copying
2794  // byval arguments to the stack.
2795  SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2796  Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2797
2798  SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
2799                                        IsN64 ? Mips::SP_64 : Mips::SP,
2800                                        getPointerTy());
2801
2802  if (MipsFI->getMaxCallFrameSize() < NextStackOffset)
2803    MipsFI->setMaxCallFrameSize(NextStackOffset);
2804
2805  // With EABI is it possible to have 16 args on registers.
2806  SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2807  SmallVector<SDValue, 8> MemOpChains;
2808
2809  // Walk the register/memloc assignments, inserting copies/loads.
2810  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2811    SDValue Arg = OutVals[i];
2812    CCValAssign &VA = ArgLocs[i];
2813    MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2814    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2815
2816    // ByVal Arg.
2817    if (Flags.isByVal()) {
2818      assert(Flags.getByValSize() &&
2819             "ByVal args of size 0 should have been ignored by front-end.");
2820      if (IsO32)
2821        WriteByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr,
2822                      MFI, DAG, Arg, VA, Flags, getPointerTy(),
2823                      Subtarget->isLittle());
2824      else
2825        PassByValArg64(Chain, dl, RegsToPass, MemOpChains, StackPtr,
2826                       MFI, DAG, Arg, VA, Flags, getPointerTy(),
2827                       Subtarget->isLittle());
2828      continue;
2829    }
2830
2831    // Promote the value if needed.
2832    switch (VA.getLocInfo()) {
2833    default: llvm_unreachable("Unknown loc info!");
2834    case CCValAssign::Full:
2835      if (VA.isRegLoc()) {
2836        if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2837            (ValVT == MVT::f64 && LocVT == MVT::i64))
2838          Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2839        else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2840          SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2841                                   Arg, DAG.getConstant(0, MVT::i32));
2842          SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2843                                   Arg, DAG.getConstant(1, MVT::i32));
2844          if (!Subtarget->isLittle())
2845            std::swap(Lo, Hi);
2846          unsigned LocRegLo = VA.getLocReg();
2847          unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2848          RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2849          RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2850          continue;
2851        }
2852      }
2853      break;
2854    case CCValAssign::SExt:
2855      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2856      break;
2857    case CCValAssign::ZExt:
2858      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2859      break;
2860    case CCValAssign::AExt:
2861      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2862      break;
2863    }
2864
2865    // Arguments that can be passed on register must be kept at
2866    // RegsToPass vector
2867    if (VA.isRegLoc()) {
2868      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2869      continue;
2870    }
2871
2872    // Register can't get to this point...
2873    assert(VA.isMemLoc());
2874
2875    // emit ISD::STORE whichs stores the
2876    // parameter value to a stack Location
2877    SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
2878                                 DAG.getIntPtrConstant(VA.getLocMemOffset()));
2879    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2880                                       MachinePointerInfo(), false, false, 0));
2881  }
2882
2883  // Transform all store nodes into one single node because all store
2884  // nodes are independent of each other.
2885  if (!MemOpChains.empty())
2886    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2887                        &MemOpChains[0], MemOpChains.size());
2888
2889  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2890  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2891  // node so that legalize doesn't hack it.
2892  unsigned char OpFlag;
2893  bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2894  bool GlobalOrExternal = false;
2895  SDValue CalleeLo;
2896
2897  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2898    if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2899      OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2900      unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2901      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2902                                          OpFlag);
2903      CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2904                                            0, LoFlag);
2905    } else {
2906      OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2907      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2908                                          getPointerTy(), 0, OpFlag);
2909    }
2910
2911    GlobalOrExternal = true;
2912  }
2913  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2914    if (IsN64 || (!IsO32 && IsPIC))
2915      OpFlag = MipsII::MO_GOT_DISP;
2916    else if (!IsPIC) // !N64 && static
2917      OpFlag = MipsII::MO_NO_FLAG;
2918    else // O32 & PIC
2919      OpFlag = MipsII::MO_GOT_CALL;
2920    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2921                                         OpFlag);
2922    GlobalOrExternal = true;
2923  }
2924
2925  SDValue InFlag;
2926
2927  // Create nodes that load address of callee and copy it to T9
2928  if (IsPICCall) {
2929    if (GlobalOrExternal) {
2930      // Load callee address
2931      Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2932                           GetGlobalReg(DAG, getPointerTy()), Callee);
2933      SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2934                                      Callee, MachinePointerInfo::getGOT(),
2935                                      false, false, false, 0);
2936
2937      // Use GOT+LO if callee has internal linkage.
2938      if (CalleeLo.getNode()) {
2939        SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2940        Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2941      } else
2942        Callee = LoadValue;
2943    }
2944  }
2945
2946  // T9 register operand.
2947  SDValue T9;
2948
2949  // T9 should contain the address of the callee function if
2950  // -reloction-model=pic or it is an indirect call.
2951  if (IsPICCall || !GlobalOrExternal) {
2952    // copy to T9
2953    unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2954    Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2955    InFlag = Chain.getValue(1);
2956
2957    if (Subtarget->inMips16Mode())
2958      T9 = DAG.getRegister(T9Reg, getPointerTy());
2959    else
2960      Callee = DAG.getRegister(T9Reg, getPointerTy());
2961  }
2962
2963  // Insert node "GP copy globalreg" before call to function.
2964  // Lazy-binding stubs require GP to point to the GOT.
2965  if (IsPICCall) {
2966    unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2967    EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2968    RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2969  }
2970
2971  // Build a sequence of copy-to-reg nodes chained together with token
2972  // chain and flag operands which copy the outgoing args into registers.
2973  // The InFlag in necessary since all emitted instructions must be
2974  // stuck together.
2975  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2976    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2977                             RegsToPass[i].second, InFlag);
2978    InFlag = Chain.getValue(1);
2979  }
2980
2981  // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2982  //             = Chain, Callee, Reg#1, Reg#2, ...
2983  //
2984  // Returns a chain & a flag for retval copy to use.
2985  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2986  SmallVector<SDValue, 8> Ops;
2987  Ops.push_back(Chain);
2988  Ops.push_back(Callee);
2989
2990  // Add argument registers to the end of the list so that they are
2991  // known live into the call.
2992  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2993    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2994                                  RegsToPass[i].second.getValueType()));
2995
2996  // Add T9 register operand.
2997  if (T9.getNode())
2998    Ops.push_back(T9);
2999
3000  // Add a register mask operand representing the call-preserved registers.
3001  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3002  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3003  assert(Mask && "Missing call preserved mask for calling convention");
3004  Ops.push_back(DAG.getRegisterMask(Mask));
3005
3006  if (InFlag.getNode())
3007    Ops.push_back(InFlag);
3008
3009  Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3010  InFlag = Chain.getValue(1);
3011
3012  // Create the CALLSEQ_END node.
3013  Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3014                             DAG.getIntPtrConstant(0, true), InFlag);
3015  InFlag = Chain.getValue(1);
3016
3017  // Handle result values, copying them out of physregs into vregs that we
3018  // return.
3019  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3020                         Ins, dl, DAG, InVals);
3021}
3022
3023/// LowerCallResult - Lower the result values of a call into the
3024/// appropriate copies out of appropriate physical registers.
3025SDValue
3026MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3027                                    CallingConv::ID CallConv, bool isVarArg,
3028                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3029                                    DebugLoc dl, SelectionDAG &DAG,
3030                                    SmallVectorImpl<SDValue> &InVals) const {
3031  // Assign locations to each value returned by this call.
3032  SmallVector<CCValAssign, 16> RVLocs;
3033  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3034                 getTargetMachine(), RVLocs, *DAG.getContext());
3035
3036  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3037
3038  // Copy all of the result registers out of their specified physreg.
3039  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3040    Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3041                               RVLocs[i].getValVT(), InFlag).getValue(1);
3042    InFlag = Chain.getValue(2);
3043    InVals.push_back(Chain.getValue(0));
3044  }
3045
3046  return Chain;
3047}
3048
3049//===----------------------------------------------------------------------===//
3050//             Formal Arguments Calling Convention Implementation
3051//===----------------------------------------------------------------------===//
3052static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
3053                         std::vector<SDValue> &OutChains,
3054                         SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
3055                         const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
3056                         const Argument *FuncArg) {
3057  unsigned LocMem = VA.getLocMemOffset();
3058  unsigned FirstWord = LocMem / 4;
3059
3060  // copy register A0 - A3 to frame object
3061  for (unsigned i = 0; i < NumWords; ++i) {
3062    unsigned CurWord = FirstWord + i;
3063    if (CurWord >= O32IntRegsSize)
3064      break;
3065
3066    unsigned SrcReg = O32IntRegs[CurWord];
3067    unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
3068    SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
3069                                   DAG.getConstant(i * 4, MVT::i32));
3070    SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
3071                                 StorePtr, MachinePointerInfo(FuncArg, i * 4),
3072                                 false, false, 0);
3073    OutChains.push_back(Store);
3074  }
3075}
3076
3077// Create frame object on stack and copy registers used for byval passing to it.
3078static unsigned
3079CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
3080                    std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3081                    const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
3082                    MachineFrameInfo *MFI, bool IsRegLoc,
3083                    SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
3084                    EVT PtrTy, const Argument *FuncArg) {
3085  const uint16_t *Reg = Mips64IntRegs + 8;
3086  int FOOffset; // Frame object offset from virtual frame pointer.
3087
3088  if (IsRegLoc) {
3089    Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
3090    FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
3091  }
3092  else
3093    FOOffset = VA.getLocMemOffset();
3094
3095  // Create frame object.
3096  unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
3097  unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
3098  SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
3099  InVals.push_back(FIN);
3100
3101  // Copy arg registers.
3102  for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
3103       ++Reg, ++I) {
3104    unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
3105    SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
3106                                   DAG.getConstant(I * 8, PtrTy));
3107    SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
3108                                 StorePtr, MachinePointerInfo(FuncArg, I * 8),
3109                                 false, false, 0);
3110    OutChains.push_back(Store);
3111  }
3112
3113  return LastFI;
3114}
3115
3116/// LowerFormalArguments - transform physical registers into virtual registers
3117/// and generate load operations for arguments places on the stack.
3118SDValue
3119MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3120                                         CallingConv::ID CallConv,
3121                                         bool isVarArg,
3122                                      const SmallVectorImpl<ISD::InputArg> &Ins,
3123                                         DebugLoc dl, SelectionDAG &DAG,
3124                                         SmallVectorImpl<SDValue> &InVals)
3125                                          const {
3126  MachineFunction &MF = DAG.getMachineFunction();
3127  MachineFrameInfo *MFI = MF.getFrameInfo();
3128  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3129
3130  MipsFI->setVarArgsFrameIndex(0);
3131
3132  // Used with vargs to acumulate store chains.
3133  std::vector<SDValue> OutChains;
3134
3135  // Assign locations to all of the incoming arguments.
3136  SmallVector<CCValAssign, 16> ArgLocs;
3137  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3138                 getTargetMachine(), ArgLocs, *DAG.getContext());
3139
3140  if (CallConv == CallingConv::Fast)
3141    CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
3142  else if (IsO32)
3143    CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
3144  else
3145    CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
3146
3147  Function::const_arg_iterator FuncArg =
3148    DAG.getMachineFunction().getFunction()->arg_begin();
3149  int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3150
3151  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3152    CCValAssign &VA = ArgLocs[i];
3153    EVT ValVT = VA.getValVT();
3154    ISD::ArgFlagsTy Flags = Ins[i].Flags;
3155    bool IsRegLoc = VA.isRegLoc();
3156
3157    if (Flags.isByVal()) {
3158      assert(Flags.getByValSize() &&
3159             "ByVal args of size 0 should have been ignored by front-end.");
3160      if (IsO32) {
3161        unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3162        LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3163                                        true);
3164        SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3165        InVals.push_back(FIN);
3166        ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3167                     &*FuncArg);
3168      } else // N32/64
3169        LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3170                                     MFI, IsRegLoc, InVals, MipsFI,
3171                                     getPointerTy(), &*FuncArg);
3172      continue;
3173    }
3174
3175    // Arguments stored on registers
3176    if (IsRegLoc) {
3177      EVT RegVT = VA.getLocVT();
3178      unsigned ArgReg = VA.getLocReg();
3179      const TargetRegisterClass *RC;
3180
3181      if (RegVT == MVT::i32)
3182        RC = &Mips::CPURegsRegClass;
3183      else if (RegVT == MVT::i64)
3184        RC = &Mips::CPU64RegsRegClass;
3185      else if (RegVT == MVT::f32)
3186        RC = &Mips::FGR32RegClass;
3187      else if (RegVT == MVT::f64)
3188        RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3189      else
3190        llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3191
3192      // Transform the arguments stored on
3193      // physical registers into virtual ones
3194      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3195      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3196
3197      // If this is an 8 or 16-bit value, it has been passed promoted
3198      // to 32 bits.  Insert an assert[sz]ext to capture this, then
3199      // truncate to the right size.
3200      if (VA.getLocInfo() != CCValAssign::Full) {
3201        unsigned Opcode = 0;
3202        if (VA.getLocInfo() == CCValAssign::SExt)
3203          Opcode = ISD::AssertSext;
3204        else if (VA.getLocInfo() == CCValAssign::ZExt)
3205          Opcode = ISD::AssertZext;
3206        if (Opcode)
3207          ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3208                                 DAG.getValueType(ValVT));
3209        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3210      }
3211
3212      // Handle floating point arguments passed in integer registers.
3213      if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3214          (RegVT == MVT::i64 && ValVT == MVT::f64))
3215        ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3216      else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3217        unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3218                                  getNextIntArgReg(ArgReg), RC);
3219        SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3220        if (!Subtarget->isLittle())
3221          std::swap(ArgValue, ArgValue2);
3222        ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3223                               ArgValue, ArgValue2);
3224      }
3225
3226      InVals.push_back(ArgValue);
3227    } else { // VA.isRegLoc()
3228
3229      // sanity check
3230      assert(VA.isMemLoc());
3231
3232      // The stack pointer offset is relative to the caller stack frame.
3233      LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3234                                      VA.getLocMemOffset(), true);
3235
3236      // Create load nodes to retrieve arguments from the stack
3237      SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3238      InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3239                                   MachinePointerInfo::getFixedStack(LastFI),
3240                                   false, false, false, 0));
3241    }
3242  }
3243
3244  // The mips ABIs for returning structs by value requires that we copy
3245  // the sret argument into $v0 for the return. Save the argument into
3246  // a virtual register so that we can access it from the return points.
3247  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3248    unsigned Reg = MipsFI->getSRetReturnReg();
3249    if (!Reg) {
3250      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3251      MipsFI->setSRetReturnReg(Reg);
3252    }
3253    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3254    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3255  }
3256
3257  if (isVarArg) {
3258    unsigned NumOfRegs = IsO32 ? 4 : 8;
3259    const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3260    unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3261    int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3262    const TargetRegisterClass *RC = IsO32 ?
3263      (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3264      (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3265    unsigned RegSize = RC->getSize();
3266    int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3267
3268    // Offset of the first variable argument from stack pointer.
3269    int FirstVaArgOffset;
3270
3271    if (IsO32 || (Idx == NumOfRegs)) {
3272      FirstVaArgOffset =
3273        (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3274    } else
3275      FirstVaArgOffset = RegSlotOffset;
3276
3277    // Record the frame index of the first variable argument
3278    // which is a value necessary to VASTART.
3279    LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3280    MipsFI->setVarArgsFrameIndex(LastFI);
3281
3282    // Copy the integer registers that have not been used for argument passing
3283    // to the argument register save area. For O32, the save area is allocated
3284    // in the caller's stack frame, while for N32/64, it is allocated in the
3285    // callee's stack frame.
3286    for (int StackOffset = RegSlotOffset;
3287         Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3288      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3289      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3290                                            MVT::getIntegerVT(RegSize * 8));
3291      LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3292      SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3293      OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3294                                       MachinePointerInfo(), false, false, 0));
3295    }
3296  }
3297
3298  MipsFI->setLastInArgFI(LastFI);
3299
3300  // All stores are grouped in one node to allow the matching between
3301  // the size of Ins and InVals. This only happens when on varg functions
3302  if (!OutChains.empty()) {
3303    OutChains.push_back(Chain);
3304    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3305                        &OutChains[0], OutChains.size());
3306  }
3307
3308  return Chain;
3309}
3310
3311//===----------------------------------------------------------------------===//
3312//               Return Value Calling Convention Implementation
3313//===----------------------------------------------------------------------===//
3314
3315SDValue
3316MipsTargetLowering::LowerReturn(SDValue Chain,
3317                                CallingConv::ID CallConv, bool isVarArg,
3318                                const SmallVectorImpl<ISD::OutputArg> &Outs,
3319                                const SmallVectorImpl<SDValue> &OutVals,
3320                                DebugLoc dl, SelectionDAG &DAG) const {
3321
3322  // CCValAssign - represent the assignment of
3323  // the return value to a location
3324  SmallVector<CCValAssign, 16> RVLocs;
3325
3326  // CCState - Info about the registers and stack slot.
3327  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3328                 getTargetMachine(), RVLocs, *DAG.getContext());
3329
3330  // Analize return values.
3331  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3332
3333  // If this is the first return lowered for this function, add
3334  // the regs to the liveout set for the function.
3335  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3336    for (unsigned i = 0; i != RVLocs.size(); ++i)
3337      if (RVLocs[i].isRegLoc())
3338        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3339  }
3340
3341  SDValue Flag;
3342
3343  // Copy the result values into the output registers.
3344  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3345    CCValAssign &VA = RVLocs[i];
3346    assert(VA.isRegLoc() && "Can only return in registers!");
3347
3348    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3349
3350    // guarantee that all emitted copies are
3351    // stuck together, avoiding something bad
3352    Flag = Chain.getValue(1);
3353  }
3354
3355  // The mips ABIs for returning structs by value requires that we copy
3356  // the sret argument into $v0 for the return. We saved the argument into
3357  // a virtual register in the entry block, so now we copy the value out
3358  // and into $v0.
3359  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3360    MachineFunction &MF      = DAG.getMachineFunction();
3361    MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3362    unsigned Reg = MipsFI->getSRetReturnReg();
3363
3364    if (!Reg)
3365      llvm_unreachable("sret virtual register not created in the entry block");
3366    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3367
3368    Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3369    Flag = Chain.getValue(1);
3370  }
3371
3372  // Return on Mips is always a "jr $ra"
3373  if (Flag.getNode())
3374    return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3375
3376  // Return Void
3377  return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3378}
3379
3380//===----------------------------------------------------------------------===//
3381//                           Mips Inline Assembly Support
3382//===----------------------------------------------------------------------===//
3383
3384/// getConstraintType - Given a constraint letter, return the type of
3385/// constraint it is for this target.
3386MipsTargetLowering::ConstraintType MipsTargetLowering::
3387getConstraintType(const std::string &Constraint) const
3388{
3389  // Mips specific constrainy
3390  // GCC config/mips/constraints.md
3391  //
3392  // 'd' : An address register. Equivalent to r
3393  //       unless generating MIPS16 code.
3394  // 'y' : Equivalent to r; retained for
3395  //       backwards compatibility.
3396  // 'c' : A register suitable for use in an indirect
3397  //       jump. This will always be $25 for -mabicalls.
3398  // 'l' : The lo register. 1 word storage.
3399  // 'x' : The hilo register pair. Double word storage.
3400  if (Constraint.size() == 1) {
3401    switch (Constraint[0]) {
3402      default : break;
3403      case 'd':
3404      case 'y':
3405      case 'f':
3406      case 'c':
3407      case 'l':
3408      case 'x':
3409        return C_RegisterClass;
3410    }
3411  }
3412  return TargetLowering::getConstraintType(Constraint);
3413}
3414
3415/// Examine constraint type and operand type and determine a weight value.
3416/// This object must already have been set up with the operand type
3417/// and the current alternative constraint selected.
3418TargetLowering::ConstraintWeight
3419MipsTargetLowering::getSingleConstraintMatchWeight(
3420    AsmOperandInfo &info, const char *constraint) const {
3421  ConstraintWeight weight = CW_Invalid;
3422  Value *CallOperandVal = info.CallOperandVal;
3423    // If we don't have a value, we can't do a match,
3424    // but allow it at the lowest weight.
3425  if (CallOperandVal == NULL)
3426    return CW_Default;
3427  Type *type = CallOperandVal->getType();
3428  // Look at the constraint type.
3429  switch (*constraint) {
3430  default:
3431    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3432    break;
3433  case 'd':
3434  case 'y':
3435    if (type->isIntegerTy())
3436      weight = CW_Register;
3437    break;
3438  case 'f':
3439    if (type->isFloatTy())
3440      weight = CW_Register;
3441    break;
3442  case 'c': // $25 for indirect jumps
3443  case 'l': // lo register
3444  case 'x': // hilo register pair
3445      if (type->isIntegerTy())
3446      weight = CW_SpecificReg;
3447      break;
3448  case 'I': // signed 16 bit immediate
3449  case 'J': // integer zero
3450  case 'K': // unsigned 16 bit immediate
3451  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3452  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3453  case 'O': // signed 15 bit immediate (+- 16383)
3454  case 'P': // immediate in the range of 65535 to 1 (inclusive)
3455    if (isa<ConstantInt>(CallOperandVal))
3456      weight = CW_Constant;
3457    break;
3458  }
3459  return weight;
3460}
3461
3462/// Given a register class constraint, like 'r', if this corresponds directly
3463/// to an LLVM register class, return a register of 0 and the register class
3464/// pointer.
3465std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3466getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3467{
3468  if (Constraint.size() == 1) {
3469    switch (Constraint[0]) {
3470    case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3471    case 'y': // Same as 'r'. Exists for compatibility.
3472    case 'r':
3473      if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3474        if (Subtarget->inMips16Mode())
3475          return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3476        return std::make_pair(0U, &Mips::CPURegsRegClass);
3477      }
3478      if (VT == MVT::i64 && !HasMips64)
3479        return std::make_pair(0U, &Mips::CPURegsRegClass);
3480      if (VT == MVT::i64 && HasMips64)
3481        return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3482      // This will generate an error message
3483      return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3484    case 'f':
3485      if (VT == MVT::f32)
3486        return std::make_pair(0U, &Mips::FGR32RegClass);
3487      if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3488        if (Subtarget->isFP64bit())
3489          return std::make_pair(0U, &Mips::FGR64RegClass);
3490        return std::make_pair(0U, &Mips::AFGR64RegClass);
3491      }
3492      break;
3493    case 'c': // register suitable for indirect jump
3494      if (VT == MVT::i32)
3495        return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3496      assert(VT == MVT::i64 && "Unexpected type.");
3497      return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3498    case 'l': // register suitable for indirect jump
3499      if (VT == MVT::i32)
3500        return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3501      return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3502    case 'x': // register suitable for indirect jump
3503      // Fixme: Not triggering the use of both hi and low
3504      // This will generate an error message
3505      return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3506    }
3507  }
3508  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3509}
3510
3511/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3512/// vector.  If it is invalid, don't add anything to Ops.
3513void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3514                                                     std::string &Constraint,
3515                                                     std::vector<SDValue>&Ops,
3516                                                     SelectionDAG &DAG) const {
3517  SDValue Result(0, 0);
3518
3519  // Only support length 1 constraints for now.
3520  if (Constraint.length() > 1) return;
3521
3522  char ConstraintLetter = Constraint[0];
3523  switch (ConstraintLetter) {
3524  default: break; // This will fall through to the generic implementation
3525  case 'I': // Signed 16 bit constant
3526    // If this fails, the parent routine will give an error
3527    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3528      EVT Type = Op.getValueType();
3529      int64_t Val = C->getSExtValue();
3530      if (isInt<16>(Val)) {
3531        Result = DAG.getTargetConstant(Val, Type);
3532        break;
3533      }
3534    }
3535    return;
3536  case 'J': // integer zero
3537    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3538      EVT Type = Op.getValueType();
3539      int64_t Val = C->getZExtValue();
3540      if (Val == 0) {
3541        Result = DAG.getTargetConstant(0, Type);
3542        break;
3543      }
3544    }
3545    return;
3546  case 'K': // unsigned 16 bit immediate
3547    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3548      EVT Type = Op.getValueType();
3549      uint64_t Val = (uint64_t)C->getZExtValue();
3550      if (isUInt<16>(Val)) {
3551        Result = DAG.getTargetConstant(Val, Type);
3552        break;
3553      }
3554    }
3555    return;
3556  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3557    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3558      EVT Type = Op.getValueType();
3559      int64_t Val = C->getSExtValue();
3560      if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3561        Result = DAG.getTargetConstant(Val, Type);
3562        break;
3563      }
3564    }
3565    return;
3566  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3567    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3568      EVT Type = Op.getValueType();
3569      int64_t Val = C->getSExtValue();
3570      if ((Val >= -65535) && (Val <= -1)) {
3571        Result = DAG.getTargetConstant(Val, Type);
3572        break;
3573      }
3574    }
3575    return;
3576  case 'O': // signed 15 bit immediate
3577    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3578      EVT Type = Op.getValueType();
3579      int64_t Val = C->getSExtValue();
3580      if ((isInt<15>(Val))) {
3581        Result = DAG.getTargetConstant(Val, Type);
3582        break;
3583      }
3584    }
3585    return;
3586  case 'P': // immediate in the range of 1 to 65535 (inclusive)
3587    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3588      EVT Type = Op.getValueType();
3589      int64_t Val = C->getSExtValue();
3590      if ((Val <= 65535) && (Val >= 1)) {
3591        Result = DAG.getTargetConstant(Val, Type);
3592        break;
3593      }
3594    }
3595    return;
3596  }
3597
3598  if (Result.getNode()) {
3599    Ops.push_back(Result);
3600    return;
3601  }
3602
3603  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3604}
3605
3606bool
3607MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3608  // The Mips target isn't yet aware of offsets.
3609  return false;
3610}
3611
3612EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3613                                            unsigned SrcAlign, bool IsZeroVal,
3614                                            bool MemcpyStrSrc,
3615                                            MachineFunction &MF) const {
3616  if (Subtarget->hasMips64())
3617    return MVT::i64;
3618
3619  return MVT::i32;
3620}
3621
3622bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3623  if (VT != MVT::f32 && VT != MVT::f64)
3624    return false;
3625  if (Imm.isNegZero())
3626    return false;
3627  return Imm.isZero();
3628}
3629
3630unsigned MipsTargetLowering::getJumpTableEncoding() const {
3631  if (IsN64)
3632    return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3633
3634  return TargetLowering::getJumpTableEncoding();
3635}
3636