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