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