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