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