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