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