1 //===-- CSKYISelLowering.cpp - CSKY DAG Lowering Implementation  ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that CSKY uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CSKYISelLowering.h"
15 #include "CSKYCallingConv.h"
16 #include "CSKYConstantPoolValue.h"
17 #include "CSKYMachineFunctionInfo.h"
18 #include "CSKYRegisterInfo.h"
19 #include "CSKYSubtarget.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Support/Debug.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "csky-isel-lowering"
28 
29 STATISTIC(NumTailCalls, "Number of tail calls");
30 
31 #include "CSKYGenCallingConv.inc"
32 
33 static const MCPhysReg GPRArgRegs[] = {CSKY::R0, CSKY::R1, CSKY::R2, CSKY::R3};
34 
35 CSKYTargetLowering::CSKYTargetLowering(const TargetMachine &TM,
36                                        const CSKYSubtarget &STI)
37     : TargetLowering(TM), Subtarget(STI) {
38   // Register Class
39   addRegisterClass(MVT::i32, &CSKY::GPRRegClass);
40 
41   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
42   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
43   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
44 
45   setOperationAction(ISD::SREM, MVT::i32, Expand);
46   setOperationAction(ISD::UREM, MVT::i32, Expand);
47   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
48   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
49   setOperationAction(ISD::CTTZ, MVT::i32, Expand);
50   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
51   setOperationAction(ISD::ROTR, MVT::i32, Expand);
52   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
53   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
54   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
55   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
56   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
57   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
58   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
59   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
60   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
61   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
62   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
63   setOperationAction(ISD::MULHS, MVT::i32, Expand);
64   setOperationAction(ISD::MULHU, MVT::i32, Expand);
65   setOperationAction(ISD::VAARG, MVT::Other, Expand);
66   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
67   setOperationAction(ISD::VAEND, MVT::Other, Expand);
68 
69   setLoadExtAction(ISD::EXTLOAD, MVT::i32, MVT::i1, Promote);
70   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i1, Promote);
71   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, MVT::i1, Promote);
72 
73   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
74   setOperationAction(ISD::ExternalSymbol, MVT::i32, Custom);
75   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
76   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
77   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
78   setOperationAction(ISD::VASTART, MVT::Other, Custom);
79 
80   if (!Subtarget.hasE2()) {
81     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i8, Expand);
82     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i16, Expand);
83     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
84     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
85   }
86 
87   if (!Subtarget.has2E3()) {
88     setOperationAction(ISD::ABS, MVT::i32, Expand);
89     setOperationAction(ISD::BITREVERSE, MVT::i32, Expand);
90     setOperationAction(ISD::SDIV, MVT::i32, Expand);
91     setOperationAction(ISD::UDIV, MVT::i32, Expand);
92   }
93 
94   if (!Subtarget.has3r2E3r3()) {
95     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
96   }
97 
98   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
99   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
100   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
101 
102   setOperationAction(ISD::SREM, MVT::i32, Expand);
103   setOperationAction(ISD::UREM, MVT::i32, Expand);
104   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
105   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
106   setOperationAction(ISD::CTTZ, MVT::i32, Expand);
107   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
108   setOperationAction(ISD::ROTR, MVT::i32, Expand);
109   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
110   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
112   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
113   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
114   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
115   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
116   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
117   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
118   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
119   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
120   setOperationAction(ISD::MULHS, MVT::i32, Expand);
121   setOperationAction(ISD::MULHU, MVT::i32, Expand);
122 
123   setLoadExtAction(ISD::EXTLOAD, MVT::i32, MVT::i1, Promote);
124   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i1, Promote);
125   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, MVT::i1, Promote);
126 
127   if (!Subtarget.hasE2()) {
128     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i8, Expand);
129     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, MVT::i16, Expand);
130     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
131     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
132   }
133 
134   if (!Subtarget.has2E3()) {
135     setOperationAction(ISD::ABS, MVT::i32, Expand);
136     setOperationAction(ISD::BITREVERSE, MVT::i32, Expand);
137     setOperationAction(ISD::SDIV, MVT::i32, Expand);
138     setOperationAction(ISD::UDIV, MVT::i32, Expand);
139   }
140 
141   // Compute derived properties from the register classes.
142   computeRegisterProperties(STI.getRegisterInfo());
143 
144   setBooleanContents(UndefinedBooleanContent);
145   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
146 
147   // TODO: Add atomic support fully.
148   setMaxAtomicSizeInBitsSupported(0);
149 
150   setStackPointerRegisterToSaveRestore(CSKY::R14);
151   const Align FunctionAlignment(2);
152   setMinFunctionAlignment(FunctionAlignment);
153   setSchedulingPreference(Sched::Source);
154 }
155 
156 SDValue CSKYTargetLowering::LowerOperation(SDValue Op,
157                                            SelectionDAG &DAG) const {
158   switch (Op.getOpcode()) {
159   default:
160     llvm_unreachable("unimplemented op");
161   case ISD::GlobalAddress:
162     return LowerGlobalAddress(Op, DAG);
163   case ISD::ExternalSymbol:
164     return LowerExternalSymbol(Op, DAG);
165   case ISD::JumpTable:
166     return LowerJumpTable(Op, DAG);
167   case ISD::BlockAddress:
168     return LowerBlockAddress(Op, DAG);
169   case ISD::VASTART:
170     return LowerVASTART(Op, DAG);
171   case ISD::FRAMEADDR:
172     return LowerFRAMEADDR(Op, DAG);
173   case ISD::RETURNADDR:
174     return LowerRETURNADDR(Op, DAG);
175   }
176 }
177 
178 EVT CSKYTargetLowering::getSetCCResultType(const DataLayout &DL,
179                                            LLVMContext &Context, EVT VT) const {
180   if (!VT.isVector())
181     return MVT::i32;
182 
183   return VT.changeVectorElementTypeToInteger();
184 }
185 
186 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
187                                    const CCValAssign &VA, const SDLoc &DL) {
188   EVT LocVT = VA.getLocVT();
189 
190   switch (VA.getLocInfo()) {
191   default:
192     llvm_unreachable("Unexpected CCValAssign::LocInfo");
193   case CCValAssign::Full:
194     break;
195   case CCValAssign::BCvt:
196     Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
197     break;
198   }
199   return Val;
200 }
201 
202 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
203                                    const CCValAssign &VA, const SDLoc &DL) {
204   switch (VA.getLocInfo()) {
205   default:
206     llvm_unreachable("Unexpected CCValAssign::LocInfo");
207   case CCValAssign::Full:
208     break;
209   case CCValAssign::BCvt:
210     Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
211     break;
212   }
213   return Val;
214 }
215 
216 static SDValue unpackFromRegLoc(const CSKYSubtarget &Subtarget,
217                                 SelectionDAG &DAG, SDValue Chain,
218                                 const CCValAssign &VA, const SDLoc &DL) {
219   MachineFunction &MF = DAG.getMachineFunction();
220   MachineRegisterInfo &RegInfo = MF.getRegInfo();
221   EVT LocVT = VA.getLocVT();
222   SDValue Val;
223   const TargetRegisterClass *RC;
224 
225   switch (LocVT.getSimpleVT().SimpleTy) {
226   default:
227     llvm_unreachable("Unexpected register type");
228   case MVT::i32:
229     RC = &CSKY::GPRRegClass;
230     break;
231   case MVT::f32:
232     RC = Subtarget.hasFPUv2SingleFloat() ? &CSKY::sFPR32RegClass
233                                          : &CSKY::FPR32RegClass;
234     break;
235   case MVT::f64:
236     RC = Subtarget.hasFPUv2DoubleFloat() ? &CSKY::sFPR64RegClass
237                                          : &CSKY::FPR64RegClass;
238     break;
239   }
240 
241   Register VReg = RegInfo.createVirtualRegister(RC);
242   RegInfo.addLiveIn(VA.getLocReg(), VReg);
243   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
244 
245   return convertLocVTToValVT(DAG, Val, VA, DL);
246 }
247 
248 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
249                                 const CCValAssign &VA, const SDLoc &DL) {
250   MachineFunction &MF = DAG.getMachineFunction();
251   MachineFrameInfo &MFI = MF.getFrameInfo();
252   EVT LocVT = VA.getLocVT();
253   EVT ValVT = VA.getValVT();
254   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
255   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
256                                  VA.getLocMemOffset(), /*Immutable=*/true);
257   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
258   SDValue Val;
259 
260   ISD::LoadExtType ExtType;
261   switch (VA.getLocInfo()) {
262   default:
263     llvm_unreachable("Unexpected CCValAssign::LocInfo");
264   case CCValAssign::Full:
265   case CCValAssign::BCvt:
266     ExtType = ISD::NON_EXTLOAD;
267     break;
268   }
269   Val = DAG.getExtLoad(
270       ExtType, DL, LocVT, Chain, FIN,
271       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
272   return Val;
273 }
274 
275 static SDValue unpack64(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA,
276                         const SDLoc &DL) {
277   assert(VA.getLocVT() == MVT::i32 &&
278          (VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::i64) &&
279          "Unexpected VA");
280   MachineFunction &MF = DAG.getMachineFunction();
281   MachineFrameInfo &MFI = MF.getFrameInfo();
282   MachineRegisterInfo &RegInfo = MF.getRegInfo();
283 
284   if (VA.isMemLoc()) {
285     // f64/i64 is passed on the stack.
286     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
287     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
288     return DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
289                        MachinePointerInfo::getFixedStack(MF, FI));
290   }
291 
292   assert(VA.isRegLoc() && "Expected register VA assignment");
293 
294   Register LoVReg = RegInfo.createVirtualRegister(&CSKY::GPRRegClass);
295   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
296   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
297   SDValue Hi;
298   if (VA.getLocReg() == CSKY::R3) {
299     // Second half of f64/i64 is passed on the stack.
300     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
301     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
302     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
303                      MachinePointerInfo::getFixedStack(MF, FI));
304   } else {
305     // Second half of f64/i64 is passed in another GPR.
306     Register HiVReg = RegInfo.createVirtualRegister(&CSKY::GPRRegClass);
307     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
308     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
309   }
310   return DAG.getNode(CSKYISD::BITCAST_FROM_LOHI, DL, VA.getValVT(), Lo, Hi);
311 }
312 
313 // Transform physical registers into virtual registers.
314 SDValue CSKYTargetLowering::LowerFormalArguments(
315     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
316     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
317     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
318 
319   switch (CallConv) {
320   default:
321     report_fatal_error("Unsupported calling convention");
322   case CallingConv::C:
323   case CallingConv::Fast:
324     break;
325   }
326 
327   MachineFunction &MF = DAG.getMachineFunction();
328 
329   // Used with vargs to acumulate store chains.
330   std::vector<SDValue> OutChains;
331 
332   // Assign locations to all of the incoming arguments.
333   SmallVector<CCValAssign, 16> ArgLocs;
334   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
335 
336   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, IsVarArg));
337 
338   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
339     CCValAssign &VA = ArgLocs[i];
340     SDValue ArgValue;
341 
342     bool IsF64OnCSKY = VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
343 
344     if (IsF64OnCSKY)
345       ArgValue = unpack64(DAG, Chain, VA, DL);
346     else if (VA.isRegLoc())
347       ArgValue = unpackFromRegLoc(Subtarget, DAG, Chain, VA, DL);
348     else
349       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
350 
351     InVals.push_back(ArgValue);
352   }
353 
354   if (IsVarArg) {
355     const unsigned XLenInBytes = 4;
356     const MVT XLenVT = MVT::i32;
357 
358     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(GPRArgRegs);
359     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
360     const TargetRegisterClass *RC = &CSKY::GPRRegClass;
361     MachineFrameInfo &MFI = MF.getFrameInfo();
362     MachineRegisterInfo &RegInfo = MF.getRegInfo();
363     CSKYMachineFunctionInfo *CSKYFI = MF.getInfo<CSKYMachineFunctionInfo>();
364 
365     // Offset of the first variable argument from stack pointer, and size of
366     // the vararg save area. For now, the varargs save area is either zero or
367     // large enough to hold a0-a4.
368     int VaArgOffset, VarArgsSaveSize;
369 
370     // If all registers are allocated, then all varargs must be passed on the
371     // stack and we don't need to save any argregs.
372     if (ArgRegs.size() == Idx) {
373       VaArgOffset = CCInfo.getNextStackOffset();
374       VarArgsSaveSize = 0;
375     } else {
376       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
377       VaArgOffset = -VarArgsSaveSize;
378     }
379 
380     // Record the frame index of the first variable argument
381     // which is a value necessary to VASTART.
382     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
383     CSKYFI->setVarArgsFrameIndex(FI);
384 
385     // Copy the integer registers that may have been used for passing varargs
386     // to the vararg save area.
387     for (unsigned I = Idx; I < ArgRegs.size();
388          ++I, VaArgOffset += XLenInBytes) {
389       const Register Reg = RegInfo.createVirtualRegister(RC);
390       RegInfo.addLiveIn(ArgRegs[I], Reg);
391       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
392       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
393       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
394       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
395                                    MachinePointerInfo::getFixedStack(MF, FI));
396       cast<StoreSDNode>(Store.getNode())
397           ->getMemOperand()
398           ->setValue((Value *)nullptr);
399       OutChains.push_back(Store);
400     }
401     CSKYFI->setVarArgsSaveSize(VarArgsSaveSize);
402   }
403 
404   // All stores are grouped in one node to allow the matching between
405   // the size of Ins and InVals. This only happens for vararg functions.
406   if (!OutChains.empty()) {
407     OutChains.push_back(Chain);
408     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
409   }
410 
411   return Chain;
412 }
413 
414 bool CSKYTargetLowering::CanLowerReturn(
415     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
416     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
417   SmallVector<CCValAssign, 16> CSKYLocs;
418   CCState CCInfo(CallConv, IsVarArg, MF, CSKYLocs, Context);
419   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
420 }
421 
422 SDValue
423 CSKYTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
424                                 bool IsVarArg,
425                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
426                                 const SmallVectorImpl<SDValue> &OutVals,
427                                 const SDLoc &DL, SelectionDAG &DAG) const {
428   // Stores the assignment of the return value to a location.
429   SmallVector<CCValAssign, 16> CSKYLocs;
430 
431   // Info about the registers and stack slot.
432   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), CSKYLocs,
433                  *DAG.getContext());
434   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
435 
436   SDValue Glue;
437   SmallVector<SDValue, 4> RetOps(1, Chain);
438 
439   // Copy the result values into the output registers.
440   for (unsigned i = 0, e = CSKYLocs.size(); i < e; ++i) {
441     SDValue Val = OutVals[i];
442     CCValAssign &VA = CSKYLocs[i];
443     assert(VA.isRegLoc() && "Can only return in registers!");
444 
445     bool IsF64OnCSKY = VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
446 
447     if (IsF64OnCSKY) {
448 
449       assert(VA.isRegLoc() && "Expected return via registers");
450       SDValue Split64 = DAG.getNode(CSKYISD::BITCAST_TO_LOHI, DL,
451                                     DAG.getVTList(MVT::i32, MVT::i32), Val);
452       SDValue Lo = Split64.getValue(0);
453       SDValue Hi = Split64.getValue(1);
454 
455       Register RegLo = VA.getLocReg();
456       assert(RegLo < CSKY::R31 && "Invalid register pair");
457       Register RegHi = RegLo + 1;
458 
459       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
460       Glue = Chain.getValue(1);
461       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
462       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
463       Glue = Chain.getValue(1);
464       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
465     } else {
466       // Handle a 'normal' return.
467       Val = convertValVTToLocVT(DAG, Val, VA, DL);
468       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
469 
470       // Guarantee that all emitted copies are stuck together.
471       Glue = Chain.getValue(1);
472       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
473     }
474   }
475 
476   RetOps[0] = Chain; // Update chain.
477 
478   // Add the glue node if we have it.
479   if (Glue.getNode()) {
480     RetOps.push_back(Glue);
481   }
482 
483   // Interrupt service routines use different return instructions.
484   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
485     return DAG.getNode(CSKYISD::NIR, DL, MVT::Other, RetOps);
486 
487   return DAG.getNode(CSKYISD::RET, DL, MVT::Other, RetOps);
488 }
489 
490 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
491 // and output parameter nodes.
492 SDValue CSKYTargetLowering::LowerCall(CallLoweringInfo &CLI,
493                                       SmallVectorImpl<SDValue> &InVals) const {
494   SelectionDAG &DAG = CLI.DAG;
495   SDLoc &DL = CLI.DL;
496   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
497   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
498   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
499   SDValue Chain = CLI.Chain;
500   SDValue Callee = CLI.Callee;
501   bool &IsTailCall = CLI.IsTailCall;
502   CallingConv::ID CallConv = CLI.CallConv;
503   bool IsVarArg = CLI.IsVarArg;
504   EVT PtrVT = getPointerTy(DAG.getDataLayout());
505   MVT XLenVT = MVT::i32;
506 
507   MachineFunction &MF = DAG.getMachineFunction();
508 
509   // Analyze the operands of the call, assigning locations to each operand.
510   SmallVector<CCValAssign, 16> ArgLocs;
511   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
512 
513   ArgCCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, IsVarArg));
514 
515   // Check if it's really possible to do a tail call.
516   if (IsTailCall)
517     IsTailCall = false; // TODO: TailCallOptimization;
518 
519   if (IsTailCall)
520     ++NumTailCalls;
521   else if (CLI.CB && CLI.CB->isMustTailCall())
522     report_fatal_error("failed to perform tail call elimination on a call "
523                        "site marked musttail");
524 
525   // Get a count of how many bytes are to be pushed on the stack.
526   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
527 
528   // Create local copies for byval args
529   SmallVector<SDValue, 8> ByValArgs;
530   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
531     ISD::ArgFlagsTy Flags = Outs[i].Flags;
532     if (!Flags.isByVal())
533       continue;
534 
535     SDValue Arg = OutVals[i];
536     unsigned Size = Flags.getByValSize();
537     Align Alignment = Flags.getNonZeroByValAlign();
538 
539     int FI =
540         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
541     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
542     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
543 
544     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
545                           /*IsVolatile=*/false,
546                           /*AlwaysInline=*/false, IsTailCall,
547                           MachinePointerInfo(), MachinePointerInfo());
548     ByValArgs.push_back(FIPtr);
549   }
550 
551   if (!IsTailCall)
552     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
553 
554   // Copy argument values to their designated locations.
555   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
556   SmallVector<SDValue, 8> MemOpChains;
557   SDValue StackPtr;
558   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
559     CCValAssign &VA = ArgLocs[i];
560     SDValue ArgValue = OutVals[i];
561     ISD::ArgFlagsTy Flags = Outs[i].Flags;
562 
563     bool IsF64OnCSKY = VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
564 
565     if (IsF64OnCSKY && VA.isRegLoc()) {
566       SDValue Split64 =
567           DAG.getNode(CSKYISD::BITCAST_TO_LOHI, DL,
568                       DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
569       SDValue Lo = Split64.getValue(0);
570       SDValue Hi = Split64.getValue(1);
571 
572       Register RegLo = VA.getLocReg();
573       RegsToPass.push_back(std::make_pair(RegLo, Lo));
574 
575       if (RegLo == CSKY::R3) {
576         // Second half of f64/i64 is passed on the stack.
577         // Work out the address of the stack slot.
578         if (!StackPtr.getNode())
579           StackPtr = DAG.getCopyFromReg(Chain, DL, CSKY::R14, PtrVT);
580         // Emit the store.
581         MemOpChains.push_back(
582             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
583       } else {
584         // Second half of f64/i64 is passed in another GPR.
585         assert(RegLo < CSKY::R31 && "Invalid register pair");
586         Register RegHigh = RegLo + 1;
587         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
588       }
589       continue;
590     }
591 
592     ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
593 
594     // Use local copy if it is a byval arg.
595     if (Flags.isByVal())
596       ArgValue = ByValArgs[j++];
597 
598     if (VA.isRegLoc()) {
599       // Queue up the argument copies and emit them at the end.
600       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
601     } else {
602       assert(VA.isMemLoc() && "Argument not register or memory");
603       assert(!IsTailCall && "Tail call not allowed if stack is used "
604                             "for passing parameters");
605 
606       // Work out the address of the stack slot.
607       if (!StackPtr.getNode())
608         StackPtr = DAG.getCopyFromReg(Chain, DL, CSKY::R14, PtrVT);
609       SDValue Address =
610           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
611                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
612 
613       // Emit the store.
614       MemOpChains.push_back(
615           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
616     }
617   }
618 
619   // Join the stores, which are independent of one another.
620   if (!MemOpChains.empty())
621     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
622 
623   SDValue Glue;
624 
625   // Build a sequence of copy-to-reg nodes, chained and glued together.
626   for (auto &Reg : RegsToPass) {
627     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
628     Glue = Chain.getValue(1);
629   }
630 
631   SmallVector<SDValue, 8> Ops;
632   EVT Ty = getPointerTy(DAG.getDataLayout());
633   bool IsRegCall = false;
634 
635   Ops.push_back(Chain);
636 
637   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
638     const GlobalValue *GV = S->getGlobal();
639     bool IsLocal =
640         getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
641 
642     if (isPositionIndependent() || !Subtarget.has2E3()) {
643       IsRegCall = true;
644       Ops.push_back(getAddr<GlobalAddressSDNode, true>(S, DAG, IsLocal));
645     } else {
646       Ops.push_back(getTargetNode(cast<GlobalAddressSDNode>(Callee), DL, Ty,
647                                   DAG, CSKYII::MO_None));
648       Ops.push_back(getTargetConstantPoolValue(
649           cast<GlobalAddressSDNode>(Callee), Ty, DAG, CSKYII::MO_None));
650     }
651   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
652     bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(
653         *MF.getFunction().getParent(), nullptr);
654 
655     if (isPositionIndependent() || !Subtarget.has2E3()) {
656       IsRegCall = true;
657       Ops.push_back(getAddr<ExternalSymbolSDNode, true>(S, DAG, IsLocal));
658     } else {
659       Ops.push_back(getTargetNode(cast<ExternalSymbolSDNode>(Callee), DL, Ty,
660                                   DAG, CSKYII::MO_None));
661       Ops.push_back(getTargetConstantPoolValue(
662           cast<ExternalSymbolSDNode>(Callee), Ty, DAG, CSKYII::MO_None));
663     }
664   } else {
665     IsRegCall = true;
666     Ops.push_back(Callee);
667   }
668 
669   // Add argument registers to the end of the list so that they are
670   // known live into the call.
671   for (auto &Reg : RegsToPass)
672     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
673 
674   if (!IsTailCall) {
675     // Add a register mask operand representing the call-preserved registers.
676     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
677     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
678     assert(Mask && "Missing call preserved mask for calling convention");
679     Ops.push_back(DAG.getRegisterMask(Mask));
680   }
681 
682   // Glue the call to the argument copies, if any.
683   if (Glue.getNode())
684     Ops.push_back(Glue);
685 
686   // Emit the call.
687   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
688 
689   if (IsTailCall) {
690     MF.getFrameInfo().setHasTailCall();
691     return DAG.getNode(IsRegCall ? CSKYISD::TAILReg : CSKYISD::TAIL, DL,
692                        NodeTys, Ops);
693   }
694 
695   Chain = DAG.getNode(IsRegCall ? CSKYISD::CALLReg : CSKYISD::CALL, DL, NodeTys,
696                       Ops);
697   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
698   Glue = Chain.getValue(1);
699 
700   // Mark the end of the call, which is glued to the call itself.
701   Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, DL, PtrVT, true),
702                              DAG.getConstant(0, DL, PtrVT, true), Glue, DL);
703   Glue = Chain.getValue(1);
704 
705   // Assign locations to each value returned by this call.
706   SmallVector<CCValAssign, 16> CSKYLocs;
707   CCState RetCCInfo(CallConv, IsVarArg, MF, CSKYLocs, *DAG.getContext());
708   RetCCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, IsVarArg));
709 
710   // Copy all of the result registers out of their specified physreg.
711   for (auto &VA : CSKYLocs) {
712     // Copy the value out
713     SDValue RetValue =
714         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
715     // Glue the RetValue to the end of the call sequence
716     Chain = RetValue.getValue(1);
717     Glue = RetValue.getValue(2);
718 
719     bool IsF64OnCSKY = VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
720 
721     if (IsF64OnCSKY) {
722       assert(VA.getLocReg() == GPRArgRegs[0] && "Unexpected reg assignment");
723       SDValue RetValue2 =
724           DAG.getCopyFromReg(Chain, DL, GPRArgRegs[1], MVT::i32, Glue);
725       Chain = RetValue2.getValue(1);
726       Glue = RetValue2.getValue(2);
727       RetValue = DAG.getNode(CSKYISD::BITCAST_FROM_LOHI, DL, VA.getValVT(),
728                              RetValue, RetValue2);
729     }
730 
731     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
732 
733     InVals.push_back(RetValue);
734   }
735 
736   return Chain;
737 }
738 
739 CCAssignFn *CSKYTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
740                                                     bool IsVarArg) const {
741   if (IsVarArg || !Subtarget.useHardFloatABI())
742     return RetCC_CSKY_ABIV2_SOFT;
743   else
744     return RetCC_CSKY_ABIV2_FP;
745 }
746 
747 CCAssignFn *CSKYTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
748                                                   bool IsVarArg) const {
749   if (IsVarArg || !Subtarget.useHardFloatABI())
750     return CC_CSKY_ABIV2_SOFT;
751   else
752     return CC_CSKY_ABIV2_FP;
753 }
754 
755 static CSKYCP::CSKYCPModifier getModifier(unsigned Flags) {
756 
757   if (Flags == CSKYII::MO_ADDR32)
758     return CSKYCP::ADDR;
759   else if (Flags == CSKYII::MO_GOT32)
760     return CSKYCP::GOT;
761   else if (Flags == CSKYII::MO_GOTOFF)
762     return CSKYCP::GOTOFF;
763   else if (Flags == CSKYII::MO_PLT32)
764     return CSKYCP::PLT;
765   else if (Flags == CSKYII::MO_None)
766     return CSKYCP::NO_MOD;
767   else
768     assert(0 && "unknown CSKYII Modifier");
769   return CSKYCP::NO_MOD;
770 }
771 
772 SDValue CSKYTargetLowering::getTargetConstantPoolValue(GlobalAddressSDNode *N,
773                                                        EVT Ty,
774                                                        SelectionDAG &DAG,
775                                                        unsigned Flags) const {
776   CSKYConstantPoolValue *CPV = CSKYConstantPoolConstant::Create(
777       N->getGlobal(), CSKYCP::CPValue, 0, getModifier(Flags), false);
778 
779   return DAG.getTargetConstantPool(CPV, Ty);
780 }
781 
782 static MachineBasicBlock *
783 emitSelectPseudo(MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode) {
784 
785   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
786   DebugLoc DL = MI.getDebugLoc();
787 
788   // To "insert" a SELECT instruction, we actually have to insert the
789   // diamond control-flow pattern.  The incoming instruction knows the
790   // destination vreg to set, the condition code register to branch on, the
791   // true/false values to select between, and a branch opcode to use.
792   const BasicBlock *LLVM_BB = BB->getBasicBlock();
793   MachineFunction::iterator It = ++BB->getIterator();
794 
795   //  thisMBB:
796   //  ...
797   //   TrueVal = ...
798   //   bt32 c, sinkMBB
799   //   fallthrough --> copyMBB
800   MachineBasicBlock *thisMBB = BB;
801   MachineFunction *F = BB->getParent();
802   MachineBasicBlock *copyMBB = F->CreateMachineBasicBlock(LLVM_BB);
803   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
804   F->insert(It, copyMBB);
805   F->insert(It, sinkMBB);
806 
807   // Transfer the remainder of BB and its successor edges to sinkMBB.
808   sinkMBB->splice(sinkMBB->begin(), BB,
809                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
810   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
811 
812   // Next, add the true and fallthrough blocks as its successors.
813   BB->addSuccessor(copyMBB);
814   BB->addSuccessor(sinkMBB);
815 
816   // bt32 condition, sinkMBB
817   BuildMI(BB, DL, TII.get(Opcode))
818       .addReg(MI.getOperand(1).getReg())
819       .addMBB(sinkMBB);
820 
821   //  copyMBB:
822   //   %FalseValue = ...
823   //   # fallthrough to sinkMBB
824   BB = copyMBB;
825 
826   // Update machine-CFG edges
827   BB->addSuccessor(sinkMBB);
828 
829   //  sinkMBB:
830   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copyMBB ]
831   //  ...
832   BB = sinkMBB;
833 
834   BuildMI(*BB, BB->begin(), DL, TII.get(CSKY::PHI), MI.getOperand(0).getReg())
835       .addReg(MI.getOperand(2).getReg())
836       .addMBB(thisMBB)
837       .addReg(MI.getOperand(3).getReg())
838       .addMBB(copyMBB);
839 
840   MI.eraseFromParent(); // The pseudo instruction is gone now.
841 
842   return BB;
843 }
844 
845 MachineBasicBlock *
846 CSKYTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
847                                                 MachineBasicBlock *BB) const {
848   switch (MI.getOpcode()) {
849   default:
850     llvm_unreachable("Unexpected instr type to insert");
851   case CSKY::ISEL32:
852     return emitSelectPseudo(MI, BB, CSKY::BT32);
853   case CSKY::ISEL16:
854     return emitSelectPseudo(MI, BB, CSKY::BT16);
855   }
856 }
857 
858 SDValue CSKYTargetLowering::getTargetConstantPoolValue(ExternalSymbolSDNode *N,
859                                                        EVT Ty,
860                                                        SelectionDAG &DAG,
861                                                        unsigned Flags) const {
862   CSKYConstantPoolValue *CPV =
863       CSKYConstantPoolSymbol::Create(Type::getInt32Ty(*DAG.getContext()),
864                                      N->getSymbol(), 0, getModifier(Flags));
865 
866   return DAG.getTargetConstantPool(CPV, Ty);
867 }
868 
869 SDValue CSKYTargetLowering::getTargetConstantPoolValue(JumpTableSDNode *N,
870                                                        EVT Ty,
871                                                        SelectionDAG &DAG,
872                                                        unsigned Flags) const {
873   CSKYConstantPoolValue *CPV =
874       CSKYConstantPoolJT::Create(Type::getInt32Ty(*DAG.getContext()),
875                                  N->getIndex(), 0, getModifier(Flags));
876   return DAG.getTargetConstantPool(CPV, Ty);
877 }
878 
879 SDValue CSKYTargetLowering::getTargetConstantPoolValue(BlockAddressSDNode *N,
880                                                        EVT Ty,
881                                                        SelectionDAG &DAG,
882                                                        unsigned Flags) const {
883   CSKYConstantPoolValue *CPV = CSKYConstantPoolConstant::Create(
884       N->getBlockAddress(), CSKYCP::CPBlockAddress, 0, getModifier(Flags),
885       false);
886   return DAG.getTargetConstantPool(CPV, Ty);
887 }
888 
889 SDValue CSKYTargetLowering::getTargetNode(GlobalAddressSDNode *N, SDLoc DL,
890                                           EVT Ty, SelectionDAG &DAG,
891                                           unsigned Flags) const {
892   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
893 }
894 
895 SDValue CSKYTargetLowering::getTargetNode(ExternalSymbolSDNode *N, SDLoc DL,
896                                           EVT Ty, SelectionDAG &DAG,
897                                           unsigned Flags) const {
898   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flags);
899 }
900 
901 SDValue CSKYTargetLowering::getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
902                                           SelectionDAG &DAG,
903                                           unsigned Flags) const {
904   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
905 }
906 
907 SDValue CSKYTargetLowering::getTargetNode(BlockAddressSDNode *N, SDLoc DL,
908                                           EVT Ty, SelectionDAG &DAG,
909                                           unsigned Flags) const {
910   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
911                                    Flags);
912 }
913 
914 const char *CSKYTargetLowering::getTargetNodeName(unsigned Opcode) const {
915   switch (Opcode) {
916   default:
917     llvm_unreachable("unknown CSKYISD node");
918   case CSKYISD::NIE:
919     return "CSKYISD::NIE";
920   case CSKYISD::NIR:
921     return "CSKYISD::NIR";
922   case CSKYISD::RET:
923     return "CSKYISD::RET";
924   case CSKYISD::CALL:
925     return "CSKYISD::CALL";
926   case CSKYISD::CALLReg:
927     return "CSKYISD::CALLReg";
928   case CSKYISD::TAIL:
929     return "CSKYISD::TAIL";
930   case CSKYISD::TAILReg:
931     return "CSKYISD::TAILReg";
932   case CSKYISD::LOAD_ADDR:
933     return "CSKYISD::LOAD_ADDR";
934   case CSKYISD::BITCAST_TO_LOHI:
935     return "CSKYISD::BITCAST_TO_LOHI";
936   case CSKYISD::BITCAST_FROM_LOHI:
937     return "CSKYISD::BITCAST_FROM_LOHI";
938   }
939 }
940 
941 SDValue CSKYTargetLowering::LowerGlobalAddress(SDValue Op,
942                                                SelectionDAG &DAG) const {
943   SDLoc DL(Op);
944   EVT Ty = Op.getValueType();
945   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
946   int64_t Offset = N->getOffset();
947 
948   const GlobalValue *GV = N->getGlobal();
949   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
950   SDValue Addr = getAddr<GlobalAddressSDNode, false>(N, DAG, IsLocal);
951 
952   // In order to maximise the opportunity for common subexpression elimination,
953   // emit a separate ADD node for the global address offset instead of folding
954   // it in the global address node. Later peephole optimisations may choose to
955   // fold it back in when profitable.
956   if (Offset != 0)
957     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
958                        DAG.getConstant(Offset, DL, MVT::i32));
959   return Addr;
960 }
961 
962 SDValue CSKYTargetLowering::LowerExternalSymbol(SDValue Op,
963                                                 SelectionDAG &DAG) const {
964   ExternalSymbolSDNode *N = cast<ExternalSymbolSDNode>(Op);
965 
966   return getAddr(N, DAG, false);
967 }
968 
969 SDValue CSKYTargetLowering::LowerJumpTable(SDValue Op,
970                                            SelectionDAG &DAG) const {
971   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
972 
973   return getAddr<JumpTableSDNode, false>(N, DAG);
974 }
975 
976 SDValue CSKYTargetLowering::LowerBlockAddress(SDValue Op,
977                                               SelectionDAG &DAG) const {
978   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
979 
980   return getAddr(N, DAG);
981 }
982 
983 SDValue CSKYTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
984   MachineFunction &MF = DAG.getMachineFunction();
985   CSKYMachineFunctionInfo *FuncInfo = MF.getInfo<CSKYMachineFunctionInfo>();
986 
987   SDLoc DL(Op);
988   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
989                                  getPointerTy(MF.getDataLayout()));
990 
991   // vastart just stores the address of the VarArgsFrameIndex slot into the
992   // memory location argument.
993   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
994   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
995                       MachinePointerInfo(SV));
996 }
997 
998 SDValue CSKYTargetLowering::LowerFRAMEADDR(SDValue Op,
999                                            SelectionDAG &DAG) const {
1000   const CSKYRegisterInfo &RI = *Subtarget.getRegisterInfo();
1001   MachineFunction &MF = DAG.getMachineFunction();
1002   MachineFrameInfo &MFI = MF.getFrameInfo();
1003   MFI.setFrameAddressIsTaken(true);
1004 
1005   EVT VT = Op.getValueType();
1006   SDLoc dl(Op);
1007   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1008   Register FrameReg = RI.getFrameRegister(MF);
1009   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1010   while (Depth--)
1011     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1012                             MachinePointerInfo());
1013   return FrameAddr;
1014 }
1015 
1016 SDValue CSKYTargetLowering::LowerRETURNADDR(SDValue Op,
1017                                             SelectionDAG &DAG) const {
1018   const CSKYRegisterInfo &RI = *Subtarget.getRegisterInfo();
1019   MachineFunction &MF = DAG.getMachineFunction();
1020   MachineFrameInfo &MFI = MF.getFrameInfo();
1021   MFI.setReturnAddressIsTaken(true);
1022 
1023   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1024     return SDValue();
1025 
1026   EVT VT = Op.getValueType();
1027   SDLoc dl(Op);
1028   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1029   if (Depth) {
1030     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1031     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
1032     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
1033                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
1034                        MachinePointerInfo());
1035   }
1036   // Return the value of the return address register, marking it an implicit
1037   // live-in.
1038   unsigned Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(MVT::i32));
1039   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1040 }
1041 
1042 Register CSKYTargetLowering::getExceptionPointerRegister(
1043     const Constant *PersonalityFn) const {
1044   return CSKY::R0;
1045 }
1046 
1047 Register CSKYTargetLowering::getExceptionSelectorRegister(
1048     const Constant *PersonalityFn) const {
1049   return CSKY::R1;
1050 }
1051