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