MipsISelLowering.cpp revision 14487d4f66c3127b29408aae46c1a948d348ec59
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 "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/CallingConv.h"
26#include "llvm/CodeGen/CallingConvLower.h"
27#include "llvm/CodeGen/MachineFrameInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/SelectionDAGISel.h"
32#include "llvm/CodeGen/ValueTypes.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/ErrorHandling.h"
35using namespace llvm;
36
37const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
38  switch (Opcode) {
39  case MipsISD::JmpLink:           return "MipsISD::JmpLink";
40  case MipsISD::Hi:                return "MipsISD::Hi";
41  case MipsISD::Lo:                return "MipsISD::Lo";
42  case MipsISD::GPRel:             return "MipsISD::GPRel";
43  case MipsISD::TlsGd:             return "MipsISD::TlsGd";
44  case MipsISD::TprelHi:           return "MipsISD::TprelHi";
45  case MipsISD::TprelLo:           return "MipsISD::TprelLo";
46  case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
47  case MipsISD::Ret:               return "MipsISD::Ret";
48  case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
49  case MipsISD::FPCmp:             return "MipsISD::FPCmp";
50  case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
51  case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
52  case MipsISD::FPRound:           return "MipsISD::FPRound";
53  case MipsISD::MAdd:              return "MipsISD::MAdd";
54  case MipsISD::MAddu:             return "MipsISD::MAddu";
55  case MipsISD::MSub:              return "MipsISD::MSub";
56  case MipsISD::MSubu:             return "MipsISD::MSubu";
57  case MipsISD::DivRem:            return "MipsISD::DivRem";
58  case MipsISD::DivRemU:           return "MipsISD::DivRemU";
59  case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
60  case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
61  case MipsISD::WrapperPIC:        return "MipsISD::WrapperPIC";
62  default:                         return NULL;
63  }
64}
65
66MipsTargetLowering::
67MipsTargetLowering(MipsTargetMachine &TM)
68  : TargetLowering(TM, new MipsTargetObjectFile()) {
69  Subtarget = &TM.getSubtarget<MipsSubtarget>();
70
71  // Mips does not have i1 type, so use i32 for
72  // setcc operations results (slt, sgt, ...).
73  setBooleanContents(ZeroOrOneBooleanContent);
74
75  // Set up the register classes
76  addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
77  addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
78
79  // When dealing with single precision only, use libcalls
80  if (!Subtarget->isSingleFloat())
81    if (!Subtarget->isFP64bit())
82      addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
83
84  // Load extented operations for i1 types must be promoted
85  setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
86  setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
87  setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
88
89  // MIPS doesn't have extending float->double load/store
90  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
91  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
92
93  // Used by legalize types to correctly generate the setcc result.
94  // Without this, every float setcc comes with a AND/OR with the result,
95  // we don't want this, since the fpcmp result goes to a flag register,
96  // which is used implicitly by brcond and select operations.
97  AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
98
99  // Mips Custom Operations
100  setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
101  setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
102  setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
103  setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
104  setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
105  setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
106  setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
107  setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
108  setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
109  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
110  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
111
112  setOperationAction(ISD::SDIV, MVT::i32, Expand);
113  setOperationAction(ISD::SREM, MVT::i32, Expand);
114  setOperationAction(ISD::UDIV, MVT::i32, Expand);
115  setOperationAction(ISD::UREM, MVT::i32, Expand);
116
117  // Operations not directly supported by Mips.
118  setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
119  setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
120  setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
121  setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
122  setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
123  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
124  setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
125  setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
126  setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
127
128  if (!Subtarget->isMips32r2())
129    setOperationAction(ISD::ROTR, MVT::i32,   Expand);
130
131  setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
132  setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
133  setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
134  setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Custom);
135  setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Custom);
136  setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
137  setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
138  setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
139  setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
140  setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
141  setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
142  setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
143  setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
144  setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
145  setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
146  setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
147
148  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
149  setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
150
151  setOperationAction(ISD::VAARG,             MVT::Other, Expand);
152  setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
153  setOperationAction(ISD::VAEND,             MVT::Other, Expand);
154
155  // Use the default for now
156  setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
157  setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
158  setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
159
160  if (Subtarget->isSingleFloat())
161    setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
162
163  if (!Subtarget->hasSEInReg()) {
164    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
165    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
166  }
167
168  if (!Subtarget->hasBitCount())
169    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
170
171  if (!Subtarget->hasSwap())
172    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
173
174  setTargetDAGCombine(ISD::ADDE);
175  setTargetDAGCombine(ISD::SUBE);
176  setTargetDAGCombine(ISD::SDIVREM);
177  setTargetDAGCombine(ISD::UDIVREM);
178  setTargetDAGCombine(ISD::SETCC);
179
180  setMinFunctionAlignment(2);
181
182  setStackPointerRegisterToSaveRestore(Mips::SP);
183  computeRegisterProperties();
184
185  setExceptionPointerRegister(Mips::A0);
186  setExceptionSelectorRegister(Mips::A1);
187}
188
189MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
190  return MVT::i32;
191}
192
193// SelectMadd -
194// Transforms a subgraph in CurDAG if the following pattern is found:
195//  (addc multLo, Lo0), (adde multHi, Hi0),
196// where,
197//  multHi/Lo: product of multiplication
198//  Lo0: initial value of Lo register
199//  Hi0: initial value of Hi register
200// Return true if pattern matching was successful.
201static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
202  // ADDENode's second operand must be a flag output of an ADDC node in order
203  // for the matching to be successful.
204  SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
205
206  if (ADDCNode->getOpcode() != ISD::ADDC)
207    return false;
208
209  SDValue MultHi = ADDENode->getOperand(0);
210  SDValue MultLo = ADDCNode->getOperand(0);
211  SDNode* MultNode = MultHi.getNode();
212  unsigned MultOpc = MultHi.getOpcode();
213
214  // MultHi and MultLo must be generated by the same node,
215  if (MultLo.getNode() != MultNode)
216    return false;
217
218  // and it must be a multiplication.
219  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
220    return false;
221
222  // MultLo amd MultHi must be the first and second output of MultNode
223  // respectively.
224  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
225    return false;
226
227  // Transform this to a MADD only if ADDENode and ADDCNode are the only users
228  // of the values of MultNode, in which case MultNode will be removed in later
229  // phases.
230  // If there exist users other than ADDENode or ADDCNode, this function returns
231  // here, which will result in MultNode being mapped to a single MULT
232  // instruction node rather than a pair of MULT and MADD instructions being
233  // produced.
234  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
235    return false;
236
237  SDValue Chain = CurDAG->getEntryNode();
238  DebugLoc dl = ADDENode->getDebugLoc();
239
240  // create MipsMAdd(u) node
241  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
242
243  SDValue MAdd = CurDAG->getNode(MultOpc, dl,
244                                 MVT::Glue,
245                                 MultNode->getOperand(0),// Factor 0
246                                 MultNode->getOperand(1),// Factor 1
247                                 ADDCNode->getOperand(1),// Lo0
248                                 ADDENode->getOperand(1));// Hi0
249
250  // create CopyFromReg nodes
251  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
252                                              MAdd);
253  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
254                                              Mips::HI, MVT::i32,
255                                              CopyFromLo.getValue(2));
256
257  // replace uses of adde and addc here
258  if (!SDValue(ADDCNode, 0).use_empty())
259    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
260
261  if (!SDValue(ADDENode, 0).use_empty())
262    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
263
264  return true;
265}
266
267// SelectMsub -
268// Transforms a subgraph in CurDAG if the following pattern is found:
269//  (addc Lo0, multLo), (sube Hi0, multHi),
270// where,
271//  multHi/Lo: product of multiplication
272//  Lo0: initial value of Lo register
273//  Hi0: initial value of Hi register
274// Return true if pattern matching was successful.
275static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
276  // SUBENode's second operand must be a flag output of an SUBC node in order
277  // for the matching to be successful.
278  SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
279
280  if (SUBCNode->getOpcode() != ISD::SUBC)
281    return false;
282
283  SDValue MultHi = SUBENode->getOperand(1);
284  SDValue MultLo = SUBCNode->getOperand(1);
285  SDNode* MultNode = MultHi.getNode();
286  unsigned MultOpc = MultHi.getOpcode();
287
288  // MultHi and MultLo must be generated by the same node,
289  if (MultLo.getNode() != MultNode)
290    return false;
291
292  // and it must be a multiplication.
293  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
294    return false;
295
296  // MultLo amd MultHi must be the first and second output of MultNode
297  // respectively.
298  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
299    return false;
300
301  // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
302  // of the values of MultNode, in which case MultNode will be removed in later
303  // phases.
304  // If there exist users other than SUBENode or SUBCNode, this function returns
305  // here, which will result in MultNode being mapped to a single MULT
306  // instruction node rather than a pair of MULT and MSUB instructions being
307  // produced.
308  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
309    return false;
310
311  SDValue Chain = CurDAG->getEntryNode();
312  DebugLoc dl = SUBENode->getDebugLoc();
313
314  // create MipsSub(u) node
315  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
316
317  SDValue MSub = CurDAG->getNode(MultOpc, dl,
318                                 MVT::Glue,
319                                 MultNode->getOperand(0),// Factor 0
320                                 MultNode->getOperand(1),// Factor 1
321                                 SUBCNode->getOperand(0),// Lo0
322                                 SUBENode->getOperand(0));// Hi0
323
324  // create CopyFromReg nodes
325  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
326                                              MSub);
327  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
328                                              Mips::HI, MVT::i32,
329                                              CopyFromLo.getValue(2));
330
331  // replace uses of sube and subc here
332  if (!SDValue(SUBCNode, 0).use_empty())
333    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
334
335  if (!SDValue(SUBENode, 0).use_empty())
336    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
337
338  return true;
339}
340
341static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
342                                  TargetLowering::DAGCombinerInfo &DCI,
343                                  const MipsSubtarget* Subtarget) {
344  if (DCI.isBeforeLegalize())
345    return SDValue();
346
347  if (Subtarget->isMips32() && SelectMadd(N, &DAG))
348    return SDValue(N, 0);
349
350  return SDValue();
351}
352
353static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
354                                  TargetLowering::DAGCombinerInfo &DCI,
355                                  const MipsSubtarget* Subtarget) {
356  if (DCI.isBeforeLegalize())
357    return SDValue();
358
359  if (Subtarget->isMips32() && SelectMsub(N, &DAG))
360    return SDValue(N, 0);
361
362  return SDValue();
363}
364
365static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
366                                    TargetLowering::DAGCombinerInfo &DCI,
367                                    const MipsSubtarget* Subtarget) {
368  if (DCI.isBeforeLegalizeOps())
369    return SDValue();
370
371  unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
372                                                  MipsISD::DivRemU;
373  DebugLoc dl = N->getDebugLoc();
374
375  SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
376                               N->getOperand(0), N->getOperand(1));
377  SDValue InChain = DAG.getEntryNode();
378  SDValue InGlue = DivRem;
379
380  // insert MFLO
381  if (N->hasAnyUseOfValue(0)) {
382    SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
383                                            InGlue);
384    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
385    InChain = CopyFromLo.getValue(1);
386    InGlue = CopyFromLo.getValue(2);
387  }
388
389  // insert MFHI
390  if (N->hasAnyUseOfValue(1)) {
391    SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
392                                            Mips::HI, MVT::i32, InGlue);
393    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
394  }
395
396  return SDValue();
397}
398
399static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
400  switch (CC) {
401  default: llvm_unreachable("Unknown fp condition code!");
402  case ISD::SETEQ:
403  case ISD::SETOEQ: return Mips::FCOND_OEQ;
404  case ISD::SETUNE: return Mips::FCOND_UNE;
405  case ISD::SETLT:
406  case ISD::SETOLT: return Mips::FCOND_OLT;
407  case ISD::SETGT:
408  case ISD::SETOGT: return Mips::FCOND_OGT;
409  case ISD::SETLE:
410  case ISD::SETOLE: return Mips::FCOND_OLE;
411  case ISD::SETGE:
412  case ISD::SETOGE: return Mips::FCOND_OGE;
413  case ISD::SETULT: return Mips::FCOND_ULT;
414  case ISD::SETULE: return Mips::FCOND_ULE;
415  case ISD::SETUGT: return Mips::FCOND_UGT;
416  case ISD::SETUGE: return Mips::FCOND_UGE;
417  case ISD::SETUO:  return Mips::FCOND_UN;
418  case ISD::SETO:   return Mips::FCOND_OR;
419  case ISD::SETNE:
420  case ISD::SETONE: return Mips::FCOND_ONE;
421  case ISD::SETUEQ: return Mips::FCOND_UEQ;
422  }
423}
424
425
426// Returns true if condition code has to be inverted.
427static bool InvertFPCondCode(Mips::CondCode CC) {
428  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
429    return false;
430
431  if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
432    return true;
433
434  assert(false && "Illegal Condition Code");
435  return false;
436}
437
438// Creates and returns an FPCmp node from a setcc node.
439// Returns Op if setcc is not a floating point comparison.
440static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
441  // must be a SETCC node
442  if (Op.getOpcode() != ISD::SETCC)
443    return Op;
444
445  SDValue LHS = Op.getOperand(0);
446
447  if (!LHS.getValueType().isFloatingPoint())
448    return Op;
449
450  SDValue RHS = Op.getOperand(1);
451  DebugLoc dl = Op.getDebugLoc();
452
453  // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
454  // node if necessary.
455  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
456
457  return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
458                     DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
459}
460
461// Creates and returns a CMovFPT/F node.
462static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
463                            SDValue False, DebugLoc DL) {
464  bool invert = InvertFPCondCode((Mips::CondCode)
465                                 cast<ConstantSDNode>(Cond.getOperand(2))
466                                 ->getSExtValue());
467
468  return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
469                     True.getValueType(), True, False, Cond);
470}
471
472static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
473                                   TargetLowering::DAGCombinerInfo &DCI,
474                                   const MipsSubtarget* Subtarget) {
475  if (DCI.isBeforeLegalizeOps())
476    return SDValue();
477
478  SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
479
480  if (Cond.getOpcode() != MipsISD::FPCmp)
481    return SDValue();
482
483  SDValue True  = DAG.getConstant(1, MVT::i32);
484  SDValue False = DAG.getConstant(0, MVT::i32);
485
486  return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
487}
488
489SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
490  const {
491  SelectionDAG &DAG = DCI.DAG;
492  unsigned opc = N->getOpcode();
493
494  switch (opc) {
495  default: break;
496  case ISD::ADDE:
497    return PerformADDECombine(N, DAG, DCI, Subtarget);
498  case ISD::SUBE:
499    return PerformSUBECombine(N, DAG, DCI, Subtarget);
500  case ISD::SDIVREM:
501  case ISD::UDIVREM:
502    return PerformDivRemCombine(N, DAG, DCI, Subtarget);
503  case ISD::SETCC:
504    return PerformSETCCCombine(N, DAG, DCI, Subtarget);
505  }
506
507  return SDValue();
508}
509
510SDValue MipsTargetLowering::
511LowerOperation(SDValue Op, SelectionDAG &DAG) const
512{
513  switch (Op.getOpcode())
514  {
515    case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
516    case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
517    case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
518    case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
519    case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
520    case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
521    case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
522    case ISD::SELECT:             return LowerSELECT(Op, DAG);
523    case ISD::VASTART:            return LowerVASTART(Op, DAG);
524    case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
525    case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
526  }
527  return SDValue();
528}
529
530//===----------------------------------------------------------------------===//
531//  Lower helper functions
532//===----------------------------------------------------------------------===//
533
534// AddLiveIn - This helper function adds the specified physical register to the
535// MachineFunction as a live in value.  It also creates a corresponding
536// virtual register for it.
537static unsigned
538AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
539{
540  assert(RC->contains(PReg) && "Not the correct regclass!");
541  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
542  MF.getRegInfo().addLiveIn(PReg, VReg);
543  return VReg;
544}
545
546// Get fp branch code (not opcode) from condition code.
547static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
548  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
549    return Mips::BRANCH_T;
550
551  if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
552    return Mips::BRANCH_F;
553
554  return Mips::BRANCH_INVALID;
555}
556
557static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
558                                        DebugLoc dl,
559                                        const MipsSubtarget* Subtarget,
560                                        const TargetInstrInfo *TII,
561                                        bool isFPCmp, unsigned Opc) {
562  // There is no need to expand CMov instructions if target has
563  // conditional moves.
564  if (Subtarget->hasCondMov())
565    return BB;
566
567  // To "insert" a SELECT_CC instruction, we actually have to insert the
568  // diamond control-flow pattern.  The incoming instruction knows the
569  // destination vreg to set, the condition code register to branch on, the
570  // true/false values to select between, and a branch opcode to use.
571  const BasicBlock *LLVM_BB = BB->getBasicBlock();
572  MachineFunction::iterator It = BB;
573  ++It;
574
575  //  thisMBB:
576  //  ...
577  //   TrueVal = ...
578  //   setcc r1, r2, r3
579  //   bNE   r1, r0, copy1MBB
580  //   fallthrough --> copy0MBB
581  MachineBasicBlock *thisMBB  = BB;
582  MachineFunction *F = BB->getParent();
583  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
584  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
585  F->insert(It, copy0MBB);
586  F->insert(It, sinkMBB);
587
588  // Transfer the remainder of BB and its successor edges to sinkMBB.
589  sinkMBB->splice(sinkMBB->begin(), BB,
590                  llvm::next(MachineBasicBlock::iterator(MI)),
591                  BB->end());
592  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
593
594  // Next, add the true and fallthrough blocks as its successors.
595  BB->addSuccessor(copy0MBB);
596  BB->addSuccessor(sinkMBB);
597
598  // Emit the right instruction according to the type of the operands compared
599  if (isFPCmp)
600    BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
601  else
602    BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
603      .addReg(Mips::ZERO).addMBB(sinkMBB);
604
605  //  copy0MBB:
606  //   %FalseValue = ...
607  //   # fallthrough to sinkMBB
608  BB = copy0MBB;
609
610  // Update machine-CFG edges
611  BB->addSuccessor(sinkMBB);
612
613  //  sinkMBB:
614  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
615  //  ...
616  BB = sinkMBB;
617
618  if (isFPCmp)
619    BuildMI(*BB, BB->begin(), dl,
620            TII->get(Mips::PHI), MI->getOperand(0).getReg())
621      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
622      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
623  else
624    BuildMI(*BB, BB->begin(), dl,
625            TII->get(Mips::PHI), MI->getOperand(0).getReg())
626      .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
627      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
628
629  MI->eraseFromParent();   // The pseudo instruction is gone now.
630  return BB;
631}
632
633MachineBasicBlock *
634MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
635                                                MachineBasicBlock *BB) const {
636  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
637  DebugLoc dl = MI->getDebugLoc();
638
639  switch (MI->getOpcode()) {
640  default:
641    assert(false && "Unexpected instr type to insert");
642    return NULL;
643  case Mips::MOVT:
644  case Mips::MOVT_S:
645  case Mips::MOVT_D:
646    return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
647  case Mips::MOVF:
648  case Mips::MOVF_S:
649  case Mips::MOVF_D:
650    return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
651  case Mips::MOVZ_I:
652  case Mips::MOVZ_S:
653  case Mips::MOVZ_D:
654    return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
655  case Mips::MOVN_I:
656  case Mips::MOVN_S:
657  case Mips::MOVN_D:
658    return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
659
660  case Mips::ATOMIC_LOAD_ADD_I8:
661    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
662  case Mips::ATOMIC_LOAD_ADD_I16:
663    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
664  case Mips::ATOMIC_LOAD_ADD_I32:
665    return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
666
667  case Mips::ATOMIC_LOAD_AND_I8:
668    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
669  case Mips::ATOMIC_LOAD_AND_I16:
670    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
671  case Mips::ATOMIC_LOAD_AND_I32:
672    return EmitAtomicBinary(MI, BB, 4, Mips::AND);
673
674  case Mips::ATOMIC_LOAD_OR_I8:
675    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
676  case Mips::ATOMIC_LOAD_OR_I16:
677    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
678  case Mips::ATOMIC_LOAD_OR_I32:
679    return EmitAtomicBinary(MI, BB, 4, Mips::OR);
680
681  case Mips::ATOMIC_LOAD_XOR_I8:
682    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
683  case Mips::ATOMIC_LOAD_XOR_I16:
684    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
685  case Mips::ATOMIC_LOAD_XOR_I32:
686    return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
687
688  case Mips::ATOMIC_LOAD_NAND_I8:
689    return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
690  case Mips::ATOMIC_LOAD_NAND_I16:
691    return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
692  case Mips::ATOMIC_LOAD_NAND_I32:
693    return EmitAtomicBinary(MI, BB, 4, 0, true);
694
695  case Mips::ATOMIC_LOAD_SUB_I8:
696    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
697  case Mips::ATOMIC_LOAD_SUB_I16:
698    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
699  case Mips::ATOMIC_LOAD_SUB_I32:
700    return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
701
702  case Mips::ATOMIC_SWAP_I8:
703    return EmitAtomicBinaryPartword(MI, BB, 1, 0);
704  case Mips::ATOMIC_SWAP_I16:
705    return EmitAtomicBinaryPartword(MI, BB, 2, 0);
706  case Mips::ATOMIC_SWAP_I32:
707    return EmitAtomicBinary(MI, BB, 4, 0);
708
709  case Mips::ATOMIC_CMP_SWAP_I8:
710    return EmitAtomicCmpSwapPartword(MI, BB, 1);
711  case Mips::ATOMIC_CMP_SWAP_I16:
712    return EmitAtomicCmpSwapPartword(MI, BB, 2);
713  case Mips::ATOMIC_CMP_SWAP_I32:
714    return EmitAtomicCmpSwap(MI, BB, 4);
715  }
716}
717
718// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
719// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
720MachineBasicBlock *
721MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
722                                     unsigned Size, unsigned BinOpcode,
723                                     bool Nand) const {
724  assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
725
726  MachineFunction *MF = BB->getParent();
727  MachineRegisterInfo &RegInfo = MF->getRegInfo();
728  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
729  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
730  DebugLoc dl = MI->getDebugLoc();
731
732  unsigned Dest = MI->getOperand(0).getReg();
733  unsigned Ptr = MI->getOperand(1).getReg();
734  unsigned Incr = MI->getOperand(2).getReg();
735
736  unsigned Oldval = RegInfo.createVirtualRegister(RC);
737  unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
738  unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
739
740  // insert new blocks after the current block
741  const BasicBlock *LLVM_BB = BB->getBasicBlock();
742  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
743  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
744  MachineFunction::iterator It = BB;
745  ++It;
746  MF->insert(It, loopMBB);
747  MF->insert(It, exitMBB);
748
749  // Transfer the remainder of BB and its successor edges to exitMBB.
750  exitMBB->splice(exitMBB->begin(), BB,
751                  llvm::next(MachineBasicBlock::iterator(MI)),
752                  BB->end());
753  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
754
755  //  thisMBB:
756  //    ...
757  //    sw incr, fi(sp)           // store incr to stack (when BinOpcode == 0)
758  //    fallthrough --> loopMBB
759
760  // Note: for atomic.swap (when BinOpcode == 0), storing incr to stack before
761  // the loop and then loading it from stack in block loopMBB is necessary to
762  // prevent MachineLICM pass to hoist "or" instruction out of the block
763  // loopMBB.
764
765  int fi = 0;
766  if (BinOpcode == 0 && !Nand) {
767    // Get or create a temporary stack location.
768    MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
769    fi = MipsFI->getAtomicFrameIndex();
770    if (fi == -1) {
771      fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
772      MipsFI->setAtomicFrameIndex(fi);
773    }
774
775    BuildMI(BB, dl, TII->get(Mips::SW))
776        .addReg(Incr).addImm(0).addFrameIndex(fi);
777  }
778  BB->addSuccessor(loopMBB);
779
780  //  loopMBB:
781  //    ll oldval, 0(ptr)
782  //    or dest, $0, oldval
783  //    <binop> tmp1, oldval, incr
784  //    sc tmp1, 0(ptr)
785  //    beq tmp1, $0, loopMBB
786  BB = loopMBB;
787  BuildMI(BB, dl, TII->get(Mips::LL), Oldval).addImm(0).addReg(Ptr);
788  BuildMI(BB, dl, TII->get(Mips::OR), Dest).addReg(Mips::ZERO).addReg(Oldval);
789  if (Nand) {
790    //  and tmp2, oldval, incr
791    //  nor tmp1, $0, tmp2
792    BuildMI(BB, dl, TII->get(Mips::AND), Tmp2).addReg(Oldval).addReg(Incr);
793    BuildMI(BB, dl, TII->get(Mips::NOR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
794  } else if (BinOpcode) {
795    //  <binop> tmp1, oldval, incr
796    BuildMI(BB, dl, TII->get(BinOpcode), Tmp1).addReg(Oldval).addReg(Incr);
797  } else {
798    //  lw tmp2, fi(sp)              // load incr from stack
799    //  or tmp1, $zero, tmp2
800    BuildMI(BB, dl, TII->get(Mips::LW), Tmp2).addImm(0).addFrameIndex(fi);;
801    BuildMI(BB, dl, TII->get(Mips::OR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
802  }
803  BuildMI(BB, dl, TII->get(Mips::SC), Tmp1).addReg(Tmp1).addImm(0).addReg(Ptr);
804  BuildMI(BB, dl, TII->get(Mips::BEQ))
805    .addReg(Tmp1).addReg(Mips::ZERO).addMBB(loopMBB);
806  BB->addSuccessor(loopMBB);
807  BB->addSuccessor(exitMBB);
808
809  MI->eraseFromParent();   // The instruction is gone now.
810
811  return BB;
812}
813
814MachineBasicBlock *
815MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
816                                             MachineBasicBlock *BB,
817                                             unsigned Size, unsigned BinOpcode,
818                                             bool Nand) const {
819  assert((Size == 1 || Size == 2) &&
820      "Unsupported size for EmitAtomicBinaryPartial.");
821
822  MachineFunction *MF = BB->getParent();
823  MachineRegisterInfo &RegInfo = MF->getRegInfo();
824  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
825  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
826  DebugLoc dl = MI->getDebugLoc();
827
828  unsigned Dest = MI->getOperand(0).getReg();
829  unsigned Ptr = MI->getOperand(1).getReg();
830  unsigned Incr = MI->getOperand(2).getReg();
831
832  unsigned Addr = RegInfo.createVirtualRegister(RC);
833  unsigned Shift = RegInfo.createVirtualRegister(RC);
834  unsigned Mask = RegInfo.createVirtualRegister(RC);
835  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
836  unsigned Newval = RegInfo.createVirtualRegister(RC);
837  unsigned Oldval = RegInfo.createVirtualRegister(RC);
838  unsigned Incr2 = RegInfo.createVirtualRegister(RC);
839  unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
840  unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
841  unsigned Tmp3 = RegInfo.createVirtualRegister(RC);
842  unsigned Tmp4 = RegInfo.createVirtualRegister(RC);
843  unsigned Tmp5 = RegInfo.createVirtualRegister(RC);
844  unsigned Tmp6 = RegInfo.createVirtualRegister(RC);
845  unsigned Tmp7 = RegInfo.createVirtualRegister(RC);
846  unsigned Tmp8 = RegInfo.createVirtualRegister(RC);
847  unsigned Tmp9 = RegInfo.createVirtualRegister(RC);
848  unsigned Tmp10 = RegInfo.createVirtualRegister(RC);
849  unsigned Tmp11 = RegInfo.createVirtualRegister(RC);
850  unsigned Tmp12 = RegInfo.createVirtualRegister(RC);
851
852  // insert new blocks after the current block
853  const BasicBlock *LLVM_BB = BB->getBasicBlock();
854  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
855  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
856  MachineFunction::iterator It = BB;
857  ++It;
858  MF->insert(It, loopMBB);
859  MF->insert(It, exitMBB);
860
861  // Transfer the remainder of BB and its successor edges to exitMBB.
862  exitMBB->splice(exitMBB->begin(), BB,
863                  llvm::next(MachineBasicBlock::iterator(MI)),
864                  BB->end());
865  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
866
867  //  thisMBB:
868  //    addiu   tmp1,$0,-4                # 0xfffffffc
869  //    and     addr,ptr,tmp1
870  //    andi    tmp2,ptr,3
871  //    sll     shift,tmp2,3
872  //    ori     tmp3,$0,255               # 0xff
873  //    sll     mask,tmp3,shift
874  //    nor     mask2,$0,mask
875  //    andi    tmp4,incr,255
876  //    sll     incr2,tmp4,shift
877  //    sw      incr2, fi(sp)      // store incr2 to stack (when BinOpcode == 0)
878
879  // Note: for atomic.swap (when BinOpcode == 0), storing incr2 to stack before
880  // the loop and then loading it from stack in block loopMBB is necessary to
881  // prevent MachineLICM pass to hoist "or" instruction out of the block
882  // loopMBB.
883
884  int64_t MaskImm = (Size == 1) ? 255 : 65535;
885  BuildMI(BB, dl, TII->get(Mips::ADDiu), Tmp1).addReg(Mips::ZERO).addImm(-4);
886  BuildMI(BB, dl, TII->get(Mips::AND), Addr).addReg(Ptr).addReg(Tmp1);
887  BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp2).addReg(Ptr).addImm(3);
888  BuildMI(BB, dl, TII->get(Mips::SLL), Shift).addReg(Tmp2).addImm(3);
889  BuildMI(BB, dl, TII->get(Mips::ORi), Tmp3).addReg(Mips::ZERO).addImm(MaskImm);
890  BuildMI(BB, dl, TII->get(Mips::SLL), Mask).addReg(Tmp3).addReg(Shift);
891  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
892  if (BinOpcode != Mips::SUBu) {
893    BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp4).addReg(Incr).addImm(MaskImm);
894    BuildMI(BB, dl, TII->get(Mips::SLL), Incr2).addReg(Tmp4).addReg(Shift);
895  } else {
896    BuildMI(BB, dl, TII->get(Mips::SUBu), Tmp4).addReg(Mips::ZERO).addReg(Incr);
897    BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp5).addReg(Tmp4).addImm(MaskImm);
898    BuildMI(BB, dl, TII->get(Mips::SLL), Incr2).addReg(Tmp5).addReg(Shift);
899  }
900
901  int fi = 0;
902  if (BinOpcode == 0 && !Nand) {
903    // Get or create a temporary stack location.
904    MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
905    fi = MipsFI->getAtomicFrameIndex();
906    if (fi == -1) {
907      fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
908      MipsFI->setAtomicFrameIndex(fi);
909    }
910
911    BuildMI(BB, dl, TII->get(Mips::SW))
912        .addReg(Incr2).addImm(0).addFrameIndex(fi);
913  }
914  BB->addSuccessor(loopMBB);
915
916  // loopMBB:
917  //   ll      oldval,0(addr)
918  //   binop   tmp7,oldval,incr2
919  //   and     newval,tmp7,mask
920  //   and     tmp8,oldval,mask2
921  //   or      tmp9,tmp8,newval
922  //   sc      tmp9,0(addr)
923  //   beq     tmp9,$0,loopMBB
924  BB = loopMBB;
925  BuildMI(BB, dl, TII->get(Mips::LL), Oldval).addImm(0).addReg(Addr);
926  if (Nand) {
927    //  and tmp6, oldval, incr2
928    //  nor tmp7, $0, tmp6
929    BuildMI(BB, dl, TII->get(Mips::AND), Tmp6).addReg(Oldval).addReg(Incr2);
930    BuildMI(BB, dl, TII->get(Mips::NOR), Tmp7).addReg(Mips::ZERO).addReg(Tmp6);
931  } else if (BinOpcode == Mips::SUBu) {
932    //  addu tmp7, oldval, incr2
933    BuildMI(BB, dl, TII->get(Mips::ADDu), Tmp7).addReg(Oldval).addReg(Incr2);
934  } else if (BinOpcode) {
935    //  <binop> tmp7, oldval, incr2
936    BuildMI(BB, dl, TII->get(BinOpcode), Tmp7).addReg(Oldval).addReg(Incr2);
937  } else {
938    //  lw tmp6, fi(sp)              // load incr2 from stack
939    //  or tmp7, $zero, tmp6
940    BuildMI(BB, dl, TII->get(Mips::LW), Tmp6).addImm(0).addFrameIndex(fi);;
941    BuildMI(BB, dl, TII->get(Mips::OR), Tmp7).addReg(Mips::ZERO).addReg(Tmp6);
942  }
943  BuildMI(BB, dl, TII->get(Mips::AND), Newval).addReg(Tmp7).addReg(Mask);
944  BuildMI(BB, dl, TII->get(Mips::AND), Tmp8).addReg(Oldval).addReg(Mask2);
945  BuildMI(BB, dl, TII->get(Mips::OR), Tmp9).addReg(Tmp8).addReg(Newval);
946  BuildMI(BB, dl, TII->get(Mips::SC), Tmp9).addReg(Tmp9).addImm(0).addReg(Addr);
947  BuildMI(BB, dl, TII->get(Mips::BEQ))
948      .addReg(Tmp9).addReg(Mips::ZERO).addMBB(loopMBB);
949  BB->addSuccessor(loopMBB);
950  BB->addSuccessor(exitMBB);
951
952  //  exitMBB:
953  //    and     tmp10,oldval,mask
954  //    srl     tmp11,tmp10,shift
955  //    sll     tmp12,tmp11,24
956  //    sra     dest,tmp12,24
957  BB = exitMBB;
958  int64_t ShiftImm = (Size == 1) ? 24 : 16;
959  // reverse order
960  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRA), Dest)
961      .addReg(Tmp12).addImm(ShiftImm);
962  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SLL), Tmp12)
963      .addReg(Tmp11).addImm(ShiftImm);
964  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRL), Tmp11)
965      .addReg(Tmp10).addReg(Shift);
966  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::AND), Tmp10)
967    .addReg(Oldval).addReg(Mask);
968
969  MI->eraseFromParent();   // The instruction is gone now.
970
971  return BB;
972}
973
974MachineBasicBlock *
975MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
976                                      MachineBasicBlock *BB,
977                                      unsigned Size) const {
978  assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
979
980  MachineFunction *MF = BB->getParent();
981  MachineRegisterInfo &RegInfo = MF->getRegInfo();
982  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
983  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
984  DebugLoc dl = MI->getDebugLoc();
985
986  unsigned Dest    = MI->getOperand(0).getReg();
987  unsigned Ptr     = MI->getOperand(1).getReg();
988  unsigned Oldval  = MI->getOperand(2).getReg();
989  unsigned Newval  = MI->getOperand(3).getReg();
990
991  unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
992  unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
993
994  // insert new blocks after the current block
995  const BasicBlock *LLVM_BB = BB->getBasicBlock();
996  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
997  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
998  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
999  MachineFunction::iterator It = BB;
1000  ++It;
1001  MF->insert(It, loop1MBB);
1002  MF->insert(It, loop2MBB);
1003  MF->insert(It, exitMBB);
1004
1005  // Transfer the remainder of BB and its successor edges to exitMBB.
1006  exitMBB->splice(exitMBB->begin(), BB,
1007                  llvm::next(MachineBasicBlock::iterator(MI)),
1008                  BB->end());
1009  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1010
1011  // Get or create a temporary stack location.
1012  MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
1013  int fi = MipsFI->getAtomicFrameIndex();
1014  if (fi == -1) {
1015    fi = MF->getFrameInfo()->CreateStackObject(Size, Size, false);
1016    MipsFI->setAtomicFrameIndex(fi);
1017  }
1018
1019  //  thisMBB:
1020  //    ...
1021  //    sw newval, fi(sp)           // store newval to stack
1022  //    fallthrough --> loop1MBB
1023
1024  // Note: storing newval to stack before the loop and then loading it from
1025  // stack in block loop2MBB is necessary to prevent MachineLICM pass to
1026  // hoist "or" instruction out of the block loop2MBB.
1027
1028  BuildMI(BB, dl, TII->get(Mips::SW))
1029      .addReg(Newval).addImm(0).addFrameIndex(fi);
1030  BB->addSuccessor(loop1MBB);
1031
1032  // loop1MBB:
1033  //   ll dest, 0(ptr)
1034  //   bne dest, oldval, exitMBB
1035  BB = loop1MBB;
1036  BuildMI(BB, dl, TII->get(Mips::LL), Dest).addImm(0).addReg(Ptr);
1037  BuildMI(BB, dl, TII->get(Mips::BNE))
1038    .addReg(Dest).addReg(Oldval).addMBB(exitMBB);
1039  BB->addSuccessor(exitMBB);
1040  BB->addSuccessor(loop2MBB);
1041
1042  // loop2MBB:
1043  //   lw tmp2, fi(sp)              // load newval from stack
1044  //   or tmp1, $0, tmp2
1045  //   sc tmp1, 0(ptr)
1046  //   beq tmp1, $0, loop1MBB
1047  BB = loop2MBB;
1048  BuildMI(BB, dl, TII->get(Mips::LW), Tmp2).addImm(0).addFrameIndex(fi);;
1049  BuildMI(BB, dl, TII->get(Mips::OR), Tmp1).addReg(Mips::ZERO).addReg(Tmp2);
1050  BuildMI(BB, dl, TII->get(Mips::SC), Tmp1).addReg(Tmp1).addImm(0).addReg(Ptr);
1051  BuildMI(BB, dl, TII->get(Mips::BEQ))
1052    .addReg(Tmp1).addReg(Mips::ZERO).addMBB(loop1MBB);
1053  BB->addSuccessor(loop1MBB);
1054  BB->addSuccessor(exitMBB);
1055
1056  MI->eraseFromParent();   // The instruction is gone now.
1057
1058  return BB;
1059}
1060
1061MachineBasicBlock *
1062MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1063                                              MachineBasicBlock *BB,
1064                                              unsigned Size) const {
1065  assert((Size == 1 || Size == 2) &&
1066      "Unsupported size for EmitAtomicCmpSwapPartial.");
1067
1068  MachineFunction *MF = BB->getParent();
1069  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1070  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1071  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1072  DebugLoc dl = MI->getDebugLoc();
1073
1074  unsigned Dest    = MI->getOperand(0).getReg();
1075  unsigned Ptr     = MI->getOperand(1).getReg();
1076  unsigned Oldval  = MI->getOperand(2).getReg();
1077  unsigned Newval  = MI->getOperand(3).getReg();
1078
1079  unsigned Addr = RegInfo.createVirtualRegister(RC);
1080  unsigned Shift = RegInfo.createVirtualRegister(RC);
1081  unsigned Mask = RegInfo.createVirtualRegister(RC);
1082  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1083  unsigned Oldval2 = RegInfo.createVirtualRegister(RC);
1084  unsigned Oldval3 = RegInfo.createVirtualRegister(RC);
1085  unsigned Oldval4 = RegInfo.createVirtualRegister(RC);
1086  unsigned Newval2 = RegInfo.createVirtualRegister(RC);
1087  unsigned Tmp1 = RegInfo.createVirtualRegister(RC);
1088  unsigned Tmp2 = RegInfo.createVirtualRegister(RC);
1089  unsigned Tmp3 = RegInfo.createVirtualRegister(RC);
1090  unsigned Tmp4 = RegInfo.createVirtualRegister(RC);
1091  unsigned Tmp5 = RegInfo.createVirtualRegister(RC);
1092  unsigned Tmp6 = RegInfo.createVirtualRegister(RC);
1093  unsigned Tmp7 = RegInfo.createVirtualRegister(RC);
1094  unsigned Tmp8 = RegInfo.createVirtualRegister(RC);
1095  unsigned Tmp9 = RegInfo.createVirtualRegister(RC);
1096
1097  // insert new blocks after the current block
1098  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1099  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1100  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1101  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1102  MachineFunction::iterator It = BB;
1103  ++It;
1104  MF->insert(It, loop1MBB);
1105  MF->insert(It, loop2MBB);
1106  MF->insert(It, exitMBB);
1107
1108  // Transfer the remainder of BB and its successor edges to exitMBB.
1109  exitMBB->splice(exitMBB->begin(), BB,
1110                  llvm::next(MachineBasicBlock::iterator(MI)),
1111                  BB->end());
1112  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1113
1114  //  thisMBB:
1115  //    addiu   tmp1,$0,-4                # 0xfffffffc
1116  //    and     addr,ptr,tmp1
1117  //    andi    tmp2,ptr,3
1118  //    sll     shift,tmp2,3
1119  //    ori     tmp3,$0,255               # 0xff
1120  //    sll     mask,tmp3,shift
1121  //    nor     mask2,$0,mask
1122  //    andi    tmp4,oldval,255
1123  //    sll     oldval2,tmp4,shift
1124  //    andi    tmp5,newval,255
1125  //    sll     newval2,tmp5,shift
1126  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1127  BuildMI(BB, dl, TII->get(Mips::ADDiu), Tmp1).addReg(Mips::ZERO).addImm(-4);
1128  BuildMI(BB, dl, TII->get(Mips::AND), Addr).addReg(Ptr).addReg(Tmp1);
1129  BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp2).addReg(Ptr).addImm(3);
1130  BuildMI(BB, dl, TII->get(Mips::SLL), Shift).addReg(Tmp2).addImm(3);
1131  BuildMI(BB, dl, TII->get(Mips::ORi), Tmp3).addReg(Mips::ZERO).addImm(MaskImm);
1132  BuildMI(BB, dl, TII->get(Mips::SLL), Mask).addReg(Tmp3).addReg(Shift);
1133  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1134  BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp4).addReg(Oldval).addImm(MaskImm);
1135  BuildMI(BB, dl, TII->get(Mips::SLL), Oldval2).addReg(Tmp4).addReg(Shift);
1136  BuildMI(BB, dl, TII->get(Mips::ANDi), Tmp5).addReg(Newval).addImm(MaskImm);
1137  BuildMI(BB, dl, TII->get(Mips::SLL), Newval2).addReg(Tmp5).addReg(Shift);
1138  BB->addSuccessor(loop1MBB);
1139
1140  //  loop1MBB:
1141  //    ll      oldval3,0(addr)
1142  //    and     oldval4,oldval3,mask
1143  //    bne     oldval4,oldval2,exitMBB
1144  BB = loop1MBB;
1145  BuildMI(BB, dl, TII->get(Mips::LL), Oldval3).addImm(0).addReg(Addr);
1146  BuildMI(BB, dl, TII->get(Mips::AND), Oldval4).addReg(Oldval3).addReg(Mask);
1147  BuildMI(BB, dl, TII->get(Mips::BNE))
1148      .addReg(Oldval4).addReg(Oldval2).addMBB(exitMBB);
1149  BB->addSuccessor(exitMBB);
1150  BB->addSuccessor(loop2MBB);
1151
1152  //  loop2MBB:
1153  //    and     tmp6,oldval3,mask2
1154  //    or      tmp7,tmp6,newval2
1155  //    sc      tmp7,0(addr)
1156  //    beq     tmp7,$0,loop1MBB
1157  BB = loop2MBB;
1158  BuildMI(BB, dl, TII->get(Mips::AND), Tmp6).addReg(Oldval3).addReg(Mask2);
1159  BuildMI(BB, dl, TII->get(Mips::OR), Tmp7).addReg(Tmp6).addReg(Newval2);
1160  BuildMI(BB, dl, TII->get(Mips::SC), Tmp7)
1161      .addReg(Tmp7).addImm(0).addReg(Addr);
1162  BuildMI(BB, dl, TII->get(Mips::BEQ))
1163      .addReg(Tmp7).addReg(Mips::ZERO).addMBB(loop1MBB);
1164  BB->addSuccessor(loop1MBB);
1165  BB->addSuccessor(exitMBB);
1166
1167  //  exitMBB:
1168  //    srl     tmp8,oldval4,shift
1169  //    sll     tmp9,tmp8,24
1170  //    sra     dest,tmp9,24
1171  BB = exitMBB;
1172  int64_t ShiftImm = (Size == 1) ? 24 : 16;
1173  // reverse order
1174  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRA), Dest)
1175      .addReg(Tmp9).addImm(ShiftImm);
1176  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SLL), Tmp9)
1177      .addReg(Tmp8).addImm(ShiftImm);
1178  BuildMI(*BB, BB->begin(), dl, TII->get(Mips::SRL), Tmp8)
1179      .addReg(Oldval4).addReg(Shift);
1180
1181  MI->eraseFromParent();   // The instruction is gone now.
1182
1183  return BB;
1184}
1185
1186//===----------------------------------------------------------------------===//
1187//  Misc Lower Operation implementation
1188//===----------------------------------------------------------------------===//
1189SDValue MipsTargetLowering::
1190LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1191{
1192  unsigned StackAlignment =
1193    getTargetMachine().getFrameLowering()->getStackAlignment();
1194  assert(StackAlignment >=
1195         cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1196         "Cannot lower if the alignment of the allocated space is larger than \
1197          that of the stack.");
1198
1199  SDValue Chain = Op.getOperand(0);
1200  SDValue Size = Op.getOperand(1);
1201  DebugLoc dl = Op.getDebugLoc();
1202
1203  // Get a reference from Mips stack pointer
1204  SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1205
1206  // Subtract the dynamic size from the actual stack size to
1207  // obtain the new stack size.
1208  SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1209
1210  // The Sub result contains the new stack start address, so it
1211  // must be placed in the stack pointer register.
1212  Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1213                           SDValue());
1214  // Retrieve updated $sp. There is a glue input to prevent instructions that
1215  // clobber $sp from being inserted between copytoreg and copyfromreg.
1216  SDValue NewSP = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32,
1217                                     Chain.getValue(1));
1218
1219  // The stack space reserved by alloca is located right above the argument
1220  // area. It is aligned on a boundary that is a multiple of StackAlignment.
1221  MachineFunction &MF = DAG.getMachineFunction();
1222  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1223  unsigned SPOffset = (MipsFI->getMaxCallFrameSize() + StackAlignment - 1) /
1224                      StackAlignment * StackAlignment;
1225  SDValue AllocPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1226                                 DAG.getConstant(SPOffset, MVT::i32));
1227
1228  // This node always has two return values: a new stack pointer
1229  // value and a chain
1230  SDValue Ops[2] = { AllocPtr, NewSP.getValue(1) };
1231  return DAG.getMergeValues(Ops, 2, dl);
1232}
1233
1234SDValue MipsTargetLowering::
1235LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1236{
1237  // The first operand is the chain, the second is the condition, the third is
1238  // the block to branch to if the condition is true.
1239  SDValue Chain = Op.getOperand(0);
1240  SDValue Dest = Op.getOperand(2);
1241  DebugLoc dl = Op.getDebugLoc();
1242
1243  SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1244
1245  // Return if flag is not set by a floating point comparison.
1246  if (CondRes.getOpcode() != MipsISD::FPCmp)
1247    return Op;
1248
1249  SDValue CCNode  = CondRes.getOperand(2);
1250  Mips::CondCode CC =
1251    (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1252  SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1253
1254  return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1255                     Dest, CondRes);
1256}
1257
1258SDValue MipsTargetLowering::
1259LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1260{
1261  SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1262
1263  // Return if flag is not set by a floating point comparison.
1264  if (Cond.getOpcode() != MipsISD::FPCmp)
1265    return Op;
1266
1267  return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1268                      Op.getDebugLoc());
1269}
1270
1271SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1272                                               SelectionDAG &DAG) const {
1273  // FIXME there isn't actually debug info here
1274  DebugLoc dl = Op.getDebugLoc();
1275  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1276
1277  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1278    SDVTList VTs = DAG.getVTList(MVT::i32);
1279
1280    MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1281
1282    // %gp_rel relocation
1283    if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1284      SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1285                                              MipsII::MO_GPREL);
1286      SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1287      SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1288      return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1289    }
1290    // %hi/%lo relocation
1291    SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1292                                              MipsII::MO_ABS_HI);
1293    SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1294                                              MipsII::MO_ABS_LO);
1295    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1296    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1297    return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1298  }
1299
1300  SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1301                                          MipsII::MO_GOT);
1302  GA = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, GA);
1303  SDValue ResNode = DAG.getLoad(MVT::i32, dl,
1304                                DAG.getEntryNode(), GA, MachinePointerInfo(),
1305                                false, false, 0);
1306  // On functions and global targets not internal linked only
1307  // a load from got/GP is necessary for PIC to work.
1308  if (!GV->hasInternalLinkage() &&
1309      (!GV->hasLocalLinkage() || isa<Function>(GV)))
1310    return ResNode;
1311  SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1312                                            MipsII::MO_ABS_LO);
1313  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1314  return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
1315}
1316
1317SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1318                                              SelectionDAG &DAG) const {
1319  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1320  // FIXME there isn't actually debug info here
1321  DebugLoc dl = Op.getDebugLoc();
1322
1323  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1324    // %hi/%lo relocation
1325    SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1326                                       MipsII::MO_ABS_HI);
1327    SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1328                                       MipsII::MO_ABS_LO);
1329    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1330    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1331    return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1332  }
1333
1334  SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1335                                            MipsII::MO_GOT);
1336  BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1337  SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1338                                           MipsII::MO_ABS_LO);
1339  SDValue Load = DAG.getLoad(MVT::i32, dl,
1340                             DAG.getEntryNode(), BAGOTOffset,
1341                             MachinePointerInfo(), false, false, 0);
1342  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1343  return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1344}
1345
1346SDValue MipsTargetLowering::
1347LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1348{
1349  // If the relocation model is PIC, use the General Dynamic TLS Model,
1350  // otherwise use the Initial Exec or Local Exec TLS Model.
1351  // TODO: implement Local Dynamic TLS model
1352
1353  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1354  DebugLoc dl = GA->getDebugLoc();
1355  const GlobalValue *GV = GA->getGlobal();
1356  EVT PtrVT = getPointerTy();
1357
1358  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1359    // General Dynamic TLS Model
1360    SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1361                                                 0, MipsII::MO_TLSGD);
1362    SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1363    SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1364    SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1365
1366    ArgListTy Args;
1367    ArgListEntry Entry;
1368    Entry.Node = Argument;
1369    Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1370    Args.push_back(Entry);
1371    std::pair<SDValue, SDValue> CallResult =
1372        LowerCallTo(DAG.getEntryNode(),
1373                 (const Type *) Type::getInt32Ty(*DAG.getContext()),
1374                 false, false, false, false,
1375                 0, CallingConv::C, false, true,
1376                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1377
1378    return CallResult.first;
1379  } else {
1380    SDValue Offset;
1381    if (GV->isDeclaration()) {
1382      // Initial Exec TLS Model
1383      SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1384                                              MipsII::MO_GOTTPREL);
1385      Offset = DAG.getLoad(MVT::i32, dl,
1386                                  DAG.getEntryNode(), TGA, MachinePointerInfo(),
1387                                  false, false, 0);
1388    } else {
1389      // Local Exec TLS Model
1390      SDVTList VTs = DAG.getVTList(MVT::i32);
1391      SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1392                                              MipsII::MO_TPREL_HI);
1393      SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1394                                              MipsII::MO_TPREL_LO);
1395      SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1396      SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1397      Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1398    }
1399
1400    SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1401    return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1402  }
1403}
1404
1405SDValue MipsTargetLowering::
1406LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1407{
1408  SDValue ResNode;
1409  SDValue HiPart;
1410  // FIXME there isn't actually debug info here
1411  DebugLoc dl = Op.getDebugLoc();
1412  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1413  unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1414
1415  EVT PtrVT = Op.getValueType();
1416  JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
1417
1418  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1419
1420  if (!IsPIC) {
1421    SDValue Ops[] = { JTI };
1422    HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1423  } else {// Emit Load from Global Pointer
1424    JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1425    HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1426                         MachinePointerInfo(),
1427                         false, false, 0);
1428  }
1429
1430  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1431                                         MipsII::MO_ABS_LO);
1432  SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1433  ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1434
1435  return ResNode;
1436}
1437
1438SDValue MipsTargetLowering::
1439LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1440{
1441  SDValue ResNode;
1442  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1443  const Constant *C = N->getConstVal();
1444  // FIXME there isn't actually debug info here
1445  DebugLoc dl = Op.getDebugLoc();
1446
1447  // gp_rel relocation
1448  // FIXME: we should reference the constant pool using small data sections,
1449  // but the asm printer currently doesn't support this feature without
1450  // hacking it. This feature should come soon so we can uncomment the
1451  // stuff below.
1452  //if (IsInSmallSection(C->getType())) {
1453  //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1454  //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1455  //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1456
1457  if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1458    SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1459                                             N->getOffset(), MipsII::MO_ABS_HI);
1460    SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1461                                             N->getOffset(), MipsII::MO_ABS_LO);
1462    SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1463    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1464    ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1465  } else {
1466    SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1467                                           N->getOffset(), MipsII::MO_GOT);
1468    CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1469    SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1470                               CP, MachinePointerInfo::getConstantPool(),
1471                               false, false, 0);
1472    SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1473                                             N->getOffset(), MipsII::MO_ABS_LO);
1474    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1475    ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1476  }
1477
1478  return ResNode;
1479}
1480
1481SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1482  MachineFunction &MF = DAG.getMachineFunction();
1483  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1484
1485  DebugLoc dl = Op.getDebugLoc();
1486  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1487                                 getPointerTy());
1488
1489  // vastart just stores the address of the VarArgsFrameIndex slot into the
1490  // memory location argument.
1491  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1492  return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1493                      MachinePointerInfo(SV),
1494                      false, false, 0);
1495}
1496
1497static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1498  // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1499  DebugLoc dl = Op.getDebugLoc();
1500  SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1501  SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1502  SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1503                             DAG.getConstant(0x7fffffff, MVT::i32));
1504  SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1505                             DAG.getConstant(0x80000000, MVT::i32));
1506  SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1507  return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1508}
1509
1510static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1511  // FIXME:
1512  //  Use ext/ins instructions if target architecture is Mips32r2.
1513  //  Eliminate redundant mfc1 and mtc1 instructions.
1514  unsigned LoIdx = 0, HiIdx = 1;
1515
1516  if (!isLittle)
1517    std::swap(LoIdx, HiIdx);
1518
1519  DebugLoc dl = Op.getDebugLoc();
1520  SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1521                              Op.getOperand(0),
1522                              DAG.getConstant(LoIdx, MVT::i32));
1523  SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1524                            Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1525  SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1526                            Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1527  SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1528                             DAG.getConstant(0x7fffffff, MVT::i32));
1529  SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1530                             DAG.getConstant(0x80000000, MVT::i32));
1531  SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1532
1533  if (!isLittle)
1534    std::swap(Word0, Word1);
1535
1536  return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1537}
1538
1539SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1540  const {
1541  EVT Ty = Op.getValueType();
1542
1543  assert(Ty == MVT::f32 || Ty == MVT::f64);
1544
1545  if (Ty == MVT::f32)
1546    return LowerFCOPYSIGN32(Op, DAG);
1547  else
1548    return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1549}
1550
1551SDValue MipsTargetLowering::
1552LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1553  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1554  assert((Depth == 0) &&
1555         "Frame address can only be determined for current frame.");
1556
1557  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1558  MFI->setFrameAddressIsTaken(true);
1559  EVT VT = Op.getValueType();
1560  DebugLoc dl = Op.getDebugLoc();
1561  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1562  return FrameAddr;
1563}
1564
1565//===----------------------------------------------------------------------===//
1566//                      Calling Convention Implementation
1567//===----------------------------------------------------------------------===//
1568
1569#include "MipsGenCallingConv.inc"
1570
1571//===----------------------------------------------------------------------===//
1572// TODO: Implement a generic logic using tblgen that can support this.
1573// Mips O32 ABI rules:
1574// ---
1575// i32 - Passed in A0, A1, A2, A3 and stack
1576// f32 - Only passed in f32 registers if no int reg has been used yet to hold
1577//       an argument. Otherwise, passed in A1, A2, A3 and stack.
1578// f64 - Only passed in two aliased f32 registers if no int reg has been used
1579//       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1580//       not used, it must be shadowed. If only A3 is avaiable, shadow it and
1581//       go to stack.
1582//
1583//  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1584//===----------------------------------------------------------------------===//
1585
1586static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1587                       MVT LocVT, CCValAssign::LocInfo LocInfo,
1588                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
1589
1590  static const unsigned IntRegsSize=4, FloatRegsSize=2;
1591
1592  static const unsigned IntRegs[] = {
1593      Mips::A0, Mips::A1, Mips::A2, Mips::A3
1594  };
1595  static const unsigned F32Regs[] = {
1596      Mips::F12, Mips::F14
1597  };
1598  static const unsigned F64Regs[] = {
1599      Mips::D6, Mips::D7
1600  };
1601
1602  // ByVal Args
1603  if (ArgFlags.isByVal()) {
1604    State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1605                      1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1606    unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1607    for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1608         r < std::min(IntRegsSize, NextReg); ++r)
1609      State.AllocateReg(IntRegs[r]);
1610    return false;
1611  }
1612
1613  // Promote i8 and i16
1614  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1615    LocVT = MVT::i32;
1616    if (ArgFlags.isSExt())
1617      LocInfo = CCValAssign::SExt;
1618    else if (ArgFlags.isZExt())
1619      LocInfo = CCValAssign::ZExt;
1620    else
1621      LocInfo = CCValAssign::AExt;
1622  }
1623
1624  unsigned Reg;
1625
1626  // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1627  // is true: function is vararg, argument is 3rd or higher, there is previous
1628  // argument which is not f32 or f64.
1629  bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1630      || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1631  unsigned OrigAlign = ArgFlags.getOrigAlign();
1632  bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1633
1634  if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1635    Reg = State.AllocateReg(IntRegs, IntRegsSize);
1636    // If this is the first part of an i64 arg,
1637    // the allocated register must be either A0 or A2.
1638    if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1639      Reg = State.AllocateReg(IntRegs, IntRegsSize);
1640    LocVT = MVT::i32;
1641  } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1642    // Allocate int register and shadow next int register. If first
1643    // available register is Mips::A1 or Mips::A3, shadow it too.
1644    Reg = State.AllocateReg(IntRegs, IntRegsSize);
1645    if (Reg == Mips::A1 || Reg == Mips::A3)
1646      Reg = State.AllocateReg(IntRegs, IntRegsSize);
1647    State.AllocateReg(IntRegs, IntRegsSize);
1648    LocVT = MVT::i32;
1649  } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1650    // we are guaranteed to find an available float register
1651    if (ValVT == MVT::f32) {
1652      Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1653      // Shadow int register
1654      State.AllocateReg(IntRegs, IntRegsSize);
1655    } else {
1656      Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1657      // Shadow int registers
1658      unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1659      if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1660        State.AllocateReg(IntRegs, IntRegsSize);
1661      State.AllocateReg(IntRegs, IntRegsSize);
1662    }
1663  } else
1664    llvm_unreachable("Cannot handle this ValVT.");
1665
1666  unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1667  unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1668
1669  if (!Reg)
1670    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1671  else
1672    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1673
1674  return false; // CC must always match
1675}
1676
1677//===----------------------------------------------------------------------===//
1678//                  Call Calling Convention Implementation
1679//===----------------------------------------------------------------------===//
1680
1681static const unsigned O32IntRegsSize = 4;
1682
1683static const unsigned O32IntRegs[] = {
1684  Mips::A0, Mips::A1, Mips::A2, Mips::A3
1685};
1686
1687// Write ByVal Arg to arg registers and stack.
1688static void
1689WriteByValArg(SDValue& Chain, DebugLoc dl,
1690              SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1691              SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1692              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1693              const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1694              MVT PtrType) {
1695  unsigned FirstWord = VA.getLocMemOffset() / 4;
1696  unsigned NumWords = (Flags.getByValSize() + 3) / 4;
1697  unsigned LastWord = FirstWord + NumWords;
1698  unsigned CurWord;
1699
1700  // copy the first 4 words of byval arg to registers A0 - A3
1701  for (CurWord = FirstWord; CurWord < std::min(LastWord, O32IntRegsSize);
1702       ++CurWord) {
1703    SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1704                                  DAG.getConstant((CurWord - FirstWord) * 4,
1705                                                  MVT::i32));
1706    SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1707                                  MachinePointerInfo(),
1708                                  false, false, 0);
1709    MemOpChains.push_back(LoadVal.getValue(1));
1710    unsigned DstReg = O32IntRegs[CurWord];
1711    RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1712  }
1713
1714  // copy remaining part of byval arg to stack.
1715  if (CurWord < LastWord) {
1716    unsigned SizeInBytes = (LastWord - CurWord) * 4;
1717    SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1718                              DAG.getConstant((CurWord - FirstWord) * 4,
1719                                              MVT::i32));
1720    LastFI = MFI->CreateFixedObject(SizeInBytes, CurWord * 4, true);
1721    SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1722    Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
1723                          DAG.getConstant(SizeInBytes, MVT::i32),
1724                          /*Align*/4,
1725                          /*isVolatile=*/false, /*AlwaysInline=*/false,
1726                          MachinePointerInfo(0), MachinePointerInfo(0));
1727    MemOpChains.push_back(Chain);
1728  }
1729}
1730
1731/// LowerCall - functions arguments are copied from virtual regs to
1732/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1733/// TODO: isTailCall.
1734SDValue
1735MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1736                              CallingConv::ID CallConv, bool isVarArg,
1737                              bool &isTailCall,
1738                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1739                              const SmallVectorImpl<SDValue> &OutVals,
1740                              const SmallVectorImpl<ISD::InputArg> &Ins,
1741                              DebugLoc dl, SelectionDAG &DAG,
1742                              SmallVectorImpl<SDValue> &InVals) const {
1743  // MIPs target does not yet support tail call optimization.
1744  isTailCall = false;
1745
1746  MachineFunction &MF = DAG.getMachineFunction();
1747  MachineFrameInfo *MFI = MF.getFrameInfo();
1748  const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1749  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1750  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1751
1752  // Analyze operands of the call, assigning locations to each operand.
1753  SmallVector<CCValAssign, 16> ArgLocs;
1754  CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1755                 *DAG.getContext());
1756
1757  if (Subtarget->isABI_O32())
1758    CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1759  else
1760    CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1761
1762  // Get a count of how many bytes are to be pushed on the stack.
1763  unsigned NumBytes = CCInfo.getNextStackOffset();
1764  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1765
1766  // With EABI is it possible to have 16 args on registers.
1767  SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1768  SmallVector<SDValue, 8> MemOpChains;
1769
1770  // If this is the first call, create a stack frame object that points to
1771  // a location to which .cprestore saves $gp. The offset of this frame object
1772  // is set to 0, since we know nothing about the size of the argument area at
1773  // this point.
1774  if (IsPIC && !MipsFI->getGPFI())
1775    MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1776
1777  int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1778
1779  // Walk the register/memloc assignments, inserting copies/loads.
1780  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1781    SDValue Arg = OutVals[i];
1782    CCValAssign &VA = ArgLocs[i];
1783
1784    // Promote the value if needed.
1785    switch (VA.getLocInfo()) {
1786    default: llvm_unreachable("Unknown loc info!");
1787    case CCValAssign::Full:
1788      if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1789        if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1790          Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1791        if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1792          SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1793                                   Arg, DAG.getConstant(0, MVT::i32));
1794          SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1795                                   Arg, DAG.getConstant(1, MVT::i32));
1796          if (!Subtarget->isLittle())
1797            std::swap(Lo, Hi);
1798          RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1799          RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1800          continue;
1801        }
1802      }
1803      break;
1804    case CCValAssign::SExt:
1805      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1806      break;
1807    case CCValAssign::ZExt:
1808      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1809      break;
1810    case CCValAssign::AExt:
1811      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1812      break;
1813    }
1814
1815    // Arguments that can be passed on register must be kept at
1816    // RegsToPass vector
1817    if (VA.isRegLoc()) {
1818      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1819      continue;
1820    }
1821
1822    // Register can't get to this point...
1823    assert(VA.isMemLoc());
1824
1825    // ByVal Arg.
1826    ISD::ArgFlagsTy Flags = Outs[i].Flags;
1827    if (Flags.isByVal()) {
1828      assert(Subtarget->isABI_O32() &&
1829             "No support for ByVal args by ABIs other than O32 yet.");
1830      assert(Flags.getByValSize() &&
1831             "ByVal args of size 0 should have been ignored by front-end.");
1832      WriteByValArg(Chain, dl, RegsToPass, MemOpChains, LastFI, MFI, DAG, Arg,
1833                    VA, Flags, getPointerTy());
1834      continue;
1835    }
1836
1837    // Create the frame index object for this incoming parameter
1838    LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1839                                    VA.getLocMemOffset(), true);
1840    SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1841
1842    // emit ISD::STORE whichs stores the
1843    // parameter value to a stack Location
1844    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1845                                       MachinePointerInfo(),
1846                                       false, false, 0));
1847  }
1848
1849  // Transform all store nodes into one single node because all store
1850  // nodes are independent of each other.
1851  if (!MemOpChains.empty())
1852    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1853                        &MemOpChains[0], MemOpChains.size());
1854
1855  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1856  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1857  // node so that legalize doesn't hack it.
1858  unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1859  bool LoadSymAddr = false;
1860  SDValue CalleeLo;
1861
1862  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1863    if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
1864      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1865                                          getPointerTy(), 0,MipsII:: MO_GOT);
1866      CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
1867                                            0, MipsII::MO_ABS_LO);
1868    } else {
1869      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1870                                          getPointerTy(), 0, OpFlag);
1871    }
1872
1873    LoadSymAddr = true;
1874  }
1875  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1876    Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1877                                getPointerTy(), OpFlag);
1878    LoadSymAddr = true;
1879  }
1880
1881  SDValue InFlag;
1882
1883  // Create nodes that load address of callee and copy it to T9
1884  if (IsPIC) {
1885    if (LoadSymAddr) {
1886      // Load callee address
1887      Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
1888      SDValue LoadValue = DAG.getLoad(MVT::i32, dl, Chain, Callee,
1889                                      MachinePointerInfo::getGOT(),
1890                                      false, false, 0);
1891
1892      // Use GOT+LO if callee has internal linkage.
1893      if (CalleeLo.getNode()) {
1894        SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
1895        Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
1896      } else
1897        Callee = LoadValue;
1898
1899      // Use chain output from LoadValue
1900      Chain = LoadValue.getValue(1);
1901    }
1902
1903    // copy to T9
1904    Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1905    InFlag = Chain.getValue(1);
1906    Callee = DAG.getRegister(Mips::T9, MVT::i32);
1907  }
1908
1909  // Build a sequence of copy-to-reg nodes chained together with token
1910  // chain and flag operands which copy the outgoing args into registers.
1911  // The InFlag in necessary since all emitted instructions must be
1912  // stuck together.
1913  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1914    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1915                             RegsToPass[i].second, InFlag);
1916    InFlag = Chain.getValue(1);
1917  }
1918
1919  // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1920  //             = Chain, Callee, Reg#1, Reg#2, ...
1921  //
1922  // Returns a chain & a flag for retval copy to use.
1923  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1924  SmallVector<SDValue, 8> Ops;
1925  Ops.push_back(Chain);
1926  Ops.push_back(Callee);
1927
1928  // Add argument registers to the end of the list so that they are
1929  // known live into the call.
1930  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1931    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1932                                  RegsToPass[i].second.getValueType()));
1933
1934  if (InFlag.getNode())
1935    Ops.push_back(InFlag);
1936
1937  Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1938  InFlag = Chain.getValue(1);
1939
1940  // Function can have an arbitrary number of calls, so
1941  // hold the LastArgStackLoc with the biggest offset.
1942  unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1943  unsigned NextStackOffset = CCInfo.getNextStackOffset();
1944
1945  // For O32, a minimum of four words (16 bytes) of argument space is
1946  // allocated.
1947  if (Subtarget->isABI_O32())
1948    NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1949
1950  if (MaxCallFrameSize < NextStackOffset) {
1951    MipsFI->setMaxCallFrameSize(NextStackOffset);
1952
1953    if (IsPIC) {
1954      // $gp restore slot must be aligned.
1955      unsigned StackAlignment = TFL->getStackAlignment();
1956      NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1957                        StackAlignment * StackAlignment;
1958      int GPFI = MipsFI->getGPFI();
1959      MFI->setObjectOffset(GPFI, NextStackOffset);
1960    }
1961  }
1962
1963  // Extend range of indices of frame objects for outgoing arguments that were
1964  // created during this function call. Skip this step if no such objects were
1965  // created.
1966  if (LastFI)
1967    MipsFI->extendOutArgFIRange(FirstFI, LastFI);
1968
1969  // Create the CALLSEQ_END node.
1970  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1971                             DAG.getIntPtrConstant(0, true), InFlag);
1972  InFlag = Chain.getValue(1);
1973
1974  // Handle result values, copying them out of physregs into vregs that we
1975  // return.
1976  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1977                         Ins, dl, DAG, InVals);
1978}
1979
1980/// LowerCallResult - Lower the result values of a call into the
1981/// appropriate copies out of appropriate physical registers.
1982SDValue
1983MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1984                                    CallingConv::ID CallConv, bool isVarArg,
1985                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1986                                    DebugLoc dl, SelectionDAG &DAG,
1987                                    SmallVectorImpl<SDValue> &InVals) const {
1988  // Assign locations to each value returned by this call.
1989  SmallVector<CCValAssign, 16> RVLocs;
1990  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1991                 RVLocs, *DAG.getContext());
1992
1993  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1994
1995  // Copy all of the result registers out of their specified physreg.
1996  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1997    Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1998                               RVLocs[i].getValVT(), InFlag).getValue(1);
1999    InFlag = Chain.getValue(2);
2000    InVals.push_back(Chain.getValue(0));
2001  }
2002
2003  return Chain;
2004}
2005
2006//===----------------------------------------------------------------------===//
2007//             Formal Arguments Calling Convention Implementation
2008//===----------------------------------------------------------------------===//
2009static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2010                         std::vector<SDValue>& OutChains,
2011                         SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2012                         const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2013  unsigned LocMem = VA.getLocMemOffset();
2014  unsigned FirstWord = LocMem / 4;
2015
2016  // copy register A0 - A3 to frame object
2017  for (unsigned i = 0; i < NumWords; ++i) {
2018    unsigned CurWord = FirstWord + i;
2019    if (CurWord >= O32IntRegsSize)
2020      break;
2021
2022    unsigned SrcReg = O32IntRegs[CurWord];
2023    unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2024    SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2025                                   DAG.getConstant(i * 4, MVT::i32));
2026    SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2027                                 StorePtr, MachinePointerInfo(), false,
2028                                 false, 0);
2029    OutChains.push_back(Store);
2030  }
2031}
2032
2033/// LowerFormalArguments - transform physical registers into virtual registers
2034/// and generate load operations for arguments places on the stack.
2035SDValue
2036MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2037                                         CallingConv::ID CallConv,
2038                                         bool isVarArg,
2039                                         const SmallVectorImpl<ISD::InputArg>
2040                                         &Ins,
2041                                         DebugLoc dl, SelectionDAG &DAG,
2042                                         SmallVectorImpl<SDValue> &InVals)
2043                                          const {
2044  MachineFunction &MF = DAG.getMachineFunction();
2045  MachineFrameInfo *MFI = MF.getFrameInfo();
2046  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2047
2048  MipsFI->setVarArgsFrameIndex(0);
2049
2050  // Used with vargs to acumulate store chains.
2051  std::vector<SDValue> OutChains;
2052
2053  // Assign locations to all of the incoming arguments.
2054  SmallVector<CCValAssign, 16> ArgLocs;
2055  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2056                 ArgLocs, *DAG.getContext());
2057
2058  if (Subtarget->isABI_O32())
2059    CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2060  else
2061    CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2062
2063  int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2064
2065  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2066    CCValAssign &VA = ArgLocs[i];
2067
2068    // Arguments stored on registers
2069    if (VA.isRegLoc()) {
2070      EVT RegVT = VA.getLocVT();
2071      unsigned ArgReg = VA.getLocReg();
2072      TargetRegisterClass *RC = 0;
2073
2074      if (RegVT == MVT::i32)
2075        RC = Mips::CPURegsRegisterClass;
2076      else if (RegVT == MVT::f32)
2077        RC = Mips::FGR32RegisterClass;
2078      else if (RegVT == MVT::f64) {
2079        if (!Subtarget->isSingleFloat())
2080          RC = Mips::AFGR64RegisterClass;
2081      } else
2082        llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2083
2084      // Transform the arguments stored on
2085      // physical registers into virtual ones
2086      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2087      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2088
2089      // If this is an 8 or 16-bit value, it has been passed promoted
2090      // to 32 bits.  Insert an assert[sz]ext to capture this, then
2091      // truncate to the right size.
2092      if (VA.getLocInfo() != CCValAssign::Full) {
2093        unsigned Opcode = 0;
2094        if (VA.getLocInfo() == CCValAssign::SExt)
2095          Opcode = ISD::AssertSext;
2096        else if (VA.getLocInfo() == CCValAssign::ZExt)
2097          Opcode = ISD::AssertZext;
2098        if (Opcode)
2099          ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2100                                 DAG.getValueType(VA.getValVT()));
2101        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2102      }
2103
2104      // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2105      if (Subtarget->isABI_O32()) {
2106        if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2107          ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2108        if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2109          unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2110                                    VA.getLocReg()+1, RC);
2111          SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2112          if (!Subtarget->isLittle())
2113            std::swap(ArgValue, ArgValue2);
2114          ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2115                                 ArgValue, ArgValue2);
2116        }
2117      }
2118
2119      InVals.push_back(ArgValue);
2120    } else { // VA.isRegLoc()
2121
2122      // sanity check
2123      assert(VA.isMemLoc());
2124
2125      ISD::ArgFlagsTy Flags = Ins[i].Flags;
2126
2127      if (Flags.isByVal()) {
2128        assert(Subtarget->isABI_O32() &&
2129               "No support for ByVal args by ABIs other than O32 yet.");
2130        assert(Flags.getByValSize() &&
2131               "ByVal args of size 0 should have been ignored by front-end.");
2132        unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2133        LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2134                                        true);
2135        SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2136        InVals.push_back(FIN);
2137        ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2138
2139        continue;
2140      }
2141
2142      // The stack pointer offset is relative to the caller stack frame.
2143      LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2144                                      VA.getLocMemOffset(), true);
2145
2146      // Create load nodes to retrieve arguments from the stack
2147      SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2148      InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2149                                   MachinePointerInfo::getFixedStack(LastFI),
2150                                   false, false, 0));
2151    }
2152  }
2153
2154  // The mips ABIs for returning structs by value requires that we copy
2155  // the sret argument into $v0 for the return. Save the argument into
2156  // a virtual register so that we can access it from the return points.
2157  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2158    unsigned Reg = MipsFI->getSRetReturnReg();
2159    if (!Reg) {
2160      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2161      MipsFI->setSRetReturnReg(Reg);
2162    }
2163    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2164    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2165  }
2166
2167  if (isVarArg && Subtarget->isABI_O32()) {
2168    // Record the frame index of the first variable argument
2169    // which is a value necessary to VASTART.
2170    unsigned NextStackOffset = CCInfo.getNextStackOffset();
2171    assert(NextStackOffset % 4 == 0 &&
2172           "NextStackOffset must be aligned to 4-byte boundaries.");
2173    LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2174    MipsFI->setVarArgsFrameIndex(LastFI);
2175
2176    // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2177    // copy the integer registers that have not been used for argument passing
2178    // to the caller's stack frame.
2179    for (; NextStackOffset < 16; NextStackOffset += 4) {
2180      TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2181      unsigned Idx = NextStackOffset / 4;
2182      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2183      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2184      LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2185      SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2186      OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2187                                       MachinePointerInfo(),
2188                                       false, false, 0));
2189    }
2190  }
2191
2192  MipsFI->setLastInArgFI(LastFI);
2193
2194  // All stores are grouped in one node to allow the matching between
2195  // the size of Ins and InVals. This only happens when on varg functions
2196  if (!OutChains.empty()) {
2197    OutChains.push_back(Chain);
2198    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2199                        &OutChains[0], OutChains.size());
2200  }
2201
2202  return Chain;
2203}
2204
2205//===----------------------------------------------------------------------===//
2206//               Return Value Calling Convention Implementation
2207//===----------------------------------------------------------------------===//
2208
2209SDValue
2210MipsTargetLowering::LowerReturn(SDValue Chain,
2211                                CallingConv::ID CallConv, bool isVarArg,
2212                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2213                                const SmallVectorImpl<SDValue> &OutVals,
2214                                DebugLoc dl, SelectionDAG &DAG) const {
2215
2216  // CCValAssign - represent the assignment of
2217  // the return value to a location
2218  SmallVector<CCValAssign, 16> RVLocs;
2219
2220  // CCState - Info about the registers and stack slot.
2221  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2222                 RVLocs, *DAG.getContext());
2223
2224  // Analize return values.
2225  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2226
2227  // If this is the first return lowered for this function, add
2228  // the regs to the liveout set for the function.
2229  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2230    for (unsigned i = 0; i != RVLocs.size(); ++i)
2231      if (RVLocs[i].isRegLoc())
2232        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2233  }
2234
2235  SDValue Flag;
2236
2237  // Copy the result values into the output registers.
2238  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2239    CCValAssign &VA = RVLocs[i];
2240    assert(VA.isRegLoc() && "Can only return in registers!");
2241
2242    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243                             OutVals[i], Flag);
2244
2245    // guarantee that all emitted copies are
2246    // stuck together, avoiding something bad
2247    Flag = Chain.getValue(1);
2248  }
2249
2250  // The mips ABIs for returning structs by value requires that we copy
2251  // the sret argument into $v0 for the return. We saved the argument into
2252  // a virtual register in the entry block, so now we copy the value out
2253  // and into $v0.
2254  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2255    MachineFunction &MF      = DAG.getMachineFunction();
2256    MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2257    unsigned Reg = MipsFI->getSRetReturnReg();
2258
2259    if (!Reg)
2260      llvm_unreachable("sret virtual register not created in the entry block");
2261    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2262
2263    Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2264    Flag = Chain.getValue(1);
2265  }
2266
2267  // Return on Mips is always a "jr $ra"
2268  if (Flag.getNode())
2269    return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2270                       Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2271  else // Return Void
2272    return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2273                       Chain, DAG.getRegister(Mips::RA, MVT::i32));
2274}
2275
2276//===----------------------------------------------------------------------===//
2277//                           Mips Inline Assembly Support
2278//===----------------------------------------------------------------------===//
2279
2280/// getConstraintType - Given a constraint letter, return the type of
2281/// constraint it is for this target.
2282MipsTargetLowering::ConstraintType MipsTargetLowering::
2283getConstraintType(const std::string &Constraint) const
2284{
2285  // Mips specific constrainy
2286  // GCC config/mips/constraints.md
2287  //
2288  // 'd' : An address register. Equivalent to r
2289  //       unless generating MIPS16 code.
2290  // 'y' : Equivalent to r; retained for
2291  //       backwards compatibility.
2292  // 'f' : Floating Point registers.
2293  if (Constraint.size() == 1) {
2294    switch (Constraint[0]) {
2295      default : break;
2296      case 'd':
2297      case 'y':
2298      case 'f':
2299        return C_RegisterClass;
2300        break;
2301    }
2302  }
2303  return TargetLowering::getConstraintType(Constraint);
2304}
2305
2306/// Examine constraint type and operand type and determine a weight value.
2307/// This object must already have been set up with the operand type
2308/// and the current alternative constraint selected.
2309TargetLowering::ConstraintWeight
2310MipsTargetLowering::getSingleConstraintMatchWeight(
2311    AsmOperandInfo &info, const char *constraint) const {
2312  ConstraintWeight weight = CW_Invalid;
2313  Value *CallOperandVal = info.CallOperandVal;
2314    // If we don't have a value, we can't do a match,
2315    // but allow it at the lowest weight.
2316  if (CallOperandVal == NULL)
2317    return CW_Default;
2318  const Type *type = CallOperandVal->getType();
2319  // Look at the constraint type.
2320  switch (*constraint) {
2321  default:
2322    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2323    break;
2324  case 'd':
2325  case 'y':
2326    if (type->isIntegerTy())
2327      weight = CW_Register;
2328    break;
2329  case 'f':
2330    if (type->isFloatTy())
2331      weight = CW_Register;
2332    break;
2333  }
2334  return weight;
2335}
2336
2337/// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
2338/// return a list of registers that can be used to satisfy the constraint.
2339/// This should only be used for C_RegisterClass constraints.
2340std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2341getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2342{
2343  if (Constraint.size() == 1) {
2344    switch (Constraint[0]) {
2345    case 'r':
2346      return std::make_pair(0U, Mips::CPURegsRegisterClass);
2347    case 'f':
2348      if (VT == MVT::f32)
2349        return std::make_pair(0U, Mips::FGR32RegisterClass);
2350      if (VT == MVT::f64)
2351        if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2352          return std::make_pair(0U, Mips::AFGR64RegisterClass);
2353    }
2354  }
2355  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2356}
2357
2358/// Given a register class constraint, like 'r', if this corresponds directly
2359/// to an LLVM register class, return a register of 0 and the register class
2360/// pointer.
2361std::vector<unsigned> MipsTargetLowering::
2362getRegClassForInlineAsmConstraint(const std::string &Constraint,
2363                                  EVT VT) const
2364{
2365  if (Constraint.size() != 1)
2366    return std::vector<unsigned>();
2367
2368  switch (Constraint[0]) {
2369    default : break;
2370    case 'r':
2371    // GCC Mips Constraint Letters
2372    case 'd':
2373    case 'y':
2374      return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
2375             Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
2376             Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
2377             Mips::T8, 0);
2378
2379    case 'f':
2380      if (VT == MVT::f32) {
2381        if (Subtarget->isSingleFloat())
2382          return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
2383                 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
2384                 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
2385                 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
2386                 Mips::F30, Mips::F31, 0);
2387        else
2388          return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
2389                 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
2390                 Mips::F28, Mips::F30, 0);
2391      }
2392
2393      if (VT == MVT::f64)
2394        if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2395          return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
2396                 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
2397                 Mips::D14, Mips::D15, 0);
2398  }
2399  return std::vector<unsigned>();
2400}
2401
2402bool
2403MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2404  // The Mips target isn't yet aware of offsets.
2405  return false;
2406}
2407
2408bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2409  if (VT != MVT::f32 && VT != MVT::f64)
2410    return false;
2411  if (Imm.isNegZero())
2412    return false;
2413  return Imm.isZero();
2414}
2415