Adding the MicroBlaze backend.
[oota-llvm.git] / lib / Target / MBlaze / MBlazeISelLowering.cpp
1 //===-- MBlazeISelLowering.cpp - MBlaze 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 MBlaze uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mblaze-lower"
16 #include "MBlazeISelLowering.h"
17 #include "MBlazeMachineFunction.h"
18 #include "MBlazeTargetMachine.h"
19 #include "MBlazeTargetObjectFile.h"
20 #include "MBlazeSubtarget.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 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37
38 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
39   switch (Opcode) {
40     case MBlazeISD::JmpLink    : return "MBlazeISD::JmpLink";
41     case MBlazeISD::GPRel      : return "MBlazeISD::GPRel";
42     case MBlazeISD::Wrap       : return "MBlazeISD::Wrap";
43     case MBlazeISD::ICmp       : return "MBlazeISD::ICmp";
44     case MBlazeISD::Ret        : return "MBlazeISD::Ret";
45     case MBlazeISD::Select_CC  : return "MBlazeISD::Select_CC";
46     default                    : return NULL;
47   }
48 }
49
50 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
51   : TargetLowering(TM, new MBlazeTargetObjectFile()) {
52   Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
53
54   // MBlaze does not have i1 type, so use i32 for
55   // setcc operations results (slt, sgt, ...).
56   setBooleanContents(ZeroOrOneBooleanContent);
57
58   // Set up the register classes
59   addRegisterClass(MVT::i32, MBlaze::CPURegsRegisterClass);
60   if (Subtarget->hasFPU()) {
61     addRegisterClass(MVT::f32, MBlaze::FGR32RegisterClass);
62     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
63   }
64
65   // Floating point operations which are not supported
66   setOperationAction(ISD::FREM,       MVT::f32, Expand);
67   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Expand);
68   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
69   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
70   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
71   setOperationAction(ISD::FP_ROUND,   MVT::f32, Expand);
72   setOperationAction(ISD::FP_ROUND,   MVT::f64, Expand);
73   setOperationAction(ISD::FCOPYSIGN,  MVT::f32, Expand);
74   setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
75   setOperationAction(ISD::FSIN,       MVT::f32, Expand);
76   setOperationAction(ISD::FCOS,       MVT::f32, Expand);
77   setOperationAction(ISD::FPOWI,      MVT::f32, Expand);
78   setOperationAction(ISD::FPOW,       MVT::f32, Expand);
79   setOperationAction(ISD::FLOG,       MVT::f32, Expand);
80   setOperationAction(ISD::FLOG2,      MVT::f32, Expand);
81   setOperationAction(ISD::FLOG10,     MVT::f32, Expand);
82   setOperationAction(ISD::FEXP,       MVT::f32, Expand);
83
84   // Load extented operations for i1 types must be promoted
85   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
86   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
87   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
88
89   // MBlaze has no REM or DIVREM operations.
90   setOperationAction(ISD::UREM,    MVT::i32, Expand);
91   setOperationAction(ISD::SREM,    MVT::i32, Expand);
92   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
93   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
94
95   // If the processor doesn't support multiply then expand it
96   if (!Subtarget->hasMul()) {
97     setOperationAction(ISD::MUL, MVT::i32, Expand);
98   }
99
100   // If the processor doesn't support 64-bit multiply then expand
101   if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
102     setOperationAction(ISD::MULHS, MVT::i32, Expand);
103     setOperationAction(ISD::MULHS, MVT::i64, Expand);
104     setOperationAction(ISD::MULHU, MVT::i32, Expand);
105     setOperationAction(ISD::MULHU, MVT::i64, Expand);
106   }
107
108   // If the processor doesn't support division then expand
109   if (!Subtarget->hasDiv()) {
110     setOperationAction(ISD::UDIV, MVT::i32, Expand);
111     setOperationAction(ISD::SDIV, MVT::i32, Expand);
112   }
113
114   // Expand unsupported conversions
115   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
116   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
117
118   // Expand SELECT_CC
119   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
120
121   // MBlaze doesn't have MUL_LOHI
122   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
123   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
124   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
125   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
126
127   // Used by legalize types to correctly generate the setcc result.
128   // Without this, every float setcc comes with a AND/OR with the result,
129   // we don't want this, since the fpcmp result goes to a flag register,
130   // which is used implicitly by brcond and select operations.
131   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
132   AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
133   AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
134
135   // MBlaze Custom Operations
136   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
137   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
138   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
139   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
140
141   // Operations not directly supported by MBlaze.
142   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
143   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
144   setOperationAction(ISD::BR_CC,              MVT::Other, Expand);
145   setOperationAction(ISD::SIGN_EXTEND_INREG,  MVT::i1,    Expand);
146   setOperationAction(ISD::ROTL,               MVT::i32,   Expand);
147   setOperationAction(ISD::ROTR,               MVT::i32,   Expand);
148   setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Expand);
149   setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Expand);
150   setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Expand);
151   setOperationAction(ISD::CTLZ,               MVT::i32,   Expand);
152   setOperationAction(ISD::CTTZ,               MVT::i32,   Expand);
153   setOperationAction(ISD::CTPOP,              MVT::i32,   Expand);
154   setOperationAction(ISD::BSWAP,              MVT::i32,   Expand);
155
156   // We don't have line number support yet.
157   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
158
159   // Use the default for now
160   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
161   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
162   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
163
164   // MBlaze doesn't have extending float->double load/store
165   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
166   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
167
168   setStackPointerRegisterToSaveRestore(MBlaze::R1);
169   computeRegisterProperties();
170 }
171
172 MVT::SimpleValueType MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
173   return MVT::i32;
174 }
175
176 /// getFunctionAlignment - Return the Log2 alignment of this function.
177 unsigned MBlazeTargetLowering::getFunctionAlignment(const Function *) const {
178   return 2;
179 }
180
181 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
182   switch (Op.getOpcode())
183   {
184     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
185     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
186     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
187     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
188     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
189   }
190   return SDValue();
191 }
192
193 //===----------------------------------------------------------------------===//
194 //  Lower helper functions
195 //===----------------------------------------------------------------------===//
196 MachineBasicBlock* MBlazeTargetLowering::
197 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *BB,
198                             DenseMap<MachineBasicBlock*,
199                             MachineBasicBlock*> *EM) const {
200   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
201   DebugLoc dl = MI->getDebugLoc();
202
203   switch (MI->getOpcode()) {
204   default: assert(false && "Unexpected instr type to insert");
205   case MBlaze::ShiftRL:
206   case MBlaze::ShiftRA:
207   case MBlaze::ShiftL: {
208     // To "insert" a shift left instruction, we actually have to insert a
209     // simple loop.  The incoming instruction knows the destination vreg to
210     // set, the source vreg to operate over and the shift amount.
211     const BasicBlock *LLVM_BB = BB->getBasicBlock();
212     MachineFunction::iterator It = BB;
213     ++It;
214
215     // start:
216     //   andi     samt, samt, 31
217     //   beqid    samt, finish
218     //   add      dst, src, r0
219     // loop:
220     //   addik    samt, samt, -1
221     //   sra      dst, dst
222     //   bneid    samt, loop
223     //   nop
224     // finish:
225     MachineFunction *F = BB->getParent();
226     MachineRegisterInfo &R = F->getRegInfo();
227     MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
228     MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
229
230     unsigned IAMT = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
231     BuildMI(BB, dl, TII->get(MBlaze::ANDI), IAMT)
232       .addReg(MI->getOperand(2).getReg())
233       .addImm(31);
234
235     unsigned IVAL = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
236     BuildMI(BB, dl, TII->get(MBlaze::ADDI), IVAL)
237       .addReg(MI->getOperand(1).getReg())
238       .addImm(0);
239
240     BuildMI(BB, dl, TII->get(MBlaze::BEQID))
241       .addReg(IAMT)
242       .addMBB(finish);
243
244     F->insert(It, loop);
245     F->insert(It, finish);
246
247     // Update machine-CFG edges by first adding all successors of the current
248     // block to the new block which will contain the Phi node for the select.
249     // Also inform sdisel of the edge changes.
250     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
251           e = BB->succ_end(); i != e; ++i) {
252       EM->insert(std::make_pair(*i, finish));
253       finish->addSuccessor(*i);
254     }
255
256     // Next, remove all successors of the current block, and add the true
257     // and fallthrough blocks as its successors.
258     while(!BB->succ_empty())
259       BB->removeSuccessor(BB->succ_begin());
260     BB->addSuccessor(loop);
261     BB->addSuccessor(finish);
262
263     // Next, add the finish block as a successor of the loop block
264     loop->addSuccessor(finish);
265     loop->addSuccessor(loop);
266
267     unsigned DST = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
268     unsigned NDST = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
269     BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
270       .addReg(IVAL).addMBB(BB)
271       .addReg(NDST).addMBB(loop);
272
273     unsigned SAMT = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
274     unsigned NAMT = R.createVirtualRegister(MBlaze::CPURegsRegisterClass);
275     BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
276       .addReg(IAMT).addMBB(BB)
277       .addReg(NAMT).addMBB(loop);
278
279     if (MI->getOpcode() == MBlaze::ShiftL)
280       BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
281     else if (MI->getOpcode() == MBlaze::ShiftRA)
282       BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
283     else if (MI->getOpcode() == MBlaze::ShiftRL)
284       BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
285     else
286         llvm_unreachable( "Cannot lower unknown shift instruction" );
287
288     BuildMI(loop, dl, TII->get(MBlaze::ADDI), NAMT)
289       .addReg(SAMT)
290       .addImm(-1);
291
292     BuildMI(loop, dl, TII->get(MBlaze::BNEID))
293       .addReg(NAMT)
294       .addMBB(loop);
295
296     BuildMI(finish, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
297       .addReg(IVAL).addMBB(BB)
298       .addReg(NDST).addMBB(loop);
299
300     // The pseudo instruction is no longer needed so remove it
301     F->DeleteMachineInstr(MI);
302     return finish;
303     }
304
305   case MBlaze::Select_FCC:
306   case MBlaze::Select_CC: {
307     // To "insert" a SELECT_CC instruction, we actually have to insert the
308     // diamond control-flow pattern.  The incoming instruction knows the
309     // destination vreg to set, the condition code register to branch on, the
310     // true/false values to select between, and a branch opcode to use.
311     const BasicBlock *LLVM_BB = BB->getBasicBlock();
312     MachineFunction::iterator It = BB;
313     ++It;
314
315     //  thisMBB:
316     //  ...
317     //   TrueVal = ...
318     //   setcc r1, r2, r3
319     //   bNE   r1, r0, copy1MBB
320     //   fallthrough --> copy0MBB
321     MachineFunction *F = BB->getParent();
322     MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
323     MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
324
325     unsigned Opc;
326     switch (MI->getOperand(4).getImm()) {
327     default: llvm_unreachable( "Unknown branch condition" );
328     case MBlazeCC::EQ: Opc = MBlaze::BNEID; break;
329     case MBlazeCC::NE: Opc = MBlaze::BEQID; break;
330     case MBlazeCC::GT: Opc = MBlaze::BLEID; break;
331     case MBlazeCC::LT: Opc = MBlaze::BGEID; break;
332     case MBlazeCC::GE: Opc = MBlaze::BLTID; break;
333     case MBlazeCC::LE: Opc = MBlaze::BGTID; break;
334     }
335
336     BuildMI(BB, dl, TII->get(Opc))
337       .addReg(MI->getOperand(3).getReg())
338       .addMBB(dneBB);
339
340     F->insert(It, flsBB);
341     F->insert(It, dneBB);
342
343     // Update machine-CFG edges by first adding all successors of the current
344     // block to the new block which will contain the Phi node for the select.
345     // Also inform sdisel of the edge changes.
346     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
347           e = BB->succ_end(); i != e; ++i) {
348       EM->insert(std::make_pair(*i, dneBB));
349       dneBB->addSuccessor(*i);
350     }
351
352     // Next, remove all successors of the current block, and add the true
353     // and fallthrough blocks as its successors.
354     while(!BB->succ_empty())
355       BB->removeSuccessor(BB->succ_begin());
356     BB->addSuccessor(flsBB);
357     BB->addSuccessor(dneBB);
358     flsBB->addSuccessor(dneBB);
359
360     //  sinkMBB:
361     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
362     //  ...
363     //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
364     //  .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
365     //  .addReg(MI->getOperand(2).getReg()).addMBB(BB);
366
367     BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
368       .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
369       .addReg(MI->getOperand(1).getReg()).addMBB(BB);
370
371     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
372     return dneBB;
373   }
374   }
375 }
376
377 //===----------------------------------------------------------------------===//
378 //  Misc Lower Operation implementation
379 //===----------------------------------------------------------------------===//
380 //
381
382 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
383   SDValue LHS = Op.getOperand(0);
384   SDValue RHS = Op.getOperand(1);
385   SDValue TrueVal = Op.getOperand(2);
386   SDValue FalseVal = Op.getOperand(3);
387   DebugLoc dl = Op.getDebugLoc();
388   unsigned Opc;
389
390   SDValue CompareFlag;
391   if (LHS.getValueType() == MVT::i32) {
392     Opc = MBlazeISD::Select_CC;
393     CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
394                     .getValue(1);
395   } else {
396     llvm_unreachable( "Cannot lower select_cc with unknown type" );
397   }
398  
399   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
400                      CompareFlag);
401 }
402
403 SDValue MBlazeTargetLowering::
404 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
405   // FIXME there isn't actually debug info here
406   DebugLoc dl = Op.getDebugLoc();
407   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
408   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
409
410   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
411 }
412
413 SDValue MBlazeTargetLowering::
414 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
415   llvm_unreachable("TLS not implemented for MicroBlaze.");
416   return SDValue(); // Not reached
417 }
418
419 SDValue MBlazeTargetLowering::
420 LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
421   SDValue ResNode;
422   SDValue HiPart;
423   // FIXME there isn't actually debug info here
424   DebugLoc dl = Op.getDebugLoc();
425   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
426   unsigned char OpFlag = IsPIC ? MBlazeII::MO_GOT : MBlazeII::MO_ABS_HILO;
427
428   EVT PtrVT = Op.getValueType();
429   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
430
431   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
432   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
433   //return JTI;
434 }
435
436 SDValue MBlazeTargetLowering::
437 LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
438   SDValue ResNode;
439   EVT PtrVT = Op.getValueType();
440   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
441   Constant *C = N->getConstVal();
442   SDValue Zero = DAG.getConstant(0, PtrVT);
443   // FIXME there isn't actually debug info here
444   DebugLoc dl = Op.getDebugLoc();
445
446   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
447                                          N->getOffset(), MBlazeII::MO_ABS_HILO);
448   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
449 }
450
451 //===----------------------------------------------------------------------===//
452 //                      Calling Convention Implementation
453 //===----------------------------------------------------------------------===//
454
455 #include "MBlazeGenCallingConv.inc"
456
457 //===----------------------------------------------------------------------===//
458 //                  Call Calling Convention Implementation
459 //===----------------------------------------------------------------------===//
460
461 /// LowerCall - functions arguments are copied from virtual regs to
462 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
463 /// TODO: isVarArg, isTailCall.
464 SDValue MBlazeTargetLowering::
465 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
466           bool isVarArg, bool &isTailCall,
467           const SmallVectorImpl<ISD::OutputArg> &Outs,
468           const SmallVectorImpl<ISD::InputArg> &Ins,
469           DebugLoc dl, SelectionDAG &DAG,
470           SmallVectorImpl<SDValue> &InVals) {
471   MachineFunction &MF = DAG.getMachineFunction();
472   MachineFrameInfo *MFI = MF.getFrameInfo();
473   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
474
475   // Analyze operands of the call, assigning locations to each operand.
476   SmallVector<CCValAssign, 16> ArgLocs;
477   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
478                  *DAG.getContext());
479   CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
480
481   // Get a count of how many bytes are to be pushed on the stack.
482   unsigned NumBytes = CCInfo.getNextStackOffset();
483   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
484
485   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
486   SmallVector<SDValue, 8> MemOpChains;
487
488   // First/LastArgStackLoc contains the first/last
489   // "at stack" argument location.
490   int LastArgStackLoc = 0;
491   unsigned FirstStackArgLoc = 4;
492
493   // Walk the register/memloc assignments, inserting copies/loads.
494   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
495     CCValAssign &VA = ArgLocs[i];
496     EVT RegVT = VA.getLocVT();
497     SDValue Arg = Outs[i].Val;
498
499     // Promote the value if needed.
500     switch (VA.getLocInfo()) {
501     default: llvm_unreachable("Unknown loc info!");
502     case CCValAssign::Full: break;
503     case CCValAssign::SExt:
504       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
505       break;
506     case CCValAssign::ZExt:
507       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
508       break;
509     case CCValAssign::AExt:
510       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
511       break;
512     case CCValAssign::BCvt:
513       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
514       break;
515     }
516
517     // Arguments that can be passed on register must be kept at
518     // RegsToPass vector
519     if (VA.isRegLoc()) {
520       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
521     } else {
522       // Register can't get to this point...
523       assert(VA.isMemLoc());
524
525       // Create the frame index object for this incoming parameter
526       LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
527       int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
528                                       LastArgStackLoc, true, false);
529
530       SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
531
532       // emit ISD::STORE whichs stores the
533       // parameter value to a stack Location
534       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0,
535                                          false, false, 0));
536     }
537   }
538
539   // Transform all store nodes into one single node because all store
540   // nodes are independent of each other.
541   if (!MemOpChains.empty())
542     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
543                         &MemOpChains[0], MemOpChains.size());
544
545   // Build a sequence of copy-to-reg nodes chained together with token
546   // chain and flag operands which copy the outgoing args into registers.
547   // The InFlag in necessary since all emited instructions must be
548   // stuck together.
549   SDValue InFlag;
550   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
551     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
552                              RegsToPass[i].second, InFlag);
553     InFlag = Chain.getValue(1);
554   }
555
556   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
557   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
558   // node so that legalize doesn't hack it.
559   unsigned char OpFlag = IsPIC ? MBlazeII::MO_GOT_CALL : MBlazeII::MO_NO_FLAG;
560   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
561     Callee = DAG.getTargetGlobalAddress(G->getGlobal(),
562                                 getPointerTy(), 0, OpFlag);
563   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
564     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
565                                 getPointerTy(), OpFlag);
566
567   // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
568   //             = Chain, Callee, Reg#1, Reg#2, ...
569   //
570   // Returns a chain & a flag for retval copy to use.
571   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
572   SmallVector<SDValue, 8> Ops;
573   Ops.push_back(Chain);
574   Ops.push_back(Callee);
575
576   // Add argument registers to the end of the list so that they are
577   // known live into the call.
578   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
579     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
580                                   RegsToPass[i].second.getValueType()));
581   }
582
583   if (InFlag.getNode())
584     Ops.push_back(InFlag);
585
586   Chain  = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
587   InFlag = Chain.getValue(1);
588
589   // Create the CALLSEQ_END node.
590   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
591                              DAG.getIntPtrConstant(0, true), InFlag);
592   if (!Ins.empty())
593     InFlag = Chain.getValue(1);
594
595   // Handle result values, copying them out of physregs into vregs that we
596   // return.
597   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
598                          Ins, dl, DAG, InVals);
599 }
600
601 /// LowerCallResult - Lower the result values of a call into the
602 /// appropriate copies out of appropriate physical registers.
603 SDValue MBlazeTargetLowering::
604 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
605                 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
606                 DebugLoc dl, SelectionDAG &DAG,
607                 SmallVectorImpl<SDValue> &InVals) {
608   // Assign locations to each value returned by this call.
609   SmallVector<CCValAssign, 16> RVLocs;
610   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
611                  RVLocs, *DAG.getContext());
612
613   CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
614
615   // Copy all of the result registers out of their specified physreg.
616   for (unsigned i = 0; i != RVLocs.size(); ++i) {
617     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
618                                RVLocs[i].getValVT(), InFlag).getValue(1);
619     InFlag = Chain.getValue(2);
620     InVals.push_back(Chain.getValue(0));
621   }
622
623   return Chain;
624 }
625
626 //===----------------------------------------------------------------------===//
627 //             Formal Arguments Calling Convention Implementation
628 //===----------------------------------------------------------------------===//
629
630 /// LowerFormalArguments - transform physical registers into
631 /// virtual registers and generate load operations for
632 /// arguments places on the stack.
633 /// TODO: isVarArg
634 SDValue MBlazeTargetLowering::
635 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
636                      const SmallVectorImpl<ISD::InputArg> &Ins,
637                      DebugLoc dl, SelectionDAG &DAG,
638                      SmallVectorImpl<SDValue> &InVals) {
639   MachineFunction &MF = DAG.getMachineFunction();
640   MachineFrameInfo *MFI = MF.getFrameInfo();
641   MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
642
643   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
644
645   // Assign locations to all of the incoming arguments.
646   SmallVector<CCValAssign, 16> ArgLocs;
647   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
648                  ArgLocs, *DAG.getContext());
649
650   CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
651   SDValue StackPtr;
652
653   unsigned FirstStackArgLoc = 4;
654
655   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
656     CCValAssign &VA = ArgLocs[i];
657
658     // Arguments stored on registers
659     if (VA.isRegLoc()) {
660       EVT RegVT = VA.getLocVT();
661       TargetRegisterClass *RC = 0;
662
663       if (RegVT == MVT::i32)
664         RC = MBlaze::CPURegsRegisterClass;
665       else if (RegVT == MVT::f32)
666         RC = MBlaze::FGR32RegisterClass;
667       else
668         llvm_unreachable("RegVT not supported by LowerFormalArguments");
669
670       // Transform the arguments stored on
671       // physical registers into virtual ones
672       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
673       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
674
675       // If this is an 8 or 16-bit value, it has been passed promoted
676       // to 32 bits.  Insert an assert[sz]ext to capture this, then
677       // truncate to the right size.
678       if (VA.getLocInfo() != CCValAssign::Full) {
679         unsigned Opcode = 0;
680         if (VA.getLocInfo() == CCValAssign::SExt)
681           Opcode = ISD::AssertSext;
682         else if (VA.getLocInfo() == CCValAssign::ZExt)
683           Opcode = ISD::AssertZext;
684         if (Opcode)
685           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
686                                  DAG.getValueType(VA.getValVT()));
687         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
688       }
689
690       InVals.push_back(ArgValue);
691
692       // To meet ABI, when VARARGS are passed on registers, the registers
693       // must have their values written to the caller stack frame.
694       if (isVarArg) {
695         if (StackPtr.getNode() == 0)
696           StackPtr = DAG.getRegister(StackReg, getPointerTy());
697
698         // The stack pointer offset is relative to the caller stack frame.
699         // Since the real stack size is unknown here, a negative SPOffset
700         // is used so there's a way to adjust these offsets when the stack
701         // size get known (on EliminateFrameIndex). A dummy SPOffset is
702         // used instead of a direct negative address (which is recorded to
703         // be used on emitPrologue) to avoid mis-calc of the first stack
704         // offset on PEI::calculateFrameObjectOffsets.
705         // Arguments are always 32-bit.
706         int FI = MFI->CreateFixedObject(4, 0, true, false);
707         MBlazeFI->recordStoreVarArgsFI(FI, -(FirstStackArgLoc+(i*4)));
708         SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
709
710         // emit ISD::STORE whichs stores the
711         // parameter value to a stack Location
712         InVals.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff, NULL, 0,
713                                       false, false, 0));
714       }
715
716     } else { // VA.isRegLoc()
717
718       // sanity check
719       assert(VA.isMemLoc());
720
721       // The stack pointer offset is relative to the caller stack frame.
722       // Since the real stack size is unknown here, a negative SPOffset
723       // is used so there's a way to adjust these offsets when the stack
724       // size get known (on EliminateFrameIndex). A dummy SPOffset is
725       // used instead of a direct negative address (which is recorded to
726       // be used on emitPrologue) to avoid mis-calc of the first stack
727       // offset on PEI::calculateFrameObjectOffsets.
728       // Arguments are always 32-bit.
729       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
730       int FI = MFI->CreateFixedObject(ArgSize, 0, true, false);
731       MBlazeFI->recordLoadArgsFI(FI, -(ArgSize+
732         (FirstStackArgLoc + VA.getLocMemOffset())));
733
734       // Create load nodes to retrieve arguments from the stack
735       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
736       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0,
737                                    false, false, 0));
738     }
739   }
740
741   return Chain;
742 }
743
744 //===----------------------------------------------------------------------===//
745 //               Return Value Calling Convention Implementation
746 //===----------------------------------------------------------------------===//
747
748 SDValue MBlazeTargetLowering::
749 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
750             const SmallVectorImpl<ISD::OutputArg> &Outs,
751             DebugLoc dl, SelectionDAG &DAG) {
752   // CCValAssign - represent the assignment of
753   // the return value to a location
754   SmallVector<CCValAssign, 16> RVLocs;
755
756   // CCState - Info about the registers and stack slot.
757   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
758                  RVLocs, *DAG.getContext());
759
760   // Analize return values.
761   CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
762
763   // If this is the first return lowered for this function, add
764   // the regs to the liveout set for the function.
765   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
766     for (unsigned i = 0; i != RVLocs.size(); ++i)
767       if (RVLocs[i].isRegLoc())
768         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
769   }
770
771   SDValue Flag;
772
773   // Copy the result values into the output registers.
774   for (unsigned i = 0; i != RVLocs.size(); ++i) {
775     CCValAssign &VA = RVLocs[i];
776     assert(VA.isRegLoc() && "Can only return in registers!");
777
778     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
779                              Outs[i].Val, Flag);
780
781     // guarantee that all emitted copies are
782     // stuck together, avoiding something bad
783     Flag = Chain.getValue(1);
784   }
785
786   // Return on MBlaze is always a "rtsd R15, 8"
787   if (Flag.getNode())
788     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
789                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32), Flag);
790   else // Return Void
791     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
792                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32));
793 }
794
795 //===----------------------------------------------------------------------===//
796 //                           MBlaze Inline Assembly Support
797 //===----------------------------------------------------------------------===//
798
799 /// getConstraintType - Given a constraint letter, return the type of
800 /// constraint it is for this target.
801 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
802 getConstraintType(const std::string &Constraint) const
803 {
804   // MBlaze specific constrainy
805   //
806   // 'd' : An address register. Equivalent to r.
807   // 'y' : Equivalent to r; retained for
808   //       backwards compatibility.
809   // 'f' : Floating Point registers.
810   if (Constraint.size() == 1) {
811     switch (Constraint[0]) {
812       default : break;
813       case 'd':
814       case 'y':
815       case 'f':
816         return C_RegisterClass;
817         break;
818     }
819   }
820   return TargetLowering::getConstraintType(Constraint);
821 }
822
823 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
824 /// return a list of registers that can be used to satisfy the constraint.
825 /// This should only be used for C_RegisterClass constraints.
826 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
827 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
828   if (Constraint.size() == 1) {
829     switch (Constraint[0]) {
830     case 'r':
831       return std::make_pair(0U, MBlaze::CPURegsRegisterClass);
832     case 'f':
833       if (VT == MVT::f32)
834         return std::make_pair(0U, MBlaze::FGR32RegisterClass);
835     }
836   }
837   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
838 }
839
840 /// Given a register class constraint, like 'r', if this corresponds directly
841 /// to an LLVM register class, return a register of 0 and the register class
842 /// pointer.
843 std::vector<unsigned> MBlazeTargetLowering::
844 getRegClassForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
845   if (Constraint.size() != 1)
846     return std::vector<unsigned>();
847
848   switch (Constraint[0]) {
849     default : break;
850     case 'r':
851     // GCC MBlaze Constraint Letters
852     case 'd':
853     case 'y':
854       return make_vector<unsigned>(
855         MBlaze::R3,  MBlaze::R4,  MBlaze::R5,  MBlaze::R6,
856         MBlaze::R7,  MBlaze::R9,  MBlaze::R10, MBlaze::R11,
857         MBlaze::R12, MBlaze::R19, MBlaze::R20, MBlaze::R21,
858         MBlaze::R22, MBlaze::R23, MBlaze::R24, MBlaze::R25,
859         MBlaze::R26, MBlaze::R27, MBlaze::R28, MBlaze::R29,
860         MBlaze::R30, MBlaze::R31, 0);
861
862     case 'f':
863       return make_vector<unsigned>(
864         MBlaze::F3,  MBlaze::F4,  MBlaze::F5,  MBlaze::F6,
865         MBlaze::F7,  MBlaze::F9,  MBlaze::F10, MBlaze::F11,
866         MBlaze::F12, MBlaze::F19, MBlaze::F20, MBlaze::F21,
867         MBlaze::F22, MBlaze::F23, MBlaze::F24, MBlaze::F25,
868         MBlaze::F26, MBlaze::F27, MBlaze::F28, MBlaze::F29,
869         MBlaze::F30, MBlaze::F31, 0);
870   }
871   return std::vector<unsigned>();
872 }
873
874 bool MBlazeTargetLowering::
875 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
876   // The MBlaze target isn't yet aware of offsets.
877   return false;
878 }
879
880 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
881   return VT != MVT::f32;
882 }