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