revert r97807, it introduced build warnings.
[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
474   // Analyze operands of the call, assigning locations to each operand.
475   SmallVector<CCValAssign, 16> ArgLocs;
476   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
477                  *DAG.getContext());
478   CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
479
480   // Get a count of how many bytes are to be pushed on the stack.
481   unsigned NumBytes = CCInfo.getNextStackOffset();
482   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
483
484   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
485   SmallVector<SDValue, 8> MemOpChains;
486
487   // First/LastArgStackLoc contains the first/last
488   // "at stack" argument location.
489   int LastArgStackLoc = 0;
490   unsigned FirstStackArgLoc = 4;
491
492   // Walk the register/memloc assignments, inserting copies/loads.
493   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
494     CCValAssign &VA = ArgLocs[i];
495     EVT RegVT = VA.getLocVT();
496     SDValue Arg = Outs[i].Val;
497
498     // Promote the value if needed.
499     switch (VA.getLocInfo()) {
500     default: llvm_unreachable("Unknown loc info!");
501     case CCValAssign::Full: break;
502     case CCValAssign::SExt:
503       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
504       break;
505     case CCValAssign::ZExt:
506       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
507       break;
508     case CCValAssign::AExt:
509       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
510       break;
511     case CCValAssign::BCvt:
512       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
513       break;
514     }
515
516     // Arguments that can be passed on register must be kept at
517     // RegsToPass vector
518     if (VA.isRegLoc()) {
519       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
520     } else {
521       // Register can't get to this point...
522       assert(VA.isMemLoc());
523
524       // Create the frame index object for this incoming parameter
525       LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
526       int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
527                                       LastArgStackLoc, true, false);
528
529       SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
530
531       // emit ISD::STORE whichs stores the
532       // parameter value to a stack Location
533       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0,
534                                          false, false, 0));
535     }
536   }
537
538   // Transform all store nodes into one single node because all store
539   // nodes are independent of each other.
540   if (!MemOpChains.empty())
541     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
542                         &MemOpChains[0], MemOpChains.size());
543
544   // Build a sequence of copy-to-reg nodes chained together with token
545   // chain and flag operands which copy the outgoing args into registers.
546   // The InFlag in necessary since all emited instructions must be
547   // stuck together.
548   SDValue InFlag;
549   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
550     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
551                              RegsToPass[i].second, InFlag);
552     InFlag = Chain.getValue(1);
553   }
554
555   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
556   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
557   // node so that legalize doesn't hack it.
558   unsigned char OpFlag = MBlazeII::MO_NO_FLAG;
559   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
560     Callee = DAG.getTargetGlobalAddress(G->getGlobal(),
561                                 getPointerTy(), 0, OpFlag);
562   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
563     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
564                                 getPointerTy(), OpFlag);
565
566   // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
567   //             = Chain, Callee, Reg#1, Reg#2, ...
568   //
569   // Returns a chain & a flag for retval copy to use.
570   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
571   SmallVector<SDValue, 8> Ops;
572   Ops.push_back(Chain);
573   Ops.push_back(Callee);
574
575   // Add argument registers to the end of the list so that they are
576   // known live into the call.
577   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
578     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
579                                   RegsToPass[i].second.getValueType()));
580   }
581
582   if (InFlag.getNode())
583     Ops.push_back(InFlag);
584
585   Chain  = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
586   InFlag = Chain.getValue(1);
587
588   // Create the CALLSEQ_END node.
589   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
590                              DAG.getIntPtrConstant(0, true), InFlag);
591   if (!Ins.empty())
592     InFlag = Chain.getValue(1);
593
594   // Handle result values, copying them out of physregs into vregs that we
595   // return.
596   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
597                          Ins, dl, DAG, InVals);
598 }
599
600 /// LowerCallResult - Lower the result values of a call into the
601 /// appropriate copies out of appropriate physical registers.
602 SDValue MBlazeTargetLowering::
603 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
604                 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
605                 DebugLoc dl, SelectionDAG &DAG,
606                 SmallVectorImpl<SDValue> &InVals) {
607   // Assign locations to each value returned by this call.
608   SmallVector<CCValAssign, 16> RVLocs;
609   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
610                  RVLocs, *DAG.getContext());
611
612   CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
613
614   // Copy all of the result registers out of their specified physreg.
615   for (unsigned i = 0; i != RVLocs.size(); ++i) {
616     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
617                                RVLocs[i].getValVT(), InFlag).getValue(1);
618     InFlag = Chain.getValue(2);
619     InVals.push_back(Chain.getValue(0));
620   }
621
622   return Chain;
623 }
624
625 //===----------------------------------------------------------------------===//
626 //             Formal Arguments Calling Convention Implementation
627 //===----------------------------------------------------------------------===//
628
629 /// LowerFormalArguments - transform physical registers into
630 /// virtual registers and generate load operations for
631 /// arguments places on the stack.
632 /// TODO: isVarArg
633 SDValue MBlazeTargetLowering::
634 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
635                      const SmallVectorImpl<ISD::InputArg> &Ins,
636                      DebugLoc dl, SelectionDAG &DAG,
637                      SmallVectorImpl<SDValue> &InVals) {
638   MachineFunction &MF = DAG.getMachineFunction();
639   MachineFrameInfo *MFI = MF.getFrameInfo();
640   MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
641
642   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
643
644   // Assign locations to all of the incoming arguments.
645   SmallVector<CCValAssign, 16> ArgLocs;
646   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
647                  ArgLocs, *DAG.getContext());
648
649   CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
650   SDValue StackPtr;
651
652   unsigned FirstStackArgLoc = 4;
653
654   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
655     CCValAssign &VA = ArgLocs[i];
656
657     // Arguments stored on registers
658     if (VA.isRegLoc()) {
659       EVT RegVT = VA.getLocVT();
660       TargetRegisterClass *RC = 0;
661
662       if (RegVT == MVT::i32)
663         RC = MBlaze::CPURegsRegisterClass;
664       else if (RegVT == MVT::f32)
665         RC = MBlaze::FGR32RegisterClass;
666       else
667         llvm_unreachable("RegVT not supported by LowerFormalArguments");
668
669       // Transform the arguments stored on
670       // physical registers into virtual ones
671       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
672       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
673
674       // If this is an 8 or 16-bit value, it has been passed promoted
675       // to 32 bits.  Insert an assert[sz]ext to capture this, then
676       // truncate to the right size.
677       if (VA.getLocInfo() != CCValAssign::Full) {
678         unsigned Opcode = 0;
679         if (VA.getLocInfo() == CCValAssign::SExt)
680           Opcode = ISD::AssertSext;
681         else if (VA.getLocInfo() == CCValAssign::ZExt)
682           Opcode = ISD::AssertZext;
683         if (Opcode)
684           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
685                                  DAG.getValueType(VA.getValVT()));
686         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
687       }
688
689       InVals.push_back(ArgValue);
690
691       // To meet ABI, when VARARGS are passed on registers, the registers
692       // must have their values written to the caller stack frame.
693       if (isVarArg) {
694         if (StackPtr.getNode() == 0)
695           StackPtr = DAG.getRegister(StackReg, getPointerTy());
696
697         // The stack pointer offset is relative to the caller stack frame.
698         // Since the real stack size is unknown here, a negative SPOffset
699         // is used so there's a way to adjust these offsets when the stack
700         // size get known (on EliminateFrameIndex). A dummy SPOffset is
701         // used instead of a direct negative address (which is recorded to
702         // be used on emitPrologue) to avoid mis-calc of the first stack
703         // offset on PEI::calculateFrameObjectOffsets.
704         // Arguments are always 32-bit.
705         int FI = MFI->CreateFixedObject(4, 0, true, false);
706         MBlazeFI->recordStoreVarArgsFI(FI, -(FirstStackArgLoc+(i*4)));
707         SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
708
709         // emit ISD::STORE whichs stores the
710         // parameter value to a stack Location
711         InVals.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff, NULL, 0,
712                                       false, false, 0));
713       }
714
715     } else { // VA.isRegLoc()
716
717       // sanity check
718       assert(VA.isMemLoc());
719
720       // The stack pointer offset is relative to the caller stack frame.
721       // Since the real stack size is unknown here, a negative SPOffset
722       // is used so there's a way to adjust these offsets when the stack
723       // size get known (on EliminateFrameIndex). A dummy SPOffset is
724       // used instead of a direct negative address (which is recorded to
725       // be used on emitPrologue) to avoid mis-calc of the first stack
726       // offset on PEI::calculateFrameObjectOffsets.
727       // Arguments are always 32-bit.
728       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
729       int FI = MFI->CreateFixedObject(ArgSize, 0, true, false);
730       MBlazeFI->recordLoadArgsFI(FI, -(ArgSize+
731         (FirstStackArgLoc + VA.getLocMemOffset())));
732
733       // Create load nodes to retrieve arguments from the stack
734       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
735       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0,
736                                    false, false, 0));
737     }
738   }
739
740   return Chain;
741 }
742
743 //===----------------------------------------------------------------------===//
744 //               Return Value Calling Convention Implementation
745 //===----------------------------------------------------------------------===//
746
747 SDValue MBlazeTargetLowering::
748 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
749             const SmallVectorImpl<ISD::OutputArg> &Outs,
750             DebugLoc dl, SelectionDAG &DAG) {
751   // CCValAssign - represent the assignment of
752   // the return value to a location
753   SmallVector<CCValAssign, 16> RVLocs;
754
755   // CCState - Info about the registers and stack slot.
756   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
757                  RVLocs, *DAG.getContext());
758
759   // Analize return values.
760   CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
761
762   // If this is the first return lowered for this function, add
763   // the regs to the liveout set for the function.
764   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
765     for (unsigned i = 0; i != RVLocs.size(); ++i)
766       if (RVLocs[i].isRegLoc())
767         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
768   }
769
770   SDValue Flag;
771
772   // Copy the result values into the output registers.
773   for (unsigned i = 0; i != RVLocs.size(); ++i) {
774     CCValAssign &VA = RVLocs[i];
775     assert(VA.isRegLoc() && "Can only return in registers!");
776
777     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
778                              Outs[i].Val, Flag);
779
780     // guarantee that all emitted copies are
781     // stuck together, avoiding something bad
782     Flag = Chain.getValue(1);
783   }
784
785   // Return on MBlaze is always a "rtsd R15, 8"
786   if (Flag.getNode())
787     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
788                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32), Flag);
789   else // Return Void
790     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
791                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32));
792 }
793
794 //===----------------------------------------------------------------------===//
795 //                           MBlaze Inline Assembly Support
796 //===----------------------------------------------------------------------===//
797
798 /// getConstraintType - Given a constraint letter, return the type of
799 /// constraint it is for this target.
800 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
801 getConstraintType(const std::string &Constraint) const
802 {
803   // MBlaze specific constrainy
804   //
805   // 'd' : An address register. Equivalent to r.
806   // 'y' : Equivalent to r; retained for
807   //       backwards compatibility.
808   // 'f' : Floating Point registers.
809   if (Constraint.size() == 1) {
810     switch (Constraint[0]) {
811       default : break;
812       case 'd':
813       case 'y':
814       case 'f':
815         return C_RegisterClass;
816         break;
817     }
818   }
819   return TargetLowering::getConstraintType(Constraint);
820 }
821
822 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
823 /// return a list of registers that can be used to satisfy the constraint.
824 /// This should only be used for C_RegisterClass constraints.
825 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
826 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
827   if (Constraint.size() == 1) {
828     switch (Constraint[0]) {
829     case 'r':
830       return std::make_pair(0U, MBlaze::CPURegsRegisterClass);
831     case 'f':
832       if (VT == MVT::f32)
833         return std::make_pair(0U, MBlaze::FGR32RegisterClass);
834     }
835   }
836   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
837 }
838
839 /// Given a register class constraint, like 'r', if this corresponds directly
840 /// to an LLVM register class, return a register of 0 and the register class
841 /// pointer.
842 std::vector<unsigned> MBlazeTargetLowering::
843 getRegClassForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
844   if (Constraint.size() != 1)
845     return std::vector<unsigned>();
846
847   switch (Constraint[0]) {
848     default : break;
849     case 'r':
850     // GCC MBlaze Constraint Letters
851     case 'd':
852     case 'y':
853       return make_vector<unsigned>(
854         MBlaze::R3,  MBlaze::R4,  MBlaze::R5,  MBlaze::R6,
855         MBlaze::R7,  MBlaze::R9,  MBlaze::R10, MBlaze::R11,
856         MBlaze::R12, MBlaze::R19, MBlaze::R20, MBlaze::R21,
857         MBlaze::R22, MBlaze::R23, MBlaze::R24, MBlaze::R25,
858         MBlaze::R26, MBlaze::R27, MBlaze::R28, MBlaze::R29,
859         MBlaze::R30, MBlaze::R31, 0);
860
861     case 'f':
862       return make_vector<unsigned>(
863         MBlaze::F3,  MBlaze::F4,  MBlaze::F5,  MBlaze::F6,
864         MBlaze::F7,  MBlaze::F9,  MBlaze::F10, MBlaze::F11,
865         MBlaze::F12, MBlaze::F19, MBlaze::F20, MBlaze::F21,
866         MBlaze::F22, MBlaze::F23, MBlaze::F24, MBlaze::F25,
867         MBlaze::F26, MBlaze::F27, MBlaze::F28, MBlaze::F29,
868         MBlaze::F30, MBlaze::F31, 0);
869   }
870   return std::vector<unsigned>();
871 }
872
873 bool MBlazeTargetLowering::
874 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
875   // The MBlaze target isn't yet aware of offsets.
876   return false;
877 }
878
879 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
880   return VT != MVT::f32;
881 }