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