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