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