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