Change the order fixed objects are created in MipsTargetLowering::LowerCall in
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
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"
35 using namespace llvm;
36
37 const 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::Ret        : return "MipsISD::Ret";
44     case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
45     case MipsISD::FPCmp      : return "MipsISD::FPCmp";
46     case MipsISD::CMovFP_T   : return "MipsISD::CMovFP_T";
47     case MipsISD::CMovFP_F   : return "MipsISD::CMovFP_F";
48     case MipsISD::FPRound    : return "MipsISD::FPRound";
49     case MipsISD::MAdd       : return "MipsISD::MAdd";
50     case MipsISD::MAddu      : return "MipsISD::MAddu";
51     case MipsISD::MSub       : return "MipsISD::MSub";
52     case MipsISD::MSubu      : return "MipsISD::MSubu";
53     case MipsISD::DivRem     : return "MipsISD::DivRem";
54     case MipsISD::DivRemU    : return "MipsISD::DivRemU";
55     case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
56     case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
57     default                  : return NULL;
58   }
59 }
60
61 MipsTargetLowering::
62 MipsTargetLowering(MipsTargetMachine &TM)
63   : TargetLowering(TM, new MipsTargetObjectFile()) {
64   Subtarget = &TM.getSubtarget<MipsSubtarget>();
65
66   // Mips does not have i1 type, so use i32 for
67   // setcc operations results (slt, sgt, ...).
68   setBooleanContents(ZeroOrOneBooleanContent);
69
70   // Set up the register classes
71   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
72   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
73
74   // When dealing with single precision only, use libcalls
75   if (!Subtarget->isSingleFloat())
76     if (!Subtarget->isFP64bit())
77       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
78
79   // Load extented operations for i1 types must be promoted
80   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
81   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
82   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
83
84   // MIPS doesn't have extending float->double load/store
85   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // Used by legalize types to correctly generate the setcc result.
89   // Without this, every float setcc comes with a AND/OR with the result,
90   // we don't want this, since the fpcmp result goes to a flag register,
91   // which is used implicitly by brcond and select operations.
92   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
93
94   // Mips Custom Operations
95   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
96   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
97   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
98   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
99   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
100   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
101   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
102   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
103   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
104   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
105   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
106   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
107
108   setOperationAction(ISD::SDIV, MVT::i32, Expand);
109   setOperationAction(ISD::SREM, MVT::i32, Expand);
110   setOperationAction(ISD::UDIV, MVT::i32, Expand);
111   setOperationAction(ISD::UREM, MVT::i32, Expand);
112
113   // Operations not directly supported by Mips.
114   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
115   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
116   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
117   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
118   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
120   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
121   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
122   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
123
124   if (!Subtarget->isMips32r2())
125     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
126
127   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
128   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
129   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
130   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
131   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
132   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
133   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
134   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
135   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
136   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
137   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
138   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
139   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
140   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
141   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
142
143   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
144
145   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
146   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
147   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
148
149   // Use the default for now
150   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
151   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
152   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
153
154   if (Subtarget->isSingleFloat())
155     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
156
157   if (!Subtarget->hasSEInReg()) {
158     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
159     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
160   }
161
162   if (!Subtarget->hasBitCount())
163     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
164
165   if (!Subtarget->hasSwap())
166     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
167
168   setTargetDAGCombine(ISD::ADDE);
169   setTargetDAGCombine(ISD::SUBE);
170   setTargetDAGCombine(ISD::SDIVREM);
171   setTargetDAGCombine(ISD::UDIVREM);
172   setTargetDAGCombine(ISD::SETCC);
173
174   setMinFunctionAlignment(2);
175
176   setStackPointerRegisterToSaveRestore(Mips::SP);
177   computeRegisterProperties();
178 }
179
180 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
181   return MVT::i32;
182 }
183
184 // SelectMadd -
185 // Transforms a subgraph in CurDAG if the following pattern is found:
186 //  (addc multLo, Lo0), (adde multHi, Hi0),
187 // where,
188 //  multHi/Lo: product of multiplication
189 //  Lo0: initial value of Lo register
190 //  Hi0: initial value of Hi register
191 // Return true if pattern matching was successful.
192 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
193   // ADDENode's second operand must be a flag output of an ADDC node in order
194   // for the matching to be successful.
195   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
196
197   if (ADDCNode->getOpcode() != ISD::ADDC)
198     return false;
199
200   SDValue MultHi = ADDENode->getOperand(0);
201   SDValue MultLo = ADDCNode->getOperand(0);
202   SDNode* MultNode = MultHi.getNode();
203   unsigned MultOpc = MultHi.getOpcode();
204
205   // MultHi and MultLo must be generated by the same node,
206   if (MultLo.getNode() != MultNode)
207     return false;
208
209   // and it must be a multiplication.
210   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
211     return false;
212
213   // MultLo amd MultHi must be the first and second output of MultNode
214   // respectively.
215   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
216     return false;
217
218   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
219   // of the values of MultNode, in which case MultNode will be removed in later
220   // phases.
221   // If there exist users other than ADDENode or ADDCNode, this function returns
222   // here, which will result in MultNode being mapped to a single MULT
223   // instruction node rather than a pair of MULT and MADD instructions being
224   // produced.
225   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
226     return false;
227
228   SDValue Chain = CurDAG->getEntryNode();
229   DebugLoc dl = ADDENode->getDebugLoc();
230
231   // create MipsMAdd(u) node
232   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
233
234   SDValue MAdd = CurDAG->getNode(MultOpc, dl,
235                                  MVT::Glue,
236                                  MultNode->getOperand(0),// Factor 0
237                                  MultNode->getOperand(1),// Factor 1
238                                  ADDCNode->getOperand(1),// Lo0
239                                  ADDENode->getOperand(1));// Hi0
240
241   // create CopyFromReg nodes
242   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
243                                               MAdd);
244   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
245                                               Mips::HI, MVT::i32,
246                                               CopyFromLo.getValue(2));
247
248   // replace uses of adde and addc here
249   if (!SDValue(ADDCNode, 0).use_empty())
250     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
251
252   if (!SDValue(ADDENode, 0).use_empty())
253     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
254
255   return true;
256 }
257
258 // SelectMsub -
259 // Transforms a subgraph in CurDAG if the following pattern is found:
260 //  (addc Lo0, multLo), (sube Hi0, multHi),
261 // where,
262 //  multHi/Lo: product of multiplication
263 //  Lo0: initial value of Lo register
264 //  Hi0: initial value of Hi register
265 // Return true if pattern matching was successful.
266 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
267   // SUBENode's second operand must be a flag output of an SUBC node in order
268   // for the matching to be successful.
269   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
270
271   if (SUBCNode->getOpcode() != ISD::SUBC)
272     return false;
273
274   SDValue MultHi = SUBENode->getOperand(1);
275   SDValue MultLo = SUBCNode->getOperand(1);
276   SDNode* MultNode = MultHi.getNode();
277   unsigned MultOpc = MultHi.getOpcode();
278
279   // MultHi and MultLo must be generated by the same node,
280   if (MultLo.getNode() != MultNode)
281     return false;
282
283   // and it must be a multiplication.
284   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
285     return false;
286
287   // MultLo amd MultHi must be the first and second output of MultNode
288   // respectively.
289   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
290     return false;
291
292   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
293   // of the values of MultNode, in which case MultNode will be removed in later
294   // phases.
295   // If there exist users other than SUBENode or SUBCNode, this function returns
296   // here, which will result in MultNode being mapped to a single MULT
297   // instruction node rather than a pair of MULT and MSUB instructions being
298   // produced.
299   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
300     return false;
301
302   SDValue Chain = CurDAG->getEntryNode();
303   DebugLoc dl = SUBENode->getDebugLoc();
304
305   // create MipsSub(u) node
306   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
307
308   SDValue MSub = CurDAG->getNode(MultOpc, dl,
309                                  MVT::Glue,
310                                  MultNode->getOperand(0),// Factor 0
311                                  MultNode->getOperand(1),// Factor 1
312                                  SUBCNode->getOperand(0),// Lo0
313                                  SUBENode->getOperand(0));// Hi0
314
315   // create CopyFromReg nodes
316   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
317                                               MSub);
318   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
319                                               Mips::HI, MVT::i32,
320                                               CopyFromLo.getValue(2));
321
322   // replace uses of sube and subc here
323   if (!SDValue(SUBCNode, 0).use_empty())
324     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
325
326   if (!SDValue(SUBENode, 0).use_empty())
327     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
328
329   return true;
330 }
331
332 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
333                                   TargetLowering::DAGCombinerInfo &DCI,
334                                   const MipsSubtarget* Subtarget) {
335   if (DCI.isBeforeLegalize())
336     return SDValue();
337
338   if (Subtarget->isMips32() && SelectMadd(N, &DAG))
339     return SDValue(N, 0);
340
341   return SDValue();
342 }
343
344 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
345                                   TargetLowering::DAGCombinerInfo &DCI,
346                                   const MipsSubtarget* Subtarget) {
347   if (DCI.isBeforeLegalize())
348     return SDValue();
349
350   if (Subtarget->isMips32() && SelectMsub(N, &DAG))
351     return SDValue(N, 0);
352
353   return SDValue();
354 }
355
356 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
357                                     TargetLowering::DAGCombinerInfo &DCI,
358                                     const MipsSubtarget* Subtarget) {
359   if (DCI.isBeforeLegalizeOps())
360     return SDValue();
361
362   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
363                                                   MipsISD::DivRemU;
364   DebugLoc dl = N->getDebugLoc();
365
366   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
367                                N->getOperand(0), N->getOperand(1));
368   SDValue InChain = DAG.getEntryNode();
369   SDValue InGlue = DivRem;
370
371   // insert MFLO
372   if (N->hasAnyUseOfValue(0)) {
373     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
374                                             InGlue);
375     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
376     InChain = CopyFromLo.getValue(1);
377     InGlue = CopyFromLo.getValue(2);
378   }
379
380   // insert MFHI
381   if (N->hasAnyUseOfValue(1)) {
382     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
383                                                Mips::HI, MVT::i32, InGlue);
384     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
385   }
386
387   return SDValue();
388 }
389
390 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
391   switch (CC) {
392   default: llvm_unreachable("Unknown fp condition code!");
393   case ISD::SETEQ:
394   case ISD::SETOEQ: return Mips::FCOND_OEQ;
395   case ISD::SETUNE: return Mips::FCOND_UNE;
396   case ISD::SETLT:
397   case ISD::SETOLT: return Mips::FCOND_OLT;
398   case ISD::SETGT:
399   case ISD::SETOGT: return Mips::FCOND_OGT;
400   case ISD::SETLE:
401   case ISD::SETOLE: return Mips::FCOND_OLE;
402   case ISD::SETGE:
403   case ISD::SETOGE: return Mips::FCOND_OGE;
404   case ISD::SETULT: return Mips::FCOND_ULT;
405   case ISD::SETULE: return Mips::FCOND_ULE;
406   case ISD::SETUGT: return Mips::FCOND_UGT;
407   case ISD::SETUGE: return Mips::FCOND_UGE;
408   case ISD::SETUO:  return Mips::FCOND_UN;
409   case ISD::SETO:   return Mips::FCOND_OR;
410   case ISD::SETNE:
411   case ISD::SETONE: return Mips::FCOND_ONE;
412   case ISD::SETUEQ: return Mips::FCOND_UEQ;
413   }
414 }
415
416
417 // Returns true if condition code has to be inverted.
418 static bool InvertFPCondCode(Mips::CondCode CC) {
419   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
420     return false;
421
422   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
423     return true;
424
425   assert(false && "Illegal Condition Code");
426   return false;
427 }
428
429 // Creates and returns an FPCmp node from a setcc node.
430 // Returns Op if setcc is not a floating point comparison.
431 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
432   // must be a SETCC node
433   if (Op.getOpcode() != ISD::SETCC)
434     return Op;
435
436   SDValue LHS = Op.getOperand(0);
437
438   if (!LHS.getValueType().isFloatingPoint())
439     return Op;
440
441   SDValue RHS = Op.getOperand(1);
442   DebugLoc dl = Op.getDebugLoc();
443
444   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
445   // node if necessary.
446   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
447
448   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
449                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
450 }
451
452 // Creates and returns a CMovFPT/F node.
453 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
454                             SDValue False, DebugLoc DL) {
455   bool invert = InvertFPCondCode((Mips::CondCode)
456                                  cast<ConstantSDNode>(Cond.getOperand(2))
457                                  ->getSExtValue());
458
459   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
460                      True.getValueType(), True, False, Cond);
461 }
462
463 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
464                                    TargetLowering::DAGCombinerInfo &DCI,
465                                    const MipsSubtarget* Subtarget) {
466   if (DCI.isBeforeLegalizeOps())
467     return SDValue();
468
469   SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
470
471   if (Cond.getOpcode() != MipsISD::FPCmp)
472     return SDValue();
473
474   SDValue True  = DAG.getConstant(1, MVT::i32);
475   SDValue False = DAG.getConstant(0, MVT::i32);
476
477   return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
478 }
479
480 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
481   const {
482   SelectionDAG &DAG = DCI.DAG;
483   unsigned opc = N->getOpcode();
484
485   switch (opc) {
486   default: break;
487   case ISD::ADDE:
488     return PerformADDECombine(N, DAG, DCI, Subtarget);
489   case ISD::SUBE:
490     return PerformSUBECombine(N, DAG, DCI, Subtarget);
491   case ISD::SDIVREM:
492   case ISD::UDIVREM:
493     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
494   case ISD::SETCC:
495     return PerformSETCCCombine(N, DAG, DCI, Subtarget);
496   }
497
498   return SDValue();
499 }
500
501 SDValue MipsTargetLowering::
502 LowerOperation(SDValue Op, SelectionDAG &DAG) const
503 {
504   switch (Op.getOpcode())
505   {
506     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
507     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
508     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
509     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
510     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
511     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
512     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
513     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
514     case ISD::SELECT:             return LowerSELECT(Op, DAG);
515     case ISD::VASTART:            return LowerVASTART(Op, DAG);
516   }
517   return SDValue();
518 }
519
520 //===----------------------------------------------------------------------===//
521 //  Lower helper functions
522 //===----------------------------------------------------------------------===//
523
524 // AddLiveIn - This helper function adds the specified physical register to the
525 // MachineFunction as a live in value.  It also creates a corresponding
526 // virtual register for it.
527 static unsigned
528 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
529 {
530   assert(RC->contains(PReg) && "Not the correct regclass!");
531   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
532   MF.getRegInfo().addLiveIn(PReg, VReg);
533   return VReg;
534 }
535
536 // Get fp branch code (not opcode) from condition code.
537 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
538   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
539     return Mips::BRANCH_T;
540
541   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
542     return Mips::BRANCH_F;
543
544   return Mips::BRANCH_INVALID;
545 }
546
547 MachineBasicBlock *
548 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
549                                                 MachineBasicBlock *BB) const {
550   // There is no need to expand CMov instructions if target has
551   // conditional moves.
552   if (Subtarget->hasCondMov())
553     return BB;
554
555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
556   bool isFPCmp = false;
557   DebugLoc dl = MI->getDebugLoc();
558   unsigned Opc;
559
560   switch (MI->getOpcode()) {
561   default: assert(false && "Unexpected instr type to insert");
562   case Mips::MOVT:
563   case Mips::MOVT_S:
564   case Mips::MOVT_D:
565     isFPCmp = true;
566     Opc = Mips::BC1F;
567     break;
568   case Mips::MOVF:
569   case Mips::MOVF_S:
570   case Mips::MOVF_D:
571     isFPCmp = true;
572     Opc = Mips::BC1T;
573     break;
574   case Mips::MOVZ_I:
575   case Mips::MOVZ_S:
576   case Mips::MOVZ_D:
577     Opc = Mips::BNE;
578     break;
579   case Mips::MOVN_I:
580   case Mips::MOVN_S:
581   case Mips::MOVN_D:
582     Opc = Mips::BEQ;
583     break;
584   }
585
586   // To "insert" a SELECT_CC instruction, we actually have to insert the
587   // diamond control-flow pattern.  The incoming instruction knows the
588   // destination vreg to set, the condition code register to branch on, the
589   // true/false values to select between, and a branch opcode to use.
590   const BasicBlock *LLVM_BB = BB->getBasicBlock();
591   MachineFunction::iterator It = BB;
592   ++It;
593
594   //  thisMBB:
595   //  ...
596   //   TrueVal = ...
597   //   setcc r1, r2, r3
598   //   bNE   r1, r0, copy1MBB
599   //   fallthrough --> copy0MBB
600   MachineBasicBlock *thisMBB  = BB;
601   MachineFunction *F = BB->getParent();
602   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
603   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
604   F->insert(It, copy0MBB);
605   F->insert(It, sinkMBB);
606
607   // Transfer the remainder of BB and its successor edges to sinkMBB.
608   sinkMBB->splice(sinkMBB->begin(), BB,
609                   llvm::next(MachineBasicBlock::iterator(MI)),
610                   BB->end());
611   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
612
613   // Next, add the true and fallthrough blocks as its successors.
614   BB->addSuccessor(copy0MBB);
615   BB->addSuccessor(sinkMBB);
616
617   // Emit the right instruction according to the type of the operands compared
618   if (isFPCmp)
619     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
620   else
621     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
622       .addReg(Mips::ZERO).addMBB(sinkMBB);
623
624
625   //  copy0MBB:
626   //   %FalseValue = ...
627   //   # fallthrough to sinkMBB
628   BB = copy0MBB;
629
630   // Update machine-CFG edges
631   BB->addSuccessor(sinkMBB);
632
633   //  sinkMBB:
634   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
635   //  ...
636   BB = sinkMBB;
637
638   if (isFPCmp)
639     BuildMI(*BB, BB->begin(), dl,
640             TII->get(Mips::PHI), MI->getOperand(0).getReg())
641       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
642       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
643   else
644     BuildMI(*BB, BB->begin(), dl,
645             TII->get(Mips::PHI), MI->getOperand(0).getReg())
646       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
647       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
648
649   MI->eraseFromParent();   // The pseudo instruction is gone now.
650   return BB;
651 }
652
653 //===----------------------------------------------------------------------===//
654 //  Misc Lower Operation implementation
655 //===----------------------------------------------------------------------===//
656
657 SDValue MipsTargetLowering::
658 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
659 {
660   if (!Subtarget->isMips1())
661     return Op;
662
663   MachineFunction &MF = DAG.getMachineFunction();
664   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
665
666   SDValue Chain = DAG.getEntryNode();
667   DebugLoc dl = Op.getDebugLoc();
668   SDValue Src = Op.getOperand(0);
669
670   // Set the condition register
671   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
672   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
673   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
674
675   SDValue Cst = DAG.getConstant(3, MVT::i32);
676   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
677   Cst = DAG.getConstant(2, MVT::i32);
678   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
679
680   SDValue InFlag(0, 0);
681   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
682
683   // Emit the round instruction and bit convert to integer
684   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
685                               Src, CondReg.getValue(1));
686   SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
687   return BitCvt;
688 }
689
690 SDValue MipsTargetLowering::
691 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
692 {
693   SDValue Chain = Op.getOperand(0);
694   SDValue Size = Op.getOperand(1);
695   DebugLoc dl = Op.getDebugLoc();
696
697   // Get a reference from Mips stack pointer
698   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
699
700   // Subtract the dynamic size from the actual stack size to
701   // obtain the new stack size.
702   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
703
704   // The Sub result contains the new stack start address, so it
705   // must be placed in the stack pointer register.
706   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
707
708   // This node always has two return values: a new stack pointer
709   // value and a chain
710   SDValue Ops[2] = { Sub, Chain };
711   return DAG.getMergeValues(Ops, 2, dl);
712 }
713
714 SDValue MipsTargetLowering::
715 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
716 {
717   // The first operand is the chain, the second is the condition, the third is
718   // the block to branch to if the condition is true.
719   SDValue Chain = Op.getOperand(0);
720   SDValue Dest = Op.getOperand(2);
721   DebugLoc dl = Op.getDebugLoc();
722
723   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
724
725   // Return if flag is not set by a floating point comparison.
726   if (CondRes.getOpcode() != MipsISD::FPCmp)
727     return Op;
728
729   SDValue CCNode  = CondRes.getOperand(2);
730   Mips::CondCode CC =
731     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
732   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
733
734   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
735                      Dest, CondRes);
736 }
737
738 SDValue MipsTargetLowering::
739 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
740 {
741   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
742
743   // Return if flag is not set by a floating point comparison.
744   if (Cond.getOpcode() != MipsISD::FPCmp)
745     return Op;
746
747   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
748                       Op.getDebugLoc());
749 }
750
751 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
752                                                SelectionDAG &DAG) const {
753   // FIXME there isn't actually debug info here
754   DebugLoc dl = Op.getDebugLoc();
755   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
756
757   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
758     SDVTList VTs = DAG.getVTList(MVT::i32);
759
760     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
761
762     // %gp_rel relocation
763     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
764       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
765                                               MipsII::MO_GPREL);
766       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
767       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
768       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
769     }
770     // %hi/%lo relocation
771     SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
772                                               MipsII::MO_ABS_HI);
773     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
774                                               MipsII::MO_ABS_LO);
775     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
776     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
777     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
778   } else {
779     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
780                                             MipsII::MO_GOT);
781     SDValue ResNode = DAG.getLoad(MVT::i32, dl,
782                                   DAG.getEntryNode(), GA, MachinePointerInfo(),
783                                   false, false, 0);
784     // On functions and global targets not internal linked only
785     // a load from got/GP is necessary for PIC to work.
786     if (!GV->hasInternalLinkage() &&
787         (!GV->hasLocalLinkage() || isa<Function>(GV)))
788       return ResNode;
789     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
790                                               MipsII::MO_ABS_LO);
791     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
792     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
793   }
794
795   llvm_unreachable("Dont know how to handle GlobalAddress");
796   return SDValue(0,0);
797 }
798
799 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
800                                               SelectionDAG &DAG) const {
801   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
802   // FIXME there isn't actually debug info here
803   DebugLoc dl = Op.getDebugLoc();
804
805   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
806     // %hi/%lo relocation
807     SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
808                                        MipsII::MO_ABS_HI);
809     SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
810                                        MipsII::MO_ABS_LO);
811     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
812     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
813     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
814   }
815
816   SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
817                                             MipsII::MO_GOT);
818   SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
819                                            MipsII::MO_ABS_LO);
820   SDValue Load = DAG.getLoad(MVT::i32, dl,
821                              DAG.getEntryNode(), BAGOTOffset,
822                              MachinePointerInfo(), false, false, 0);
823   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
824   return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
825 }
826
827 SDValue MipsTargetLowering::
828 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
829 {
830   llvm_unreachable("TLS not implemented for MIPS.");
831   return SDValue(); // Not reached
832 }
833
834 SDValue MipsTargetLowering::
835 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
836 {
837   SDValue ResNode;
838   SDValue HiPart;
839   // FIXME there isn't actually debug info here
840   DebugLoc dl = Op.getDebugLoc();
841   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
842   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
843
844   EVT PtrVT = Op.getValueType();
845   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
846
847   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
848
849   if (!IsPIC) {
850     SDValue Ops[] = { JTI };
851     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
852   } else // Emit Load from Global Pointer
853     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
854                          MachinePointerInfo(),
855                          false, false, 0);
856
857   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
858                                          MipsII::MO_ABS_LO);
859   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
860   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
861
862   return ResNode;
863 }
864
865 SDValue MipsTargetLowering::
866 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
867 {
868   SDValue ResNode;
869   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
870   const Constant *C = N->getConstVal();
871   // FIXME there isn't actually debug info here
872   DebugLoc dl = Op.getDebugLoc();
873
874   // gp_rel relocation
875   // FIXME: we should reference the constant pool using small data sections,
876   // but the asm printer currently doesn't support this feature without
877   // hacking it. This feature should come soon so we can uncomment the
878   // stuff below.
879   //if (IsInSmallSection(C->getType())) {
880   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
881   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
882   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
883
884   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
885     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
886                                              N->getOffset(), MipsII::MO_ABS_HI);
887     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
888                                              N->getOffset(), MipsII::MO_ABS_LO);
889     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
890     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
891     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
892   } else {
893     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
894                                            N->getOffset(), MipsII::MO_GOT);
895     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
896                                CP, MachinePointerInfo::getConstantPool(),
897                                false, false, 0);
898     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
899                                              N->getOffset(), MipsII::MO_ABS_LO);
900     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
901     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
902   }
903
904   return ResNode;
905 }
906
907 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
908   MachineFunction &MF = DAG.getMachineFunction();
909   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
910
911   DebugLoc dl = Op.getDebugLoc();
912   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
913                                  getPointerTy());
914
915   // vastart just stores the address of the VarArgsFrameIndex slot into the
916   // memory location argument.
917   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
918   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
919                       MachinePointerInfo(SV),
920                       false, false, 0);
921 }
922
923 //===----------------------------------------------------------------------===//
924 //                      Calling Convention Implementation
925 //===----------------------------------------------------------------------===//
926
927 #include "MipsGenCallingConv.inc"
928
929 //===----------------------------------------------------------------------===//
930 // TODO: Implement a generic logic using tblgen that can support this.
931 // Mips O32 ABI rules:
932 // ---
933 // i32 - Passed in A0, A1, A2, A3 and stack
934 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
935 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
936 // f64 - Only passed in two aliased f32 registers if no int reg has been used
937 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
938 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
939 //       go to stack.
940 //
941 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
942 //===----------------------------------------------------------------------===//
943
944 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
945                        MVT LocVT, CCValAssign::LocInfo LocInfo,
946                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
947
948   static const unsigned IntRegsSize=4, FloatRegsSize=2;
949
950   static const unsigned IntRegs[] = {
951       Mips::A0, Mips::A1, Mips::A2, Mips::A3
952   };
953   static const unsigned F32Regs[] = {
954       Mips::F12, Mips::F14
955   };
956   static const unsigned F64Regs[] = {
957       Mips::D6, Mips::D7
958   };
959
960   // Promote i8 and i16
961   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
962     LocVT = MVT::i32;
963     if (ArgFlags.isSExt())
964       LocInfo = CCValAssign::SExt;
965     else if (ArgFlags.isZExt())
966       LocInfo = CCValAssign::ZExt;
967     else
968       LocInfo = CCValAssign::AExt;
969   }
970
971   unsigned Reg;
972
973   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
974   // is true: function is vararg, argument is 3rd or higher, there is previous
975   // argument which is not f32 or f64.
976   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
977       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
978   unsigned OrigAlign = ArgFlags.getOrigAlign();
979   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
980
981   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
982     Reg = State.AllocateReg(IntRegs, IntRegsSize);
983     // If this is the first part of an i64 arg,
984     // the allocated register must be either A0 or A2.
985     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
986       Reg = State.AllocateReg(IntRegs, IntRegsSize);
987     LocVT = MVT::i32;
988   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
989     // Allocate int register and shadow next int register. If first
990     // available register is Mips::A1 or Mips::A3, shadow it too.
991     Reg = State.AllocateReg(IntRegs, IntRegsSize);
992     if (Reg == Mips::A1 || Reg == Mips::A3)
993       Reg = State.AllocateReg(IntRegs, IntRegsSize);
994     State.AllocateReg(IntRegs, IntRegsSize);
995     LocVT = MVT::i32;
996   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
997     // we are guaranteed to find an available float register
998     if (ValVT == MVT::f32) {
999       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1000       // Shadow int register
1001       State.AllocateReg(IntRegs, IntRegsSize);
1002     } else {
1003       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1004       // Shadow int registers
1005       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1006       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1007         State.AllocateReg(IntRegs, IntRegsSize);
1008       State.AllocateReg(IntRegs, IntRegsSize);
1009     }
1010   } else
1011     llvm_unreachable("Cannot handle this ValVT.");
1012
1013   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1014   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1015
1016   if (!Reg)
1017     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1018   else
1019     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1020
1021   return false; // CC must always match
1022 }
1023
1024 //===----------------------------------------------------------------------===//
1025 //                  Call Calling Convention Implementation
1026 //===----------------------------------------------------------------------===//
1027
1028 /// LowerCall - functions arguments are copied from virtual regs to
1029 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1030 /// TODO: isTailCall.
1031 SDValue
1032 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1033                               CallingConv::ID CallConv, bool isVarArg,
1034                               bool &isTailCall,
1035                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1036                               const SmallVectorImpl<SDValue> &OutVals,
1037                               const SmallVectorImpl<ISD::InputArg> &Ins,
1038                               DebugLoc dl, SelectionDAG &DAG,
1039                               SmallVectorImpl<SDValue> &InVals) const {
1040   // MIPs target does not yet support tail call optimization.
1041   isTailCall = false;
1042
1043   MachineFunction &MF = DAG.getMachineFunction();
1044   MachineFrameInfo *MFI = MF.getFrameInfo();
1045   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1046   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1047   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1048
1049   // Analyze operands of the call, assigning locations to each operand.
1050   SmallVector<CCValAssign, 16> ArgLocs;
1051   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1052                  *DAG.getContext());
1053
1054   if (Subtarget->isABI_O32()) {
1055     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1056   } else
1057     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1058
1059   // Get a count of how many bytes are to be pushed on the stack.
1060   unsigned NumBytes = CCInfo.getNextStackOffset();
1061   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1062
1063   // With EABI is it possible to have 16 args on registers.
1064   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1065   SmallVector<SDValue, 8> MemOpChains;
1066   unsigned NextStackOffset = (Subtarget->isABI_EABI() ? 0 : 16);
1067
1068   MipsFI->setHasCall();
1069
1070   // Create GP frame object if this is the first call. 
1071   // SPOffset will be updated after call frame size is known.
1072   if (IsPIC && MipsFI->getGPStackOffset() == -1)
1073     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1074
1075   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0; 
1076
1077   // Walk the register/memloc assignments, inserting copies/loads.
1078   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1079     SDValue Arg = OutVals[i];
1080     CCValAssign &VA = ArgLocs[i];
1081
1082     // Promote the value if needed.
1083     switch (VA.getLocInfo()) {
1084     default: llvm_unreachable("Unknown loc info!");
1085     case CCValAssign::Full:
1086       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1087         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1088           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1089         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1090           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1091                                    Arg, DAG.getConstant(0, MVT::i32));
1092           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1093                                    Arg, DAG.getConstant(1, MVT::i32));
1094           if (!Subtarget->isLittle())
1095             std::swap(Lo, Hi);
1096           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1097           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1098           continue;
1099         }
1100       }
1101       break;
1102     case CCValAssign::SExt:
1103       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1104       break;
1105     case CCValAssign::ZExt:
1106       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1107       break;
1108     case CCValAssign::AExt:
1109       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1110       break;
1111     }
1112
1113     // Arguments that can be passed on register must be kept at
1114     // RegsToPass vector
1115     if (VA.isRegLoc()) {
1116       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1117       continue;
1118     }
1119
1120     // Register can't get to this point...
1121     assert(VA.isMemLoc());
1122
1123     // Create the frame index object for this incoming parameter
1124     // This guarantees that when allocating Local Area the firsts
1125     // 16 bytes which are alwayes reserved won't be overwritten
1126     // if O32 ABI is used. For EABI the first address is zero.
1127     NextStackOffset = VA.getLocMemOffset();
1128     LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1129                                     NextStackOffset, true);
1130     NextStackOffset += VA.getValVT().getSizeInBits()/8;
1131
1132     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1133
1134     // emit ISD::STORE whichs stores the
1135     // parameter value to a stack Location
1136     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1137                                        MachinePointerInfo(),
1138                                        false, false, 0));
1139   }
1140
1141   // Transform all store nodes into one single node because all store
1142   // nodes are independent of each other.
1143   if (!MemOpChains.empty())
1144     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1145                         &MemOpChains[0], MemOpChains.size());
1146
1147   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1148   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1149   // node so that legalize doesn't hack it.
1150   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1151   bool LoadSymAddr = false;
1152   SDValue CalleeLo;
1153
1154   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1155     if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
1156       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1157                                           getPointerTy(), 0,MipsII:: MO_GOT);
1158       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
1159                                             0, MipsII::MO_ABS_LO);
1160     } else {
1161       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1162                                           getPointerTy(), 0, OpFlag);
1163     }
1164
1165     LoadSymAddr = true;
1166   }
1167   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1168     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1169                                 getPointerTy(), OpFlag);
1170     LoadSymAddr = true;
1171   }
1172
1173   SDValue InFlag;
1174
1175   // Create nodes that load address of callee and copy it to T9
1176   if (IsPIC) {
1177     if (LoadSymAddr) {
1178       // Load callee address
1179       SDValue LoadValue = DAG.getLoad(MVT::i32, dl, Chain, Callee,
1180                                       MachinePointerInfo::getGOT(),
1181                                       false, false, 0);
1182
1183       // Use GOT+LO if callee has internal linkage.
1184       if (CalleeLo.getNode()) {
1185         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
1186         Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
1187       } else
1188         Callee = LoadValue;
1189
1190       // Use chain output from LoadValue 
1191       Chain = LoadValue.getValue(1);
1192     }
1193
1194     // copy to T9
1195     Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1196     InFlag = Chain.getValue(1);
1197     Callee = DAG.getRegister(Mips::T9, MVT::i32);
1198   }
1199
1200   // Build a sequence of copy-to-reg nodes chained together with token
1201   // chain and flag operands which copy the outgoing args into registers.
1202   // The InFlag in necessary since all emitted instructions must be
1203   // stuck together.
1204   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1205     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1206                              RegsToPass[i].second, InFlag);
1207     InFlag = Chain.getValue(1);
1208   }
1209
1210   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1211   //             = Chain, Callee, Reg#1, Reg#2, ...
1212   //
1213   // Returns a chain & a flag for retval copy to use.
1214   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1215   SmallVector<SDValue, 8> Ops;
1216   Ops.push_back(Chain);
1217   Ops.push_back(Callee);
1218
1219   // Add argument registers to the end of the list so that they are
1220   // known live into the call.
1221   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1222     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1223                                   RegsToPass[i].second.getValueType()));
1224
1225   if (InFlag.getNode())
1226     Ops.push_back(InFlag);
1227
1228   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1229   InFlag = Chain.getValue(1);
1230
1231   // Create a stack location to hold GP when PIC is used. This stack
1232   // location is used on function prologue to save GP and also after all
1233   // emitted CALL's to restore GP.
1234   if (IsPIC) {
1235       // Function can have an arbitrary number of calls, so
1236       // hold the LastArgStackLoc with the biggest offset.
1237       int MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1238
1239       if (MaxCallFrameSize < (int)NextStackOffset) {
1240         MipsFI->setMaxCallFrameSize(NextStackOffset);
1241
1242         // $gp restore slot must be aligned.
1243         unsigned StackAlignment = TFL->getStackAlignment();
1244         NextStackOffset = (NextStackOffset + StackAlignment - 1) / 
1245                           StackAlignment * StackAlignment;
1246         MipsFI->setGPStackOffset(NextStackOffset);
1247       }
1248   }
1249
1250   // Extend range of indices of frame objects for outgoing arguments that were
1251   // created during this function call. Skip this step if no such objects were
1252   // created.
1253   if (LastFI)
1254     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
1255
1256   // Create the CALLSEQ_END node.
1257   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1258                              DAG.getIntPtrConstant(0, true), InFlag);
1259   InFlag = Chain.getValue(1);
1260
1261   // Handle result values, copying them out of physregs into vregs that we
1262   // return.
1263   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1264                          Ins, dl, DAG, InVals);
1265 }
1266
1267 /// LowerCallResult - Lower the result values of a call into the
1268 /// appropriate copies out of appropriate physical registers.
1269 SDValue
1270 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1271                                     CallingConv::ID CallConv, bool isVarArg,
1272                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1273                                     DebugLoc dl, SelectionDAG &DAG,
1274                                     SmallVectorImpl<SDValue> &InVals) const {
1275
1276   // Assign locations to each value returned by this call.
1277   SmallVector<CCValAssign, 16> RVLocs;
1278   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1279                  RVLocs, *DAG.getContext());
1280
1281   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1282
1283   // Copy all of the result registers out of their specified physreg.
1284   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1285     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1286                                RVLocs[i].getValVT(), InFlag).getValue(1);
1287     InFlag = Chain.getValue(2);
1288     InVals.push_back(Chain.getValue(0));
1289   }
1290
1291   return Chain;
1292 }
1293
1294 //===----------------------------------------------------------------------===//
1295 //             Formal Arguments Calling Convention Implementation
1296 //===----------------------------------------------------------------------===//
1297
1298 /// LowerFormalArguments - transform physical registers into virtual registers
1299 /// and generate load operations for arguments places on the stack.
1300 SDValue
1301 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1302                                          CallingConv::ID CallConv,
1303                                          bool isVarArg,
1304                                          const SmallVectorImpl<ISD::InputArg>
1305                                          &Ins,
1306                                          DebugLoc dl, SelectionDAG &DAG,
1307                                          SmallVectorImpl<SDValue> &InVals)
1308                                           const {
1309
1310   MachineFunction &MF = DAG.getMachineFunction();
1311   MachineFrameInfo *MFI = MF.getFrameInfo();
1312   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1313
1314   MipsFI->setVarArgsFrameIndex(0);
1315
1316   // Used with vargs to acumulate store chains.
1317   std::vector<SDValue> OutChains;
1318
1319   // Keep track of the last register used for arguments
1320   unsigned ArgRegEnd = 0;
1321
1322   // Assign locations to all of the incoming arguments.
1323   SmallVector<CCValAssign, 16> ArgLocs;
1324   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1325                  ArgLocs, *DAG.getContext());
1326
1327   if (Subtarget->isABI_O32())
1328     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
1329   else
1330     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1331
1332   unsigned NextStackOffset = (Subtarget->isABI_EABI() ? 0 : 16);
1333   EVT LastRegArgValVT;
1334   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
1335
1336   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1337     CCValAssign &VA = ArgLocs[i];
1338
1339     // Arguments stored on registers
1340     if (VA.isRegLoc()) {
1341       EVT RegVT = VA.getLocVT();
1342       ArgRegEnd = VA.getLocReg();
1343       LastRegArgValVT = VA.getValVT();
1344       TargetRegisterClass *RC = 0;
1345
1346       if (RegVT == MVT::i32)
1347         RC = Mips::CPURegsRegisterClass;
1348       else if (RegVT == MVT::f32)
1349         RC = Mips::FGR32RegisterClass;
1350       else if (RegVT == MVT::f64) {
1351         if (!Subtarget->isSingleFloat())
1352           RC = Mips::AFGR64RegisterClass;
1353       } else
1354         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1355
1356       // Transform the arguments stored on
1357       // physical registers into virtual ones
1358       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1359       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1360
1361       // If this is an 8 or 16-bit value, it has been passed promoted
1362       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1363       // truncate to the right size.
1364       if (VA.getLocInfo() != CCValAssign::Full) {
1365         unsigned Opcode = 0;
1366         if (VA.getLocInfo() == CCValAssign::SExt)
1367           Opcode = ISD::AssertSext;
1368         else if (VA.getLocInfo() == CCValAssign::ZExt)
1369           Opcode = ISD::AssertZext;
1370         if (Opcode)
1371           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1372                                  DAG.getValueType(VA.getValVT()));
1373         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1374       }
1375
1376       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1377       if (Subtarget->isABI_O32()) {
1378         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1379           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1380         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1381           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1382                                     VA.getLocReg()+1, RC);
1383           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1384           if (!Subtarget->isLittle())
1385             std::swap(ArgValue, ArgValue2);
1386           ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
1387                                  ArgValue, ArgValue2);
1388         }
1389       }
1390
1391       InVals.push_back(ArgValue);
1392     } else { // VA.isRegLoc()
1393
1394       // sanity check
1395       assert(VA.isMemLoc());
1396
1397       // The last argument is not a register anymore
1398       ArgRegEnd = 0;
1399
1400       // The stack pointer offset is relative to the caller stack frame.
1401       // Since the real stack size is unknown here, a negative SPOffset
1402       // is used so there's a way to adjust these offsets when the stack
1403       // size get known (on EliminateFrameIndex). A dummy SPOffset is
1404       // used instead of a direct negative address (which is recorded to
1405       // be used on emitPrologue) to avoid mis-calc of the first stack
1406       // offset on PEI::calculateFrameObjectOffsets.
1407       unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
1408       NextStackOffset = VA.getLocMemOffset() + ArgSize;
1409       LastFI = MFI->CreateFixedObject(ArgSize, 0, true);
1410       MipsFI->recordLoadArgsFI(LastFI, -(4 + VA.getLocMemOffset()));
1411
1412       // Create load nodes to retrieve arguments from the stack
1413       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
1414       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1415                                    MachinePointerInfo::getFixedStack(LastFI),
1416                                    false, false, 0));
1417     }
1418   }
1419
1420   // The mips ABIs for returning structs by value requires that we copy
1421   // the sret argument into $v0 for the return. Save the argument into
1422   // a virtual register so that we can access it from the return points.
1423   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1424     unsigned Reg = MipsFI->getSRetReturnReg();
1425     if (!Reg) {
1426       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1427       MipsFI->setSRetReturnReg(Reg);
1428     }
1429     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1430     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1431   }
1432
1433   // To meet ABI, when VARARGS are passed on registers, the registers
1434   // must have their values written to the caller stack frame. If the last
1435   // argument was placed in the stack, there's no need to save any register.
1436   if (isVarArg && Subtarget->isABI_O32()) {
1437     if (ArgRegEnd) {
1438       // Last named formal argument is passed in register.
1439
1440       // The last register argument that must be saved is Mips::A3
1441       TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1442       if (LastRegArgValVT == MVT::f64)
1443         ArgRegEnd++;
1444
1445       if (ArgRegEnd < Mips::A3) {
1446         // Both the last named formal argument and the first variable
1447         // argument are passed in registers.
1448         for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd) {
1449           unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1450           SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1451
1452           LastFI = MFI->CreateFixedObject(4, 0, true);
1453           MipsFI->recordStoreVarArgsFI(LastFI, -(4+(ArgRegEnd-Mips::A0)*4));
1454           SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1455           OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1456                                            MachinePointerInfo(),
1457                                            false, false, 0));
1458
1459           // Record the frame index of the first variable argument
1460           // which is a value necessary to VASTART.
1461           if (!MipsFI->getVarArgsFrameIndex()) {
1462             MFI->setObjectAlignment(LastFI, 4);
1463             MipsFI->setVarArgsFrameIndex(LastFI);
1464           }
1465         }
1466       } else {
1467         // Last named formal argument is in register Mips::A3, and the first
1468         // variable argument is on stack. Record the frame index of the first
1469         // variable argument.
1470         LastFI = MFI->CreateFixedObject(4, 0, true);
1471         MFI->setObjectAlignment(LastFI, 4);
1472         MipsFI->recordStoreVarArgsFI(LastFI, -20);
1473         MipsFI->setVarArgsFrameIndex(LastFI);
1474       }
1475     } else {
1476       // Last named formal argument and all the variable arguments are passed
1477       // on stack. Record the frame index of the first variable argument.
1478       LastFI = MFI->CreateFixedObject(4, 0, true);
1479       MFI->setObjectAlignment(LastFI, 4);
1480       MipsFI->recordStoreVarArgsFI(LastFI, -(4+NextStackOffset));
1481       MipsFI->setVarArgsFrameIndex(LastFI);
1482     }
1483   }
1484
1485   MipsFI->setLastInArgFI(LastFI);
1486
1487   // All stores are grouped in one node to allow the matching between
1488   // the size of Ins and InVals. This only happens when on varg functions
1489   if (!OutChains.empty()) {
1490     OutChains.push_back(Chain);
1491     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1492                         &OutChains[0], OutChains.size());
1493   }
1494
1495   return Chain;
1496 }
1497
1498 //===----------------------------------------------------------------------===//
1499 //               Return Value Calling Convention Implementation
1500 //===----------------------------------------------------------------------===//
1501
1502 SDValue
1503 MipsTargetLowering::LowerReturn(SDValue Chain,
1504                                 CallingConv::ID CallConv, bool isVarArg,
1505                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1506                                 const SmallVectorImpl<SDValue> &OutVals,
1507                                 DebugLoc dl, SelectionDAG &DAG) const {
1508
1509   // CCValAssign - represent the assignment of
1510   // the return value to a location
1511   SmallVector<CCValAssign, 16> RVLocs;
1512
1513   // CCState - Info about the registers and stack slot.
1514   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1515                  RVLocs, *DAG.getContext());
1516
1517   // Analize return values.
1518   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1519
1520   // If this is the first return lowered for this function, add
1521   // the regs to the liveout set for the function.
1522   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1523     for (unsigned i = 0; i != RVLocs.size(); ++i)
1524       if (RVLocs[i].isRegLoc())
1525         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1526   }
1527
1528   SDValue Flag;
1529
1530   // Copy the result values into the output registers.
1531   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1532     CCValAssign &VA = RVLocs[i];
1533     assert(VA.isRegLoc() && "Can only return in registers!");
1534
1535     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1536                              OutVals[i], Flag);
1537
1538     // guarantee that all emitted copies are
1539     // stuck together, avoiding something bad
1540     Flag = Chain.getValue(1);
1541   }
1542
1543   // The mips ABIs for returning structs by value requires that we copy
1544   // the sret argument into $v0 for the return. We saved the argument into
1545   // a virtual register in the entry block, so now we copy the value out
1546   // and into $v0.
1547   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1548     MachineFunction &MF      = DAG.getMachineFunction();
1549     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1550     unsigned Reg = MipsFI->getSRetReturnReg();
1551
1552     if (!Reg)
1553       llvm_unreachable("sret virtual register not created in the entry block");
1554     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1555
1556     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1557     Flag = Chain.getValue(1);
1558   }
1559
1560   // Return on Mips is always a "jr $ra"
1561   if (Flag.getNode())
1562     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1563                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1564   else // Return Void
1565     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1566                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1567 }
1568
1569 //===----------------------------------------------------------------------===//
1570 //                           Mips Inline Assembly Support
1571 //===----------------------------------------------------------------------===//
1572
1573 /// getConstraintType - Given a constraint letter, return the type of
1574 /// constraint it is for this target.
1575 MipsTargetLowering::ConstraintType MipsTargetLowering::
1576 getConstraintType(const std::string &Constraint) const
1577 {
1578   // Mips specific constrainy
1579   // GCC config/mips/constraints.md
1580   //
1581   // 'd' : An address register. Equivalent to r
1582   //       unless generating MIPS16 code.
1583   // 'y' : Equivalent to r; retained for
1584   //       backwards compatibility.
1585   // 'f' : Floating Point registers.
1586   if (Constraint.size() == 1) {
1587     switch (Constraint[0]) {
1588       default : break;
1589       case 'd':
1590       case 'y':
1591       case 'f':
1592         return C_RegisterClass;
1593         break;
1594     }
1595   }
1596   return TargetLowering::getConstraintType(Constraint);
1597 }
1598
1599 /// Examine constraint type and operand type and determine a weight value.
1600 /// This object must already have been set up with the operand type
1601 /// and the current alternative constraint selected.
1602 TargetLowering::ConstraintWeight
1603 MipsTargetLowering::getSingleConstraintMatchWeight(
1604     AsmOperandInfo &info, const char *constraint) const {
1605   ConstraintWeight weight = CW_Invalid;
1606   Value *CallOperandVal = info.CallOperandVal;
1607     // If we don't have a value, we can't do a match,
1608     // but allow it at the lowest weight.
1609   if (CallOperandVal == NULL)
1610     return CW_Default;
1611   const Type *type = CallOperandVal->getType();
1612   // Look at the constraint type.
1613   switch (*constraint) {
1614   default:
1615     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1616     break;
1617   case 'd':
1618   case 'y':
1619     if (type->isIntegerTy())
1620       weight = CW_Register;
1621     break;
1622   case 'f':
1623     if (type->isFloatTy())
1624       weight = CW_Register;
1625     break;
1626   }
1627   return weight;
1628 }
1629
1630 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1631 /// return a list of registers that can be used to satisfy the constraint.
1632 /// This should only be used for C_RegisterClass constraints.
1633 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1634 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1635 {
1636   if (Constraint.size() == 1) {
1637     switch (Constraint[0]) {
1638     case 'r':
1639       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1640     case 'f':
1641       if (VT == MVT::f32)
1642         return std::make_pair(0U, Mips::FGR32RegisterClass);
1643       if (VT == MVT::f64)
1644         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1645           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1646     }
1647   }
1648   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1649 }
1650
1651 /// Given a register class constraint, like 'r', if this corresponds directly
1652 /// to an LLVM register class, return a register of 0 and the register class
1653 /// pointer.
1654 std::vector<unsigned> MipsTargetLowering::
1655 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1656                                   EVT VT) const
1657 {
1658   if (Constraint.size() != 1)
1659     return std::vector<unsigned>();
1660
1661   switch (Constraint[0]) {
1662     default : break;
1663     case 'r':
1664     // GCC Mips Constraint Letters
1665     case 'd':
1666     case 'y':
1667       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1668              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1669              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1670              Mips::T8, 0);
1671
1672     case 'f':
1673       if (VT == MVT::f32) {
1674         if (Subtarget->isSingleFloat())
1675           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1676                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1677                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1678                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1679                  Mips::F30, Mips::F31, 0);
1680         else
1681           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1682                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1683                  Mips::F28, Mips::F30, 0);
1684       }
1685
1686       if (VT == MVT::f64)
1687         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1688           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1689                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1690                  Mips::D14, Mips::D15, 0);
1691   }
1692   return std::vector<unsigned>();
1693 }
1694
1695 bool
1696 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1697   // The Mips target isn't yet aware of offsets.
1698   return false;
1699 }
1700
1701 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1702   if (VT != MVT::f32 && VT != MVT::f64)
1703     return false;
1704   if (Imm.isNegZero())
1705     return false;
1706   return Imm.isZero();
1707 }