Start moving TargetLowering away from using full MVTs and towards SimpleValueType...
[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
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.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/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 using namespace llvm;
37
38 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
39   switch (Opcode) {
40     case MipsISD::JmpLink    : return "MipsISD::JmpLink";
41     case MipsISD::Hi         : return "MipsISD::Hi";
42     case MipsISD::Lo         : return "MipsISD::Lo";
43     case MipsISD::GPRel      : return "MipsISD::GPRel";
44     case MipsISD::Ret        : return "MipsISD::Ret";
45     case MipsISD::CMov       : return "MipsISD::CMov";
46     case MipsISD::SelectCC   : return "MipsISD::SelectCC";
47     case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
48     case MipsISD::FPBrcond   : return "MipsISD::FPBrcond";
49     case MipsISD::FPCmp      : return "MipsISD::FPCmp";
50     case MipsISD::FPRound    : return "MipsISD::FPRound";
51     default                  : return NULL;
52   }
53 }
54
55 MipsTargetLowering::
56 MipsTargetLowering(MipsTargetMachine &TM)
57   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
58   Subtarget = &TM.getSubtarget<MipsSubtarget>();
59
60   // Mips does not have i1 type, so use i32 for
61   // setcc operations results (slt, sgt, ...). 
62   setBooleanContents(ZeroOrOneBooleanContent);
63
64   // JumpTable targets must use GOT when using PIC_
65   setUsesGlobalOffsetTable(true);
66
67   // Set up the register classes
68   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
69   addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
70
71   // When dealing with single precision only, use libcalls
72   if (!Subtarget->isSingleFloat())
73     if (!Subtarget->isFP64bit())
74       addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
75
76   // Legal fp constants
77   addLegalFPImmediate(APFloat(+0.0f));
78
79   // Load extented operations for i1 types must be promoted 
80   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
81   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
82   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
83
84   // MIPS doesn't have extending float->double load/store
85   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // Used by legalize types to correctly generate the setcc result. 
89   // Without this, every float setcc comes with a AND/OR with the result, 
90   // we don't want this, since the fpcmp result goes to a flag register, 
91   // which is used implicitly by brcond and select operations.
92   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
93
94   // Mips Custom Operations
95   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
96   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
97   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
98   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
99   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
100   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
101   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
102   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
103   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
104   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
105   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
106   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
107
108   // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors' 
109   // with operands comming from setcc fp comparions. This is necessary since 
110   // the result from these setcc are in a flag registers (FCR31).
111   setOperationAction(ISD::AND,              MVT::i32,   Custom);
112   setOperationAction(ISD::OR,               MVT::i32,   Custom);
113
114   // Operations not directly supported by Mips.
115   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
116   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
117   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
118   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
119   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
121   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
122   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
123   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
124   setOperationAction(ISD::ROTR,              MVT::i32,   Expand);
125   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
126   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
127   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
128   setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Expand);
129   setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Expand);
130   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
131   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
132   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
133   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
134   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
135   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
136   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
137   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
138
139   // We don't have line number support yet.
140   setOperationAction(ISD::DBG_STOPPOINT,     MVT::Other, Expand);
141   setOperationAction(ISD::DEBUG_LOC,         MVT::Other, Expand);
142   setOperationAction(ISD::DBG_LABEL,         MVT::Other, Expand);
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   setStackPointerRegisterToSaveRestore(Mips::SP);
165   computeRegisterProperties();
166 }
167
168 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(MVT 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 SDValue MipsTargetLowering::
178 LowerOperation(SDValue Op, SelectionDAG &DAG) 
179 {
180   switch (Op.getOpcode()) 
181   {
182     case ISD::AND:                return LowerANDOR(Op, DAG);
183     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
184     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
185     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
186     case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
187     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
188     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
189     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
190     case ISD::OR:                 return LowerANDOR(Op, DAG);
191     case ISD::SELECT:             return LowerSELECT(Op, DAG);
192     case ISD::SETCC:              return LowerSETCC(Op, DAG);
193   }
194   return SDValue();
195 }
196
197 //===----------------------------------------------------------------------===//
198 //  Lower helper functions
199 //===----------------------------------------------------------------------===//
200
201 // AddLiveIn - This helper function adds the specified physical register to the
202 // MachineFunction as a live in value.  It also creates a corresponding
203 // virtual register for it.
204 static unsigned
205 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
206 {
207   assert(RC->contains(PReg) && "Not the correct regclass!");
208   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
209   MF.getRegInfo().addLiveIn(PReg, VReg);
210   return VReg;
211 }
212
213 // Get fp branch code (not opcode) from condition code.
214 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
215   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
216     return Mips::BRANCH_T;
217
218   if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
219     return Mips::BRANCH_F;
220
221   return Mips::BRANCH_INVALID;
222 }
223   
224 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
225   switch(BC) {
226     default:
227       llvm_unreachable("Unknown branch code");
228     case Mips::BRANCH_T  : return Mips::BC1T;
229     case Mips::BRANCH_F  : return Mips::BC1F;
230     case Mips::BRANCH_TL : return Mips::BC1TL;
231     case Mips::BRANCH_FL : return Mips::BC1FL;
232   }
233 }
234
235 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
236   switch (CC) {
237   default: llvm_unreachable("Unknown fp condition code!");
238   case ISD::SETEQ:  
239   case ISD::SETOEQ: return Mips::FCOND_EQ;
240   case ISD::SETUNE: return Mips::FCOND_OGL;
241   case ISD::SETLT:  
242   case ISD::SETOLT: return Mips::FCOND_OLT;
243   case ISD::SETGT:  
244   case ISD::SETOGT: return Mips::FCOND_OGT;
245   case ISD::SETLE:  
246   case ISD::SETOLE: return Mips::FCOND_OLE; 
247   case ISD::SETGE:
248   case ISD::SETOGE: return Mips::FCOND_OGE;
249   case ISD::SETULT: return Mips::FCOND_ULT;
250   case ISD::SETULE: return Mips::FCOND_ULE; 
251   case ISD::SETUGT: return Mips::FCOND_UGT;
252   case ISD::SETUGE: return Mips::FCOND_UGE;
253   case ISD::SETUO:  return Mips::FCOND_UN; 
254   case ISD::SETO:   return Mips::FCOND_OR;
255   case ISD::SETNE:  
256   case ISD::SETONE: return Mips::FCOND_NEQ;
257   case ISD::SETUEQ: return Mips::FCOND_UEQ;
258   }
259 }
260
261 MachineBasicBlock *
262 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
263                                                 MachineBasicBlock *BB) const {
264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
265   bool isFPCmp = false;
266   DebugLoc dl = MI->getDebugLoc();
267
268   switch (MI->getOpcode()) {
269   default: assert(false && "Unexpected instr type to insert");
270   case Mips::Select_FCC:
271   case Mips::Select_FCC_S32:
272   case Mips::Select_FCC_D32:
273     isFPCmp = true; // FALL THROUGH
274   case Mips::Select_CC:
275   case Mips::Select_CC_S32:
276   case Mips::Select_CC_D32: {
277     // To "insert" a SELECT_CC instruction, we actually have to insert the
278     // diamond control-flow pattern.  The incoming instruction knows the
279     // destination vreg to set, the condition code register to branch on, the
280     // true/false values to select between, and a branch opcode to use.
281     const BasicBlock *LLVM_BB = BB->getBasicBlock();
282     MachineFunction::iterator It = BB;
283     ++It;
284
285     //  thisMBB:
286     //  ...
287     //   TrueVal = ...
288     //   setcc r1, r2, r3
289     //   bNE   r1, r0, copy1MBB
290     //   fallthrough --> copy0MBB
291     MachineBasicBlock *thisMBB  = BB;
292     MachineFunction *F = BB->getParent();
293     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
294     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
295
296     // Emit the right instruction according to the type of the operands compared
297     if (isFPCmp) {
298       // Find the condiction code present in the setcc operation.
299       Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
300       // Get the branch opcode from the branch code.
301       unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
302       BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
303     } else
304       BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
305         .addReg(Mips::ZERO).addMBB(sinkMBB);
306
307     F->insert(It, copy0MBB);
308     F->insert(It, sinkMBB);
309     // Update machine-CFG edges by first adding all successors of the current
310     // block to the new block which will contain the Phi node for the select.
311     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
312         e = BB->succ_end(); i != e; ++i)
313       sinkMBB->addSuccessor(*i);
314     // Next, remove all successors of the current block, and add the true
315     // and fallthrough blocks as its successors.
316     while(!BB->succ_empty())
317       BB->removeSuccessor(BB->succ_begin());
318     BB->addSuccessor(copy0MBB);
319     BB->addSuccessor(sinkMBB);
320
321     //  copy0MBB:
322     //   %FalseValue = ...
323     //   # fallthrough to sinkMBB
324     BB = copy0MBB;
325
326     // Update machine-CFG edges
327     BB->addSuccessor(sinkMBB);
328
329     //  sinkMBB:
330     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
331     //  ...
332     BB = sinkMBB;
333     BuildMI(BB, dl, TII->get(Mips::PHI), MI->getOperand(0).getReg())
334       .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
335       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
336
337     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
338     return BB;
339   }
340   }
341 }
342
343 //===----------------------------------------------------------------------===//
344 //  Misc Lower Operation implementation
345 //===----------------------------------------------------------------------===//
346
347 SDValue MipsTargetLowering::
348 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG)
349 {
350   if (!Subtarget->isMips1())
351     return Op;
352
353   MachineFunction &MF = DAG.getMachineFunction();
354   unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
355
356   SDValue Chain = DAG.getEntryNode();
357   DebugLoc dl = Op.getDebugLoc();
358   SDValue Src = Op.getOperand(0);
359
360   // Set the condition register
361   SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
362   CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
363   CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
364
365   SDValue Cst = DAG.getConstant(3, MVT::i32);
366   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
367   Cst = DAG.getConstant(2, MVT::i32);
368   SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
369
370   SDValue InFlag(0, 0);
371   CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
372
373   // Emit the round instruction and bit convert to integer
374   SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
375                               Src, CondReg.getValue(1));
376   SDValue BitCvt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Trunc);
377   return BitCvt;
378 }
379
380 SDValue MipsTargetLowering::
381 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG)
382 {
383   SDValue Chain = Op.getOperand(0);
384   SDValue Size = Op.getOperand(1);
385   DebugLoc dl = Op.getDebugLoc();
386
387   // Get a reference from Mips stack pointer
388   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
389
390   // Subtract the dynamic size from the actual stack size to
391   // obtain the new stack size.
392   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
393
394   // The Sub result contains the new stack start address, so it 
395   // must be placed in the stack pointer register.
396   Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
397   
398   // This node always has two return values: a new stack pointer 
399   // value and a chain
400   SDValue Ops[2] = { Sub, Chain };
401   return DAG.getMergeValues(Ops, 2, dl);
402 }
403
404 SDValue MipsTargetLowering::
405 LowerANDOR(SDValue Op, SelectionDAG &DAG)
406 {
407   SDValue LHS   = Op.getOperand(0);
408   SDValue RHS   = Op.getOperand(1);
409   DebugLoc dl   = Op.getDebugLoc();
410
411   if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
412     return Op;
413
414   SDValue True  = DAG.getConstant(1, MVT::i32);
415   SDValue False = DAG.getConstant(0, MVT::i32);
416
417   SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
418                              LHS, True, False, LHS.getOperand(2));
419   SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
420                              RHS, True, False, RHS.getOperand(2));
421
422   return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
423 }
424
425 SDValue MipsTargetLowering::
426 LowerBRCOND(SDValue Op, SelectionDAG &DAG)
427 {
428   // The first operand is the chain, the second is the condition, the third is 
429   // the block to branch to if the condition is true.
430   SDValue Chain = Op.getOperand(0);
431   SDValue Dest = Op.getOperand(2);
432   DebugLoc dl = Op.getDebugLoc();
433
434   if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
435     return Op;
436   
437   SDValue CondRes = Op.getOperand(1);
438   SDValue CCNode  = CondRes.getOperand(2);
439   Mips::CondCode CC =
440     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
441   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32); 
442
443   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode, 
444              Dest, CondRes);
445 }
446
447 SDValue MipsTargetLowering::
448 LowerSETCC(SDValue Op, SelectionDAG &DAG)
449 {
450   // The operands to this are the left and right operands to compare (ops #0, 
451   // and #1) and the condition code to compare them with (op #2) as a 
452   // CondCodeSDNode.
453   SDValue LHS = Op.getOperand(0); 
454   SDValue RHS = Op.getOperand(1);
455   DebugLoc dl = Op.getDebugLoc();
456
457   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
458   
459   return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS, 
460                  DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
461 }
462
463 SDValue MipsTargetLowering::
464 LowerSELECT(SDValue Op, SelectionDAG &DAG) 
465 {
466   SDValue Cond  = Op.getOperand(0); 
467   SDValue True  = Op.getOperand(1);
468   SDValue False = Op.getOperand(2);
469   DebugLoc dl = Op.getDebugLoc();
470
471   // if the incomming condition comes from a integer compare, the select 
472   // operation must be SelectCC or a conditional move if the subtarget 
473   // supports it.
474   if (Cond.getOpcode() != MipsISD::FPCmp) {
475     if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
476       return Op;
477     return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(), 
478                        Cond, True, False);
479   }
480
481   // if the incomming condition comes from fpcmp, the select
482   // operation must use FPSelectCC.
483   SDValue CCNode = Cond.getOperand(2);
484   return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(), 
485                      Cond, True, False, CCNode);
486 }
487
488 SDValue MipsTargetLowering::
489 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) 
490 {
491   // FIXME there isn't actually debug info here
492   DebugLoc dl = Op.getDebugLoc();
493   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
494   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
495
496   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
497     // %hi/%lo relocation
498     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, GA);
499     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
500     return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
501
502   } else { // Abicall relocations, TODO: make this cleaner.
503     SDValue ResNode = DAG.getLoad(MVT::i32, dl, 
504                                   DAG.getEntryNode(), GA, NULL, 0);
505     // On functions and global targets not internal linked only
506     // a load from got/GP is necessary for PIC to work.
507     if (!GV->hasLocalLinkage() || isa<Function>(GV))
508       return ResNode;
509     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
510     return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
511   }
512
513   llvm_unreachable("Dont know how to handle GlobalAddress");
514   return SDValue(0,0);
515 }
516
517 SDValue MipsTargetLowering::
518 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
519 {
520   llvm_unreachable("TLS not implemented for MIPS.");
521   return SDValue(); // Not reached
522 }
523
524 SDValue MipsTargetLowering::
525 LowerJumpTable(SDValue Op, SelectionDAG &DAG) 
526 {
527   SDValue ResNode;
528   SDValue HiPart; 
529   // FIXME there isn't actually debug info here
530   DebugLoc dl = Op.getDebugLoc();
531
532   MVT PtrVT = Op.getValueType();
533   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
534   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
535
536   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
537     SDVTList VTs = DAG.getVTList(MVT::i32);
538     SDValue Ops[] = { JTI };
539     HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, Ops, 1);
540   } else // Emit Load from Global Pointer
541     HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI, NULL, 0);
542
543   SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
544   ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
545
546   return ResNode;
547 }
548
549 SDValue MipsTargetLowering::
550 LowerConstantPool(SDValue Op, SelectionDAG &DAG) 
551 {
552   SDValue ResNode;
553   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
554   Constant *C = N->getConstVal();
555   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
556   // FIXME there isn't actually debug info here
557   DebugLoc dl = Op.getDebugLoc();
558
559   // gp_rel relocation
560   // FIXME: we should reference the constant pool using small data sections, 
561   // but the asm printer currently doens't support this feature without
562   // hacking it. This feature should come soon so we can uncomment the 
563   // stuff below.
564   //if (IsInSmallSection(C->getType())) {
565   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
566   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
567   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode); 
568   //} else { // %hi/%lo relocation
569     SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
570     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
571     ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
572   //}
573
574   return ResNode;
575 }
576
577 //===----------------------------------------------------------------------===//
578 //                      Calling Convention Implementation
579 //===----------------------------------------------------------------------===//
580
581 #include "MipsGenCallingConv.inc"
582
583 //===----------------------------------------------------------------------===//
584 // TODO: Implement a generic logic using tblgen that can support this. 
585 // Mips O32 ABI rules:
586 // ---
587 // i32 - Passed in A0, A1, A2, A3 and stack
588 // f32 - Only passed in f32 registers if no int reg has been used yet to hold 
589 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
590 // f64 - Only passed in two aliased f32 registers if no int reg has been used 
591 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is 
592 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
593 //       go to stack.
594 //===----------------------------------------------------------------------===//
595
596 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
597                        MVT LocVT, CCValAssign::LocInfo LocInfo,
598                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
599
600   static const unsigned IntRegsSize=4, FloatRegsSize=2; 
601
602   static const unsigned IntRegs[] = {
603       Mips::A0, Mips::A1, Mips::A2, Mips::A3
604   };
605   static const unsigned F32Regs[] = {
606       Mips::F12, Mips::F14
607   };
608   static const unsigned F64Regs[] = {
609       Mips::D6, Mips::D7
610   };
611
612   unsigned Reg=0;
613   unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
614   bool IntRegUsed = (IntRegs[UnallocIntReg] != (unsigned (Mips::A0)));
615
616   // Promote i8 and i16
617   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
618     LocVT = MVT::i32;
619     if (ArgFlags.isSExt())
620       LocInfo = CCValAssign::SExt;
621     else if (ArgFlags.isZExt())
622       LocInfo = CCValAssign::ZExt;
623     else
624       LocInfo = CCValAssign::AExt;
625   }
626
627   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && IntRegUsed)) {
628     Reg = State.AllocateReg(IntRegs, IntRegsSize);
629     IntRegUsed = true;
630     LocVT = MVT::i32;
631   }
632
633   if (ValVT.isFloatingPoint() && !IntRegUsed) {
634     if (ValVT == MVT::f32)
635       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
636     else
637       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
638   }
639
640   if (ValVT == MVT::f64 && IntRegUsed) {
641     if (UnallocIntReg != IntRegsSize) {
642       // If we hit register A3 as the first not allocated, we must
643       // mark it as allocated (shadow) and use the stack instead.
644       if (IntRegs[UnallocIntReg] != (unsigned (Mips::A3)))
645         Reg = Mips::A2;
646       for (;UnallocIntReg < IntRegsSize; ++UnallocIntReg)
647         State.AllocateReg(UnallocIntReg);
648     } 
649     LocVT = MVT::i32;
650   }
651
652   if (!Reg) {
653     unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
654     unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
655     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
656   } else
657     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
658
659   return false; // CC must always match
660 }
661
662 //===----------------------------------------------------------------------===//
663 //                  Call Calling Convention Implementation
664 //===----------------------------------------------------------------------===//
665
666 /// LowerCall - functions arguments are copied from virtual regs to
667 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
668 /// TODO: isVarArg, isTailCall.
669 SDValue
670 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
671                               unsigned CallConv, bool isVarArg,
672                               bool isTailCall,
673                               const SmallVectorImpl<ISD::OutputArg> &Outs,
674                               const SmallVectorImpl<ISD::InputArg> &Ins,
675                               DebugLoc dl, SelectionDAG &DAG,
676                               SmallVectorImpl<SDValue> &InVals) {
677
678   MachineFunction &MF = DAG.getMachineFunction();
679   MachineFrameInfo *MFI = MF.getFrameInfo();
680
681   // Analyze operands of the call, assigning locations to each operand.
682   SmallVector<CCValAssign, 16> ArgLocs;
683   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
684                  *DAG.getContext());
685
686   // To meet O32 ABI, Mips must always allocate 16 bytes on
687   // the stack (even if less than 4 are used as arguments)
688   if (Subtarget->isABI_O32()) {
689     int VTsize = MVT(MVT::i32).getSizeInBits()/8;
690     MFI->CreateFixedObject(VTsize, (VTsize*3));
691     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
692   } else
693     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
694   
695   // Get a count of how many bytes are to be pushed on the stack.
696   unsigned NumBytes = CCInfo.getNextStackOffset();
697   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
698
699   // With EABI is it possible to have 16 args on registers.
700   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
701   SmallVector<SDValue, 8> MemOpChains;
702
703   // First/LastArgStackLoc contains the first/last 
704   // "at stack" argument location.
705   int LastArgStackLoc = 0;
706   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
707
708   // Walk the register/memloc assignments, inserting copies/loads.
709   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
710     SDValue Arg = Outs[i].Val;
711     CCValAssign &VA = ArgLocs[i];
712
713     // Promote the value if needed.
714     switch (VA.getLocInfo()) {
715     default: llvm_unreachable("Unknown loc info!");
716     case CCValAssign::Full: 
717       if (Subtarget->isABI_O32() && VA.isRegLoc()) {
718         if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
719           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Arg);
720         if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
721           Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
722           SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
723                                    DAG.getConstant(0, getPointerTy()));
724           SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
725                                    DAG.getConstant(1, getPointerTy()));
726           RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
727           RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
728           continue;
729         }  
730       }
731       break;
732     case CCValAssign::SExt:
733       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
734       break;
735     case CCValAssign::ZExt:
736       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
737       break;
738     case CCValAssign::AExt:
739       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
740       break;
741     }
742     
743     // Arguments that can be passed on register must be kept at 
744     // RegsToPass vector
745     if (VA.isRegLoc()) {
746       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
747       continue;
748     }
749     
750     // Register can't get to this point...
751     assert(VA.isMemLoc());
752     
753     // Create the frame index object for this incoming parameter
754     // This guarantees that when allocating Local Area the firsts
755     // 16 bytes which are alwayes reserved won't be overwritten
756     // if O32 ABI is used. For EABI the first address is zero.
757     LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
758     int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
759                                     LastArgStackLoc);
760
761     SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
762
763     // emit ISD::STORE whichs stores the 
764     // parameter value to a stack Location
765     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
766   }
767
768   // Transform all store nodes into one single node because all store
769   // nodes are independent of each other.
770   if (!MemOpChains.empty())     
771     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
772                         &MemOpChains[0], MemOpChains.size());
773
774   // Build a sequence of copy-to-reg nodes chained together with token 
775   // chain and flag operands which copy the outgoing args into registers.
776   // The InFlag in necessary since all emited instructions must be
777   // stuck together.
778   SDValue InFlag;
779   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
780     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
781                              RegsToPass[i].second, InFlag);
782     InFlag = Chain.getValue(1);
783   }
784
785   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
786   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
787   // node so that legalize doesn't hack it. 
788   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
789     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
790   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
791     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
792
793   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
794   //             = Chain, Callee, Reg#1, Reg#2, ...  
795   //
796   // Returns a chain & a flag for retval copy to use.
797   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
798   SmallVector<SDValue, 8> Ops;
799   Ops.push_back(Chain);
800   Ops.push_back(Callee);
801
802   // Add argument registers to the end of the list so that they are 
803   // known live into the call.
804   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
805     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
806                                   RegsToPass[i].second.getValueType()));
807
808   if (InFlag.getNode())
809     Ops.push_back(InFlag);
810
811   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
812   InFlag = Chain.getValue(1);
813
814   // Create the CALLSEQ_END node.
815   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
816                              DAG.getIntPtrConstant(0, true), InFlag);
817   InFlag = Chain.getValue(1);
818
819   // Create a stack location to hold GP when PIC is used. This stack 
820   // location is used on function prologue to save GP and also after all 
821   // emited CALL's to restore GP. 
822   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
823       // Function can have an arbitrary number of calls, so 
824       // hold the LastArgStackLoc with the biggest offset.
825       int FI;
826       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
827       if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
828         LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
829         // Create the frame index only once. SPOffset here can be anything 
830         // (this will be fixed on processFunctionBeforeFrameFinalized)
831         if (MipsFI->getGPStackOffset() == -1) {
832           FI = MFI->CreateFixedObject(4, 0);
833           MipsFI->setGPFI(FI);
834         }
835         MipsFI->setGPStackOffset(LastArgStackLoc);
836       }
837
838       // Reload GP value.
839       FI = MipsFI->getGPFI();
840       SDValue FIN = DAG.getFrameIndex(FI,getPointerTy());
841       SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN, NULL, 0);
842       Chain = GPLoad.getValue(1);
843       Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32), 
844                                GPLoad, SDValue(0,0));
845       InFlag = Chain.getValue(1);
846   }      
847
848   // Handle result values, copying them out of physregs into vregs that we
849   // return.
850   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
851                          Ins, dl, DAG, InVals);
852 }
853
854 /// LowerCallResult - Lower the result values of a call into the
855 /// appropriate copies out of appropriate physical registers.
856 SDValue
857 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
858                                     unsigned CallConv, bool isVarArg,
859                                     const SmallVectorImpl<ISD::InputArg> &Ins,
860                                     DebugLoc dl, SelectionDAG &DAG,
861                                     SmallVectorImpl<SDValue> &InVals) {
862
863   // Assign locations to each value returned by this call.
864   SmallVector<CCValAssign, 16> RVLocs;
865   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
866                  RVLocs, *DAG.getContext());
867
868   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
869
870   // Copy all of the result registers out of their specified physreg.
871   for (unsigned i = 0; i != RVLocs.size(); ++i) {
872     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
873                                RVLocs[i].getValVT(), InFlag).getValue(1);
874     InFlag = Chain.getValue(2);
875     InVals.push_back(Chain.getValue(0));
876   }
877
878   return Chain;
879 }
880
881 //===----------------------------------------------------------------------===//
882 //             Formal Arguments Calling Convention Implementation
883 //===----------------------------------------------------------------------===//
884
885 /// LowerFormalArguments - transform physical registers into
886 /// virtual registers and generate load operations for
887 /// arguments places on the stack.
888 /// TODO: isVarArg
889 SDValue
890 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
891                                          unsigned CallConv, bool isVarArg,
892                                          const SmallVectorImpl<ISD::InputArg>
893                                            &Ins,
894                                          DebugLoc dl, SelectionDAG &DAG,
895                                          SmallVectorImpl<SDValue> &InVals) {
896
897   MachineFunction &MF = DAG.getMachineFunction();
898   MachineFrameInfo *MFI = MF.getFrameInfo();
899   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
900
901   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
902
903   // Assign locations to all of the incoming arguments.
904   SmallVector<CCValAssign, 16> ArgLocs;
905   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
906                  ArgLocs, *DAG.getContext());
907
908   if (Subtarget->isABI_O32())
909     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
910   else
911     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
912
913   SDValue StackPtr;
914
915   unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
916
917   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
918     CCValAssign &VA = ArgLocs[i];
919
920     // Arguments stored on registers
921     if (VA.isRegLoc()) {
922       MVT RegVT = VA.getLocVT();
923       TargetRegisterClass *RC = 0;
924
925       if (RegVT == MVT::i32)
926         RC = Mips::CPURegsRegisterClass; 
927       else if (RegVT == MVT::f32) 
928         RC = Mips::FGR32RegisterClass;
929       else if (RegVT == MVT::f64) {
930         if (!Subtarget->isSingleFloat()) 
931           RC = Mips::AFGR64RegisterClass;
932       } else  
933         llvm_unreachable("RegVT not supported by LowerFormalArguments Lowering");
934
935       // Transform the arguments stored on 
936       // physical registers into virtual ones
937       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
938       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
939       
940       // If this is an 8 or 16-bit value, it has been passed promoted 
941       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
942       // truncate to the right size.
943       if (VA.getLocInfo() != CCValAssign::Full) {
944         unsigned Opcode = 0;
945         if (VA.getLocInfo() == CCValAssign::SExt)
946           Opcode = ISD::AssertSext;
947         else if (VA.getLocInfo() == CCValAssign::ZExt)
948           Opcode = ISD::AssertZext;
949         if (Opcode)
950           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue, 
951                                  DAG.getValueType(VA.getValVT()));
952         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
953       }
954
955       // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64 
956       if (Subtarget->isABI_O32()) {
957         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32) 
958           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
959         if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
960           unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(), 
961                                     VA.getLocReg()+1, RC);
962           SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
963           SDValue Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
964           SDValue Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue2);
965           ArgValue = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::f64, Lo, Hi);
966         }
967       }
968
969       InVals.push_back(ArgValue);
970
971       // To meet ABI, when VARARGS are passed on registers, the registers
972       // must have their values written to the caller stack frame. 
973       if ((isVarArg) && (Subtarget->isABI_O32())) {
974         if (StackPtr.getNode() == 0)
975           StackPtr = DAG.getRegister(StackReg, getPointerTy());
976      
977         // The stack pointer offset is relative to the caller stack frame. 
978         // Since the real stack size is unknown here, a negative SPOffset 
979         // is used so there's a way to adjust these offsets when the stack
980         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
981         // used instead of a direct negative address (which is recorded to
982         // be used on emitPrologue) to avoid mis-calc of the first stack 
983         // offset on PEI::calculateFrameObjectOffsets.
984         // Arguments are always 32-bit.
985         int FI = MFI->CreateFixedObject(4, 0);
986         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
987         SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
988       
989         // emit ISD::STORE whichs stores the 
990         // parameter value to a stack Location
991         InVals.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff, NULL, 0));
992       }
993
994     } else { // VA.isRegLoc()
995
996       // sanity check
997       assert(VA.isMemLoc());
998       
999       // The stack pointer offset is relative to the caller stack frame. 
1000       // Since the real stack size is unknown here, a negative SPOffset 
1001       // is used so there's a way to adjust these offsets when the stack
1002       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
1003       // used instead of a direct negative address (which is recorded to
1004       // be used on emitPrologue) to avoid mis-calc of the first stack 
1005       // offset on PEI::calculateFrameObjectOffsets.
1006       // Arguments are always 32-bit.
1007       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1008       int FI = MFI->CreateFixedObject(ArgSize, 0);
1009       MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1010         (FirstStackArgLoc + VA.getLocMemOffset())));
1011
1012       // Create load nodes to retrieve arguments from the stack
1013       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1014       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1015     }
1016   }
1017
1018   // The mips ABIs for returning structs by value requires that we copy
1019   // the sret argument into $v0 for the return. Save the argument into
1020   // a virtual register so that we can access it from the return points.
1021   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1022     unsigned Reg = MipsFI->getSRetReturnReg();
1023     if (!Reg) {
1024       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1025       MipsFI->setSRetReturnReg(Reg);
1026     }
1027     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1028     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1029   }
1030
1031   return Chain;
1032 }
1033
1034 //===----------------------------------------------------------------------===//
1035 //               Return Value Calling Convention Implementation
1036 //===----------------------------------------------------------------------===//
1037
1038 SDValue
1039 MipsTargetLowering::LowerReturn(SDValue Chain,
1040                                 unsigned CallConv, bool isVarArg,
1041                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
1042                                 DebugLoc dl, SelectionDAG &DAG) {
1043
1044   // CCValAssign - represent the assignment of
1045   // the return value to a location
1046   SmallVector<CCValAssign, 16> RVLocs;
1047
1048   // CCState - Info about the registers and stack slot.
1049   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1050                  RVLocs, *DAG.getContext());
1051
1052   // Analize return values.
1053   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1054
1055   // If this is the first return lowered for this function, add 
1056   // the regs to the liveout set for the function.
1057   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1058     for (unsigned i = 0; i != RVLocs.size(); ++i)
1059       if (RVLocs[i].isRegLoc())
1060         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1061   }
1062
1063   SDValue Flag;
1064
1065   // Copy the result values into the output registers.
1066   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1067     CCValAssign &VA = RVLocs[i];
1068     assert(VA.isRegLoc() && "Can only return in registers!");
1069
1070     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
1071                              Outs[i].Val, Flag);
1072
1073     // guarantee that all emitted copies are
1074     // stuck together, avoiding something bad
1075     Flag = Chain.getValue(1);
1076   }
1077
1078   // The mips ABIs for returning structs by value requires that we copy
1079   // the sret argument into $v0 for the return. We saved the argument into
1080   // a virtual register in the entry block, so now we copy the value out
1081   // and into $v0.
1082   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1083     MachineFunction &MF      = DAG.getMachineFunction();
1084     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1085     unsigned Reg = MipsFI->getSRetReturnReg();
1086
1087     if (!Reg) 
1088       llvm_unreachable("sret virtual register not created in the entry block");
1089     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1090
1091     Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1092     Flag = Chain.getValue(1);
1093   }
1094
1095   // Return on Mips is always a "jr $ra"
1096   if (Flag.getNode())
1097     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
1098                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1099   else // Return Void
1100     return DAG.getNode(MipsISD::Ret, dl, MVT::Other, 
1101                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
1102 }
1103
1104 //===----------------------------------------------------------------------===//
1105 //                           Mips Inline Assembly Support
1106 //===----------------------------------------------------------------------===//
1107
1108 /// getConstraintType - Given a constraint letter, return the type of
1109 /// constraint it is for this target.
1110 MipsTargetLowering::ConstraintType MipsTargetLowering::
1111 getConstraintType(const std::string &Constraint) const 
1112 {
1113   // Mips specific constrainy 
1114   // GCC config/mips/constraints.md
1115   //
1116   // 'd' : An address register. Equivalent to r 
1117   //       unless generating MIPS16 code. 
1118   // 'y' : Equivalent to r; retained for 
1119   //       backwards compatibility. 
1120   // 'f' : Floating Point registers.      
1121   if (Constraint.size() == 1) {
1122     switch (Constraint[0]) {
1123       default : break;
1124       case 'd':     
1125       case 'y': 
1126       case 'f':
1127         return C_RegisterClass;
1128         break;
1129     }
1130   }
1131   return TargetLowering::getConstraintType(Constraint);
1132 }
1133
1134 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1135 /// return a list of registers that can be used to satisfy the constraint.
1136 /// This should only be used for C_RegisterClass constraints.
1137 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1138 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
1139 {
1140   if (Constraint.size() == 1) {
1141     switch (Constraint[0]) {
1142     case 'r':
1143       return std::make_pair(0U, Mips::CPURegsRegisterClass);
1144     case 'f':
1145       if (VT == MVT::f32)
1146         return std::make_pair(0U, Mips::FGR32RegisterClass);
1147       if (VT == MVT::f64)    
1148         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1149           return std::make_pair(0U, Mips::AFGR64RegisterClass);
1150     }
1151   }
1152   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1153 }
1154
1155 /// Given a register class constraint, like 'r', if this corresponds directly
1156 /// to an LLVM register class, return a register of 0 and the register class
1157 /// pointer.
1158 std::vector<unsigned> MipsTargetLowering::
1159 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1160                                   MVT VT) const
1161 {
1162   if (Constraint.size() != 1)
1163     return std::vector<unsigned>();
1164
1165   switch (Constraint[0]) {         
1166     default : break;
1167     case 'r':
1168     // GCC Mips Constraint Letters
1169     case 'd':     
1170     case 'y': 
1171       return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3, 
1172              Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1, 
1173              Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 
1174              Mips::T8, 0);
1175
1176     case 'f':
1177       if (VT == MVT::f32) {
1178         if (Subtarget->isSingleFloat())
1179           return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1180                  Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1181                  Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1182                  Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1183                  Mips::F30, Mips::F31, 0);
1184         else
1185           return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8, 
1186                  Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26, 
1187                  Mips::F28, Mips::F30, 0);
1188       }
1189
1190       if (VT == MVT::f64)    
1191         if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1192           return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4, 
1193                  Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13, 
1194                  Mips::D14, Mips::D15, 0);
1195   }
1196   return std::vector<unsigned>();
1197 }
1198
1199 bool
1200 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1201   // The Mips target isn't yet aware of offsets.
1202   return false;
1203 }