Implement LowerReturn_64 for SPARC v9.
[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 "SparcMachineFunctionInfo.h"
17 #include "SparcTargetMachine.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ErrorHandling.h"
29 using namespace llvm;
30
31
32 //===----------------------------------------------------------------------===//
33 // Calling Convention Implementation
34 //===----------------------------------------------------------------------===//
35
36 static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
37                                  MVT &LocVT, CCValAssign::LocInfo &LocInfo,
38                                  ISD::ArgFlagsTy &ArgFlags, CCState &State)
39 {
40   assert (ArgFlags.isSRet());
41
42   //Assign SRet argument
43   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
44                                          0,
45                                          LocVT, LocInfo));
46   return true;
47 }
48
49 static bool CC_Sparc_Assign_f64(unsigned &ValNo, MVT &ValVT,
50                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
51                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
52 {
53   static const uint16_t RegList[] = {
54     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
55   };
56   //Try to get first reg
57   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
58     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
59   } else {
60     //Assign whole thing in stack
61     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
62                                            State.AllocateStack(8,4),
63                                            LocVT, LocInfo));
64     return true;
65   }
66
67   //Try to get second reg
68   if (unsigned Reg = State.AllocateReg(RegList, 6))
69     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
70   else
71     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
72                                            State.AllocateStack(4,4),
73                                            LocVT, LocInfo));
74   return true;
75 }
76
77 // Allocate a full-sized argument for the 64-bit ABI.
78 static bool CC_Sparc64_Full(unsigned &ValNo, MVT &ValVT,
79                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
80                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
81   assert((LocVT == MVT::f32 || LocVT.getSizeInBits() == 64) &&
82          "Can't handle non-64 bits locations");
83
84   // Stack space is allocated for all arguments starting from [%fp+BIAS+128].
85   unsigned Offset = State.AllocateStack(8, 8);
86   unsigned Reg = 0;
87
88   if (LocVT == MVT::i64 && Offset < 6*8)
89     // Promote integers to %i0-%i5.
90     Reg = SP::I0 + Offset/8;
91   else if (LocVT == MVT::f64 && Offset < 16*8)
92     // Promote doubles to %d0-%d30. (Which LLVM calls D0-D15).
93     Reg = SP::D0 + Offset/8;
94   else if (LocVT == MVT::f32 && Offset < 16*8)
95     // Promote floats to %f1, %f3, ...
96     Reg = SP::F1 + Offset/4;
97
98   // Promote to register when possible, otherwise use the stack slot.
99   if (Reg) {
100     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
101     return true;
102   }
103
104   // This argument goes on the stack in an 8-byte slot.
105   // When passing floats, LocVT is smaller than 8 bytes. Adjust the offset to
106   // the right-aligned float. The first 4 bytes of the stack slot are undefined.
107   if (LocVT == MVT::f32)
108     Offset += 4;
109
110   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
111   return true;
112 }
113
114 // Allocate a half-sized argument for the 64-bit ABI.
115 //
116 // This is used when passing { float, int } structs by value in registers.
117 static bool CC_Sparc64_Half(unsigned &ValNo, MVT &ValVT,
118                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
119                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
120   assert(LocVT.getSizeInBits() == 32 && "Can't handle non-32 bits locations");
121   unsigned Offset = State.AllocateStack(4, 4);
122
123   if (LocVT == MVT::f32 && Offset < 16*8) {
124     // Promote floats to %f0-%f31.
125     State.addLoc(CCValAssign::getReg(ValNo, ValVT, SP::F0 + Offset/4,
126                                      LocVT, LocInfo));
127     return true;
128   }
129
130   if (LocVT == MVT::i32 && Offset < 6*8) {
131     // Promote integers to %i0-%i5, using half the register.
132     unsigned Reg = SP::I0 + Offset/8;
133     LocVT = MVT::i64;
134     LocInfo = CCValAssign::AExt;
135
136     // Set the Custom bit if this i32 goes in the high bits of a register.
137     if (Offset % 8 == 0)
138       State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg,
139                                              LocVT, LocInfo));
140     else
141       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
142     return true;
143   }
144
145   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
146   return true;
147 }
148
149 #include "SparcGenCallingConv.inc"
150
151 SDValue
152 SparcTargetLowering::LowerReturn(SDValue Chain,
153                                  CallingConv::ID CallConv, bool IsVarArg,
154                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
155                                  const SmallVectorImpl<SDValue> &OutVals,
156                                  DebugLoc DL, SelectionDAG &DAG) const {
157   if (Subtarget->is64Bit())
158     return LowerReturn_64(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
159   return LowerReturn_32(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
160 }
161
162 SDValue
163 SparcTargetLowering::LowerReturn_32(SDValue Chain,
164                                     CallingConv::ID CallConv, bool IsVarArg,
165                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
166                                     const SmallVectorImpl<SDValue> &OutVals,
167                                     DebugLoc DL, SelectionDAG &DAG) const {
168   MachineFunction &MF = DAG.getMachineFunction();
169
170   // CCValAssign - represent the assignment of the return value to locations.
171   SmallVector<CCValAssign, 16> RVLocs;
172
173   // CCState - Info about the registers and stack slot.
174   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
175                  DAG.getTarget(), RVLocs, *DAG.getContext());
176
177   // Analyze return values.
178   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
179
180   SDValue Flag;
181   SmallVector<SDValue, 4> RetOps(1, Chain);
182   // Make room for the return address offset.
183   RetOps.push_back(SDValue());
184
185   // Copy the result values into the output registers.
186   for (unsigned i = 0; i != RVLocs.size(); ++i) {
187     CCValAssign &VA = RVLocs[i];
188     assert(VA.isRegLoc() && "Can only return in registers!");
189
190     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(),
191                              OutVals[i], Flag);
192
193     // Guarantee that all emitted copies are stuck together with flags.
194     Flag = Chain.getValue(1);
195     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
196   }
197
198   unsigned RetAddrOffset = 8; //Call Inst + Delay Slot
199   // If the function returns a struct, copy the SRetReturnReg to I0
200   if (MF.getFunction()->hasStructRetAttr()) {
201     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
202     unsigned Reg = SFI->getSRetReturnReg();
203     if (!Reg)
204       llvm_unreachable("sret virtual register not created in the entry block");
205     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
206     Chain = DAG.getCopyToReg(Chain, DL, SP::I0, Val, Flag);
207     Flag = Chain.getValue(1);
208     RetOps.push_back(DAG.getRegister(SP::I0, getPointerTy()));
209     RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
210   }
211
212   RetOps[0] = Chain;  // Update chain.
213   RetOps[1] = DAG.getConstant(RetAddrOffset, MVT::i32);
214
215   // Add the flag if we have it.
216   if (Flag.getNode())
217     RetOps.push_back(Flag);
218
219   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
220                      &RetOps[0], RetOps.size());
221 }
222
223 // Lower return values for the 64-bit ABI.
224 // Return values are passed the exactly the same way as function arguments.
225 SDValue
226 SparcTargetLowering::LowerReturn_64(SDValue Chain,
227                                     CallingConv::ID CallConv, bool IsVarArg,
228                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
229                                     const SmallVectorImpl<SDValue> &OutVals,
230                                     DebugLoc DL, SelectionDAG &DAG) const {
231   // CCValAssign - represent the assignment of the return value to locations.
232   SmallVector<CCValAssign, 16> RVLocs;
233
234   // CCState - Info about the registers and stack slot.
235   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
236                  DAG.getTarget(), RVLocs, *DAG.getContext());
237
238   // Analyze return values.
239   CCInfo.AnalyzeReturn(Outs, CC_Sparc64);
240
241   SDValue Flag;
242   SmallVector<SDValue, 4> RetOps(1, Chain);
243
244   // The second operand on the return instruction is the return address offset.
245   // The return address is always %i7+8 with the 64-bit ABI.
246   RetOps.push_back(DAG.getConstant(8, MVT::i32));
247
248   // Copy the result values into the output registers.
249   for (unsigned i = 0; i != RVLocs.size(); ++i) {
250     CCValAssign &VA = RVLocs[i];
251     assert(VA.isRegLoc() && "Can only return in registers!");
252     SDValue OutVal = OutVals[i];
253
254     // Integer return values must be sign or zero extended by the callee.
255     switch (VA.getLocInfo()) {
256     case CCValAssign::SExt:
257       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
258       break;
259     case CCValAssign::ZExt:
260       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
261       break;
262     case CCValAssign::AExt:
263       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
264     default:
265       break;
266     }
267
268     // The custom bit on an i32 return value indicates that it should be passed
269     // in the high bits of the register.
270     if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
271       OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
272                            DAG.getConstant(32, MVT::i32));
273
274       // The next value may go in the low bits of the same register.
275       // Handle both at once.
276       if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
277         SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
278         OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
279         // Skip the next value, it's already done.
280         ++i;
281       }
282     }
283
284     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
285
286     // Guarantee that all emitted copies are stuck together with flags.
287     Flag = Chain.getValue(1);
288     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
289   }
290
291   RetOps[0] = Chain;  // Update chain.
292
293   // Add the flag if we have it.
294   if (Flag.getNode())
295     RetOps.push_back(Flag);
296
297   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
298                      &RetOps[0], RetOps.size());
299 }
300
301 SDValue SparcTargetLowering::
302 LowerFormalArguments(SDValue Chain,
303                      CallingConv::ID CallConv,
304                      bool IsVarArg,
305                      const SmallVectorImpl<ISD::InputArg> &Ins,
306                      DebugLoc DL,
307                      SelectionDAG &DAG,
308                      SmallVectorImpl<SDValue> &InVals) const {
309   if (Subtarget->is64Bit())
310     return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
311                                    DL, DAG, InVals);
312   return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
313                                  DL, DAG, InVals);
314 }
315
316 /// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
317 /// passed in either one or two GPRs, including FP values.  TODO: we should
318 /// pass FP values in FP registers for fastcc functions.
319 SDValue SparcTargetLowering::
320 LowerFormalArguments_32(SDValue Chain,
321                         CallingConv::ID CallConv,
322                         bool isVarArg,
323                         const SmallVectorImpl<ISD::InputArg> &Ins,
324                         DebugLoc dl,
325                         SelectionDAG &DAG,
326                         SmallVectorImpl<SDValue> &InVals) const {
327   MachineFunction &MF = DAG.getMachineFunction();
328   MachineRegisterInfo &RegInfo = MF.getRegInfo();
329   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
330
331   // Assign locations to all of the incoming arguments.
332   SmallVector<CCValAssign, 16> ArgLocs;
333   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
334                  getTargetMachine(), ArgLocs, *DAG.getContext());
335   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
336
337   const unsigned StackOffset = 92;
338
339   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
340     CCValAssign &VA = ArgLocs[i];
341
342     if (i == 0  && Ins[i].Flags.isSRet()) {
343       //Get SRet from [%fp+64]
344       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
345       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
346       SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
347                                 MachinePointerInfo(),
348                                 false, false, false, 0);
349       InVals.push_back(Arg);
350       continue;
351     }
352
353     if (VA.isRegLoc()) {
354       if (VA.needsCustom()) {
355         assert(VA.getLocVT() == MVT::f64);
356         unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
357         MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
358         SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
359
360         assert(i+1 < e);
361         CCValAssign &NextVA = ArgLocs[++i];
362
363         SDValue LoVal;
364         if (NextVA.isMemLoc()) {
365           int FrameIdx = MF.getFrameInfo()->
366             CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
367           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
368           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
369                               MachinePointerInfo(),
370                               false, false, false, 0);
371         } else {
372           unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
373                                         &SP::IntRegsRegClass);
374           LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
375         }
376         SDValue WholeValue =
377           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
378         WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
379         InVals.push_back(WholeValue);
380         continue;
381       }
382       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
383       MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
384       SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
385       if (VA.getLocVT() == MVT::f32)
386         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
387       else if (VA.getLocVT() != MVT::i32) {
388         Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
389                           DAG.getValueType(VA.getLocVT()));
390         Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
391       }
392       InVals.push_back(Arg);
393       continue;
394     }
395
396     assert(VA.isMemLoc());
397
398     unsigned Offset = VA.getLocMemOffset()+StackOffset;
399
400     if (VA.needsCustom()) {
401       assert(VA.getValVT() == MVT::f64);
402       //If it is double-word aligned, just load.
403       if (Offset % 8 == 0) {
404         int FI = MF.getFrameInfo()->CreateFixedObject(8,
405                                                       Offset,
406                                                       true);
407         SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
408         SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
409                                    MachinePointerInfo(),
410                                    false,false, false, 0);
411         InVals.push_back(Load);
412         continue;
413       }
414
415       int FI = MF.getFrameInfo()->CreateFixedObject(4,
416                                                     Offset,
417                                                     true);
418       SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
419       SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
420                                   MachinePointerInfo(),
421                                   false, false, false, 0);
422       int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
423                                                      Offset+4,
424                                                      true);
425       SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
426
427       SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
428                                   MachinePointerInfo(),
429                                   false, false, false, 0);
430
431       SDValue WholeValue =
432         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
433       WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
434       InVals.push_back(WholeValue);
435       continue;
436     }
437
438     int FI = MF.getFrameInfo()->CreateFixedObject(4,
439                                                   Offset,
440                                                   true);
441     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
442     SDValue Load ;
443     if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
444       Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
445                          MachinePointerInfo(),
446                          false, false, false, 0);
447     } else {
448       ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
449       // Sparc is big endian, so add an offset based on the ObjectVT.
450       unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
451       FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
452                           DAG.getConstant(Offset, MVT::i32));
453       Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
454                             MachinePointerInfo(),
455                             VA.getValVT(), false, false,0);
456       Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
457     }
458     InVals.push_back(Load);
459   }
460
461   if (MF.getFunction()->hasStructRetAttr()) {
462     //Copy the SRet Argument to SRetReturnReg
463     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
464     unsigned Reg = SFI->getSRetReturnReg();
465     if (!Reg) {
466       Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
467       SFI->setSRetReturnReg(Reg);
468     }
469     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
470     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
471   }
472
473   // Store remaining ArgRegs to the stack if this is a varargs function.
474   if (isVarArg) {
475     static const uint16_t ArgRegs[] = {
476       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
477     };
478     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
479     const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
480     unsigned ArgOffset = CCInfo.getNextStackOffset();
481     if (NumAllocated == 6)
482       ArgOffset += StackOffset;
483     else {
484       assert(!ArgOffset);
485       ArgOffset = 68+4*NumAllocated;
486     }
487
488     // Remember the vararg offset for the va_start implementation.
489     FuncInfo->setVarArgsFrameOffset(ArgOffset);
490
491     std::vector<SDValue> OutChains;
492
493     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
494       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
495       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
496       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
497
498       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
499                                                           true);
500       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
501
502       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
503                                        MachinePointerInfo(),
504                                        false, false, 0));
505       ArgOffset += 4;
506     }
507
508     if (!OutChains.empty()) {
509       OutChains.push_back(Chain);
510       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
511                           &OutChains[0], OutChains.size());
512     }
513   }
514
515   return Chain;
516 }
517
518 // Lower formal arguments for the 64 bit ABI.
519 SDValue SparcTargetLowering::
520 LowerFormalArguments_64(SDValue Chain,
521                         CallingConv::ID CallConv,
522                         bool IsVarArg,
523                         const SmallVectorImpl<ISD::InputArg> &Ins,
524                         DebugLoc DL,
525                         SelectionDAG &DAG,
526                         SmallVectorImpl<SDValue> &InVals) const {
527   MachineFunction &MF = DAG.getMachineFunction();
528
529   // Analyze arguments according to CC_Sparc64.
530   SmallVector<CCValAssign, 16> ArgLocs;
531   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
532                  getTargetMachine(), ArgLocs, *DAG.getContext());
533   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
534
535   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
536     CCValAssign &VA = ArgLocs[i];
537     if (VA.isRegLoc()) {
538       // This argument is passed in a register.
539       // All integer register arguments are promoted by the caller to i64.
540
541       // Create a virtual register for the promoted live-in value.
542       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
543                                    getRegClassFor(VA.getLocVT()));
544       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
545
546       // Get the high bits for i32 struct elements.
547       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
548         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
549                           DAG.getConstant(32, MVT::i32));
550
551       // The caller promoted the argument, so insert an Assert?ext SDNode so we
552       // won't promote the value again in this function.
553       switch (VA.getLocInfo()) {
554       case CCValAssign::SExt:
555         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
556                           DAG.getValueType(VA.getValVT()));
557         break;
558       case CCValAssign::ZExt:
559         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
560                           DAG.getValueType(VA.getValVT()));
561         break;
562       default:
563         break;
564       }
565
566       // Truncate the register down to the argument type.
567       if (VA.isExtInLoc())
568         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
569
570       InVals.push_back(Arg);
571       continue;
572     }
573
574     // The registers are exhausted. This argument was passed on the stack.
575     assert(VA.isMemLoc());
576     // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
577     // beginning of the arguments area at %fp+BIAS+128.
578     unsigned Offset = VA.getLocMemOffset() + 128;
579     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
580     // Adjust offset for extended arguments, SPARC is big-endian.
581     // The caller will have written the full slot with extended bytes, but we
582     // prefer our own extending loads.
583     if (VA.isExtInLoc())
584       Offset += 8 - ValSize;
585     int FI = MF.getFrameInfo()->CreateFixedObject(ValSize, Offset, true);
586     InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
587                                  DAG.getFrameIndex(FI, getPointerTy()),
588                                  MachinePointerInfo::getFixedStack(FI),
589                                  false, false, false, 0));
590   }
591   return Chain;
592 }
593
594 SDValue
595 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
596                                SmallVectorImpl<SDValue> &InVals) const {
597   SelectionDAG &DAG                     = CLI.DAG;
598   DebugLoc &dl                          = CLI.DL;
599   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
600   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
601   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
602   SDValue Chain                         = CLI.Chain;
603   SDValue Callee                        = CLI.Callee;
604   bool &isTailCall                      = CLI.IsTailCall;
605   CallingConv::ID CallConv              = CLI.CallConv;
606   bool isVarArg                         = CLI.IsVarArg;
607
608   // Sparc target does not yet support tail call optimization.
609   isTailCall = false;
610
611   // Analyze operands of the call, assigning locations to each operand.
612   SmallVector<CCValAssign, 16> ArgLocs;
613   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
614                  DAG.getTarget(), ArgLocs, *DAG.getContext());
615   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
616
617   // Get the size of the outgoing arguments stack space requirement.
618   unsigned ArgsSize = CCInfo.getNextStackOffset();
619
620   // Keep stack frames 8-byte aligned.
621   ArgsSize = (ArgsSize+7) & ~7;
622
623   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
624
625   //Create local copies for byval args.
626   SmallVector<SDValue, 8> ByValArgs;
627   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
628     ISD::ArgFlagsTy Flags = Outs[i].Flags;
629     if (!Flags.isByVal())
630       continue;
631
632     SDValue Arg = OutVals[i];
633     unsigned Size = Flags.getByValSize();
634     unsigned Align = Flags.getByValAlign();
635
636     int FI = MFI->CreateStackObject(Size, Align, false);
637     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
638     SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
639
640     Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
641                           false,        //isVolatile,
642                           (Size <= 32), //AlwaysInline if size <= 32
643                           MachinePointerInfo(), MachinePointerInfo());
644     ByValArgs.push_back(FIPtr);
645   }
646
647   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
648
649   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
650   SmallVector<SDValue, 8> MemOpChains;
651
652   const unsigned StackOffset = 92;
653   bool hasStructRetAttr = false;
654   // Walk the register/memloc assignments, inserting copies/loads.
655   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
656        i != e;
657        ++i, ++realArgIdx) {
658     CCValAssign &VA = ArgLocs[i];
659     SDValue Arg = OutVals[realArgIdx];
660
661     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
662
663     //Use local copy if it is a byval arg.
664     if (Flags.isByVal())
665       Arg = ByValArgs[byvalArgIdx++];
666
667     // Promote the value if needed.
668     switch (VA.getLocInfo()) {
669     default: llvm_unreachable("Unknown loc info!");
670     case CCValAssign::Full: break;
671     case CCValAssign::SExt:
672       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
673       break;
674     case CCValAssign::ZExt:
675       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
676       break;
677     case CCValAssign::AExt:
678       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
679       break;
680     case CCValAssign::BCvt:
681       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
682       break;
683     }
684
685     if (Flags.isSRet()) {
686       assert(VA.needsCustom());
687       // store SRet argument in %sp+64
688       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
689       SDValue PtrOff = DAG.getIntPtrConstant(64);
690       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
691       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
692                                          MachinePointerInfo(),
693                                          false, false, 0));
694       hasStructRetAttr = true;
695       continue;
696     }
697
698     if (VA.needsCustom()) {
699       assert(VA.getLocVT() == MVT::f64);
700
701       if (VA.isMemLoc()) {
702         unsigned Offset = VA.getLocMemOffset() + StackOffset;
703         //if it is double-word aligned, just store.
704         if (Offset % 8 == 0) {
705           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
706           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
707           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
708           MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
709                                              MachinePointerInfo(),
710                                              false, false, 0));
711           continue;
712         }
713       }
714
715       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
716       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
717                                    Arg, StackPtr, MachinePointerInfo(),
718                                    false, false, 0);
719       // Sparc is big-endian, so the high part comes first.
720       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
721                                MachinePointerInfo(), false, false, false, 0);
722       // Increment the pointer to the other half.
723       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
724                              DAG.getIntPtrConstant(4));
725       // Load the low part.
726       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
727                                MachinePointerInfo(), false, false, false, 0);
728
729       if (VA.isRegLoc()) {
730         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
731         assert(i+1 != e);
732         CCValAssign &NextVA = ArgLocs[++i];
733         if (NextVA.isRegLoc()) {
734           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
735         } else {
736           //Store the low part in stack.
737           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
738           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
739           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
740           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
741           MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
742                                              MachinePointerInfo(),
743                                              false, false, 0));
744         }
745       } else {
746         unsigned Offset = VA.getLocMemOffset() + StackOffset;
747         // Store the high part.
748         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
749         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
750         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
751         MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
752                                            MachinePointerInfo(),
753                                            false, false, 0));
754         // Store the low part.
755         PtrOff = DAG.getIntPtrConstant(Offset+4);
756         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
757         MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
758                                            MachinePointerInfo(),
759                                            false, false, 0));
760       }
761       continue;
762     }
763
764     // Arguments that can be passed on register must be kept at
765     // RegsToPass vector
766     if (VA.isRegLoc()) {
767       if (VA.getLocVT() != MVT::f32) {
768         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
769         continue;
770       }
771       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
772       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
773       continue;
774     }
775
776     assert(VA.isMemLoc());
777
778     // Create a store off the stack pointer for this argument.
779     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
780     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
781     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
782     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
783                                        MachinePointerInfo(),
784                                        false, false, 0));
785   }
786
787
788   // Emit all stores, make sure the occur before any copies into physregs.
789   if (!MemOpChains.empty())
790     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
791                         &MemOpChains[0], MemOpChains.size());
792
793   // Build a sequence of copy-to-reg nodes chained together with token
794   // chain and flag operands which copy the outgoing args into registers.
795   // The InFlag in necessary since all emitted instructions must be
796   // stuck together.
797   SDValue InFlag;
798   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
799     unsigned Reg = RegsToPass[i].first;
800     // Remap I0->I7 -> O0->O7.
801     if (Reg >= SP::I0 && Reg <= SP::I7)
802       Reg = Reg-SP::I0+SP::O0;
803
804     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
805     InFlag = Chain.getValue(1);
806   }
807
808   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
809
810   // If the callee is a GlobalAddress node (quite common, every direct call is)
811   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
812   // Likewise ExternalSymbol -> TargetExternalSymbol.
813   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
814     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
815   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
816     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
817
818   // Returns a chain & a flag for retval copy to use
819   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
820   SmallVector<SDValue, 8> Ops;
821   Ops.push_back(Chain);
822   Ops.push_back(Callee);
823   if (hasStructRetAttr)
824     Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
825   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
826     unsigned Reg = RegsToPass[i].first;
827     if (Reg >= SP::I0 && Reg <= SP::I7)
828       Reg = Reg-SP::I0+SP::O0;
829
830     Ops.push_back(DAG.getRegister(Reg, RegsToPass[i].second.getValueType()));
831   }
832   if (InFlag.getNode())
833     Ops.push_back(InFlag);
834
835   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
836   InFlag = Chain.getValue(1);
837
838   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
839                              DAG.getIntPtrConstant(0, true), InFlag);
840   InFlag = Chain.getValue(1);
841
842   // Assign locations to each value returned by this call.
843   SmallVector<CCValAssign, 16> RVLocs;
844   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
845                  DAG.getTarget(), RVLocs, *DAG.getContext());
846
847   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
848
849   // Copy all of the result registers out of their specified physreg.
850   for (unsigned i = 0; i != RVLocs.size(); ++i) {
851     unsigned Reg = RVLocs[i].getLocReg();
852
853     // Remap I0->I7 -> O0->O7.
854     if (Reg >= SP::I0 && Reg <= SP::I7)
855       Reg = Reg-SP::I0+SP::O0;
856
857     Chain = DAG.getCopyFromReg(Chain, dl, Reg,
858                                RVLocs[i].getValVT(), InFlag).getValue(1);
859     InFlag = Chain.getValue(2);
860     InVals.push_back(Chain.getValue(0));
861   }
862
863   return Chain;
864 }
865
866 unsigned
867 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
868 {
869   const Function *CalleeFn = 0;
870   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
871     CalleeFn = dyn_cast<Function>(G->getGlobal());
872   } else if (ExternalSymbolSDNode *E =
873              dyn_cast<ExternalSymbolSDNode>(Callee)) {
874     const Function *Fn = DAG.getMachineFunction().getFunction();
875     const Module *M = Fn->getParent();
876     CalleeFn = M->getFunction(E->getSymbol());
877   }
878
879   if (!CalleeFn)
880     return 0;
881
882   assert(CalleeFn->hasStructRetAttr() &&
883          "Callee does not have the StructRet attribute.");
884
885   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
886   Type *ElementTy = Ty->getElementType();
887   return getDataLayout()->getTypeAllocSize(ElementTy);
888 }
889
890 //===----------------------------------------------------------------------===//
891 // TargetLowering Implementation
892 //===----------------------------------------------------------------------===//
893
894 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
895 /// condition.
896 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
897   switch (CC) {
898   default: llvm_unreachable("Unknown integer condition code!");
899   case ISD::SETEQ:  return SPCC::ICC_E;
900   case ISD::SETNE:  return SPCC::ICC_NE;
901   case ISD::SETLT:  return SPCC::ICC_L;
902   case ISD::SETGT:  return SPCC::ICC_G;
903   case ISD::SETLE:  return SPCC::ICC_LE;
904   case ISD::SETGE:  return SPCC::ICC_GE;
905   case ISD::SETULT: return SPCC::ICC_CS;
906   case ISD::SETULE: return SPCC::ICC_LEU;
907   case ISD::SETUGT: return SPCC::ICC_GU;
908   case ISD::SETUGE: return SPCC::ICC_CC;
909   }
910 }
911
912 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
913 /// FCC condition.
914 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
915   switch (CC) {
916   default: llvm_unreachable("Unknown fp condition code!");
917   case ISD::SETEQ:
918   case ISD::SETOEQ: return SPCC::FCC_E;
919   case ISD::SETNE:
920   case ISD::SETUNE: return SPCC::FCC_NE;
921   case ISD::SETLT:
922   case ISD::SETOLT: return SPCC::FCC_L;
923   case ISD::SETGT:
924   case ISD::SETOGT: return SPCC::FCC_G;
925   case ISD::SETLE:
926   case ISD::SETOLE: return SPCC::FCC_LE;
927   case ISD::SETGE:
928   case ISD::SETOGE: return SPCC::FCC_GE;
929   case ISD::SETULT: return SPCC::FCC_UL;
930   case ISD::SETULE: return SPCC::FCC_ULE;
931   case ISD::SETUGT: return SPCC::FCC_UG;
932   case ISD::SETUGE: return SPCC::FCC_UGE;
933   case ISD::SETUO:  return SPCC::FCC_U;
934   case ISD::SETO:   return SPCC::FCC_O;
935   case ISD::SETONE: return SPCC::FCC_LG;
936   case ISD::SETUEQ: return SPCC::FCC_UE;
937   }
938 }
939
940 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
941   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
942   Subtarget = &TM.getSubtarget<SparcSubtarget>();
943
944   // Set up the register classes.
945   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
946   addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
947   addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
948   if (Subtarget->is64Bit())
949     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
950
951   // Turn FP extload into load/fextend
952   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
953   // Sparc doesn't have i1 sign extending load
954   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
955   // Turn FP truncstore into trunc + store.
956   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
957
958   // Custom legalize GlobalAddress nodes into LO/HI parts.
959   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
960   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
961   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
962
963   // Sparc doesn't have sext_inreg, replace them with shl/sra
964   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
965   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
966   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
967
968   // Sparc has no REM or DIVREM operations.
969   setOperationAction(ISD::UREM, MVT::i32, Expand);
970   setOperationAction(ISD::SREM, MVT::i32, Expand);
971   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
972   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
973
974   // Custom expand fp<->sint
975   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
976   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
977
978   // Expand fp<->uint
979   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
980   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
981
982   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
983   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
984
985   // Sparc has no select or setcc: expand to SELECT_CC.
986   setOperationAction(ISD::SELECT, MVT::i32, Expand);
987   setOperationAction(ISD::SELECT, MVT::f32, Expand);
988   setOperationAction(ISD::SELECT, MVT::f64, Expand);
989   setOperationAction(ISD::SETCC, MVT::i32, Expand);
990   setOperationAction(ISD::SETCC, MVT::f32, Expand);
991   setOperationAction(ISD::SETCC, MVT::f64, Expand);
992
993   // Sparc doesn't have BRCOND either, it has BR_CC.
994   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
995   setOperationAction(ISD::BRIND, MVT::Other, Expand);
996   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
997   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
998   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
999   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1000
1001   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1002   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1003   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1004
1005   if (Subtarget->is64Bit()) {
1006     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1007     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1008   }
1009
1010   // FIXME: There are instructions available for ATOMIC_FENCE
1011   // on SparcV8 and later.
1012   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
1013   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
1014
1015   setOperationAction(ISD::FSIN , MVT::f64, Expand);
1016   setOperationAction(ISD::FCOS , MVT::f64, Expand);
1017   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1018   setOperationAction(ISD::FREM , MVT::f64, Expand);
1019   setOperationAction(ISD::FMA  , MVT::f64, Expand);
1020   setOperationAction(ISD::FSIN , MVT::f32, Expand);
1021   setOperationAction(ISD::FCOS , MVT::f32, Expand);
1022   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1023   setOperationAction(ISD::FREM , MVT::f32, Expand);
1024   setOperationAction(ISD::FMA  , MVT::f32, Expand);
1025   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1026   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1027   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1028   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1029   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1030   setOperationAction(ISD::ROTL , MVT::i32, Expand);
1031   setOperationAction(ISD::ROTR , MVT::i32, Expand);
1032   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1033   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1034   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1035   setOperationAction(ISD::FPOW , MVT::f64, Expand);
1036   setOperationAction(ISD::FPOW , MVT::f32, Expand);
1037
1038   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1039   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1040   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1041
1042   // FIXME: Sparc provides these multiplies, but we don't have them yet.
1043   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1044   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1045
1046   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1047
1048   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1049   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1050   // VAARG needs to be lowered to not do unaligned accesses for doubles.
1051   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1052
1053   // Use the default implementation.
1054   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1055   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1056   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1057   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1058   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1059
1060   // No debug info support yet.
1061   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1062
1063   setStackPointerRegisterToSaveRestore(SP::O6);
1064
1065   if (TM.getSubtarget<SparcSubtarget>().isV9())
1066     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1067
1068   setMinFunctionAlignment(2);
1069
1070   computeRegisterProperties();
1071 }
1072
1073 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1074   switch (Opcode) {
1075   default: return 0;
1076   case SPISD::CMPICC:     return "SPISD::CMPICC";
1077   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
1078   case SPISD::BRICC:      return "SPISD::BRICC";
1079   case SPISD::BRXCC:      return "SPISD::BRXCC";
1080   case SPISD::BRFCC:      return "SPISD::BRFCC";
1081   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
1082   case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
1083   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
1084   case SPISD::Hi:         return "SPISD::Hi";
1085   case SPISD::Lo:         return "SPISD::Lo";
1086   case SPISD::FTOI:       return "SPISD::FTOI";
1087   case SPISD::ITOF:       return "SPISD::ITOF";
1088   case SPISD::CALL:       return "SPISD::CALL";
1089   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
1090   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1091   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
1092   }
1093 }
1094
1095 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1096 /// be zero. Op is expected to be a target specific node. Used by DAG
1097 /// combiner.
1098 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1099                                                          APInt &KnownZero,
1100                                                          APInt &KnownOne,
1101                                                          const SelectionDAG &DAG,
1102                                                          unsigned Depth) const {
1103   APInt KnownZero2, KnownOne2;
1104   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1105
1106   switch (Op.getOpcode()) {
1107   default: break;
1108   case SPISD::SELECT_ICC:
1109   case SPISD::SELECT_XCC:
1110   case SPISD::SELECT_FCC:
1111     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1112     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1113     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1114     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1115
1116     // Only known if known in both the LHS and RHS.
1117     KnownOne &= KnownOne2;
1118     KnownZero &= KnownZero2;
1119     break;
1120   }
1121 }
1122
1123 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1124 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1125 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1126                              ISD::CondCode CC, unsigned &SPCC) {
1127   if (isa<ConstantSDNode>(RHS) &&
1128       cast<ConstantSDNode>(RHS)->isNullValue() &&
1129       CC == ISD::SETNE &&
1130       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1131          LHS.getOpcode() == SPISD::SELECT_XCC) &&
1132         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1133        (LHS.getOpcode() == SPISD::SELECT_FCC &&
1134         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1135       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1136       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1137       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
1138       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
1139     SDValue CMPCC = LHS.getOperand(3);
1140     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1141     LHS = CMPCC.getOperand(0);
1142     RHS = CMPCC.getOperand(1);
1143   }
1144 }
1145
1146 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
1147                                                 SelectionDAG &DAG) const {
1148   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1149   // FIXME there isn't really any debug info here
1150   DebugLoc dl = Op.getDebugLoc();
1151   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
1152   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
1153   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
1154
1155   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1156     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1157
1158   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1159                                    getPointerTy());
1160   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1161   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1162                                 GlobalBase, RelAddr);
1163   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1164                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1165 }
1166
1167 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
1168                                                SelectionDAG &DAG) const {
1169   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1170   // FIXME there isn't really any debug info here
1171   DebugLoc dl = Op.getDebugLoc();
1172   const Constant *C = N->getConstVal();
1173   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
1174   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
1175   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
1176   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1177     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1178
1179   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1180                                    getPointerTy());
1181   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1182   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1183                                 GlobalBase, RelAddr);
1184   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1185                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1186 }
1187
1188 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1189   DebugLoc dl = Op.getDebugLoc();
1190   // Convert the fp value to integer in an FP register.
1191   assert(Op.getValueType() == MVT::i32);
1192   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
1193   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
1194 }
1195
1196 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1197   DebugLoc dl = Op.getDebugLoc();
1198   assert(Op.getOperand(0).getValueType() == MVT::i32);
1199   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
1200   // Convert the int value to FP in an FP register.
1201   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
1202 }
1203
1204 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1205   SDValue Chain = Op.getOperand(0);
1206   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1207   SDValue LHS = Op.getOperand(2);
1208   SDValue RHS = Op.getOperand(3);
1209   SDValue Dest = Op.getOperand(4);
1210   DebugLoc dl = Op.getDebugLoc();
1211   unsigned Opc, SPCC = ~0U;
1212
1213   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1214   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1215   LookThroughSetCC(LHS, RHS, CC, SPCC);
1216
1217   // Get the condition flag.
1218   SDValue CompareFlag;
1219   if (LHS.getValueType().isInteger()) {
1220     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1221     SDValue Ops[2] = { LHS, RHS };
1222     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1223     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1224     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
1225     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
1226   } else {
1227     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1228     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1229     Opc = SPISD::BRFCC;
1230   }
1231   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
1232                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1233 }
1234
1235 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1236   SDValue LHS = Op.getOperand(0);
1237   SDValue RHS = Op.getOperand(1);
1238   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1239   SDValue TrueVal = Op.getOperand(2);
1240   SDValue FalseVal = Op.getOperand(3);
1241   DebugLoc dl = Op.getDebugLoc();
1242   unsigned Opc, SPCC = ~0U;
1243
1244   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1245   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1246   LookThroughSetCC(LHS, RHS, CC, SPCC);
1247
1248   SDValue CompareFlag;
1249   if (LHS.getValueType().isInteger()) {
1250     // subcc returns a value
1251     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1252     SDValue Ops[2] = { LHS, RHS };
1253     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1254     Opc = LHS.getValueType() == MVT::i32 ?
1255           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
1256     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1257   } else {
1258     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1259     Opc = SPISD::SELECT_FCC;
1260     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1261   }
1262   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1263                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1264 }
1265
1266 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1267                             const SparcTargetLowering &TLI) {
1268   MachineFunction &MF = DAG.getMachineFunction();
1269   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1270
1271   // vastart just stores the address of the VarArgsFrameIndex slot into the
1272   // memory location argument.
1273   DebugLoc dl = Op.getDebugLoc();
1274   SDValue Offset =
1275     DAG.getNode(ISD::ADD, dl, MVT::i32,
1276                 DAG.getRegister(SP::I6, MVT::i32),
1277                 DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1278                                 MVT::i32));
1279   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1280   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1281                       MachinePointerInfo(SV), false, false, 0);
1282 }
1283
1284 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1285   SDNode *Node = Op.getNode();
1286   EVT VT = Node->getValueType(0);
1287   SDValue InChain = Node->getOperand(0);
1288   SDValue VAListPtr = Node->getOperand(1);
1289   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1290   DebugLoc dl = Node->getDebugLoc();
1291   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1292                                MachinePointerInfo(SV), false, false, false, 0);
1293   // Increment the pointer, VAList, to the next vaarg
1294   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1295                                   DAG.getConstant(VT.getSizeInBits()/8,
1296                                                   MVT::i32));
1297   // Store the incremented VAList to the legalized pointer
1298   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1299                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
1300   // Load the actual argument out of the pointer VAList, unless this is an
1301   // f64 load.
1302   if (VT != MVT::f64)
1303     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1304                        false, false, false, 0);
1305
1306   // Otherwise, load it as i64, then do a bitconvert.
1307   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1308                           false, false, false, 0);
1309
1310   // Bit-Convert the value to f64.
1311   SDValue Ops[2] = {
1312     DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1313     V.getValue(1)
1314   };
1315   return DAG.getMergeValues(Ops, 2, dl);
1316 }
1317
1318 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1319   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1320   SDValue Size  = Op.getOperand(1);  // Legalize the size.
1321   DebugLoc dl = Op.getDebugLoc();
1322
1323   unsigned SPReg = SP::O6;
1324   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1325   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1326   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1327
1328   // The resultant pointer is actually 16 words from the bottom of the stack,
1329   // to provide a register spill area.
1330   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1331                                  DAG.getConstant(96, MVT::i32));
1332   SDValue Ops[2] = { NewVal, Chain };
1333   return DAG.getMergeValues(Ops, 2, dl);
1334 }
1335
1336
1337 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1338   DebugLoc dl = Op.getDebugLoc();
1339   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1340                               dl, MVT::Other, DAG.getEntryNode());
1341   return Chain;
1342 }
1343
1344 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1345   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1346   MFI->setFrameAddressIsTaken(true);
1347
1348   EVT VT = Op.getValueType();
1349   DebugLoc dl = Op.getDebugLoc();
1350   unsigned FrameReg = SP::I6;
1351
1352   uint64_t depth = Op.getConstantOperandVal(0);
1353
1354   SDValue FrameAddr;
1355   if (depth == 0)
1356     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1357   else {
1358     // flush first to make sure the windowed registers' values are in stack
1359     SDValue Chain = getFLUSHW(Op, DAG);
1360     FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1361
1362     for (uint64_t i = 0; i != depth; ++i) {
1363       SDValue Ptr = DAG.getNode(ISD::ADD,
1364                                 dl, MVT::i32,
1365                                 FrameAddr, DAG.getIntPtrConstant(56));
1366       FrameAddr = DAG.getLoad(MVT::i32, dl,
1367                               Chain,
1368                               Ptr,
1369                               MachinePointerInfo(), false, false, false, 0);
1370     }
1371   }
1372   return FrameAddr;
1373 }
1374
1375 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1376   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1377   MFI->setReturnAddressIsTaken(true);
1378
1379   EVT VT = Op.getValueType();
1380   DebugLoc dl = Op.getDebugLoc();
1381   unsigned RetReg = SP::I7;
1382
1383   uint64_t depth = Op.getConstantOperandVal(0);
1384
1385   SDValue RetAddr;
1386   if (depth == 0)
1387     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1388   else {
1389     // flush first to make sure the windowed registers' values are in stack
1390     SDValue Chain = getFLUSHW(Op, DAG);
1391     RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1392
1393     for (uint64_t i = 0; i != depth; ++i) {
1394       SDValue Ptr = DAG.getNode(ISD::ADD,
1395                                 dl, MVT::i32,
1396                                 RetAddr,
1397                                 DAG.getIntPtrConstant((i == depth-1)?60:56));
1398       RetAddr = DAG.getLoad(MVT::i32, dl,
1399                             Chain,
1400                             Ptr,
1401                             MachinePointerInfo(), false, false, false, 0);
1402     }
1403   }
1404   return RetAddr;
1405 }
1406
1407 SDValue SparcTargetLowering::
1408 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1409   switch (Op.getOpcode()) {
1410   default: llvm_unreachable("Should not custom lower this!");
1411   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1412   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1413   case ISD::GlobalTLSAddress:
1414     llvm_unreachable("TLS not implemented for Sparc.");
1415   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1416   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1417   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1418   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1419   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1420   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1421   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1422   case ISD::VAARG:              return LowerVAARG(Op, DAG);
1423   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1424   }
1425 }
1426
1427 MachineBasicBlock *
1428 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1429                                                  MachineBasicBlock *BB) const {
1430   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1431   unsigned BROpcode;
1432   unsigned CC;
1433   DebugLoc dl = MI->getDebugLoc();
1434   // Figure out the conditional branch opcode to use for this select_cc.
1435   switch (MI->getOpcode()) {
1436   default: llvm_unreachable("Unknown SELECT_CC!");
1437   case SP::SELECT_CC_Int_ICC:
1438   case SP::SELECT_CC_FP_ICC:
1439   case SP::SELECT_CC_DFP_ICC:
1440     BROpcode = SP::BCOND;
1441     break;
1442   case SP::SELECT_CC_Int_FCC:
1443   case SP::SELECT_CC_FP_FCC:
1444   case SP::SELECT_CC_DFP_FCC:
1445     BROpcode = SP::FBCOND;
1446     break;
1447   }
1448
1449   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1450
1451   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1452   // control-flow pattern.  The incoming instruction knows the destination vreg
1453   // to set, the condition code register to branch on, the true/false values to
1454   // select between, and a branch opcode to use.
1455   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1456   MachineFunction::iterator It = BB;
1457   ++It;
1458
1459   //  thisMBB:
1460   //  ...
1461   //   TrueVal = ...
1462   //   [f]bCC copy1MBB
1463   //   fallthrough --> copy0MBB
1464   MachineBasicBlock *thisMBB = BB;
1465   MachineFunction *F = BB->getParent();
1466   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1467   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1468   F->insert(It, copy0MBB);
1469   F->insert(It, sinkMBB);
1470
1471   // Transfer the remainder of BB and its successor edges to sinkMBB.
1472   sinkMBB->splice(sinkMBB->begin(), BB,
1473                   llvm::next(MachineBasicBlock::iterator(MI)),
1474                   BB->end());
1475   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1476
1477   // Add the true and fallthrough blocks as its successors.
1478   BB->addSuccessor(copy0MBB);
1479   BB->addSuccessor(sinkMBB);
1480
1481   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1482
1483   //  copy0MBB:
1484   //   %FalseValue = ...
1485   //   # fallthrough to sinkMBB
1486   BB = copy0MBB;
1487
1488   // Update machine-CFG edges
1489   BB->addSuccessor(sinkMBB);
1490
1491   //  sinkMBB:
1492   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1493   //  ...
1494   BB = sinkMBB;
1495   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1496     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1497     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1498
1499   MI->eraseFromParent();   // The pseudo instruction is gone now.
1500   return BB;
1501 }
1502
1503 //===----------------------------------------------------------------------===//
1504 //                         Sparc Inline Assembly Support
1505 //===----------------------------------------------------------------------===//
1506
1507 /// getConstraintType - Given a constraint letter, return the type of
1508 /// constraint it is for this target.
1509 SparcTargetLowering::ConstraintType
1510 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1511   if (Constraint.size() == 1) {
1512     switch (Constraint[0]) {
1513     default:  break;
1514     case 'r': return C_RegisterClass;
1515     }
1516   }
1517
1518   return TargetLowering::getConstraintType(Constraint);
1519 }
1520
1521 std::pair<unsigned, const TargetRegisterClass*>
1522 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1523                                                   EVT VT) const {
1524   if (Constraint.size() == 1) {
1525     switch (Constraint[0]) {
1526     case 'r':
1527       return std::make_pair(0U, &SP::IntRegsRegClass);
1528     }
1529   }
1530
1531   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1532 }
1533
1534 bool
1535 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1536   // The Sparc target isn't yet aware of offsets.
1537   return false;
1538 }