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