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