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