Expand 64-bit CTLZ nodes if target architecture does not support it. Add test
[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 "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 using namespace llvm;
38
39 // If I is a shifted mask, set the size (Size) and the first bit of the 
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).  
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43   if (!isShiftedMask_64(I))
44      return false;
45
46   Size = CountPopulation_64(I);
47   Pos = CountTrailingZeros_64(I);
48   return true;
49 }
50
51 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
52   switch (Opcode) {
53   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
54   case MipsISD::Hi:                return "MipsISD::Hi";
55   case MipsISD::Lo:                return "MipsISD::Lo";
56   case MipsISD::GPRel:             return "MipsISD::GPRel";
57   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
58   case MipsISD::Ret:               return "MipsISD::Ret";
59   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
60   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
61   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
62   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
63   case MipsISD::FPRound:           return "MipsISD::FPRound";
64   case MipsISD::MAdd:              return "MipsISD::MAdd";
65   case MipsISD::MAddu:             return "MipsISD::MAddu";
66   case MipsISD::MSub:              return "MipsISD::MSub";
67   case MipsISD::MSubu:             return "MipsISD::MSubu";
68   case MipsISD::DivRem:            return "MipsISD::DivRem";
69   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
70   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
71   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
72   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
73   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
74   case MipsISD::Sync:              return "MipsISD::Sync";
75   case MipsISD::Ext:               return "MipsISD::Ext";
76   case MipsISD::Ins:               return "MipsISD::Ins";
77   default:                         return NULL;
78   }
79 }
80
81 MipsTargetLowering::
82 MipsTargetLowering(MipsTargetMachine &TM)
83   : TargetLowering(TM, new MipsTargetObjectFile()),
84     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
85     HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
86     IsO32(Subtarget->isABI_O32()) {
87
88   // Mips does not have i1 type, so use i32 for
89   // setcc operations results (slt, sgt, ...).
90   setBooleanContents(ZeroOrOneBooleanContent);
91   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92
93   // Set up the register classes
94   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
95   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
96
97   if (HasMips64)
98     addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
99
100   // When dealing with single precision only, use libcalls
101   if (!Subtarget->isSingleFloat()) {
102     if (HasMips64)
103       addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
104     else
105       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
106   }
107
108   // Load extented operations for i1 types must be promoted
109   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
110   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
111   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
112
113   // MIPS doesn't have extending float->double load/store
114   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
115   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
116
117   // Used by legalize types to correctly generate the setcc result.
118   // Without this, every float setcc comes with a AND/OR with the result,
119   // we don't want this, since the fpcmp result goes to a flag register,
120   // which is used implicitly by brcond and select operations.
121   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
122
123   // Mips Custom Operations
124   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
125   setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
126   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
127   setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
128   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
129   setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
130   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
131   setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
132   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
133   setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
134   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
135   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
136   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
137   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
138   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
139   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,   Custom);
140   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
141
142   setOperationAction(ISD::SDIV, MVT::i32, Expand);
143   setOperationAction(ISD::SREM, MVT::i32, Expand);
144   setOperationAction(ISD::UDIV, MVT::i32, Expand);
145   setOperationAction(ISD::UREM, MVT::i32, Expand);
146   setOperationAction(ISD::SDIV, MVT::i64, Expand);
147   setOperationAction(ISD::SREM, MVT::i64, Expand);
148   setOperationAction(ISD::UDIV, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Operations not directly supported by Mips.
152   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
153   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
154   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
155   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
156   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
157   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
158   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
159   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
160   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
161   setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
162   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
163   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
164   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
165   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
166   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
167   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
168   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
169   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
170
171   if (!Subtarget->hasMips32r2())
172     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
173
174   if (!Subtarget->hasMips64r2())
175     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
176
177   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
178   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
179   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
180   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Custom);
181   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Custom);
182   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
183   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
184   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
185   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
186   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
187   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
188   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
189   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
190   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
191   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
192   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
193   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
194   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
195
196   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
197   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
198
199   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
200   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
201   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
202
203   // Use the default for now
204   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
205   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
206
207   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Custom);
208   setOperationAction(ISD::ATOMIC_FENCE,      MVT::Other, Custom);  
209
210   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);  
211   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);  
212   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);  
213   setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);  
214
215   setInsertFencesForAtomic(true);
216
217   if (Subtarget->isSingleFloat())
218     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
219
220   if (!Subtarget->hasSEInReg()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
222     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
223   }
224
225   if (!Subtarget->hasBitCount()) {
226     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
227     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
228   }
229
230   if (!Subtarget->hasSwap()) {
231     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
232     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
233   }
234
235   setTargetDAGCombine(ISD::ADDE);
236   setTargetDAGCombine(ISD::SUBE);
237   setTargetDAGCombine(ISD::SDIVREM);
238   setTargetDAGCombine(ISD::UDIVREM);
239   setTargetDAGCombine(ISD::SETCC);
240   setTargetDAGCombine(ISD::AND);
241   setTargetDAGCombine(ISD::OR);
242
243   setMinFunctionAlignment(2);
244
245   setStackPointerRegisterToSaveRestore(HasMips64 ? Mips::SP_64 : Mips::SP);
246   computeRegisterProperties();
247
248   setExceptionPointerRegister(Mips::A0);
249   setExceptionSelectorRegister(Mips::A1);
250 }
251
252 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
253   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
254   return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16; 
255 }
256
257 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
258   return MVT::i32;
259 }
260
261 // SelectMadd -
262 // Transforms a subgraph in CurDAG if the following pattern is found:
263 //  (addc multLo, Lo0), (adde multHi, Hi0),
264 // where,
265 //  multHi/Lo: product of multiplication
266 //  Lo0: initial value of Lo register
267 //  Hi0: initial value of Hi register
268 // Return true if pattern matching was successful.
269 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
270   // ADDENode's second operand must be a flag output of an ADDC node in order
271   // for the matching to be successful.
272   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
273
274   if (ADDCNode->getOpcode() != ISD::ADDC)
275     return false;
276
277   SDValue MultHi = ADDENode->getOperand(0);
278   SDValue MultLo = ADDCNode->getOperand(0);
279   SDNode* MultNode = MultHi.getNode();
280   unsigned MultOpc = MultHi.getOpcode();
281
282   // MultHi and MultLo must be generated by the same node,
283   if (MultLo.getNode() != MultNode)
284     return false;
285
286   // and it must be a multiplication.
287   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
288     return false;
289
290   // MultLo amd MultHi must be the first and second output of MultNode
291   // respectively.
292   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
293     return false;
294
295   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
296   // of the values of MultNode, in which case MultNode will be removed in later
297   // phases.
298   // If there exist users other than ADDENode or ADDCNode, this function returns
299   // here, which will result in MultNode being mapped to a single MULT
300   // instruction node rather than a pair of MULT and MADD instructions being
301   // produced.
302   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
303     return false;
304
305   SDValue Chain = CurDAG->getEntryNode();
306   DebugLoc dl = ADDENode->getDebugLoc();
307
308   // create MipsMAdd(u) node
309   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
310
311   SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
312                                  MultNode->getOperand(0),// Factor 0
313                                  MultNode->getOperand(1),// Factor 1
314                                  ADDCNode->getOperand(1),// Lo0
315                                  ADDENode->getOperand(1));// Hi0
316
317   // create CopyFromReg nodes
318   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
319                                               MAdd);
320   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
321                                               Mips::HI, MVT::i32,
322                                               CopyFromLo.getValue(2));
323
324   // replace uses of adde and addc here
325   if (!SDValue(ADDCNode, 0).use_empty())
326     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
327
328   if (!SDValue(ADDENode, 0).use_empty())
329     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
330
331   return true;
332 }
333
334 // SelectMsub -
335 // Transforms a subgraph in CurDAG if the following pattern is found:
336 //  (addc Lo0, multLo), (sube Hi0, multHi),
337 // where,
338 //  multHi/Lo: product of multiplication
339 //  Lo0: initial value of Lo register
340 //  Hi0: initial value of Hi register
341 // Return true if pattern matching was successful.
342 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
343   // SUBENode's second operand must be a flag output of an SUBC node in order
344   // for the matching to be successful.
345   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
346
347   if (SUBCNode->getOpcode() != ISD::SUBC)
348     return false;
349
350   SDValue MultHi = SUBENode->getOperand(1);
351   SDValue MultLo = SUBCNode->getOperand(1);
352   SDNode* MultNode = MultHi.getNode();
353   unsigned MultOpc = MultHi.getOpcode();
354
355   // MultHi and MultLo must be generated by the same node,
356   if (MultLo.getNode() != MultNode)
357     return false;
358
359   // and it must be a multiplication.
360   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
361     return false;
362
363   // MultLo amd MultHi must be the first and second output of MultNode
364   // respectively.
365   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
366     return false;
367
368   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
369   // of the values of MultNode, in which case MultNode will be removed in later
370   // phases.
371   // If there exist users other than SUBENode or SUBCNode, this function returns
372   // here, which will result in MultNode being mapped to a single MULT
373   // instruction node rather than a pair of MULT and MSUB instructions being
374   // produced.
375   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
376     return false;
377
378   SDValue Chain = CurDAG->getEntryNode();
379   DebugLoc dl = SUBENode->getDebugLoc();
380
381   // create MipsSub(u) node
382   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
383
384   SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
385                                  MultNode->getOperand(0),// Factor 0
386                                  MultNode->getOperand(1),// Factor 1
387                                  SUBCNode->getOperand(0),// Lo0
388                                  SUBENode->getOperand(0));// Hi0
389
390   // create CopyFromReg nodes
391   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
392                                               MSub);
393   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
394                                               Mips::HI, MVT::i32,
395                                               CopyFromLo.getValue(2));
396
397   // replace uses of sube and subc here
398   if (!SDValue(SUBCNode, 0).use_empty())
399     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
400
401   if (!SDValue(SUBENode, 0).use_empty())
402     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
403
404   return true;
405 }
406
407 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
408                                   TargetLowering::DAGCombinerInfo &DCI,
409                                   const MipsSubtarget* Subtarget) {
410   if (DCI.isBeforeLegalize())
411     return SDValue();
412
413   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
414       SelectMadd(N, &DAG))
415     return SDValue(N, 0);
416
417   return SDValue();
418 }
419
420 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
421                                   TargetLowering::DAGCombinerInfo &DCI,
422                                   const MipsSubtarget* Subtarget) {
423   if (DCI.isBeforeLegalize())
424     return SDValue();
425
426   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
427       SelectMsub(N, &DAG))
428     return SDValue(N, 0);
429
430   return SDValue();
431 }
432
433 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
434                                     TargetLowering::DAGCombinerInfo &DCI,
435                                     const MipsSubtarget* Subtarget) {
436   if (DCI.isBeforeLegalizeOps())
437     return SDValue();
438
439   EVT Ty = N->getValueType(0);
440   unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64; 
441   unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64; 
442   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
443                                                   MipsISD::DivRemU;
444   DebugLoc dl = N->getDebugLoc();
445
446   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
447                                N->getOperand(0), N->getOperand(1));
448   SDValue InChain = DAG.getEntryNode();
449   SDValue InGlue = DivRem;
450
451   // insert MFLO
452   if (N->hasAnyUseOfValue(0)) {
453     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
454                                             InGlue);
455     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
456     InChain = CopyFromLo.getValue(1);
457     InGlue = CopyFromLo.getValue(2);
458   }
459
460   // insert MFHI
461   if (N->hasAnyUseOfValue(1)) {
462     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
463                                             HI, Ty, InGlue);
464     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
465   }
466
467   return SDValue();
468 }
469
470 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
471   switch (CC) {
472   default: llvm_unreachable("Unknown fp condition code!");
473   case ISD::SETEQ:
474   case ISD::SETOEQ: return Mips::FCOND_OEQ;
475   case ISD::SETUNE: return Mips::FCOND_UNE;
476   case ISD::SETLT:
477   case ISD::SETOLT: return Mips::FCOND_OLT;
478   case ISD::SETGT:
479   case ISD::SETOGT: return Mips::FCOND_OGT;
480   case ISD::SETLE:
481   case ISD::SETOLE: return Mips::FCOND_OLE;
482   case ISD::SETGE:
483   case ISD::SETOGE: return Mips::FCOND_OGE;
484   case ISD::SETULT: return Mips::FCOND_ULT;
485   case ISD::SETULE: return Mips::FCOND_ULE;
486   case ISD::SETUGT: return Mips::FCOND_UGT;
487   case ISD::SETUGE: return Mips::FCOND_UGE;
488   case ISD::SETUO:  return Mips::FCOND_UN;
489   case ISD::SETO:   return Mips::FCOND_OR;
490   case ISD::SETNE:
491   case ISD::SETONE: return Mips::FCOND_ONE;
492   case ISD::SETUEQ: return Mips::FCOND_UEQ;
493   }
494 }
495
496
497 // Returns true if condition code has to be inverted.
498 static bool InvertFPCondCode(Mips::CondCode CC) {
499   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
500     return false;
501
502   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
503          "Illegal Condition Code");
504
505   return true;
506 }
507
508 // Creates and returns an FPCmp node from a setcc node.
509 // Returns Op if setcc is not a floating point comparison.
510 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
511   // must be a SETCC node
512   if (Op.getOpcode() != ISD::SETCC)
513     return Op;
514
515   SDValue LHS = Op.getOperand(0);
516
517   if (!LHS.getValueType().isFloatingPoint())
518     return Op;
519
520   SDValue RHS = Op.getOperand(1);
521   DebugLoc dl = Op.getDebugLoc();
522
523   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
524   // node if necessary.
525   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
526
527   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
528                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
529 }
530
531 // Creates and returns a CMovFPT/F node.
532 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
533                             SDValue False, DebugLoc DL) {
534   bool invert = InvertFPCondCode((Mips::CondCode)
535                                  cast<ConstantSDNode>(Cond.getOperand(2))
536                                  ->getSExtValue());
537
538   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
539                      True.getValueType(), True, False, Cond);
540 }
541
542 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
543                                    TargetLowering::DAGCombinerInfo &DCI,
544                                    const MipsSubtarget* Subtarget) {
545   if (DCI.isBeforeLegalizeOps())
546     return SDValue();
547
548   SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
549
550   if (Cond.getOpcode() != MipsISD::FPCmp)
551     return SDValue();
552
553   SDValue True  = DAG.getConstant(1, MVT::i32);
554   SDValue False = DAG.getConstant(0, MVT::i32);
555
556   return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
557 }
558
559 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
560                                  TargetLowering::DAGCombinerInfo &DCI,
561                                  const MipsSubtarget* Subtarget) {
562   // Pattern match EXT.
563   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
564   //  => ext $dst, $src, size, pos
565   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
566     return SDValue();
567
568   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
569   unsigned ShiftRightOpc = ShiftRight.getOpcode();
570
571   // Op's first operand must be a shift right.
572   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
573     return SDValue();
574
575   // The second operand of the shift must be an immediate.
576   ConstantSDNode *CN;
577   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
578     return SDValue();
579   
580   uint64_t Pos = CN->getZExtValue();
581   uint64_t SMPos, SMSize;
582
583   // Op's second operand must be a shifted mask.
584   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
585       !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
586     return SDValue();
587
588   // Return if the shifted mask does not start at bit 0 or the sum of its size
589   // and Pos exceeds the word's size.
590   EVT ValTy = N->getValueType(0);
591   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
592     return SDValue();
593
594   return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
595                      ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
596                      DAG.getConstant(SMSize, MVT::i32));
597 }
598   
599 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
600                                 TargetLowering::DAGCombinerInfo &DCI,
601                                 const MipsSubtarget* Subtarget) {
602   // Pattern match INS.
603   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
604   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1 
605   //  => ins $dst, $src, size, pos, $src1
606   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
607     return SDValue();
608
609   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
610   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
611   ConstantSDNode *CN;
612
613   // See if Op's first operand matches (and $src1 , mask0).
614   if (And0.getOpcode() != ISD::AND)
615     return SDValue();
616
617   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
618       !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
619     return SDValue();
620
621   // See if Op's second operand matches (and (shl $src, pos), mask1).
622   if (And1.getOpcode() != ISD::AND)
623     return SDValue();
624   
625   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
626       !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
627     return SDValue();
628
629   // The shift masks must have the same position and size.
630   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
631     return SDValue();
632
633   SDValue Shl = And1.getOperand(0);
634   if (Shl.getOpcode() != ISD::SHL)
635     return SDValue();
636
637   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
638     return SDValue();
639
640   unsigned Shamt = CN->getZExtValue();
641
642   // Return if the shift amount and the first bit position of mask are not the
643   // same.  
644   EVT ValTy = N->getValueType(0);
645   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
646     return SDValue();
647   
648   return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
649                      DAG.getConstant(SMPos0, MVT::i32),
650                      DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
651 }
652   
653 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
654   const {
655   SelectionDAG &DAG = DCI.DAG;
656   unsigned opc = N->getOpcode();
657
658   switch (opc) {
659   default: break;
660   case ISD::ADDE:
661     return PerformADDECombine(N, DAG, DCI, Subtarget);
662   case ISD::SUBE:
663     return PerformSUBECombine(N, DAG, DCI, Subtarget);
664   case ISD::SDIVREM:
665   case ISD::UDIVREM:
666     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
667   case ISD::SETCC:
668     return PerformSETCCCombine(N, DAG, DCI, Subtarget);
669   case ISD::AND:
670     return PerformANDCombine(N, DAG, DCI, Subtarget);
671   case ISD::OR:
672     return PerformORCombine(N, DAG, DCI, Subtarget);
673   }
674
675   return SDValue();
676 }
677
678 SDValue MipsTargetLowering::
679 LowerOperation(SDValue Op, SelectionDAG &DAG) const
680 {
681   switch (Op.getOpcode())
682   {
683     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
684     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
685     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
686     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
687     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
688     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
689     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
690     case ISD::SELECT:             return LowerSELECT(Op, DAG);
691     case ISD::VASTART:            return LowerVASTART(Op, DAG);
692     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
693     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
694     case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
695     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
696   }
697   return SDValue();
698 }
699
700 //===----------------------------------------------------------------------===//
701 //  Lower helper functions
702 //===----------------------------------------------------------------------===//
703
704 // AddLiveIn - This helper function adds the specified physical register to the
705 // MachineFunction as a live in value.  It also creates a corresponding
706 // virtual register for it.
707 static unsigned
708 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
709 {
710   assert(RC->contains(PReg) && "Not the correct regclass!");
711   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
712   MF.getRegInfo().addLiveIn(PReg, VReg);
713   return VReg;
714 }
715
716 // Get fp branch code (not opcode) from condition code.
717 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
718   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
719     return Mips::BRANCH_T;
720
721   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
722          "Invalid CondCode.");
723
724   return Mips::BRANCH_F;
725 }
726
727 /*
728 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
729                                         DebugLoc dl,
730                                         const MipsSubtarget* Subtarget,
731                                         const TargetInstrInfo *TII,
732                                         bool isFPCmp, unsigned Opc) {
733   // There is no need to expand CMov instructions if target has
734   // conditional moves.
735   if (Subtarget->hasCondMov())
736     return BB;
737
738   // To "insert" a SELECT_CC instruction, we actually have to insert the
739   // diamond control-flow pattern.  The incoming instruction knows the
740   // destination vreg to set, the condition code register to branch on, the
741   // true/false values to select between, and a branch opcode to use.
742   const BasicBlock *LLVM_BB = BB->getBasicBlock();
743   MachineFunction::iterator It = BB;
744   ++It;
745
746   //  thisMBB:
747   //  ...
748   //   TrueVal = ...
749   //   setcc r1, r2, r3
750   //   bNE   r1, r0, copy1MBB
751   //   fallthrough --> copy0MBB
752   MachineBasicBlock *thisMBB  = BB;
753   MachineFunction *F = BB->getParent();
754   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
755   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
756   F->insert(It, copy0MBB);
757   F->insert(It, sinkMBB);
758
759   // Transfer the remainder of BB and its successor edges to sinkMBB.
760   sinkMBB->splice(sinkMBB->begin(), BB,
761                   llvm::next(MachineBasicBlock::iterator(MI)),
762                   BB->end());
763   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
764
765   // Next, add the true and fallthrough blocks as its successors.
766   BB->addSuccessor(copy0MBB);
767   BB->addSuccessor(sinkMBB);
768
769   // Emit the right instruction according to the type of the operands compared
770   if (isFPCmp)
771     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
772   else
773     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
774       .addReg(Mips::ZERO).addMBB(sinkMBB);
775
776   //  copy0MBB:
777   //   %FalseValue = ...
778   //   # fallthrough to sinkMBB
779   BB = copy0MBB;
780
781   // Update machine-CFG edges
782   BB->addSuccessor(sinkMBB);
783
784   //  sinkMBB:
785   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
786   //  ...
787   BB = sinkMBB;
788
789   if (isFPCmp)
790     BuildMI(*BB, BB->begin(), dl,
791             TII->get(Mips::PHI), MI->getOperand(0).getReg())
792       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
793       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
794   else
795     BuildMI(*BB, BB->begin(), dl,
796             TII->get(Mips::PHI), MI->getOperand(0).getReg())
797       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
798       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
799
800   MI->eraseFromParent();   // The pseudo instruction is gone now.
801   return BB;
802 }
803 */
804 MachineBasicBlock *
805 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
806                                                 MachineBasicBlock *BB) const {
807   switch (MI->getOpcode()) {
808   default:
809     assert(false && "Unexpected instr type to insert");
810     return NULL;
811   case Mips::ATOMIC_LOAD_ADD_I8:
812   case Mips::ATOMIC_LOAD_ADD_I8_P8:
813     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
814   case Mips::ATOMIC_LOAD_ADD_I16:
815   case Mips::ATOMIC_LOAD_ADD_I16_P8:
816     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
817   case Mips::ATOMIC_LOAD_ADD_I32:
818   case Mips::ATOMIC_LOAD_ADD_I32_P8:
819     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
820   case Mips::ATOMIC_LOAD_ADD_I64:
821   case Mips::ATOMIC_LOAD_ADD_I64_P8:
822     return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
823
824   case Mips::ATOMIC_LOAD_AND_I8:
825   case Mips::ATOMIC_LOAD_AND_I8_P8:
826     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
827   case Mips::ATOMIC_LOAD_AND_I16:
828   case Mips::ATOMIC_LOAD_AND_I16_P8:
829     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
830   case Mips::ATOMIC_LOAD_AND_I32:
831   case Mips::ATOMIC_LOAD_AND_I32_P8:
832     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
833   case Mips::ATOMIC_LOAD_AND_I64:
834   case Mips::ATOMIC_LOAD_AND_I64_P8:
835     return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
836
837   case Mips::ATOMIC_LOAD_OR_I8:
838   case Mips::ATOMIC_LOAD_OR_I8_P8:
839     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
840   case Mips::ATOMIC_LOAD_OR_I16:
841   case Mips::ATOMIC_LOAD_OR_I16_P8:
842     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
843   case Mips::ATOMIC_LOAD_OR_I32:
844   case Mips::ATOMIC_LOAD_OR_I32_P8:
845     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
846   case Mips::ATOMIC_LOAD_OR_I64:
847   case Mips::ATOMIC_LOAD_OR_I64_P8:
848     return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
849
850   case Mips::ATOMIC_LOAD_XOR_I8:
851   case Mips::ATOMIC_LOAD_XOR_I8_P8:
852     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
853   case Mips::ATOMIC_LOAD_XOR_I16:
854   case Mips::ATOMIC_LOAD_XOR_I16_P8:
855     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
856   case Mips::ATOMIC_LOAD_XOR_I32:
857   case Mips::ATOMIC_LOAD_XOR_I32_P8:
858     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
859   case Mips::ATOMIC_LOAD_XOR_I64:
860   case Mips::ATOMIC_LOAD_XOR_I64_P8:
861     return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
862
863   case Mips::ATOMIC_LOAD_NAND_I8:
864   case Mips::ATOMIC_LOAD_NAND_I8_P8:
865     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
866   case Mips::ATOMIC_LOAD_NAND_I16:
867   case Mips::ATOMIC_LOAD_NAND_I16_P8:
868     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
869   case Mips::ATOMIC_LOAD_NAND_I32:
870   case Mips::ATOMIC_LOAD_NAND_I32_P8:
871     return EmitAtomicBinary(MI, BB, 4, 0, true);
872   case Mips::ATOMIC_LOAD_NAND_I64:
873   case Mips::ATOMIC_LOAD_NAND_I64_P8:
874     return EmitAtomicBinary(MI, BB, 8, 0, true);
875
876   case Mips::ATOMIC_LOAD_SUB_I8:
877   case Mips::ATOMIC_LOAD_SUB_I8_P8:
878     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
879   case Mips::ATOMIC_LOAD_SUB_I16:
880   case Mips::ATOMIC_LOAD_SUB_I16_P8:
881     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
882   case Mips::ATOMIC_LOAD_SUB_I32:
883   case Mips::ATOMIC_LOAD_SUB_I32_P8:
884     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
885   case Mips::ATOMIC_LOAD_SUB_I64:
886   case Mips::ATOMIC_LOAD_SUB_I64_P8:
887     return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
888
889   case Mips::ATOMIC_SWAP_I8:
890   case Mips::ATOMIC_SWAP_I8_P8:
891     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
892   case Mips::ATOMIC_SWAP_I16:
893   case Mips::ATOMIC_SWAP_I16_P8:
894     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
895   case Mips::ATOMIC_SWAP_I32:
896   case Mips::ATOMIC_SWAP_I32_P8:
897     return EmitAtomicBinary(MI, BB, 4, 0);
898   case Mips::ATOMIC_SWAP_I64:
899   case Mips::ATOMIC_SWAP_I64_P8:
900     return EmitAtomicBinary(MI, BB, 8, 0);
901
902   case Mips::ATOMIC_CMP_SWAP_I8:
903   case Mips::ATOMIC_CMP_SWAP_I8_P8:
904     return EmitAtomicCmpSwapPartword(MI, BB, 1);
905   case Mips::ATOMIC_CMP_SWAP_I16:
906   case Mips::ATOMIC_CMP_SWAP_I16_P8:
907     return EmitAtomicCmpSwapPartword(MI, BB, 2);
908   case Mips::ATOMIC_CMP_SWAP_I32:
909   case Mips::ATOMIC_CMP_SWAP_I32_P8:
910     return EmitAtomicCmpSwap(MI, BB, 4);
911   case Mips::ATOMIC_CMP_SWAP_I64:
912   case Mips::ATOMIC_CMP_SWAP_I64_P8:
913     return EmitAtomicCmpSwap(MI, BB, 8);
914   }
915 }
916
917 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
918 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
919 MachineBasicBlock *
920 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
921                                      unsigned Size, unsigned BinOpcode,
922                                      bool Nand) const {
923   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
924
925   MachineFunction *MF = BB->getParent();
926   MachineRegisterInfo &RegInfo = MF->getRegInfo();
927   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
928   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
929   DebugLoc dl = MI->getDebugLoc();
930   unsigned LL, SC, AND, NOR, ZERO, BEQ;
931
932   if (Size == 4) {
933     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
934     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
935     AND = Mips::AND;
936     NOR = Mips::NOR;
937     ZERO = Mips::ZERO;
938     BEQ = Mips::BEQ;
939   }
940   else {
941     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
942     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
943     AND = Mips::AND64;
944     NOR = Mips::NOR64;
945     ZERO = Mips::ZERO_64;
946     BEQ = Mips::BEQ64;
947   }
948
949   unsigned OldVal = MI->getOperand(0).getReg();
950   unsigned Ptr = MI->getOperand(1).getReg();
951   unsigned Incr = MI->getOperand(2).getReg();
952
953   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
954   unsigned AndRes = RegInfo.createVirtualRegister(RC);
955   unsigned Success = RegInfo.createVirtualRegister(RC);
956
957   // insert new blocks after the current block
958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
959   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
960   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
961   MachineFunction::iterator It = BB;
962   ++It;
963   MF->insert(It, loopMBB);
964   MF->insert(It, exitMBB);
965
966   // Transfer the remainder of BB and its successor edges to exitMBB.
967   exitMBB->splice(exitMBB->begin(), BB,
968                   llvm::next(MachineBasicBlock::iterator(MI)),
969                   BB->end());
970   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
971
972   //  thisMBB:
973   //    ...
974   //    fallthrough --> loopMBB
975   BB->addSuccessor(loopMBB);
976   loopMBB->addSuccessor(loopMBB);
977   loopMBB->addSuccessor(exitMBB);
978
979   //  loopMBB:
980   //    ll oldval, 0(ptr)
981   //    <binop> storeval, oldval, incr
982   //    sc success, storeval, 0(ptr)
983   //    beq success, $0, loopMBB
984   BB = loopMBB;
985   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
986   if (Nand) {
987     //  and andres, oldval, incr
988     //  nor storeval, $0, andres
989     BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
990     BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
991   } else if (BinOpcode) {
992     //  <binop> storeval, oldval, incr
993     BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
994   } else {
995     StoreVal = Incr;
996   }
997   BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
998   BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
999
1000   MI->eraseFromParent();   // The instruction is gone now.
1001
1002   return exitMBB;
1003 }
1004
1005 MachineBasicBlock *
1006 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1007                                              MachineBasicBlock *BB,
1008                                              unsigned Size, unsigned BinOpcode,
1009                                              bool Nand) const {
1010   assert((Size == 1 || Size == 2) &&
1011       "Unsupported size for EmitAtomicBinaryPartial.");
1012
1013   MachineFunction *MF = BB->getParent();
1014   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1015   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1016   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1017   DebugLoc dl = MI->getDebugLoc();
1018   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1019   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1020
1021   unsigned Dest = MI->getOperand(0).getReg();
1022   unsigned Ptr = MI->getOperand(1).getReg();
1023   unsigned Incr = MI->getOperand(2).getReg();
1024
1025   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1026   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1027   unsigned Mask = RegInfo.createVirtualRegister(RC);
1028   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1029   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1030   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1031   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1032   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1033   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1034   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1035   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1036   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1037   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1038   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1039   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1040   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1041   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1042   unsigned Success = RegInfo.createVirtualRegister(RC);
1043
1044   // insert new blocks after the current block
1045   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1046   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049   MachineFunction::iterator It = BB;
1050   ++It;
1051   MF->insert(It, loopMBB);
1052   MF->insert(It, sinkMBB);
1053   MF->insert(It, exitMBB);
1054
1055   // Transfer the remainder of BB and its successor edges to exitMBB.
1056   exitMBB->splice(exitMBB->begin(), BB,
1057                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1058   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1059
1060   BB->addSuccessor(loopMBB);
1061   loopMBB->addSuccessor(loopMBB);
1062   loopMBB->addSuccessor(sinkMBB);
1063   sinkMBB->addSuccessor(exitMBB);
1064
1065   //  thisMBB:
1066   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1067   //    and     alignedaddr,ptr,masklsb2
1068   //    andi    ptrlsb2,ptr,3
1069   //    sll     shiftamt,ptrlsb2,3
1070   //    ori     maskupper,$0,255               # 0xff
1071   //    sll     mask,maskupper,shiftamt
1072   //    nor     mask2,$0,mask
1073   //    sll     incr2,incr,shiftamt
1074
1075   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1076   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1077     .addReg(Mips::ZERO).addImm(-4);
1078   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1079     .addReg(Ptr).addReg(MaskLSB2);
1080   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1081   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1082   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1083     .addReg(Mips::ZERO).addImm(MaskImm);
1084   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1085     .addReg(ShiftAmt).addReg(MaskUpper);
1086   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1087   BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1088
1089   // atomic.load.binop
1090   // loopMBB:
1091   //   ll      oldval,0(alignedaddr)
1092   //   binop   binopres,oldval,incr2
1093   //   and     newval,binopres,mask
1094   //   and     maskedoldval0,oldval,mask2
1095   //   or      storeval,maskedoldval0,newval
1096   //   sc      success,storeval,0(alignedaddr)
1097   //   beq     success,$0,loopMBB
1098
1099   // atomic.swap
1100   // loopMBB:
1101   //   ll      oldval,0(alignedaddr)
1102   //   and     newval,incr2,mask
1103   //   and     maskedoldval0,oldval,mask2
1104   //   or      storeval,maskedoldval0,newval
1105   //   sc      success,storeval,0(alignedaddr)
1106   //   beq     success,$0,loopMBB
1107
1108   BB = loopMBB;
1109   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1110   if (Nand) {
1111     //  and andres, oldval, incr2
1112     //  nor binopres, $0, andres
1113     //  and newval, binopres, mask
1114     BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1115     BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1116       .addReg(Mips::ZERO).addReg(AndRes);
1117     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1118   } else if (BinOpcode) {
1119     //  <binop> binopres, oldval, incr2
1120     //  and newval, binopres, mask
1121     BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1122     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1123   } else {// atomic.swap
1124     //  and newval, incr2, mask
1125     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1126   }
1127     
1128   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1129     .addReg(OldVal).addReg(Mask2);
1130   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1131     .addReg(MaskedOldVal0).addReg(NewVal);
1132   BuildMI(BB, dl, TII->get(SC), Success)
1133     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1134   BuildMI(BB, dl, TII->get(Mips::BEQ))
1135     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1136
1137   //  sinkMBB:
1138   //    and     maskedoldval1,oldval,mask
1139   //    srl     srlres,maskedoldval1,shiftamt
1140   //    sll     sllres,srlres,24
1141   //    sra     dest,sllres,24
1142   BB = sinkMBB;
1143   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1144
1145   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1146     .addReg(OldVal).addReg(Mask);
1147   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1148       .addReg(ShiftAmt).addReg(MaskedOldVal1);
1149   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1150       .addReg(SrlRes).addImm(ShiftImm);
1151   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1152       .addReg(SllRes).addImm(ShiftImm);
1153
1154   MI->eraseFromParent();   // The instruction is gone now.
1155
1156   return exitMBB;
1157 }
1158
1159 MachineBasicBlock *
1160 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1161                                       MachineBasicBlock *BB,
1162                                       unsigned Size) const {
1163   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1164
1165   MachineFunction *MF = BB->getParent();
1166   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1167   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1168   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1169   DebugLoc dl = MI->getDebugLoc();
1170   unsigned LL, SC, ZERO, BNE, BEQ;
1171
1172   if (Size == 4) {
1173     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1174     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1175     ZERO = Mips::ZERO;
1176     BNE = Mips::BNE;
1177     BEQ = Mips::BEQ;
1178   }
1179   else {
1180     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1181     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1182     ZERO = Mips::ZERO_64;
1183     BNE = Mips::BNE64;
1184     BEQ = Mips::BEQ64;
1185   }
1186
1187   unsigned Dest    = MI->getOperand(0).getReg();
1188   unsigned Ptr     = MI->getOperand(1).getReg();
1189   unsigned OldVal  = MI->getOperand(2).getReg();
1190   unsigned NewVal  = MI->getOperand(3).getReg();
1191
1192   unsigned Success = RegInfo.createVirtualRegister(RC);
1193
1194   // insert new blocks after the current block
1195   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1196   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1197   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1198   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1199   MachineFunction::iterator It = BB;
1200   ++It;
1201   MF->insert(It, loop1MBB);
1202   MF->insert(It, loop2MBB);
1203   MF->insert(It, exitMBB);
1204
1205   // Transfer the remainder of BB and its successor edges to exitMBB.
1206   exitMBB->splice(exitMBB->begin(), BB,
1207                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1208   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1209
1210   //  thisMBB:
1211   //    ...
1212   //    fallthrough --> loop1MBB
1213   BB->addSuccessor(loop1MBB);
1214   loop1MBB->addSuccessor(exitMBB);
1215   loop1MBB->addSuccessor(loop2MBB);
1216   loop2MBB->addSuccessor(loop1MBB);
1217   loop2MBB->addSuccessor(exitMBB);
1218
1219   // loop1MBB:
1220   //   ll dest, 0(ptr)
1221   //   bne dest, oldval, exitMBB
1222   BB = loop1MBB;
1223   BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1224   BuildMI(BB, dl, TII->get(BNE))
1225     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1226
1227   // loop2MBB:
1228   //   sc success, newval, 0(ptr)
1229   //   beq success, $0, loop1MBB
1230   BB = loop2MBB;
1231   BuildMI(BB, dl, TII->get(SC), Success)
1232     .addReg(NewVal).addReg(Ptr).addImm(0);
1233   BuildMI(BB, dl, TII->get(BEQ))
1234     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1235
1236   MI->eraseFromParent();   // The instruction is gone now.
1237
1238   return exitMBB;
1239 }
1240
1241 MachineBasicBlock *
1242 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1243                                               MachineBasicBlock *BB,
1244                                               unsigned Size) const {
1245   assert((Size == 1 || Size == 2) &&
1246       "Unsupported size for EmitAtomicCmpSwapPartial.");
1247
1248   MachineFunction *MF = BB->getParent();
1249   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1250   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1251   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1252   DebugLoc dl = MI->getDebugLoc();
1253   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1254   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1255
1256   unsigned Dest    = MI->getOperand(0).getReg();
1257   unsigned Ptr     = MI->getOperand(1).getReg();
1258   unsigned CmpVal  = MI->getOperand(2).getReg();
1259   unsigned NewVal  = MI->getOperand(3).getReg();
1260
1261   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1262   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1263   unsigned Mask = RegInfo.createVirtualRegister(RC);
1264   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1265   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1266   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1267   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1268   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1269   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1270   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1271   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1272   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1273   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1274   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1275   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1276   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1277   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1278   unsigned Success = RegInfo.createVirtualRegister(RC);
1279
1280   // insert new blocks after the current block
1281   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1282   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1283   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1285   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1286   MachineFunction::iterator It = BB;
1287   ++It;
1288   MF->insert(It, loop1MBB);
1289   MF->insert(It, loop2MBB);
1290   MF->insert(It, sinkMBB);
1291   MF->insert(It, exitMBB);
1292
1293   // Transfer the remainder of BB and its successor edges to exitMBB.
1294   exitMBB->splice(exitMBB->begin(), BB,
1295                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1296   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1297
1298   BB->addSuccessor(loop1MBB);
1299   loop1MBB->addSuccessor(sinkMBB);
1300   loop1MBB->addSuccessor(loop2MBB);
1301   loop2MBB->addSuccessor(loop1MBB);
1302   loop2MBB->addSuccessor(sinkMBB);
1303   sinkMBB->addSuccessor(exitMBB);
1304
1305   // FIXME: computation of newval2 can be moved to loop2MBB.
1306   //  thisMBB:
1307   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1308   //    and     alignedaddr,ptr,masklsb2
1309   //    andi    ptrlsb2,ptr,3
1310   //    sll     shiftamt,ptrlsb2,3
1311   //    ori     maskupper,$0,255               # 0xff
1312   //    sll     mask,maskupper,shiftamt
1313   //    nor     mask2,$0,mask
1314   //    andi    maskedcmpval,cmpval,255
1315   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1316   //    andi    maskednewval,newval,255
1317   //    sll     shiftednewval,maskednewval,shiftamt
1318   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1319   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1320     .addReg(Mips::ZERO).addImm(-4);
1321   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1322     .addReg(Ptr).addReg(MaskLSB2);
1323   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1324   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1325   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1326     .addReg(Mips::ZERO).addImm(MaskImm);
1327   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1328     .addReg(ShiftAmt).addReg(MaskUpper);
1329   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1330   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1331     .addReg(CmpVal).addImm(MaskImm);
1332   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1333     .addReg(ShiftAmt).addReg(MaskedCmpVal);
1334   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1335     .addReg(NewVal).addImm(MaskImm);
1336   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1337     .addReg(ShiftAmt).addReg(MaskedNewVal);
1338
1339   //  loop1MBB:
1340   //    ll      oldval,0(alginedaddr)
1341   //    and     maskedoldval0,oldval,mask
1342   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1343   BB = loop1MBB;
1344   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1345   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1346     .addReg(OldVal).addReg(Mask);
1347   BuildMI(BB, dl, TII->get(Mips::BNE))
1348     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1349
1350   //  loop2MBB:
1351   //    and     maskedoldval1,oldval,mask2
1352   //    or      storeval,maskedoldval1,shiftednewval
1353   //    sc      success,storeval,0(alignedaddr)
1354   //    beq     success,$0,loop1MBB
1355   BB = loop2MBB;
1356   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1357     .addReg(OldVal).addReg(Mask2);
1358   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1359     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1360   BuildMI(BB, dl, TII->get(SC), Success)
1361       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1362   BuildMI(BB, dl, TII->get(Mips::BEQ))
1363       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1364
1365   //  sinkMBB:
1366   //    srl     srlres,maskedoldval0,shiftamt
1367   //    sll     sllres,srlres,24
1368   //    sra     dest,sllres,24
1369   BB = sinkMBB;
1370   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1371
1372   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1373       .addReg(ShiftAmt).addReg(MaskedOldVal0);
1374   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1375       .addReg(SrlRes).addImm(ShiftImm);
1376   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1377       .addReg(SllRes).addImm(ShiftImm);
1378
1379   MI->eraseFromParent();   // The instruction is gone now.
1380
1381   return exitMBB;
1382 }
1383
1384 //===----------------------------------------------------------------------===//
1385 //  Misc Lower Operation implementation
1386 //===----------------------------------------------------------------------===//
1387 SDValue MipsTargetLowering::
1388 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1389 {
1390   MachineFunction &MF = DAG.getMachineFunction();
1391   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1392   unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1393
1394   assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1395          cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1396          "Cannot lower if the alignment of the allocated space is larger than \
1397           that of the stack.");
1398
1399   SDValue Chain = Op.getOperand(0);
1400   SDValue Size = Op.getOperand(1);
1401   DebugLoc dl = Op.getDebugLoc();
1402
1403   // Get a reference from Mips stack pointer
1404   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1405
1406   // Subtract the dynamic size from the actual stack size to
1407   // obtain the new stack size.
1408   SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1409
1410   // The Sub result contains the new stack start address, so it
1411   // must be placed in the stack pointer register.
1412   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1413
1414   // This node always has two return values: a new stack pointer
1415   // value and a chain
1416   SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1417   SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1418   SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1419
1420   return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1421 }
1422
1423 SDValue MipsTargetLowering::
1424 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1425 {
1426   // The first operand is the chain, the second is the condition, the third is
1427   // the block to branch to if the condition is true.
1428   SDValue Chain = Op.getOperand(0);
1429   SDValue Dest = Op.getOperand(2);
1430   DebugLoc dl = Op.getDebugLoc();
1431
1432   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1433
1434   // Return if flag is not set by a floating point comparison.
1435   if (CondRes.getOpcode() != MipsISD::FPCmp)
1436     return Op;
1437
1438   SDValue CCNode  = CondRes.getOperand(2);
1439   Mips::CondCode CC =
1440     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1441   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1442
1443   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1444                      Dest, CondRes);
1445 }
1446
1447 SDValue MipsTargetLowering::
1448 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1449 {
1450   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1451
1452   // Return if flag is not set by a floating point comparison.
1453   if (Cond.getOpcode() != MipsISD::FPCmp)
1454     return Op;
1455
1456   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1457                       Op.getDebugLoc());
1458 }
1459
1460 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1461                                                SelectionDAG &DAG) const {
1462   // FIXME there isn't actually debug info here
1463   DebugLoc dl = Op.getDebugLoc();
1464   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();   
1465
1466   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1467     SDVTList VTs = DAG.getVTList(MVT::i32);
1468
1469     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1470
1471     // %gp_rel relocation
1472     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1473       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1474                                               MipsII::MO_GPREL);
1475       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1476       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1477       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1478     }
1479     // %hi/%lo relocation
1480     SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1481                                               MipsII::MO_ABS_HI);
1482     SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1483                                               MipsII::MO_ABS_LO);
1484     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1485     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1486     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1487   }
1488
1489   EVT ValTy = Op.getValueType();
1490   bool HasGotOfst = (GV->hasInternalLinkage() ||
1491                      (GV->hasLocalLinkage() && !isa<Function>(GV)));
1492   unsigned GotFlag = IsN64 ?
1493                      (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1494                      (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1495   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1496   GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GA);
1497   SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1498                                 MachinePointerInfo(), false, false, false, 0);
1499   // On functions and global targets not internal linked only
1500   // a load from got/GP is necessary for PIC to work.
1501   if (!HasGotOfst)
1502     return ResNode;
1503   SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1504                                             IsN64 ? MipsII::MO_GOT_OFST :
1505                                                     MipsII::MO_ABS_LO);
1506   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1507   return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1508 }
1509
1510 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1511                                               SelectionDAG &DAG) const {
1512   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1513   // FIXME there isn't actually debug info here
1514   DebugLoc dl = Op.getDebugLoc();
1515
1516   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1517     // %hi/%lo relocation
1518     SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1519     SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1520     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1521     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1522     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1523   }
1524
1525   EVT ValTy = Op.getValueType();
1526   unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1527   unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1528   SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1529   BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy, BAGOTOffset);
1530   SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1531   SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1532                              MachinePointerInfo(), false, false, false, 0);
1533   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1534   return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1535 }
1536
1537 SDValue MipsTargetLowering::
1538 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1539 {
1540   // If the relocation model is PIC, use the General Dynamic TLS Model or
1541   // Local Dynamic TLS model, otherwise use the Initial Exec or
1542   // Local Exec TLS Model.
1543
1544   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1545   DebugLoc dl = GA->getDebugLoc();
1546   const GlobalValue *GV = GA->getGlobal();
1547   EVT PtrVT = getPointerTy();
1548
1549   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1550     // General Dynamic TLS Model
1551     bool LocalDynamic = GV->hasInternalLinkage();
1552     unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1553     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1554     SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1555     unsigned PtrSize = PtrVT.getSizeInBits();
1556     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1557
1558     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1559
1560     ArgListTy Args;
1561     ArgListEntry Entry;
1562     Entry.Node = Argument;
1563     Entry.Ty = PtrTy;
1564     Args.push_back(Entry);
1565     
1566     std::pair<SDValue, SDValue> CallResult =
1567       LowerCallTo(DAG.getEntryNode(), PtrTy,
1568                   false, false, false, false, 0, CallingConv::C, false, true,
1569                   TlsGetAddr, Args, DAG, dl);
1570
1571     SDValue Ret = CallResult.first;
1572
1573     if (!LocalDynamic)
1574       return Ret;
1575
1576     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1577                                                MipsII::MO_DTPREL_HI);
1578     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1579     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1580                                                MipsII::MO_DTPREL_LO);
1581     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1582     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1583     return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1584   }
1585
1586   SDValue Offset;
1587   if (GV->isDeclaration()) {
1588     // Initial Exec TLS Model
1589     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1590                                              MipsII::MO_GOTTPREL);
1591     TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1592     Offset = DAG.getLoad(PtrVT, dl,
1593                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
1594                          false, false, false, 0);
1595   } else {
1596     // Local Exec TLS Model
1597     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1598                                                MipsII::MO_TPREL_HI);
1599     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1600                                                MipsII::MO_TPREL_LO);
1601     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1602     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1603     Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1604   }
1605
1606   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1607   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1608 }
1609
1610 SDValue MipsTargetLowering::
1611 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1612 {
1613   SDValue HiPart, JTI, JTILo;
1614   // FIXME there isn't actually debug info here
1615   DebugLoc dl = Op.getDebugLoc();
1616   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1617   EVT PtrVT = Op.getValueType();
1618   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1619
1620   if (!IsPIC && !IsN64) {
1621     JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1622     HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1623     JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1624   } else {// Emit Load from Global Pointer
1625     unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1626     unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1627     JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1628     JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, JTI);
1629     HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1630                          MachinePointerInfo(), false, false, false, 0);
1631     JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1632   }
1633
1634   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1635   return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1636 }
1637
1638 SDValue MipsTargetLowering::
1639 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1640 {
1641   SDValue ResNode;
1642   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1643   const Constant *C = N->getConstVal();
1644   // FIXME there isn't actually debug info here
1645   DebugLoc dl = Op.getDebugLoc();
1646
1647   // gp_rel relocation
1648   // FIXME: we should reference the constant pool using small data sections,
1649   // but the asm printer currently doesn't support this feature without
1650   // hacking it. This feature should come soon so we can uncomment the
1651   // stuff below.
1652   //if (IsInSmallSection(C->getType())) {
1653   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1654   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1655   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1656
1657   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1658     SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1659                                              N->getOffset(), MipsII::MO_ABS_HI);
1660     SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1661                                              N->getOffset(), MipsII::MO_ABS_LO);
1662     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1663     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1664     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1665   } else {
1666     EVT ValTy = Op.getValueType();
1667     unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1668     unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1669     SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1670                                            N->getOffset(), GOTFlag);
1671     CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, CP);
1672     SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1673                                MachinePointerInfo::getConstantPool(), false,
1674                                false, false, 0);
1675     SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1676                                              N->getOffset(), OFSTFlag);
1677     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1678     ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1679   }
1680
1681   return ResNode;
1682 }
1683
1684 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1685   MachineFunction &MF = DAG.getMachineFunction();
1686   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1687
1688   DebugLoc dl = Op.getDebugLoc();
1689   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1690                                  getPointerTy());
1691
1692   // vastart just stores the address of the VarArgsFrameIndex slot into the
1693   // memory location argument.
1694   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1695   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1696                       MachinePointerInfo(SV), false, false, 0);
1697 }
1698  
1699 // Called if the size of integer registers is large enough to hold the whole
1700 // floating point number.
1701 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1702   // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1703   EVT ValTy = Op.getValueType();
1704   EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1705   uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1706   DebugLoc dl = Op.getDebugLoc();
1707   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1708   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1709   SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1710                              DAG.getConstant(Mask - 1, IntValTy));
1711   SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1712                              DAG.getConstant(Mask, IntValTy));
1713   SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1714   return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1715 }
1716
1717 // Called if the size of integer registers is not large enough to hold the whole
1718 // floating point number (e.g. f64 & 32-bit integer register).
1719 static SDValue
1720 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1721   // FIXME:
1722   //  Use ext/ins instructions if target architecture is Mips32r2.
1723   //  Eliminate redundant mfc1 and mtc1 instructions.
1724   unsigned LoIdx = 0, HiIdx = 1;
1725
1726   if (!isLittle)
1727     std::swap(LoIdx, HiIdx);
1728
1729   DebugLoc dl = Op.getDebugLoc();
1730   SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1731                               Op.getOperand(0),
1732                               DAG.getConstant(LoIdx, MVT::i32));
1733   SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1734                             Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1735   SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1736                             Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1737   SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1738                              DAG.getConstant(0x7fffffff, MVT::i32));
1739   SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1740                              DAG.getConstant(0x80000000, MVT::i32));
1741   SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1742
1743   if (!isLittle)
1744     std::swap(Word0, Word1);
1745
1746   return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1747 }
1748
1749 SDValue
1750 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1751   EVT Ty = Op.getValueType();
1752
1753   assert(Ty == MVT::f32 || Ty == MVT::f64);
1754
1755   if (Ty == MVT::f32 || HasMips64)
1756     return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1757   
1758   return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1759 }
1760
1761 SDValue MipsTargetLowering::
1762 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1763   // check the depth
1764   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1765          "Frame address can only be determined for current frame.");
1766
1767   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1768   MFI->setFrameAddressIsTaken(true);
1769   EVT VT = Op.getValueType();
1770   DebugLoc dl = Op.getDebugLoc();
1771   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1772                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
1773   return FrameAddr;
1774 }
1775
1776 // TODO: set SType according to the desired memory barrier behavior.
1777 SDValue
1778 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1779   unsigned SType = 0;
1780   DebugLoc dl = Op.getDebugLoc();
1781   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1782                      DAG.getConstant(SType, MVT::i32));
1783 }
1784
1785 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1786                                               SelectionDAG& DAG) const {
1787   // FIXME: Need pseudo-fence for 'singlethread' fences
1788   // FIXME: Set SType for weaker fences where supported/appropriate.
1789   unsigned SType = 0;
1790   DebugLoc dl = Op.getDebugLoc();
1791   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1792                      DAG.getConstant(SType, MVT::i32));
1793 }
1794
1795 //===----------------------------------------------------------------------===//
1796 //                      Calling Convention Implementation
1797 //===----------------------------------------------------------------------===//
1798
1799 //===----------------------------------------------------------------------===//
1800 // TODO: Implement a generic logic using tblgen that can support this.
1801 // Mips O32 ABI rules:
1802 // ---
1803 // i32 - Passed in A0, A1, A2, A3 and stack
1804 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1805 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
1806 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1807 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1808 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
1809 //       go to stack.
1810 //
1811 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1812 //===----------------------------------------------------------------------===//
1813
1814 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1815                        MVT LocVT, CCValAssign::LocInfo LocInfo,
1816                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
1817
1818   static const unsigned IntRegsSize=4, FloatRegsSize=2;
1819
1820   static const unsigned IntRegs[] = {
1821       Mips::A0, Mips::A1, Mips::A2, Mips::A3
1822   };
1823   static const unsigned F32Regs[] = {
1824       Mips::F12, Mips::F14
1825   };
1826   static const unsigned F64Regs[] = {
1827       Mips::D6, Mips::D7
1828   };
1829
1830   // ByVal Args
1831   if (ArgFlags.isByVal()) {
1832     State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1833                       1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1834     unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1835     for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1836          r < std::min(IntRegsSize, NextReg); ++r)
1837       State.AllocateReg(IntRegs[r]);
1838     return false;
1839   }
1840
1841   // Promote i8 and i16
1842   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1843     LocVT = MVT::i32;
1844     if (ArgFlags.isSExt())
1845       LocInfo = CCValAssign::SExt;
1846     else if (ArgFlags.isZExt())
1847       LocInfo = CCValAssign::ZExt;
1848     else
1849       LocInfo = CCValAssign::AExt;
1850   }
1851
1852   unsigned Reg;
1853
1854   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1855   // is true: function is vararg, argument is 3rd or higher, there is previous
1856   // argument which is not f32 or f64.
1857   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1858       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1859   unsigned OrigAlign = ArgFlags.getOrigAlign();
1860   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1861
1862   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1863     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1864     // If this is the first part of an i64 arg,
1865     // the allocated register must be either A0 or A2.
1866     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1867       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1868     LocVT = MVT::i32;
1869   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1870     // Allocate int register and shadow next int register. If first
1871     // available register is Mips::A1 or Mips::A3, shadow it too.
1872     Reg = State.AllocateReg(IntRegs, IntRegsSize);
1873     if (Reg == Mips::A1 || Reg == Mips::A3)
1874       Reg = State.AllocateReg(IntRegs, IntRegsSize);
1875     State.AllocateReg(IntRegs, IntRegsSize);
1876     LocVT = MVT::i32;
1877   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1878     // we are guaranteed to find an available float register
1879     if (ValVT == MVT::f32) {
1880       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1881       // Shadow int register
1882       State.AllocateReg(IntRegs, IntRegsSize);
1883     } else {
1884       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1885       // Shadow int registers
1886       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1887       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1888         State.AllocateReg(IntRegs, IntRegsSize);
1889       State.AllocateReg(IntRegs, IntRegsSize);
1890     }
1891   } else
1892     llvm_unreachable("Cannot handle this ValVT.");
1893
1894   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1895   unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1896
1897   if (!Reg)
1898     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1899   else
1900     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1901
1902   return false; // CC must always match
1903 }
1904
1905 static const unsigned Mips64IntRegs[8] =
1906   {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1907    Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1908 static const unsigned Mips64DPRegs[8] =
1909   {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1910    Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1911
1912 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1913                            CCValAssign::LocInfo LocInfo,
1914                            ISD::ArgFlagsTy ArgFlags, CCState &State) {
1915   unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1916   unsigned Size  = (ArgFlags.getByValSize() + 7) / 8 * 8;
1917   unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1918
1919   assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1920
1921   // If byval is 16-byte aligned, the first arg register must be even.  
1922   if ((Align == 16) && (FirstIdx % 2)) {
1923     State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1924     ++FirstIdx;
1925   }
1926
1927   // Mark the registers allocated.
1928   for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1929     State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1930
1931   // Allocate space on caller's stack.
1932   unsigned Offset = State.AllocateStack(Size, Align);
1933   
1934   if (FirstIdx < 8)
1935     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1936                                      LocVT, LocInfo));    
1937   else
1938     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1939
1940   return true;
1941 }
1942
1943 #include "MipsGenCallingConv.inc"
1944
1945 static void
1946 AnalyzeMips64CallOperands(CCState CCInfo,
1947                           const SmallVectorImpl<ISD::OutputArg> &Outs) {
1948   unsigned NumOps = Outs.size();
1949   for (unsigned i = 0; i != NumOps; ++i) {
1950     MVT ArgVT = Outs[i].VT;
1951     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1952     bool R;
1953
1954     if (Outs[i].IsFixed)
1955       R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1956     else
1957       R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1958       
1959     if (R) {
1960 #ifndef NDEBUG
1961       dbgs() << "Call operand #" << i << " has unhandled type "
1962              << EVT(ArgVT).getEVTString();
1963 #endif
1964       llvm_unreachable(0);
1965     }
1966   }
1967 }
1968
1969 //===----------------------------------------------------------------------===//
1970 //                  Call Calling Convention Implementation
1971 //===----------------------------------------------------------------------===//
1972
1973 static const unsigned O32IntRegsSize = 4;
1974
1975 static const unsigned O32IntRegs[] = {
1976   Mips::A0, Mips::A1, Mips::A2, Mips::A3
1977 };
1978
1979 // Return next O32 integer argument register.
1980 static unsigned getNextIntArgReg(unsigned Reg) {
1981   assert((Reg == Mips::A0) || (Reg == Mips::A2));
1982   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1983 }
1984
1985 // Write ByVal Arg to arg registers and stack.
1986 static void
1987 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1988               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1989               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1990               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1991               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1992               MVT PtrType, bool isLittle) {
1993   unsigned LocMemOffset = VA.getLocMemOffset();
1994   unsigned Offset = 0;
1995   uint32_t RemainingSize = Flags.getByValSize();
1996   unsigned ByValAlign = Flags.getByValAlign();
1997
1998   // Copy the first 4 words of byval arg to registers A0 - A3.
1999   // FIXME: Use a stricter alignment if it enables better optimization in passes
2000   //        run later.
2001   for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2002        Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2003     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2004                                   DAG.getConstant(Offset, MVT::i32));
2005     SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2006                                   MachinePointerInfo(), false, false, false,
2007                                   std::min(ByValAlign, (unsigned )4));
2008     MemOpChains.push_back(LoadVal.getValue(1));
2009     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2010     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2011   }
2012
2013   if (RemainingSize == 0)
2014     return;
2015
2016   // If there still is a register available for argument passing, write the
2017   // remaining part of the structure to it using subword loads and shifts.
2018   if (LocMemOffset < 4 * 4) {
2019     assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2020            "There must be one to three bytes remaining.");
2021     unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2022     SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2023                                   DAG.getConstant(Offset, MVT::i32));
2024     unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2025     SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2026                                      LoadPtr, MachinePointerInfo(),
2027                                      MVT::getIntegerVT(LoadSize * 8), false,
2028                                      false, Alignment);
2029     MemOpChains.push_back(LoadVal.getValue(1));
2030
2031     // If target is big endian, shift it to the most significant half-word or
2032     // byte.
2033     if (!isLittle)
2034       LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2035                             DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2036
2037     Offset += LoadSize;
2038     RemainingSize -= LoadSize;
2039
2040     // Read second subword if necessary.
2041     if (RemainingSize != 0)  {
2042       assert(RemainingSize == 1 && "There must be one byte remaining.");
2043       LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg, 
2044                             DAG.getConstant(Offset, MVT::i32));
2045       unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2046       SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2047                                        LoadPtr, MachinePointerInfo(),
2048                                        MVT::i8, false, false, Alignment);
2049       MemOpChains.push_back(Subword.getValue(1));
2050       // Insert the loaded byte to LoadVal.
2051       // FIXME: Use INS if supported by target.
2052       unsigned ShiftAmt = isLittle ? 16 : 8;
2053       SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2054                                   DAG.getConstant(ShiftAmt, MVT::i32));
2055       LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2056     }
2057
2058     unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2059     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2060     return;
2061   }
2062
2063   // Create a fixed object on stack at offset LocMemOffset and copy
2064   // remaining part of byval arg to it using memcpy.
2065   SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2066                             DAG.getConstant(Offset, MVT::i32));
2067   LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2068   SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2069   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2070                              DAG.getConstant(RemainingSize, MVT::i32),
2071                              std::min(ByValAlign, (unsigned)4),
2072                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2073                              MachinePointerInfo(0), MachinePointerInfo(0));
2074 }
2075
2076 // Copy Mips64 byVal arg to registers and stack.
2077 void static
2078 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2079                SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2080                SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2081                MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2082                const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2083                EVT PtrTy, bool isLittle) {
2084   unsigned ByValSize = Flags.getByValSize();
2085   unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2086   bool IsRegLoc = VA.isRegLoc();
2087   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2088   unsigned LocMemOffset = 0;
2089   unsigned MemCpySize = ByValSize;
2090
2091   if (!IsRegLoc)
2092     LocMemOffset = VA.getLocMemOffset();
2093   else {
2094     const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2095                                     VA.getLocReg());
2096     const unsigned *RegEnd = Mips64IntRegs + 8;
2097
2098     // Copy double words to registers.
2099     for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2100       SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2101                                     DAG.getConstant(Offset, PtrTy));
2102       SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2103                                     MachinePointerInfo(), false, false, false,
2104                                     Alignment);
2105       MemOpChains.push_back(LoadVal.getValue(1));
2106       RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2107     }
2108
2109     // Return if the struct has been fully copied. 
2110     if (!(MemCpySize = ByValSize - Offset))
2111       return;
2112
2113     // If there is an argument register available, copy the remainder of the
2114     // byval argument with sub-doubleword loads and shifts.
2115     if (Reg != RegEnd) {
2116       assert((ByValSize < Offset + 8) &&
2117              "Size of the remainder should be smaller than 8-byte.");
2118       SDValue Val;
2119       for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2120         unsigned RemSize = ByValSize - Offset;
2121
2122         if (RemSize < LoadSize)
2123           continue;
2124         
2125         SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2126                                       DAG.getConstant(Offset, PtrTy));
2127         SDValue LoadVal = 
2128           DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2129                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2130                          false, false, Alignment);
2131         MemOpChains.push_back(LoadVal.getValue(1));
2132
2133         // Offset in number of bits from double word boundary.
2134         unsigned OffsetDW = (Offset % 8) * 8;
2135         unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2136         SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2137                                     DAG.getConstant(Shamt, MVT::i32));
2138         
2139         Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2140                               Shift;
2141         Offset += LoadSize;
2142         Alignment = std::min(Alignment, LoadSize);
2143       }
2144       
2145       RegsToPass.push_back(std::make_pair(*Reg, Val));
2146       return;
2147     }
2148   }
2149
2150   assert(MemCpySize && "MemCpySize must not be zero.");
2151
2152   // Create a fixed object on stack at offset LocMemOffset and copy
2153   // remainder of byval arg to it with memcpy.
2154   SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2155                             DAG.getConstant(Offset, PtrTy));
2156   LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2157   SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2158   ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2159                              DAG.getConstant(MemCpySize, PtrTy), Alignment,
2160                              /*isVolatile=*/false, /*AlwaysInline=*/false,
2161                              MachinePointerInfo(0), MachinePointerInfo(0));
2162 }
2163
2164 /// LowerCall - functions arguments are copied from virtual regs to
2165 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2166 /// TODO: isTailCall.
2167 SDValue
2168 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2169                               CallingConv::ID CallConv, bool isVarArg,
2170                               bool &isTailCall,
2171                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2172                               const SmallVectorImpl<SDValue> &OutVals,
2173                               const SmallVectorImpl<ISD::InputArg> &Ins,
2174                               DebugLoc dl, SelectionDAG &DAG,
2175                               SmallVectorImpl<SDValue> &InVals) const {
2176   // MIPs target does not yet support tail call optimization.
2177   isTailCall = false;
2178
2179   MachineFunction &MF = DAG.getMachineFunction();
2180   MachineFrameInfo *MFI = MF.getFrameInfo();
2181   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2182   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2183   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2184
2185   // Analyze operands of the call, assigning locations to each operand.
2186   SmallVector<CCValAssign, 16> ArgLocs;
2187   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2188                  getTargetMachine(), ArgLocs, *DAG.getContext());
2189
2190   if (IsO32)
2191     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2192   else if (HasMips64)
2193     AnalyzeMips64CallOperands(CCInfo, Outs);
2194   else
2195     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2196
2197   // Get a count of how many bytes are to be pushed on the stack.
2198   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2199
2200   // Chain is the output chain of the last Load/Store or CopyToReg node.
2201   // ByValChain is the output chain of the last Memcpy node created for copying
2202   // byval arguments to the stack.
2203   SDValue Chain, CallSeqStart, ByValChain;
2204   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2205   Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2206   ByValChain = InChain;
2207
2208   // If this is the first call, create a stack frame object that points to
2209   // a location to which .cprestore saves $gp.
2210   if (IsO32 && IsPIC && !MipsFI->getGPFI())
2211     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2212
2213   // Get the frame index of the stack frame object that points to the location
2214   // of dynamically allocated area on the stack.
2215   int DynAllocFI = MipsFI->getDynAllocFI();
2216
2217   // Update size of the maximum argument space.
2218   // For O32, a minimum of four words (16 bytes) of argument space is
2219   // allocated.
2220   if (IsO32)
2221     NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2222
2223   unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2224
2225   if (MaxCallFrameSize < NextStackOffset) {
2226     MipsFI->setMaxCallFrameSize(NextStackOffset);
2227
2228     // Set the offsets relative to $sp of the $gp restore slot and dynamically
2229     // allocated stack space. These offsets must be aligned to a boundary
2230     // determined by the stack alignment of the ABI.
2231     unsigned StackAlignment = TFL->getStackAlignment();
2232     NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2233                       StackAlignment * StackAlignment;
2234
2235     if (MipsFI->needGPSaveRestore())
2236       MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2237
2238     MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2239   }
2240
2241   // With EABI is it possible to have 16 args on registers.
2242   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2243   SmallVector<SDValue, 8> MemOpChains;
2244
2245   int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2246
2247   // Walk the register/memloc assignments, inserting copies/loads.
2248   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2249     SDValue Arg = OutVals[i];
2250     CCValAssign &VA = ArgLocs[i];
2251     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2252     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2253
2254     // ByVal Arg.
2255     if (Flags.isByVal()) {
2256       assert(Flags.getByValSize() &&
2257              "ByVal args of size 0 should have been ignored by front-end.");
2258       if (IsO32)
2259         WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2260                       MFI, DAG, Arg, VA, Flags, getPointerTy(),
2261                       Subtarget->isLittle());
2262       else
2263         PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2264                        MFI, DAG, Arg, VA, Flags, getPointerTy(), 
2265                        Subtarget->isLittle());
2266       continue;
2267     }
2268     
2269     // Promote the value if needed.
2270     switch (VA.getLocInfo()) {
2271     default: llvm_unreachable("Unknown loc info!");
2272     case CCValAssign::Full:
2273       if (VA.isRegLoc()) {
2274         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2275             (ValVT == MVT::f64 && LocVT == MVT::i64))
2276           Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2277         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2278           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2279                                    Arg, DAG.getConstant(0, MVT::i32));
2280           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2281                                    Arg, DAG.getConstant(1, MVT::i32));
2282           if (!Subtarget->isLittle())
2283             std::swap(Lo, Hi);
2284           unsigned LocRegLo = VA.getLocReg(); 
2285           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2286           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2287           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2288           continue;
2289         }
2290       }
2291       break;
2292     case CCValAssign::SExt:
2293       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2294       break;
2295     case CCValAssign::ZExt:
2296       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2297       break;
2298     case CCValAssign::AExt:
2299       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2300       break;
2301     }
2302
2303     // Arguments that can be passed on register must be kept at
2304     // RegsToPass vector
2305     if (VA.isRegLoc()) {
2306       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2307       continue;
2308     }
2309
2310     // Register can't get to this point...
2311     assert(VA.isMemLoc());
2312
2313     // Create the frame index object for this incoming parameter
2314     LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2315                                     VA.getLocMemOffset(), true);
2316     SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2317
2318     // emit ISD::STORE whichs stores the
2319     // parameter value to a stack Location
2320     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2321                                        MachinePointerInfo(), false, false, 0));
2322   }
2323
2324   // Extend range of indices of frame objects for outgoing arguments that were
2325   // created during this function call. Skip this step if no such objects were
2326   // created.
2327   if (LastFI)
2328     MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2329
2330   // If a memcpy has been created to copy a byval arg to a stack, replace the
2331   // chain input of CallSeqStart with ByValChain.
2332   if (InChain != ByValChain)
2333     DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2334                            NextStackOffsetVal);
2335
2336   // Transform all store nodes into one single node because all store
2337   // nodes are independent of each other.
2338   if (!MemOpChains.empty())
2339     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2340                         &MemOpChains[0], MemOpChains.size());
2341
2342   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2343   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2344   // node so that legalize doesn't hack it.
2345   unsigned char OpFlag;
2346   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2347   bool GlobalOrExternal = false;
2348   SDValue CalleeLo;
2349
2350   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2351     if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2352       OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2353       unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2354       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2355                                           OpFlag);
2356       CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2357                                             0, LoFlag);
2358     } else {
2359       OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2360       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2361                                           getPointerTy(), 0, OpFlag);
2362     }
2363
2364     GlobalOrExternal = true;
2365   }
2366   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2367     if (IsN64 || (!IsO32 && IsPIC))
2368       OpFlag = MipsII::MO_GOT_DISP;
2369     else if (!IsPIC) // !N64 && static
2370       OpFlag = MipsII::MO_NO_FLAG;
2371     else // O32 & PIC
2372       OpFlag = MipsII::MO_GOT_CALL;
2373     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2374                                          OpFlag);
2375     GlobalOrExternal = true;
2376   }
2377
2378   SDValue InFlag;
2379
2380   // Create nodes that load address of callee and copy it to T9
2381   if (IsPICCall) {
2382     if (GlobalOrExternal) {
2383       // Load callee address
2384       Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(), Callee);
2385       SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2386                                       Callee, MachinePointerInfo::getGOT(),
2387                                       false, false, false, 0);
2388
2389       // Use GOT+LO if callee has internal linkage.
2390       if (CalleeLo.getNode()) {
2391         SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2392         Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2393       } else
2394         Callee = LoadValue;
2395     }
2396   }
2397
2398   // T9 should contain the address of the callee function if 
2399   // -reloction-model=pic or it is an indirect call.
2400   if (IsPICCall || !GlobalOrExternal) {
2401     // copy to T9
2402     unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2403     Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2404     InFlag = Chain.getValue(1);
2405     Callee = DAG.getRegister(T9Reg, getPointerTy());
2406   }
2407
2408   // Build a sequence of copy-to-reg nodes chained together with token
2409   // chain and flag operands which copy the outgoing args into registers.
2410   // The InFlag in necessary since all emitted instructions must be
2411   // stuck together.
2412   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2413     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2414                              RegsToPass[i].second, InFlag);
2415     InFlag = Chain.getValue(1);
2416   }
2417
2418   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2419   //             = Chain, Callee, Reg#1, Reg#2, ...
2420   //
2421   // Returns a chain & a flag for retval copy to use.
2422   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2423   SmallVector<SDValue, 8> Ops;
2424   Ops.push_back(Chain);
2425   Ops.push_back(Callee);
2426
2427   // Add argument registers to the end of the list so that they are
2428   // known live into the call.
2429   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2430     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2431                                   RegsToPass[i].second.getValueType()));
2432
2433   if (InFlag.getNode())
2434     Ops.push_back(InFlag);
2435
2436   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2437   InFlag = Chain.getValue(1);
2438
2439   // Create the CALLSEQ_END node.
2440   Chain = DAG.getCALLSEQ_END(Chain,
2441                              DAG.getIntPtrConstant(NextStackOffset, true),
2442                              DAG.getIntPtrConstant(0, true), InFlag);
2443   InFlag = Chain.getValue(1);
2444
2445   // Handle result values, copying them out of physregs into vregs that we
2446   // return.
2447   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2448                          Ins, dl, DAG, InVals);
2449 }
2450
2451 /// LowerCallResult - Lower the result values of a call into the
2452 /// appropriate copies out of appropriate physical registers.
2453 SDValue
2454 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2455                                     CallingConv::ID CallConv, bool isVarArg,
2456                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2457                                     DebugLoc dl, SelectionDAG &DAG,
2458                                     SmallVectorImpl<SDValue> &InVals) const {
2459   // Assign locations to each value returned by this call.
2460   SmallVector<CCValAssign, 16> RVLocs;
2461   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2462                  getTargetMachine(), RVLocs, *DAG.getContext());
2463
2464   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2465
2466   // Copy all of the result registers out of their specified physreg.
2467   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2468     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2469                                RVLocs[i].getValVT(), InFlag).getValue(1);
2470     InFlag = Chain.getValue(2);
2471     InVals.push_back(Chain.getValue(0));
2472   }
2473
2474   return Chain;
2475 }
2476
2477 //===----------------------------------------------------------------------===//
2478 //             Formal Arguments Calling Convention Implementation
2479 //===----------------------------------------------------------------------===//
2480 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2481                          std::vector<SDValue>& OutChains,
2482                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2483                          const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2484   unsigned LocMem = VA.getLocMemOffset();
2485   unsigned FirstWord = LocMem / 4;
2486
2487   // copy register A0 - A3 to frame object
2488   for (unsigned i = 0; i < NumWords; ++i) {
2489     unsigned CurWord = FirstWord + i;
2490     if (CurWord >= O32IntRegsSize)
2491       break;
2492
2493     unsigned SrcReg = O32IntRegs[CurWord];
2494     unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2495     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2496                                    DAG.getConstant(i * 4, MVT::i32));
2497     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2498                                  StorePtr, MachinePointerInfo(), false,
2499                                  false, 0);
2500     OutChains.push_back(Store);
2501   }
2502 }
2503
2504 // Create frame object on stack and copy registers used for byval passing to it.
2505 static unsigned
2506 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2507                     std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2508                     const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2509                     MachineFrameInfo *MFI, bool IsRegLoc,
2510                     SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2511                     EVT PtrTy) {
2512   const unsigned *Reg = Mips64IntRegs + 8;
2513   int FOOffset; // Frame object offset from virtual frame pointer.
2514
2515   if (IsRegLoc) {
2516     Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2517     FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2518   }
2519   else
2520     FOOffset = VA.getLocMemOffset();
2521
2522   // Create frame object.
2523   unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2524   unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2525   SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2526   InVals.push_back(FIN);
2527
2528   // Copy arg registers.
2529   for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2530        ++Reg, ++I) {
2531     unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2532     SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2533                                    DAG.getConstant(I * 8, PtrTy));
2534     SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2535                                  StorePtr, MachinePointerInfo(), false,
2536                                  false, 0);
2537     OutChains.push_back(Store);
2538   }
2539   
2540   return LastFI;
2541 }
2542
2543 /// LowerFormalArguments - transform physical registers into virtual registers
2544 /// and generate load operations for arguments places on the stack.
2545 SDValue
2546 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2547                                          CallingConv::ID CallConv,
2548                                          bool isVarArg,
2549                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2550                                          DebugLoc dl, SelectionDAG &DAG,
2551                                          SmallVectorImpl<SDValue> &InVals)
2552                                           const {
2553   MachineFunction &MF = DAG.getMachineFunction();
2554   MachineFrameInfo *MFI = MF.getFrameInfo();
2555   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2556
2557   MipsFI->setVarArgsFrameIndex(0);
2558
2559   // Used with vargs to acumulate store chains.
2560   std::vector<SDValue> OutChains;
2561
2562   // Assign locations to all of the incoming arguments.
2563   SmallVector<CCValAssign, 16> ArgLocs;
2564   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2565                  getTargetMachine(), ArgLocs, *DAG.getContext());
2566
2567   if (IsO32)
2568     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2569   else
2570     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2571
2572   int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2573
2574   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2575     CCValAssign &VA = ArgLocs[i];
2576     EVT ValVT = VA.getValVT();
2577     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2578     bool IsRegLoc = VA.isRegLoc();
2579
2580     if (Flags.isByVal()) {
2581       assert(Flags.getByValSize() &&
2582              "ByVal args of size 0 should have been ignored by front-end.");
2583       if (IsO32) {
2584         unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2585         LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2586                                         true);
2587         SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2588         InVals.push_back(FIN);
2589         ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2590       } else // N32/64
2591         LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2592                                      MFI, IsRegLoc, InVals, MipsFI,
2593                                      getPointerTy());
2594       continue;
2595     }
2596
2597     // Arguments stored on registers
2598     if (IsRegLoc) {
2599       EVT RegVT = VA.getLocVT();
2600       unsigned ArgReg = VA.getLocReg();
2601       TargetRegisterClass *RC = 0;
2602
2603       if (RegVT == MVT::i32)
2604         RC = Mips::CPURegsRegisterClass;
2605       else if (RegVT == MVT::i64)
2606         RC = Mips::CPU64RegsRegisterClass;
2607       else if (RegVT == MVT::f32)
2608         RC = Mips::FGR32RegisterClass;
2609       else if (RegVT == MVT::f64)
2610         RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2611       else
2612         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2613
2614       // Transform the arguments stored on
2615       // physical registers into virtual ones
2616       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2617       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2618
2619       // If this is an 8 or 16-bit value, it has been passed promoted
2620       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2621       // truncate to the right size.
2622       if (VA.getLocInfo() != CCValAssign::Full) {
2623         unsigned Opcode = 0;
2624         if (VA.getLocInfo() == CCValAssign::SExt)
2625           Opcode = ISD::AssertSext;
2626         else if (VA.getLocInfo() == CCValAssign::ZExt)
2627           Opcode = ISD::AssertZext;
2628         if (Opcode)
2629           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2630                                  DAG.getValueType(ValVT));
2631         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2632       }
2633
2634       // Handle floating point arguments passed in integer registers.
2635       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2636           (RegVT == MVT::i64 && ValVT == MVT::f64))
2637         ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2638       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2639         unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2640                                   getNextIntArgReg(ArgReg), RC);
2641         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2642         if (!Subtarget->isLittle())
2643           std::swap(ArgValue, ArgValue2);
2644         ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2645                                ArgValue, ArgValue2);
2646       }
2647
2648       InVals.push_back(ArgValue);
2649     } else { // VA.isRegLoc()
2650
2651       // sanity check
2652       assert(VA.isMemLoc());
2653
2654       // The stack pointer offset is relative to the caller stack frame.
2655       LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2656                                       VA.getLocMemOffset(), true);
2657
2658       // Create load nodes to retrieve arguments from the stack
2659       SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2660       InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2661                                    MachinePointerInfo::getFixedStack(LastFI),
2662                                    false, false, false, 0));
2663     }
2664   }
2665
2666   // The mips ABIs for returning structs by value requires that we copy
2667   // the sret argument into $v0 for the return. Save the argument into
2668   // a virtual register so that we can access it from the return points.
2669   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2670     unsigned Reg = MipsFI->getSRetReturnReg();
2671     if (!Reg) {
2672       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2673       MipsFI->setSRetReturnReg(Reg);
2674     }
2675     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2676     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2677   }
2678
2679   if (isVarArg) {
2680     unsigned NumOfRegs = IsO32 ? 4 : 8;
2681     const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2682     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2683     int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2684     TargetRegisterClass *RC
2685       = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2686     unsigned RegSize = RC->getSize();
2687     int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2688
2689     // Offset of the first variable argument from stack pointer.
2690     int FirstVaArgOffset;
2691
2692     if (IsO32 || (Idx == NumOfRegs)) {
2693       FirstVaArgOffset =
2694         (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2695     } else
2696       FirstVaArgOffset = RegSlotOffset;
2697
2698     // Record the frame index of the first variable argument
2699     // which is a value necessary to VASTART.
2700     LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2701     MipsFI->setVarArgsFrameIndex(LastFI);
2702
2703     // Copy the integer registers that have not been used for argument passing
2704     // to the argument register save area. For O32, the save area is allocated
2705     // in the caller's stack frame, while for N32/64, it is allocated in the
2706     // callee's stack frame.
2707     for (int StackOffset = RegSlotOffset;
2708          Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2709       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2710       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2711                                             MVT::getIntegerVT(RegSize * 8));
2712       LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2713       SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2714       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2715                                        MachinePointerInfo(), false, false, 0));
2716     }
2717   }
2718
2719   MipsFI->setLastInArgFI(LastFI);
2720
2721   // All stores are grouped in one node to allow the matching between
2722   // the size of Ins and InVals. This only happens when on varg functions
2723   if (!OutChains.empty()) {
2724     OutChains.push_back(Chain);
2725     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2726                         &OutChains[0], OutChains.size());
2727   }
2728
2729   return Chain;
2730 }
2731
2732 //===----------------------------------------------------------------------===//
2733 //               Return Value Calling Convention Implementation
2734 //===----------------------------------------------------------------------===//
2735
2736 SDValue
2737 MipsTargetLowering::LowerReturn(SDValue Chain,
2738                                 CallingConv::ID CallConv, bool isVarArg,
2739                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2740                                 const SmallVectorImpl<SDValue> &OutVals,
2741                                 DebugLoc dl, SelectionDAG &DAG) const {
2742
2743   // CCValAssign - represent the assignment of
2744   // the return value to a location
2745   SmallVector<CCValAssign, 16> RVLocs;
2746
2747   // CCState - Info about the registers and stack slot.
2748   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2749                  getTargetMachine(), RVLocs, *DAG.getContext());
2750
2751   // Analize return values.
2752   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2753
2754   // If this is the first return lowered for this function, add
2755   // the regs to the liveout set for the function.
2756   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2757     for (unsigned i = 0; i != RVLocs.size(); ++i)
2758       if (RVLocs[i].isRegLoc())
2759         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2760   }
2761
2762   SDValue Flag;
2763
2764   // Copy the result values into the output registers.
2765   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2766     CCValAssign &VA = RVLocs[i];
2767     assert(VA.isRegLoc() && "Can only return in registers!");
2768
2769     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2770
2771     // guarantee that all emitted copies are
2772     // stuck together, avoiding something bad
2773     Flag = Chain.getValue(1);
2774   }
2775
2776   // The mips ABIs for returning structs by value requires that we copy
2777   // the sret argument into $v0 for the return. We saved the argument into
2778   // a virtual register in the entry block, so now we copy the value out
2779   // and into $v0.
2780   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2781     MachineFunction &MF      = DAG.getMachineFunction();
2782     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2783     unsigned Reg = MipsFI->getSRetReturnReg();
2784
2785     if (!Reg)
2786       llvm_unreachable("sret virtual register not created in the entry block");
2787     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2788
2789     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2790     Flag = Chain.getValue(1);
2791   }
2792
2793   // Return on Mips is always a "jr $ra"
2794   if (Flag.getNode())
2795     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2796                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2797   else // Return Void
2798     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2799                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
2800 }
2801
2802 //===----------------------------------------------------------------------===//
2803 //                           Mips Inline Assembly Support
2804 //===----------------------------------------------------------------------===//
2805
2806 /// getConstraintType - Given a constraint letter, return the type of
2807 /// constraint it is for this target.
2808 MipsTargetLowering::ConstraintType MipsTargetLowering::
2809 getConstraintType(const std::string &Constraint) const
2810 {
2811   // Mips specific constrainy
2812   // GCC config/mips/constraints.md
2813   //
2814   // 'd' : An address register. Equivalent to r
2815   //       unless generating MIPS16 code.
2816   // 'y' : Equivalent to r; retained for
2817   //       backwards compatibility.
2818   // 'f' : Floating Point registers.
2819   if (Constraint.size() == 1) {
2820     switch (Constraint[0]) {
2821       default : break;
2822       case 'd':
2823       case 'y':
2824       case 'f':
2825         return C_RegisterClass;
2826         break;
2827     }
2828   }
2829   return TargetLowering::getConstraintType(Constraint);
2830 }
2831
2832 /// Examine constraint type and operand type and determine a weight value.
2833 /// This object must already have been set up with the operand type
2834 /// and the current alternative constraint selected.
2835 TargetLowering::ConstraintWeight
2836 MipsTargetLowering::getSingleConstraintMatchWeight(
2837     AsmOperandInfo &info, const char *constraint) const {
2838   ConstraintWeight weight = CW_Invalid;
2839   Value *CallOperandVal = info.CallOperandVal;
2840     // If we don't have a value, we can't do a match,
2841     // but allow it at the lowest weight.
2842   if (CallOperandVal == NULL)
2843     return CW_Default;
2844   Type *type = CallOperandVal->getType();
2845   // Look at the constraint type.
2846   switch (*constraint) {
2847   default:
2848     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2849     break;
2850   case 'd':
2851   case 'y':
2852     if (type->isIntegerTy())
2853       weight = CW_Register;
2854     break;
2855   case 'f':
2856     if (type->isFloatTy())
2857       weight = CW_Register;
2858     break;
2859   }
2860   return weight;
2861 }
2862
2863 /// Given a register class constraint, like 'r', if this corresponds directly
2864 /// to an LLVM register class, return a register of 0 and the register class
2865 /// pointer.
2866 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2867 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2868 {
2869   if (Constraint.size() == 1) {
2870     switch (Constraint[0]) {
2871     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2872     case 'y': // Same as 'r'. Exists for compatibility.
2873     case 'r':
2874       return std::make_pair(0U, Mips::CPURegsRegisterClass);
2875     case 'f':
2876       if (VT == MVT::f32)
2877         return std::make_pair(0U, Mips::FGR32RegisterClass);
2878       if (VT == MVT::f64)
2879         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2880           return std::make_pair(0U, Mips::AFGR64RegisterClass);
2881       break;
2882     }
2883   }
2884   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2885 }
2886
2887 bool
2888 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2889   // The Mips target isn't yet aware of offsets.
2890   return false;
2891 }
2892
2893 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2894   if (VT != MVT::f32 && VT != MVT::f64)
2895     return false;
2896   if (Imm.isNegZero())
2897     return false;
2898   return Imm.isZero();
2899 }