7664c60c9328d64c5bf5f6dd8bd37d6c1e0cdaa1
[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 "MBlazeSubtarget.h"
19 #include "MBlazeTargetMachine.h"
20 #include "MBlazeTargetObjectFile.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.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 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
39                                 CCValAssign::LocInfo &LocInfo,
40                                 ISD::ArgFlagsTy &ArgFlags,
41                                 CCState &State);
42
43 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
44   switch (Opcode) {
45     case MBlazeISD::JmpLink    : return "MBlazeISD::JmpLink";
46     case MBlazeISD::GPRel      : return "MBlazeISD::GPRel";
47     case MBlazeISD::Wrap       : return "MBlazeISD::Wrap";
48     case MBlazeISD::ICmp       : return "MBlazeISD::ICmp";
49     case MBlazeISD::Ret        : return "MBlazeISD::Ret";
50     case MBlazeISD::Select_CC  : return "MBlazeISD::Select_CC";
51     default                    : return NULL;
52   }
53 }
54
55 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
56   : TargetLowering(TM, new MBlazeTargetObjectFile()) {
57   Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
58
59   // MBlaze does not have i1 type, so use i32 for
60   // setcc operations results (slt, sgt, ...).
61   setBooleanContents(ZeroOrOneBooleanContent);
62   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
63
64   // Set up the register classes
65   addRegisterClass(MVT::i32, &MBlaze::GPRRegClass);
66   if (Subtarget->hasFPU()) {
67     addRegisterClass(MVT::f32, &MBlaze::GPRRegClass);
68     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
69   }
70
71   // Floating point operations which are not supported
72   setOperationAction(ISD::FREM,       MVT::f32, Expand);
73   setOperationAction(ISD::FMA,        MVT::f32, Expand);
74   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Expand);
75   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
76   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
77   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
78   setOperationAction(ISD::FP_ROUND,   MVT::f32, Expand);
79   setOperationAction(ISD::FP_ROUND,   MVT::f64, Expand);
80   setOperationAction(ISD::FCOPYSIGN,  MVT::f32, Expand);
81   setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
82   setOperationAction(ISD::FSIN,       MVT::f32, Expand);
83   setOperationAction(ISD::FCOS,       MVT::f32, Expand);
84   setOperationAction(ISD::FSINCOS,    MVT::f32, Expand);
85   setOperationAction(ISD::FPOWI,      MVT::f32, Expand);
86   setOperationAction(ISD::FPOW,       MVT::f32, Expand);
87   setOperationAction(ISD::FLOG,       MVT::f32, Expand);
88   setOperationAction(ISD::FLOG2,      MVT::f32, Expand);
89   setOperationAction(ISD::FLOG10,     MVT::f32, Expand);
90   setOperationAction(ISD::FEXP,       MVT::f32, Expand);
91
92   // Load extented operations for i1 types must be promoted
93   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
94   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
95   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
96
97   // Sign extended loads must be expanded
98   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
99   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
100
101   // MBlaze has no REM or DIVREM operations.
102   setOperationAction(ISD::UREM,    MVT::i32, Expand);
103   setOperationAction(ISD::SREM,    MVT::i32, Expand);
104   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
105   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
106
107   // If the processor doesn't support multiply then expand it
108   if (!Subtarget->hasMul()) {
109     setOperationAction(ISD::MUL, MVT::i32, Expand);
110   }
111
112   // If the processor doesn't support 64-bit multiply then expand
113   if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
114     setOperationAction(ISD::MULHS, MVT::i32, Expand);
115     setOperationAction(ISD::MULHS, MVT::i64, Expand);
116     setOperationAction(ISD::MULHU, MVT::i32, Expand);
117     setOperationAction(ISD::MULHU, MVT::i64, Expand);
118   }
119
120   // If the processor doesn't support division then expand
121   if (!Subtarget->hasDiv()) {
122     setOperationAction(ISD::UDIV, MVT::i32, Expand);
123     setOperationAction(ISD::SDIV, MVT::i32, Expand);
124   }
125
126   // Expand unsupported conversions
127   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
128   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
129
130   // Expand SELECT_CC
131   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
132
133   // MBlaze doesn't have MUL_LOHI
134   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
135   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
136   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
137   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
138
139   // Used by legalize types to correctly generate the setcc result.
140   // Without this, every float setcc comes with a AND/OR with the result,
141   // we don't want this, since the fpcmp result goes to a flag register,
142   // which is used implicitly by brcond and select operations.
143   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
144   AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
145   AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
146
147   // MBlaze Custom Operations
148   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
149   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
150   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
151   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
152
153   // Variable Argument support
154   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
155   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
156   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
157   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
158
159
160   // Operations not directly supported by MBlaze.
161   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
162   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
163   setOperationAction(ISD::BR_CC,              MVT::Other, Expand);
164   setOperationAction(ISD::SIGN_EXTEND_INREG,  MVT::i1,    Expand);
165   setOperationAction(ISD::ROTL,               MVT::i32,   Expand);
166   setOperationAction(ISD::ROTR,               MVT::i32,   Expand);
167   setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Expand);
168   setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Expand);
169   setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Expand);
170   setOperationAction(ISD::CTLZ,               MVT::i32,   Expand);
171   setOperationAction(ISD::CTLZ_ZERO_UNDEF,    MVT::i32,   Expand);
172   setOperationAction(ISD::CTTZ,               MVT::i32,   Expand);
173   setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::i32,   Expand);
174   setOperationAction(ISD::CTPOP,              MVT::i32,   Expand);
175   setOperationAction(ISD::BSWAP,              MVT::i32,   Expand);
176
177   // We don't have line number support yet.
178   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
179
180   // Use the default for now
181   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
182   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
183
184   // MBlaze doesn't have extending float->double load/store
185   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
186   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187
188   setMinFunctionAlignment(2);
189
190   setStackPointerRegisterToSaveRestore(MBlaze::R1);
191   computeRegisterProperties();
192 }
193
194 EVT MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
195   return MVT::i32;
196 }
197
198 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
199                                              SelectionDAG &DAG) const {
200   switch (Op.getOpcode())
201   {
202     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
203     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
204     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
205     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
206     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
207     case ISD::VASTART:            return LowerVASTART(Op, DAG);
208   }
209   return SDValue();
210 }
211
212 //===----------------------------------------------------------------------===//
213 //  Lower helper functions
214 //===----------------------------------------------------------------------===//
215 MachineBasicBlock*
216 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
217                                                   MachineBasicBlock *MBB)
218                                                   const {
219   switch (MI->getOpcode()) {
220   default: llvm_unreachable("Unexpected instr type to insert");
221
222   case MBlaze::ShiftRL:
223   case MBlaze::ShiftRA:
224   case MBlaze::ShiftL:
225     return EmitCustomShift(MI, MBB);
226
227   case MBlaze::Select_FCC:
228   case MBlaze::Select_CC:
229     return EmitCustomSelect(MI, MBB);
230
231   case MBlaze::CAS32:
232   case MBlaze::SWP32:
233   case MBlaze::LAA32:
234   case MBlaze::LAS32:
235   case MBlaze::LAD32:
236   case MBlaze::LAO32:
237   case MBlaze::LAX32:
238   case MBlaze::LAN32:
239     return EmitCustomAtomic(MI, MBB);
240
241   case MBlaze::MEMBARRIER:
242     // The Microblaze does not need memory barriers. Just delete the pseudo
243     // instruction and finish.
244     MI->eraseFromParent();
245     return MBB;
246   }
247 }
248
249 MachineBasicBlock*
250 MBlazeTargetLowering::EmitCustomShift(MachineInstr *MI,
251                                       MachineBasicBlock *MBB) const {
252   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
253   DebugLoc dl = MI->getDebugLoc();
254
255   // To "insert" a shift left instruction, we actually have to insert a
256   // simple loop.  The incoming instruction knows the destination vreg to
257   // set, the source vreg to operate over and the shift amount.
258   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
259   MachineFunction::iterator It = MBB;
260   ++It;
261
262   // start:
263   //   andi     samt, samt, 31
264   //   beqid    samt, finish
265   //   add      dst, src, r0
266   // loop:
267   //   addik    samt, samt, -1
268   //   sra      dst, dst
269   //   bneid    samt, loop
270   //   nop
271   // finish:
272   MachineFunction *F = MBB->getParent();
273   MachineRegisterInfo &R = F->getRegInfo();
274   MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
275   MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
276   F->insert(It, loop);
277   F->insert(It, finish);
278
279   // Update machine-CFG edges by transferring adding all successors and
280   // remaining instructions from the current block to the new block which
281   // will contain the Phi node for the select.
282   finish->splice(finish->begin(), MBB,
283                  llvm::next(MachineBasicBlock::iterator(MI)),
284                  MBB->end());
285   finish->transferSuccessorsAndUpdatePHIs(MBB);
286
287   // Add the true and fallthrough blocks as its successors.
288   MBB->addSuccessor(loop);
289   MBB->addSuccessor(finish);
290
291   // Next, add the finish block as a successor of the loop block
292   loop->addSuccessor(finish);
293   loop->addSuccessor(loop);
294
295   unsigned IAMT = R.createVirtualRegister(&MBlaze::GPRRegClass);
296   BuildMI(MBB, dl, TII->get(MBlaze::ANDI), IAMT)
297     .addReg(MI->getOperand(2).getReg())
298     .addImm(31);
299
300   unsigned IVAL = R.createVirtualRegister(&MBlaze::GPRRegClass);
301   BuildMI(MBB, dl, TII->get(MBlaze::ADDIK), IVAL)
302     .addReg(MI->getOperand(1).getReg())
303     .addImm(0);
304
305   BuildMI(MBB, dl, TII->get(MBlaze::BEQID))
306     .addReg(IAMT)
307     .addMBB(finish);
308
309   unsigned DST = R.createVirtualRegister(&MBlaze::GPRRegClass);
310   unsigned NDST = R.createVirtualRegister(&MBlaze::GPRRegClass);
311   BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
312     .addReg(IVAL).addMBB(MBB)
313     .addReg(NDST).addMBB(loop);
314
315   unsigned SAMT = R.createVirtualRegister(&MBlaze::GPRRegClass);
316   unsigned NAMT = R.createVirtualRegister(&MBlaze::GPRRegClass);
317   BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
318     .addReg(IAMT).addMBB(MBB)
319     .addReg(NAMT).addMBB(loop);
320
321   if (MI->getOpcode() == MBlaze::ShiftL)
322     BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
323   else if (MI->getOpcode() == MBlaze::ShiftRA)
324     BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
325   else if (MI->getOpcode() == MBlaze::ShiftRL)
326     BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
327   else
328     llvm_unreachable("Cannot lower unknown shift instruction");
329
330   BuildMI(loop, dl, TII->get(MBlaze::ADDIK), NAMT)
331     .addReg(SAMT)
332     .addImm(-1);
333
334   BuildMI(loop, dl, TII->get(MBlaze::BNEID))
335     .addReg(NAMT)
336     .addMBB(loop);
337
338   BuildMI(*finish, finish->begin(), dl,
339           TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
340     .addReg(IVAL).addMBB(MBB)
341     .addReg(NDST).addMBB(loop);
342
343   // The pseudo instruction is no longer needed so remove it
344   MI->eraseFromParent();
345   return finish;
346 }
347
348 MachineBasicBlock*
349 MBlazeTargetLowering::EmitCustomSelect(MachineInstr *MI,
350                                        MachineBasicBlock *MBB) const {
351   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
352   DebugLoc dl = MI->getDebugLoc();
353
354   // To "insert" a SELECT_CC instruction, we actually have to insert the
355   // diamond control-flow pattern.  The incoming instruction knows the
356   // destination vreg to set, the condition code register to branch on, the
357   // true/false values to select between, and a branch opcode to use.
358   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
359   MachineFunction::iterator It = MBB;
360   ++It;
361
362   //  thisMBB:
363   //  ...
364   //   TrueVal = ...
365   //   setcc r1, r2, r3
366   //   bNE   r1, r0, copy1MBB
367   //   fallthrough --> copy0MBB
368   MachineFunction *F = MBB->getParent();
369   MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
370   MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
371
372   unsigned Opc;
373   switch (MI->getOperand(4).getImm()) {
374   default: llvm_unreachable("Unknown branch condition");
375   case MBlazeCC::EQ: Opc = MBlaze::BEQID; break;
376   case MBlazeCC::NE: Opc = MBlaze::BNEID; break;
377   case MBlazeCC::GT: Opc = MBlaze::BGTID; break;
378   case MBlazeCC::LT: Opc = MBlaze::BLTID; break;
379   case MBlazeCC::GE: Opc = MBlaze::BGEID; break;
380   case MBlazeCC::LE: Opc = MBlaze::BLEID; break;
381   }
382
383   F->insert(It, flsBB);
384   F->insert(It, dneBB);
385
386   // Transfer the remainder of MBB and its successor edges to dneBB.
387   dneBB->splice(dneBB->begin(), MBB,
388                 llvm::next(MachineBasicBlock::iterator(MI)),
389                 MBB->end());
390   dneBB->transferSuccessorsAndUpdatePHIs(MBB);
391
392   MBB->addSuccessor(flsBB);
393   MBB->addSuccessor(dneBB);
394   flsBB->addSuccessor(dneBB);
395
396   BuildMI(MBB, dl, TII->get(Opc))
397     .addReg(MI->getOperand(3).getReg())
398     .addMBB(dneBB);
399
400   //  sinkMBB:
401   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
402   //  ...
403   //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
404   //  .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
405   //  .addReg(MI->getOperand(2).getReg()).addMBB(BB);
406
407   BuildMI(*dneBB, dneBB->begin(), dl,
408           TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
409     .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
410     .addReg(MI->getOperand(1).getReg()).addMBB(MBB);
411
412   MI->eraseFromParent();   // The pseudo instruction is gone now.
413   return dneBB;
414 }
415
416 MachineBasicBlock*
417 MBlazeTargetLowering::EmitCustomAtomic(MachineInstr *MI,
418                                        MachineBasicBlock *MBB) const {
419   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
420   DebugLoc dl = MI->getDebugLoc();
421
422   // All atomic instructions on the Microblaze are implemented using the
423   // load-linked / store-conditional style atomic instruction sequences.
424   // Thus, all operations will look something like the following:
425   //
426   //  start:
427   //    lwx     RV, RP, 0
428   //    <do stuff>
429   //    swx     RV, RP, 0
430   //    addic   RC, R0, 0
431   //    bneid   RC, start
432   //
433   //  exit:
434   //
435   // To "insert" a shift left instruction, we actually have to insert a
436   // simple loop.  The incoming instruction knows the destination vreg to
437   // set, the source vreg to operate over and the shift amount.
438   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
439   MachineFunction::iterator It = MBB;
440   ++It;
441
442   // start:
443   //   andi     samt, samt, 31
444   //   beqid    samt, finish
445   //   add      dst, src, r0
446   // loop:
447   //   addik    samt, samt, -1
448   //   sra      dst, dst
449   //   bneid    samt, loop
450   //   nop
451   // finish:
452   MachineFunction *F = MBB->getParent();
453   MachineRegisterInfo &R = F->getRegInfo();
454
455   // Create the start and exit basic blocks for the atomic operation
456   MachineBasicBlock *start = F->CreateMachineBasicBlock(LLVM_BB);
457   MachineBasicBlock *exit = F->CreateMachineBasicBlock(LLVM_BB);
458   F->insert(It, start);
459   F->insert(It, exit);
460
461   // Update machine-CFG edges by transferring adding all successors and
462   // remaining instructions from the current block to the new block which
463   // will contain the Phi node for the select.
464   exit->splice(exit->begin(), MBB, llvm::next(MachineBasicBlock::iterator(MI)),
465                MBB->end());
466   exit->transferSuccessorsAndUpdatePHIs(MBB);
467
468   // Add the fallthrough block as its successors.
469   MBB->addSuccessor(start);
470
471   BuildMI(start, dl, TII->get(MBlaze::LWX), MI->getOperand(0).getReg())
472     .addReg(MI->getOperand(1).getReg())
473     .addReg(MBlaze::R0);
474
475   MachineBasicBlock *final = start;
476   unsigned finalReg = 0;
477
478   switch (MI->getOpcode()) {
479   default: llvm_unreachable("Cannot lower unknown atomic instruction!");
480
481   case MBlaze::SWP32:
482     finalReg = MI->getOperand(2).getReg();
483     start->addSuccessor(exit);
484     start->addSuccessor(start);
485     break;
486
487   case MBlaze::LAN32:
488   case MBlaze::LAX32:
489   case MBlaze::LAO32:
490   case MBlaze::LAD32:
491   case MBlaze::LAS32:
492   case MBlaze::LAA32: {
493     unsigned opcode = 0;
494     switch (MI->getOpcode()) {
495     default: llvm_unreachable("Cannot lower unknown atomic load!");
496     case MBlaze::LAA32: opcode = MBlaze::ADDIK; break;
497     case MBlaze::LAS32: opcode = MBlaze::RSUBIK; break;
498     case MBlaze::LAD32: opcode = MBlaze::AND; break;
499     case MBlaze::LAO32: opcode = MBlaze::OR; break;
500     case MBlaze::LAX32: opcode = MBlaze::XOR; break;
501     case MBlaze::LAN32: opcode = MBlaze::AND; break;
502     }
503
504     finalReg = R.createVirtualRegister(&MBlaze::GPRRegClass);
505     start->addSuccessor(exit);
506     start->addSuccessor(start);
507
508     BuildMI(start, dl, TII->get(opcode), finalReg)
509       .addReg(MI->getOperand(0).getReg())
510       .addReg(MI->getOperand(2).getReg());
511
512     if (MI->getOpcode() == MBlaze::LAN32) {
513       unsigned tmp = finalReg;
514       finalReg = R.createVirtualRegister(&MBlaze::GPRRegClass);
515       BuildMI(start, dl, TII->get(MBlaze::XORI), finalReg)
516         .addReg(tmp)
517         .addImm(-1);
518     }
519     break;
520   }
521
522   case MBlaze::CAS32: {
523     finalReg = MI->getOperand(3).getReg();
524     final = F->CreateMachineBasicBlock(LLVM_BB);
525
526     F->insert(It, final);
527     start->addSuccessor(exit);
528     start->addSuccessor(final);
529     final->addSuccessor(exit);
530     final->addSuccessor(start);
531
532     unsigned CMP = R.createVirtualRegister(&MBlaze::GPRRegClass);
533     BuildMI(start, dl, TII->get(MBlaze::CMP), CMP)
534       .addReg(MI->getOperand(0).getReg())
535       .addReg(MI->getOperand(2).getReg());
536
537     BuildMI(start, dl, TII->get(MBlaze::BNEID))
538       .addReg(CMP)
539       .addMBB(exit);
540
541     final->moveAfter(start);
542     exit->moveAfter(final);
543     break;
544   }
545   }
546
547   unsigned CHK = R.createVirtualRegister(&MBlaze::GPRRegClass);
548   BuildMI(final, dl, TII->get(MBlaze::SWX))
549     .addReg(finalReg)
550     .addReg(MI->getOperand(1).getReg())
551     .addReg(MBlaze::R0);
552
553   BuildMI(final, dl, TII->get(MBlaze::ADDIC), CHK)
554     .addReg(MBlaze::R0)
555     .addImm(0);
556
557   BuildMI(final, dl, TII->get(MBlaze::BNEID))
558     .addReg(CHK)
559     .addMBB(start);
560
561   // The pseudo instruction is no longer needed so remove it
562   MI->eraseFromParent();
563   return exit;
564 }
565
566 //===----------------------------------------------------------------------===//
567 //  Misc Lower Operation implementation
568 //===----------------------------------------------------------------------===//
569 //
570
571 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op,
572                                              SelectionDAG &DAG) const {
573   SDValue LHS = Op.getOperand(0);
574   SDValue RHS = Op.getOperand(1);
575   SDValue TrueVal = Op.getOperand(2);
576   SDValue FalseVal = Op.getOperand(3);
577   DebugLoc dl = Op.getDebugLoc();
578   unsigned Opc;
579
580   SDValue CompareFlag;
581   if (LHS.getValueType() == MVT::i32) {
582     Opc = MBlazeISD::Select_CC;
583     CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
584                     .getValue(1);
585   } else {
586     llvm_unreachable("Cannot lower select_cc with unknown type");
587   }
588
589   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
590                      CompareFlag);
591 }
592
593 SDValue MBlazeTargetLowering::
594 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
595   // FIXME there isn't actually debug info here
596   DebugLoc dl = Op.getDebugLoc();
597   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
598   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
599
600   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
601 }
602
603 SDValue MBlazeTargetLowering::
604 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
605   llvm_unreachable("TLS not implemented for MicroBlaze.");
606 }
607
608 SDValue MBlazeTargetLowering::
609 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
610   SDValue ResNode;
611   SDValue HiPart;
612   // FIXME there isn't actually debug info here
613   DebugLoc dl = Op.getDebugLoc();
614
615   EVT PtrVT = Op.getValueType();
616   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
617
618   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0);
619   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
620 }
621
622 SDValue MBlazeTargetLowering::
623 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
624   SDValue ResNode;
625   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
626   const Constant *C = N->getConstVal();
627   DebugLoc dl = Op.getDebugLoc();
628
629   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
630                                          N->getOffset(), 0);
631   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
632 }
633
634 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
635                                            SelectionDAG &DAG) const {
636   MachineFunction &MF = DAG.getMachineFunction();
637   MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
638
639   DebugLoc dl = Op.getDebugLoc();
640   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
641                                  getPointerTy());
642
643   // vastart just stores the address of the VarArgsFrameIndex slot into the
644   // memory location argument.
645   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
646   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
647                       MachinePointerInfo(SV),
648                       false, false, 0);
649 }
650
651 //===----------------------------------------------------------------------===//
652 //                      Calling Convention Implementation
653 //===----------------------------------------------------------------------===//
654
655 #include "MBlazeGenCallingConv.inc"
656
657 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
658                                 CCValAssign::LocInfo &LocInfo,
659                                 ISD::ArgFlagsTy &ArgFlags,
660                                 CCState &State) {
661   static const uint16_t ArgRegs[] = {
662     MBlaze::R5, MBlaze::R6, MBlaze::R7,
663     MBlaze::R8, MBlaze::R9, MBlaze::R10
664   };
665
666   const unsigned NumArgRegs = array_lengthof(ArgRegs);
667   unsigned Reg = State.AllocateReg(ArgRegs, NumArgRegs);
668   if (!Reg) return false;
669
670   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
671   State.AllocateStack(SizeInBytes, SizeInBytes);
672   State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
673
674   return true;
675 }
676
677 //===----------------------------------------------------------------------===//
678 //                  Call Calling Convention Implementation
679 //===----------------------------------------------------------------------===//
680
681 /// LowerCall - functions arguments are copied from virtual regs to
682 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
683 /// TODO: isVarArg, isTailCall.
684 SDValue MBlazeTargetLowering::
685 LowerCall(TargetLowering::CallLoweringInfo &CLI,
686           SmallVectorImpl<SDValue> &InVals) const {
687   SelectionDAG &DAG                     = CLI.DAG;
688   DebugLoc &dl                          = CLI.DL;
689   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
690   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
691   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
692   SDValue Chain                         = CLI.Chain;
693   SDValue Callee                        = CLI.Callee;
694   bool &isTailCall                      = CLI.IsTailCall;
695   CallingConv::ID CallConv              = CLI.CallConv;
696   bool isVarArg                         = CLI.IsVarArg;
697
698   // MBlaze does not yet support tail call optimization
699   isTailCall = false;
700
701   // The MBlaze requires stack slots for arguments passed to var arg
702   // functions even if they are passed in registers.
703   bool needsRegArgSlots = isVarArg;
704
705   MachineFunction &MF = DAG.getMachineFunction();
706   MachineFrameInfo *MFI = MF.getFrameInfo();
707   const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
708
709   // Analyze operands of the call, assigning locations to each operand.
710   SmallVector<CCValAssign, 16> ArgLocs;
711   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
712                  getTargetMachine(), ArgLocs, *DAG.getContext());
713   CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
714
715   // Get a count of how many bytes are to be pushed on the stack.
716   unsigned NumBytes = CCInfo.getNextStackOffset();
717
718   // Variable argument function calls require a minimum of 24-bytes of stack
719   if (isVarArg && NumBytes < 24) NumBytes = 24;
720
721   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
722
723   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
724   SmallVector<SDValue, 8> MemOpChains;
725
726   // Walk the register/memloc assignments, inserting copies/loads.
727   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
728     CCValAssign &VA = ArgLocs[i];
729     MVT RegVT = VA.getLocVT();
730     SDValue Arg = OutVals[i];
731
732     // Promote the value if needed.
733     switch (VA.getLocInfo()) {
734     default: llvm_unreachable("Unknown loc info!");
735     case CCValAssign::Full: break;
736     case CCValAssign::SExt:
737       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
738       break;
739     case CCValAssign::ZExt:
740       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
741       break;
742     case CCValAssign::AExt:
743       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
744       break;
745     }
746
747     // Arguments that can be passed on register must be kept at
748     // RegsToPass vector
749     if (VA.isRegLoc()) {
750       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
751     } else {
752       // Register can't get to this point...
753       assert(VA.isMemLoc());
754
755       // Since we are alread passing values on the stack we don't
756       // need to worry about creating additional slots for the
757       // values passed via registers.
758       needsRegArgSlots = false;
759
760       // Create the frame index object for this incoming parameter
761       unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
762       unsigned StackLoc = VA.getLocMemOffset() + 4;
763       int FI = MFI->CreateFixedObject(ArgSize, StackLoc, true);
764
765       SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
766
767       // emit ISD::STORE whichs stores the
768       // parameter value to a stack Location
769       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
770                                          MachinePointerInfo(),
771                                          false, false, 0));
772     }
773   }
774
775   // If we need to reserve stack space for the arguments passed via registers
776   // then create a fixed stack object at the beginning of the stack.
777   if (needsRegArgSlots && TFI.hasReservedCallFrame(MF))
778     MFI->CreateFixedObject(28,0,true);
779
780   // Transform all store nodes into one single node because all store
781   // nodes are independent of each other.
782   if (!MemOpChains.empty())
783     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
784                         &MemOpChains[0], MemOpChains.size());
785
786   // Build a sequence of copy-to-reg nodes chained together with token
787   // chain and flag operands which copy the outgoing args into registers.
788   // The InFlag in necessary since all emitted instructions must be
789   // stuck together.
790   SDValue InFlag;
791   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
792     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
793                              RegsToPass[i].second, InFlag);
794     InFlag = Chain.getValue(1);
795   }
796
797   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
798   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
799   // node so that legalize doesn't hack it.
800   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
801     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
802                                 getPointerTy(), 0, 0);
803   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
804     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
805                                 getPointerTy(), 0);
806
807   // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
808   //             = Chain, Callee, Reg#1, Reg#2, ...
809   //
810   // Returns a chain & a flag for retval copy to use.
811   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
812   SmallVector<SDValue, 8> Ops;
813   Ops.push_back(Chain);
814   Ops.push_back(Callee);
815
816   // Add argument registers to the end of the list so that they are
817   // known live into the call.
818   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
819     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
820                                   RegsToPass[i].second.getValueType()));
821   }
822
823   if (InFlag.getNode())
824     Ops.push_back(InFlag);
825
826   Chain  = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
827   InFlag = Chain.getValue(1);
828
829   // Create the CALLSEQ_END node.
830   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
831                              DAG.getIntPtrConstant(0, true), InFlag);
832   if (!Ins.empty())
833     InFlag = Chain.getValue(1);
834
835   // Handle result values, copying them out of physregs into vregs that we
836   // return.
837   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
838                          Ins, dl, DAG, InVals);
839 }
840
841 /// LowerCallResult - Lower the result values of a call into the
842 /// appropriate copies out of appropriate physical registers.
843 SDValue MBlazeTargetLowering::
844 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
845                 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
846                 DebugLoc dl, SelectionDAG &DAG,
847                 SmallVectorImpl<SDValue> &InVals) const {
848   // Assign locations to each value returned by this call.
849   SmallVector<CCValAssign, 16> RVLocs;
850   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
851                  getTargetMachine(), RVLocs, *DAG.getContext());
852
853   CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
854
855   // Copy all of the result registers out of their specified physreg.
856   for (unsigned i = 0; i != RVLocs.size(); ++i) {
857     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
858                                RVLocs[i].getValVT(), InFlag).getValue(1);
859     InFlag = Chain.getValue(2);
860     InVals.push_back(Chain.getValue(0));
861   }
862
863   return Chain;
864 }
865
866 //===----------------------------------------------------------------------===//
867 //             Formal Arguments Calling Convention Implementation
868 //===----------------------------------------------------------------------===//
869
870 /// LowerFormalArguments - transform physical registers into
871 /// virtual registers and generate load operations for
872 /// arguments places on the stack.
873 SDValue MBlazeTargetLowering::
874 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
875                      const SmallVectorImpl<ISD::InputArg> &Ins,
876                      DebugLoc dl, SelectionDAG &DAG,
877                      SmallVectorImpl<SDValue> &InVals) const {
878   MachineFunction &MF = DAG.getMachineFunction();
879   MachineFrameInfo *MFI = MF.getFrameInfo();
880   MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
881
882   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
883   MBlazeFI->setVarArgsFrameIndex(0);
884
885   // Used with vargs to acumulate store chains.
886   std::vector<SDValue> OutChains;
887
888   // Keep track of the last register used for arguments
889   unsigned ArgRegEnd = 0;
890
891   // Assign locations to all of the incoming arguments.
892   SmallVector<CCValAssign, 16> ArgLocs;
893   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
894                  getTargetMachine(), ArgLocs, *DAG.getContext());
895
896   CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
897   SDValue StackPtr;
898
899   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
900     CCValAssign &VA = ArgLocs[i];
901
902     // Arguments stored on registers
903     if (VA.isRegLoc()) {
904       MVT RegVT = VA.getLocVT();
905       ArgRegEnd = VA.getLocReg();
906       const TargetRegisterClass *RC;
907
908       if (RegVT == MVT::i32)
909         RC = &MBlaze::GPRRegClass;
910       else if (RegVT == MVT::f32)
911         RC = &MBlaze::GPRRegClass;
912       else
913         llvm_unreachable("RegVT not supported by LowerFormalArguments");
914
915       // Transform the arguments stored on
916       // physical registers into virtual ones
917       unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
918       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
919
920       // If this is an 8 or 16-bit value, it has been passed promoted
921       // to 32 bits.  Insert an assert[sz]ext to capture this, then
922       // truncate to the right size. If if is a floating point value
923       // then convert to the correct type.
924       if (VA.getLocInfo() != CCValAssign::Full) {
925         unsigned Opcode = 0;
926         if (VA.getLocInfo() == CCValAssign::SExt)
927           Opcode = ISD::AssertSext;
928         else if (VA.getLocInfo() == CCValAssign::ZExt)
929           Opcode = ISD::AssertZext;
930         if (Opcode)
931           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
932                                  DAG.getValueType(VA.getValVT()));
933         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
934       }
935
936       InVals.push_back(ArgValue);
937     } else { // VA.isRegLoc()
938       // sanity check
939       assert(VA.isMemLoc());
940
941       // The last argument is not a register
942       ArgRegEnd = 0;
943
944       // The stack pointer offset is relative to the caller stack frame.
945       // Since the real stack size is unknown here, a negative SPOffset
946       // is used so there's a way to adjust these offsets when the stack
947       // size get known (on EliminateFrameIndex). A dummy SPOffset is
948       // used instead of a direct negative address (which is recorded to
949       // be used on emitPrologue) to avoid mis-calc of the first stack
950       // offset on PEI::calculateFrameObjectOffsets.
951       // Arguments are always 32-bit.
952       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
953       unsigned StackLoc = VA.getLocMemOffset() + 4;
954       int FI = MFI->CreateFixedObject(ArgSize, 0, true);
955       MBlazeFI->recordLoadArgsFI(FI, -StackLoc);
956       MBlazeFI->recordLiveIn(FI);
957
958       // Create load nodes to retrieve arguments from the stack
959       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
960       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
961                                    MachinePointerInfo::getFixedStack(FI),
962                                    false, false, false, 0));
963     }
964   }
965
966   // To meet ABI, when VARARGS are passed on registers, the registers
967   // must have their values written to the caller stack frame. If the last
968   // argument was placed in the stack, there's no need to save any register.
969   if ((isVarArg) && ArgRegEnd) {
970     if (StackPtr.getNode() == 0)
971       StackPtr = DAG.getRegister(StackReg, getPointerTy());
972
973     // The last register argument that must be saved is MBlaze::R10
974     const TargetRegisterClass *RC = &MBlaze::GPRRegClass;
975
976     unsigned Begin = getMBlazeRegisterNumbering(MBlaze::R5);
977     unsigned Start = getMBlazeRegisterNumbering(ArgRegEnd+1);
978     unsigned End   = getMBlazeRegisterNumbering(MBlaze::R10);
979     unsigned StackLoc = Start - Begin + 1;
980
981     for (; Start <= End; ++Start, ++StackLoc) {
982       unsigned Reg = getMBlazeRegisterFromNumbering(Start);
983       unsigned LiveReg = MF.addLiveIn(Reg, RC);
984       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
985
986       int FI = MFI->CreateFixedObject(4, 0, true);
987       MBlazeFI->recordStoreVarArgsFI(FI, -(StackLoc*4));
988       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
989       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
990                                        MachinePointerInfo(),
991                                        false, false, 0));
992
993       // Record the frame index of the first variable argument
994       // which is a value necessary to VASTART.
995       if (!MBlazeFI->getVarArgsFrameIndex())
996         MBlazeFI->setVarArgsFrameIndex(FI);
997     }
998   }
999
1000   // All stores are grouped in one node to allow the matching between
1001   // the size of Ins and InVals. This only happens when on varg functions
1002   if (!OutChains.empty()) {
1003     OutChains.push_back(Chain);
1004     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1005                         &OutChains[0], OutChains.size());
1006   }
1007
1008   return Chain;
1009 }
1010
1011 //===----------------------------------------------------------------------===//
1012 //               Return Value Calling Convention Implementation
1013 //===----------------------------------------------------------------------===//
1014
1015 SDValue MBlazeTargetLowering::
1016 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1017             const SmallVectorImpl<ISD::OutputArg> &Outs,
1018             const SmallVectorImpl<SDValue> &OutVals,
1019             DebugLoc dl, SelectionDAG &DAG) const {
1020   // CCValAssign - represent the assignment of
1021   // the return value to a location
1022   SmallVector<CCValAssign, 16> RVLocs;
1023
1024   // CCState - Info about the registers and stack slot.
1025   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1026                  getTargetMachine(), RVLocs, *DAG.getContext());
1027
1028   // Analize return values.
1029   CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
1030
1031   SDValue Flag;
1032   SmallVector<SDValue, 4> RetOps(1, Chain);
1033
1034   // If this function is using the interrupt_handler calling convention
1035   // then use "rtid r14, 0" otherwise use "rtsd r15, 8"
1036   unsigned Ret = (CallConv == CallingConv::MBLAZE_INTR) ? MBlazeISD::IRet
1037                                                         : MBlazeISD::Ret;
1038   unsigned Reg = (CallConv == CallingConv::MBLAZE_INTR) ? MBlaze::R14
1039                                                         : MBlaze::R15;
1040   RetOps.push_back(DAG.getRegister(Reg, MVT::i32));
1041
1042
1043   // Copy the result values into the output registers.
1044   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1045     CCValAssign &VA = RVLocs[i];
1046     assert(VA.isRegLoc() && "Can only return in registers!");
1047
1048     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1049                              OutVals[i], Flag);
1050
1051     // guarantee that all emitted copies are
1052     // stuck together, avoiding something bad
1053     Flag = Chain.getValue(1);
1054     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1055   }
1056
1057   RetOps[0] = Chain;  // Update chain.
1058
1059   // Add the flag if we have it.
1060   if (Flag.getNode())
1061     RetOps.push_back(Flag);
1062
1063   return DAG.getNode(Ret, dl, MVT::Other, &RetOps[0], RetOps.size());
1064 }
1065
1066 //===----------------------------------------------------------------------===//
1067 //                           MBlaze Inline Assembly Support
1068 //===----------------------------------------------------------------------===//
1069
1070 /// getConstraintType - Given a constraint letter, return the type of
1071 /// constraint it is for this target.
1072 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
1073 getConstraintType(const std::string &Constraint) const
1074 {
1075   // MBlaze specific constrainy
1076   //
1077   // 'd' : An address register. Equivalent to r.
1078   // 'y' : Equivalent to r; retained for
1079   //       backwards compatibility.
1080   // 'f' : Floating Point registers.
1081   if (Constraint.size() == 1) {
1082     switch (Constraint[0]) {
1083       default : break;
1084       case 'd':
1085       case 'y':
1086       case 'f':
1087         return C_RegisterClass;
1088     }
1089   }
1090   return TargetLowering::getConstraintType(Constraint);
1091 }
1092
1093 /// Examine constraint type and operand type and determine a weight value.
1094 /// This object must already have been set up with the operand type
1095 /// and the current alternative constraint selected.
1096 TargetLowering::ConstraintWeight
1097 MBlazeTargetLowering::getSingleConstraintMatchWeight(
1098     AsmOperandInfo &info, const char *constraint) const {
1099   ConstraintWeight weight = CW_Invalid;
1100   Value *CallOperandVal = info.CallOperandVal;
1101     // If we don't have a value, we can't do a match,
1102     // but allow it at the lowest weight.
1103   if (CallOperandVal == NULL)
1104     return CW_Default;
1105   Type *type = CallOperandVal->getType();
1106   // Look at the constraint type.
1107   switch (*constraint) {
1108   default:
1109     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1110     break;
1111   case 'd':
1112   case 'y':
1113     if (type->isIntegerTy())
1114       weight = CW_Register;
1115     break;
1116   case 'f':
1117     if (type->isFloatTy())
1118       weight = CW_Register;
1119     break;
1120   }
1121   return weight;
1122 }
1123
1124 /// Given a register class constraint, like 'r', if this corresponds directly
1125 /// to an LLVM register class, return a register of 0 and the register class
1126 /// pointer.
1127 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
1128 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
1129   if (Constraint.size() == 1) {
1130     switch (Constraint[0]) {
1131     case 'r':
1132       return std::make_pair(0U, &MBlaze::GPRRegClass);
1133       // TODO: These can't possibly be right, but match what was in
1134       // getRegClassForInlineAsmConstraint.
1135     case 'd':
1136     case 'y':
1137     case 'f':
1138       if (VT == MVT::f32)
1139         return std::make_pair(0U, &MBlaze::GPRRegClass);
1140     }
1141   }
1142   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1143 }
1144
1145 bool MBlazeTargetLowering::
1146 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1147   // The MBlaze target isn't yet aware of offsets.
1148   return false;
1149 }
1150
1151 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1152   return VT != MVT::f32;
1153 }