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