Fix a lot of o32 CC issues and add a bunch of tests. Patch by Akira Hatanaka with...
[oota-llvm.git] / lib / Target / Mips / MipsISelLowering.cpp
1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 using namespace llvm;
36
37 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
38   switch (Opcode) {
39     case MipsISD::JmpLink    : return "MipsISD::JmpLink";
40     case MipsISD::Hi         : return "MipsISD::Hi";
41     case MipsISD::Lo         : return "MipsISD::Lo";
42     case MipsISD::GPRel      : return "MipsISD::GPRel";
43     case MipsISD::Ret        : return "MipsISD::Ret";
44     case MipsISD::SelectCC   : return "MipsISD::SelectCC";
45     case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
46     case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
47     case MipsISD::FPCmp      : return "MipsISD::FPCmp";
48     case MipsISD::FPRound    : return "MipsISD::FPRound";
49     case MipsISD::MAdd       : return "MipsISD::MAdd";
50     case MipsISD::MAddu      : return "MipsISD::MAddu";
51     case MipsISD::MSub       : return "MipsISD::MSub";
52     case MipsISD::MSubu      : return "MipsISD::MSubu";
53     default                  : return NULL;
54   }
55 }
56
57 MipsTargetLowering::
58 MipsTargetLowering(MipsTargetMachine &TM)
59   : TargetLowering(TM, new MipsTargetObjectFile()) {
60   Subtarget = &TM.getSubtarget<MipsSubtarget>();
61
62   // Mips does not have i1 type, so use i32 for
63   // setcc operations results (slt, sgt, ...).
64   setBooleanContents(ZeroOrOneBooleanContent);
65
66   // Set up the register classes
67   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
68   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
69
70   // When dealing with single precision only, use libcalls
71   if (!Subtarget->isSingleFloat())
72     if (!Subtarget->isFP64bit())
73       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
74
75   // Load extented operations for i1 types must be promoted
76   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
77   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
78   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
79
80   // MIPS doesn't have extending float->double load/store
81   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
82   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
83
84   // Used by legalize types to correctly generate the setcc result.
85   // Without this, every float setcc comes with a AND/OR with the result,
86   // we don't want this, since the fpcmp result goes to a flag register,
87   // which is used implicitly by brcond and select operations.
88   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
89
90   // Mips Custom Operations
91   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
92   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
93   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
94   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
95   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
96   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
97   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
98   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
99   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
100   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
101   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
102   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
103   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
104
105
106   // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors'
107   // with operands comming from setcc fp comparions. This is necessary since
108   // the result from these setcc are in a flag registers (FCR31).
109   setOperationAction(ISD::AND,              MVT::i32,   Custom);
110   setOperationAction(ISD::OR,               MVT::i32,   Custom);
111
112   // Operations not directly supported by Mips.
113   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
114   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
115   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
116   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
117   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
118   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
119   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
120   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
121   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
122
123   if (!Subtarget->isMips32r2())
124     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
125
126   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
127   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
128   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
129   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
130   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
131   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
132   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
133   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
134   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
135   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
136   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
137   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
138   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
139
140   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
141
142   // Use the default for now
143   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
144   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
145   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
146
147   if (Subtarget->isSingleFloat())
148     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
149
150   if (!Subtarget->hasSEInReg()) {
151     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
152     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
153   }
154
155   if (!Subtarget->hasBitCount())
156     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
157
158   if (!Subtarget->hasSwap())
159     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
160
161   setTargetDAGCombine(ISD::ADDE);
162   setTargetDAGCombine(ISD::SUBE);
163
164   setStackPointerRegisterToSaveRestore(Mips::SP);
165   computeRegisterProperties();
166 }
167
168 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
169   return MVT::i32;
170 }
171
172 /// getFunctionAlignment - Return the Log2 alignment of this function.
173 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
174   return 2;
175 }
176
177 // SelectMadd -
178 // Transforms a subgraph in CurDAG if the following pattern is found:
179 //  (addc multLo, Lo0), (adde multHi, Hi0),
180 // where,
181 //  multHi/Lo: product of multiplication
182 //  Lo0: initial value of Lo register
183 //  Hi0: initial value of Hi register
184 // Return true if mattern matching was successful.
185 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
186   // ADDENode's second operand must be a flag output of an ADDC node in order
187   // for the matching to be successful.
188   SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
189
190   if (ADDCNode->getOpcode() != ISD::ADDC)
191     return false;
192
193   SDValue MultHi = ADDENode->getOperand(0);
194   SDValue MultLo = ADDCNode->getOperand(0);
195   SDNode* MultNode = MultHi.getNode();
196   unsigned MultOpc = MultHi.getOpcode();
197
198   // MultHi and MultLo must be generated by the same node,
199   if (MultLo.getNode() != MultNode)
200     return false;
201
202   // and it must be a multiplication.
203   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
204     return false;
205
206   // MultLo amd MultHi must be the first and second output of MultNode
207   // respectively.
208   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
209     return false;
210
211   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
212   // of the values of MultNode, in which case MultNode will be removed in later
213   // phases.
214   // If there exist users other than ADDENode or ADDCNode, this function returns
215   // here, which will result in MultNode being mapped to a single MULT
216   // instruction node rather than a pair of MULT and MADD instructions being
217   // produced.
218   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
219     return false;
220
221   SDValue Chain = CurDAG->getEntryNode();
222   DebugLoc dl = ADDENode->getDebugLoc();
223
224   // create MipsMAdd(u) node
225   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
226
227   SDValue MAdd = CurDAG->getNode(MultOpc, dl,
228                                  MVT::Glue,
229                                  MultNode->getOperand(0),// Factor 0
230                                  MultNode->getOperand(1),// Factor 1
231                                  ADDCNode->getOperand(1),// Lo0
232                                  ADDENode->getOperand(1));// Hi0
233
234   // create CopyFromReg nodes
235   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
236                                               MAdd);
237   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
238                                               Mips::HI, MVT::i32,
239                                               CopyFromLo.getValue(2));
240
241   // replace uses of adde and addc here
242   if (!SDValue(ADDCNode, 0).use_empty())
243     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
244
245   if (!SDValue(ADDENode, 0).use_empty())
246     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
247
248   return true;
249 }
250
251 // SelectMsub -
252 // Transforms a subgraph in CurDAG if the following pattern is found:
253 //  (addc Lo0, multLo), (sube Hi0, multHi),
254 // where,
255 //  multHi/Lo: product of multiplication
256 //  Lo0: initial value of Lo register
257 //  Hi0: initial value of Hi register
258 // Return true if mattern matching was successful.
259 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
260   // SUBENode's second operand must be a flag output of an SUBC node in order
261   // for the matching to be successful.
262   SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
263
264   if (SUBCNode->getOpcode() != ISD::SUBC)
265     return false;
266
267   SDValue MultHi = SUBENode->getOperand(1);
268   SDValue MultLo = SUBCNode->getOperand(1);
269   SDNode* MultNode = MultHi.getNode();
270   unsigned MultOpc = MultHi.getOpcode();
271
272   // MultHi and MultLo must be generated by the same node,
273   if (MultLo.getNode() != MultNode)
274     return false;
275
276   // and it must be a multiplication.
277   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
278     return false;
279
280   // MultLo amd MultHi must be the first and second output of MultNode
281   // respectively.
282   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
283     return false;
284
285   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
286   // of the values of MultNode, in which case MultNode will be removed in later
287   // phases.
288   // If there exist users other than SUBENode or SUBCNode, this function returns
289   // here, which will result in MultNode being mapped to a single MULT
290   // instruction node rather than a pair of MULT and MSUB instructions being
291   // produced.
292   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
293     return false;
294
295   SDValue Chain = CurDAG->getEntryNode();
296   DebugLoc dl = SUBENode->getDebugLoc();
297
298   // create MipsSub(u) node
299   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
300
301   SDValue MSub = CurDAG->getNode(MultOpc, dl,
302                                  MVT::Glue,
303                                  MultNode->getOperand(0),// Factor 0
304                                  MultNode->getOperand(1),// Factor 1
305                                  SUBCNode->getOperand(0),// Lo0
306                                  SUBENode->getOperand(0));// Hi0
307
308   // create CopyFromReg nodes
309   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
310                                               MSub);
311   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
312                                               Mips::HI, MVT::i32,
313                                               CopyFromLo.getValue(2));
314
315   // replace uses of sube and subc here
316   if (!SDValue(SUBCNode, 0).use_empty())
317     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
318
319   if (!SDValue(SUBENode, 0).use_empty())
320     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
321
322   return true;
323 }
324
325 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
326                                   TargetLowering::DAGCombinerInfo &DCI,
327                                   const MipsSubtarget* Subtarget) {
328   if (DCI.isBeforeLegalize())
329     return SDValue();
330
331   if (Subtarget->isMips32() && SelectMadd(N, &DAG))
332     return SDValue(N, 0);
333
334   return SDValue();
335 }
336
337 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
338                                   TargetLowering::DAGCombinerInfo &DCI,
339                                   const MipsSubtarget* Subtarget) {
340   if (DCI.isBeforeLegalize())
341     return SDValue();
342
343   if (Subtarget->isMips32() && SelectMsub(N, &DAG))
344     return SDValue(N, 0);
345
346   return SDValue();
347 }
348
349 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
350   const {
351   SelectionDAG &DAG = DCI.DAG;
352   unsigned opc = N->getOpcode();
353
354   switch (opc) {
355   default: break;
356   case ISD::ADDE:
357     return PerformADDECombine(N, DAG, DCI, Subtarget);
358   case ISD::SUBE:
359     return PerformSUBECombine(N, DAG, DCI, Subtarget);
360   }
361
362   return SDValue();
363 }
364
365 SDValue MipsTargetLowering::
366 LowerOperation(SDValue Op, SelectionDAG &DAG) const
367 {
368   switch (Op.getOpcode())
369   {
370     case ISD::AND:                return LowerANDOR(Op, DAG);
371     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
372     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
373     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
374     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
375     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
376     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
377     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
378     case ISD::OR:                 return LowerANDOR(Op, DAG);
379     case ISD::SELECT:             return LowerSELECT(Op, DAG);
380     case ISD::SETCC:              return LowerSETCC(Op, DAG);
381     case ISD::VASTART:            return LowerVASTART(Op, DAG);
382   }
383   return SDValue();
384 }
385
386 //===----------------------------------------------------------------------===//
387 //  Lower helper functions
388 //===----------------------------------------------------------------------===//
389
390 // AddLiveIn - This helper function adds the specified physical register to the
391 // MachineFunction as a live in value.  It also creates a corresponding
392 // virtual register for it.
393 static unsigned
394 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
395 {
396   assert(RC->contains(PReg) && "Not the correct regclass!");
397   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
398   MF.getRegInfo().addLiveIn(PReg, VReg);
399   return VReg;
400 }
401
402 // Get fp branch code (not opcode) from condition code.
403 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
404   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
405     return Mips::BRANCH_T;
406
407   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
408     return Mips::BRANCH_F;
409
410   return Mips::BRANCH_INVALID;
411 }
412
413 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
414   switch(BC) {
415     default:
416       llvm_unreachable("Unknown branch code");
417     case Mips::BRANCH_T  : return Mips::BC1T;
418     case Mips::BRANCH_F  : return Mips::BC1F;
419     case Mips::BRANCH_TL : return Mips::BC1TL;
420     case Mips::BRANCH_FL : return Mips::BC1FL;
421   }
422 }
423
424 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
425   switch (CC) {
426   default: llvm_unreachable("Unknown fp condition code!");
427   case ISD::SETEQ:
428   case ISD::SETOEQ: return Mips::FCOND_EQ;
429   case ISD::SETUNE: return Mips::FCOND_OGL;
430   case ISD::SETLT:
431   case ISD::SETOLT: return Mips::FCOND_OLT;
432   case ISD::SETGT:
433   case ISD::SETOGT: return Mips::FCOND_OGT;
434   case ISD::SETLE:
435   case ISD::SETOLE: return Mips::FCOND_OLE;
436   case ISD::SETGE:
437   case ISD::SETOGE: return Mips::FCOND_OGE;
438   case ISD::SETULT: return Mips::FCOND_ULT;
439   case ISD::SETULE: return Mips::FCOND_ULE;
440   case ISD::SETUGT: return Mips::FCOND_UGT;
441   case ISD::SETUGE: return Mips::FCOND_UGE;
442   case ISD::SETUO:  return Mips::FCOND_UN;
443   case ISD::SETO:   return Mips::FCOND_OR;
444   case ISD::SETNE:
445   case ISD::SETONE: return Mips::FCOND_NEQ;
446   case ISD::SETUEQ: return Mips::FCOND_UEQ;
447   }
448 }
449
450 MachineBasicBlock *
451 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
452                                                 MachineBasicBlock *BB) const {
453   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
454   bool isFPCmp = false;
455   DebugLoc dl = MI->getDebugLoc();
456
457   switch (MI->getOpcode()) {
458   default: assert(false && "Unexpected instr type to insert");
459   case Mips::Select_FCC:
460   case Mips::Select_FCC_S32:
461   case Mips::Select_FCC_D32:
462     isFPCmp = true; // FALL THROUGH
463   case Mips::Select_CC:
464   case Mips::Select_CC_S32:
465   case Mips::Select_CC_D32: {
466     // To "insert" a SELECT_CC instruction, we actually have to insert the
467     // diamond control-flow pattern.  The incoming instruction knows the
468     // destination vreg to set, the condition code register to branch on, the
469     // true/false values to select between, and a branch opcode to use.
470     const BasicBlock *LLVM_BB = BB->getBasicBlock();
471     MachineFunction::iterator It = BB;
472     ++It;
473
474     //  thisMBB:
475     //  ...
476     //   TrueVal = ...
477     //   setcc r1, r2, r3
478     //   bNE   r1, r0, copy1MBB
479     //   fallthrough --> copy0MBB
480     MachineBasicBlock *thisMBB  = BB;
481     MachineFunction *F = BB->getParent();
482     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
483     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
484     F->insert(It, copy0MBB);
485     F->insert(It, sinkMBB);
486
487     // Transfer the remainder of BB and its successor edges to sinkMBB.
488     sinkMBB->splice(sinkMBB->begin(), BB,
489                     llvm::next(MachineBasicBlock::iterator(MI)),
490                     BB->end());
491     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
492
493     // Next, add the true and fallthrough blocks as its successors.
494     BB->addSuccessor(copy0MBB);
495     BB->addSuccessor(sinkMBB);
496
497     // Emit the right instruction according to the type of the operands compared
498     if (isFPCmp) {
499       // Find the condiction code present in the setcc operation.
500       Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
501       // Get the branch opcode from the branch code.
502       unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
503       BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
504     } else
505       BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
506         .addReg(Mips::ZERO).addMBB(sinkMBB);
507
508     //  copy0MBB:
509     //   %FalseValue = ...
510     //   # fallthrough to sinkMBB
511     BB = copy0MBB;
512
513     // Update machine-CFG edges
514     BB->addSuccessor(sinkMBB);
515
516     //  sinkMBB:
517     //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
518     //  ...
519     BB = sinkMBB;
520     BuildMI(*BB, BB->begin(), dl,
521             TII->get(Mips::PHI), MI->getOperand(0).getReg())
522       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
523       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
524
525     MI->eraseFromParent();   // The pseudo instruction is gone now.
526     return BB;
527   }
528   }
529 }
530
531 //===----------------------------------------------------------------------===//
532 //  Misc Lower Operation implementation
533 //===----------------------------------------------------------------------===//
534
535 SDValue MipsTargetLowering::
536 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
537 {
538   if (!Subtarget->isMips1())
539     return Op;
540
541   MachineFunction &MF = DAG.getMachineFunction();
542   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
543
544   SDValue Chain = DAG.getEntryNode();
545   DebugLoc dl = Op.getDebugLoc();
546   SDValue Src = Op.getOperand(0);
547
548   // Set the condition register
549   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
550   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
551   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
552
553   SDValue Cst = DAG.getConstant(3, MVT::i32);
554   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
555   Cst = DAG.getConstant(2, MVT::i32);
556   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
557
558   SDValue InFlag(0, 0);
559   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
560
561   // Emit the round instruction and bit convert to integer
562   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
563                               Src, CondReg.getValue(1));
564   SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
565   return BitCvt;
566 }
567
568 SDValue MipsTargetLowering::
569 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
570 {
571   SDValue Chain = Op.getOperand(0);
572   SDValue Size = Op.getOperand(1);
573   DebugLoc dl = Op.getDebugLoc();
574
575   // Get a reference from Mips stack pointer
576   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
577
578   // Subtract the dynamic size from the actual stack size to
579   // obtain the new stack size.
580   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
581
582   // The Sub result contains the new stack start address, so it
583   // must be placed in the stack pointer register.
584   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
585
586   // This node always has two return values: a new stack pointer
587   // value and a chain
588   SDValue Ops[2] = { Sub, Chain };
589   return DAG.getMergeValues(Ops, 2, dl);
590 }
591
592 SDValue MipsTargetLowering::
593 LowerANDOR(SDValue Op, SelectionDAG &DAG) const
594 {
595   SDValue LHS   = Op.getOperand(0);
596   SDValue RHS   = Op.getOperand(1);
597   DebugLoc dl   = Op.getDebugLoc();
598
599   if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
600     return Op;
601
602   SDValue True  = DAG.getConstant(1, MVT::i32);
603   SDValue False = DAG.getConstant(0, MVT::i32);
604
605   SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
606                              LHS, True, False, LHS.getOperand(2));
607   SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
608                              RHS, True, False, RHS.getOperand(2));
609
610   return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
611 }
612
613 SDValue MipsTargetLowering::
614 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
615 {
616   // The first operand is the chain, the second is the condition, the third is
617   // the block to branch to if the condition is true.
618   SDValue Chain = Op.getOperand(0);
619   SDValue Dest = Op.getOperand(2);
620   DebugLoc dl = Op.getDebugLoc();
621
622   if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
623     return Op;
624
625   SDValue CondRes = Op.getOperand(1);
626   SDValue CCNode  = CondRes.getOperand(2);
627   Mips::CondCode CC =
628     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
629   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
630
631   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
632              Dest, CondRes);
633 }
634
635 SDValue MipsTargetLowering::
636 LowerSETCC(SDValue Op, SelectionDAG &DAG) const
637 {
638   // The operands to this are the left and right operands to compare (ops #0,
639   // and #1) and the condition code to compare them with (op #2) as a
640   // CondCodeSDNode.
641   SDValue LHS = Op.getOperand(0);
642   SDValue RHS = Op.getOperand(1);
643   DebugLoc dl = Op.getDebugLoc();
644
645   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
646
647   return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS,
648                  DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
649 }
650
651 SDValue MipsTargetLowering::
652 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
653 {
654   SDValue Cond  = Op.getOperand(0);
655   SDValue True  = Op.getOperand(1);
656   SDValue False = Op.getOperand(2);
657   DebugLoc dl = Op.getDebugLoc();
658
659   // if the incomming condition comes from a integer compare, the select
660   // operation must be SelectCC or a conditional move if the subtarget
661   // supports it.
662   if (Cond.getOpcode() != MipsISD::FPCmp) {
663     if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
664       return Op;
665     return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(),
666                        Cond, True, False);
667   }
668
669   // if the incomming condition comes from fpcmp, the select
670   // operation must use FPSelectCC.
671   SDValue CCNode = Cond.getOperand(2);
672   return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
673                      Cond, True, False, CCNode);
674 }
675
676 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
677                                                SelectionDAG &DAG) const {
678   // FIXME there isn't actually debug info here
679   DebugLoc dl = Op.getDebugLoc();
680   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
681
682   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
683     SDVTList VTs = DAG.getVTList(MVT::i32);
684
685     MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
686
687     // %gp_rel relocation
688     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
689       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
690                                               MipsII::MO_GPREL);
691       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
692       SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
693       return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
694     }
695     // %hi/%lo relocation
696     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
697                                             MipsII::MO_ABS_HILO);
698     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
699     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
700     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
701
702   } else {
703     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
704                                             MipsII::MO_GOT);
705     SDValue ResNode = DAG.getLoad(MVT::i32, dl,
706                                   DAG.getEntryNode(), GA, MachinePointerInfo(),
707                                   false, false, 0);
708     // On functions and global targets not internal linked only
709     // a load from got/GP is necessary for PIC to work.
710     if (!GV->hasLocalLinkage() || isa<Function>(GV))
711       return ResNode;
712     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
713     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
714   }
715
716   llvm_unreachable("Dont know how to handle GlobalAddress");
717   return SDValue(0,0);
718 }
719
720 SDValue MipsTargetLowering::
721 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
722 {
723   llvm_unreachable("TLS not implemented for MIPS.");
724   return SDValue(); // Not reached
725 }
726
727 SDValue MipsTargetLowering::
728 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
729 {
730   SDValue ResNode;
731   SDValue HiPart;
732   // FIXME there isn't actually debug info here
733   DebugLoc dl = Op.getDebugLoc();
734   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
735   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HILO;
736
737   EVT PtrVT = Op.getValueType();
738   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
739
740   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
741
742   if (!IsPIC) {
743     SDValue Ops[] = { JTI };
744     HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
745   } else // Emit Load from Global Pointer
746     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
747                          MachinePointerInfo(),
748                          false, false, 0);
749
750   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
751   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
752
753   return ResNode;
754 }
755
756 SDValue MipsTargetLowering::
757 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
758 {
759   SDValue ResNode;
760   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
761   const Constant *C = N->getConstVal();
762   // FIXME there isn't actually debug info here
763   DebugLoc dl = Op.getDebugLoc();
764
765   // gp_rel relocation
766   // FIXME: we should reference the constant pool using small data sections,
767   // but the asm printer currently doens't support this feature without
768   // hacking it. This feature should come soon so we can uncomment the
769   // stuff below.
770   //if (IsInSmallSection(C->getType())) {
771   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
772   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
773   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
774
775   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
776     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
777                                       N->getOffset(), MipsII::MO_ABS_HILO);
778     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
779     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
780     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
781   } else {
782     SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
783                                       N->getOffset(), MipsII::MO_GOT);
784     SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
785                                CP, MachinePointerInfo::getConstantPool(),
786                                false, false, 0);
787     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
788     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
789   }
790
791   return ResNode;
792 }
793
794 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
795   MachineFunction &MF = DAG.getMachineFunction();
796   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
797
798   DebugLoc dl = Op.getDebugLoc();
799   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
800                                  getPointerTy());
801
802   // vastart just stores the address of the VarArgsFrameIndex slot into the
803   // memory location argument.
804   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
805   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
806                       MachinePointerInfo(SV),
807                       false, false, 0);
808 }
809
810 //===----------------------------------------------------------------------===//
811 //                      Calling Convention Implementation
812 //===----------------------------------------------------------------------===//
813
814 #include "MipsGenCallingConv.inc"
815
816 //===----------------------------------------------------------------------===//
817 // TODO: Implement a generic logic using tblgen that can support this.
818 // Mips O32 ABI rules:
819 // ---
820 // i32 - Passed in A0, A1, A2, A3 and stack
821 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
822 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
823 // f64 - Only passed in two aliased f32 registers if no int reg has been used
824 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
825 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
826 //       go to stack.
827 //===----------------------------------------------------------------------===//
828
829 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
830                        MVT LocVT, CCValAssign::LocInfo LocInfo,
831                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
832
833   static const unsigned IntRegsSize=4, FloatRegsSize=2;
834
835   static const unsigned IntRegs[] = {
836       Mips::A0, Mips::A1, Mips::A2, Mips::A3
837   };
838   static const unsigned F32Regs[] = {
839       Mips::F12, Mips::F14
840   };
841   static const unsigned F64Regs[] = {
842       Mips::D6, Mips::D7
843   };
844
845   unsigned Reg = 0;
846   static bool IntRegUsed = false;
847
848   // This must be the first arg of the call if no regs have been allocated.
849   // Initialize IntRegUsed in that case.
850   if (IntRegs[State.getFirstUnallocated(IntRegs, IntRegsSize)] == Mips::A0 &&
851       F32Regs[State.getFirstUnallocated(F32Regs, FloatRegsSize)] == Mips::F12 &&
852       F64Regs[State.getFirstUnallocated(F64Regs, FloatRegsSize)] == Mips::D6)
853     IntRegUsed = false;
854
855   // Promote i8 and i16
856   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
857     LocVT = MVT::i32;
858     if (ArgFlags.isSExt())
859       LocInfo = CCValAssign::SExt;
860     else if (ArgFlags.isZExt())
861       LocInfo = CCValAssign::ZExt;
862     else
863       LocInfo = CCValAssign::AExt;
864   }
865
866   if (ValVT == MVT::i32) {
867     Reg = State.AllocateReg(IntRegs, IntRegsSize);
868     IntRegUsed = true;
869   } else if (ValVT == MVT::f32) {
870     // An int reg has to be marked allocated regardless of whether or not
871     // IntRegUsed is true.
872     Reg = State.AllocateReg(IntRegs, IntRegsSize);
873
874     if (IntRegUsed) {
875       if (Reg) // Int reg is available
876         LocVT = MVT::i32;
877     } else {
878       unsigned FReg = State.AllocateReg(F32Regs, FloatRegsSize);
879       if (FReg) // F32 reg is available
880         Reg = FReg;
881       else if (Reg) // No F32 regs are available, but an int reg is available.
882         LocVT = MVT::i32;
883     }
884   } else if (ValVT == MVT::f64) {
885     // Int regs have to be marked allocated regardless of whether or not
886     // IntRegUsed is true.
887     Reg = State.AllocateReg(IntRegs, IntRegsSize);
888     if (Reg == Mips::A1)
889       Reg = State.AllocateReg(IntRegs, IntRegsSize);
890     else if (Reg == Mips::A3)
891       Reg = 0;
892     State.AllocateReg(IntRegs, IntRegsSize);
893
894     // At this point, Reg is A0, A2 or 0, and all the unavailable integer regs
895     // are marked as allocated.
896     if (IntRegUsed) {
897       if (Reg)// if int reg is available
898         LocVT = MVT::i32;
899     } else {
900       unsigned FReg = State.AllocateReg(F64Regs, FloatRegsSize);
901       if (FReg) // F64 reg is available.
902         Reg = FReg;
903       else if (Reg) // No F64 regs are available, but an int reg is available.
904         LocVT = MVT::i32;
905     }
906   } else
907     assert(false && "cannot handle this ValVT");
908
909   if (!Reg) {
910     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
911     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
912     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
913   } else
914     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
915
916   return false; // CC must always match
917 }
918
919 static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
920                        MVT LocVT, CCValAssign::LocInfo LocInfo,
921                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
922
923   static const unsigned IntRegsSize=4;
924
925   static const unsigned IntRegs[] = {
926       Mips::A0, Mips::A1, Mips::A2, Mips::A3
927   };
928
929   // Promote i8 and i16
930   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
931     LocVT = MVT::i32;
932     if (ArgFlags.isSExt())
933       LocInfo = CCValAssign::SExt;
934     else if (ArgFlags.isZExt())
935       LocInfo = CCValAssign::ZExt;
936     else
937       LocInfo = CCValAssign::AExt;
938   }
939
940   if (ValVT == MVT::i32 || ValVT == MVT::f32) {
941     if (unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize)) {
942       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
943       return false;
944     }
945     unsigned Off = State.AllocateStack(4, 4);
946     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
947     return false;
948   }
949
950   unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
951   if (ValVT == MVT::f64) {
952     if (IntRegs[UnallocIntReg] == (unsigned (Mips::A1))) {
953       // A1 can't be used anymore, because 64 bit arguments
954       // must be aligned when copied back to the caller stack
955       State.AllocateReg(IntRegs, IntRegsSize);
956       UnallocIntReg++;
957     }
958
959     if (IntRegs[UnallocIntReg] == (unsigned (Mips::A0)) ||
960         IntRegs[UnallocIntReg] == (unsigned (Mips::A2))) {
961       unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize);
962       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
963       // Shadow the next register so it can be used
964       // later to get the other 32bit part.
965       State.AllocateReg(IntRegs, IntRegsSize);
966       return false;
967     }
968
969     // Register is shadowed to preserve alignment, and the
970     // argument goes to a stack location.
971     if (UnallocIntReg != IntRegsSize)
972       State.AllocateReg(IntRegs, IntRegsSize);
973
974     unsigned Off = State.AllocateStack(8, 8);
975     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
976     return false;
977   }
978
979   return true; // CC didn't match
980 }
981
982 //===----------------------------------------------------------------------===//
983 //                  Call Calling Convention Implementation
984 //===----------------------------------------------------------------------===//
985
986 /// LowerCall - functions arguments are copied from virtual regs to
987 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
988 /// TODO: isTailCall.
989 SDValue
990 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
991                               CallingConv::ID CallConv, bool isVarArg,
992                               bool &isTailCall,
993                               const SmallVectorImpl<ISD::OutputArg> &Outs,
994                               const SmallVectorImpl<SDValue> &OutVals,
995                               const SmallVectorImpl<ISD::InputArg> &Ins,
996                               DebugLoc dl, SelectionDAG &DAG,
997                               SmallVectorImpl<SDValue> &InVals) const {
998   // MIPs target does not yet support tail call optimization.
999   isTailCall = false;
1000
1001   MachineFunction &MF = DAG.getMachineFunction();
1002   MachineFrameInfo *MFI = MF.getFrameInfo();
1003   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1004
1005   // Analyze operands of the call, assigning locations to each operand.
1006   SmallVector<CCValAssign, 16> ArgLocs;
1007   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1008                  *DAG.getContext());
1009
1010   // To meet O32 ABI, Mips must always allocate 16 bytes on
1011   // the stack (even if less than 4 are used as arguments)
1012   if (Subtarget->isABI_O32()) {
1013     int VTsize = MVT(MVT::i32).getSizeInBits()/8;
1014     MFI->CreateFixedObject(VTsize, (VTsize*3), true);
1015     CCInfo.AnalyzeCallOperands(Outs,
1016                      isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1017   } else
1018     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1019
1020   // Get a count of how many bytes are to be pushed on the stack.
1021   unsigned NumBytes = CCInfo.getNextStackOffset();
1022   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1023
1024   // With EABI is it possible to have 16 args on registers.
1025   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1026   SmallVector<SDValue, 8> MemOpChains;
1027
1028   // First/LastArgStackLoc contains the first/last
1029   // "at stack" argument location.
1030   int LastArgStackLoc = 0;
1031   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1032
1033   // Walk the register/memloc assignments, inserting copies/loads.
1034   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1035     SDValue Arg = OutVals[i];
1036     CCValAssign &VA = ArgLocs[i];
1037
1038     // Promote the value if needed.
1039     switch (VA.getLocInfo()) {
1040     default: llvm_unreachable("Unknown loc info!");
1041     case CCValAssign::Full:
1042       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1043         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1044           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1045         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1046           Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1047           SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1048                                    DAG.getConstant(0, getPointerTy()));
1049           SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1050                                    DAG.getConstant(1, getPointerTy()));
1051           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1052           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1053           continue;
1054         }
1055       }
1056       break;
1057     case CCValAssign::SExt:
1058       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1059       break;
1060     case CCValAssign::ZExt:
1061       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1062       break;
1063     case CCValAssign::AExt:
1064       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1065       break;
1066     }
1067
1068     // Arguments that can be passed on register must be kept at
1069     // RegsToPass vector
1070     if (VA.isRegLoc()) {
1071       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1072       continue;
1073     }
1074
1075     // Register can't get to this point...
1076     assert(VA.isMemLoc());
1077
1078     // Create the frame index object for this incoming parameter
1079     // This guarantees that when allocating Local Area the firsts
1080     // 16 bytes which are alwayes reserved won't be overwritten
1081     // if O32 ABI is used. For EABI the first address is zero.
1082     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1083     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1084                                     LastArgStackLoc, true);
1085
1086     SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1087
1088     // emit ISD::STORE whichs stores the
1089     // parameter value to a stack Location
1090     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1091                                        MachinePointerInfo(),
1092                                        false, false, 0));
1093   }
1094
1095   // Transform all store nodes into one single node because all store
1096   // nodes are independent of each other.
1097   if (!MemOpChains.empty())
1098     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1099                         &MemOpChains[0], MemOpChains.size());
1100
1101   // Build a sequence of copy-to-reg nodes chained together with token
1102   // chain and flag operands which copy the outgoing args into registers.
1103   // The InFlag in necessary since all emited instructions must be
1104   // stuck together.
1105   SDValue InFlag;
1106   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1107     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1108                              RegsToPass[i].second, InFlag);
1109     InFlag = Chain.getValue(1);
1110   }
1111
1112   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1113   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1114   // node so that legalize doesn't hack it.
1115   unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1116   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1117     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1118                                 getPointerTy(), 0, OpFlag);
1119   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1120     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1121                                 getPointerTy(), OpFlag);
1122
1123   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1124   //             = Chain, Callee, Reg#1, Reg#2, ...
1125   //
1126   // Returns a chain & a flag for retval copy to use.
1127   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1128   SmallVector<SDValue, 8> Ops;
1129   Ops.push_back(Chain);
1130   Ops.push_back(Callee);
1131
1132   // Add argument registers to the end of the list so that they are
1133   // known live into the call.
1134   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1135     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1136                                   RegsToPass[i].second.getValueType()));
1137
1138   if (InFlag.getNode())
1139     Ops.push_back(InFlag);
1140
1141   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1142   InFlag = Chain.getValue(1);
1143
1144   // Create a stack location to hold GP when PIC is used. This stack
1145   // location is used on function prologue to save GP and also after all
1146   // emited CALL's to restore GP.
1147   if (IsPIC) {
1148       // Function can have an arbitrary number of calls, so
1149       // hold the LastArgStackLoc with the biggest offset.
1150       int FI;
1151       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1152       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1153         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1154         // Create the frame index only once. SPOffset here can be anything
1155         // (this will be fixed on processFunctionBeforeFrameFinalized)
1156         if (MipsFI->getGPStackOffset() == -1) {
1157           FI = MFI->CreateFixedObject(4, 0, true);
1158           MipsFI->setGPFI(FI);
1159         }
1160         MipsFI->setGPStackOffset(LastArgStackLoc);
1161       }
1162
1163       // Reload GP value.
1164       FI = MipsFI->getGPFI();
1165       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1166       SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1167                                    MachinePointerInfo::getFixedStack(FI),
1168                                    false, false, 0);
1169       Chain = GPLoad.getValue(1);
1170       Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1171                                GPLoad, SDValue(0,0));
1172       InFlag = Chain.getValue(1);
1173   }
1174
1175   // Create the CALLSEQ_END node.
1176   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1177                              DAG.getIntPtrConstant(0, true), InFlag);
1178   InFlag = Chain.getValue(1);
1179
1180   // Handle result values, copying them out of physregs into vregs that we
1181   // return.
1182   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1183                          Ins, dl, DAG, InVals);
1184 }
1185
1186 /// LowerCallResult - Lower the result values of a call into the
1187 /// appropriate copies out of appropriate physical registers.
1188 SDValue
1189 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1190                                     CallingConv::ID CallConv, bool isVarArg,
1191                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1192                                     DebugLoc dl, SelectionDAG &DAG,
1193                                     SmallVectorImpl<SDValue> &InVals) const {
1194
1195   // Assign locations to each value returned by this call.
1196   SmallVector<CCValAssign, 16> RVLocs;
1197   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1198                  RVLocs, *DAG.getContext());
1199
1200   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1201
1202   // Copy all of the result registers out of their specified physreg.
1203   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1204     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1205                                RVLocs[i].getValVT(), InFlag).getValue(1);
1206     InFlag = Chain.getValue(2);
1207     InVals.push_back(Chain.getValue(0));
1208   }
1209
1210   return Chain;
1211 }
1212
1213 //===----------------------------------------------------------------------===//
1214 //             Formal Arguments Calling Convention Implementation
1215 //===----------------------------------------------------------------------===//
1216
1217 /// LowerFormalArguments - transform physical registers into virtual registers
1218 /// and generate load operations for arguments places on the stack.
1219 SDValue
1220 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1221                                         CallingConv::ID CallConv, bool isVarArg,
1222                                         const SmallVectorImpl<ISD::InputArg>
1223                                         &Ins,
1224                                         DebugLoc dl, SelectionDAG &DAG,
1225                                         SmallVectorImpl<SDValue> &InVals)
1226                                           const {
1227
1228   MachineFunction &MF = DAG.getMachineFunction();
1229   MachineFrameInfo *MFI = MF.getFrameInfo();
1230   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1231
1232   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
1233   MipsFI->setVarArgsFrameIndex(0);
1234
1235   // Used with vargs to acumulate store chains.
1236   std::vector<SDValue> OutChains;
1237
1238   // Keep track of the last register used for arguments
1239   unsigned ArgRegEnd = 0;
1240
1241   // Assign locations to all of the incoming arguments.
1242   SmallVector<CCValAssign, 16> ArgLocs;
1243   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1244                  ArgLocs, *DAG.getContext());
1245
1246   if (Subtarget->isABI_O32())
1247     CCInfo.AnalyzeFormalArguments(Ins,
1248                         isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1249   else
1250     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1251
1252   SDValue StackPtr;
1253
1254   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1255
1256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1257     CCValAssign &VA = ArgLocs[i];
1258
1259     // Arguments stored on registers
1260     if (VA.isRegLoc()) {
1261       EVT RegVT = VA.getLocVT();
1262       ArgRegEnd = VA.getLocReg();
1263       TargetRegisterClass *RC = 0;
1264
1265       if (RegVT == MVT::i32)
1266         RC = Mips::CPURegsRegisterClass;
1267       else if (RegVT == MVT::f32)
1268         RC = Mips::FGR32RegisterClass;
1269       else if (RegVT == MVT::f64) {
1270         if (!Subtarget->isSingleFloat())
1271           RC = Mips::AFGR64RegisterClass;
1272       } else
1273         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1274
1275       // Transform the arguments stored on
1276       // physical registers into virtual ones
1277       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1278       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1279
1280       // If this is an 8 or 16-bit value, it has been passed promoted
1281       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1282       // truncate to the right size.
1283       if (VA.getLocInfo() != CCValAssign::Full) {
1284         unsigned Opcode = 0;
1285         if (VA.getLocInfo() == CCValAssign::SExt)
1286           Opcode = ISD::AssertSext;
1287         else if (VA.getLocInfo() == CCValAssign::ZExt)
1288           Opcode = ISD::AssertZext;
1289         if (Opcode)
1290           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1291                                  DAG.getValueType(VA.getValVT()));
1292         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1293       }
1294
1295       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1296       if (Subtarget->isABI_O32()) {
1297         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1298           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1299         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1300           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1301                                     VA.getLocReg()+1, RC);
1302           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1303           SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, ArgValue2, ArgValue);
1304           ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Pair);
1305         }
1306       }
1307
1308       InVals.push_back(ArgValue);
1309     } else { // VA.isRegLoc()
1310
1311       // sanity check
1312       assert(VA.isMemLoc());
1313
1314       // The last argument is not a register anymore
1315       ArgRegEnd = 0;
1316
1317       // The stack pointer offset is relative to the caller stack frame.
1318       // Since the real stack size is unknown here, a negative SPOffset
1319       // is used so there's a way to adjust these offsets when the stack
1320       // size get known (on EliminateFrameIndex). A dummy SPOffset is
1321       // used instead of a direct negative address (which is recorded to
1322       // be used on emitPrologue) to avoid mis-calc of the first stack
1323       // offset on PEI::calculateFrameObjectOffsets.
1324       // Arguments are always 32-bit.
1325       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1326       int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1327       MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1328         (FirstStackArgLoc + VA.getLocMemOffset())));
1329
1330       // Create load nodes to retrieve arguments from the stack
1331       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1332       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1333                                    MachinePointerInfo::getFixedStack(FI),
1334                                    false, false, 0));
1335     }
1336   }
1337
1338   // The mips ABIs for returning structs by value requires that we copy
1339   // the sret argument into $v0 for the return. Save the argument into
1340   // a virtual register so that we can access it from the return points.
1341   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1342     unsigned Reg = MipsFI->getSRetReturnReg();
1343     if (!Reg) {
1344       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1345       MipsFI->setSRetReturnReg(Reg);
1346     }
1347     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1348     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1349   }
1350
1351   // To meet ABI, when VARARGS are passed on registers, the registers
1352   // must have their values written to the caller stack frame. If the last
1353   // argument was placed in the stack, there's no need to save any register.
1354   if ((isVarArg) && (Subtarget->isABI_O32() && ArgRegEnd)) {
1355     if (StackPtr.getNode() == 0)
1356       StackPtr = DAG.getRegister(StackReg, getPointerTy());
1357
1358     // The last register argument that must be saved is Mips::A3
1359     TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1360     unsigned StackLoc = ArgLocs.size()-1;
1361
1362     for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd, ++StackLoc) {
1363       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1364       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1365
1366       int FI = MFI->CreateFixedObject(4, 0, true);
1367       MipsFI->recordStoreVarArgsFI(FI, -(4+(StackLoc*4)));
1368       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1369       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1370                                        MachinePointerInfo(),
1371                                        false, false, 0));
1372
1373       // Record the frame index of the first variable argument
1374       // which is a value necessary to VASTART.
1375       if (!MipsFI->getVarArgsFrameIndex())
1376         MipsFI->setVarArgsFrameIndex(FI);
1377     }
1378   }
1379
1380   // All stores are grouped in one node to allow the matching between
1381   // the size of Ins and InVals. This only happens when on varg functions
1382   if (!OutChains.empty()) {
1383     OutChains.push_back(Chain);
1384     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1385                         &OutChains[0], OutChains.size());
1386   }
1387
1388   return Chain;
1389 }
1390
1391 //===----------------------------------------------------------------------===//
1392 //               Return Value Calling Convention Implementation
1393 //===----------------------------------------------------------------------===//
1394
1395 SDValue
1396 MipsTargetLowering::LowerReturn(SDValue Chain,
1397                                 CallingConv::ID CallConv, bool isVarArg,
1398                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1399                                 const SmallVectorImpl<SDValue> &OutVals,
1400                                 DebugLoc dl, SelectionDAG &DAG) const {
1401
1402   // CCValAssign - represent the assignment of
1403   // the return value to a location
1404   SmallVector<CCValAssign, 16> RVLocs;
1405
1406   // CCState - Info about the registers and stack slot.
1407   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1408                  RVLocs, *DAG.getContext());
1409
1410   // Analize return values.
1411   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1412
1413   // If this is the first return lowered for this function, add
1414   // the regs to the liveout set for the function.
1415   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1416     for (unsigned i = 0; i != RVLocs.size(); ++i)
1417       if (RVLocs[i].isRegLoc())
1418         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1419   }
1420
1421   SDValue Flag;
1422
1423   // Copy the result values into the output registers.
1424   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1425     CCValAssign &VA = RVLocs[i];
1426     assert(VA.isRegLoc() && "Can only return in registers!");
1427
1428     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1429                              OutVals[i], Flag);
1430
1431     // guarantee that all emitted copies are
1432     // stuck together, avoiding something bad
1433     Flag = Chain.getValue(1);
1434   }
1435
1436   // The mips ABIs for returning structs by value requires that we copy
1437   // the sret argument into $v0 for the return. We saved the argument into
1438   // a virtual register in the entry block, so now we copy the value out
1439   // and into $v0.
1440   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1441     MachineFunction &MF      = DAG.getMachineFunction();
1442     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1443     unsigned Reg = MipsFI->getSRetReturnReg();
1444
1445     if (!Reg)
1446       llvm_unreachable("sret virtual register not created in the entry block");
1447     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1448
1449     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1450     Flag = Chain.getValue(1);
1451   }
1452
1453   // Return on Mips is always a "jr $ra"
1454   if (Flag.getNode())
1455     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1456                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1457   else // Return Void
1458     return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1459                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1460 }
1461
1462 //===----------------------------------------------------------------------===//
1463 //                           Mips Inline Assembly Support
1464 //===----------------------------------------------------------------------===//
1465
1466 /// getConstraintType - Given a constraint letter, return the type of
1467 /// constraint it is for this target.
1468 MipsTargetLowering::ConstraintType MipsTargetLowering::
1469 getConstraintType(const std::string &Constraint) const
1470 {
1471   // Mips specific constrainy
1472   // GCC config/mips/constraints.md
1473   //
1474   // 'd' : An address register. Equivalent to r
1475   //       unless generating MIPS16 code.
1476   // 'y' : Equivalent to r; retained for
1477   //       backwards compatibility.
1478   // 'f' : Floating Point registers.
1479   if (Constraint.size() == 1) {
1480     switch (Constraint[0]) {
1481       default : break;
1482       case 'd':
1483       case 'y':
1484       case 'f':
1485         return C_RegisterClass;
1486         break;
1487     }
1488   }
1489   return TargetLowering::getConstraintType(Constraint);
1490 }
1491
1492 /// Examine constraint type and operand type and determine a weight value.
1493 /// This object must already have been set up with the operand type
1494 /// and the current alternative constraint selected.
1495 TargetLowering::ConstraintWeight
1496 MipsTargetLowering::getSingleConstraintMatchWeight(
1497     AsmOperandInfo &info, const char *constraint) const {
1498   ConstraintWeight weight = CW_Invalid;
1499   Value *CallOperandVal = info.CallOperandVal;
1500     // If we don't have a value, we can't do a match,
1501     // but allow it at the lowest weight.
1502   if (CallOperandVal == NULL)
1503     return CW_Default;
1504   const Type *type = CallOperandVal->getType();
1505   // Look at the constraint type.
1506   switch (*constraint) {
1507   default:
1508     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1509     break;
1510   case 'd':
1511   case 'y':
1512     if (type->isIntegerTy())
1513       weight = CW_Register;
1514     break;
1515   case 'f':
1516     if (type->isFloatTy())
1517       weight = CW_Register;
1518     break;
1519   }
1520   return weight;
1521 }
1522
1523 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1524 /// return a list of registers that can be used to satisfy the constraint.
1525 /// This should only be used for C_RegisterClass constraints.
1526 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1527 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1528 {
1529   if (Constraint.size() == 1) {
1530     switch (Constraint[0]) {
1531     case 'r':
1532       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1533     case 'f':
1534       if (VT == MVT::f32)
1535         return std::make_pair(0U, Mips::FGR32RegisterClass);
1536       if (VT == MVT::f64)
1537         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1538           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1539     }
1540   }
1541   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1542 }
1543
1544 /// Given a register class constraint, like 'r', if this corresponds directly
1545 /// to an LLVM register class, return a register of 0 and the register class
1546 /// pointer.
1547 std::vector<unsigned> MipsTargetLowering::
1548 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1549                                   EVT VT) const
1550 {
1551   if (Constraint.size() != 1)
1552     return std::vector<unsigned>();
1553
1554   switch (Constraint[0]) {
1555     default : break;
1556     case 'r':
1557     // GCC Mips Constraint Letters
1558     case 'd':
1559     case 'y':
1560       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1561              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1562              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1563              Mips::T8, 0);
1564
1565     case 'f':
1566       if (VT == MVT::f32) {
1567         if (Subtarget->isSingleFloat())
1568           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1569                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1570                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1571                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1572                  Mips::F30, Mips::F31, 0);
1573         else
1574           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1575                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1576                  Mips::F28, Mips::F30, 0);
1577       }
1578
1579       if (VT == MVT::f64)
1580         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1581           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1582                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1583                  Mips::D14, Mips::D15, 0);
1584   }
1585   return std::vector<unsigned>();
1586 }
1587
1588 bool
1589 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1590   // The Mips target isn't yet aware of offsets.
1591   return false;
1592 }
1593
1594 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1595   if (VT != MVT::f32 && VT != MVT::f64)
1596     return false;
1597   if (Imm.isNegZero())
1598     return false;
1599   return Imm.isZero();
1600 }