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