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