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