Bug Summary

File:llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp
Warning:line 369, column 25
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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