09c4b8bd2204edcf515aa857ca98078a3eea0f17
[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 "SparcRegisterInfo.h"
18 #include "SparcTargetMachine.h"
19 #include "MCTargetDesc/SparcBaseInfo.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/ErrorHandling.h"
31 using namespace llvm;
32
33
34 //===----------------------------------------------------------------------===//
35 // Calling Convention Implementation
36 //===----------------------------------------------------------------------===//
37
38 static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
39                                  MVT &LocVT, CCValAssign::LocInfo &LocInfo,
40                                  ISD::ArgFlagsTy &ArgFlags, CCState &State)
41 {
42   assert (ArgFlags.isSRet());
43
44   // Assign SRet argument.
45   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
46                                          0,
47                                          LocVT, LocInfo));
48   return true;
49 }
50
51 static bool CC_Sparc_Assign_f64(unsigned &ValNo, MVT &ValVT,
52                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
53                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
54 {
55   static const uint16_t RegList[] = {
56     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
57   };
58   // Try to get first reg.
59   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
60     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
61   } else {
62     // Assign whole thing in stack.
63     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
64                                            State.AllocateStack(8,4),
65                                            LocVT, LocInfo));
66     return true;
67   }
68
69   // Try to get second reg.
70   if (unsigned Reg = State.AllocateReg(RegList, 6))
71     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
72   else
73     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
74                                            State.AllocateStack(4,4),
75                                            LocVT, LocInfo));
76   return true;
77 }
78
79 // Allocate a full-sized argument for the 64-bit ABI.
80 static bool CC_Sparc64_Full(unsigned &ValNo, MVT &ValVT,
81                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
82                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
83   assert((LocVT == MVT::f32 || LocVT == MVT::f128
84           || LocVT.getSizeInBits() == 64) &&
85          "Can't handle non-64 bits locations");
86
87   // Stack space is allocated for all arguments starting from [%fp+BIAS+128].
88   unsigned size      = (LocVT == MVT::f128) ? 16 : 8;
89   unsigned alignment = (LocVT == MVT::f128) ? 16 : 8;
90   unsigned Offset = State.AllocateStack(size, alignment);
91   unsigned Reg = 0;
92
93   if (LocVT == MVT::i64 && Offset < 6*8)
94     // Promote integers to %i0-%i5.
95     Reg = SP::I0 + Offset/8;
96   else if (LocVT == MVT::f64 && Offset < 16*8)
97     // Promote doubles to %d0-%d30. (Which LLVM calls D0-D15).
98     Reg = SP::D0 + Offset/8;
99   else if (LocVT == MVT::f32 && Offset < 16*8)
100     // Promote floats to %f1, %f3, ...
101     Reg = SP::F1 + Offset/4;
102   else if (LocVT == MVT::f128 && Offset < 16*8)
103     // Promote long doubles to %q0-%q28. (Which LLVM calls Q0-Q7).
104     Reg = SP::Q0 + Offset/16;
105
106   // Promote to register when possible, otherwise use the stack slot.
107   if (Reg) {
108     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
109     return true;
110   }
111
112   // This argument goes on the stack in an 8-byte slot.
113   // When passing floats, LocVT is smaller than 8 bytes. Adjust the offset to
114   // the right-aligned float. The first 4 bytes of the stack slot are undefined.
115   if (LocVT == MVT::f32)
116     Offset += 4;
117
118   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
119   return true;
120 }
121
122 // Allocate a half-sized argument for the 64-bit ABI.
123 //
124 // This is used when passing { float, int } structs by value in registers.
125 static bool CC_Sparc64_Half(unsigned &ValNo, MVT &ValVT,
126                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
127                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
128   assert(LocVT.getSizeInBits() == 32 && "Can't handle non-32 bits locations");
129   unsigned Offset = State.AllocateStack(4, 4);
130
131   if (LocVT == MVT::f32 && Offset < 16*8) {
132     // Promote floats to %f0-%f31.
133     State.addLoc(CCValAssign::getReg(ValNo, ValVT, SP::F0 + Offset/4,
134                                      LocVT, LocInfo));
135     return true;
136   }
137
138   if (LocVT == MVT::i32 && Offset < 6*8) {
139     // Promote integers to %i0-%i5, using half the register.
140     unsigned Reg = SP::I0 + Offset/8;
141     LocVT = MVT::i64;
142     LocInfo = CCValAssign::AExt;
143
144     // Set the Custom bit if this i32 goes in the high bits of a register.
145     if (Offset % 8 == 0)
146       State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg,
147                                              LocVT, LocInfo));
148     else
149       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
150     return true;
151   }
152
153   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
154   return true;
155 }
156
157 #include "SparcGenCallingConv.inc"
158
159 // The calling conventions in SparcCallingConv.td are described in terms of the
160 // callee's register window. This function translates registers to the
161 // corresponding caller window %o register.
162 static unsigned toCallerWindow(unsigned Reg) {
163   assert(SP::I0 + 7 == SP::I7 && SP::O0 + 7 == SP::O7 && "Unexpected enum");
164   if (Reg >= SP::I0 && Reg <= SP::I7)
165     return Reg - SP::I0 + SP::O0;
166   return Reg;
167 }
168
169 SDValue
170 SparcTargetLowering::LowerReturn(SDValue Chain,
171                                  CallingConv::ID CallConv, bool IsVarArg,
172                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
173                                  const SmallVectorImpl<SDValue> &OutVals,
174                                  SDLoc DL, SelectionDAG &DAG) const {
175   if (Subtarget->is64Bit())
176     return LowerReturn_64(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
177   return LowerReturn_32(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
178 }
179
180 SDValue
181 SparcTargetLowering::LowerReturn_32(SDValue Chain,
182                                     CallingConv::ID CallConv, bool IsVarArg,
183                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
184                                     const SmallVectorImpl<SDValue> &OutVals,
185                                     SDLoc DL, SelectionDAG &DAG) const {
186   MachineFunction &MF = DAG.getMachineFunction();
187
188   // CCValAssign - represent the assignment of the return value to locations.
189   SmallVector<CCValAssign, 16> RVLocs;
190
191   // CCState - Info about the registers and stack slot.
192   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
193                  DAG.getTarget(), RVLocs, *DAG.getContext());
194
195   // Analyze return values.
196   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
197
198   SDValue Flag;
199   SmallVector<SDValue, 4> RetOps(1, Chain);
200   // Make room for the return address offset.
201   RetOps.push_back(SDValue());
202
203   // Copy the result values into the output registers.
204   for (unsigned i = 0; i != RVLocs.size(); ++i) {
205     CCValAssign &VA = RVLocs[i];
206     assert(VA.isRegLoc() && "Can only return in registers!");
207
208     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(),
209                              OutVals[i], Flag);
210
211     // Guarantee that all emitted copies are stuck together with flags.
212     Flag = Chain.getValue(1);
213     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
214   }
215
216   unsigned RetAddrOffset = 8; // Call Inst + Delay Slot
217   // If the function returns a struct, copy the SRetReturnReg to I0
218   if (MF.getFunction()->hasStructRetAttr()) {
219     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
220     unsigned Reg = SFI->getSRetReturnReg();
221     if (!Reg)
222       llvm_unreachable("sret virtual register not created in the entry block");
223     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
224     Chain = DAG.getCopyToReg(Chain, DL, SP::I0, Val, Flag);
225     Flag = Chain.getValue(1);
226     RetOps.push_back(DAG.getRegister(SP::I0, getPointerTy()));
227     RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
228   }
229
230   RetOps[0] = Chain;  // Update chain.
231   RetOps[1] = DAG.getConstant(RetAddrOffset, MVT::i32);
232
233   // Add the flag if we have it.
234   if (Flag.getNode())
235     RetOps.push_back(Flag);
236
237   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
238                      &RetOps[0], RetOps.size());
239 }
240
241 // Lower return values for the 64-bit ABI.
242 // Return values are passed the exactly the same way as function arguments.
243 SDValue
244 SparcTargetLowering::LowerReturn_64(SDValue Chain,
245                                     CallingConv::ID CallConv, bool IsVarArg,
246                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
247                                     const SmallVectorImpl<SDValue> &OutVals,
248                                     SDLoc DL, SelectionDAG &DAG) const {
249   // CCValAssign - represent the assignment of the return value to locations.
250   SmallVector<CCValAssign, 16> RVLocs;
251
252   // CCState - Info about the registers and stack slot.
253   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
254                  DAG.getTarget(), RVLocs, *DAG.getContext());
255
256   // Analyze return values.
257   CCInfo.AnalyzeReturn(Outs, CC_Sparc64);
258
259   SDValue Flag;
260   SmallVector<SDValue, 4> RetOps(1, Chain);
261
262   // The second operand on the return instruction is the return address offset.
263   // The return address is always %i7+8 with the 64-bit ABI.
264   RetOps.push_back(DAG.getConstant(8, MVT::i32));
265
266   // Copy the result values into the output registers.
267   for (unsigned i = 0; i != RVLocs.size(); ++i) {
268     CCValAssign &VA = RVLocs[i];
269     assert(VA.isRegLoc() && "Can only return in registers!");
270     SDValue OutVal = OutVals[i];
271
272     // Integer return values must be sign or zero extended by the callee.
273     switch (VA.getLocInfo()) {
274     case CCValAssign::SExt:
275       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
276       break;
277     case CCValAssign::ZExt:
278       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
279       break;
280     case CCValAssign::AExt:
281       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
282     default:
283       break;
284     }
285
286     // The custom bit on an i32 return value indicates that it should be passed
287     // in the high bits of the register.
288     if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
289       OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
290                            DAG.getConstant(32, MVT::i32));
291
292       // The next value may go in the low bits of the same register.
293       // Handle both at once.
294       if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
295         SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
296         OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
297         // Skip the next value, it's already done.
298         ++i;
299       }
300     }
301
302     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
303
304     // Guarantee that all emitted copies are stuck together with flags.
305     Flag = Chain.getValue(1);
306     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
307   }
308
309   RetOps[0] = Chain;  // Update chain.
310
311   // Add the flag if we have it.
312   if (Flag.getNode())
313     RetOps.push_back(Flag);
314
315   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
316                      &RetOps[0], RetOps.size());
317 }
318
319 SDValue SparcTargetLowering::
320 LowerFormalArguments(SDValue Chain,
321                      CallingConv::ID CallConv,
322                      bool IsVarArg,
323                      const SmallVectorImpl<ISD::InputArg> &Ins,
324                      SDLoc DL,
325                      SelectionDAG &DAG,
326                      SmallVectorImpl<SDValue> &InVals) const {
327   if (Subtarget->is64Bit())
328     return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
329                                    DL, DAG, InVals);
330   return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
331                                  DL, DAG, InVals);
332 }
333
334 /// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
335 /// passed in either one or two GPRs, including FP values.  TODO: we should
336 /// pass FP values in FP registers for fastcc functions.
337 SDValue SparcTargetLowering::
338 LowerFormalArguments_32(SDValue Chain,
339                         CallingConv::ID CallConv,
340                         bool isVarArg,
341                         const SmallVectorImpl<ISD::InputArg> &Ins,
342                         SDLoc dl,
343                         SelectionDAG &DAG,
344                         SmallVectorImpl<SDValue> &InVals) const {
345   MachineFunction &MF = DAG.getMachineFunction();
346   MachineRegisterInfo &RegInfo = MF.getRegInfo();
347   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
348
349   // Assign locations to all of the incoming arguments.
350   SmallVector<CCValAssign, 16> ArgLocs;
351   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
352                  getTargetMachine(), ArgLocs, *DAG.getContext());
353   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
354
355   const unsigned StackOffset = 92;
356
357   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
358     CCValAssign &VA = ArgLocs[i];
359
360     if (i == 0  && Ins[i].Flags.isSRet()) {
361       // Get SRet from [%fp+64].
362       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
363       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
364       SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
365                                 MachinePointerInfo(),
366                                 false, false, false, 0);
367       InVals.push_back(Arg);
368       continue;
369     }
370
371     if (VA.isRegLoc()) {
372       if (VA.needsCustom()) {
373         assert(VA.getLocVT() == MVT::f64);
374         unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
375         MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
376         SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
377
378         assert(i+1 < e);
379         CCValAssign &NextVA = ArgLocs[++i];
380
381         SDValue LoVal;
382         if (NextVA.isMemLoc()) {
383           int FrameIdx = MF.getFrameInfo()->
384             CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
385           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
386           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
387                               MachinePointerInfo(),
388                               false, false, false, 0);
389         } else {
390           unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
391                                         &SP::IntRegsRegClass);
392           LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
393         }
394         SDValue WholeValue =
395           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
396         WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
397         InVals.push_back(WholeValue);
398         continue;
399       }
400       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
401       MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
402       SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
403       if (VA.getLocVT() == MVT::f32)
404         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
405       else if (VA.getLocVT() != MVT::i32) {
406         Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
407                           DAG.getValueType(VA.getLocVT()));
408         Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
409       }
410       InVals.push_back(Arg);
411       continue;
412     }
413
414     assert(VA.isMemLoc());
415
416     unsigned Offset = VA.getLocMemOffset()+StackOffset;
417
418     if (VA.needsCustom()) {
419       assert(VA.getValVT() == MVT::f64);
420       // If it is double-word aligned, just load.
421       if (Offset % 8 == 0) {
422         int FI = MF.getFrameInfo()->CreateFixedObject(8,
423                                                       Offset,
424                                                       true);
425         SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
426         SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
427                                    MachinePointerInfo(),
428                                    false,false, false, 0);
429         InVals.push_back(Load);
430         continue;
431       }
432
433       int FI = MF.getFrameInfo()->CreateFixedObject(4,
434                                                     Offset,
435                                                     true);
436       SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
437       SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
438                                   MachinePointerInfo(),
439                                   false, false, false, 0);
440       int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
441                                                      Offset+4,
442                                                      true);
443       SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
444
445       SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
446                                   MachinePointerInfo(),
447                                   false, false, false, 0);
448
449       SDValue WholeValue =
450         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
451       WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
452       InVals.push_back(WholeValue);
453       continue;
454     }
455
456     int FI = MF.getFrameInfo()->CreateFixedObject(4,
457                                                   Offset,
458                                                   true);
459     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
460     SDValue Load ;
461     if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
462       Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
463                          MachinePointerInfo(),
464                          false, false, false, 0);
465     } else {
466       ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
467       // Sparc is big endian, so add an offset based on the ObjectVT.
468       unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
469       FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
470                           DAG.getConstant(Offset, MVT::i32));
471       Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
472                             MachinePointerInfo(),
473                             VA.getValVT(), false, false,0);
474       Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
475     }
476     InVals.push_back(Load);
477   }
478
479   if (MF.getFunction()->hasStructRetAttr()) {
480     // Copy the SRet Argument to SRetReturnReg.
481     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
482     unsigned Reg = SFI->getSRetReturnReg();
483     if (!Reg) {
484       Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
485       SFI->setSRetReturnReg(Reg);
486     }
487     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
489   }
490
491   // Store remaining ArgRegs to the stack if this is a varargs function.
492   if (isVarArg) {
493     static const uint16_t ArgRegs[] = {
494       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
495     };
496     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
497     const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
498     unsigned ArgOffset = CCInfo.getNextStackOffset();
499     if (NumAllocated == 6)
500       ArgOffset += StackOffset;
501     else {
502       assert(!ArgOffset);
503       ArgOffset = 68+4*NumAllocated;
504     }
505
506     // Remember the vararg offset for the va_start implementation.
507     FuncInfo->setVarArgsFrameOffset(ArgOffset);
508
509     std::vector<SDValue> OutChains;
510
511     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
512       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
513       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
514       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
515
516       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
517                                                           true);
518       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
519
520       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
521                                        MachinePointerInfo(),
522                                        false, false, 0));
523       ArgOffset += 4;
524     }
525
526     if (!OutChains.empty()) {
527       OutChains.push_back(Chain);
528       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
529                           &OutChains[0], OutChains.size());
530     }
531   }
532
533   return Chain;
534 }
535
536 // Lower formal arguments for the 64 bit ABI.
537 SDValue SparcTargetLowering::
538 LowerFormalArguments_64(SDValue Chain,
539                         CallingConv::ID CallConv,
540                         bool IsVarArg,
541                         const SmallVectorImpl<ISD::InputArg> &Ins,
542                         SDLoc DL,
543                         SelectionDAG &DAG,
544                         SmallVectorImpl<SDValue> &InVals) const {
545   MachineFunction &MF = DAG.getMachineFunction();
546
547   // Analyze arguments according to CC_Sparc64.
548   SmallVector<CCValAssign, 16> ArgLocs;
549   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
550                  getTargetMachine(), ArgLocs, *DAG.getContext());
551   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
552
553   // The argument array begins at %fp+BIAS+128, after the register save area.
554   const unsigned ArgArea = 128;
555
556   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
557     CCValAssign &VA = ArgLocs[i];
558     if (VA.isRegLoc()) {
559       // This argument is passed in a register.
560       // All integer register arguments are promoted by the caller to i64.
561
562       // Create a virtual register for the promoted live-in value.
563       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
564                                    getRegClassFor(VA.getLocVT()));
565       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
566
567       // Get the high bits for i32 struct elements.
568       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
569         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
570                           DAG.getConstant(32, MVT::i32));
571
572       // The caller promoted the argument, so insert an Assert?ext SDNode so we
573       // won't promote the value again in this function.
574       switch (VA.getLocInfo()) {
575       case CCValAssign::SExt:
576         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
577                           DAG.getValueType(VA.getValVT()));
578         break;
579       case CCValAssign::ZExt:
580         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
581                           DAG.getValueType(VA.getValVT()));
582         break;
583       default:
584         break;
585       }
586
587       // Truncate the register down to the argument type.
588       if (VA.isExtInLoc())
589         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
590
591       InVals.push_back(Arg);
592       continue;
593     }
594
595     // The registers are exhausted. This argument was passed on the stack.
596     assert(VA.isMemLoc());
597     // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
598     // beginning of the arguments area at %fp+BIAS+128.
599     unsigned Offset = VA.getLocMemOffset() + ArgArea;
600     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
601     // Adjust offset for extended arguments, SPARC is big-endian.
602     // The caller will have written the full slot with extended bytes, but we
603     // prefer our own extending loads.
604     if (VA.isExtInLoc())
605       Offset += 8 - ValSize;
606     int FI = MF.getFrameInfo()->CreateFixedObject(ValSize, Offset, true);
607     InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
608                                  DAG.getFrameIndex(FI, getPointerTy()),
609                                  MachinePointerInfo::getFixedStack(FI),
610                                  false, false, false, 0));
611   }
612
613   if (!IsVarArg)
614     return Chain;
615
616   // This function takes variable arguments, some of which may have been passed
617   // in registers %i0-%i5. Variable floating point arguments are never passed
618   // in floating point registers. They go on %i0-%i5 or on the stack like
619   // integer arguments.
620   //
621   // The va_start intrinsic needs to know the offset to the first variable
622   // argument.
623   unsigned ArgOffset = CCInfo.getNextStackOffset();
624   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
625   // Skip the 128 bytes of register save area.
626   FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgArea +
627                                   Subtarget->getStackPointerBias());
628
629   // Save the variable arguments that were passed in registers.
630   // The caller is required to reserve stack space for 6 arguments regardless
631   // of how many arguments were actually passed.
632   SmallVector<SDValue, 8> OutChains;
633   for (; ArgOffset < 6*8; ArgOffset += 8) {
634     unsigned VReg = MF.addLiveIn(SP::I0 + ArgOffset/8, &SP::I64RegsRegClass);
635     SDValue VArg = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
636     int FI = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset + ArgArea, true);
637     OutChains.push_back(DAG.getStore(Chain, DL, VArg,
638                                      DAG.getFrameIndex(FI, getPointerTy()),
639                                      MachinePointerInfo::getFixedStack(FI),
640                                      false, false, 0));
641   }
642
643   if (!OutChains.empty())
644     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
645                         &OutChains[0], OutChains.size());
646
647   return Chain;
648 }
649
650 SDValue
651 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
652                                SmallVectorImpl<SDValue> &InVals) const {
653   if (Subtarget->is64Bit())
654     return LowerCall_64(CLI, InVals);
655   return LowerCall_32(CLI, InVals);
656 }
657
658 static bool hasReturnsTwiceAttr(SelectionDAG &DAG, SDValue Callee,
659                                      ImmutableCallSite *CS) {
660   if (CS)
661     return CS->hasFnAttr(Attribute::ReturnsTwice);
662
663   const Function *CalleeFn = 0;
664   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
665     CalleeFn = dyn_cast<Function>(G->getGlobal());
666   } else if (ExternalSymbolSDNode *E =
667              dyn_cast<ExternalSymbolSDNode>(Callee)) {
668     const Function *Fn = DAG.getMachineFunction().getFunction();
669     const Module *M = Fn->getParent();
670     const char *CalleeName = E->getSymbol();
671     CalleeFn = M->getFunction(CalleeName);
672   }
673
674   if (!CalleeFn)
675     return false;
676   return CalleeFn->hasFnAttribute(Attribute::ReturnsTwice);
677 }
678
679 // Lower a call for the 32-bit ABI.
680 SDValue
681 SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI,
682                                   SmallVectorImpl<SDValue> &InVals) const {
683   SelectionDAG &DAG                     = CLI.DAG;
684   SDLoc &dl                             = CLI.DL;
685   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
686   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
687   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
688   SDValue Chain                         = CLI.Chain;
689   SDValue Callee                        = CLI.Callee;
690   bool &isTailCall                      = CLI.IsTailCall;
691   CallingConv::ID CallConv              = CLI.CallConv;
692   bool isVarArg                         = CLI.IsVarArg;
693
694   // Sparc target does not yet support tail call optimization.
695   isTailCall = false;
696
697   // Analyze operands of the call, assigning locations to each operand.
698   SmallVector<CCValAssign, 16> ArgLocs;
699   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
700                  DAG.getTarget(), ArgLocs, *DAG.getContext());
701   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
702
703   // Get the size of the outgoing arguments stack space requirement.
704   unsigned ArgsSize = CCInfo.getNextStackOffset();
705
706   // Keep stack frames 8-byte aligned.
707   ArgsSize = (ArgsSize+7) & ~7;
708
709   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
710
711   // Create local copies for byval args.
712   SmallVector<SDValue, 8> ByValArgs;
713   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
714     ISD::ArgFlagsTy Flags = Outs[i].Flags;
715     if (!Flags.isByVal())
716       continue;
717
718     SDValue Arg = OutVals[i];
719     unsigned Size = Flags.getByValSize();
720     unsigned Align = Flags.getByValAlign();
721
722     int FI = MFI->CreateStackObject(Size, Align, false);
723     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
724     SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
725
726     Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
727                           false,        // isVolatile,
728                           (Size <= 32), // AlwaysInline if size <= 32
729                           MachinePointerInfo(), MachinePointerInfo());
730     ByValArgs.push_back(FIPtr);
731   }
732
733   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true),
734                                dl);
735
736   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
737   SmallVector<SDValue, 8> MemOpChains;
738
739   const unsigned StackOffset = 92;
740   bool hasStructRetAttr = false;
741   // Walk the register/memloc assignments, inserting copies/loads.
742   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
743        i != e;
744        ++i, ++realArgIdx) {
745     CCValAssign &VA = ArgLocs[i];
746     SDValue Arg = OutVals[realArgIdx];
747
748     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
749
750     // Use local copy if it is a byval arg.
751     if (Flags.isByVal())
752       Arg = ByValArgs[byvalArgIdx++];
753
754     // Promote the value if needed.
755     switch (VA.getLocInfo()) {
756     default: llvm_unreachable("Unknown loc info!");
757     case CCValAssign::Full: break;
758     case CCValAssign::SExt:
759       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
760       break;
761     case CCValAssign::ZExt:
762       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
763       break;
764     case CCValAssign::AExt:
765       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
766       break;
767     case CCValAssign::BCvt:
768       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
769       break;
770     }
771
772     if (Flags.isSRet()) {
773       assert(VA.needsCustom());
774       // store SRet argument in %sp+64
775       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
776       SDValue PtrOff = DAG.getIntPtrConstant(64);
777       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
778       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
779                                          MachinePointerInfo(),
780                                          false, false, 0));
781       hasStructRetAttr = true;
782       continue;
783     }
784
785     if (VA.needsCustom()) {
786       assert(VA.getLocVT() == MVT::f64);
787
788       if (VA.isMemLoc()) {
789         unsigned Offset = VA.getLocMemOffset() + StackOffset;
790         // if it is double-word aligned, just store.
791         if (Offset % 8 == 0) {
792           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
793           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
794           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
795           MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
796                                              MachinePointerInfo(),
797                                              false, false, 0));
798           continue;
799         }
800       }
801
802       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
803       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
804                                    Arg, StackPtr, MachinePointerInfo(),
805                                    false, false, 0);
806       // Sparc is big-endian, so the high part comes first.
807       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
808                                MachinePointerInfo(), false, false, false, 0);
809       // Increment the pointer to the other half.
810       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
811                              DAG.getIntPtrConstant(4));
812       // Load the low part.
813       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
814                                MachinePointerInfo(), false, false, false, 0);
815
816       if (VA.isRegLoc()) {
817         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
818         assert(i+1 != e);
819         CCValAssign &NextVA = ArgLocs[++i];
820         if (NextVA.isRegLoc()) {
821           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
822         } else {
823           // Store the low part in stack.
824           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
825           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
826           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
827           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
828           MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
829                                              MachinePointerInfo(),
830                                              false, false, 0));
831         }
832       } else {
833         unsigned Offset = VA.getLocMemOffset() + StackOffset;
834         // Store the high part.
835         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
836         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
837         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
838         MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
839                                            MachinePointerInfo(),
840                                            false, false, 0));
841         // Store the low part.
842         PtrOff = DAG.getIntPtrConstant(Offset+4);
843         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
844         MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
845                                            MachinePointerInfo(),
846                                            false, false, 0));
847       }
848       continue;
849     }
850
851     // Arguments that can be passed on register must be kept at
852     // RegsToPass vector
853     if (VA.isRegLoc()) {
854       if (VA.getLocVT() != MVT::f32) {
855         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
856         continue;
857       }
858       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
859       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
860       continue;
861     }
862
863     assert(VA.isMemLoc());
864
865     // Create a store off the stack pointer for this argument.
866     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
867     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
868     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
869     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
870                                        MachinePointerInfo(),
871                                        false, false, 0));
872   }
873
874
875   // Emit all stores, make sure the occur before any copies into physregs.
876   if (!MemOpChains.empty())
877     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
878                         &MemOpChains[0], MemOpChains.size());
879
880   // Build a sequence of copy-to-reg nodes chained together with token
881   // chain and flag operands which copy the outgoing args into registers.
882   // The InFlag in necessary since all emitted instructions must be
883   // stuck together.
884   SDValue InFlag;
885   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
886     unsigned Reg = toCallerWindow(RegsToPass[i].first);
887     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
888     InFlag = Chain.getValue(1);
889   }
890
891   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
892   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
893
894   // If the callee is a GlobalAddress node (quite common, every direct call is)
895   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
896   // Likewise ExternalSymbol -> TargetExternalSymbol.
897   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
898     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
899   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
900     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
901
902   // Returns a chain & a flag for retval copy to use
903   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
904   SmallVector<SDValue, 8> Ops;
905   Ops.push_back(Chain);
906   Ops.push_back(Callee);
907   if (hasStructRetAttr)
908     Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
909   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
910     Ops.push_back(DAG.getRegister(toCallerWindow(RegsToPass[i].first),
911                                   RegsToPass[i].second.getValueType()));
912
913   // Add a register mask operand representing the call-preserved registers.
914   const SparcRegisterInfo *TRI =
915     ((const SparcTargetMachine&)getTargetMachine()).getRegisterInfo();
916   const uint32_t *Mask = ((hasReturnsTwice)
917                           ? TRI->getRTCallPreservedMask(CallConv)
918                           : TRI->getCallPreservedMask(CallConv));
919   assert(Mask && "Missing call preserved mask for calling convention");
920   Ops.push_back(DAG.getRegisterMask(Mask));
921
922   if (InFlag.getNode())
923     Ops.push_back(InFlag);
924
925   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
926   InFlag = Chain.getValue(1);
927
928   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
929                              DAG.getIntPtrConstant(0, true), InFlag, dl);
930   InFlag = Chain.getValue(1);
931
932   // Assign locations to each value returned by this call.
933   SmallVector<CCValAssign, 16> RVLocs;
934   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
935                  DAG.getTarget(), RVLocs, *DAG.getContext());
936
937   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
938
939   // Copy all of the result registers out of their specified physreg.
940   for (unsigned i = 0; i != RVLocs.size(); ++i) {
941     Chain = DAG.getCopyFromReg(Chain, dl, toCallerWindow(RVLocs[i].getLocReg()),
942                                RVLocs[i].getValVT(), InFlag).getValue(1);
943     InFlag = Chain.getValue(2);
944     InVals.push_back(Chain.getValue(0));
945   }
946
947   return Chain;
948 }
949
950 // This functions returns true if CalleeName is a ABI function that returns
951 // a long double (fp128).
952 static bool isFP128ABICall(const char *CalleeName)
953 {
954   static const char *const ABICalls[] =
955     {  "_Q_add", "_Q_sub", "_Q_mul", "_Q_div",
956        "_Q_sqrt", "_Q_neg",
957        "_Q_itoq", "_Q_stoq", "_Q_dtoq", "_Q_utoq",
958        "_Q_lltoq", "_Q_ulltoq",
959        0
960     };
961   for (const char * const *I = ABICalls; *I != 0; ++I)
962     if (strcmp(CalleeName, *I) == 0)
963       return true;
964   return false;
965 }
966
967 unsigned
968 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
969 {
970   const Function *CalleeFn = 0;
971   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
972     CalleeFn = dyn_cast<Function>(G->getGlobal());
973   } else if (ExternalSymbolSDNode *E =
974              dyn_cast<ExternalSymbolSDNode>(Callee)) {
975     const Function *Fn = DAG.getMachineFunction().getFunction();
976     const Module *M = Fn->getParent();
977     const char *CalleeName = E->getSymbol();
978     CalleeFn = M->getFunction(CalleeName);
979     if (!CalleeFn && isFP128ABICall(CalleeName))
980       return 16; // Return sizeof(fp128)
981   }
982
983   if (!CalleeFn)
984     return 0;
985
986   assert(CalleeFn->hasStructRetAttr() &&
987          "Callee does not have the StructRet attribute.");
988
989   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
990   Type *ElementTy = Ty->getElementType();
991   return getDataLayout()->getTypeAllocSize(ElementTy);
992 }
993
994
995 // Fixup floating point arguments in the ... part of a varargs call.
996 //
997 // The SPARC v9 ABI requires that floating point arguments are treated the same
998 // as integers when calling a varargs function. This does not apply to the
999 // fixed arguments that are part of the function's prototype.
1000 //
1001 // This function post-processes a CCValAssign array created by
1002 // AnalyzeCallOperands().
1003 static void fixupVariableFloatArgs(SmallVectorImpl<CCValAssign> &ArgLocs,
1004                                    ArrayRef<ISD::OutputArg> Outs) {
1005   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1006     const CCValAssign &VA = ArgLocs[i];
1007     MVT ValTy = VA.getLocVT();
1008     // FIXME: What about f32 arguments? C promotes them to f64 when calling
1009     // varargs functions.
1010     if (!VA.isRegLoc() || (ValTy != MVT::f64 && ValTy != MVT::f128))
1011       continue;
1012     // The fixed arguments to a varargs function still go in FP registers.
1013     if (Outs[VA.getValNo()].IsFixed)
1014       continue;
1015
1016     // This floating point argument should be reassigned.
1017     CCValAssign NewVA;
1018
1019     // Determine the offset into the argument array.
1020     unsigned firstReg = (ValTy == MVT::f64) ? SP::D0 : SP::Q0;
1021     unsigned argSize  = (ValTy == MVT::f64) ? 8 : 16;
1022     unsigned Offset = argSize * (VA.getLocReg() - firstReg);
1023     assert(Offset < 16*8 && "Offset out of range, bad register enum?");
1024
1025     if (Offset < 6*8) {
1026       // This argument should go in %i0-%i5.
1027       unsigned IReg = SP::I0 + Offset/8;
1028       if (ValTy == MVT::f64)
1029         // Full register, just bitconvert into i64.
1030         NewVA = CCValAssign::getReg(VA.getValNo(), VA.getValVT(),
1031                                     IReg, MVT::i64, CCValAssign::BCvt);
1032       else {
1033         assert(ValTy == MVT::f128 && "Unexpected type!");
1034         // Full register, just bitconvert into i128 -- We will lower this into
1035         // two i64s in LowerCall_64.
1036         NewVA = CCValAssign::getCustomReg(VA.getValNo(), VA.getValVT(),
1037                                           IReg, MVT::i128, CCValAssign::BCvt);
1038       }
1039     } else {
1040       // This needs to go to memory, we're out of integer registers.
1041       NewVA = CCValAssign::getMem(VA.getValNo(), VA.getValVT(),
1042                                   Offset, VA.getLocVT(), VA.getLocInfo());
1043     }
1044     ArgLocs[i] = NewVA;
1045   }
1046 }
1047
1048 // Lower a call for the 64-bit ABI.
1049 SDValue
1050 SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI,
1051                                   SmallVectorImpl<SDValue> &InVals) const {
1052   SelectionDAG &DAG = CLI.DAG;
1053   SDLoc DL = CLI.DL;
1054   SDValue Chain = CLI.Chain;
1055
1056   // Sparc target does not yet support tail call optimization.
1057   CLI.IsTailCall = false;
1058
1059   // Analyze operands of the call, assigning locations to each operand.
1060   SmallVector<CCValAssign, 16> ArgLocs;
1061   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1062                  DAG.getTarget(), ArgLocs, *DAG.getContext());
1063   CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Sparc64);
1064
1065   // Get the size of the outgoing arguments stack space requirement.
1066   // The stack offset computed by CC_Sparc64 includes all arguments.
1067   // Called functions expect 6 argument words to exist in the stack frame, used
1068   // or not.
1069   unsigned ArgsSize = std::max(6*8u, CCInfo.getNextStackOffset());
1070
1071   // Keep stack frames 16-byte aligned.
1072   ArgsSize = RoundUpToAlignment(ArgsSize, 16);
1073
1074   // Varargs calls require special treatment.
1075   if (CLI.IsVarArg)
1076     fixupVariableFloatArgs(ArgLocs, CLI.Outs);
1077
1078   // Adjust the stack pointer to make room for the arguments.
1079   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
1080   // with more than 6 arguments.
1081   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1082                                DL);
1083
1084   // Collect the set of registers to pass to the function and their values.
1085   // This will be emitted as a sequence of CopyToReg nodes glued to the call
1086   // instruction.
1087   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1088
1089   // Collect chains from all the memory opeations that copy arguments to the
1090   // stack. They must follow the stack pointer adjustment above and precede the
1091   // call instruction itself.
1092   SmallVector<SDValue, 8> MemOpChains;
1093
1094   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1095     const CCValAssign &VA = ArgLocs[i];
1096     SDValue Arg = CLI.OutVals[i];
1097
1098     // Promote the value if needed.
1099     switch (VA.getLocInfo()) {
1100     default:
1101       llvm_unreachable("Unknown location info!");
1102     case CCValAssign::Full:
1103       break;
1104     case CCValAssign::SExt:
1105       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1106       break;
1107     case CCValAssign::ZExt:
1108       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1109       break;
1110     case CCValAssign::AExt:
1111       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1112       break;
1113     case CCValAssign::BCvt:
1114       // fixupVariableFloatArgs() may create bitcasts from f128 to i128. But
1115       // SPARC does not support i128 natively. Lower it into two i64, see below.
1116       if (!VA.needsCustom() || VA.getValVT() != MVT::f128
1117           || VA.getLocVT() != MVT::i128)
1118         Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1119       break;
1120     }
1121
1122     if (VA.isRegLoc()) {
1123       if (VA.needsCustom() && VA.getValVT() == MVT::f128
1124           && VA.getLocVT() == MVT::i128) {
1125         // Store and reload into the interger register reg and reg+1.
1126         unsigned Offset = 8 * (VA.getLocReg() - SP::I0);
1127         unsigned StackOffset = Offset + Subtarget->getStackPointerBias() + 128;
1128         SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
1129         SDValue HiPtrOff = DAG.getIntPtrConstant(StackOffset);
1130         HiPtrOff         = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
1131                                        HiPtrOff);
1132         SDValue LoPtrOff = DAG.getIntPtrConstant(StackOffset + 8);
1133         LoPtrOff         = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
1134                                        LoPtrOff);
1135
1136         // Store to %sp+BIAS+128+Offset
1137         SDValue Store = DAG.getStore(Chain, DL, Arg, HiPtrOff,
1138                                      MachinePointerInfo(),
1139                                      false, false, 0);
1140         // Load into Reg and Reg+1
1141         SDValue Hi64 = DAG.getLoad(MVT::i64, DL, Store, HiPtrOff,
1142                                    MachinePointerInfo(),
1143                                    false, false, false, 0);
1144         SDValue Lo64 = DAG.getLoad(MVT::i64, DL, Store, LoPtrOff,
1145                                    MachinePointerInfo(),
1146                                    false, false, false, 0);
1147         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()),
1148                                             Hi64));
1149         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()+1),
1150                                             Lo64));
1151         continue;
1152       }
1153
1154       // The custom bit on an i32 return value indicates that it should be
1155       // passed in the high bits of the register.
1156       if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
1157         Arg = DAG.getNode(ISD::SHL, DL, MVT::i64, Arg,
1158                           DAG.getConstant(32, MVT::i32));
1159
1160         // The next value may go in the low bits of the same register.
1161         // Handle both at once.
1162         if (i+1 < ArgLocs.size() && ArgLocs[i+1].isRegLoc() &&
1163             ArgLocs[i+1].getLocReg() == VA.getLocReg()) {
1164           SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64,
1165                                    CLI.OutVals[i+1]);
1166           Arg = DAG.getNode(ISD::OR, DL, MVT::i64, Arg, NV);
1167           // Skip the next value, it's already done.
1168           ++i;
1169         }
1170       }
1171       RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()), Arg));
1172       continue;
1173     }
1174
1175     assert(VA.isMemLoc());
1176
1177     // Create a store off the stack pointer for this argument.
1178     SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
1179     // The argument area starts at %fp+BIAS+128 in the callee frame,
1180     // %sp+BIAS+128 in ours.
1181     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() +
1182                                            Subtarget->getStackPointerBias() +
1183                                            128);
1184     PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
1185     MemOpChains.push_back(DAG.getStore(Chain, DL, Arg, PtrOff,
1186                                        MachinePointerInfo(),
1187                                        false, false, 0));
1188   }
1189
1190   // Emit all stores, make sure they occur before the call.
1191   if (!MemOpChains.empty())
1192     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1193                         &MemOpChains[0], MemOpChains.size());
1194
1195   // Build a sequence of CopyToReg nodes glued together with token chain and
1196   // glue operands which copy the outgoing args into registers. The InGlue is
1197   // necessary since all emitted instructions must be stuck together in order
1198   // to pass the live physical registers.
1199   SDValue InGlue;
1200   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1201     Chain = DAG.getCopyToReg(Chain, DL,
1202                              RegsToPass[i].first, RegsToPass[i].second, InGlue);
1203     InGlue = Chain.getValue(1);
1204   }
1205
1206   // If the callee is a GlobalAddress node (quite common, every direct call is)
1207   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1208   // Likewise ExternalSymbol -> TargetExternalSymbol.
1209   SDValue Callee = CLI.Callee;
1210   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
1211   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1212     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy());
1213   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1214     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
1215
1216   // Build the operands for the call instruction itself.
1217   SmallVector<SDValue, 8> Ops;
1218   Ops.push_back(Chain);
1219   Ops.push_back(Callee);
1220   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1221     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1222                                   RegsToPass[i].second.getValueType()));
1223
1224   // Add a register mask operand representing the call-preserved registers.
1225   const SparcRegisterInfo *TRI =
1226     ((const SparcTargetMachine&)getTargetMachine()).getRegisterInfo();
1227   const uint32_t *Mask = ((hasReturnsTwice)
1228                           ? TRI->getRTCallPreservedMask(CLI.CallConv)
1229                           : TRI->getCallPreservedMask(CLI.CallConv));
1230   assert(Mask && "Missing call preserved mask for calling convention");
1231   Ops.push_back(DAG.getRegisterMask(Mask));
1232
1233   // Make sure the CopyToReg nodes are glued to the call instruction which
1234   // consumes the registers.
1235   if (InGlue.getNode())
1236     Ops.push_back(InGlue);
1237
1238   // Now the call itself.
1239   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1240   Chain = DAG.getNode(SPISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
1241   InGlue = Chain.getValue(1);
1242
1243   // Revert the stack pointer immediately after the call.
1244   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1245                              DAG.getIntPtrConstant(0, true), InGlue, DL);
1246   InGlue = Chain.getValue(1);
1247
1248   // Now extract the return values. This is more or less the same as
1249   // LowerFormalArguments_64.
1250
1251   // Assign locations to each value returned by this call.
1252   SmallVector<CCValAssign, 16> RVLocs;
1253   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1254                  DAG.getTarget(), RVLocs, *DAG.getContext());
1255
1256   // Set inreg flag manually for codegen generated library calls that
1257   // return float.
1258   if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && CLI.CS == 0)
1259     CLI.Ins[0].Flags.setInReg();
1260
1261   RVInfo.AnalyzeCallResult(CLI.Ins, CC_Sparc64);
1262
1263   // Copy all of the result registers out of their specified physreg.
1264   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1265     CCValAssign &VA = RVLocs[i];
1266     unsigned Reg = toCallerWindow(VA.getLocReg());
1267
1268     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
1269     // reside in the same register in the high and low bits. Reuse the
1270     // CopyFromReg previous node to avoid duplicate copies.
1271     SDValue RV;
1272     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
1273       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
1274         RV = Chain.getValue(0);
1275
1276     // But usually we'll create a new CopyFromReg for a different register.
1277     if (!RV.getNode()) {
1278       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
1279       Chain = RV.getValue(1);
1280       InGlue = Chain.getValue(2);
1281     }
1282
1283     // Get the high bits for i32 struct elements.
1284     if (VA.getValVT() == MVT::i32 && VA.needsCustom())
1285       RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
1286                        DAG.getConstant(32, MVT::i32));
1287
1288     // The callee promoted the return value, so insert an Assert?ext SDNode so
1289     // we won't promote the value again in this function.
1290     switch (VA.getLocInfo()) {
1291     case CCValAssign::SExt:
1292       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
1293                        DAG.getValueType(VA.getValVT()));
1294       break;
1295     case CCValAssign::ZExt:
1296       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
1297                        DAG.getValueType(VA.getValVT()));
1298       break;
1299     default:
1300       break;
1301     }
1302
1303     // Truncate the register down to the return value type.
1304     if (VA.isExtInLoc())
1305       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
1306
1307     InVals.push_back(RV);
1308   }
1309
1310   return Chain;
1311 }
1312
1313 //===----------------------------------------------------------------------===//
1314 // TargetLowering Implementation
1315 //===----------------------------------------------------------------------===//
1316
1317 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
1318 /// condition.
1319 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
1320   switch (CC) {
1321   default: llvm_unreachable("Unknown integer condition code!");
1322   case ISD::SETEQ:  return SPCC::ICC_E;
1323   case ISD::SETNE:  return SPCC::ICC_NE;
1324   case ISD::SETLT:  return SPCC::ICC_L;
1325   case ISD::SETGT:  return SPCC::ICC_G;
1326   case ISD::SETLE:  return SPCC::ICC_LE;
1327   case ISD::SETGE:  return SPCC::ICC_GE;
1328   case ISD::SETULT: return SPCC::ICC_CS;
1329   case ISD::SETULE: return SPCC::ICC_LEU;
1330   case ISD::SETUGT: return SPCC::ICC_GU;
1331   case ISD::SETUGE: return SPCC::ICC_CC;
1332   }
1333 }
1334
1335 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
1336 /// FCC condition.
1337 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
1338   switch (CC) {
1339   default: llvm_unreachable("Unknown fp condition code!");
1340   case ISD::SETEQ:
1341   case ISD::SETOEQ: return SPCC::FCC_E;
1342   case ISD::SETNE:
1343   case ISD::SETUNE: return SPCC::FCC_NE;
1344   case ISD::SETLT:
1345   case ISD::SETOLT: return SPCC::FCC_L;
1346   case ISD::SETGT:
1347   case ISD::SETOGT: return SPCC::FCC_G;
1348   case ISD::SETLE:
1349   case ISD::SETOLE: return SPCC::FCC_LE;
1350   case ISD::SETGE:
1351   case ISD::SETOGE: return SPCC::FCC_GE;
1352   case ISD::SETULT: return SPCC::FCC_UL;
1353   case ISD::SETULE: return SPCC::FCC_ULE;
1354   case ISD::SETUGT: return SPCC::FCC_UG;
1355   case ISD::SETUGE: return SPCC::FCC_UGE;
1356   case ISD::SETUO:  return SPCC::FCC_U;
1357   case ISD::SETO:   return SPCC::FCC_O;
1358   case ISD::SETONE: return SPCC::FCC_LG;
1359   case ISD::SETUEQ: return SPCC::FCC_UE;
1360   }
1361 }
1362
1363 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
1364   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
1365   Subtarget = &TM.getSubtarget<SparcSubtarget>();
1366
1367   // Set up the register classes.
1368   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
1369   addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
1370   addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
1371   addRegisterClass(MVT::f128, &SP::QFPRegsRegClass);
1372   if (Subtarget->is64Bit())
1373     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
1374
1375   // Turn FP extload into load/fextend
1376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
1378
1379   // Sparc doesn't have i1 sign extending load
1380   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1381
1382   // Turn FP truncstore into trunc + store.
1383   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1384   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1385   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1386
1387   // Custom legalize GlobalAddress nodes into LO/HI parts.
1388   setOperationAction(ISD::GlobalAddress, getPointerTy(), Custom);
1389   setOperationAction(ISD::GlobalTLSAddress, getPointerTy(), Custom);
1390   setOperationAction(ISD::ConstantPool, getPointerTy(), Custom);
1391   setOperationAction(ISD::BlockAddress, getPointerTy(), Custom);
1392
1393   // Sparc doesn't have sext_inreg, replace them with shl/sra
1394   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1395   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
1396   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1397
1398   // Sparc has no REM or DIVREM operations.
1399   setOperationAction(ISD::UREM, MVT::i32, Expand);
1400   setOperationAction(ISD::SREM, MVT::i32, Expand);
1401   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1402   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1403
1404   // ... nor does SparcV9.
1405   if (Subtarget->is64Bit()) {
1406     setOperationAction(ISD::UREM, MVT::i64, Expand);
1407     setOperationAction(ISD::SREM, MVT::i64, Expand);
1408     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1409     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1410   }
1411
1412   // Custom expand fp<->sint
1413   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1414   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1415   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
1416   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
1417
1418   // Custom Expand fp<->uint
1419   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1420   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1421   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
1422   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
1423
1424   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
1425   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
1426
1427   // Sparc has no select or setcc: expand to SELECT_CC.
1428   setOperationAction(ISD::SELECT, MVT::i32, Expand);
1429   setOperationAction(ISD::SELECT, MVT::f32, Expand);
1430   setOperationAction(ISD::SELECT, MVT::f64, Expand);
1431   setOperationAction(ISD::SELECT, MVT::f128, Expand);
1432
1433   setOperationAction(ISD::SETCC, MVT::i32, Expand);
1434   setOperationAction(ISD::SETCC, MVT::f32, Expand);
1435   setOperationAction(ISD::SETCC, MVT::f64, Expand);
1436   setOperationAction(ISD::SETCC, MVT::f128, Expand);
1437
1438   // Sparc doesn't have BRCOND either, it has BR_CC.
1439   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1440   setOperationAction(ISD::BRIND, MVT::Other, Expand);
1441   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1442   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1443   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1444   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1445   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
1446
1447   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1448   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1449   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1450   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1451
1452   if (Subtarget->is64Bit()) {
1453     setOperationAction(ISD::ADDC, MVT::i64, Custom);
1454     setOperationAction(ISD::ADDE, MVT::i64, Custom);
1455     setOperationAction(ISD::SUBC, MVT::i64, Custom);
1456     setOperationAction(ISD::SUBE, MVT::i64, Custom);
1457     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
1458     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
1459     setOperationAction(ISD::SELECT, MVT::i64, Expand);
1460     setOperationAction(ISD::SETCC, MVT::i64, Expand);
1461     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1462     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1463
1464     setOperationAction(ISD::CTPOP, MVT::i64, Legal);
1465     setOperationAction(ISD::CTTZ , MVT::i64, Expand);
1466     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
1467     setOperationAction(ISD::CTLZ , MVT::i64, Expand);
1468     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
1469     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1470     setOperationAction(ISD::ROTL , MVT::i64, Expand);
1471     setOperationAction(ISD::ROTR , MVT::i64, Expand);
1472     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
1473   }
1474
1475   // ATOMICs.
1476   // FIXME: We insert fences for each atomics and generate sub-optimal code
1477   // for PSO/TSO. Also, implement other atomicrmw operations.
1478
1479   setInsertFencesForAtomic(true);
1480
1481   setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Legal);
1482   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32,
1483                      (Subtarget->isV9() ? Legal: Expand));
1484
1485
1486   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Legal);
1487
1488   // Custom Lower Atomic LOAD/STORE
1489   setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1490   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1491
1492   if (Subtarget->is64Bit()) {
1493     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Legal);
1494     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Expand);
1495     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
1496     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
1497   }
1498
1499   if (!Subtarget->isV9()) {
1500     // SparcV8 does not have FNEGD and FABSD.
1501     setOperationAction(ISD::FNEG, MVT::f64, Custom);
1502     setOperationAction(ISD::FABS, MVT::f64, Custom);
1503   }
1504
1505   setOperationAction(ISD::FSIN , MVT::f128, Expand);
1506   setOperationAction(ISD::FCOS , MVT::f128, Expand);
1507   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
1508   setOperationAction(ISD::FREM , MVT::f128, Expand);
1509   setOperationAction(ISD::FMA  , MVT::f128, Expand);
1510   setOperationAction(ISD::FSIN , MVT::f64, Expand);
1511   setOperationAction(ISD::FCOS , MVT::f64, Expand);
1512   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1513   setOperationAction(ISD::FREM , MVT::f64, Expand);
1514   setOperationAction(ISD::FMA  , MVT::f64, Expand);
1515   setOperationAction(ISD::FSIN , MVT::f32, Expand);
1516   setOperationAction(ISD::FCOS , MVT::f32, Expand);
1517   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1518   setOperationAction(ISD::FREM , MVT::f32, Expand);
1519   setOperationAction(ISD::FMA  , MVT::f32, Expand);
1520   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1521   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1522   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1523   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1524   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1525   setOperationAction(ISD::ROTL , MVT::i32, Expand);
1526   setOperationAction(ISD::ROTR , MVT::i32, Expand);
1527   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1528   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1529   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1530   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1531   setOperationAction(ISD::FPOW , MVT::f128, Expand);
1532   setOperationAction(ISD::FPOW , MVT::f64, Expand);
1533   setOperationAction(ISD::FPOW , MVT::f32, Expand);
1534
1535   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1536   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1537   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1538
1539   // FIXME: Sparc provides these multiplies, but we don't have them yet.
1540   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1541   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1542
1543   if (Subtarget->is64Bit()) {
1544     setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1545     setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1546     setOperationAction(ISD::MULHU,     MVT::i64, Expand);
1547     setOperationAction(ISD::MULHS,     MVT::i64, Expand);
1548
1549     setOperationAction(ISD::UMULO,     MVT::i64, Custom);
1550     setOperationAction(ISD::SMULO,     MVT::i64, Custom);
1551   }
1552
1553   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1554   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1555   // VAARG needs to be lowered to not do unaligned accesses for doubles.
1556   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1557
1558   // Use the default implementation.
1559   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1560   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1561   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1562   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1563   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1564
1565   setExceptionPointerRegister(SP::I0);
1566   setExceptionSelectorRegister(SP::I1);
1567
1568   setStackPointerRegisterToSaveRestore(SP::O6);
1569
1570   if (Subtarget->isV9())
1571     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1572
1573   if (Subtarget->isV9() && Subtarget->hasHardQuad()) {
1574     setOperationAction(ISD::LOAD, MVT::f128, Legal);
1575     setOperationAction(ISD::STORE, MVT::f128, Legal);
1576   } else {
1577     setOperationAction(ISD::LOAD, MVT::f128, Custom);
1578     setOperationAction(ISD::STORE, MVT::f128, Custom);
1579   }
1580
1581   if (Subtarget->hasHardQuad()) {
1582     setOperationAction(ISD::FADD,  MVT::f128, Legal);
1583     setOperationAction(ISD::FSUB,  MVT::f128, Legal);
1584     setOperationAction(ISD::FMUL,  MVT::f128, Legal);
1585     setOperationAction(ISD::FDIV,  MVT::f128, Legal);
1586     setOperationAction(ISD::FSQRT, MVT::f128, Legal);
1587     setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1588     setOperationAction(ISD::FP_ROUND,  MVT::f64, Legal);
1589     if (Subtarget->isV9()) {
1590       setOperationAction(ISD::FNEG, MVT::f128, Legal);
1591       setOperationAction(ISD::FABS, MVT::f128, Legal);
1592     } else {
1593       setOperationAction(ISD::FNEG, MVT::f128, Custom);
1594       setOperationAction(ISD::FABS, MVT::f128, Custom);
1595     }
1596
1597     if (!Subtarget->is64Bit()) {
1598       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1599       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1600       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1601       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1602     }
1603
1604   } else {
1605     // Custom legalize f128 operations.
1606
1607     setOperationAction(ISD::FADD,  MVT::f128, Custom);
1608     setOperationAction(ISD::FSUB,  MVT::f128, Custom);
1609     setOperationAction(ISD::FMUL,  MVT::f128, Custom);
1610     setOperationAction(ISD::FDIV,  MVT::f128, Custom);
1611     setOperationAction(ISD::FSQRT, MVT::f128, Custom);
1612     setOperationAction(ISD::FNEG,  MVT::f128, Custom);
1613     setOperationAction(ISD::FABS,  MVT::f128, Custom);
1614
1615     setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
1616     setOperationAction(ISD::FP_ROUND,  MVT::f64, Custom);
1617     setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
1618
1619     // Setup Runtime library names.
1620     if (Subtarget->is64Bit()) {
1621       setLibcallName(RTLIB::ADD_F128,  "_Qp_add");
1622       setLibcallName(RTLIB::SUB_F128,  "_Qp_sub");
1623       setLibcallName(RTLIB::MUL_F128,  "_Qp_mul");
1624       setLibcallName(RTLIB::DIV_F128,  "_Qp_div");
1625       setLibcallName(RTLIB::SQRT_F128, "_Qp_sqrt");
1626       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Qp_qtoi");
1627       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Qp_qtoui");
1628       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Qp_itoq");
1629       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Qp_uitoq");
1630       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Qp_qtox");
1631       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Qp_qtoux");
1632       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Qp_xtoq");
1633       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Qp_uxtoq");
1634       setLibcallName(RTLIB::FPEXT_F32_F128, "_Qp_stoq");
1635       setLibcallName(RTLIB::FPEXT_F64_F128, "_Qp_dtoq");
1636       setLibcallName(RTLIB::FPROUND_F128_F32, "_Qp_qtos");
1637       setLibcallName(RTLIB::FPROUND_F128_F64, "_Qp_qtod");
1638     } else {
1639       setLibcallName(RTLIB::ADD_F128,  "_Q_add");
1640       setLibcallName(RTLIB::SUB_F128,  "_Q_sub");
1641       setLibcallName(RTLIB::MUL_F128,  "_Q_mul");
1642       setLibcallName(RTLIB::DIV_F128,  "_Q_div");
1643       setLibcallName(RTLIB::SQRT_F128, "_Q_sqrt");
1644       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Q_qtoi");
1645       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Q_qtou");
1646       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Q_itoq");
1647       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Q_utoq");
1648       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1649       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1650       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1651       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1652       setLibcallName(RTLIB::FPEXT_F32_F128, "_Q_stoq");
1653       setLibcallName(RTLIB::FPEXT_F64_F128, "_Q_dtoq");
1654       setLibcallName(RTLIB::FPROUND_F128_F32, "_Q_qtos");
1655       setLibcallName(RTLIB::FPROUND_F128_F64, "_Q_qtod");
1656     }
1657   }
1658
1659   setMinFunctionAlignment(2);
1660
1661   computeRegisterProperties();
1662 }
1663
1664 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1665   switch (Opcode) {
1666   default: return 0;
1667   case SPISD::CMPICC:     return "SPISD::CMPICC";
1668   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
1669   case SPISD::BRICC:      return "SPISD::BRICC";
1670   case SPISD::BRXCC:      return "SPISD::BRXCC";
1671   case SPISD::BRFCC:      return "SPISD::BRFCC";
1672   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
1673   case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
1674   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
1675   case SPISD::Hi:         return "SPISD::Hi";
1676   case SPISD::Lo:         return "SPISD::Lo";
1677   case SPISD::FTOI:       return "SPISD::FTOI";
1678   case SPISD::ITOF:       return "SPISD::ITOF";
1679   case SPISD::FTOX:       return "SPISD::FTOX";
1680   case SPISD::XTOF:       return "SPISD::XTOF";
1681   case SPISD::CALL:       return "SPISD::CALL";
1682   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
1683   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1684   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
1685   case SPISD::TLS_ADD:    return "SPISD::TLS_ADD";
1686   case SPISD::TLS_LD:     return "SPISD::TLS_LD";
1687   case SPISD::TLS_CALL:   return "SPISD::TLS_CALL";
1688   }
1689 }
1690
1691 EVT SparcTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1692   if (!VT.isVector())
1693     return MVT::i32;
1694   return VT.changeVectorElementTypeToInteger();
1695 }
1696
1697 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1698 /// be zero. Op is expected to be a target specific node. Used by DAG
1699 /// combiner.
1700 void SparcTargetLowering::computeMaskedBitsForTargetNode
1701                                 (const SDValue Op,
1702                                  APInt &KnownZero,
1703                                  APInt &KnownOne,
1704                                  const SelectionDAG &DAG,
1705                                  unsigned Depth) const {
1706   APInt KnownZero2, KnownOne2;
1707   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1708
1709   switch (Op.getOpcode()) {
1710   default: break;
1711   case SPISD::SELECT_ICC:
1712   case SPISD::SELECT_XCC:
1713   case SPISD::SELECT_FCC:
1714     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1715     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1716     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1717     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1718
1719     // Only known if known in both the LHS and RHS.
1720     KnownOne &= KnownOne2;
1721     KnownZero &= KnownZero2;
1722     break;
1723   }
1724 }
1725
1726 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1727 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1728 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1729                              ISD::CondCode CC, unsigned &SPCC) {
1730   if (isa<ConstantSDNode>(RHS) &&
1731       cast<ConstantSDNode>(RHS)->isNullValue() &&
1732       CC == ISD::SETNE &&
1733       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1734          LHS.getOpcode() == SPISD::SELECT_XCC) &&
1735         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1736        (LHS.getOpcode() == SPISD::SELECT_FCC &&
1737         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1738       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1739       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1740       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
1741       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
1742     SDValue CMPCC = LHS.getOperand(3);
1743     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1744     LHS = CMPCC.getOperand(0);
1745     RHS = CMPCC.getOperand(1);
1746   }
1747 }
1748
1749 // Convert to a target node and set target flags.
1750 SDValue SparcTargetLowering::withTargetFlags(SDValue Op, unsigned TF,
1751                                              SelectionDAG &DAG) const {
1752   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1753     return DAG.getTargetGlobalAddress(GA->getGlobal(),
1754                                       SDLoc(GA),
1755                                       GA->getValueType(0),
1756                                       GA->getOffset(), TF);
1757
1758   if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op))
1759     return DAG.getTargetConstantPool(CP->getConstVal(),
1760                                      CP->getValueType(0),
1761                                      CP->getAlignment(),
1762                                      CP->getOffset(), TF);
1763
1764   if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op))
1765     return DAG.getTargetBlockAddress(BA->getBlockAddress(),
1766                                      Op.getValueType(),
1767                                      0,
1768                                      TF);
1769
1770   if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op))
1771     return DAG.getTargetExternalSymbol(ES->getSymbol(),
1772                                        ES->getValueType(0), TF);
1773
1774   llvm_unreachable("Unhandled address SDNode");
1775 }
1776
1777 // Split Op into high and low parts according to HiTF and LoTF.
1778 // Return an ADD node combining the parts.
1779 SDValue SparcTargetLowering::makeHiLoPair(SDValue Op,
1780                                           unsigned HiTF, unsigned LoTF,
1781                                           SelectionDAG &DAG) const {
1782   SDLoc DL(Op);
1783   EVT VT = Op.getValueType();
1784   SDValue Hi = DAG.getNode(SPISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG));
1785   SDValue Lo = DAG.getNode(SPISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG));
1786   return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
1787 }
1788
1789 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool,
1790 // or ExternalSymbol SDNode.
1791 SDValue SparcTargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const {
1792   SDLoc DL(Op);
1793   EVT VT = getPointerTy();
1794
1795   // Handle PIC mode first.
1796   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1797     // This is the pic32 code model, the GOT is known to be smaller than 4GB.
1798     SDValue HiLo = makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1799     SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, VT);
1800     SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, VT, GlobalBase, HiLo);
1801     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
1802     // function has calls.
1803     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1804     MFI->setHasCalls(true);
1805     return DAG.getLoad(VT, DL, DAG.getEntryNode(), AbsAddr,
1806                        MachinePointerInfo::getGOT(), false, false, false, 0);
1807   }
1808
1809   // This is one of the absolute code models.
1810   switch(getTargetMachine().getCodeModel()) {
1811   default:
1812     llvm_unreachable("Unsupported absolute code model");
1813   case CodeModel::JITDefault:
1814   case CodeModel::Small:
1815     // abs32.
1816     return makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1817   case CodeModel::Medium: {
1818     // abs44.
1819     SDValue H44 = makeHiLoPair(Op, SPII::MO_H44, SPII::MO_M44, DAG);
1820     H44 = DAG.getNode(ISD::SHL, DL, VT, H44, DAG.getConstant(12, MVT::i32));
1821     SDValue L44 = withTargetFlags(Op, SPII::MO_L44, DAG);
1822     L44 = DAG.getNode(SPISD::Lo, DL, VT, L44);
1823     return DAG.getNode(ISD::ADD, DL, VT, H44, L44);
1824   }
1825   case CodeModel::Large: {
1826     // abs64.
1827     SDValue Hi = makeHiLoPair(Op, SPII::MO_HH, SPII::MO_HM, DAG);
1828     Hi = DAG.getNode(ISD::SHL, DL, VT, Hi, DAG.getConstant(32, MVT::i32));
1829     SDValue Lo = makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1830     return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
1831   }
1832   }
1833 }
1834
1835 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
1836                                                 SelectionDAG &DAG) const {
1837   return makeAddress(Op, DAG);
1838 }
1839
1840 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
1841                                                SelectionDAG &DAG) const {
1842   return makeAddress(Op, DAG);
1843 }
1844
1845 SDValue SparcTargetLowering::LowerBlockAddress(SDValue Op,
1846                                                SelectionDAG &DAG) const {
1847   return makeAddress(Op, DAG);
1848 }
1849
1850 SDValue SparcTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1851                                                    SelectionDAG &DAG) const {
1852
1853   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1854   SDLoc DL(GA);
1855   const GlobalValue *GV = GA->getGlobal();
1856   EVT PtrVT = getPointerTy();
1857
1858   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1859
1860   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1861     unsigned HiTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_HI22
1862                      : SPII::MO_TLS_LDM_HI22);
1863     unsigned LoTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_LO10
1864                      : SPII::MO_TLS_LDM_LO10);
1865     unsigned addTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_ADD
1866                       : SPII::MO_TLS_LDM_ADD);
1867     unsigned callTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_CALL
1868                        : SPII::MO_TLS_LDM_CALL);
1869
1870     SDValue HiLo = makeHiLoPair(Op, HiTF, LoTF, DAG);
1871     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
1872     SDValue Argument = DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Base, HiLo,
1873                                withTargetFlags(Op, addTF, DAG));
1874
1875     SDValue Chain = DAG.getEntryNode();
1876     SDValue InFlag;
1877
1878     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(1, true), DL);
1879     Chain = DAG.getCopyToReg(Chain, DL, SP::O0, Argument, InFlag);
1880     InFlag = Chain.getValue(1);
1881     SDValue Callee = DAG.getTargetExternalSymbol("__tls_get_addr", PtrVT);
1882     SDValue Symbol = withTargetFlags(Op, callTF, DAG);
1883
1884     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1885     SmallVector<SDValue, 4> Ops;
1886     Ops.push_back(Chain);
1887     Ops.push_back(Callee);
1888     Ops.push_back(Symbol);
1889     Ops.push_back(DAG.getRegister(SP::O0, PtrVT));
1890     const uint32_t *Mask = getTargetMachine()
1891       .getRegisterInfo()->getCallPreservedMask(CallingConv::C);
1892     assert(Mask && "Missing call preserved mask for calling convention");
1893     Ops.push_back(DAG.getRegisterMask(Mask));
1894     Ops.push_back(InFlag);
1895     Chain = DAG.getNode(SPISD::TLS_CALL, DL, NodeTys, &Ops[0], Ops.size());
1896     InFlag = Chain.getValue(1);
1897     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(1, true),
1898                                DAG.getIntPtrConstant(0, true), InFlag, DL);
1899     InFlag = Chain.getValue(1);
1900     SDValue Ret = DAG.getCopyFromReg(Chain, DL, SP::O0, PtrVT, InFlag);
1901
1902     if (model != TLSModel::LocalDynamic)
1903       return Ret;
1904
1905     SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
1906                              withTargetFlags(Op, SPII::MO_TLS_LDO_HIX22, DAG));
1907     SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
1908                              withTargetFlags(Op, SPII::MO_TLS_LDO_LOX10, DAG));
1909     HiLo =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
1910     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Ret, HiLo,
1911                        withTargetFlags(Op, SPII::MO_TLS_LDO_ADD, DAG));
1912   }
1913
1914   if (model == TLSModel::InitialExec) {
1915     unsigned ldTF     = ((PtrVT == MVT::i64)? SPII::MO_TLS_IE_LDX
1916                          : SPII::MO_TLS_IE_LD);
1917
1918     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
1919
1920     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
1921     // function has calls.
1922     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1923     MFI->setHasCalls(true);
1924
1925     SDValue TGA = makeHiLoPair(Op,
1926                                SPII::MO_TLS_IE_HI22, SPII::MO_TLS_IE_LO10, DAG);
1927     SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base, TGA);
1928     SDValue Offset = DAG.getNode(SPISD::TLS_LD,
1929                                  DL, PtrVT, Ptr,
1930                                  withTargetFlags(Op, ldTF, DAG));
1931     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT,
1932                        DAG.getRegister(SP::G7, PtrVT), Offset,
1933                        withTargetFlags(Op, SPII::MO_TLS_IE_ADD, DAG));
1934   }
1935
1936   assert(model == TLSModel::LocalExec);
1937   SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
1938                            withTargetFlags(Op, SPII::MO_TLS_LE_HIX22, DAG));
1939   SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
1940                            withTargetFlags(Op, SPII::MO_TLS_LE_LOX10, DAG));
1941   SDValue Offset =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
1942
1943   return DAG.getNode(ISD::ADD, DL, PtrVT,
1944                      DAG.getRegister(SP::G7, PtrVT), Offset);
1945 }
1946
1947 SDValue
1948 SparcTargetLowering::LowerF128_LibCallArg(SDValue Chain, ArgListTy &Args,
1949                                           SDValue Arg, SDLoc DL,
1950                                           SelectionDAG &DAG) const {
1951   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1952   EVT ArgVT = Arg.getValueType();
1953   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1954
1955   ArgListEntry Entry;
1956   Entry.Node = Arg;
1957   Entry.Ty   = ArgTy;
1958
1959   if (ArgTy->isFP128Ty()) {
1960     // Create a stack object and pass the pointer to the library function.
1961     int FI = MFI->CreateStackObject(16, 8, false);
1962     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
1963     Chain = DAG.getStore(Chain,
1964                          DL,
1965                          Entry.Node,
1966                          FIPtr,
1967                          MachinePointerInfo(),
1968                          false,
1969                          false,
1970                          8);
1971
1972     Entry.Node = FIPtr;
1973     Entry.Ty   = PointerType::getUnqual(ArgTy);
1974   }
1975   Args.push_back(Entry);
1976   return Chain;
1977 }
1978
1979 SDValue
1980 SparcTargetLowering::LowerF128Op(SDValue Op, SelectionDAG &DAG,
1981                                  const char *LibFuncName,
1982                                  unsigned numArgs) const {
1983
1984   ArgListTy Args;
1985
1986   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1987
1988   SDValue Callee = DAG.getExternalSymbol(LibFuncName, getPointerTy());
1989   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1990   Type *RetTyABI = RetTy;
1991   SDValue Chain = DAG.getEntryNode();
1992   SDValue RetPtr;
1993
1994   if (RetTy->isFP128Ty()) {
1995     // Create a Stack Object to receive the return value of type f128.
1996     ArgListEntry Entry;
1997     int RetFI = MFI->CreateStackObject(16, 8, false);
1998     RetPtr = DAG.getFrameIndex(RetFI, getPointerTy());
1999     Entry.Node = RetPtr;
2000     Entry.Ty   = PointerType::getUnqual(RetTy);
2001     if (!Subtarget->is64Bit())
2002       Entry.isSRet = true;
2003     Entry.isReturned = false;
2004     Args.push_back(Entry);
2005     RetTyABI = Type::getVoidTy(*DAG.getContext());
2006   }
2007
2008   assert(Op->getNumOperands() >= numArgs && "Not enough operands!");
2009   for (unsigned i = 0, e = numArgs; i != e; ++i) {
2010     Chain = LowerF128_LibCallArg(Chain, Args, Op.getOperand(i), SDLoc(Op), DAG);
2011   }
2012   TargetLowering::
2013     CallLoweringInfo CLI(Chain,
2014                          RetTyABI,
2015                          false, false, false, false,
2016                          0, CallingConv::C,
2017                          false, false, true,
2018                          Callee, Args, DAG, SDLoc(Op));
2019   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2020
2021   // chain is in second result.
2022   if (RetTyABI == RetTy)
2023     return CallInfo.first;
2024
2025   assert (RetTy->isFP128Ty() && "Unexpected return type!");
2026
2027   Chain = CallInfo.second;
2028
2029   // Load RetPtr to get the return value.
2030   return DAG.getLoad(Op.getValueType(),
2031                      SDLoc(Op),
2032                      Chain,
2033                      RetPtr,
2034                      MachinePointerInfo(),
2035                      false, false, false, 8);
2036 }
2037
2038 SDValue
2039 SparcTargetLowering::LowerF128Compare(SDValue LHS, SDValue RHS,
2040                                       unsigned &SPCC,
2041                                       SDLoc DL,
2042                                       SelectionDAG &DAG) const {
2043
2044   const char *LibCall = 0;
2045   bool is64Bit = Subtarget->is64Bit();
2046   switch(SPCC) {
2047   default: llvm_unreachable("Unhandled conditional code!");
2048   case SPCC::FCC_E  : LibCall = is64Bit? "_Qp_feq" : "_Q_feq"; break;
2049   case SPCC::FCC_NE : LibCall = is64Bit? "_Qp_fne" : "_Q_fne"; break;
2050   case SPCC::FCC_L  : LibCall = is64Bit? "_Qp_flt" : "_Q_flt"; break;
2051   case SPCC::FCC_G  : LibCall = is64Bit? "_Qp_fgt" : "_Q_fgt"; break;
2052   case SPCC::FCC_LE : LibCall = is64Bit? "_Qp_fle" : "_Q_fle"; break;
2053   case SPCC::FCC_GE : LibCall = is64Bit? "_Qp_fge" : "_Q_fge"; break;
2054   case SPCC::FCC_UL :
2055   case SPCC::FCC_ULE:
2056   case SPCC::FCC_UG :
2057   case SPCC::FCC_UGE:
2058   case SPCC::FCC_U  :
2059   case SPCC::FCC_O  :
2060   case SPCC::FCC_LG :
2061   case SPCC::FCC_UE : LibCall = is64Bit? "_Qp_cmp" : "_Q_cmp"; break;
2062   }
2063
2064   SDValue Callee = DAG.getExternalSymbol(LibCall, getPointerTy());
2065   Type *RetTy = Type::getInt32Ty(*DAG.getContext());
2066   ArgListTy Args;
2067   SDValue Chain = DAG.getEntryNode();
2068   Chain = LowerF128_LibCallArg(Chain, Args, LHS, DL, DAG);
2069   Chain = LowerF128_LibCallArg(Chain, Args, RHS, DL, DAG);
2070
2071   TargetLowering::
2072     CallLoweringInfo CLI(Chain,
2073                          RetTy,
2074                          false, false, false, false,
2075                          0, CallingConv::C,
2076                          false, false, true,
2077                          Callee, Args, DAG, DL);
2078
2079   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2080
2081   // result is in first, and chain is in second result.
2082   SDValue Result =  CallInfo.first;
2083
2084   switch(SPCC) {
2085   default: {
2086     SDValue RHS = DAG.getTargetConstant(0, Result.getValueType());
2087     SPCC = SPCC::ICC_NE;
2088     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2089   }
2090   case SPCC::FCC_UL : {
2091     SDValue Mask   = DAG.getTargetConstant(1, Result.getValueType());
2092     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2093     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2094     SPCC = SPCC::ICC_NE;
2095     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2096   }
2097   case SPCC::FCC_ULE: {
2098     SDValue RHS = DAG.getTargetConstant(2, Result.getValueType());
2099     SPCC = SPCC::ICC_NE;
2100     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2101   }
2102   case SPCC::FCC_UG :  {
2103     SDValue RHS = DAG.getTargetConstant(1, Result.getValueType());
2104     SPCC = SPCC::ICC_G;
2105     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2106   }
2107   case SPCC::FCC_UGE: {
2108     SDValue RHS = DAG.getTargetConstant(1, Result.getValueType());
2109     SPCC = SPCC::ICC_NE;
2110     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2111   }
2112
2113   case SPCC::FCC_U  :  {
2114     SDValue RHS = DAG.getTargetConstant(3, Result.getValueType());
2115     SPCC = SPCC::ICC_E;
2116     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2117   }
2118   case SPCC::FCC_O  :  {
2119     SDValue RHS = DAG.getTargetConstant(3, Result.getValueType());
2120     SPCC = SPCC::ICC_NE;
2121     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2122   }
2123   case SPCC::FCC_LG :  {
2124     SDValue Mask   = DAG.getTargetConstant(3, Result.getValueType());
2125     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2126     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2127     SPCC = SPCC::ICC_NE;
2128     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2129   }
2130   case SPCC::FCC_UE : {
2131     SDValue Mask   = DAG.getTargetConstant(3, Result.getValueType());
2132     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2133     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2134     SPCC = SPCC::ICC_E;
2135     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2136   }
2137   }
2138 }
2139
2140 static SDValue
2141 LowerF128_FPEXTEND(SDValue Op, SelectionDAG &DAG,
2142                    const SparcTargetLowering &TLI) {
2143
2144   if (Op.getOperand(0).getValueType() == MVT::f64)
2145     return TLI.LowerF128Op(Op, DAG,
2146                            TLI.getLibcallName(RTLIB::FPEXT_F64_F128), 1);
2147
2148   if (Op.getOperand(0).getValueType() == MVT::f32)
2149     return TLI.LowerF128Op(Op, DAG,
2150                            TLI.getLibcallName(RTLIB::FPEXT_F32_F128), 1);
2151
2152   llvm_unreachable("fpextend with non-float operand!");
2153   return SDValue(0, 0);
2154 }
2155
2156 static SDValue
2157 LowerF128_FPROUND(SDValue Op, SelectionDAG &DAG,
2158                   const SparcTargetLowering &TLI) {
2159   // FP_ROUND on f64 and f32 are legal.
2160   if (Op.getOperand(0).getValueType() != MVT::f128)
2161     return Op;
2162
2163   if (Op.getValueType() == MVT::f64)
2164     return TLI.LowerF128Op(Op, DAG,
2165                            TLI.getLibcallName(RTLIB::FPROUND_F128_F64), 1);
2166   if (Op.getValueType() == MVT::f32)
2167     return TLI.LowerF128Op(Op, DAG,
2168                            TLI.getLibcallName(RTLIB::FPROUND_F128_F32), 1);
2169
2170   llvm_unreachable("fpround to non-float!");
2171   return SDValue(0, 0);
2172 }
2173
2174 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG,
2175                                const SparcTargetLowering &TLI,
2176                                bool hasHardQuad) {
2177   SDLoc dl(Op);
2178   EVT VT = Op.getValueType();
2179   assert(VT == MVT::i32 || VT == MVT::i64);
2180
2181   // Expand f128 operations to fp128 abi calls.
2182   if (Op.getOperand(0).getValueType() == MVT::f128
2183       && (!hasHardQuad || !TLI.isTypeLegal(VT))) {
2184     const char *libName = TLI.getLibcallName(VT == MVT::i32
2185                                              ? RTLIB::FPTOSINT_F128_I32
2186                                              : RTLIB::FPTOSINT_F128_I64);
2187     return TLI.LowerF128Op(Op, DAG, libName, 1);
2188   }
2189
2190   // Expand if the resulting type is illegal.
2191   if (!TLI.isTypeLegal(VT))
2192     return SDValue(0, 0);
2193
2194   // Otherwise, Convert the fp value to integer in an FP register.
2195   if (VT == MVT::i32)
2196     Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
2197   else
2198     Op = DAG.getNode(SPISD::FTOX, dl, MVT::f64, Op.getOperand(0));
2199
2200   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
2201 }
2202
2203 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2204                                const SparcTargetLowering &TLI,
2205                                bool hasHardQuad) {
2206   SDLoc dl(Op);
2207   EVT OpVT = Op.getOperand(0).getValueType();
2208   assert(OpVT == MVT::i32 || (OpVT == MVT::i64));
2209
2210   EVT floatVT = (OpVT == MVT::i32) ? MVT::f32 : MVT::f64;
2211
2212   // Expand f128 operations to fp128 ABI calls.
2213   if (Op.getValueType() == MVT::f128
2214       && (!hasHardQuad || !TLI.isTypeLegal(OpVT))) {
2215     const char *libName = TLI.getLibcallName(OpVT == MVT::i32
2216                                              ? RTLIB::SINTTOFP_I32_F128
2217                                              : RTLIB::SINTTOFP_I64_F128);
2218     return TLI.LowerF128Op(Op, DAG, libName, 1);
2219   }
2220
2221   // Expand if the operand type is illegal.
2222   if (!TLI.isTypeLegal(OpVT))
2223     return SDValue(0, 0);
2224
2225   // Otherwise, Convert the int value to FP in an FP register.
2226   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, floatVT, Op.getOperand(0));
2227   unsigned opcode = (OpVT == MVT::i32)? SPISD::ITOF : SPISD::XTOF;
2228   return DAG.getNode(opcode, dl, Op.getValueType(), Tmp);
2229 }
2230
2231 static SDValue LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG,
2232                                const SparcTargetLowering &TLI,
2233                                bool hasHardQuad) {
2234   SDLoc dl(Op);
2235   EVT VT = Op.getValueType();
2236
2237   // Expand if it does not involve f128 or the target has support for
2238   // quad floating point instructions and the resulting type is legal.
2239   if (Op.getOperand(0).getValueType() != MVT::f128 ||
2240       (hasHardQuad && TLI.isTypeLegal(VT)))
2241     return SDValue(0, 0);
2242
2243   assert(VT == MVT::i32 || VT == MVT::i64);
2244
2245   return TLI.LowerF128Op(Op, DAG,
2246                          TLI.getLibcallName(VT == MVT::i32
2247                                             ? RTLIB::FPTOUINT_F128_I32
2248                                             : RTLIB::FPTOUINT_F128_I64),
2249                          1);
2250 }
2251
2252 static SDValue LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2253                                const SparcTargetLowering &TLI,
2254                                bool hasHardQuad) {
2255   SDLoc dl(Op);
2256   EVT OpVT = Op.getOperand(0).getValueType();
2257   assert(OpVT == MVT::i32 || OpVT == MVT::i64);
2258
2259   // Expand if it does not involve f128 or the target has support for
2260   // quad floating point instructions and the operand type is legal.
2261   if (Op.getValueType() != MVT::f128 || (hasHardQuad && TLI.isTypeLegal(OpVT)))
2262     return SDValue(0, 0);
2263
2264   return TLI.LowerF128Op(Op, DAG,
2265                          TLI.getLibcallName(OpVT == MVT::i32
2266                                             ? RTLIB::UINTTOFP_I32_F128
2267                                             : RTLIB::UINTTOFP_I64_F128),
2268                          1);
2269 }
2270
2271 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
2272                           const SparcTargetLowering &TLI,
2273                           bool hasHardQuad) {
2274   SDValue Chain = Op.getOperand(0);
2275   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2276   SDValue LHS = Op.getOperand(2);
2277   SDValue RHS = Op.getOperand(3);
2278   SDValue Dest = Op.getOperand(4);
2279   SDLoc dl(Op);
2280   unsigned Opc, SPCC = ~0U;
2281
2282   // If this is a br_cc of a "setcc", and if the setcc got lowered into
2283   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2284   LookThroughSetCC(LHS, RHS, CC, SPCC);
2285
2286   // Get the condition flag.
2287   SDValue CompareFlag;
2288   if (LHS.getValueType().isInteger()) {
2289     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2290     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2291     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
2292     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
2293   } else {
2294     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2295       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2296       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2297       Opc = SPISD::BRICC;
2298     } else {
2299       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2300       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2301       Opc = SPISD::BRFCC;
2302     }
2303   }
2304   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
2305                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
2306 }
2307
2308 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
2309                               const SparcTargetLowering &TLI,
2310                               bool hasHardQuad) {
2311   SDValue LHS = Op.getOperand(0);
2312   SDValue RHS = Op.getOperand(1);
2313   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2314   SDValue TrueVal = Op.getOperand(2);
2315   SDValue FalseVal = Op.getOperand(3);
2316   SDLoc dl(Op);
2317   unsigned Opc, SPCC = ~0U;
2318
2319   // If this is a select_cc of a "setcc", and if the setcc got lowered into
2320   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2321   LookThroughSetCC(LHS, RHS, CC, SPCC);
2322
2323   SDValue CompareFlag;
2324   if (LHS.getValueType().isInteger()) {
2325     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2326     Opc = LHS.getValueType() == MVT::i32 ?
2327           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
2328     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2329   } else {
2330     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2331       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2332       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2333       Opc = SPISD::SELECT_ICC;
2334     } else {
2335       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2336       Opc = SPISD::SELECT_FCC;
2337       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2338     }
2339   }
2340   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
2341                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
2342 }
2343
2344 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
2345                             const SparcTargetLowering &TLI) {
2346   MachineFunction &MF = DAG.getMachineFunction();
2347   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
2348
2349   // Need frame address to find the address of VarArgsFrameIndex.
2350   MF.getFrameInfo()->setFrameAddressIsTaken(true);
2351
2352   // vastart just stores the address of the VarArgsFrameIndex slot into the
2353   // memory location argument.
2354   SDLoc DL(Op);
2355   SDValue Offset =
2356     DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(),
2357                 DAG.getRegister(SP::I6, TLI.getPointerTy()),
2358                 DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset()));
2359   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2360   return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1),
2361                       MachinePointerInfo(SV), false, false, 0);
2362 }
2363
2364 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
2365   SDNode *Node = Op.getNode();
2366   EVT VT = Node->getValueType(0);
2367   SDValue InChain = Node->getOperand(0);
2368   SDValue VAListPtr = Node->getOperand(1);
2369   EVT PtrVT = VAListPtr.getValueType();
2370   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2371   SDLoc DL(Node);
2372   SDValue VAList = DAG.getLoad(PtrVT, DL, InChain, VAListPtr,
2373                                MachinePointerInfo(SV), false, false, false, 0);
2374   // Increment the pointer, VAList, to the next vaarg.
2375   SDValue NextPtr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
2376                                 DAG.getIntPtrConstant(VT.getSizeInBits()/8));
2377   // Store the incremented VAList to the legalized pointer.
2378   InChain = DAG.getStore(VAList.getValue(1), DL, NextPtr,
2379                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
2380   // Load the actual argument out of the pointer VAList.
2381   // We can't count on greater alignment than the word size.
2382   return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(),
2383                      false, false, false,
2384                      std::min(PtrVT.getSizeInBits(), VT.getSizeInBits())/8);
2385 }
2386
2387 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG,
2388                                        const SparcSubtarget *Subtarget) {
2389   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
2390   SDValue Size  = Op.getOperand(1);  // Legalize the size.
2391   EVT VT = Size->getValueType(0);
2392   SDLoc dl(Op);
2393
2394   unsigned SPReg = SP::O6;
2395   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
2396   SDValue NewSP = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
2397   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
2398
2399   // The resultant pointer is actually 16 words from the bottom of the stack,
2400   // to provide a register spill area.
2401   unsigned regSpillArea = Subtarget->is64Bit() ? 128 : 96;
2402   regSpillArea += Subtarget->getStackPointerBias();
2403
2404   SDValue NewVal = DAG.getNode(ISD::ADD, dl, VT, NewSP,
2405                                DAG.getConstant(regSpillArea, VT));
2406   SDValue Ops[2] = { NewVal, Chain };
2407   return DAG.getMergeValues(Ops, 2, dl);
2408 }
2409
2410
2411 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
2412   SDLoc dl(Op);
2413   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
2414                               dl, MVT::Other, DAG.getEntryNode());
2415   return Chain;
2416 }
2417
2418 static SDValue getFRAMEADDR(uint64_t depth, SDValue Op, SelectionDAG &DAG,
2419                             const SparcSubtarget *Subtarget) {
2420   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2421   MFI->setFrameAddressIsTaken(true);
2422
2423   EVT VT = Op.getValueType();
2424   SDLoc dl(Op);
2425   unsigned FrameReg = SP::I6;
2426   unsigned stackBias = Subtarget->getStackPointerBias();
2427
2428   SDValue FrameAddr;
2429
2430   if (depth == 0) {
2431     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2432     if (Subtarget->is64Bit())
2433       FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2434                               DAG.getIntPtrConstant(stackBias));
2435     return FrameAddr;
2436   }
2437
2438   // flush first to make sure the windowed registers' values are in stack
2439   SDValue Chain = getFLUSHW(Op, DAG);
2440   FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
2441
2442   unsigned Offset = (Subtarget->is64Bit()) ? (stackBias + 112) : 56;
2443
2444   while (depth--) {
2445     SDValue Ptr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2446                               DAG.getIntPtrConstant(Offset));
2447     FrameAddr = DAG.getLoad(VT, dl, Chain, Ptr, MachinePointerInfo(),
2448                             false, false, false, 0);
2449   }
2450   if (Subtarget->is64Bit())
2451     FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2452                             DAG.getIntPtrConstant(stackBias));
2453   return FrameAddr;
2454 }
2455
2456
2457 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG,
2458                               const SparcSubtarget *Subtarget) {
2459
2460   uint64_t depth = Op.getConstantOperandVal(0);
2461
2462   return getFRAMEADDR(depth, Op, DAG, Subtarget);
2463
2464 }
2465
2466 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG,
2467                                const SparcTargetLowering &TLI,
2468                                const SparcSubtarget *Subtarget) {
2469   MachineFunction &MF = DAG.getMachineFunction();
2470   MachineFrameInfo *MFI = MF.getFrameInfo();
2471   MFI->setReturnAddressIsTaken(true);
2472
2473   if (TLI.verifyReturnAddressArgumentIsConstant(Op, DAG))
2474     return SDValue();
2475
2476   EVT VT = Op.getValueType();
2477   SDLoc dl(Op);
2478   uint64_t depth = Op.getConstantOperandVal(0);
2479
2480   SDValue RetAddr;
2481   if (depth == 0) {
2482     unsigned RetReg = MF.addLiveIn(SP::I7,
2483                                    TLI.getRegClassFor(TLI.getPointerTy()));
2484     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
2485     return RetAddr;
2486   }
2487
2488   // Need frame address to find return address of the caller.
2489   SDValue FrameAddr = getFRAMEADDR(depth - 1, Op, DAG, Subtarget);
2490
2491   unsigned Offset = (Subtarget->is64Bit()) ? 120 : 60;
2492   SDValue Ptr = DAG.getNode(ISD::ADD,
2493                             dl, VT,
2494                             FrameAddr,
2495                             DAG.getIntPtrConstant(Offset));
2496   RetAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), Ptr,
2497                         MachinePointerInfo(), false, false, false, 0);
2498
2499   return RetAddr;
2500 }
2501
2502 static SDValue LowerF64Op(SDValue Op, SelectionDAG &DAG, unsigned opcode)
2503 {
2504   SDLoc dl(Op);
2505
2506   assert(Op.getValueType() == MVT::f64 && "LowerF64Op called on non-double!");
2507   assert(opcode == ISD::FNEG || opcode == ISD::FABS);
2508
2509   // Lower fneg/fabs on f64 to fneg/fabs on f32.
2510   // fneg f64 => fneg f32:sub_even, fmov f32:sub_odd.
2511   // fabs f64 => fabs f32:sub_even, fmov f32:sub_odd.
2512
2513   SDValue SrcReg64 = Op.getOperand(0);
2514   SDValue Hi32 = DAG.getTargetExtractSubreg(SP::sub_even, dl, MVT::f32,
2515                                             SrcReg64);
2516   SDValue Lo32 = DAG.getTargetExtractSubreg(SP::sub_odd, dl, MVT::f32,
2517                                             SrcReg64);
2518
2519   Hi32 = DAG.getNode(opcode, dl, MVT::f32, Hi32);
2520
2521   SDValue DstReg64 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2522                                                 dl, MVT::f64), 0);
2523   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_even, dl, MVT::f64,
2524                                        DstReg64, Hi32);
2525   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_odd, dl, MVT::f64,
2526                                        DstReg64, Lo32);
2527   return DstReg64;
2528 }
2529
2530 // Lower a f128 load into two f64 loads.
2531 static SDValue LowerF128Load(SDValue Op, SelectionDAG &DAG)
2532 {
2533   SDLoc dl(Op);
2534   LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode());
2535   assert(LdNode && LdNode->getOffset().getOpcode() == ISD::UNDEF
2536          && "Unexpected node type");
2537
2538   unsigned alignment = LdNode->getAlignment();
2539   if (alignment > 8)
2540     alignment = 8;
2541
2542   SDValue Hi64 = DAG.getLoad(MVT::f64,
2543                              dl,
2544                              LdNode->getChain(),
2545                              LdNode->getBasePtr(),
2546                              LdNode->getPointerInfo(),
2547                              false, false, false, alignment);
2548   EVT addrVT = LdNode->getBasePtr().getValueType();
2549   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2550                               LdNode->getBasePtr(),
2551                               DAG.getConstant(8, addrVT));
2552   SDValue Lo64 = DAG.getLoad(MVT::f64,
2553                              dl,
2554                              LdNode->getChain(),
2555                              LoPtr,
2556                              LdNode->getPointerInfo(),
2557                              false, false, false, alignment);
2558
2559   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, MVT::i32);
2560   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, MVT::i32);
2561
2562   SDNode *InFP128 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2563                                        dl, MVT::f128);
2564   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2565                                MVT::f128,
2566                                SDValue(InFP128, 0),
2567                                Hi64,
2568                                SubRegEven);
2569   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2570                                MVT::f128,
2571                                SDValue(InFP128, 0),
2572                                Lo64,
2573                                SubRegOdd);
2574   SDValue OutChains[2] = { SDValue(Hi64.getNode(), 1),
2575                            SDValue(Lo64.getNode(), 1) };
2576   SDValue OutChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2577                                  &OutChains[0], 2);
2578   SDValue Ops[2] = {SDValue(InFP128,0), OutChain};
2579   return DAG.getMergeValues(Ops, 2, dl);
2580 }
2581
2582 // Lower a f128 store into two f64 stores.
2583 static SDValue LowerF128Store(SDValue Op, SelectionDAG &DAG) {
2584   SDLoc dl(Op);
2585   StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode());
2586   assert(StNode && StNode->getOffset().getOpcode() == ISD::UNDEF
2587          && "Unexpected node type");
2588   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, MVT::i32);
2589   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, MVT::i32);
2590
2591   SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2592                                     dl,
2593                                     MVT::f64,
2594                                     StNode->getValue(),
2595                                     SubRegEven);
2596   SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2597                                     dl,
2598                                     MVT::f64,
2599                                     StNode->getValue(),
2600                                     SubRegOdd);
2601
2602   unsigned alignment = StNode->getAlignment();
2603   if (alignment > 8)
2604     alignment = 8;
2605
2606   SDValue OutChains[2];
2607   OutChains[0] = DAG.getStore(StNode->getChain(),
2608                               dl,
2609                               SDValue(Hi64, 0),
2610                               StNode->getBasePtr(),
2611                               MachinePointerInfo(),
2612                               false, false, alignment);
2613   EVT addrVT = StNode->getBasePtr().getValueType();
2614   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2615                               StNode->getBasePtr(),
2616                               DAG.getConstant(8, addrVT));
2617   OutChains[1] = DAG.getStore(StNode->getChain(),
2618                              dl,
2619                              SDValue(Lo64, 0),
2620                              LoPtr,
2621                              MachinePointerInfo(),
2622                              false, false, alignment);
2623   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2624                      &OutChains[0], 2);
2625 }
2626
2627 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG,
2628                          const SparcTargetLowering &TLI,
2629                          bool is64Bit) {
2630   if (Op.getValueType() == MVT::f64)
2631     return LowerF64Op(Op, DAG, ISD::FNEG);
2632   if (Op.getValueType() == MVT::f128)
2633     return TLI.LowerF128Op(Op, DAG, ((is64Bit) ? "_Qp_neg" : "_Q_neg"), 1);
2634   return Op;
2635 }
2636
2637 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG, bool isV9) {
2638   if (Op.getValueType() == MVT::f64)
2639     return LowerF64Op(Op, DAG, ISD::FABS);
2640   if (Op.getValueType() != MVT::f128)
2641     return Op;
2642
2643   // Lower fabs on f128 to fabs on f64
2644   // fabs f128 => fabs f64:sub_even64, fmov f64:sub_odd64
2645
2646   SDLoc dl(Op);
2647   SDValue SrcReg128 = Op.getOperand(0);
2648   SDValue Hi64 = DAG.getTargetExtractSubreg(SP::sub_even64, dl, MVT::f64,
2649                                             SrcReg128);
2650   SDValue Lo64 = DAG.getTargetExtractSubreg(SP::sub_odd64, dl, MVT::f64,
2651                                             SrcReg128);
2652   if (isV9)
2653     Hi64 = DAG.getNode(Op.getOpcode(), dl, MVT::f64, Hi64);
2654   else
2655     Hi64 = LowerF64Op(Hi64, DAG, ISD::FABS);
2656
2657   SDValue DstReg128 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2658                                                  dl, MVT::f128), 0);
2659   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_even64, dl, MVT::f128,
2660                                         DstReg128, Hi64);
2661   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_odd64, dl, MVT::f128,
2662                                         DstReg128, Lo64);
2663   return DstReg128;
2664 }
2665
2666 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2667
2668   if (Op.getValueType() != MVT::i64)
2669     return Op;
2670
2671   SDLoc dl(Op);
2672   SDValue Src1 = Op.getOperand(0);
2673   SDValue Src1Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1);
2674   SDValue Src1Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src1,
2675                                DAG.getConstant(32, MVT::i64));
2676   Src1Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1Hi);
2677
2678   SDValue Src2 = Op.getOperand(1);
2679   SDValue Src2Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2);
2680   SDValue Src2Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src2,
2681                                DAG.getConstant(32, MVT::i64));
2682   Src2Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2Hi);
2683
2684
2685   bool hasChain = false;
2686   unsigned hiOpc = Op.getOpcode();
2687   switch (Op.getOpcode()) {
2688   default: llvm_unreachable("Invalid opcode");
2689   case ISD::ADDC: hiOpc = ISD::ADDE; break;
2690   case ISD::ADDE: hasChain = true; break;
2691   case ISD::SUBC: hiOpc = ISD::SUBE; break;
2692   case ISD::SUBE: hasChain = true; break;
2693   }
2694   SDValue Lo;
2695   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Glue);
2696   if (hasChain) {
2697     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo,
2698                      Op.getOperand(2));
2699   } else {
2700     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo);
2701   }
2702   SDValue Hi = DAG.getNode(hiOpc, dl, VTs, Src1Hi, Src2Hi, Lo.getValue(1));
2703   SDValue Carry = Hi.getValue(1);
2704
2705   Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Lo);
2706   Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Hi);
2707   Hi = DAG.getNode(ISD::SHL, dl, MVT::i64, Hi,
2708                    DAG.getConstant(32, MVT::i64));
2709
2710   SDValue Dst = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, Lo);
2711   SDValue Ops[2] = { Dst, Carry };
2712   return DAG.getMergeValues(Ops, 2, dl);
2713 }
2714
2715 // Custom lower UMULO/SMULO for SPARC. This code is similar to ExpandNode()
2716 // in LegalizeDAG.cpp except the order of arguments to the library function.
2717 static SDValue LowerUMULO_SMULO(SDValue Op, SelectionDAG &DAG,
2718                                 const SparcTargetLowering &TLI)
2719 {
2720   unsigned opcode = Op.getOpcode();
2721   assert((opcode == ISD::UMULO || opcode == ISD::SMULO) && "Invalid Opcode.");
2722
2723   bool isSigned = (opcode == ISD::SMULO);
2724   EVT VT = MVT::i64;
2725   EVT WideVT = MVT::i128;
2726   SDLoc dl(Op);
2727   SDValue LHS = Op.getOperand(0);
2728
2729   if (LHS.getValueType() != VT)
2730     return Op;
2731
2732   SDValue ShiftAmt = DAG.getConstant(63, VT);
2733
2734   SDValue RHS = Op.getOperand(1);
2735   SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, ShiftAmt);
2736   SDValue HiRHS = DAG.getNode(ISD::SRA, dl, MVT::i64, RHS, ShiftAmt);
2737   SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
2738
2739   SDValue MulResult = TLI.makeLibCall(DAG,
2740                                       RTLIB::MUL_I128, WideVT,
2741                                       Args, 4, isSigned, dl).first;
2742   SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
2743                                    MulResult, DAG.getIntPtrConstant(0));
2744   SDValue TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
2745                                 MulResult, DAG.getIntPtrConstant(1));
2746   if (isSigned) {
2747     SDValue Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
2748     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, Tmp1, ISD::SETNE);
2749   } else {
2750     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, DAG.getConstant(0, VT),
2751                            ISD::SETNE);
2752   }
2753   // MulResult is a node with an illegal type. Because such things are not
2754   // generally permitted during this phase of legalization, delete the
2755   // node. The above EXTRACT_ELEMENT nodes should have been folded.
2756   DAG.DeleteNode(MulResult.getNode());
2757
2758   SDValue Ops[2] = { BottomHalf, TopHalf } ;
2759   return DAG.getMergeValues(Ops, 2, dl);
2760 }
2761
2762 static SDValue LowerATOMIC_LOAD_STORE(SDValue Op, SelectionDAG &DAG) {
2763   // Monotonic load/stores are legal.
2764   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
2765     return Op;
2766
2767   // Otherwise, expand with a fence.
2768   return SDValue();
2769 }
2770
2771
2772 SDValue SparcTargetLowering::
2773 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2774
2775   bool hasHardQuad = Subtarget->hasHardQuad();
2776   bool is64Bit     = Subtarget->is64Bit();
2777   bool isV9        = Subtarget->isV9();
2778
2779   switch (Op.getOpcode()) {
2780   default: llvm_unreachable("Should not custom lower this!");
2781
2782   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG, *this,
2783                                                        Subtarget);
2784   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG,
2785                                                       Subtarget);
2786   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2787   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
2788   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
2789   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
2790   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG, *this,
2791                                                        hasHardQuad);
2792   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG, *this,
2793                                                        hasHardQuad);
2794   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG, *this,
2795                                                        hasHardQuad);
2796   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG, *this,
2797                                                        hasHardQuad);
2798   case ISD::BR_CC:              return LowerBR_CC(Op, DAG, *this,
2799                                                   hasHardQuad);
2800   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG, *this,
2801                                                       hasHardQuad);
2802   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
2803   case ISD::VAARG:              return LowerVAARG(Op, DAG);
2804   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG,
2805                                                                Subtarget);
2806
2807   case ISD::LOAD:               return LowerF128Load(Op, DAG);
2808   case ISD::STORE:              return LowerF128Store(Op, DAG);
2809   case ISD::FADD:               return LowerF128Op(Op, DAG,
2810                                        getLibcallName(RTLIB::ADD_F128), 2);
2811   case ISD::FSUB:               return LowerF128Op(Op, DAG,
2812                                        getLibcallName(RTLIB::SUB_F128), 2);
2813   case ISD::FMUL:               return LowerF128Op(Op, DAG,
2814                                        getLibcallName(RTLIB::MUL_F128), 2);
2815   case ISD::FDIV:               return LowerF128Op(Op, DAG,
2816                                        getLibcallName(RTLIB::DIV_F128), 2);
2817   case ISD::FSQRT:              return LowerF128Op(Op, DAG,
2818                                        getLibcallName(RTLIB::SQRT_F128),1);
2819   case ISD::FNEG:               return LowerFNEG(Op, DAG, *this, is64Bit);
2820   case ISD::FABS:               return LowerFABS(Op, DAG, isV9);
2821   case ISD::FP_EXTEND:          return LowerF128_FPEXTEND(Op, DAG, *this);
2822   case ISD::FP_ROUND:           return LowerF128_FPROUND(Op, DAG, *this);
2823   case ISD::ADDC:
2824   case ISD::ADDE:
2825   case ISD::SUBC:
2826   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2827   case ISD::UMULO:
2828   case ISD::SMULO:              return LowerUMULO_SMULO(Op, DAG, *this);
2829   case ISD::ATOMIC_LOAD:
2830   case ISD::ATOMIC_STORE:       return LowerATOMIC_LOAD_STORE(Op, DAG);
2831   }
2832 }
2833
2834 MachineBasicBlock *
2835 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2836                                                  MachineBasicBlock *BB) const {
2837   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
2838   unsigned BROpcode;
2839   unsigned CC;
2840   DebugLoc dl = MI->getDebugLoc();
2841   // Figure out the conditional branch opcode to use for this select_cc.
2842   switch (MI->getOpcode()) {
2843   default: llvm_unreachable("Unknown SELECT_CC!");
2844   case SP::SELECT_CC_Int_ICC:
2845   case SP::SELECT_CC_FP_ICC:
2846   case SP::SELECT_CC_DFP_ICC:
2847   case SP::SELECT_CC_QFP_ICC:
2848     BROpcode = SP::BCOND;
2849     break;
2850   case SP::SELECT_CC_Int_FCC:
2851   case SP::SELECT_CC_FP_FCC:
2852   case SP::SELECT_CC_DFP_FCC:
2853   case SP::SELECT_CC_QFP_FCC:
2854     BROpcode = SP::FBCOND;
2855     break;
2856   }
2857
2858   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
2859
2860   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
2861   // control-flow pattern.  The incoming instruction knows the destination vreg
2862   // to set, the condition code register to branch on, the true/false values to
2863   // select between, and a branch opcode to use.
2864   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2865   MachineFunction::iterator It = BB;
2866   ++It;
2867
2868   //  thisMBB:
2869   //  ...
2870   //   TrueVal = ...
2871   //   [f]bCC copy1MBB
2872   //   fallthrough --> copy0MBB
2873   MachineBasicBlock *thisMBB = BB;
2874   MachineFunction *F = BB->getParent();
2875   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2876   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
2877   F->insert(It, copy0MBB);
2878   F->insert(It, sinkMBB);
2879
2880   // Transfer the remainder of BB and its successor edges to sinkMBB.
2881   sinkMBB->splice(sinkMBB->begin(), BB,
2882                   llvm::next(MachineBasicBlock::iterator(MI)),
2883                   BB->end());
2884   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
2885
2886   // Add the true and fallthrough blocks as its successors.
2887   BB->addSuccessor(copy0MBB);
2888   BB->addSuccessor(sinkMBB);
2889
2890   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
2891
2892   //  copy0MBB:
2893   //   %FalseValue = ...
2894   //   # fallthrough to sinkMBB
2895   BB = copy0MBB;
2896
2897   // Update machine-CFG edges
2898   BB->addSuccessor(sinkMBB);
2899
2900   //  sinkMBB:
2901   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2902   //  ...
2903   BB = sinkMBB;
2904   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
2905     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
2906     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
2907
2908   MI->eraseFromParent();   // The pseudo instruction is gone now.
2909   return BB;
2910 }
2911
2912 //===----------------------------------------------------------------------===//
2913 //                         Sparc Inline Assembly Support
2914 //===----------------------------------------------------------------------===//
2915
2916 /// getConstraintType - Given a constraint letter, return the type of
2917 /// constraint it is for this target.
2918 SparcTargetLowering::ConstraintType
2919 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
2920   if (Constraint.size() == 1) {
2921     switch (Constraint[0]) {
2922     default:  break;
2923     case 'r': return C_RegisterClass;
2924     }
2925   }
2926
2927   return TargetLowering::getConstraintType(Constraint);
2928 }
2929
2930 std::pair<unsigned, const TargetRegisterClass*>
2931 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
2932                                                   MVT VT) const {
2933   if (Constraint.size() == 1) {
2934     switch (Constraint[0]) {
2935     case 'r':
2936       return std::make_pair(0U, &SP::IntRegsRegClass);
2937     }
2938   }
2939
2940   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2941 }
2942
2943 bool
2944 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2945   // The Sparc target isn't yet aware of offsets.
2946   return false;
2947 }
2948
2949 void SparcTargetLowering::ReplaceNodeResults(SDNode *N,
2950                                              SmallVectorImpl<SDValue>& Results,
2951                                              SelectionDAG &DAG) const {
2952
2953   SDLoc dl(N);
2954
2955   RTLIB::Libcall libCall = RTLIB::UNKNOWN_LIBCALL;
2956
2957   switch (N->getOpcode()) {
2958   default:
2959     llvm_unreachable("Do not know how to custom type legalize this operation!");
2960
2961   case ISD::FP_TO_SINT:
2962   case ISD::FP_TO_UINT:
2963     // Custom lower only if it involves f128 or i64.
2964     if (N->getOperand(0).getValueType() != MVT::f128
2965         || N->getValueType(0) != MVT::i64)
2966       return;
2967     libCall = ((N->getOpcode() == ISD::FP_TO_SINT)
2968                ? RTLIB::FPTOSINT_F128_I64
2969                : RTLIB::FPTOUINT_F128_I64);
2970
2971     Results.push_back(LowerF128Op(SDValue(N, 0),
2972                                   DAG,
2973                                   getLibcallName(libCall),
2974                                   1));
2975     return;
2976
2977   case ISD::SINT_TO_FP:
2978   case ISD::UINT_TO_FP:
2979     // Custom lower only if it involves f128 or i64.
2980     if (N->getValueType(0) != MVT::f128
2981         || N->getOperand(0).getValueType() != MVT::i64)
2982       return;
2983
2984     libCall = ((N->getOpcode() == ISD::SINT_TO_FP)
2985                ? RTLIB::SINTTOFP_I64_F128
2986                : RTLIB::UINTTOFP_I64_F128);
2987
2988     Results.push_back(LowerF128Op(SDValue(N, 0),
2989                                   DAG,
2990                                   getLibcallName(libCall),
2991                                   1));
2992     return;
2993   }
2994 }