SparcISelLowering.cpp revision 362dd0bef5437f85586c046bc53287b6fbe9c099
1//===-- SparcISelLowering.cpp - Sparc 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 implements the interfaces that Sparc uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SparcISelLowering.h"
16#include "SparcTargetMachine.h"
17#include "llvm/Function.h"
18#include "llvm/CodeGen/CallingConvLower.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/SelectionDAG.h"
24#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25#include "llvm/ADT/VectorExtras.h"
26#include "llvm/Support/ErrorHandling.h"
27using namespace llvm;
28
29
30//===----------------------------------------------------------------------===//
31// Calling Convention Implementation
32//===----------------------------------------------------------------------===//
33
34#include "SparcGenCallingConv.inc"
35
36SDValue
37SparcTargetLowering::LowerReturn(SDValue Chain,
38                                 CallingConv::ID CallConv, bool isVarArg,
39                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
40                                 DebugLoc dl, SelectionDAG &DAG) {
41
42  // CCValAssign - represent the assignment of the return value to locations.
43  SmallVector<CCValAssign, 16> RVLocs;
44
45  // CCState - Info about the registers and stack slot.
46  CCState CCInfo(CallConv, isVarArg, DAG.getTarget(),
47                 RVLocs, *DAG.getContext());
48
49  // Analize return values.
50  CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
51
52  // If this is the first return lowered for this function, add the regs to the
53  // liveout set for the function.
54  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
55    for (unsigned i = 0; i != RVLocs.size(); ++i)
56      if (RVLocs[i].isRegLoc())
57        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
58  }
59
60  SDValue Flag;
61
62  // Copy the result values into the output registers.
63  for (unsigned i = 0; i != RVLocs.size(); ++i) {
64    CCValAssign &VA = RVLocs[i];
65    assert(VA.isRegLoc() && "Can only return in registers!");
66
67    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
68                             Outs[i].Val, Flag);
69
70    // Guarantee that all emitted copies are stuck together with flags.
71    Flag = Chain.getValue(1);
72  }
73
74  if (Flag.getNode())
75    return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
76  return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain);
77}
78
79/// LowerFormalArguments - V8 uses a very simple ABI, where all values are
80/// passed in either one or two GPRs, including FP values.  TODO: we should
81/// pass FP values in FP registers for fastcc functions.
82SDValue
83SparcTargetLowering::LowerFormalArguments(SDValue Chain,
84                                          CallingConv::ID CallConv, bool isVarArg,
85                                          const SmallVectorImpl<ISD::InputArg>
86                                            &Ins,
87                                          DebugLoc dl, SelectionDAG &DAG,
88                                          SmallVectorImpl<SDValue> &InVals) {
89
90  MachineFunction &MF = DAG.getMachineFunction();
91  MachineRegisterInfo &RegInfo = MF.getRegInfo();
92
93  // Assign locations to all of the incoming arguments.
94  SmallVector<CCValAssign, 16> ArgLocs;
95  CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
96                 ArgLocs, *DAG.getContext());
97  CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
98
99  static const unsigned ArgRegs[] = {
100    SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
101  };
102  const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
103  unsigned ArgOffset = 68;
104
105  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
106    SDValue ArgValue;
107    CCValAssign &VA = ArgLocs[i];
108    // FIXME: We ignore the register assignments of AnalyzeFormalArguments
109    // because it doesn't know how to split a double into two i32 registers.
110    EVT ObjectVT = VA.getValVT();
111    switch (ObjectVT.getSimpleVT().SimpleTy) {
112    default: llvm_unreachable("Unhandled argument type!");
113    case MVT::i1:
114    case MVT::i8:
115    case MVT::i16:
116    case MVT::i32:
117      if (!Ins[i].Used) {                  // Argument is dead.
118        if (CurArgReg < ArgRegEnd) ++CurArgReg;
119        InVals.push_back(DAG.getUNDEF(ObjectVT));
120      } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
121        unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
122        MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
123        SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
124        if (ObjectVT != MVT::i32) {
125          unsigned AssertOp = ISD::AssertSext;
126          Arg = DAG.getNode(AssertOp, dl, MVT::i32, Arg,
127                            DAG.getValueType(ObjectVT));
128          Arg = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Arg);
129        }
130        InVals.push_back(Arg);
131      } else {
132        int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
133                                                            true, false);
134        SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
135        SDValue Load;
136        if (ObjectVT == MVT::i32) {
137          Load = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0,
138                             false, false, 0);
139        } else {
140          ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
141
142          // Sparc is big endian, so add an offset based on the ObjectVT.
143          unsigned Offset = 4-std::max(1U, ObjectVT.getSizeInBits()/8);
144          FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
145                              DAG.getConstant(Offset, MVT::i32));
146          Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
147                                NULL, 0, ObjectVT, false, false, 0);
148          Load = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Load);
149        }
150        InVals.push_back(Load);
151      }
152
153      ArgOffset += 4;
154      break;
155    case MVT::f32:
156      if (!Ins[i].Used) {                  // Argument is dead.
157        if (CurArgReg < ArgRegEnd) ++CurArgReg;
158        InVals.push_back(DAG.getUNDEF(ObjectVT));
159      } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
160        // FP value is passed in an integer register.
161        unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
162        MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
163        SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
164
165        Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Arg);
166        InVals.push_back(Arg);
167      } else {
168        int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
169                                                            true, false);
170        SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
171        SDValue Load = DAG.getLoad(MVT::f32, dl, Chain, FIPtr, NULL, 0,
172                                   false, false, 0);
173        InVals.push_back(Load);
174      }
175      ArgOffset += 4;
176      break;
177
178    case MVT::i64:
179    case MVT::f64:
180      if (!Ins[i].Used) {                // Argument is dead.
181        if (CurArgReg < ArgRegEnd) ++CurArgReg;
182        if (CurArgReg < ArgRegEnd) ++CurArgReg;
183        InVals.push_back(DAG.getUNDEF(ObjectVT));
184      } else {
185        SDValue HiVal;
186        if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
187          unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
188          MF.getRegInfo().addLiveIn(*CurArgReg++, VRegHi);
189          HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
190        } else {
191          int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
192                                                              true, false);
193          SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
194          HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0,
195                              false, false, 0);
196        }
197
198        SDValue LoVal;
199        if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
200          unsigned VRegLo = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
201          MF.getRegInfo().addLiveIn(*CurArgReg++, VRegLo);
202          LoVal = DAG.getCopyFromReg(Chain, dl, VRegLo, MVT::i32);
203        } else {
204          int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4,
205                                                              true, false);
206          SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
207          LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, NULL, 0,
208                              false, false, 0);
209        }
210
211        // Compose the two halves together into an i64 unit.
212        SDValue WholeValue =
213          DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
214
215        // If we want a double, do a bit convert.
216        if (ObjectVT == MVT::f64)
217          WholeValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, WholeValue);
218
219        InVals.push_back(WholeValue);
220      }
221      ArgOffset += 8;
222      break;
223    }
224  }
225
226  // Store remaining ArgRegs to the stack if this is a varargs function.
227  if (isVarArg) {
228    // Remember the vararg offset for the va_start implementation.
229    VarArgsFrameOffset = ArgOffset;
230
231    std::vector<SDValue> OutChains;
232
233    for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
234      unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
235      MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
236      SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
237
238      int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
239                                                          true, false);
240      SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
241
242      OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr, NULL, 0,
243                                       false, false, 0));
244      ArgOffset += 4;
245    }
246
247    if (!OutChains.empty()) {
248      OutChains.push_back(Chain);
249      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
250                          &OutChains[0], OutChains.size());
251    }
252  }
253
254  return Chain;
255}
256
257SDValue
258SparcTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
259                               CallingConv::ID CallConv, bool isVarArg,
260                               bool &isTailCall,
261                               const SmallVectorImpl<ISD::OutputArg> &Outs,
262                               const SmallVectorImpl<ISD::InputArg> &Ins,
263                               DebugLoc dl, SelectionDAG &DAG,
264                               SmallVectorImpl<SDValue> &InVals) {
265  // Sparc target does not yet support tail call optimization.
266  isTailCall = false;
267
268#if 0
269  // Analyze operands of the call, assigning locations to each operand.
270  SmallVector<CCValAssign, 16> ArgLocs;
271  CCState CCInfo(CallConv, isVarArg, DAG.getTarget(), ArgLocs);
272  CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
273
274  // Get the size of the outgoing arguments stack space requirement.
275  unsigned ArgsSize = CCInfo.getNextStackOffset();
276  // FIXME: We can't use this until f64 is known to take two GPRs.
277#else
278  (void)CC_Sparc32;
279
280  // Count the size of the outgoing arguments.
281  unsigned ArgsSize = 0;
282  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
283    switch (Outs[i].Val.getValueType().getSimpleVT().SimpleTy) {
284      default: llvm_unreachable("Unknown value type!");
285      case MVT::i1:
286      case MVT::i8:
287      case MVT::i16:
288      case MVT::i32:
289      case MVT::f32:
290        ArgsSize += 4;
291        break;
292      case MVT::i64:
293      case MVT::f64:
294        ArgsSize += 8;
295        break;
296    }
297  }
298  if (ArgsSize > 4*6)
299    ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
300  else
301    ArgsSize = 0;
302#endif
303
304  // Keep stack frames 8-byte aligned.
305  ArgsSize = (ArgsSize+7) & ~7;
306
307  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
308
309  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
310  SmallVector<SDValue, 8> MemOpChains;
311
312#if 0
313  // Walk the register/memloc assignments, inserting copies/loads.
314  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
315    CCValAssign &VA = ArgLocs[i];
316    SDValue Arg = Outs[i].Val;
317
318    // Promote the value if needed.
319    switch (VA.getLocInfo()) {
320    default: llvm_unreachable("Unknown loc info!");
321    case CCValAssign::Full: break;
322    case CCValAssign::SExt:
323      Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
324      break;
325    case CCValAssign::ZExt:
326      Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
327      break;
328    case CCValAssign::AExt:
329      Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
330      break;
331    }
332
333    // Arguments that can be passed on register must be kept at
334    // RegsToPass vector
335    if (VA.isRegLoc()) {
336      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
337      continue;
338    }
339
340    assert(VA.isMemLoc());
341
342    // Create a store off the stack pointer for this argument.
343    SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
344    // FIXME: VERIFY THAT 68 IS RIGHT.
345    SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+68);
346    PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
347    MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0,
348                                       false, false, 0));
349  }
350
351#else
352  static const unsigned ArgRegs[] = {
353    SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
354  };
355  unsigned ArgOffset = 68;
356
357  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
358    SDValue Val = Outs[i].Val;
359    EVT ObjectVT = Val.getValueType();
360    SDValue ValToStore(0, 0);
361    unsigned ObjSize;
362    switch (ObjectVT.getSimpleVT().SimpleTy) {
363    default: llvm_unreachable("Unhandled argument type!");
364    case MVT::i32:
365      ObjSize = 4;
366
367      if (RegsToPass.size() >= 6) {
368        ValToStore = Val;
369      } else {
370        RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
371      }
372      break;
373    case MVT::f32:
374      ObjSize = 4;
375      if (RegsToPass.size() >= 6) {
376        ValToStore = Val;
377      } else {
378        // Convert this to a FP value in an int reg.
379        Val = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Val);
380        RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
381      }
382      break;
383    case MVT::f64: {
384      ObjSize = 8;
385      if (RegsToPass.size() >= 6) {
386        ValToStore = Val;    // Whole thing is passed in memory.
387        break;
388      }
389
390      // Break into top and bottom parts by storing to the stack and loading
391      // out the parts as integers.  Top part goes in a reg.
392      SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
393      SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
394                                   Val, StackPtr, NULL, 0,
395                                   false, false, 0);
396      // Sparc is big-endian, so the high part comes first.
397      SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr, NULL, 0,
398                               false, false, 0);
399      // Increment the pointer to the other half.
400      StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
401                             DAG.getIntPtrConstant(4));
402      // Load the low part.
403      SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr, NULL, 0,
404                               false, false, 0);
405
406      RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
407
408      if (RegsToPass.size() >= 6) {
409        ValToStore = Lo;
410        ArgOffset += 4;
411        ObjSize = 4;
412      } else {
413        RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
414      }
415      break;
416    }
417    case MVT::i64: {
418      ObjSize = 8;
419      if (RegsToPass.size() >= 6) {
420        ValToStore = Val;    // Whole thing is passed in memory.
421        break;
422      }
423
424      // Split the value into top and bottom part.  Top part goes in a reg.
425      SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
426                                 DAG.getConstant(1, MVT::i32));
427      SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
428                                 DAG.getConstant(0, MVT::i32));
429      RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
430
431      if (RegsToPass.size() >= 6) {
432        ValToStore = Lo;
433        ArgOffset += 4;
434        ObjSize = 4;
435      } else {
436        RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
437      }
438      break;
439    }
440    }
441
442    if (ValToStore.getNode()) {
443      SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
444      SDValue PtrOff = DAG.getConstant(ArgOffset, MVT::i32);
445      PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
446      MemOpChains.push_back(DAG.getStore(Chain, dl, ValToStore,
447                                         PtrOff, NULL, 0,
448                                         false, false, 0));
449    }
450    ArgOffset += ObjSize;
451  }
452#endif
453
454  // Emit all stores, make sure the occur before any copies into physregs.
455  if (!MemOpChains.empty())
456    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
457                        &MemOpChains[0], MemOpChains.size());
458
459  // Build a sequence of copy-to-reg nodes chained together with token
460  // chain and flag operands which copy the outgoing args into registers.
461  // The InFlag in necessary since all emited instructions must be
462  // stuck together.
463  SDValue InFlag;
464  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
465    unsigned Reg = RegsToPass[i].first;
466    // Remap I0->I7 -> O0->O7.
467    if (Reg >= SP::I0 && Reg <= SP::I7)
468      Reg = Reg-SP::I0+SP::O0;
469
470    Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
471    InFlag = Chain.getValue(1);
472  }
473
474  // If the callee is a GlobalAddress node (quite common, every direct call is)
475  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
476  // Likewise ExternalSymbol -> TargetExternalSymbol.
477  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
478    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
479  else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
480    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
481
482  std::vector<EVT> NodeTys;
483  NodeTys.push_back(MVT::Other);   // Returns a chain
484  NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
485  SDValue Ops[] = { Chain, Callee, InFlag };
486  Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, Ops, InFlag.getNode() ? 3 : 2);
487  InFlag = Chain.getValue(1);
488
489  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
490                             DAG.getIntPtrConstant(0, true), InFlag);
491  InFlag = Chain.getValue(1);
492
493  // Assign locations to each value returned by this call.
494  SmallVector<CCValAssign, 16> RVLocs;
495  CCState RVInfo(CallConv, isVarArg, DAG.getTarget(),
496                 RVLocs, *DAG.getContext());
497
498  RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
499
500  // Copy all of the result registers out of their specified physreg.
501  for (unsigned i = 0; i != RVLocs.size(); ++i) {
502    unsigned Reg = RVLocs[i].getLocReg();
503
504    // Remap I0->I7 -> O0->O7.
505    if (Reg >= SP::I0 && Reg <= SP::I7)
506      Reg = Reg-SP::I0+SP::O0;
507
508    Chain = DAG.getCopyFromReg(Chain, dl, Reg,
509                               RVLocs[i].getValVT(), InFlag).getValue(1);
510    InFlag = Chain.getValue(2);
511    InVals.push_back(Chain.getValue(0));
512  }
513
514  return Chain;
515}
516
517
518
519//===----------------------------------------------------------------------===//
520// TargetLowering Implementation
521//===----------------------------------------------------------------------===//
522
523/// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
524/// condition.
525static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
526  switch (CC) {
527  default: llvm_unreachable("Unknown integer condition code!");
528  case ISD::SETEQ:  return SPCC::ICC_E;
529  case ISD::SETNE:  return SPCC::ICC_NE;
530  case ISD::SETLT:  return SPCC::ICC_L;
531  case ISD::SETGT:  return SPCC::ICC_G;
532  case ISD::SETLE:  return SPCC::ICC_LE;
533  case ISD::SETGE:  return SPCC::ICC_GE;
534  case ISD::SETULT: return SPCC::ICC_CS;
535  case ISD::SETULE: return SPCC::ICC_LEU;
536  case ISD::SETUGT: return SPCC::ICC_GU;
537  case ISD::SETUGE: return SPCC::ICC_CC;
538  }
539}
540
541/// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
542/// FCC condition.
543static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
544  switch (CC) {
545  default: llvm_unreachable("Unknown fp condition code!");
546  case ISD::SETEQ:
547  case ISD::SETOEQ: return SPCC::FCC_E;
548  case ISD::SETNE:
549  case ISD::SETUNE: return SPCC::FCC_NE;
550  case ISD::SETLT:
551  case ISD::SETOLT: return SPCC::FCC_L;
552  case ISD::SETGT:
553  case ISD::SETOGT: return SPCC::FCC_G;
554  case ISD::SETLE:
555  case ISD::SETOLE: return SPCC::FCC_LE;
556  case ISD::SETGE:
557  case ISD::SETOGE: return SPCC::FCC_GE;
558  case ISD::SETULT: return SPCC::FCC_UL;
559  case ISD::SETULE: return SPCC::FCC_ULE;
560  case ISD::SETUGT: return SPCC::FCC_UG;
561  case ISD::SETUGE: return SPCC::FCC_UGE;
562  case ISD::SETUO:  return SPCC::FCC_U;
563  case ISD::SETO:   return SPCC::FCC_O;
564  case ISD::SETONE: return SPCC::FCC_LG;
565  case ISD::SETUEQ: return SPCC::FCC_UE;
566  }
567}
568
569SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
570  : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
571
572  // Set up the register classes.
573  addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
574  addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
575  addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
576
577  // Turn FP extload into load/fextend
578  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579  // Sparc doesn't have i1 sign extending load
580  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581  // Turn FP truncstore into trunc + store.
582  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
583
584  // Custom legalize GlobalAddress nodes into LO/HI parts.
585  setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
586  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
587  setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
588
589  // Sparc doesn't have sext_inreg, replace them with shl/sra
590  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
591  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
592  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
593
594  // Sparc has no REM or DIVREM operations.
595  setOperationAction(ISD::UREM, MVT::i32, Expand);
596  setOperationAction(ISD::SREM, MVT::i32, Expand);
597  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
598  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
599
600  // Custom expand fp<->sint
601  setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
602  setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
603
604  // Expand fp<->uint
605  setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
606  setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
607
608  setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
609  setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
610
611  // Sparc has no select or setcc: expand to SELECT_CC.
612  setOperationAction(ISD::SELECT, MVT::i32, Expand);
613  setOperationAction(ISD::SELECT, MVT::f32, Expand);
614  setOperationAction(ISD::SELECT, MVT::f64, Expand);
615  setOperationAction(ISD::SETCC, MVT::i32, Expand);
616  setOperationAction(ISD::SETCC, MVT::f32, Expand);
617  setOperationAction(ISD::SETCC, MVT::f64, Expand);
618
619  // Sparc doesn't have BRCOND either, it has BR_CC.
620  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
621  setOperationAction(ISD::BRIND, MVT::Other, Expand);
622  setOperationAction(ISD::BR_JT, MVT::Other, Expand);
623  setOperationAction(ISD::BR_CC, MVT::i32, Custom);
624  setOperationAction(ISD::BR_CC, MVT::f32, Custom);
625  setOperationAction(ISD::BR_CC, MVT::f64, Custom);
626
627  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
628  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
629  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
630
631  // SPARC has no intrinsics for these particular operations.
632  setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
633
634  setOperationAction(ISD::FSIN , MVT::f64, Expand);
635  setOperationAction(ISD::FCOS , MVT::f64, Expand);
636  setOperationAction(ISD::FREM , MVT::f64, Expand);
637  setOperationAction(ISD::FSIN , MVT::f32, Expand);
638  setOperationAction(ISD::FCOS , MVT::f32, Expand);
639  setOperationAction(ISD::FREM , MVT::f32, Expand);
640  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
641  setOperationAction(ISD::CTTZ , MVT::i32, Expand);
642  setOperationAction(ISD::CTLZ , MVT::i32, Expand);
643  setOperationAction(ISD::ROTL , MVT::i32, Expand);
644  setOperationAction(ISD::ROTR , MVT::i32, Expand);
645  setOperationAction(ISD::BSWAP, MVT::i32, Expand);
646  setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647  setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648  setOperationAction(ISD::FPOW , MVT::f64, Expand);
649  setOperationAction(ISD::FPOW , MVT::f32, Expand);
650
651  setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
652  setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
653  setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
654
655  // FIXME: Sparc provides these multiplies, but we don't have them yet.
656  setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
657  setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
658
659  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
660
661  // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
662  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
663  // VAARG needs to be lowered to not do unaligned accesses for doubles.
664  setOperationAction(ISD::VAARG             , MVT::Other, Custom);
665
666  // Use the default implementation.
667  setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
668  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
669  setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
670  setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
671  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
672
673  // No debug info support yet.
674  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
675
676  setStackPointerRegisterToSaveRestore(SP::O6);
677
678  if (TM.getSubtarget<SparcSubtarget>().isV9())
679    setOperationAction(ISD::CTPOP, MVT::i32, Legal);
680
681  computeRegisterProperties();
682}
683
684const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
685  switch (Opcode) {
686  default: return 0;
687  case SPISD::CMPICC:     return "SPISD::CMPICC";
688  case SPISD::CMPFCC:     return "SPISD::CMPFCC";
689  case SPISD::BRICC:      return "SPISD::BRICC";
690  case SPISD::BRFCC:      return "SPISD::BRFCC";
691  case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
692  case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
693  case SPISD::Hi:         return "SPISD::Hi";
694  case SPISD::Lo:         return "SPISD::Lo";
695  case SPISD::FTOI:       return "SPISD::FTOI";
696  case SPISD::ITOF:       return "SPISD::ITOF";
697  case SPISD::CALL:       return "SPISD::CALL";
698  case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
699  }
700}
701
702/// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
703/// be zero. Op is expected to be a target specific node. Used by DAG
704/// combiner.
705void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
706                                                         const APInt &Mask,
707                                                         APInt &KnownZero,
708                                                         APInt &KnownOne,
709                                                         const SelectionDAG &DAG,
710                                                         unsigned Depth) const {
711  APInt KnownZero2, KnownOne2;
712  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
713
714  switch (Op.getOpcode()) {
715  default: break;
716  case SPISD::SELECT_ICC:
717  case SPISD::SELECT_FCC:
718    DAG.ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne,
719                          Depth+1);
720    DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2,
721                          Depth+1);
722    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
723    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
724
725    // Only known if known in both the LHS and RHS.
726    KnownOne &= KnownOne2;
727    KnownZero &= KnownZero2;
728    break;
729  }
730}
731
732// Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
733// set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
734static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
735                             ISD::CondCode CC, unsigned &SPCC) {
736  if (isa<ConstantSDNode>(RHS) &&
737      cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
738      CC == ISD::SETNE &&
739      ((LHS.getOpcode() == SPISD::SELECT_ICC &&
740        LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
741       (LHS.getOpcode() == SPISD::SELECT_FCC &&
742        LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
743      isa<ConstantSDNode>(LHS.getOperand(0)) &&
744      isa<ConstantSDNode>(LHS.getOperand(1)) &&
745      cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
746      cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
747    SDValue CMPCC = LHS.getOperand(3);
748    SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
749    LHS = CMPCC.getOperand(0);
750    RHS = CMPCC.getOperand(1);
751  }
752}
753
754SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
755                                                SelectionDAG &DAG) {
756  GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
757  // FIXME there isn't really any debug info here
758  DebugLoc dl = Op.getDebugLoc();
759  SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
760  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
761  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
762
763  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
764    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
765
766  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
767                                   getPointerTy());
768  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
769  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
770                                GlobalBase, RelAddr);
771  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
772                     AbsAddr, NULL, 0, false, false, 0);
773}
774
775SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
776                                               SelectionDAG &DAG) {
777  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
778  // FIXME there isn't really any debug info here
779  DebugLoc dl = Op.getDebugLoc();
780  Constant *C = N->getConstVal();
781  SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
782  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
783  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
784  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
785    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
786
787  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
788                                   getPointerTy());
789  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
790  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
791                                GlobalBase, RelAddr);
792  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
793                     AbsAddr, NULL, 0, false, false, 0);
794}
795
796static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
797  DebugLoc dl = Op.getDebugLoc();
798  // Convert the fp value to integer in an FP register.
799  assert(Op.getValueType() == MVT::i32);
800  Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
801  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
802}
803
804static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
805  DebugLoc dl = Op.getDebugLoc();
806  assert(Op.getOperand(0).getValueType() == MVT::i32);
807  SDValue Tmp = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
808  // Convert the int value to FP in an FP register.
809  return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
810}
811
812static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
813  SDValue Chain = Op.getOperand(0);
814  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
815  SDValue LHS = Op.getOperand(2);
816  SDValue RHS = Op.getOperand(3);
817  SDValue Dest = Op.getOperand(4);
818  DebugLoc dl = Op.getDebugLoc();
819  unsigned Opc, SPCC = ~0U;
820
821  // If this is a br_cc of a "setcc", and if the setcc got lowered into
822  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
823  LookThroughSetCC(LHS, RHS, CC, SPCC);
824
825  // Get the condition flag.
826  SDValue CompareFlag;
827  if (LHS.getValueType() == MVT::i32) {
828    std::vector<EVT> VTs;
829    VTs.push_back(MVT::i32);
830    VTs.push_back(MVT::Flag);
831    SDValue Ops[2] = { LHS, RHS };
832    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
833    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
834    Opc = SPISD::BRICC;
835  } else {
836    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Flag, LHS, RHS);
837    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
838    Opc = SPISD::BRFCC;
839  }
840  return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
841                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
842}
843
844static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
845  SDValue LHS = Op.getOperand(0);
846  SDValue RHS = Op.getOperand(1);
847  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
848  SDValue TrueVal = Op.getOperand(2);
849  SDValue FalseVal = Op.getOperand(3);
850  DebugLoc dl = Op.getDebugLoc();
851  unsigned Opc, SPCC = ~0U;
852
853  // If this is a select_cc of a "setcc", and if the setcc got lowered into
854  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
855  LookThroughSetCC(LHS, RHS, CC, SPCC);
856
857  SDValue CompareFlag;
858  if (LHS.getValueType() == MVT::i32) {
859    std::vector<EVT> VTs;
860    VTs.push_back(LHS.getValueType());   // subcc returns a value
861    VTs.push_back(MVT::Flag);
862    SDValue Ops[2] = { LHS, RHS };
863    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
864    Opc = SPISD::SELECT_ICC;
865    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
866  } else {
867    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Flag, LHS, RHS);
868    Opc = SPISD::SELECT_FCC;
869    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
870  }
871  return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
872                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
873}
874
875static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
876                              SparcTargetLowering &TLI) {
877  // vastart just stores the address of the VarArgsFrameIndex slot into the
878  // memory location argument.
879  DebugLoc dl = Op.getDebugLoc();
880  SDValue Offset = DAG.getNode(ISD::ADD, dl, MVT::i32,
881                                 DAG.getRegister(SP::I6, MVT::i32),
882                                 DAG.getConstant(TLI.getVarArgsFrameOffset(),
883                                                 MVT::i32));
884  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
885  return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1), SV, 0,
886                      false, false, 0);
887}
888
889static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
890  SDNode *Node = Op.getNode();
891  EVT VT = Node->getValueType(0);
892  SDValue InChain = Node->getOperand(0);
893  SDValue VAListPtr = Node->getOperand(1);
894  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
895  DebugLoc dl = Node->getDebugLoc();
896  SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr, SV, 0,
897                               false, false, 0);
898  // Increment the pointer, VAList, to the next vaarg
899  SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
900                                  DAG.getConstant(VT.getSizeInBits()/8,
901                                                  MVT::i32));
902  // Store the incremented VAList to the legalized pointer
903  InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
904                         VAListPtr, SV, 0, false, false, 0);
905  // Load the actual argument out of the pointer VAList, unless this is an
906  // f64 load.
907  if (VT != MVT::f64)
908    return DAG.getLoad(VT, dl, InChain, VAList, NULL, 0, false, false, 0);
909
910  // Otherwise, load it as i64, then do a bitconvert.
911  SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, NULL, 0,
912                          false, false, 0);
913
914  // Bit-Convert the value to f64.
915  SDValue Ops[2] = {
916    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, V),
917    V.getValue(1)
918  };
919  return DAG.getMergeValues(Ops, 2, dl);
920}
921
922static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
923  SDValue Chain = Op.getOperand(0);  // Legalize the chain.
924  SDValue Size  = Op.getOperand(1);  // Legalize the size.
925  DebugLoc dl = Op.getDebugLoc();
926
927  unsigned SPReg = SP::O6;
928  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
929  SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
930  Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
931
932  // The resultant pointer is actually 16 words from the bottom of the stack,
933  // to provide a register spill area.
934  SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
935                                 DAG.getConstant(96, MVT::i32));
936  SDValue Ops[2] = { NewVal, Chain };
937  return DAG.getMergeValues(Ops, 2, dl);
938}
939
940
941SDValue SparcTargetLowering::
942LowerOperation(SDValue Op, SelectionDAG &DAG) {
943  switch (Op.getOpcode()) {
944  default: llvm_unreachable("Should not custom lower this!");
945  // Frame & Return address.  Currently unimplemented
946  case ISD::RETURNADDR: return SDValue();
947  case ISD::FRAMEADDR:  return SDValue();
948  case ISD::GlobalTLSAddress:
949    llvm_unreachable("TLS not implemented for Sparc.");
950  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
951  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
952  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
953  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
954  case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
955  case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
956  case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
957  case ISD::VAARG:              return LowerVAARG(Op, DAG);
958  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
959  }
960}
961
962MachineBasicBlock *
963SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
964                                                 MachineBasicBlock *BB,
965                   DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
966  const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
967  unsigned BROpcode;
968  unsigned CC;
969  DebugLoc dl = MI->getDebugLoc();
970  // Figure out the conditional branch opcode to use for this select_cc.
971  switch (MI->getOpcode()) {
972  default: llvm_unreachable("Unknown SELECT_CC!");
973  case SP::SELECT_CC_Int_ICC:
974  case SP::SELECT_CC_FP_ICC:
975  case SP::SELECT_CC_DFP_ICC:
976    BROpcode = SP::BCOND;
977    break;
978  case SP::SELECT_CC_Int_FCC:
979  case SP::SELECT_CC_FP_FCC:
980  case SP::SELECT_CC_DFP_FCC:
981    BROpcode = SP::FBCOND;
982    break;
983  }
984
985  CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
986
987  // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
988  // control-flow pattern.  The incoming instruction knows the destination vreg
989  // to set, the condition code register to branch on, the true/false values to
990  // select between, and a branch opcode to use.
991  const BasicBlock *LLVM_BB = BB->getBasicBlock();
992  MachineFunction::iterator It = BB;
993  ++It;
994
995  //  thisMBB:
996  //  ...
997  //   TrueVal = ...
998  //   [f]bCC copy1MBB
999  //   fallthrough --> copy0MBB
1000  MachineBasicBlock *thisMBB = BB;
1001  MachineFunction *F = BB->getParent();
1002  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1003  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1004  BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1005  F->insert(It, copy0MBB);
1006  F->insert(It, sinkMBB);
1007  // Update machine-CFG edges by first adding all successors of the current
1008  // block to the new block which will contain the Phi node for the select.
1009  // Also inform sdisel of the edge changes.
1010  for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1011         E = BB->succ_end(); I != E; ++I) {
1012    EM->insert(std::make_pair(*I, sinkMBB));
1013    sinkMBB->addSuccessor(*I);
1014  }
1015  // Next, remove all successors of the current block, and add the true
1016  // and fallthrough blocks as its successors.
1017  while (!BB->succ_empty())
1018    BB->removeSuccessor(BB->succ_begin());
1019  // Next, add the true and fallthrough blocks as its successors.
1020  BB->addSuccessor(copy0MBB);
1021  BB->addSuccessor(sinkMBB);
1022
1023  //  copy0MBB:
1024  //   %FalseValue = ...
1025  //   # fallthrough to sinkMBB
1026  BB = copy0MBB;
1027
1028  // Update machine-CFG edges
1029  BB->addSuccessor(sinkMBB);
1030
1031  //  sinkMBB:
1032  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1033  //  ...
1034  BB = sinkMBB;
1035  BuildMI(BB, dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1036    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1037    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1038
1039  F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1040  return BB;
1041}
1042
1043//===----------------------------------------------------------------------===//
1044//                         Sparc Inline Assembly Support
1045//===----------------------------------------------------------------------===//
1046
1047/// getConstraintType - Given a constraint letter, return the type of
1048/// constraint it is for this target.
1049SparcTargetLowering::ConstraintType
1050SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1051  if (Constraint.size() == 1) {
1052    switch (Constraint[0]) {
1053    default:  break;
1054    case 'r': return C_RegisterClass;
1055    }
1056  }
1057
1058  return TargetLowering::getConstraintType(Constraint);
1059}
1060
1061std::pair<unsigned, const TargetRegisterClass*>
1062SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1063                                                  EVT VT) const {
1064  if (Constraint.size() == 1) {
1065    switch (Constraint[0]) {
1066    case 'r':
1067      return std::make_pair(0U, SP::IntRegsRegisterClass);
1068    }
1069  }
1070
1071  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1072}
1073
1074std::vector<unsigned> SparcTargetLowering::
1075getRegClassForInlineAsmConstraint(const std::string &Constraint,
1076                                  EVT VT) const {
1077  if (Constraint.size() != 1)
1078    return std::vector<unsigned>();
1079
1080  switch (Constraint[0]) {
1081  default: break;
1082  case 'r':
1083    return make_vector<unsigned>(SP::L0, SP::L1, SP::L2, SP::L3,
1084                                 SP::L4, SP::L5, SP::L6, SP::L7,
1085                                 SP::I0, SP::I1, SP::I2, SP::I3,
1086                                 SP::I4, SP::I5,
1087                                 SP::O0, SP::O1, SP::O2, SP::O3,
1088                                 SP::O4, SP::O5, SP::O7, 0);
1089  }
1090
1091  return std::vector<unsigned>();
1092}
1093
1094bool
1095SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1096  // The Sparc target isn't yet aware of offsets.
1097  return false;
1098}
1099
1100/// getFunctionAlignment - Return the Log2 alignment of this function.
1101unsigned SparcTargetLowering::getFunctionAlignment(const Function *) const {
1102  return 2;
1103}
1104