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