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