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