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