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