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