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