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