Give TargetLowering::getSetCCResultType() a parameter so that ISD::SETCC's
[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 "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Debug.h"
32 #include <queue>
33 #include <set>
34
35 using namespace llvm;
36
37 const char *MipsTargetLowering::
38 getTargetNodeName(unsigned Opcode) const 
39 {
40   switch (Opcode) 
41   {
42     case MipsISD::JmpLink : return "MipsISD::JmpLink";
43     case MipsISD::Hi      : return "MipsISD::Hi";
44     case MipsISD::Lo      : return "MipsISD::Lo";
45     case MipsISD::Ret     : return "MipsISD::Ret";
46     default               : return NULL;
47   }
48 }
49
50 MipsTargetLowering::
51 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM) 
52 {
53   // Mips does not have i1 type, so use i32 for
54   // setcc operations results (slt, sgt, ...). 
55   setSetCCResultContents(ZeroOrOneSetCCResult);
56
57   // JumpTable targets must use GOT when using PIC_
58   setUsesGlobalOffsetTable(true);
59
60   // Set up the register classes
61   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
62
63   // Custom
64   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
65   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
66   setOperationAction(ISD::RET, MVT::Other, Custom);
67   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
68
69   // Load extented operations for i1 types must be promoted 
70   setLoadXAction(ISD::EXTLOAD,  MVT::i1,  Promote);
71   setLoadXAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
72   setLoadXAction(ISD::SEXTLOAD, MVT::i1,  Promote);
73
74   // Mips does not have these NodeTypes below.
75   setOperationAction(ISD::BR_JT,     MVT::Other, Expand);
76   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
77   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
78   setOperationAction(ISD::SELECT_CC, MVT::i32,   Expand);
79   setOperationAction(ISD::SELECT,    MVT::i32,   Expand);
80   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
81
82   // Mips not supported intrinsics.
83   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
84   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
85   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
86   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
87   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
88
89   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
90   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
91   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
92   setOperationAction(ISD::ROTL , MVT::i32, Expand);
93   setOperationAction(ISD::ROTR , MVT::i32, Expand);
94   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
95
96   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
97   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
98   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
99
100   // We don't have line number support yet.
101   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
102   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
103   setOperationAction(ISD::LABEL, MVT::Other, Expand);
104
105   // Use the default for now
106   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
107   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
108
109   setStackPointerRegisterToSaveRestore(Mips::SP);
110   computeRegisterProperties();
111 }
112
113
114 MVT::ValueType
115 MipsTargetLowering::getSetCCResultType(const SDOperand &) const {
116   return MVT::i32;
117 }
118
119
120 SDOperand MipsTargetLowering::
121 LowerOperation(SDOperand Op, SelectionDAG &DAG) 
122 {
123   switch (Op.getOpcode()) 
124   {
125     case ISD::CALL:             return LowerCALL(Op, DAG);
126     case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
127     case ISD::RET:              return LowerRET(Op, DAG);
128     case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
129     case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
130     case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
131   }
132   return SDOperand();
133 }
134
135 //===----------------------------------------------------------------------===//
136 //  Lower helper functions
137 //===----------------------------------------------------------------------===//
138
139 // AddLiveIn - This helper function adds the specified physical register to the
140 // MachineFunction as a live in value.  It also creates a corresponding
141 // virtual register for it.
142 static unsigned
143 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC) 
144 {
145   assert(RC->contains(PReg) && "Not the correct regclass!");
146   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
147   MF.getRegInfo().addLiveIn(PReg, VReg);
148   return VReg;
149 }
150
151 //===----------------------------------------------------------------------===//
152 //  Misc Lower Operation implementation
153 //===----------------------------------------------------------------------===//
154 SDOperand MipsTargetLowering::
155 LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) 
156 {
157   SDOperand ResNode;
158   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
159   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
160   bool isPIC = (getTargetMachine().getRelocationModel() == Reloc::PIC_);
161
162   SDOperand HiPart; 
163   if (!isPIC) {
164     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::i32);
165     SDOperand Ops[] = { GA };
166     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
167   } else // Emit Load from Global Pointer
168     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
169
170   // On functions and global targets not internal linked only
171   // a load from got/GP is necessary for PIC to work.
172   if ((isPIC) && ((!GV->hasInternalLinkage()) || (isa<Function>(GV))))
173     return HiPart;
174
175   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
176   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
177
178   return ResNode;
179 }
180
181 SDOperand MipsTargetLowering::
182 LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG)
183 {
184   assert(0 && "TLS not implemented for MIPS.");
185 }
186
187 SDOperand MipsTargetLowering::
188 LowerJumpTable(SDOperand Op, SelectionDAG &DAG) 
189 {
190   SDOperand ResNode;
191   SDOperand HiPart; 
192
193   MVT::ValueType PtrVT = Op.getValueType();
194   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
195   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
196
197   if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
198     const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::i32);
199     SDOperand Ops[] = { JTI };
200     HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
201   } else // Emit Load from Global Pointer
202     HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
203
204   SDOperand Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
205   ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
206
207   return ResNode;
208 }
209
210 //===----------------------------------------------------------------------===//
211 //                      Calling Convention Implementation
212 //
213 //  The lower operations present on calling convention works on this order:
214 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
215 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
216 //      LowerRET (virt regs --> phys regs)
217 //      LowerCALL (phys regs --> virt regs)
218 //
219 //===----------------------------------------------------------------------===//
220
221 #include "MipsGenCallingConv.inc"
222
223 //===----------------------------------------------------------------------===//
224 //                  CALL Calling Convention Implementation
225 //===----------------------------------------------------------------------===//
226
227 /// Mips custom CALL implementation
228 SDOperand MipsTargetLowering::
229 LowerCALL(SDOperand Op, SelectionDAG &DAG)
230 {
231   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
232
233   // By now, only CallingConv::C implemented
234   switch (CallingConv) 
235   {
236     default:
237       assert(0 && "Unsupported calling convention");
238     case CallingConv::Fast:
239     case CallingConv::C:
240       return LowerCCCCallTo(Op, DAG, CallingConv);
241   }
242 }
243
244 /// LowerCCCCallTo - functions arguments are copied from virtual
245 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
246 /// CALLSEQ_END are emitted.
247 /// TODO: isVarArg, isTailCall, sret.
248 SDOperand MipsTargetLowering::
249 LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG, unsigned CC) 
250 {
251   MachineFunction &MF = DAG.getMachineFunction();
252   unsigned StackReg   = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
253
254   SDOperand Chain  = Op.getOperand(0);
255   SDOperand Callee = Op.getOperand(4);
256   bool isVarArg    = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
257
258   MachineFrameInfo *MFI = MF.getFrameInfo();
259
260   // Analyze operands of the call, assigning locations to each operand.
261   SmallVector<CCValAssign, 16> ArgLocs;
262   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
263
264   // To meet ABI, Mips must always allocate 16 bytes on
265   // the stack (even if less than 4 are used as arguments)
266   int VTsize = MVT::getSizeInBits(MVT::i32)/8;
267   MFI->CreateFixedObject(VTsize, (VTsize*3));
268
269   CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
270   
271   // Get a count of how many bytes are to be pushed on the stack.
272   unsigned NumBytes = CCInfo.getNextStackOffset();
273   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
274                                  getPointerTy()));
275
276   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
277   SmallVector<SDOperand, 8> MemOpChains;
278
279   SDOperand StackPtr;
280   int LastStackLoc=0;
281
282   // Walk the register/memloc assignments, inserting copies/loads.
283   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
284     CCValAssign &VA = ArgLocs[i];
285
286     // Arguments start after the 5 first operands of ISD::CALL
287     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
288     
289     // Promote the value if needed.
290     switch (VA.getLocInfo()) {
291       default: assert(0 && "Unknown loc info!");
292       case CCValAssign::Full: break;
293       case CCValAssign::SExt:
294         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
295         break;
296       case CCValAssign::ZExt:
297         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
298         break;
299       case CCValAssign::AExt:
300         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
301         break;
302     }
303     
304     // Arguments that can be passed on register must be kept at 
305     // RegsToPass vector
306     if (VA.isRegLoc()) {
307       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
308     } else {
309
310       assert(VA.isMemLoc());
311
312       if (StackPtr.Val == 0)
313         StackPtr = DAG.getRegister(StackReg, getPointerTy());
314      
315       // Create the frame index object for this incoming parameter
316       // This guarantees that when allocating Local Area the firsts
317       // 16 bytes which are alwayes reserved won't be overwritten.
318       LastStackLoc = (16 + VA.getLocMemOffset());
319       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
320                                       LastStackLoc);
321
322       SDOperand PtrOff = DAG.getFrameIndex(FI,getPointerTy());
323
324       // emit ISD::STORE whichs stores the 
325       // parameter value to a stack Location
326       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
327     }
328   }
329
330   // Transform all store nodes into one single node because
331   // all store nodes are independent of each other.
332   if (!MemOpChains.empty())     
333     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
334                         &MemOpChains[0], MemOpChains.size());
335
336   // Build a sequence of copy-to-reg nodes chained together with token 
337   // chain and flag operands which copy the outgoing args into registers.
338   // The InFlag in necessary since all emited instructions must be
339   // stuck together.
340   SDOperand InFlag;
341   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
342     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
343                              RegsToPass[i].second, InFlag);
344     InFlag = Chain.getValue(1);
345   }
346
347   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
348   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 
349   // node so that legalize doesn't hack it. 
350   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 
351     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
352   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
353     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
354
355
356   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
357   //             = Chain, Callee, Reg#1, Reg#2, ...  
358   //
359   // Returns a chain & a flag for retval copy to use.
360   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
361   SmallVector<SDOperand, 8> Ops;
362   Ops.push_back(Chain);
363   Ops.push_back(Callee);
364
365   // Add argument registers to the end of the list so that they are 
366   // known live into the call.
367   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
368     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
369                                   RegsToPass[i].second.getValueType()));
370
371   if (InFlag.Val)
372     Ops.push_back(InFlag);
373
374   Chain  = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
375   InFlag = Chain.getValue(1);
376
377   // Create a stack location to hold GP when PIC is used. This stack 
378   // location is used on function prologue to save GP and also after all 
379   // emited CALL's to restore GP. 
380   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
381       // Function can have an arbitrary number of calls, so 
382       // hold the LastStackLoc with the biggest offset.
383       int FI;
384       MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
385       if (LastStackLoc >= MipsFI->getGPStackOffset()) {
386         LastStackLoc = (!LastStackLoc) ? (16) : (LastStackLoc+4);
387         // Create the frame index only once. SPOffset here can be anything 
388         // (this will be fixed on processFunctionBeforeFrameFinalized)
389         if (MipsFI->getGPStackOffset() == -1) {
390           FI = MFI->CreateFixedObject(4, 0);
391           MipsFI->setGPFI(FI);
392         }
393         MipsFI->setGPStackOffset(LastStackLoc);
394       }
395
396       // Reload GP value.
397       FI = MipsFI->getGPFI();
398       SDOperand FIN = DAG.getFrameIndex(FI,getPointerTy());
399       SDOperand GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
400       Chain = GPLoad.getValue(1);
401       Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32), 
402                                GPLoad, SDOperand(0,0));
403   }      
404
405   // Create the CALLSEQ_END node.
406   Chain = DAG.getCALLSEQ_END(Chain,
407                              DAG.getConstant(NumBytes, getPointerTy()),
408                              DAG.getConstant(0, getPointerTy()),
409                              InFlag);
410   InFlag = Chain.getValue(1);
411
412   // Handle result values, copying them out of physregs into vregs that we
413   // return.
414   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
415 }
416
417 /// LowerCallResult - Lower the result values of an ISD::CALL into the
418 /// appropriate copies out of appropriate physical registers.  This assumes that
419 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
420 /// being lowered. Returns a SDNode with the same number of values as the 
421 /// ISD::CALL.
422 SDNode *MipsTargetLowering::
423 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
424         unsigned CallingConv, SelectionDAG &DAG) {
425   
426   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
427
428   // Assign locations to each value returned by this call.
429   SmallVector<CCValAssign, 16> RVLocs;
430   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
431
432   CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
433   SmallVector<SDOperand, 8> ResultVals;
434
435   // Copy all of the result registers out of their specified physreg.
436   for (unsigned i = 0; i != RVLocs.size(); ++i) {
437     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
438                                  RVLocs[i].getValVT(), InFlag).getValue(1);
439     InFlag = Chain.getValue(2);
440     ResultVals.push_back(Chain.getValue(0));
441   }
442   
443   ResultVals.push_back(Chain);
444
445   // Merge everything together with a MERGE_VALUES node.
446   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
447                      &ResultVals[0], ResultVals.size()).Val;                       
448 }
449
450 //===----------------------------------------------------------------------===//
451 //             FORMAL_ARGUMENTS Calling Convention Implementation
452 //===----------------------------------------------------------------------===//
453
454 /// Mips custom FORMAL_ARGUMENTS implementation
455 SDOperand MipsTargetLowering::
456 LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) 
457 {
458   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
459   switch(CC) 
460   {
461     default:
462       assert(0 && "Unsupported calling convention");
463     case CallingConv::C:
464       return LowerCCCArguments(Op, DAG);
465   }
466 }
467
468 /// LowerCCCArguments - transform physical registers into
469 /// virtual registers and generate load operations for
470 /// arguments places on the stack.
471 /// TODO: isVarArg, sret
472 SDOperand MipsTargetLowering::
473 LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) 
474 {
475   SDOperand Root        = Op.getOperand(0);
476   MachineFunction &MF   = DAG.getMachineFunction();
477   MachineFrameInfo *MFI = MF.getFrameInfo();
478   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
479
480   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
481   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
482
483   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
484
485   // GP holds the GOT address on PIC calls.
486   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
487     AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
488
489   // Assign locations to all of the incoming arguments.
490   SmallVector<CCValAssign, 16> ArgLocs;
491   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
492
493   CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
494   SmallVector<SDOperand, 8> ArgValues;
495   SDOperand StackPtr;
496
497   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
498
499     CCValAssign &VA = ArgLocs[i];
500
501     // Arguments stored on registers
502     if (VA.isRegLoc()) {
503       MVT::ValueType RegVT = VA.getLocVT();
504       TargetRegisterClass *RC;
505             
506       if (RegVT == MVT::i32)
507         RC = Mips::CPURegsRegisterClass;
508       else
509         assert(0 && "support only Mips::CPURegsRegisterClass");
510
511       // Transform the arguments stored on 
512       // physical registers into virtual ones
513       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
514       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
515       
516       // If this is an 8 or 16-bit value, it is really passed promoted 
517       // to 32 bits.  Insert an assert[sz]ext to capture this, then 
518       // truncate to the right size.
519       if (VA.getLocInfo() == CCValAssign::SExt)
520         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
521                                DAG.getValueType(VA.getValVT()));
522       else if (VA.getLocInfo() == CCValAssign::ZExt)
523         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
524                                DAG.getValueType(VA.getValVT()));
525       
526       if (VA.getLocInfo() != CCValAssign::Full)
527         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
528
529       ArgValues.push_back(ArgValue);
530
531       // To meet ABI, when VARARGS are passed on registers, the registers
532       // must have their values written to the caller stack frame. 
533       if (isVarArg) {
534
535         if (StackPtr.Val == 0)
536           StackPtr = DAG.getRegister(StackReg, getPointerTy());
537      
538         // The stack pointer offset is relative to the caller stack frame. 
539         // Since the real stack size is unknown here, a negative SPOffset 
540         // is used so there's a way to adjust these offsets when the stack
541         // size get known (on EliminateFrameIndex). A dummy SPOffset is 
542         // used instead of a direct negative address (which is recorded to
543         // be used on emitPrologue) to avoid mis-calc of the first stack 
544         // offset on PEI::calculateFrameObjectOffsets.
545         // Arguments are always 32-bit.
546         int FI = MFI->CreateFixedObject(4, 0);
547         MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
548         SDOperand PtrOff = DAG.getFrameIndex(FI, getPointerTy());
549       
550         // emit ISD::STORE whichs stores the 
551         // parameter value to a stack Location
552         ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
553       }
554
555     } else {
556       // sanity check
557       assert(VA.isMemLoc());
558       
559       // The stack pointer offset is relative to the caller stack frame. 
560       // Since the real stack size is unknown here, a negative SPOffset 
561       // is used so there's a way to adjust these offsets when the stack
562       // size get known (on EliminateFrameIndex). A dummy SPOffset is 
563       // used instead of a direct negative address (which is recorded to
564       // be used on emitPrologue) to avoid mis-calc of the first stack 
565       // offset on PEI::calculateFrameObjectOffsets.
566       // Arguments are always 32-bit.
567       int FI = MFI->CreateFixedObject(4, 0);
568       MipsFI->recordLoadArgsFI(FI, -(4+(16+VA.getLocMemOffset())));
569
570       // Create load nodes to retrieve arguments from the stack
571       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
572       ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
573     }
574   }
575   ArgValues.push_back(Root);
576
577   // Return the new list of results.
578   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
579                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
580 }
581
582 //===----------------------------------------------------------------------===//
583 //               Return Value Calling Convention Implementation
584 //===----------------------------------------------------------------------===//
585
586 SDOperand MipsTargetLowering::
587 LowerRET(SDOperand Op, SelectionDAG &DAG)
588 {
589   // CCValAssign - represent the assignment of
590   // the return value to a location
591   SmallVector<CCValAssign, 16> RVLocs;
592   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
593   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
594
595   // CCState - Info about the registers and stack slot.
596   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
597
598   // Analize return values of ISD::RET
599   CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
600
601   // If this is the first return lowered for this function, add 
602   // the regs to the liveout set for the function.
603   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
604     for (unsigned i = 0; i != RVLocs.size(); ++i)
605       if (RVLocs[i].isRegLoc())
606         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
607   }
608
609   // The chain is always operand #0
610   SDOperand Chain = Op.getOperand(0);
611   SDOperand Flag;
612
613   // Copy the result values into the output registers.
614   for (unsigned i = 0; i != RVLocs.size(); ++i) {
615     CCValAssign &VA = RVLocs[i];
616     assert(VA.isRegLoc() && "Can only return in registers!");
617
618     // ISD::RET => ret chain, (regnum1,val1), ...
619     // So i*2+1 index only the regnums
620     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
621
622     // guarantee that all emitted copies are
623     // stuck together, avoiding something bad
624     Flag = Chain.getValue(1);
625   }
626
627   // Return on Mips is always a "jr $ra"
628   if (Flag.Val)
629     return DAG.getNode(MipsISD::Ret, MVT::Other, 
630                        Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
631   else // Return Void
632     return DAG.getNode(MipsISD::Ret, MVT::Other, 
633                        Chain, DAG.getRegister(Mips::RA, MVT::i32));
634 }
635
636 //===----------------------------------------------------------------------===//
637 //                           Mips Inline Assembly Support
638 //===----------------------------------------------------------------------===//
639
640 /// getConstraintType - Given a constraint letter, return the type of
641 /// constraint it is for this target.
642 MipsTargetLowering::ConstraintType MipsTargetLowering::
643 getConstraintType(const std::string &Constraint) const 
644 {
645   if (Constraint.size() == 1) {
646     // Mips specific constrainy 
647     // GCC config/mips/constraints.md
648     //
649     // 'd' : An address register. Equivalent to r 
650     //       unless generating MIPS16 code. 
651     // 'y' : Equivalent to r; retained for 
652     //       backwards compatibility. 
653     //
654     switch (Constraint[0]) {
655       default : break;
656       case 'd':     
657       case 'y': 
658         return C_RegisterClass;
659         break;
660     }
661   }
662   return TargetLowering::getConstraintType(Constraint);
663 }
664
665 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
666 getRegForInlineAsmConstraint(const std::string &Constraint,
667                              MVT::ValueType VT) const 
668 {
669   if (Constraint.size() == 1) {
670     switch (Constraint[0]) {
671     case 'r':
672       return std::make_pair(0U, Mips::CPURegsRegisterClass);
673       break;
674     }
675   }
676   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
677 }
678
679 std::vector<unsigned> MipsTargetLowering::
680 getRegClassForInlineAsmConstraint(const std::string &Constraint,
681                                   MVT::ValueType VT) const 
682 {
683   if (Constraint.size() != 1)
684     return std::vector<unsigned>();
685
686   switch (Constraint[0]) {         
687     default : break;
688     case 'r':
689     // GCC Mips Constraint Letters
690     case 'd':     
691     case 'y': 
692       return make_vector<unsigned>(Mips::V0, Mips::V1, Mips::A0, 
693                                    Mips::A1, Mips::A2, Mips::A3, 
694                                    Mips::T0, Mips::T1, Mips::T2, 
695                                    Mips::T3, Mips::T4, Mips::T5, 
696                                    Mips::T6, Mips::T7, Mips::S0, 
697                                    Mips::S1, Mips::S2, Mips::S3, 
698                                    Mips::S4, Mips::S5, Mips::S6, 
699                                    Mips::S7, Mips::T8, Mips::T9, 0);
700       break;
701   }
702   return std::vector<unsigned>();
703 }