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