1 //===-- llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp - Call lowering -----===//
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 /// \file
10 /// This file implements the lowering of LLVM calls to machine code calls for
11 /// GlobalISel.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUCallLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDGPULegalizerInfo.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/IR/IntrinsicsAMDGPU.h"
26 
27 #define DEBUG_TYPE "amdgpu-call-lowering"
28 
29 using namespace llvm;
30 
31 namespace {
32 
33 /// Wrapper around extendRegister to ensure we extend to a full 32-bit register.
34 static Register extendRegisterMin32(CallLowering::ValueHandler &Handler,
35                                     Register ValVReg, CCValAssign &VA) {
36   if (VA.getLocVT().getSizeInBits() < 32) {
37     // 16-bit types are reported as legal for 32-bit registers. We need to
38     // extend and do a 32-bit copy to avoid the verifier complaining about it.
39     return Handler.MIRBuilder.buildAnyExt(LLT::scalar(32), ValVReg).getReg(0);
40   }
41 
42   return Handler.extendRegister(ValVReg, VA);
43 }
44 
45 struct AMDGPUOutgoingValueHandler : public CallLowering::OutgoingValueHandler {
46   AMDGPUOutgoingValueHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI,
47                              MachineInstrBuilder MIB)
48       : OutgoingValueHandler(B, MRI), MIB(MIB) {}
49 
50   MachineInstrBuilder MIB;
51 
52   Register getStackAddress(uint64_t Size, int64_t Offset,
53                            MachinePointerInfo &MPO,
54                            ISD::ArgFlagsTy Flags) override {
55     llvm_unreachable("not implemented");
56   }
57 
58   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
59                             MachinePointerInfo &MPO, CCValAssign &VA) override {
60     llvm_unreachable("not implemented");
61   }
62 
63   void assignValueToReg(Register ValVReg, Register PhysReg,
64                         CCValAssign VA) override {
65     Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);
66 
67     // If this is a scalar return, insert a readfirstlane just in case the value
68     // ends up in a VGPR.
69     // FIXME: Assert this is a shader return.
70     const SIRegisterInfo *TRI
71       = static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());
72     if (TRI->isSGPRReg(MRI, PhysReg)) {
73       auto ToSGPR = MIRBuilder.buildIntrinsic(Intrinsic::amdgcn_readfirstlane,
74                                               {MRI.getType(ExtReg)}, false)
75         .addReg(ExtReg);
76       ExtReg = ToSGPR.getReg(0);
77     }
78 
79     MIRBuilder.buildCopy(PhysReg, ExtReg);
80     MIB.addUse(PhysReg, RegState::Implicit);
81   }
82 };
83 
84 struct AMDGPUIncomingArgHandler : public CallLowering::IncomingValueHandler {
85   uint64_t StackUsed = 0;
86 
87   AMDGPUIncomingArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
88       : IncomingValueHandler(B, MRI) {}
89 
90   Register getStackAddress(uint64_t Size, int64_t Offset,
91                            MachinePointerInfo &MPO,
92                            ISD::ArgFlagsTy Flags) override {
93     auto &MFI = MIRBuilder.getMF().getFrameInfo();
94 
95     // Byval is assumed to be writable memory, but other stack passed arguments
96     // are not.
97     const bool IsImmutable = !Flags.isByVal();
98     int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
99     MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
100     auto AddrReg = MIRBuilder.buildFrameIndex(
101         LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32), FI);
102     StackUsed = std::max(StackUsed, Size + Offset);
103     return AddrReg.getReg(0);
104   }
105 
106   void assignValueToReg(Register ValVReg, Register PhysReg,
107                         CCValAssign VA) override {
108     markPhysRegUsed(PhysReg);
109 
110     if (VA.getLocVT().getSizeInBits() < 32) {
111       // 16-bit types are reported as legal for 32-bit registers. We need to do
112       // a 32-bit copy, and truncate to avoid the verifier complaining about it.
113       auto Copy = MIRBuilder.buildCopy(LLT::scalar(32), PhysReg);
114 
115       // If we have signext/zeroext, it applies to the whole 32-bit register
116       // before truncation.
117       auto Extended =
118           buildExtensionHint(VA, Copy.getReg(0), LLT(VA.getLocVT()));
119       MIRBuilder.buildTrunc(ValVReg, Extended);
120       return;
121     }
122 
123     IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
124   }
125 
126   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
127                             MachinePointerInfo &MPO, CCValAssign &VA) override {
128     MachineFunction &MF = MIRBuilder.getMF();
129 
130     auto MMO = MF.getMachineMemOperand(
131         MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, MemTy,
132         inferAlignFromPtrInfo(MF, MPO));
133     MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
134   }
135 
136   /// How the physical register gets marked varies between formal
137   /// parameters (it's a basic-block live-in), and a call instruction
138   /// (it's an implicit-def of the BL).
139   virtual void markPhysRegUsed(unsigned PhysReg) = 0;
140 };
141 
142 struct FormalArgHandler : public AMDGPUIncomingArgHandler {
143   FormalArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
144       : AMDGPUIncomingArgHandler(B, MRI) {}
145 
146   void markPhysRegUsed(unsigned PhysReg) override {
147     MIRBuilder.getMBB().addLiveIn(PhysReg);
148   }
149 };
150 
151 struct CallReturnHandler : public AMDGPUIncomingArgHandler {
152   CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
153                     MachineInstrBuilder MIB)
154       : AMDGPUIncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
155 
156   void markPhysRegUsed(unsigned PhysReg) override {
157     MIB.addDef(PhysReg, RegState::Implicit);
158   }
159 
160   MachineInstrBuilder MIB;
161 };
162 
163 struct AMDGPUOutgoingArgHandler : public AMDGPUOutgoingValueHandler {
164   /// For tail calls, the byte offset of the call's argument area from the
165   /// callee's. Unused elsewhere.
166   int FPDiff;
167 
168   // Cache the SP register vreg if we need it more than once in this call site.
169   Register SPReg;
170 
171   bool IsTailCall;
172 
173   AMDGPUOutgoingArgHandler(MachineIRBuilder &MIRBuilder,
174                            MachineRegisterInfo &MRI, MachineInstrBuilder MIB,
175                            bool IsTailCall = false, int FPDiff = 0)
176       : AMDGPUOutgoingValueHandler(MIRBuilder, MRI, MIB), FPDiff(FPDiff),
177         IsTailCall(IsTailCall) {}
178 
179   Register getStackAddress(uint64_t Size, int64_t Offset,
180                            MachinePointerInfo &MPO,
181                            ISD::ArgFlagsTy Flags) override {
182     MachineFunction &MF = MIRBuilder.getMF();
183     const LLT PtrTy = LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32);
184     const LLT S32 = LLT::scalar(32);
185 
186     if (IsTailCall) {
187       Offset += FPDiff;
188       int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
189       auto FIReg = MIRBuilder.buildFrameIndex(PtrTy, FI);
190       MPO = MachinePointerInfo::getFixedStack(MF, FI);
191       return FIReg.getReg(0);
192     }
193 
194     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
195 
196     if (!SPReg) {
197       const GCNSubtarget &ST = MIRBuilder.getMF().getSubtarget<GCNSubtarget>();
198       if (ST.enableFlatScratch()) {
199         // The stack is accessed unswizzled, so we can use a regular copy.
200         SPReg = MIRBuilder.buildCopy(PtrTy,
201                                      MFI->getStackPtrOffsetReg()).getReg(0);
202       } else {
203         // The address we produce here, without knowing the use context, is going
204         // to be interpreted as a vector address, so we need to convert to a
205         // swizzled address.
206         SPReg = MIRBuilder.buildInstr(AMDGPU::G_AMDGPU_WAVE_ADDRESS, {PtrTy},
207                                       {MFI->getStackPtrOffsetReg()}).getReg(0);
208       }
209     }
210 
211     auto OffsetReg = MIRBuilder.buildConstant(S32, Offset);
212 
213     auto AddrReg = MIRBuilder.buildPtrAdd(PtrTy, SPReg, OffsetReg);
214     MPO = MachinePointerInfo::getStack(MF, Offset);
215     return AddrReg.getReg(0);
216   }
217 
218   void assignValueToReg(Register ValVReg, Register PhysReg,
219                         CCValAssign VA) override {
220     MIB.addUse(PhysReg, RegState::Implicit);
221     Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);
222     MIRBuilder.buildCopy(PhysReg, ExtReg);
223   }
224 
225   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
226                             MachinePointerInfo &MPO, CCValAssign &VA) override {
227     MachineFunction &MF = MIRBuilder.getMF();
228     uint64_t LocMemOffset = VA.getLocMemOffset();
229     const auto &ST = MF.getSubtarget<GCNSubtarget>();
230 
231     auto MMO = MF.getMachineMemOperand(
232         MPO, MachineMemOperand::MOStore, MemTy,
233         commonAlignment(ST.getStackAlignment(), LocMemOffset));
234     MIRBuilder.buildStore(ValVReg, Addr, *MMO);
235   }
236 
237   void assignValueToAddress(const CallLowering::ArgInfo &Arg,
238                             unsigned ValRegIndex, Register Addr, LLT MemTy,
239                             MachinePointerInfo &MPO, CCValAssign &VA) override {
240     Register ValVReg = VA.getLocInfo() != CCValAssign::LocInfo::FPExt
241                            ? extendRegister(Arg.Regs[ValRegIndex], VA)
242                            : Arg.Regs[ValRegIndex];
243     assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
244   }
245 };
246 }
247 
248 AMDGPUCallLowering::AMDGPUCallLowering(const AMDGPUTargetLowering &TLI)
249   : CallLowering(&TLI) {
250 }
251 
252 // FIXME: Compatibility shim
253 static ISD::NodeType extOpcodeToISDExtOpcode(unsigned MIOpc) {
254   switch (MIOpc) {
255   case TargetOpcode::G_SEXT:
256     return ISD::SIGN_EXTEND;
257   case TargetOpcode::G_ZEXT:
258     return ISD::ZERO_EXTEND;
259   case TargetOpcode::G_ANYEXT:
260     return ISD::ANY_EXTEND;
261   default:
262     llvm_unreachable("not an extend opcode");
263   }
264 }
265 
266 bool AMDGPUCallLowering::canLowerReturn(MachineFunction &MF,
267                                         CallingConv::ID CallConv,
268                                         SmallVectorImpl<BaseArgInfo> &Outs,
269                                         bool IsVarArg) const {
270   // For shaders. Vector types should be explicitly handled by CC.
271   if (AMDGPU::isEntryFunctionCC(CallConv))
272     return true;
273 
274   SmallVector<CCValAssign, 16> ArgLocs;
275   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
276   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
277                  MF.getFunction().getContext());
278 
279   return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv, IsVarArg));
280 }
281 
282 /// Lower the return value for the already existing \p Ret. This assumes that
283 /// \p B's insertion point is correct.
284 bool AMDGPUCallLowering::lowerReturnVal(MachineIRBuilder &B,
285                                         const Value *Val, ArrayRef<Register> VRegs,
286                                         MachineInstrBuilder &Ret) const {
287   if (!Val)
288     return true;
289 
290   auto &MF = B.getMF();
291   const auto &F = MF.getFunction();
292   const DataLayout &DL = MF.getDataLayout();
293   MachineRegisterInfo *MRI = B.getMRI();
294   LLVMContext &Ctx = F.getContext();
295 
296   CallingConv::ID CC = F.getCallingConv();
297   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
298 
299   SmallVector<EVT, 8> SplitEVTs;
300   ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
301   assert(VRegs.size() == SplitEVTs.size() &&
302          "For each split Type there should be exactly one VReg.");
303 
304   SmallVector<ArgInfo, 8> SplitRetInfos;
305 
306   for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
307     EVT VT = SplitEVTs[i];
308     Register Reg = VRegs[i];
309     ArgInfo RetInfo(Reg, VT.getTypeForEVT(Ctx), 0);
310     setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
311 
312     if (VT.isScalarInteger()) {
313       unsigned ExtendOp = TargetOpcode::G_ANYEXT;
314       if (RetInfo.Flags[0].isSExt()) {
315         assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
316         ExtendOp = TargetOpcode::G_SEXT;
317       } else if (RetInfo.Flags[0].isZExt()) {
318         assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
319         ExtendOp = TargetOpcode::G_ZEXT;
320       }
321 
322       EVT ExtVT = TLI.getTypeForExtReturn(Ctx, VT,
323                                           extOpcodeToISDExtOpcode(ExtendOp));
324       if (ExtVT != VT) {
325         RetInfo.Ty = ExtVT.getTypeForEVT(Ctx);
326         LLT ExtTy = getLLTForType(*RetInfo.Ty, DL);
327         Reg = B.buildInstr(ExtendOp, {ExtTy}, {Reg}).getReg(0);
328       }
329     }
330 
331     if (Reg != RetInfo.Regs[0]) {
332       RetInfo.Regs[0] = Reg;
333       // Reset the arg flags after modifying Reg.
334       setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
335     }
336 
337     splitToValueTypes(RetInfo, SplitRetInfos, DL, CC);
338   }
339 
340   CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(CC, F.isVarArg());
341 
342   OutgoingValueAssigner Assigner(AssignFn);
343   AMDGPUOutgoingValueHandler RetHandler(B, *MRI, Ret);
344   return determineAndHandleAssignments(RetHandler, Assigner, SplitRetInfos, B,
345                                        CC, F.isVarArg());
346 }
347 
348 bool AMDGPUCallLowering::lowerReturn(MachineIRBuilder &B, const Value *Val,
349                                      ArrayRef<Register> VRegs,
350                                      FunctionLoweringInfo &FLI) const {
351 
352   MachineFunction &MF = B.getMF();
353   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
354   MFI->setIfReturnsVoid(!Val);
355 
356   assert(!Val == VRegs.empty() && "Return value without a vreg");
357 
358   CallingConv::ID CC = B.getMF().getFunction().getCallingConv();
359   const bool IsShader = AMDGPU::isShader(CC);
360   const bool IsWaveEnd =
361       (IsShader && MFI->returnsVoid()) || AMDGPU::isKernel(CC);
362   if (IsWaveEnd) {
363     B.buildInstr(AMDGPU::S_ENDPGM)
364       .addImm(0);
365     return true;
366   }
367 
368   unsigned ReturnOpc =
369       IsShader ? AMDGPU::SI_RETURN_TO_EPILOG : AMDGPU::SI_RETURN;
370   auto Ret = B.buildInstrNoInsert(ReturnOpc);
371 
372   if (!FLI.CanLowerReturn)
373     insertSRetStores(B, Val->getType(), VRegs, FLI.DemoteRegister);
374   else if (!lowerReturnVal(B, Val, VRegs, Ret))
375     return false;
376 
377   // TODO: Handle CalleeSavedRegsViaCopy.
378 
379   B.insertInstr(Ret);
380   return true;
381 }
382 
383 void AMDGPUCallLowering::lowerParameterPtr(Register DstReg, MachineIRBuilder &B,
384                                            uint64_t Offset) const {
385   MachineFunction &MF = B.getMF();
386   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
387   MachineRegisterInfo &MRI = MF.getRegInfo();
388   Register KernArgSegmentPtr =
389     MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
390   Register KernArgSegmentVReg = MRI.getLiveInVirtReg(KernArgSegmentPtr);
391 
392   auto OffsetReg = B.buildConstant(LLT::scalar(64), Offset);
393 
394   B.buildPtrAdd(DstReg, KernArgSegmentVReg, OffsetReg);
395 }
396 
397 void AMDGPUCallLowering::lowerParameter(MachineIRBuilder &B, ArgInfo &OrigArg,
398                                         uint64_t Offset,
399                                         Align Alignment) const {
400   MachineFunction &MF = B.getMF();
401   const Function &F = MF.getFunction();
402   const DataLayout &DL = F.getParent()->getDataLayout();
403   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
404 
405   LLT PtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
406 
407   SmallVector<ArgInfo, 32> SplitArgs;
408   SmallVector<uint64_t> FieldOffsets;
409   splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv(), &FieldOffsets);
410 
411   unsigned Idx = 0;
412   for (ArgInfo &SplitArg : SplitArgs) {
413     Register PtrReg = B.getMRI()->createGenericVirtualRegister(PtrTy);
414     lowerParameterPtr(PtrReg, B, Offset + FieldOffsets[Idx]);
415 
416     LLT ArgTy = getLLTForType(*SplitArg.Ty, DL);
417     if (SplitArg.Flags[0].isPointer()) {
418       // Compensate for losing pointeriness in splitValueTypes.
419       LLT PtrTy = LLT::pointer(SplitArg.Flags[0].getPointerAddrSpace(),
420                                ArgTy.getScalarSizeInBits());
421       ArgTy = ArgTy.isVector() ? LLT::vector(ArgTy.getElementCount(), PtrTy)
422                                : PtrTy;
423     }
424 
425     MachineMemOperand *MMO = MF.getMachineMemOperand(
426         PtrInfo,
427         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
428             MachineMemOperand::MOInvariant,
429         ArgTy, commonAlignment(Alignment, FieldOffsets[Idx]));
430 
431     assert(SplitArg.Regs.size() == 1);
432 
433     B.buildLoad(SplitArg.Regs[0], PtrReg, *MMO);
434     ++Idx;
435   }
436 }
437 
438 // Allocate special inputs passed in user SGPRs.
439 static void allocateHSAUserSGPRs(CCState &CCInfo,
440                                  MachineIRBuilder &B,
441                                  MachineFunction &MF,
442                                  const SIRegisterInfo &TRI,
443                                  SIMachineFunctionInfo &Info) {
444   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
445   if (Info.hasPrivateSegmentBuffer()) {
446     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
447     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
448     CCInfo.AllocateReg(PrivateSegmentBufferReg);
449   }
450 
451   if (Info.hasDispatchPtr()) {
452     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
453     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
454     CCInfo.AllocateReg(DispatchPtrReg);
455   }
456 
457   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
458     Register QueuePtrReg = Info.addQueuePtr(TRI);
459     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
460     CCInfo.AllocateReg(QueuePtrReg);
461   }
462 
463   if (Info.hasKernargSegmentPtr()) {
464     MachineRegisterInfo &MRI = MF.getRegInfo();
465     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
466     const LLT P4 = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
467     Register VReg = MRI.createGenericVirtualRegister(P4);
468     MRI.addLiveIn(InputPtrReg, VReg);
469     B.getMBB().addLiveIn(InputPtrReg);
470     B.buildCopy(VReg, InputPtrReg);
471     CCInfo.AllocateReg(InputPtrReg);
472   }
473 
474   if (Info.hasDispatchID()) {
475     Register DispatchIDReg = Info.addDispatchID(TRI);
476     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
477     CCInfo.AllocateReg(DispatchIDReg);
478   }
479 
480   if (Info.hasFlatScratchInit()) {
481     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
482     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
483     CCInfo.AllocateReg(FlatScratchInitReg);
484   }
485 
486   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
487   // these from the dispatch pointer.
488 }
489 
490 bool AMDGPUCallLowering::lowerFormalArgumentsKernel(
491     MachineIRBuilder &B, const Function &F,
492     ArrayRef<ArrayRef<Register>> VRegs) const {
493   MachineFunction &MF = B.getMF();
494   const GCNSubtarget *Subtarget = &MF.getSubtarget<GCNSubtarget>();
495   MachineRegisterInfo &MRI = MF.getRegInfo();
496   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
497   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
498   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
499   const DataLayout &DL = F.getParent()->getDataLayout();
500 
501   Info->allocateModuleLDSGlobal(F);
502 
503   SmallVector<CCValAssign, 16> ArgLocs;
504   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
505 
506   allocateHSAUserSGPRs(CCInfo, B, MF, *TRI, *Info);
507 
508   unsigned i = 0;
509   const Align KernArgBaseAlign(16);
510   const unsigned BaseOffset = Subtarget->getExplicitKernelArgOffset(F);
511   uint64_t ExplicitArgOffset = 0;
512 
513   // TODO: Align down to dword alignment and extract bits for extending loads.
514   for (auto &Arg : F.args()) {
515     const bool IsByRef = Arg.hasByRefAttr();
516     Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
517     unsigned AllocSize = DL.getTypeAllocSize(ArgTy);
518     if (AllocSize == 0)
519       continue;
520 
521     MaybeAlign ParamAlign = IsByRef ? Arg.getParamAlign() : None;
522     Align ABIAlign = DL.getValueOrABITypeAlignment(ParamAlign, ArgTy);
523 
524     uint64_t ArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + BaseOffset;
525     ExplicitArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + AllocSize;
526 
527     if (Arg.use_empty()) {
528       ++i;
529       continue;
530     }
531 
532     Align Alignment = commonAlignment(KernArgBaseAlign, ArgOffset);
533 
534     if (IsByRef) {
535       unsigned ByRefAS = cast<PointerType>(Arg.getType())->getAddressSpace();
536 
537       assert(VRegs[i].size() == 1 &&
538              "expected only one register for byval pointers");
539       if (ByRefAS == AMDGPUAS::CONSTANT_ADDRESS) {
540         lowerParameterPtr(VRegs[i][0], B, ArgOffset);
541       } else {
542         const LLT ConstPtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
543         Register PtrReg = MRI.createGenericVirtualRegister(ConstPtrTy);
544         lowerParameterPtr(PtrReg, B, ArgOffset);
545 
546         B.buildAddrSpaceCast(VRegs[i][0], PtrReg);
547       }
548     } else {
549       ArgInfo OrigArg(VRegs[i], Arg, i);
550       const unsigned OrigArgIdx = i + AttributeList::FirstArgIndex;
551       setArgFlags(OrigArg, OrigArgIdx, DL, F);
552       lowerParameter(B, OrigArg, ArgOffset, Alignment);
553     }
554 
555     ++i;
556   }
557 
558   TLI.allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
559   TLI.allocateSystemSGPRs(CCInfo, MF, *Info, F.getCallingConv(), false);
560   return true;
561 }
562 
563 bool AMDGPUCallLowering::lowerFormalArguments(
564     MachineIRBuilder &B, const Function &F, ArrayRef<ArrayRef<Register>> VRegs,
565     FunctionLoweringInfo &FLI) const {
566   CallingConv::ID CC = F.getCallingConv();
567 
568   // The infrastructure for normal calling convention lowering is essentially
569   // useless for kernels. We want to avoid any kind of legalization or argument
570   // splitting.
571   if (CC == CallingConv::AMDGPU_KERNEL)
572     return lowerFormalArgumentsKernel(B, F, VRegs);
573 
574   const bool IsGraphics = AMDGPU::isGraphics(CC);
575   const bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CC);
576 
577   MachineFunction &MF = B.getMF();
578   MachineBasicBlock &MBB = B.getMBB();
579   MachineRegisterInfo &MRI = MF.getRegInfo();
580   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
581   const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
582   const SIRegisterInfo *TRI = Subtarget.getRegisterInfo();
583   const DataLayout &DL = F.getParent()->getDataLayout();
584 
585   Info->allocateModuleLDSGlobal(F);
586 
587   SmallVector<CCValAssign, 16> ArgLocs;
588   CCState CCInfo(CC, F.isVarArg(), MF, ArgLocs, F.getContext());
589 
590   if (Info->hasImplicitBufferPtr()) {
591     Register ImplicitBufferPtrReg = Info->addImplicitBufferPtr(*TRI);
592     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
593     CCInfo.AllocateReg(ImplicitBufferPtrReg);
594   }
595 
596   // FIXME: This probably isn't defined for mesa
597   if (Info->hasFlatScratchInit() && !Subtarget.isAmdPalOS()) {
598     Register FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
599     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
600     CCInfo.AllocateReg(FlatScratchInitReg);
601   }
602 
603   SmallVector<ArgInfo, 32> SplitArgs;
604   unsigned Idx = 0;
605   unsigned PSInputNum = 0;
606 
607   // Insert the hidden sret parameter if the return value won't fit in the
608   // return registers.
609   if (!FLI.CanLowerReturn)
610     insertSRetIncomingArgument(F, SplitArgs, FLI.DemoteRegister, MRI, DL);
611 
612   for (auto &Arg : F.args()) {
613     if (DL.getTypeStoreSize(Arg.getType()) == 0)
614       continue;
615 
616     const bool InReg = Arg.hasAttribute(Attribute::InReg);
617 
618     // SGPR arguments to functions not implemented.
619     if (!IsGraphics && InReg)
620       return false;
621 
622     if (Arg.hasAttribute(Attribute::SwiftSelf) ||
623         Arg.hasAttribute(Attribute::SwiftError) ||
624         Arg.hasAttribute(Attribute::Nest))
625       return false;
626 
627     if (CC == CallingConv::AMDGPU_PS && !InReg && PSInputNum <= 15) {
628       const bool ArgUsed = !Arg.use_empty();
629       bool SkipArg = !ArgUsed && !Info->isPSInputAllocated(PSInputNum);
630 
631       if (!SkipArg) {
632         Info->markPSInputAllocated(PSInputNum);
633         if (ArgUsed)
634           Info->markPSInputEnabled(PSInputNum);
635       }
636 
637       ++PSInputNum;
638 
639       if (SkipArg) {
640         for (Register R : VRegs[Idx])
641           B.buildUndef(R);
642 
643         ++Idx;
644         continue;
645       }
646     }
647 
648     ArgInfo OrigArg(VRegs[Idx], Arg, Idx);
649     const unsigned OrigArgIdx = Idx + AttributeList::FirstArgIndex;
650     setArgFlags(OrigArg, OrigArgIdx, DL, F);
651 
652     splitToValueTypes(OrigArg, SplitArgs, DL, CC);
653     ++Idx;
654   }
655 
656   // At least one interpolation mode must be enabled or else the GPU will
657   // hang.
658   //
659   // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
660   // set PSInputAddr, the user wants to enable some bits after the compilation
661   // based on run-time states. Since we can't know what the final PSInputEna
662   // will look like, so we shouldn't do anything here and the user should take
663   // responsibility for the correct programming.
664   //
665   // Otherwise, the following restrictions apply:
666   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
667   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
668   //   enabled too.
669   if (CC == CallingConv::AMDGPU_PS) {
670     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
671         ((Info->getPSInputAddr() & 0xF) == 0 &&
672          Info->isPSInputAllocated(11))) {
673       CCInfo.AllocateReg(AMDGPU::VGPR0);
674       CCInfo.AllocateReg(AMDGPU::VGPR1);
675       Info->markPSInputAllocated(0);
676       Info->markPSInputEnabled(0);
677     }
678 
679     if (Subtarget.isAmdPalOS()) {
680       // For isAmdPalOS, the user does not enable some bits after compilation
681       // based on run-time states; the register values being generated here are
682       // the final ones set in hardware. Therefore we need to apply the
683       // workaround to PSInputAddr and PSInputEnable together.  (The case where
684       // a bit is set in PSInputAddr but not PSInputEnable is where the frontend
685       // set up an input arg for a particular interpolation mode, but nothing
686       // uses that input arg. Really we should have an earlier pass that removes
687       // such an arg.)
688       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
689       if ((PsInputBits & 0x7F) == 0 ||
690           ((PsInputBits & 0xF) == 0 &&
691            (PsInputBits >> 11 & 1)))
692         Info->markPSInputEnabled(
693           countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
694     }
695   }
696 
697   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
698   CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CC, F.isVarArg());
699 
700   if (!MBB.empty())
701     B.setInstr(*MBB.begin());
702 
703   if (!IsEntryFunc && !IsGraphics) {
704     // For the fixed ABI, pass workitem IDs in the last argument register.
705     TLI.allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
706   }
707 
708   IncomingValueAssigner Assigner(AssignFn);
709   if (!determineAssignments(Assigner, SplitArgs, CCInfo))
710     return false;
711 
712   FormalArgHandler Handler(B, MRI);
713   if (!handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, B))
714     return false;
715 
716   uint64_t StackOffset = Assigner.StackOffset;
717 
718   // Start adding system SGPRs.
719   if (IsEntryFunc) {
720     TLI.allocateSystemSGPRs(CCInfo, MF, *Info, CC, IsGraphics);
721   } else {
722     if (!Subtarget.enableFlatScratch())
723       CCInfo.AllocateReg(Info->getScratchRSrcReg());
724     TLI.allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
725   }
726 
727   // When we tail call, we need to check if the callee's arguments will fit on
728   // the caller's stack. So, whenever we lower formal arguments, we should keep
729   // track of this information, since we might lower a tail call in this
730   // function later.
731   Info->setBytesInStackArgArea(StackOffset);
732 
733   // Move back to the end of the basic block.
734   B.setMBB(MBB);
735 
736   return true;
737 }
738 
739 bool AMDGPUCallLowering::passSpecialInputs(MachineIRBuilder &MIRBuilder,
740                                            CCState &CCInfo,
741                                            SmallVectorImpl<std::pair<MCRegister, Register>> &ArgRegs,
742                                            CallLoweringInfo &Info) const {
743   MachineFunction &MF = MIRBuilder.getMF();
744 
745   // If there's no call site, this doesn't correspond to a call from the IR and
746   // doesn't need implicit inputs.
747   if (!Info.CB)
748     return true;
749 
750   const AMDGPUFunctionArgInfo *CalleeArgInfo
751     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
752 
753   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
754   const AMDGPUFunctionArgInfo &CallerArgInfo = MFI->getArgInfo();
755 
756 
757   // TODO: Unify with private memory register handling. This is complicated by
758   // the fact that at least in kernels, the input argument is not necessarily
759   // in the same location as the input.
760   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
761     AMDGPUFunctionArgInfo::DISPATCH_PTR,
762     AMDGPUFunctionArgInfo::QUEUE_PTR,
763     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
764     AMDGPUFunctionArgInfo::DISPATCH_ID,
765     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
766     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
767     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
768   };
769 
770   static constexpr StringLiteral ImplicitAttrNames[] = {
771     "amdgpu-no-dispatch-ptr",
772     "amdgpu-no-queue-ptr",
773     "amdgpu-no-implicitarg-ptr",
774     "amdgpu-no-dispatch-id",
775     "amdgpu-no-workgroup-id-x",
776     "amdgpu-no-workgroup-id-y",
777     "amdgpu-no-workgroup-id-z"
778   };
779 
780   MachineRegisterInfo &MRI = MF.getRegInfo();
781 
782   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
783   const AMDGPULegalizerInfo *LI
784     = static_cast<const AMDGPULegalizerInfo*>(ST.getLegalizerInfo());
785 
786   unsigned I = 0;
787   for (auto InputID : InputRegs) {
788     const ArgDescriptor *OutgoingArg;
789     const TargetRegisterClass *ArgRC;
790     LLT ArgTy;
791 
792     // If the callee does not use the attribute value, skip copying the value.
793     if (Info.CB->hasFnAttr(ImplicitAttrNames[I++]))
794       continue;
795 
796     std::tie(OutgoingArg, ArgRC, ArgTy) =
797         CalleeArgInfo->getPreloadedValue(InputID);
798     if (!OutgoingArg)
799       continue;
800 
801     const ArgDescriptor *IncomingArg;
802     const TargetRegisterClass *IncomingArgRC;
803     std::tie(IncomingArg, IncomingArgRC, ArgTy) =
804         CallerArgInfo.getPreloadedValue(InputID);
805     assert(IncomingArgRC == ArgRC);
806 
807     Register InputReg = MRI.createGenericVirtualRegister(ArgTy);
808 
809     if (IncomingArg) {
810       LI->loadInputValue(InputReg, MIRBuilder, IncomingArg, ArgRC, ArgTy);
811     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
812       LI->getImplicitArgPtr(InputReg, MRI, MIRBuilder);
813     } else {
814       // We may have proven the input wasn't needed, although the ABI is
815       // requiring it. We just need to allocate the register appropriately.
816       MIRBuilder.buildUndef(InputReg);
817     }
818 
819     if (OutgoingArg->isRegister()) {
820       ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
821       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
822         report_fatal_error("failed to allocate implicit input argument");
823     } else {
824       LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
825       return false;
826     }
827   }
828 
829   // Pack workitem IDs into a single register or pass it as is if already
830   // packed.
831   const ArgDescriptor *OutgoingArg;
832   const TargetRegisterClass *ArgRC;
833   LLT ArgTy;
834 
835   std::tie(OutgoingArg, ArgRC, ArgTy) =
836       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
837   if (!OutgoingArg)
838     std::tie(OutgoingArg, ArgRC, ArgTy) =
839         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
840   if (!OutgoingArg)
841     std::tie(OutgoingArg, ArgRC, ArgTy) =
842         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
843   if (!OutgoingArg)
844     return false;
845 
846   auto WorkitemIDX =
847       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
848   auto WorkitemIDY =
849       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
850   auto WorkitemIDZ =
851       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
852 
853   const ArgDescriptor *IncomingArgX = std::get<0>(WorkitemIDX);
854   const ArgDescriptor *IncomingArgY = std::get<0>(WorkitemIDY);
855   const ArgDescriptor *IncomingArgZ = std::get<0>(WorkitemIDZ);
856   const LLT S32 = LLT::scalar(32);
857 
858   const bool NeedWorkItemIDX = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-x");
859   const bool NeedWorkItemIDY = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-y");
860   const bool NeedWorkItemIDZ = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-z");
861 
862   // If incoming ids are not packed we need to pack them.
863   // FIXME: Should consider known workgroup size to eliminate known 0 cases.
864   Register InputReg;
865   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
866       NeedWorkItemIDX) {
867     if (ST.getMaxWorkitemID(MF.getFunction(), 0) != 0) {
868       InputReg = MRI.createGenericVirtualRegister(S32);
869       LI->loadInputValue(InputReg, MIRBuilder, IncomingArgX,
870                          std::get<1>(WorkitemIDX), std::get<2>(WorkitemIDX));
871     } else {
872       InputReg = MIRBuilder.buildConstant(S32, 0).getReg(0);
873     }
874   }
875 
876   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
877       NeedWorkItemIDY && ST.getMaxWorkitemID(MF.getFunction(), 1) != 0) {
878     Register Y = MRI.createGenericVirtualRegister(S32);
879     LI->loadInputValue(Y, MIRBuilder, IncomingArgY, std::get<1>(WorkitemIDY),
880                        std::get<2>(WorkitemIDY));
881 
882     Y = MIRBuilder.buildShl(S32, Y, MIRBuilder.buildConstant(S32, 10)).getReg(0);
883     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Y).getReg(0) : Y;
884   }
885 
886   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
887       NeedWorkItemIDZ && ST.getMaxWorkitemID(MF.getFunction(), 2) != 0) {
888     Register Z = MRI.createGenericVirtualRegister(S32);
889     LI->loadInputValue(Z, MIRBuilder, IncomingArgZ, std::get<1>(WorkitemIDZ),
890                        std::get<2>(WorkitemIDZ));
891 
892     Z = MIRBuilder.buildShl(S32, Z, MIRBuilder.buildConstant(S32, 20)).getReg(0);
893     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Z).getReg(0) : Z;
894   }
895 
896   if (!InputReg &&
897       (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
898     InputReg = MRI.createGenericVirtualRegister(S32);
899     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
900       // We're in a situation where the outgoing function requires the workitem
901       // ID, but the calling function does not have it (e.g a graphics function
902       // calling a C calling convention function). This is illegal, but we need
903       // to produce something.
904       MIRBuilder.buildUndef(InputReg);
905     } else {
906       // Workitem ids are already packed, any of present incoming arguments will
907       // carry all required fields.
908       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
909         IncomingArgX ? *IncomingArgX :
910         IncomingArgY ? *IncomingArgY : *IncomingArgZ, ~0u);
911       LI->loadInputValue(InputReg, MIRBuilder, &IncomingArg,
912                          &AMDGPU::VGPR_32RegClass, S32);
913     }
914   }
915 
916   if (OutgoingArg->isRegister()) {
917     if (InputReg)
918       ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
919 
920     if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
921       report_fatal_error("failed to allocate implicit input argument");
922   } else {
923     LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
924     return false;
925   }
926 
927   return true;
928 }
929 
930 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
931 /// CC.
932 static std::pair<CCAssignFn *, CCAssignFn *>
933 getAssignFnsForCC(CallingConv::ID CC, const SITargetLowering &TLI) {
934   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
935 }
936 
937 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
938                               bool IsTailCall) {
939   assert(!(IsIndirect && IsTailCall) && "Indirect calls can't be tail calls, "
940                                         "because the address can be divergent");
941   return IsTailCall ? AMDGPU::SI_TCRETURN : AMDGPU::G_SI_CALL;
942 }
943 
944 // Add operands to call instruction to track the callee.
945 static bool addCallTargetOperands(MachineInstrBuilder &CallInst,
946                                   MachineIRBuilder &MIRBuilder,
947                                   AMDGPUCallLowering::CallLoweringInfo &Info) {
948   if (Info.Callee.isReg()) {
949     CallInst.addReg(Info.Callee.getReg());
950     CallInst.addImm(0);
951   } else if (Info.Callee.isGlobal() && Info.Callee.getOffset() == 0) {
952     // The call lowering lightly assumed we can directly encode a call target in
953     // the instruction, which is not the case. Materialize the address here.
954     const GlobalValue *GV = Info.Callee.getGlobal();
955     auto Ptr = MIRBuilder.buildGlobalValue(
956       LLT::pointer(GV->getAddressSpace(), 64), GV);
957     CallInst.addReg(Ptr.getReg(0));
958     CallInst.add(Info.Callee);
959   } else
960     return false;
961 
962   return true;
963 }
964 
965 bool AMDGPUCallLowering::doCallerAndCalleePassArgsTheSameWay(
966     CallLoweringInfo &Info, MachineFunction &MF,
967     SmallVectorImpl<ArgInfo> &InArgs) const {
968   const Function &CallerF = MF.getFunction();
969   CallingConv::ID CalleeCC = Info.CallConv;
970   CallingConv::ID CallerCC = CallerF.getCallingConv();
971 
972   // If the calling conventions match, then everything must be the same.
973   if (CalleeCC == CallerCC)
974     return true;
975 
976   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
977 
978   // Make sure that the caller and callee preserve all of the same registers.
979   auto TRI = ST.getRegisterInfo();
980 
981   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
982   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
983   if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
984     return false;
985 
986   // Check if the caller and callee will handle arguments in the same way.
987   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
988   CCAssignFn *CalleeAssignFnFixed;
989   CCAssignFn *CalleeAssignFnVarArg;
990   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
991       getAssignFnsForCC(CalleeCC, TLI);
992 
993   CCAssignFn *CallerAssignFnFixed;
994   CCAssignFn *CallerAssignFnVarArg;
995   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
996       getAssignFnsForCC(CallerCC, TLI);
997 
998   // FIXME: We are not accounting for potential differences in implicitly passed
999   // inputs, but only the fixed ABI is supported now anyway.
1000   IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
1001                                        CalleeAssignFnVarArg);
1002   IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
1003                                        CallerAssignFnVarArg);
1004   return resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner);
1005 }
1006 
1007 bool AMDGPUCallLowering::areCalleeOutgoingArgsTailCallable(
1008     CallLoweringInfo &Info, MachineFunction &MF,
1009     SmallVectorImpl<ArgInfo> &OutArgs) const {
1010   // If there are no outgoing arguments, then we are done.
1011   if (OutArgs.empty())
1012     return true;
1013 
1014   const Function &CallerF = MF.getFunction();
1015   CallingConv::ID CalleeCC = Info.CallConv;
1016   CallingConv::ID CallerCC = CallerF.getCallingConv();
1017   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1018 
1019   CCAssignFn *AssignFnFixed;
1020   CCAssignFn *AssignFnVarArg;
1021   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1022 
1023   // We have outgoing arguments. Make sure that we can tail call with them.
1024   SmallVector<CCValAssign, 16> OutLocs;
1025   CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
1026   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1027 
1028   if (!determineAssignments(Assigner, OutArgs, OutInfo)) {
1029     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
1030     return false;
1031   }
1032 
1033   // Make sure that they can fit on the caller's stack.
1034   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1035   if (OutInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) {
1036     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
1037     return false;
1038   }
1039 
1040   // Verify that the parameters in callee-saved registers match.
1041   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1042   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1043   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
1044   MachineRegisterInfo &MRI = MF.getRegInfo();
1045   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
1046 }
1047 
1048 /// Return true if the calling convention is one that we can guarantee TCO for.
1049 static bool canGuaranteeTCO(CallingConv::ID CC) {
1050   return CC == CallingConv::Fast;
1051 }
1052 
1053 /// Return true if we might ever do TCO for calls with this calling convention.
1054 static bool mayTailCallThisCC(CallingConv::ID CC) {
1055   switch (CC) {
1056   case CallingConv::C:
1057   case CallingConv::AMDGPU_Gfx:
1058     return true;
1059   default:
1060     return canGuaranteeTCO(CC);
1061   }
1062 }
1063 
1064 bool AMDGPUCallLowering::isEligibleForTailCallOptimization(
1065     MachineIRBuilder &B, CallLoweringInfo &Info,
1066     SmallVectorImpl<ArgInfo> &InArgs, SmallVectorImpl<ArgInfo> &OutArgs) const {
1067   // Must pass all target-independent checks in order to tail call optimize.
1068   if (!Info.IsTailCall)
1069     return false;
1070 
1071   // Indirect calls can't be tail calls, because the address can be divergent.
1072   // TODO Check divergence info if the call really is divergent.
1073   if (Info.Callee.isReg())
1074     return false;
1075 
1076   MachineFunction &MF = B.getMF();
1077   const Function &CallerF = MF.getFunction();
1078   CallingConv::ID CalleeCC = Info.CallConv;
1079   CallingConv::ID CallerCC = CallerF.getCallingConv();
1080 
1081   const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1082   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1083   // Kernels aren't callable, and don't have a live in return address so it
1084   // doesn't make sense to do a tail call with entry functions.
1085   if (!CallerPreserved)
1086     return false;
1087 
1088   if (!mayTailCallThisCC(CalleeCC)) {
1089     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
1090     return false;
1091   }
1092 
1093   if (any_of(CallerF.args(), [](const Argument &A) {
1094         return A.hasByValAttr() || A.hasSwiftErrorAttr();
1095       })) {
1096     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval "
1097                          "or swifterror arguments\n");
1098     return false;
1099   }
1100 
1101   // If we have -tailcallopt, then we're done.
1102   if (MF.getTarget().Options.GuaranteedTailCallOpt)
1103     return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();
1104 
1105   // Verify that the incoming and outgoing arguments from the callee are
1106   // safe to tail call.
1107   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1108     LLVM_DEBUG(
1109         dbgs()
1110         << "... Caller and callee have incompatible calling conventions.\n");
1111     return false;
1112   }
1113 
1114   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1115     return false;
1116 
1117   LLVM_DEBUG(dbgs() << "... Call is eligible for tail call optimization.\n");
1118   return true;
1119 }
1120 
1121 // Insert outgoing implicit arguments for a call, by inserting copies to the
1122 // implicit argument registers and adding the necessary implicit uses to the
1123 // call instruction.
1124 void AMDGPUCallLowering::handleImplicitCallArguments(
1125     MachineIRBuilder &MIRBuilder, MachineInstrBuilder &CallInst,
1126     const GCNSubtarget &ST, const SIMachineFunctionInfo &FuncInfo,
1127     ArrayRef<std::pair<MCRegister, Register>> ImplicitArgRegs) const {
1128   if (!ST.enableFlatScratch()) {
1129     // Insert copies for the SRD. In the HSA case, this should be an identity
1130     // copy.
1131     auto ScratchRSrcReg = MIRBuilder.buildCopy(LLT::fixed_vector(4, 32),
1132                                                FuncInfo.getScratchRSrcReg());
1133     MIRBuilder.buildCopy(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
1134     CallInst.addReg(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, RegState::Implicit);
1135   }
1136 
1137   for (std::pair<MCRegister, Register> ArgReg : ImplicitArgRegs) {
1138     MIRBuilder.buildCopy((Register)ArgReg.first, ArgReg.second);
1139     CallInst.addReg(ArgReg.first, RegState::Implicit);
1140   }
1141 }
1142 
1143 bool AMDGPUCallLowering::lowerTailCall(
1144     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1145     SmallVectorImpl<ArgInfo> &OutArgs) const {
1146   MachineFunction &MF = MIRBuilder.getMF();
1147   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1148   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1149   const Function &F = MF.getFunction();
1150   MachineRegisterInfo &MRI = MF.getRegInfo();
1151   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1152 
1153   // True when we're tail calling, but without -tailcallopt.
1154   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
1155 
1156   // Find out which ABI gets to decide where things go.
1157   CallingConv::ID CalleeCC = Info.CallConv;
1158   CCAssignFn *AssignFnFixed;
1159   CCAssignFn *AssignFnVarArg;
1160   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1161 
1162   MachineInstrBuilder CallSeqStart;
1163   if (!IsSibCall)
1164     CallSeqStart = MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP);
1165 
1166   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
1167   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1168   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1169     return false;
1170 
1171   // Byte offset for the tail call. When we are sibcalling, this will always
1172   // be 0.
1173   MIB.addImm(0);
1174 
1175   // Tell the call which registers are clobbered.
1176   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1177   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1178   MIB.addRegMask(Mask);
1179 
1180   // FPDiff is the byte offset of the call's argument area from the callee's.
1181   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1182   // by this amount for a tail call. In a sibling call it must be 0 because the
1183   // caller will deallocate the entire stack and the callee still expects its
1184   // arguments to begin at SP+0.
1185   int FPDiff = 0;
1186 
1187   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1188   // by -tailcallopt. For sibcalls, the memory operands for the call are
1189   // already available in the caller's incoming argument space.
1190   unsigned NumBytes = 0;
1191   if (!IsSibCall) {
1192     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1193     // before handling assignments, because FPDiff must be known for memory
1194     // arguments.
1195     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1196     SmallVector<CCValAssign, 16> OutLocs;
1197     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1198 
1199     // FIXME: Not accounting for callee implicit inputs
1200     OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg);
1201     if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1202       return false;
1203 
1204     // The callee will pop the argument stack as a tail call. Thus, we must
1205     // keep it 16-byte aligned.
1206     NumBytes = alignTo(OutInfo.getNextStackOffset(), ST.getStackAlignment());
1207 
1208     // FPDiff will be negative if this tail call requires more space than we
1209     // would automatically have in our incoming argument space. Positive if we
1210     // actually shrink the stack.
1211     FPDiff = NumReusableBytes - NumBytes;
1212 
1213     // The stack pointer must be 16-byte aligned at all times it's used for a
1214     // memory operation, which in practice means at *all* times and in
1215     // particular across call boundaries. Therefore our own arguments started at
1216     // a 16-byte aligned SP and the delta applied for the tail call should
1217     // satisfy the same constraint.
1218     assert(isAligned(ST.getStackAlignment(), FPDiff) &&
1219            "unaligned stack on tail call");
1220   }
1221 
1222   SmallVector<CCValAssign, 16> ArgLocs;
1223   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1224 
1225   // We could pass MIB and directly add the implicit uses to the call
1226   // now. However, as an aesthetic choice, place implicit argument operands
1227   // after the ordinary user argument registers.
1228   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1229 
1230   if (Info.CallConv != CallingConv::AMDGPU_Gfx) {
1231     // With a fixed ABI, allocate fixed registers before user arguments.
1232     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1233       return false;
1234   }
1235 
1236   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1237 
1238   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1239     return false;
1240 
1241   // Do the actual argument marshalling.
1242   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, true, FPDiff);
1243   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1244     return false;
1245 
1246   handleImplicitCallArguments(MIRBuilder, MIB, ST, *FuncInfo, ImplicitArgRegs);
1247 
1248   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1249   // sequence start and end here.
1250   if (!IsSibCall) {
1251     MIB->getOperand(1).setImm(FPDiff);
1252     CallSeqStart.addImm(NumBytes).addImm(0);
1253     // End the call sequence *before* emitting the call. Normally, we would
1254     // tidy the frame up after the call. However, here, we've laid out the
1255     // parameters so that when SP is reset, they will be in the correct
1256     // location.
1257     MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN).addImm(NumBytes).addImm(0);
1258   }
1259 
1260   // Now we can add the actual call instruction to the correct basic block.
1261   MIRBuilder.insertInstr(MIB);
1262 
1263   // If Callee is a reg, since it is used by a target specific
1264   // instruction, it must have a register class matching the
1265   // constraint of that instruction.
1266 
1267   // FIXME: We should define regbankselectable call instructions to handle
1268   // divergent call targets.
1269   if (MIB->getOperand(0).isReg()) {
1270     MIB->getOperand(0).setReg(constrainOperandRegClass(
1271         MF, *TRI, MRI, *ST.getInstrInfo(), *ST.getRegBankInfo(), *MIB,
1272         MIB->getDesc(), MIB->getOperand(0), 0));
1273   }
1274 
1275   MF.getFrameInfo().setHasTailCall();
1276   Info.LoweredTailCall = true;
1277   return true;
1278 }
1279 
1280 bool AMDGPUCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
1281                                    CallLoweringInfo &Info) const {
1282   if (Info.IsVarArg) {
1283     LLVM_DEBUG(dbgs() << "Variadic functions not implemented\n");
1284     return false;
1285   }
1286 
1287   MachineFunction &MF = MIRBuilder.getMF();
1288   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1289   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1290 
1291   const Function &F = MF.getFunction();
1292   MachineRegisterInfo &MRI = MF.getRegInfo();
1293   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1294   const DataLayout &DL = F.getParent()->getDataLayout();
1295 
1296   SmallVector<ArgInfo, 8> OutArgs;
1297   for (auto &OrigArg : Info.OrigArgs)
1298     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1299 
1300   SmallVector<ArgInfo, 8> InArgs;
1301   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy())
1302     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1303 
1304   // If we can lower as a tail call, do that instead.
1305   bool CanTailCallOpt =
1306       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1307 
1308   // We must emit a tail call if we have musttail.
1309   if (Info.IsMustTailCall && !CanTailCallOpt) {
1310     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1311     return false;
1312   }
1313 
1314   Info.IsTailCall = CanTailCallOpt;
1315   if (CanTailCallOpt)
1316     return lowerTailCall(MIRBuilder, Info, OutArgs);
1317 
1318   // Find out which ABI gets to decide where things go.
1319   CCAssignFn *AssignFnFixed;
1320   CCAssignFn *AssignFnVarArg;
1321   std::tie(AssignFnFixed, AssignFnVarArg) =
1322       getAssignFnsForCC(Info.CallConv, TLI);
1323 
1324   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP)
1325     .addImm(0)
1326     .addImm(0);
1327 
1328   // Create a temporarily-floating call instruction so we can add the implicit
1329   // uses of arg registers.
1330   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
1331 
1332   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1333   MIB.addDef(TRI->getReturnAddressReg(MF));
1334 
1335   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1336     return false;
1337 
1338   // Tell the call which registers are clobbered.
1339   const uint32_t *Mask = TRI->getCallPreservedMask(MF, Info.CallConv);
1340   MIB.addRegMask(Mask);
1341 
1342   SmallVector<CCValAssign, 16> ArgLocs;
1343   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1344 
1345   // We could pass MIB and directly add the implicit uses to the call
1346   // now. However, as an aesthetic choice, place implicit argument operands
1347   // after the ordinary user argument registers.
1348   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1349 
1350   if (Info.CallConv != CallingConv::AMDGPU_Gfx) {
1351     // With a fixed ABI, allocate fixed registers before user arguments.
1352     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1353       return false;
1354   }
1355 
1356   // Do the actual argument marshalling.
1357   SmallVector<Register, 8> PhysRegs;
1358 
1359   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1360   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1361     return false;
1362 
1363   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, false);
1364   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1365     return false;
1366 
1367   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1368 
1369   handleImplicitCallArguments(MIRBuilder, MIB, ST, *MFI, ImplicitArgRegs);
1370 
1371   // Get a count of how many bytes are to be pushed on the stack.
1372   unsigned NumBytes = CCInfo.getNextStackOffset();
1373 
1374   // If Callee is a reg, since it is used by a target specific
1375   // instruction, it must have a register class matching the
1376   // constraint of that instruction.
1377 
1378   // FIXME: We should define regbankselectable call instructions to handle
1379   // divergent call targets.
1380   if (MIB->getOperand(1).isReg()) {
1381     MIB->getOperand(1).setReg(constrainOperandRegClass(
1382         MF, *TRI, MRI, *ST.getInstrInfo(),
1383         *ST.getRegBankInfo(), *MIB, MIB->getDesc(), MIB->getOperand(1),
1384         1));
1385   }
1386 
1387   // Now we can add the actual call instruction to the correct position.
1388   MIRBuilder.insertInstr(MIB);
1389 
1390   // Finally we can copy the returned value back into its virtual-register. In
1391   // symmetry with the arguments, the physical register must be an
1392   // implicit-define of the call instruction.
1393   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1394     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv,
1395                                                       Info.IsVarArg);
1396     IncomingValueAssigner Assigner(RetAssignFn);
1397     CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1398     if (!determineAndHandleAssignments(Handler, Assigner, InArgs, MIRBuilder,
1399                                        Info.CallConv, Info.IsVarArg))
1400       return false;
1401   }
1402 
1403   uint64_t CalleePopBytes = NumBytes;
1404 
1405   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN)
1406             .addImm(0)
1407             .addImm(CalleePopBytes);
1408 
1409   if (!Info.CanLowerReturn) {
1410     insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1411                     Info.DemoteRegister, Info.DemoteStackIndex);
1412   }
1413 
1414   return true;
1415 }
1416