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