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