1 //===-- lib/CodeGen/GlobalISel/CallLowering.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 some simple delegations needed for call lowering. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/Analysis.h" 15 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 16 #include "llvm/CodeGen/GlobalISel/Utils.h" 17 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" 18 #include "llvm/CodeGen/MachineOperand.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/TargetLowering.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/Target/TargetMachine.h" 26 27 #define DEBUG_TYPE "call-lowering" 28 29 using namespace llvm; 30 31 void CallLowering::anchor() {} 32 33 /// Helper function which updates \p Flags when \p AttrFn returns true. 34 static void 35 addFlagsUsingAttrFn(ISD::ArgFlagsTy &Flags, 36 const std::function<bool(Attribute::AttrKind)> &AttrFn) { 37 if (AttrFn(Attribute::SExt)) 38 Flags.setSExt(); 39 if (AttrFn(Attribute::ZExt)) 40 Flags.setZExt(); 41 if (AttrFn(Attribute::InReg)) 42 Flags.setInReg(); 43 if (AttrFn(Attribute::StructRet)) 44 Flags.setSRet(); 45 if (AttrFn(Attribute::Nest)) 46 Flags.setNest(); 47 if (AttrFn(Attribute::ByVal)) 48 Flags.setByVal(); 49 if (AttrFn(Attribute::Preallocated)) 50 Flags.setPreallocated(); 51 if (AttrFn(Attribute::InAlloca)) 52 Flags.setInAlloca(); 53 if (AttrFn(Attribute::Returned)) 54 Flags.setReturned(); 55 if (AttrFn(Attribute::SwiftSelf)) 56 Flags.setSwiftSelf(); 57 if (AttrFn(Attribute::SwiftError)) 58 Flags.setSwiftError(); 59 } 60 61 ISD::ArgFlagsTy CallLowering::getAttributesForArgIdx(const CallBase &Call, 62 unsigned ArgIdx) const { 63 ISD::ArgFlagsTy Flags; 64 addFlagsUsingAttrFn(Flags, [&Call, &ArgIdx](Attribute::AttrKind Attr) { 65 return Call.paramHasAttr(ArgIdx, Attr); 66 }); 67 return Flags; 68 } 69 70 void CallLowering::addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags, 71 const AttributeList &Attrs, 72 unsigned OpIdx) const { 73 addFlagsUsingAttrFn(Flags, [&Attrs, &OpIdx](Attribute::AttrKind Attr) { 74 return Attrs.hasAttribute(OpIdx, Attr); 75 }); 76 } 77 78 bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, const CallBase &CB, 79 ArrayRef<Register> ResRegs, 80 ArrayRef<ArrayRef<Register>> ArgRegs, 81 Register SwiftErrorVReg, 82 std::function<unsigned()> GetCalleeReg) const { 83 CallLoweringInfo Info; 84 const DataLayout &DL = MIRBuilder.getDataLayout(); 85 MachineFunction &MF = MIRBuilder.getMF(); 86 bool CanBeTailCalled = CB.isTailCall() && 87 isInTailCallPosition(CB, MF.getTarget()) && 88 (MF.getFunction() 89 .getFnAttribute("disable-tail-calls") 90 .getValueAsString() != "true"); 91 92 CallingConv::ID CallConv = CB.getCallingConv(); 93 Type *RetTy = CB.getType(); 94 bool IsVarArg = CB.getFunctionType()->isVarArg(); 95 96 SmallVector<BaseArgInfo, 4> SplitArgs; 97 getReturnInfo(CallConv, RetTy, CB.getAttributes(), SplitArgs, DL); 98 Info.CanLowerReturn = canLowerReturn(MF, CallConv, SplitArgs, IsVarArg); 99 100 if (!Info.CanLowerReturn) { 101 // Callee requires sret demotion. 102 insertSRetOutgoingArgument(MIRBuilder, CB, Info); 103 104 // The sret demotion isn't compatible with tail-calls, since the sret 105 // argument points into the caller's stack frame. 106 CanBeTailCalled = false; 107 } 108 109 // First step is to marshall all the function's parameters into the correct 110 // physregs and memory locations. Gather the sequence of argument types that 111 // we'll pass to the assigner function. 112 unsigned i = 0; 113 unsigned NumFixedArgs = CB.getFunctionType()->getNumParams(); 114 for (auto &Arg : CB.args()) { 115 ArgInfo OrigArg{ArgRegs[i], Arg->getType(), getAttributesForArgIdx(CB, i), 116 i < NumFixedArgs}; 117 setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CB); 118 119 // If we have an explicit sret argument that is an Instruction, (i.e., it 120 // might point to function-local memory), we can't meaningfully tail-call. 121 if (OrigArg.Flags[0].isSRet() && isa<Instruction>(&Arg)) 122 CanBeTailCalled = false; 123 124 Info.OrigArgs.push_back(OrigArg); 125 ++i; 126 } 127 128 // Try looking through a bitcast from one function type to another. 129 // Commonly happens with calls to objc_msgSend(). 130 const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts(); 131 if (const Function *F = dyn_cast<Function>(CalleeV)) 132 Info.Callee = MachineOperand::CreateGA(F, 0); 133 else 134 Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false); 135 136 Info.OrigRet = ArgInfo{ResRegs, RetTy, ISD::ArgFlagsTy{}}; 137 if (!Info.OrigRet.Ty->isVoidTy()) 138 setArgFlags(Info.OrigRet, AttributeList::ReturnIndex, DL, CB); 139 140 Info.KnownCallees = CB.getMetadata(LLVMContext::MD_callees); 141 Info.CallConv = CallConv; 142 Info.SwiftErrorVReg = SwiftErrorVReg; 143 Info.IsMustTailCall = CB.isMustTailCall(); 144 Info.IsTailCall = CanBeTailCalled; 145 Info.IsVarArg = IsVarArg; 146 return lowerCall(MIRBuilder, Info); 147 } 148 149 template <typename FuncInfoTy> 150 void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx, 151 const DataLayout &DL, 152 const FuncInfoTy &FuncInfo) const { 153 auto &Flags = Arg.Flags[0]; 154 const AttributeList &Attrs = FuncInfo.getAttributes(); 155 addArgFlagsFromAttributes(Flags, Attrs, OpIdx); 156 157 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) { 158 Type *ElementTy = cast<PointerType>(Arg.Ty)->getElementType(); 159 160 auto Ty = Attrs.getAttribute(OpIdx, Attribute::ByVal).getValueAsType(); 161 Flags.setByValSize(DL.getTypeAllocSize(Ty ? Ty : ElementTy)); 162 163 // For ByVal, alignment should be passed from FE. BE will guess if 164 // this info is not there but there are cases it cannot get right. 165 Align FrameAlign; 166 if (auto ParamAlign = FuncInfo.getParamAlign(OpIdx - 2)) 167 FrameAlign = *ParamAlign; 168 else 169 FrameAlign = Align(getTLI()->getByValTypeAlignment(ElementTy, DL)); 170 Flags.setByValAlign(FrameAlign); 171 } 172 Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty)); 173 } 174 175 template void 176 CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx, 177 const DataLayout &DL, 178 const Function &FuncInfo) const; 179 180 template void 181 CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx, 182 const DataLayout &DL, 183 const CallBase &FuncInfo) const; 184 185 Register CallLowering::packRegs(ArrayRef<Register> SrcRegs, Type *PackedTy, 186 MachineIRBuilder &MIRBuilder) const { 187 assert(SrcRegs.size() > 1 && "Nothing to pack"); 188 189 const DataLayout &DL = MIRBuilder.getMF().getDataLayout(); 190 MachineRegisterInfo *MRI = MIRBuilder.getMRI(); 191 192 LLT PackedLLT = getLLTForType(*PackedTy, DL); 193 194 SmallVector<LLT, 8> LLTs; 195 SmallVector<uint64_t, 8> Offsets; 196 computeValueLLTs(DL, *PackedTy, LLTs, &Offsets); 197 assert(LLTs.size() == SrcRegs.size() && "Regs / types mismatch"); 198 199 Register Dst = MRI->createGenericVirtualRegister(PackedLLT); 200 MIRBuilder.buildUndef(Dst); 201 for (unsigned i = 0; i < SrcRegs.size(); ++i) { 202 Register NewDst = MRI->createGenericVirtualRegister(PackedLLT); 203 MIRBuilder.buildInsert(NewDst, Dst, SrcRegs[i], Offsets[i]); 204 Dst = NewDst; 205 } 206 207 return Dst; 208 } 209 210 void CallLowering::unpackRegs(ArrayRef<Register> DstRegs, Register SrcReg, 211 Type *PackedTy, 212 MachineIRBuilder &MIRBuilder) const { 213 assert(DstRegs.size() > 1 && "Nothing to unpack"); 214 215 const DataLayout &DL = MIRBuilder.getDataLayout(); 216 217 SmallVector<LLT, 8> LLTs; 218 SmallVector<uint64_t, 8> Offsets; 219 computeValueLLTs(DL, *PackedTy, LLTs, &Offsets); 220 assert(LLTs.size() == DstRegs.size() && "Regs / types mismatch"); 221 222 for (unsigned i = 0; i < DstRegs.size(); ++i) 223 MIRBuilder.buildExtract(DstRegs[i], SrcReg, Offsets[i]); 224 } 225 226 bool CallLowering::handleAssignments(MachineIRBuilder &MIRBuilder, 227 SmallVectorImpl<ArgInfo> &Args, 228 ValueHandler &Handler) const { 229 MachineFunction &MF = MIRBuilder.getMF(); 230 const Function &F = MF.getFunction(); 231 SmallVector<CCValAssign, 16> ArgLocs; 232 CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext()); 233 return handleAssignments(CCInfo, ArgLocs, MIRBuilder, Args, Handler); 234 } 235 236 bool CallLowering::handleAssignments(CCState &CCInfo, 237 SmallVectorImpl<CCValAssign> &ArgLocs, 238 MachineIRBuilder &MIRBuilder, 239 SmallVectorImpl<ArgInfo> &Args, 240 ValueHandler &Handler) const { 241 MachineFunction &MF = MIRBuilder.getMF(); 242 const Function &F = MF.getFunction(); 243 const DataLayout &DL = F.getParent()->getDataLayout(); 244 245 unsigned NumArgs = Args.size(); 246 for (unsigned i = 0; i != NumArgs; ++i) { 247 EVT CurVT = EVT::getEVT(Args[i].Ty); 248 if (CurVT.isSimple() && 249 !Handler.assignArg(i, CurVT.getSimpleVT(), CurVT.getSimpleVT(), 250 CCValAssign::Full, Args[i], Args[i].Flags[0], 251 CCInfo)) 252 continue; 253 254 MVT NewVT = TLI->getRegisterTypeForCallingConv( 255 F.getContext(), F.getCallingConv(), EVT(CurVT)); 256 257 // If we need to split the type over multiple regs, check it's a scenario 258 // we currently support. 259 unsigned NumParts = TLI->getNumRegistersForCallingConv( 260 F.getContext(), F.getCallingConv(), CurVT); 261 262 if (NumParts == 1) { 263 // Try to use the register type if we couldn't assign the VT. 264 if (Handler.assignArg(i, NewVT, NewVT, CCValAssign::Full, Args[i], 265 Args[i].Flags[0], CCInfo)) 266 return false; 267 continue; 268 } 269 270 assert(NumParts > 1); 271 // For now only handle exact splits. 272 if (NewVT.getSizeInBits() * NumParts != CurVT.getSizeInBits()) 273 return false; 274 275 // For incoming arguments (physregs to vregs), we could have values in 276 // physregs (or memlocs) which we want to extract and copy to vregs. 277 // During this, we might have to deal with the LLT being split across 278 // multiple regs, so we have to record this information for later. 279 // 280 // If we have outgoing args, then we have the opposite case. We have a 281 // vreg with an LLT which we want to assign to a physical location, and 282 // we might have to record that the value has to be split later. 283 if (Handler.isIncomingArgumentHandler()) { 284 // We're handling an incoming arg which is split over multiple regs. 285 // E.g. passing an s128 on AArch64. 286 ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0]; 287 Args[i].OrigRegs.push_back(Args[i].Regs[0]); 288 Args[i].Regs.clear(); 289 Args[i].Flags.clear(); 290 LLT NewLLT = getLLTForMVT(NewVT); 291 // For each split register, create and assign a vreg that will store 292 // the incoming component of the larger value. These will later be 293 // merged to form the final vreg. 294 for (unsigned Part = 0; Part < NumParts; ++Part) { 295 Register Reg = 296 MIRBuilder.getMRI()->createGenericVirtualRegister(NewLLT); 297 ISD::ArgFlagsTy Flags = OrigFlags; 298 if (Part == 0) { 299 Flags.setSplit(); 300 } else { 301 Flags.setOrigAlign(Align(1)); 302 if (Part == NumParts - 1) 303 Flags.setSplitEnd(); 304 } 305 Args[i].Regs.push_back(Reg); 306 Args[i].Flags.push_back(Flags); 307 if (Handler.assignArg(i, NewVT, NewVT, CCValAssign::Full, Args[i], 308 Args[i].Flags[Part], CCInfo)) { 309 // Still couldn't assign this smaller part type for some reason. 310 return false; 311 } 312 } 313 } else { 314 // This type is passed via multiple registers in the calling convention. 315 // We need to extract the individual parts. 316 Register LargeReg = Args[i].Regs[0]; 317 LLT SmallTy = LLT::scalar(NewVT.getSizeInBits()); 318 auto Unmerge = MIRBuilder.buildUnmerge(SmallTy, LargeReg); 319 assert(Unmerge->getNumOperands() == NumParts + 1); 320 ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0]; 321 // We're going to replace the regs and flags with the split ones. 322 Args[i].Regs.clear(); 323 Args[i].Flags.clear(); 324 for (unsigned PartIdx = 0; PartIdx < NumParts; ++PartIdx) { 325 ISD::ArgFlagsTy Flags = OrigFlags; 326 if (PartIdx == 0) { 327 Flags.setSplit(); 328 } else { 329 Flags.setOrigAlign(Align(1)); 330 if (PartIdx == NumParts - 1) 331 Flags.setSplitEnd(); 332 } 333 Args[i].Regs.push_back(Unmerge.getReg(PartIdx)); 334 Args[i].Flags.push_back(Flags); 335 if (Handler.assignArg(i, NewVT, NewVT, CCValAssign::Full, 336 Args[i], Args[i].Flags[PartIdx], CCInfo)) 337 return false; 338 } 339 } 340 } 341 342 for (unsigned i = 0, e = Args.size(), j = 0; i != e; ++i, ++j) { 343 assert(j < ArgLocs.size() && "Skipped too many arg locs"); 344 345 CCValAssign &VA = ArgLocs[j]; 346 assert(VA.getValNo() == i && "Location doesn't correspond to current arg"); 347 348 if (VA.needsCustom()) { 349 unsigned NumArgRegs = 350 Handler.assignCustomValue(Args[i], makeArrayRef(ArgLocs).slice(j)); 351 if (!NumArgRegs) 352 return false; 353 j += NumArgRegs; 354 continue; 355 } 356 357 // FIXME: Pack registers if we have more than one. 358 Register ArgReg = Args[i].Regs[0]; 359 360 EVT OrigVT = EVT::getEVT(Args[i].Ty); 361 EVT VAVT = VA.getValVT(); 362 const LLT OrigTy = getLLTForType(*Args[i].Ty, DL); 363 364 // Expected to be multiple regs for a single incoming arg. 365 // There should be Regs.size() ArgLocs per argument. 366 unsigned NumArgRegs = Args[i].Regs.size(); 367 368 assert((j + (NumArgRegs - 1)) < ArgLocs.size() && 369 "Too many regs for number of args"); 370 for (unsigned Part = 0; Part < NumArgRegs; ++Part) { 371 // There should be Regs.size() ArgLocs per argument. 372 VA = ArgLocs[j + Part]; 373 if (VA.isMemLoc()) { 374 // Don't currently support loading/storing a type that needs to be split 375 // to the stack. Should be easy, just not implemented yet. 376 if (NumArgRegs > 1) { 377 LLVM_DEBUG( 378 dbgs() 379 << "Load/store a split arg to/from the stack not implemented yet\n"); 380 return false; 381 } 382 383 // FIXME: Use correct address space for pointer size 384 EVT LocVT = VA.getValVT(); 385 unsigned MemSize = LocVT == MVT::iPTR ? DL.getPointerSize() 386 : LocVT.getStoreSize(); 387 unsigned Offset = VA.getLocMemOffset(); 388 MachinePointerInfo MPO; 389 Register StackAddr = Handler.getStackAddress(MemSize, Offset, MPO); 390 Handler.assignValueToAddress(Args[i], StackAddr, 391 MemSize, MPO, VA); 392 continue; 393 } 394 395 assert(VA.isRegLoc() && "custom loc should have been handled already"); 396 397 // GlobalISel does not currently work for scalable vectors. 398 if (OrigVT.getFixedSizeInBits() >= VAVT.getFixedSizeInBits() || 399 !Handler.isIncomingArgumentHandler()) { 400 // This is an argument that might have been split. There should be 401 // Regs.size() ArgLocs per argument. 402 403 // Insert the argument copies. If VAVT < OrigVT, we'll insert the merge 404 // to the original register after handling all of the parts. 405 Handler.assignValueToReg(Args[i].Regs[Part], VA.getLocReg(), VA); 406 continue; 407 } 408 409 // This ArgLoc covers multiple pieces, so we need to split it. 410 const LLT VATy(VAVT.getSimpleVT()); 411 Register NewReg = 412 MIRBuilder.getMRI()->createGenericVirtualRegister(VATy); 413 Handler.assignValueToReg(NewReg, VA.getLocReg(), VA); 414 // If it's a vector type, we either need to truncate the elements 415 // or do an unmerge to get the lower block of elements. 416 if (VATy.isVector() && 417 VATy.getNumElements() > OrigVT.getVectorNumElements()) { 418 // Just handle the case where the VA type is 2 * original type. 419 if (VATy.getNumElements() != OrigVT.getVectorNumElements() * 2) { 420 LLVM_DEBUG(dbgs() 421 << "Incoming promoted vector arg has too many elts"); 422 return false; 423 } 424 auto Unmerge = MIRBuilder.buildUnmerge({OrigTy, OrigTy}, {NewReg}); 425 MIRBuilder.buildCopy(ArgReg, Unmerge.getReg(0)); 426 } else { 427 MIRBuilder.buildTrunc(ArgReg, {NewReg}).getReg(0); 428 } 429 } 430 431 // Now that all pieces have been handled, re-pack any arguments into any 432 // wider, original registers. 433 if (Handler.isIncomingArgumentHandler()) { 434 if (VAVT.getFixedSizeInBits() < OrigVT.getFixedSizeInBits()) { 435 assert(NumArgRegs >= 2); 436 437 // Merge the split registers into the expected larger result vreg 438 // of the original call. 439 MIRBuilder.buildMerge(Args[i].OrigRegs[0], Args[i].Regs); 440 } 441 } 442 443 j += NumArgRegs - 1; 444 } 445 446 return true; 447 } 448 449 void CallLowering::insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, 450 ArrayRef<Register> VRegs, Register DemoteReg, 451 int FI) const { 452 MachineFunction &MF = MIRBuilder.getMF(); 453 MachineRegisterInfo &MRI = MF.getRegInfo(); 454 const DataLayout &DL = MF.getDataLayout(); 455 456 SmallVector<EVT, 4> SplitVTs; 457 SmallVector<uint64_t, 4> Offsets; 458 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0); 459 460 assert(VRegs.size() == SplitVTs.size()); 461 462 unsigned NumValues = SplitVTs.size(); 463 Align BaseAlign = DL.getPrefTypeAlign(RetTy); 464 Type *RetPtrTy = RetTy->getPointerTo(DL.getAllocaAddrSpace()); 465 LLT OffsetLLTy = getLLTForType(*DL.getIntPtrType(RetPtrTy), DL); 466 467 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI); 468 469 for (unsigned I = 0; I < NumValues; ++I) { 470 Register Addr; 471 MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]); 472 auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad, 473 MRI.getType(VRegs[I]).getSizeInBytes(), 474 commonAlignment(BaseAlign, Offsets[I])); 475 MIRBuilder.buildLoad(VRegs[I], Addr, *MMO); 476 } 477 } 478 479 void CallLowering::insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, 480 ArrayRef<Register> VRegs, 481 Register DemoteReg) const { 482 MachineFunction &MF = MIRBuilder.getMF(); 483 MachineRegisterInfo &MRI = MF.getRegInfo(); 484 const DataLayout &DL = MF.getDataLayout(); 485 486 SmallVector<EVT, 4> SplitVTs; 487 SmallVector<uint64_t, 4> Offsets; 488 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0); 489 490 assert(VRegs.size() == SplitVTs.size()); 491 492 unsigned NumValues = SplitVTs.size(); 493 Align BaseAlign = DL.getPrefTypeAlign(RetTy); 494 unsigned AS = DL.getAllocaAddrSpace(); 495 LLT OffsetLLTy = 496 getLLTForType(*DL.getIntPtrType(RetTy->getPointerTo(AS)), DL); 497 498 MachinePointerInfo PtrInfo(AS); 499 500 for (unsigned I = 0; I < NumValues; ++I) { 501 Register Addr; 502 MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]); 503 auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore, 504 MRI.getType(VRegs[I]).getSizeInBytes(), 505 commonAlignment(BaseAlign, Offsets[I])); 506 MIRBuilder.buildStore(VRegs[I], Addr, *MMO); 507 } 508 } 509 510 void CallLowering::insertSRetIncomingArgument( 511 const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg, 512 MachineRegisterInfo &MRI, const DataLayout &DL) const { 513 unsigned AS = DL.getAllocaAddrSpace(); 514 DemoteReg = MRI.createGenericVirtualRegister( 515 LLT::pointer(AS, DL.getPointerSizeInBits(AS))); 516 517 Type *PtrTy = PointerType::get(F.getReturnType(), AS); 518 519 SmallVector<EVT, 1> ValueVTs; 520 ComputeValueVTs(*TLI, DL, PtrTy, ValueVTs); 521 522 // NOTE: Assume that a pointer won't get split into more than one VT. 523 assert(ValueVTs.size() == 1); 524 525 ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(PtrTy->getContext())); 526 setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, F); 527 DemoteArg.Flags[0].setSRet(); 528 SplitArgs.insert(SplitArgs.begin(), DemoteArg); 529 } 530 531 void CallLowering::insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder, 532 const CallBase &CB, 533 CallLoweringInfo &Info) const { 534 const DataLayout &DL = MIRBuilder.getDataLayout(); 535 Type *RetTy = CB.getType(); 536 unsigned AS = DL.getAllocaAddrSpace(); 537 LLT FramePtrTy = LLT::pointer(AS, DL.getPointerSizeInBits(AS)); 538 539 int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject( 540 DL.getTypeAllocSize(RetTy), DL.getPrefTypeAlign(RetTy), false); 541 542 Register DemoteReg = MIRBuilder.buildFrameIndex(FramePtrTy, FI).getReg(0); 543 ArgInfo DemoteArg(DemoteReg, PointerType::get(RetTy, AS)); 544 setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, CB); 545 DemoteArg.Flags[0].setSRet(); 546 547 Info.OrigArgs.insert(Info.OrigArgs.begin(), DemoteArg); 548 Info.DemoteStackIndex = FI; 549 Info.DemoteRegister = DemoteReg; 550 } 551 552 bool CallLowering::checkReturn(CCState &CCInfo, 553 SmallVectorImpl<BaseArgInfo> &Outs, 554 CCAssignFn *Fn) const { 555 for (unsigned I = 0, E = Outs.size(); I < E; ++I) { 556 MVT VT = MVT::getVT(Outs[I].Ty); 557 if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], CCInfo)) 558 return false; 559 } 560 return true; 561 } 562 563 void CallLowering::getReturnInfo(CallingConv::ID CallConv, Type *RetTy, 564 AttributeList Attrs, 565 SmallVectorImpl<BaseArgInfo> &Outs, 566 const DataLayout &DL) const { 567 LLVMContext &Context = RetTy->getContext(); 568 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 569 570 SmallVector<EVT, 4> SplitVTs; 571 ComputeValueVTs(*TLI, DL, RetTy, SplitVTs); 572 addArgFlagsFromAttributes(Flags, Attrs, AttributeList::ReturnIndex); 573 574 for (EVT VT : SplitVTs) { 575 unsigned NumParts = 576 TLI->getNumRegistersForCallingConv(Context, CallConv, VT); 577 MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CallConv, VT); 578 Type *PartTy = EVT(RegVT).getTypeForEVT(Context); 579 580 for (unsigned I = 0; I < NumParts; ++I) { 581 Outs.emplace_back(PartTy, Flags); 582 } 583 } 584 } 585 586 bool CallLowering::checkReturnTypeForCallConv(MachineFunction &MF) const { 587 const auto &F = MF.getFunction(); 588 Type *ReturnType = F.getReturnType(); 589 CallingConv::ID CallConv = F.getCallingConv(); 590 591 SmallVector<BaseArgInfo, 4> SplitArgs; 592 getReturnInfo(CallConv, ReturnType, F.getAttributes(), SplitArgs, 593 MF.getDataLayout()); 594 return canLowerReturn(MF, CallConv, SplitArgs, F.isVarArg()); 595 } 596 597 bool CallLowering::analyzeArgInfo(CCState &CCState, 598 SmallVectorImpl<ArgInfo> &Args, 599 CCAssignFn &AssignFnFixed, 600 CCAssignFn &AssignFnVarArg) const { 601 for (unsigned i = 0, e = Args.size(); i < e; ++i) { 602 MVT VT = MVT::getVT(Args[i].Ty); 603 CCAssignFn &Fn = Args[i].IsFixed ? AssignFnFixed : AssignFnVarArg; 604 if (Fn(i, VT, VT, CCValAssign::Full, Args[i].Flags[0], CCState)) { 605 // Bail out on anything we can't handle. 606 LLVM_DEBUG(dbgs() << "Cannot analyze " << EVT(VT).getEVTString() 607 << " (arg number = " << i << "\n"); 608 return false; 609 } 610 } 611 return true; 612 } 613 614 bool CallLowering::parametersInCSRMatch( 615 const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, 616 const SmallVectorImpl<CCValAssign> &OutLocs, 617 const SmallVectorImpl<ArgInfo> &OutArgs) const { 618 for (unsigned i = 0; i < OutLocs.size(); ++i) { 619 auto &ArgLoc = OutLocs[i]; 620 // If it's not a register, it's fine. 621 if (!ArgLoc.isRegLoc()) 622 continue; 623 624 MCRegister PhysReg = ArgLoc.getLocReg(); 625 626 // Only look at callee-saved registers. 627 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, PhysReg)) 628 continue; 629 630 LLVM_DEBUG( 631 dbgs() 632 << "... Call has an argument passed in a callee-saved register.\n"); 633 634 // Check if it was copied from. 635 const ArgInfo &OutInfo = OutArgs[i]; 636 637 if (OutInfo.Regs.size() > 1) { 638 LLVM_DEBUG( 639 dbgs() << "... Cannot handle arguments in multiple registers.\n"); 640 return false; 641 } 642 643 // Check if we copy the register, walking through copies from virtual 644 // registers. Note that getDefIgnoringCopies does not ignore copies from 645 // physical registers. 646 MachineInstr *RegDef = getDefIgnoringCopies(OutInfo.Regs[0], MRI); 647 if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) { 648 LLVM_DEBUG( 649 dbgs() 650 << "... Parameter was not copied into a VReg, cannot tail call.\n"); 651 return false; 652 } 653 654 // Got a copy. Verify that it's the same as the register we want. 655 Register CopyRHS = RegDef->getOperand(1).getReg(); 656 if (CopyRHS != PhysReg) { 657 LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into " 658 "VReg, cannot tail call.\n"); 659 return false; 660 } 661 } 662 663 return true; 664 } 665 666 bool CallLowering::resultsCompatible(CallLoweringInfo &Info, 667 MachineFunction &MF, 668 SmallVectorImpl<ArgInfo> &InArgs, 669 CCAssignFn &CalleeAssignFnFixed, 670 CCAssignFn &CalleeAssignFnVarArg, 671 CCAssignFn &CallerAssignFnFixed, 672 CCAssignFn &CallerAssignFnVarArg) const { 673 const Function &F = MF.getFunction(); 674 CallingConv::ID CalleeCC = Info.CallConv; 675 CallingConv::ID CallerCC = F.getCallingConv(); 676 677 if (CallerCC == CalleeCC) 678 return true; 679 680 SmallVector<CCValAssign, 16> ArgLocs1; 681 CCState CCInfo1(CalleeCC, false, MF, ArgLocs1, F.getContext()); 682 if (!analyzeArgInfo(CCInfo1, InArgs, CalleeAssignFnFixed, 683 CalleeAssignFnVarArg)) 684 return false; 685 686 SmallVector<CCValAssign, 16> ArgLocs2; 687 CCState CCInfo2(CallerCC, false, MF, ArgLocs2, F.getContext()); 688 if (!analyzeArgInfo(CCInfo2, InArgs, CallerAssignFnFixed, 689 CalleeAssignFnVarArg)) 690 return false; 691 692 // We need the argument locations to match up exactly. If there's more in 693 // one than the other, then we are done. 694 if (ArgLocs1.size() != ArgLocs2.size()) 695 return false; 696 697 // Make sure that each location is passed in exactly the same way. 698 for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) { 699 const CCValAssign &Loc1 = ArgLocs1[i]; 700 const CCValAssign &Loc2 = ArgLocs2[i]; 701 702 // We need both of them to be the same. So if one is a register and one 703 // isn't, we're done. 704 if (Loc1.isRegLoc() != Loc2.isRegLoc()) 705 return false; 706 707 if (Loc1.isRegLoc()) { 708 // If they don't have the same register location, we're done. 709 if (Loc1.getLocReg() != Loc2.getLocReg()) 710 return false; 711 712 // They matched, so we can move to the next ArgLoc. 713 continue; 714 } 715 716 // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match. 717 if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset()) 718 return false; 719 } 720 721 return true; 722 } 723 724 Register CallLowering::ValueHandler::extendRegister(Register ValReg, 725 CCValAssign &VA, 726 unsigned MaxSizeBits) { 727 LLT LocTy{VA.getLocVT()}; 728 LLT ValTy = MRI.getType(ValReg); 729 if (LocTy.getSizeInBits() == ValTy.getSizeInBits()) 730 return ValReg; 731 732 if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) { 733 if (MaxSizeBits <= ValTy.getSizeInBits()) 734 return ValReg; 735 LocTy = LLT::scalar(MaxSizeBits); 736 } 737 738 switch (VA.getLocInfo()) { 739 default: break; 740 case CCValAssign::Full: 741 case CCValAssign::BCvt: 742 // FIXME: bitconverting between vector types may or may not be a 743 // nop in big-endian situations. 744 return ValReg; 745 case CCValAssign::AExt: { 746 auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg); 747 return MIB.getReg(0); 748 } 749 case CCValAssign::SExt: { 750 Register NewReg = MRI.createGenericVirtualRegister(LocTy); 751 MIRBuilder.buildSExt(NewReg, ValReg); 752 return NewReg; 753 } 754 case CCValAssign::ZExt: { 755 Register NewReg = MRI.createGenericVirtualRegister(LocTy); 756 MIRBuilder.buildZExt(NewReg, ValReg); 757 return NewReg; 758 } 759 } 760 llvm_unreachable("unable to extend register"); 761 } 762 763 void CallLowering::ValueHandler::anchor() {} 764