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/GlobalISel/CallLowering.h"
15#include "llvm/CodeGen/Analysis.h"
16#include "llvm/CodeGen/CallingConvLower.h"
17#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
18#include "llvm/CodeGen/GlobalISel/Utils.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineOperand.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/TargetLowering.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Target/TargetMachine.h"
27
28#define DEBUG_TYPE "call-lowering"
29
30using namespace llvm;
31
32void CallLowering::anchor() {}
33
34/// Helper function which updates \p Flags based on the contents of \p Attrs.
35static void addFlagsFromAttrSet(ISD::ArgFlagsTy &Flags, AttributeSet Attrs) {
36 if (!Attrs.hasAttributes())
37 return;
38
39 // TODO: There are missing flags. Add them here.
40 for (Attribute Attr : Attrs) {
41 if (Attr.isStringAttribute())
42 continue;
43
44 switch (Attr.getKindAsEnum()) {
45 case Attribute::SExt:
46 Flags.setSExt();
47 break;
48 case Attribute::ZExt:
49 Flags.setZExt();
50 break;
51 case Attribute::InReg:
52 Flags.setInReg();
53 break;
54 case Attribute::StructRet:
55 Flags.setSRet();
56 break;
57 case Attribute::Nest:
58 Flags.setNest();
59 break;
60 case Attribute::ByVal:
61 Flags.setByVal();
62 break;
63 case Attribute::ByRef:
64 Flags.setByRef();
65 break;
66 case Attribute::InAlloca:
67 Flags.setInAlloca();
68 // Set the byval flag for CCAssignFn callbacks that don't know about
69 // inalloca. This way we can know how many bytes we should've allocated
70 // and how many bytes a callee cleanup function will pop. If we port
71 // inalloca to more targets, we'll have to add custom inalloca handling
72 // in the various CC lowering callbacks.
73 Flags.setByVal();
74 break;
75 case Attribute::Preallocated:
76 Flags.setPreallocated();
77 // Set the byval flag for CCAssignFn callbacks that don't know about
78 // preallocated. This way we can know how many bytes we should've
79 // allocated and how many bytes a callee cleanup function will pop. If
80 // we port preallocated to more targets, we'll have to add custom
81 // preallocated handling in the various CC lowering callbacks.
82 Flags.setByVal();
83 break;
84 case Attribute::Returned:
85 Flags.setReturned();
86 break;
87 case Attribute::SwiftSelf:
88 Flags.setSwiftSelf();
89 break;
90 case Attribute::SwiftAsync:
91 Flags.setSwiftAsync();
92 break;
93 case Attribute::SwiftError:
94 Flags.setSwiftError();
95 break;
96 default:
97 break;
98 }
99 }
100}
101
102ISD::ArgFlagsTy CallLowering::getAttributesForArgIdx(const CallBase &Call,
103 unsigned ArgIdx) const {
104 ISD::ArgFlagsTy Flags;
105 const AttributeList &Attrs = Call.getAttributes();
106 addFlagsFromAttrSet(Flags, Attrs: Attrs.getParamAttrs(ArgNo: ArgIdx));
107 if (const Function *F = Call.getCalledFunction())
108 addFlagsFromAttrSet(Flags, Attrs: F->getAttributes().getParamAttrs(ArgNo: ArgIdx));
109 return Flags;
110}
111
112ISD::ArgFlagsTy
113CallLowering::getAttributesForReturn(const CallBase &Call) const {
114 ISD::ArgFlagsTy Flags;
115 addFlagsFromAttrSet(Flags, Attrs: Call.getAttributes().getRetAttrs());
116 if (const Function *F = Call.getCalledFunction())
117 addFlagsFromAttrSet(Flags, Attrs: F->getAttributes().getRetAttrs());
118 return Flags;
119}
120
121void CallLowering::addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags,
122 const AttributeList &Attrs,
123 unsigned OpIdx) const {
124 addFlagsFromAttrSet(Flags, Attrs: Attrs.getAttributes(Index: OpIdx));
125}
126
127bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, const CallBase &CB,
128 ArrayRef<Register> ResRegs,
129 ArrayRef<ArrayRef<Register>> ArgRegs,
130 Register SwiftErrorVReg,
131 std::optional<PtrAuthInfo> PAI,
132 Register ConvergenceCtrlToken,
133 std::function<Register()> GetCalleeReg) const {
134 CallLoweringInfo Info;
135 const DataLayout &DL = MIRBuilder.getDataLayout();
136 MachineFunction &MF = MIRBuilder.getMF();
137 MachineRegisterInfo &MRI = MF.getRegInfo();
138 bool CanBeTailCalled = CB.isTailCall() &&
139 isInTailCallPosition(Call: CB, TM: MF.getTarget()) &&
140 (MF.getFunction()
141 .getFnAttribute(Kind: "disable-tail-calls")
142 .getValueAsString() != "true");
143
144 CallingConv::ID CallConv = CB.getCallingConv();
145 Type *RetTy = CB.getType();
146 bool IsVarArg = CB.getFunctionType()->isVarArg();
147
148 SmallVector<BaseArgInfo, 4> SplitArgs;
149 getReturnInfo(CallConv, RetTy, Attrs: CB.getAttributes(), Outs&: SplitArgs, DL);
150 Info.CanLowerReturn = canLowerReturn(MF, CallConv, Outs&: SplitArgs, IsVarArg);
151
152 Info.IsConvergent = CB.isConvergent();
153
154 if (!Info.CanLowerReturn) {
155 // Callee requires sret demotion.
156 insertSRetOutgoingArgument(MIRBuilder, CB, Info);
157
158 // The sret demotion isn't compatible with tail-calls, since the sret
159 // argument points into the caller's stack frame.
160 CanBeTailCalled = false;
161 }
162
163 // First step is to marshall all the function's parameters into the correct
164 // physregs and memory locations. Gather the sequence of argument types that
165 // we'll pass to the assigner function.
166 unsigned i = 0;
167 unsigned NumFixedArgs = CB.getFunctionType()->getNumParams();
168 for (const auto &Arg : CB.args()) {
169 ArgInfo OrigArg{ArgRegs[i], *Arg.get(), i, getAttributesForArgIdx(Call: CB, ArgIdx: i)};
170 setArgFlags(Arg&: OrigArg, OpIdx: i + AttributeList::FirstArgIndex, DL, FuncInfo: CB);
171 if (i >= NumFixedArgs)
172 OrigArg.Flags[0].setVarArg();
173
174 // If we have an explicit sret argument that is an Instruction, (i.e., it
175 // might point to function-local memory), we can't meaningfully tail-call.
176 if (OrigArg.Flags[0].isSRet() && isa<Instruction>(Val: &Arg))
177 CanBeTailCalled = false;
178
179 Info.OrigArgs.push_back(Elt: OrigArg);
180 ++i;
181 }
182
183 // Try looking through a bitcast from one function type to another.
184 // Commonly happens with calls to objc_msgSend().
185 const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts();
186
187 // If IRTranslator chose to drop the ptrauth info, we can turn this into
188 // a direct call.
189 if (!PAI && CB.countOperandBundlesOfType(ID: LLVMContext::OB_ptrauth)) {
190 CalleeV = cast<ConstantPtrAuth>(Val: CalleeV)->getPointer();
191 assert(isa<Function>(CalleeV));
192 }
193
194 if (const Function *F = dyn_cast<Function>(Val: CalleeV)) {
195 if (F->hasFnAttribute(Kind: Attribute::NonLazyBind)) {
196 LLT Ty = getLLTForType(Ty&: *F->getType(), DL);
197 Register Reg = MIRBuilder.buildGlobalValue(Res: Ty, GV: F).getReg(Idx: 0);
198 Info.Callee = MachineOperand::CreateReg(Reg, isDef: false);
199 } else {
200 Info.Callee = MachineOperand::CreateGA(GV: F, Offset: 0);
201 }
202 } else if (isa<GlobalIFunc>(Val: CalleeV) || isa<GlobalAlias>(Val: CalleeV)) {
203 // IR IFuncs and Aliases can't be forward declared (only defined), so the
204 // callee must be in the same TU and therefore we can direct-call it without
205 // worrying about it being out of range.
206 Info.Callee = MachineOperand::CreateGA(GV: cast<GlobalValue>(Val: CalleeV), Offset: 0);
207 } else
208 Info.Callee = MachineOperand::CreateReg(Reg: GetCalleeReg(), isDef: false);
209
210 Register ReturnHintAlignReg;
211 Align ReturnHintAlign;
212
213 Info.OrigRet = ArgInfo{ResRegs, RetTy, 0, getAttributesForReturn(Call: CB)};
214
215 if (!Info.OrigRet.Ty->isVoidTy()) {
216 setArgFlags(Arg&: Info.OrigRet, OpIdx: AttributeList::ReturnIndex, DL, FuncInfo: CB);
217
218 if (MaybeAlign Alignment = CB.getRetAlign()) {
219 if (*Alignment > Align(1)) {
220 ReturnHintAlignReg = MRI.cloneVirtualRegister(VReg: ResRegs[0]);
221 Info.OrigRet.Regs[0] = ReturnHintAlignReg;
222 ReturnHintAlign = *Alignment;
223 }
224 }
225 }
226
227 auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_kcfi);
228 if (Bundle && CB.isIndirectCall()) {
229 Info.CFIType = cast<ConstantInt>(Val: Bundle->Inputs[0]);
230 assert(Info.CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
231 }
232
233 if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) {
234 Info.DeactivationSymbol = cast<GlobalValue>(Val: Bundle->Inputs[0]);
235 }
236
237 Info.CB = &CB;
238 Info.KnownCallees = CB.getMetadata(KindID: LLVMContext::MD_callees);
239 Info.CallConv = CallConv;
240 Info.SwiftErrorVReg = SwiftErrorVReg;
241 Info.PAI = PAI;
242 Info.ConvergenceCtrlToken = ConvergenceCtrlToken;
243 Info.IsMustTailCall = CB.isMustTailCall();
244 Info.IsTailCall = CanBeTailCalled;
245 Info.IsVarArg = IsVarArg;
246 if (!lowerCall(MIRBuilder, Info))
247 return false;
248
249 if (ReturnHintAlignReg && !Info.LoweredTailCall) {
250 MIRBuilder.buildAssertAlign(Res: ResRegs[0], Op: ReturnHintAlignReg,
251 AlignVal: ReturnHintAlign);
252 }
253
254 return true;
255}
256
257template <typename FuncInfoTy>
258void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx,
259 const DataLayout &DL,
260 const FuncInfoTy &FuncInfo) const {
261 auto &Flags = Arg.Flags[0];
262 const AttributeList &Attrs = FuncInfo.getAttributes();
263 addArgFlagsFromAttributes(Flags, Attrs, OpIdx);
264
265 PointerType *PtrTy = dyn_cast<PointerType>(Val: Arg.Ty->getScalarType());
266 if (PtrTy) {
267 Flags.setPointer();
268 Flags.setPointerAddrSpace(PtrTy->getPointerAddressSpace());
269 }
270
271 Align MemAlign = DL.getABITypeAlign(Ty: Arg.Ty);
272 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
273 Flags.isByRef()) {
274 assert(OpIdx >= AttributeList::FirstArgIndex);
275 unsigned ParamIdx = OpIdx - AttributeList::FirstArgIndex;
276
277 Type *ElementTy = FuncInfo.getParamByValType(ParamIdx);
278 if (!ElementTy)
279 ElementTy = FuncInfo.getParamByRefType(ParamIdx);
280 if (!ElementTy)
281 ElementTy = FuncInfo.getParamInAllocaType(ParamIdx);
282 if (!ElementTy)
283 ElementTy = FuncInfo.getParamPreallocatedType(ParamIdx);
284
285 assert(ElementTy && "Must have byval, inalloca or preallocated type");
286
287 uint64_t MemSize = DL.getTypeAllocSize(Ty: ElementTy);
288 if (Flags.isByRef())
289 Flags.setByRefSize(MemSize);
290 else
291 Flags.setByValSize(MemSize);
292
293 // For ByVal, alignment should be passed from FE. BE will guess if
294 // this info is not there but there are cases it cannot get right.
295 if (auto ParamAlign = FuncInfo.getParamStackAlign(ParamIdx))
296 MemAlign = *ParamAlign;
297 else if ((ParamAlign = FuncInfo.getParamAlign(ParamIdx)))
298 MemAlign = *ParamAlign;
299 else
300 MemAlign = getTLI()->getByValTypeAlignment(Ty: ElementTy, DL);
301 } else if (OpIdx >= AttributeList::FirstArgIndex) {
302 if (auto ParamAlign =
303 FuncInfo.getParamStackAlign(OpIdx - AttributeList::FirstArgIndex))
304 MemAlign = *ParamAlign;
305 }
306 Flags.setMemAlign(MemAlign);
307 Flags.setOrigAlign(DL.getABITypeAlign(Ty: Arg.Ty));
308
309 // Don't try to use the returned attribute if the argument is marked as
310 // swiftself, since it won't be passed in x0.
311 if (Flags.isSwiftSelf())
312 Flags.setReturned(false);
313}
314
315template void
316CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
317 const DataLayout &DL,
318 const Function &FuncInfo) const;
319
320template void
321CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
322 const DataLayout &DL,
323 const CallBase &FuncInfo) const;
324
325void CallLowering::splitToValueTypes(const ArgInfo &OrigArg,
326 SmallVectorImpl<ArgInfo> &SplitArgs,
327 const DataLayout &DL,
328 CallingConv::ID CallConv,
329 SmallVectorImpl<TypeSize> *Offsets) const {
330 SmallVector<Type *, 4> SplitTys;
331 ComputeValueTypes(DL, Ty: OrigArg.Ty, Types&: SplitTys, Offsets);
332
333 if (SplitTys.size() == 0)
334 return;
335
336 if (SplitTys.size() == 1) {
337 // No splitting to do, but we want to replace the original type (e.g. [1 x
338 // double] -> double).
339 SplitArgs.emplace_back(Args: OrigArg.Regs[0], Args&: SplitTys[0], Args: OrigArg.OrigArgIndex,
340 Args: OrigArg.Flags[0], Args: OrigArg.OrigValue);
341 return;
342 }
343
344 // Create one ArgInfo for each virtual register in the original ArgInfo.
345 assert(OrigArg.Regs.size() == SplitTys.size() && "Regs / types mismatch");
346
347 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
348 Ty: OrigArg.Ty, CallConv, isVarArg: false, DL);
349 for (unsigned i = 0, e = SplitTys.size(); i < e; ++i) {
350 SplitArgs.emplace_back(Args: OrigArg.Regs[i], Args&: SplitTys[i], Args: OrigArg.OrigArgIndex,
351 Args: OrigArg.Flags[0]);
352 if (NeedsRegBlock)
353 SplitArgs.back().Flags[0].setInConsecutiveRegs();
354 }
355
356 SplitArgs.back().Flags[0].setInConsecutiveRegsLast();
357}
358
359/// Pack values \p SrcRegs to cover the vector type result \p DstRegs.
360static MachineInstrBuilder
361mergeVectorRegsToResultRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs,
362 ArrayRef<Register> SrcRegs) {
363 MachineRegisterInfo &MRI = *B.getMRI();
364 LLT LLTy = MRI.getType(Reg: DstRegs[0]);
365 LLT PartLLT = MRI.getType(Reg: SrcRegs[0]);
366
367 // Deal with v3s16 split into v2s16
368 LLT LCMTy = getCoverTy(OrigTy: LLTy, TargetTy: PartLLT);
369 if (LCMTy == LLTy) {
370 // Common case where no padding is needed.
371 assert(DstRegs.size() == 1);
372
373 SmallVector<Register, 8> ConcatRegs(SrcRegs.size());
374 llvm::copy(Range&: SrcRegs, Out: ConcatRegs.begin());
375
376 if (LLTy.getScalarType() != PartLLT.getScalarType())
377 for (size_t I = 0, E = SrcRegs.size(); I != E; ++I) {
378 auto BitcastDst =
379 MRI.getType(Reg: SrcRegs[I]).changeElementType(NewEltTy: LLTy.getScalarType());
380 ConcatRegs[I] = B.buildBitcast(Dst: BitcastDst, Src: SrcRegs[I]).getReg(Idx: 0);
381 }
382
383 return B.buildConcatVectors(Res: DstRegs[0], Ops: ConcatRegs);
384 }
385
386 // We need to create an unmerge to the result registers, which may require
387 // widening the original value.
388 Register UnmergeSrcReg;
389 if (LCMTy.getSizeInBits() != PartLLT.getSizeInBits()) {
390 assert(DstRegs.size() == 1);
391 return B.buildDeleteTrailingVectorElements(
392 Res: DstRegs[0], Op0: B.buildMergeLikeInstr(Res: LCMTy, Ops: SrcRegs));
393 } else {
394 // We don't need to widen anything if we're extracting a scalar which was
395 // promoted to a vector e.g. s8 -> v4s8 -> s8
396 assert(SrcRegs.size() == 1);
397 UnmergeSrcReg = SrcRegs[0];
398 }
399
400 size_t NumDst = LCMTy.getSizeInBits() / LLTy.getSizeInBits();
401
402 SmallVector<Register, 8> PadDstRegs(NumDst);
403 llvm::copy(Range&: DstRegs, Out: PadDstRegs.begin());
404
405 // Create the excess dead defs for the unmerge.
406 for (size_t I = DstRegs.size(); I != NumDst; ++I)
407 PadDstRegs[I] = MRI.createGenericVirtualRegister(Ty: LLTy);
408
409 if (PartLLT != LCMTy)
410 UnmergeSrcReg = B.buildBitcast(Dst: LCMTy, Src: UnmergeSrcReg).getReg(Idx: 0);
411
412 if (PadDstRegs.size() == 1)
413 return B.buildDeleteTrailingVectorElements(Res: DstRegs[0], Op0: UnmergeSrcReg);
414 return B.buildUnmerge(Res: PadDstRegs, Op: UnmergeSrcReg);
415}
416
417void CallLowering::buildCopyFromRegs(MachineIRBuilder &B,
418 ArrayRef<Register> OrigRegs,
419 ArrayRef<Register> Regs, LLT LLTy,
420 LLT PartLLT, const ISD::ArgFlagsTy Flags) {
421 MachineRegisterInfo &MRI = *B.getMRI();
422
423 if (PartLLT == LLTy) {
424 // We should have avoided introducing a new virtual register, and just
425 // directly assigned here.
426 assert(OrigRegs[0] == Regs[0]);
427 return;
428 }
429
430 if (PartLLT.getSizeInBits() == LLTy.getSizeInBits() && OrigRegs.size() == 1 &&
431 Regs.size() == 1) {
432 B.buildBitcast(Dst: OrigRegs[0], Src: Regs[0]);
433 return;
434 }
435
436 // A vector PartLLT needs extending to LLTy's element size.
437 // E.g. <2 x s64> = G_SEXT <2 x s32>.
438 if (PartLLT.isVector() == LLTy.isVector() &&
439 PartLLT.getScalarSizeInBits() > LLTy.getScalarSizeInBits() &&
440 (!PartLLT.isVector() ||
441 PartLLT.getElementCount() == LLTy.getElementCount()) &&
442 OrigRegs.size() == 1 && Regs.size() == 1) {
443 Register SrcReg = Regs[0];
444
445 LLT LocTy = MRI.getType(Reg: SrcReg);
446
447 if (Flags.isSExt()) {
448 SrcReg = B.buildAssertSExt(Res: LocTy, Op: SrcReg, Size: LLTy.getScalarSizeInBits())
449 .getReg(Idx: 0);
450 } else if (Flags.isZExt()) {
451 SrcReg = B.buildAssertZExt(Res: LocTy, Op: SrcReg, Size: LLTy.getScalarSizeInBits())
452 .getReg(Idx: 0);
453 }
454
455 // Sometimes pointers are passed zero extended.
456 LLT OrigTy = MRI.getType(Reg: OrigRegs[0]);
457 if (OrigTy.isPointer()) {
458 LLT IntPtrTy = LLT::scalar(SizeInBits: OrigTy.getSizeInBits());
459 B.buildIntToPtr(Dst: OrigRegs[0], Src: B.buildTrunc(Res: IntPtrTy, Op: SrcReg));
460 return;
461 }
462
463 B.buildTrunc(Res: OrigRegs[0], Op: SrcReg);
464 return;
465 }
466
467 if (!LLTy.isVector() && !PartLLT.isVector()) {
468 assert(OrigRegs.size() == 1);
469 LLT OrigTy = MRI.getType(Reg: OrigRegs[0]);
470
471 unsigned SrcSize = PartLLT.getSizeInBits().getFixedValue() * Regs.size();
472 if (SrcSize == OrigTy.getSizeInBits())
473 B.buildMergeValues(Res: OrigRegs[0], Ops: Regs);
474 else {
475 auto Widened = B.buildMergeLikeInstr(Res: LLT::integer(SizeInBits: SrcSize), Ops: Regs);
476 B.buildTrunc(Res: OrigRegs[0], Op: Widened);
477 }
478
479 return;
480 }
481
482 if (PartLLT.isVector()) {
483 assert(OrigRegs.size() == 1);
484 SmallVector<Register> CastRegs(Regs);
485
486 // If PartLLT is a mismatched vector in both number of elements and element
487 // size, e.g. PartLLT == v2s64 and LLTy is v3s32, then first coerce it to
488 // have the same elt type, i.e. v4s32.
489 // TODO: Extend this coersion to element multiples other than just 2.
490 if (TypeSize::isKnownGT(LHS: PartLLT.getSizeInBits(), RHS: LLTy.getSizeInBits()) &&
491 PartLLT.getScalarSizeInBits() == LLTy.getScalarSizeInBits() * 2 &&
492 Regs.size() == 1) {
493 LLT NewTy = PartLLT.changeElementType(NewEltTy: LLTy.getElementType())
494 .changeElementCount(EC: PartLLT.getElementCount() * 2);
495 CastRegs[0] = B.buildBitcast(Dst: NewTy, Src: Regs[0]).getReg(Idx: 0);
496 PartLLT = NewTy;
497 }
498
499 if (LLTy.getScalarSizeInBits() == PartLLT.getScalarSizeInBits()) {
500 mergeVectorRegsToResultRegs(B, DstRegs: OrigRegs, SrcRegs: CastRegs);
501 } else {
502 unsigned I = 0;
503 LLT GCDTy = getGCDType(OrigTy: LLTy, TargetTy: PartLLT);
504
505 // We are both splitting a vector, and bitcasting its element types. Cast
506 // the source pieces into the appropriate number of pieces with the result
507 // element type.
508 for (Register SrcReg : CastRegs)
509 CastRegs[I++] = B.buildBitcast(Dst: GCDTy, Src: SrcReg).getReg(Idx: 0);
510 mergeVectorRegsToResultRegs(B, DstRegs: OrigRegs, SrcRegs: CastRegs);
511 }
512
513 return;
514 }
515
516 assert(LLTy.isVector() && !PartLLT.isVector());
517
518 LLT DstEltTy = LLTy.getElementType();
519
520 // Pointer information was discarded. We'll need to coerce some register types
521 // to avoid violating type constraints.
522 LLT RealDstEltTy = MRI.getType(Reg: OrigRegs[0]).getElementType();
523
524 assert(DstEltTy.getSizeInBits() == RealDstEltTy.getSizeInBits());
525
526 if (DstEltTy == PartLLT) {
527 // Vector was trivially scalarized.
528
529 if (RealDstEltTy.isPointer()) {
530 for (Register Reg : Regs)
531 MRI.setType(VReg: Reg, Ty: RealDstEltTy);
532 }
533
534 B.buildBuildVector(Res: OrigRegs[0], Ops: Regs);
535 } else if (DstEltTy.getSizeInBits() > PartLLT.getSizeInBits()) {
536 // Deal with vector with 64-bit elements decomposed to 32-bit
537 // registers. Need to create intermediate 64-bit elements.
538 SmallVector<Register, 8> EltMerges;
539 int PartsPerElt =
540 divideCeil(Numerator: DstEltTy.getSizeInBits(), Denominator: PartLLT.getSizeInBits());
541 LLT ExtendedPartTy = LLT::integer(SizeInBits: PartLLT.getSizeInBits() * PartsPerElt);
542
543 for (int I = 0, NumElts = LLTy.getNumElements(); I != NumElts; ++I) {
544 auto Merge =
545 B.buildMergeLikeInstr(Res: ExtendedPartTy, Ops: Regs.take_front(N: PartsPerElt));
546 if (ExtendedPartTy.getSizeInBits() > RealDstEltTy.getSizeInBits())
547 Merge = B.buildTrunc(Res: RealDstEltTy, Op: Merge);
548 // Fix the type in case this is really a vector of pointers.
549 MRI.setType(VReg: Merge.getReg(Idx: 0), Ty: RealDstEltTy);
550 EltMerges.push_back(Elt: Merge.getReg(Idx: 0));
551 Regs = Regs.drop_front(N: PartsPerElt);
552 }
553
554 B.buildBuildVector(Res: OrigRegs[0], Ops: EltMerges);
555 } else {
556 // Vector was split, and elements promoted to a wider type.
557 // FIXME: Should handle floating point promotions.
558 unsigned NumElts = LLTy.getNumElements();
559 LLT BVType = LLT::fixed_vector(NumElements: NumElts, ScalarTy: PartLLT);
560
561 Register BuildVec;
562 if (NumElts == Regs.size())
563 BuildVec = B.buildBuildVector(Res: BVType, Ops: Regs).getReg(Idx: 0);
564 else {
565 // Vector elements are packed in the inputs.
566 // e.g. we have a <4 x s16> but 2 x s32 in regs.
567 assert(NumElts > Regs.size());
568 LLT SrcEltTy = MRI.getType(Reg: Regs[0]);
569
570 LLT OriginalEltTy = MRI.getType(Reg: OrigRegs[0]).getElementType();
571
572 // Input registers contain packed elements.
573 // Determine how many elements per reg.
574 assert((SrcEltTy.getSizeInBits() % OriginalEltTy.getSizeInBits()) == 0);
575 unsigned EltPerReg =
576 (SrcEltTy.getSizeInBits() / OriginalEltTy.getSizeInBits());
577
578 SmallVector<Register, 0> BVRegs;
579 BVRegs.reserve(N: Regs.size() * EltPerReg);
580 for (Register R : Regs) {
581 auto Unmerge = B.buildUnmerge(Res: OriginalEltTy, Op: R);
582 for (unsigned K = 0; K < EltPerReg; ++K)
583 BVRegs.push_back(Elt: B.buildAnyExt(Res: PartLLT, Op: Unmerge.getReg(Idx: K)).getReg(Idx: 0));
584 }
585
586 // We may have some more elements in BVRegs, e.g. if we have 2 s32 pieces
587 // for a <3 x s16> vector. We should have less than EltPerReg extra items.
588 if (BVRegs.size() > NumElts) {
589 assert((BVRegs.size() - NumElts) < EltPerReg);
590 BVRegs.truncate(N: NumElts);
591 }
592 BuildVec = B.buildBuildVector(Res: BVType, Ops: BVRegs).getReg(Idx: 0);
593 }
594 B.buildTrunc(Res: OrigRegs[0], Op: BuildVec);
595 }
596}
597
598void CallLowering::buildCopyToRegs(MachineIRBuilder &B,
599 ArrayRef<Register> DstRegs, Register SrcReg,
600 LLT SrcTy, LLT PartTy, unsigned ExtendOp) {
601 // We could just insert a regular copy, but this is unreachable at the moment.
602 assert(SrcTy != PartTy && "identical part types shouldn't reach here");
603
604 const TypeSize PartSize = PartTy.getSizeInBits();
605
606 if (PartSize == SrcTy.getSizeInBits() && DstRegs.size() == 1) {
607 // TODO: Handle int<->ptr casts. It just happens the ABI lowering
608 // assignments are not pointer aware.
609 B.buildBitcast(Dst: DstRegs[0], Src: SrcReg);
610 return;
611 }
612
613 if (PartTy.isVector() == SrcTy.isVector() &&
614 PartTy.getScalarSizeInBits() > SrcTy.getScalarSizeInBits()) {
615 assert(DstRegs.size() == 1);
616 B.buildInstr(Opc: ExtendOp, DstOps: {DstRegs[0]}, SrcOps: {SrcReg});
617 return;
618 }
619
620 if (SrcTy.isVector() && !PartTy.isVector() &&
621 TypeSize::isKnownGT(LHS: PartSize, RHS: SrcTy.getElementType().getSizeInBits()) &&
622 SrcTy.getElementCount() == ElementCount::getFixed(MinVal: DstRegs.size())) {
623 // Vector was scalarized, and the elements extended.
624 auto UnmergeToEltTy = B.buildUnmerge(Res: SrcTy.getElementType(), Op: SrcReg);
625 for (int i = 0, e = DstRegs.size(); i != e; ++i)
626 B.buildAnyExt(Res: DstRegs[i], Op: UnmergeToEltTy.getReg(Idx: i));
627 return;
628 }
629
630 if (SrcTy.isVector() && PartTy.isVector() &&
631 PartTy.getSizeInBits() == SrcTy.getSizeInBits() &&
632 ElementCount::isKnownLT(LHS: SrcTy.getElementCount(),
633 RHS: PartTy.getElementCount())) {
634 // A coercion like: v2f32 -> v4f32 or nxv2f32 -> nxv4f32
635 Register DstReg = DstRegs.front();
636 B.buildPadVectorWithUndefElements(Res: DstReg, Op0: SrcReg);
637 return;
638 }
639
640 LLT GCDTy = getGCDType(OrigTy: SrcTy, TargetTy: PartTy);
641 if (GCDTy == PartTy) {
642 // If this already evenly divisible, we can create a simple unmerge.
643 B.buildUnmerge(Res: DstRegs, Op: SrcReg);
644 return;
645 }
646
647 if (SrcTy.isVector() && !PartTy.isVector() &&
648 SrcTy.getScalarSizeInBits() > PartTy.getSizeInBits()) {
649 LLT ExtTy =
650 LLT::vector(EC: SrcTy.getElementCount(),
651 ScalarTy: LLT::integer(SizeInBits: PartTy.getScalarSizeInBits() * DstRegs.size() /
652 SrcTy.getNumElements()));
653 auto Ext = B.buildAnyExt(Res: ExtTy, Op: SrcReg);
654 B.buildUnmerge(Res: DstRegs, Op: Ext);
655 return;
656 }
657
658 MachineRegisterInfo &MRI = *B.getMRI();
659 LLT DstTy = MRI.getType(Reg: DstRegs[0]);
660 LLT CoverTy = getCoverTy(OrigTy: SrcTy, TargetTy: PartTy);
661 if (SrcTy.isVector() && DstRegs.size() > 1) {
662 TypeSize FullCoverSize =
663 DstTy.getSizeInBits().multiplyCoefficientBy(RHS: DstRegs.size());
664
665 LLT EltTy = SrcTy.getElementType();
666 TypeSize EltSize = EltTy.getSizeInBits();
667 if (FullCoverSize.isKnownMultipleOf(RHS: EltSize)) {
668 TypeSize VecSize = FullCoverSize.divideCoefficientBy(RHS: EltSize);
669 CoverTy =
670 LLT::vector(EC: ElementCount::get(MinVal: VecSize, Scalable: VecSize.isScalable()), ScalarTy: EltTy);
671 }
672 }
673
674 if (PartTy.isVector() && CoverTy == PartTy) {
675 assert(DstRegs.size() == 1);
676 B.buildPadVectorWithUndefElements(Res: DstRegs[0], Op0: SrcReg);
677 return;
678 }
679
680 const unsigned DstSize = DstTy.getSizeInBits();
681 const unsigned SrcSize = SrcTy.getSizeInBits();
682 unsigned CoveringSize = CoverTy.getSizeInBits();
683
684 Register UnmergeSrc = SrcReg;
685
686 if (!CoverTy.isVector() && CoveringSize != SrcSize) {
687 // For scalars, it's common to be able to use a simple extension.
688 if (SrcTy.isScalar() && DstTy.isScalar()) {
689 CoveringSize = alignTo(Value: SrcSize, Align: DstSize);
690 LLT CoverTy = LLT::integer(SizeInBits: CoveringSize);
691 UnmergeSrc = B.buildInstr(Opc: ExtendOp, DstOps: {CoverTy}, SrcOps: {SrcReg}).getReg(Idx: 0);
692 } else {
693 // Widen to the common type.
694 // FIXME: This should respect the extend type
695 Register Undef = B.buildUndef(Res: SrcTy).getReg(Idx: 0);
696 SmallVector<Register, 8> MergeParts(1, SrcReg);
697 for (unsigned Size = SrcSize; Size != CoveringSize; Size += SrcSize)
698 MergeParts.push_back(Elt: Undef);
699 UnmergeSrc = B.buildMergeLikeInstr(Res: CoverTy, Ops: MergeParts).getReg(Idx: 0);
700 }
701 }
702
703 if (CoverTy.isVector() && CoveringSize != SrcSize)
704 UnmergeSrc = B.buildPadVectorWithUndefElements(Res: CoverTy, Op0: SrcReg).getReg(Idx: 0);
705
706 B.buildUnmerge(Res: DstRegs, Op: UnmergeSrc);
707}
708
709bool CallLowering::determineAndHandleAssignments(
710 ValueHandler &Handler, ValueAssigner &Assigner,
711 SmallVectorImpl<ArgInfo> &Args, MachineIRBuilder &MIRBuilder,
712 CallingConv::ID CallConv, bool IsVarArg,
713 ArrayRef<Register> ThisReturnRegs) const {
714 MachineFunction &MF = MIRBuilder.getMF();
715 const Function &F = MF.getFunction();
716 SmallVector<CCValAssign, 16> ArgLocs;
717
718 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, F.getContext());
719 if (!determineAssignments(Assigner, Args, CCInfo))
720 return false;
721
722 return handleAssignments(Handler, Args, CCState&: CCInfo, ArgLocs, MIRBuilder,
723 ThisReturnRegs);
724}
725
726static unsigned extendOpFromFlags(llvm::ISD::ArgFlagsTy Flags) {
727 if (Flags.isSExt())
728 return TargetOpcode::G_SEXT;
729 if (Flags.isZExt())
730 return TargetOpcode::G_ZEXT;
731 return TargetOpcode::G_ANYEXT;
732}
733
734bool CallLowering::determineAssignments(ValueAssigner &Assigner,
735 SmallVectorImpl<ArgInfo> &Args,
736 CCState &CCInfo) const {
737 LLVMContext &Ctx = CCInfo.getContext();
738 const DataLayout &DL = CCInfo.getMachineFunction().getDataLayout();
739 const CallingConv::ID CallConv = CCInfo.getCallingConv();
740
741 unsigned NumArgs = Args.size();
742 for (unsigned i = 0; i != NumArgs; ++i) {
743 EVT CurVT = TLI->getValueType(DL, Ty: Args[i].Ty);
744
745 MVT NewVT = TLI->getRegisterTypeForCallingConv(Context&: Ctx, CC: CallConv, VT: CurVT);
746
747 // If we need to split the type over multiple regs, check it's a scenario
748 // we currently support.
749 unsigned NumParts =
750 TLI->getNumRegistersForCallingConv(Context&: Ctx, CC: CallConv, VT: CurVT);
751
752 if (NumParts == 1) {
753 // Try to use the register type if we couldn't assign the VT.
754 if (Assigner.assignArg(ValNo: i, OrigVT: CurVT, ValVT: NewVT, LocVT: NewVT, LocInfo: CCValAssign::Full, Info: Args[i],
755 Flags: Args[i].Flags[0], State&: CCInfo))
756 return false;
757 continue;
758 }
759
760 // For incoming arguments (physregs to vregs), we could have values in
761 // physregs (or memlocs) which we want to extract and copy to vregs.
762 // During this, we might have to deal with the LLT being split across
763 // multiple regs, so we have to record this information for later.
764 //
765 // If we have outgoing args, then we have the opposite case. We have a
766 // vreg with an LLT which we want to assign to a physical location, and
767 // we might have to record that the value has to be split later.
768
769 // We're handling an incoming arg which is split over multiple regs.
770 // E.g. passing an s128 on AArch64.
771 ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
772 Args[i].Flags.clear();
773
774 for (unsigned Part = 0; Part < NumParts; ++Part) {
775 ISD::ArgFlagsTy Flags = OrigFlags;
776 if (Part == 0) {
777 Flags.setSplit();
778 } else {
779 Flags.setOrigAlign(Align(1));
780 if (Part == NumParts - 1)
781 Flags.setSplitEnd();
782 }
783
784 Args[i].Flags.push_back(Elt: Flags);
785 if (Assigner.assignArg(ValNo: i, OrigVT: CurVT, ValVT: NewVT, LocVT: NewVT, LocInfo: CCValAssign::Full, Info: Args[i],
786 Flags: Args[i].Flags[Part], State&: CCInfo)) {
787 // Still couldn't assign this smaller part type for some reason.
788 return false;
789 }
790 }
791 }
792
793 return true;
794}
795
796bool CallLowering::handleAssignments(ValueHandler &Handler,
797 SmallVectorImpl<ArgInfo> &Args,
798 CCState &CCInfo,
799 SmallVectorImpl<CCValAssign> &ArgLocs,
800 MachineIRBuilder &MIRBuilder,
801 ArrayRef<Register> ThisReturnRegs) const {
802 MachineFunction &MF = MIRBuilder.getMF();
803 MachineRegisterInfo &MRI = MF.getRegInfo();
804 const Function &F = MF.getFunction();
805 const DataLayout &DL = F.getDataLayout();
806
807 const unsigned NumArgs = Args.size();
808
809 // Stores thunks for outgoing register assignments. This is used so we delay
810 // generating register copies until mem loc assignments are done. We do this
811 // so that if the target is using the delayed stack protector feature, we can
812 // find the split point of the block accurately. E.g. if we have:
813 // G_STORE %val, %memloc
814 // $x0 = COPY %foo
815 // $x1 = COPY %bar
816 // CALL func
817 // ... then the split point for the block will correctly be at, and including,
818 // the copy to $x0. If instead the G_STORE instruction immediately precedes
819 // the CALL, then we'd prematurely choose the CALL as the split point, thus
820 // generating a split block with a CALL that uses undefined physregs.
821 SmallVector<std::function<void()>> DelayedOutgoingRegAssignments;
822
823 for (unsigned i = 0, j = 0; i != NumArgs; ++i, ++j) {
824 assert(j < ArgLocs.size() && "Skipped too many arg locs");
825 CCValAssign &VA = ArgLocs[j];
826 assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
827
828 if (VA.needsCustom()) {
829 std::function<void()> Thunk;
830 unsigned NumArgRegs = Handler.assignCustomValue(
831 Arg&: Args[i], VAs: ArrayRef(ArgLocs).slice(N: j), Thunk: &Thunk);
832 if (Thunk)
833 DelayedOutgoingRegAssignments.emplace_back(Args&: Thunk);
834 if (!NumArgRegs)
835 return false;
836 j += (NumArgRegs - 1);
837 continue;
838 }
839
840 auto AllocaAddressSpace = MF.getDataLayout().getAllocaAddrSpace();
841
842 const MVT ValVT = VA.getValVT();
843 const MVT LocVT = VA.getLocVT();
844
845 const LLT LocTy = getLLTForMVT(Ty: LocVT);
846 const LLT ValTy = getLLTForMVT(Ty: ValVT);
847 const LLT NewLLT = Handler.isIncomingArgumentHandler() ? LocTy : ValTy;
848 const EVT OrigVT = TLI->getValueType(DL, Ty: Args[i].Ty);
849 // Use the EVT here to strip pointerness.
850 const LLT OrigTy = getLLTForType(Ty&: *OrigVT.getTypeForEVT(Context&: F.getContext()), DL);
851 const LLT PointerTy = LLT::pointer(
852 AddressSpace: AllocaAddressSpace, SizeInBits: DL.getPointerSizeInBits(AS: AllocaAddressSpace));
853
854 // Expected to be multiple regs for a single incoming arg.
855 // There should be Regs.size() ArgLocs per argument.
856 // This should be the same as getNumRegistersForCallingConv
857 const unsigned NumParts = Args[i].Flags.size();
858
859 // Now split the registers into the assigned types.
860 Args[i].OrigRegs.assign(in_start: Args[i].Regs.begin(), in_end: Args[i].Regs.end());
861
862 if (NumParts != 1 || NewLLT != OrigTy) {
863 // If we can't directly assign the register, we need one or more
864 // intermediate values.
865 Args[i].Regs.resize(N: NumParts);
866
867 // When we have indirect parameter passing we are receiving a pointer,
868 // that points to the actual value, so we need one "temporary" pointer.
869 if (VA.getLocInfo() == CCValAssign::Indirect) {
870 if (Handler.isIncomingArgumentHandler())
871 Args[i].Regs[0] = MRI.createGenericVirtualRegister(Ty: PointerTy);
872 } else {
873 // For each split register, create and assign a vreg that will store
874 // the incoming component of the larger value. These will later be
875 // merged to form the final vreg.
876 for (unsigned Part = 0; Part < NumParts; ++Part)
877 Args[i].Regs[Part] = MRI.createGenericVirtualRegister(Ty: NewLLT);
878 }
879 }
880
881 assert((j + (NumParts - 1)) < ArgLocs.size() &&
882 "Too many regs for number of args");
883
884 // Coerce into outgoing value types before register assignment.
885 if (!Handler.isIncomingArgumentHandler() && OrigTy != ValTy &&
886 VA.getLocInfo() != CCValAssign::Indirect) {
887 assert(Args[i].OrigRegs.size() == 1);
888 buildCopyToRegs(B&: MIRBuilder, DstRegs: Args[i].Regs, SrcReg: Args[i].OrigRegs[0], SrcTy: OrigTy,
889 PartTy: ValTy, ExtendOp: extendOpFromFlags(Flags: Args[i].Flags[0]));
890 }
891
892 bool IndirectParameterPassingHandled = false;
893 bool BigEndianPartOrdering = TLI->hasBigEndianPartOrdering(VT: OrigVT, DL);
894 for (unsigned Part = 0; Part < NumParts; ++Part) {
895 assert((VA.getLocInfo() != CCValAssign::Indirect || Part == 0) &&
896 "Only the first parameter should be processed when "
897 "handling indirect passing!");
898 Register ArgReg = Args[i].Regs[Part];
899 // There should be Regs.size() ArgLocs per argument.
900 unsigned Idx = BigEndianPartOrdering ? NumParts - 1 - Part : Part;
901 CCValAssign &VA = ArgLocs[j + Idx];
902 const ISD::ArgFlagsTy Flags = Args[i].Flags[Part];
903
904 // We found an indirect parameter passing, and we have an
905 // OutgoingValueHandler as our handler (so we are at the call site or the
906 // return value). In this case, start the construction of the following
907 // GMIR, that is responsible for the preparation of indirect parameter
908 // passing:
909 //
910 // %1(indirectly passed type) = The value to pass
911 // %3(pointer) = G_FRAME_INDEX %stack.0
912 // G_STORE %1, %3 :: (store (s128), align 8)
913 //
914 // After this GMIR, the remaining part of the loop body will decide how
915 // to get the value to the caller and we break out of the loop.
916 if (VA.getLocInfo() == CCValAssign::Indirect &&
917 !Handler.isIncomingArgumentHandler()) {
918 Align AlignmentForStored = DL.getPrefTypeAlign(Ty: Args[i].Ty);
919 MachineFrameInfo &MFI = MF.getFrameInfo();
920 // Get some space on the stack for the value, so later we can pass it
921 // as a reference.
922 int FrameIdx = MFI.CreateStackObject(Size: OrigTy.getScalarSizeInBits(),
923 Alignment: AlignmentForStored, isSpillSlot: false);
924 Register PointerToStackReg =
925 MIRBuilder.buildFrameIndex(Res: PointerTy, Idx: FrameIdx).getReg(Idx: 0);
926 MachinePointerInfo StackPointerMPO =
927 MachinePointerInfo::getFixedStack(MF, FI: FrameIdx);
928 // Store the value in the previously created stack space.
929 MIRBuilder.buildStore(Val: Args[i].OrigRegs[Part], Addr: PointerToStackReg,
930 PtrInfo: StackPointerMPO,
931 Alignment: inferAlignFromPtrInfo(MF, MPO: StackPointerMPO));
932
933 ArgReg = PointerToStackReg;
934 IndirectParameterPassingHandled = true;
935 }
936
937 if (VA.isMemLoc() && !Flags.isByVal()) {
938 // Individual pieces may have been spilled to the stack and others
939 // passed in registers.
940
941 // TODO: The memory size may be larger than the value we need to
942 // store. We may need to adjust the offset for big endian targets.
943 LLT MemTy = Handler.getStackValueStoreType(DL, VA, Flags);
944
945 MachinePointerInfo MPO;
946 Register StackAddr =
947 Handler.getStackAddress(MemSize: VA.getLocInfo() == CCValAssign::Indirect
948 ? PointerTy.getSizeInBytes()
949 : MemTy.getSizeInBytes(),
950 Offset: VA.getLocMemOffset(), MPO, Flags);
951
952 // Finish the handling of indirect passing from the passers
953 // (OutgoingParameterHandler) side.
954 // This branch is needed, so the pointer to the value is loaded onto the
955 // stack.
956 if (VA.getLocInfo() == CCValAssign::Indirect)
957 Handler.assignValueToAddress(ValVReg: ArgReg, Addr: StackAddr, MemTy: PointerTy, MPO, VA);
958 else
959 Handler.assignValueToAddress(Arg: Args[i], ValRegIndex: Part, Addr: StackAddr, MemTy, MPO,
960 VA);
961 } else if (VA.isMemLoc() && Flags.isByVal()) {
962 assert(Args[i].Regs.size() == 1 && "didn't expect split byval pointer");
963
964 if (Handler.isIncomingArgumentHandler()) {
965 // We just need to copy the frame index value to the pointer.
966 MachinePointerInfo MPO;
967 Register StackAddr = Handler.getStackAddress(
968 MemSize: Flags.getByValSize(), Offset: VA.getLocMemOffset(), MPO, Flags);
969 MIRBuilder.buildCopy(Res: Args[i].Regs[0], Op: StackAddr);
970 } else {
971 // For outgoing byval arguments, insert the implicit copy byval
972 // implies, such that writes in the callee do not modify the caller's
973 // value.
974 uint64_t MemSize = Flags.getByValSize();
975 int64_t Offset = VA.getLocMemOffset();
976
977 MachinePointerInfo DstMPO;
978 Register StackAddr =
979 Handler.getStackAddress(MemSize, Offset, MPO&: DstMPO, Flags);
980
981 MachinePointerInfo SrcMPO(Args[i].OrigValue);
982 if (!Args[i].OrigValue) {
983 // We still need to accurately track the stack address space if we
984 // don't know the underlying value.
985 const LLT PtrTy = MRI.getType(Reg: StackAddr);
986 SrcMPO = MachinePointerInfo(PtrTy.getAddressSpace());
987 }
988
989 Align DstAlign = std::max(a: Flags.getNonZeroByValAlign(),
990 b: inferAlignFromPtrInfo(MF, MPO: DstMPO));
991
992 Align SrcAlign = std::max(a: Flags.getNonZeroByValAlign(),
993 b: inferAlignFromPtrInfo(MF, MPO: SrcMPO));
994
995 Handler.copyArgumentMemory(Arg: Args[i], DstPtr: StackAddr, SrcPtr: Args[i].Regs[0],
996 DstPtrInfo: DstMPO, DstAlign, SrcPtrInfo: SrcMPO, SrcAlign,
997 MemSize, VA);
998 }
999 } else if (i == 0 && !ThisReturnRegs.empty() &&
1000 Handler.isIncomingArgumentHandler() &&
1001 isTypeIsValidForThisReturn(Ty: ValVT)) {
1002 Handler.assignValueToReg(ValVReg: ArgReg, PhysReg: ThisReturnRegs[Part], VA, Flags);
1003 } else if (Handler.isIncomingArgumentHandler()) {
1004 Handler.assignValueToReg(ValVReg: ArgReg, PhysReg: VA.getLocReg(), VA, Flags);
1005 } else {
1006 DelayedOutgoingRegAssignments.emplace_back(Args: [=, &Handler]() {
1007 Handler.assignValueToReg(ValVReg: ArgReg, PhysReg: VA.getLocReg(), VA, Flags);
1008 });
1009 }
1010
1011 // Finish the handling of indirect parameter passing when receiving
1012 // the value (we are in the called function or the caller when receiving
1013 // the return value).
1014 if (VA.getLocInfo() == CCValAssign::Indirect &&
1015 Handler.isIncomingArgumentHandler()) {
1016 Align Alignment = DL.getABITypeAlign(Ty: Args[i].Ty);
1017 MachinePointerInfo MPO = MachinePointerInfo::getUnknownStack(MF);
1018
1019 // Since we are doing indirect parameter passing, we know that the value
1020 // in the temporary register is not the value passed to the function,
1021 // but rather a pointer to that value. Let's load that value into the
1022 // virtual register where the parameter should go.
1023 MIRBuilder.buildLoad(Res: Args[i].OrigRegs[0], Addr: Args[i].Regs[0], PtrInfo: MPO,
1024 Alignment);
1025
1026 IndirectParameterPassingHandled = true;
1027 }
1028
1029 if (IndirectParameterPassingHandled)
1030 break;
1031 }
1032
1033 // Now that all pieces have been assigned, re-pack the register typed values
1034 // into the original value typed registers. This is only necessary, when
1035 // the value was passed in multiple registers, not indirectly.
1036 if (Handler.isIncomingArgumentHandler() && OrigVT != LocVT &&
1037 !IndirectParameterPassingHandled) {
1038 // Merge the split registers into the expected larger result vregs of
1039 // the original call.
1040 buildCopyFromRegs(B&: MIRBuilder, OrigRegs: Args[i].OrigRegs, Regs: Args[i].Regs, LLTy: OrigTy,
1041 PartLLT: LocTy, Flags: Args[i].Flags[0]);
1042 }
1043
1044 j += NumParts - 1;
1045 }
1046 for (auto &Fn : DelayedOutgoingRegAssignments)
1047 Fn();
1048
1049 return true;
1050}
1051
1052void CallLowering::insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy,
1053 ArrayRef<Register> VRegs, Register DemoteReg,
1054 int FI) const {
1055 MachineFunction &MF = MIRBuilder.getMF();
1056 MachineRegisterInfo &MRI = MF.getRegInfo();
1057 const DataLayout &DL = MF.getDataLayout();
1058
1059 SmallVector<EVT, 4> SplitVTs;
1060 SmallVector<uint64_t, 4> Offsets;
1061 ComputeValueVTs(TLI: *TLI, DL, Ty: RetTy, ValueVTs&: SplitVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
1062
1063 assert(VRegs.size() == SplitVTs.size());
1064
1065 unsigned NumValues = SplitVTs.size();
1066 Align BaseAlign = DL.getPrefTypeAlign(Ty: RetTy);
1067 Type *RetPtrTy =
1068 PointerType::get(C&: RetTy->getContext(), AddressSpace: DL.getAllocaAddrSpace());
1069 LLT OffsetLLTy = getLLTForType(Ty&: *DL.getIndexType(PtrTy: RetPtrTy), DL);
1070
1071 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
1072
1073 for (unsigned I = 0; I < NumValues; ++I) {
1074 Register Addr;
1075 MIRBuilder.materializeObjectPtrOffset(Res&: Addr, Op0: DemoteReg, ValueTy: OffsetLLTy,
1076 Value: Offsets[I]);
1077 auto *MMO = MF.getMachineMemOperand(PtrInfo, F: MachineMemOperand::MOLoad,
1078 MemTy: MRI.getType(Reg: VRegs[I]),
1079 BaseAlignment: commonAlignment(A: BaseAlign, Offset: Offsets[I]));
1080 MIRBuilder.buildLoad(Res: VRegs[I], Addr, MMO&: *MMO);
1081 }
1082}
1083
1084void CallLowering::insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy,
1085 ArrayRef<Register> VRegs,
1086 Register DemoteReg) const {
1087 MachineFunction &MF = MIRBuilder.getMF();
1088 MachineRegisterInfo &MRI = MF.getRegInfo();
1089 const DataLayout &DL = MF.getDataLayout();
1090
1091 SmallVector<EVT, 4> SplitVTs;
1092 SmallVector<uint64_t, 4> Offsets;
1093 ComputeValueVTs(TLI: *TLI, DL, Ty: RetTy, ValueVTs&: SplitVTs, /*MemVTs=*/nullptr, FixedOffsets: &Offsets, StartingOffset: 0);
1094
1095 assert(VRegs.size() == SplitVTs.size());
1096
1097 unsigned NumValues = SplitVTs.size();
1098 Align BaseAlign = DL.getPrefTypeAlign(Ty: RetTy);
1099 unsigned AS = DL.getAllocaAddrSpace();
1100 LLT OffsetLLTy = getLLTForType(Ty&: *DL.getIndexType(C&: RetTy->getContext(), AddressSpace: AS), DL);
1101
1102 MachinePointerInfo PtrInfo(AS);
1103
1104 for (unsigned I = 0; I < NumValues; ++I) {
1105 Register Addr;
1106 MIRBuilder.materializeObjectPtrOffset(Res&: Addr, Op0: DemoteReg, ValueTy: OffsetLLTy,
1107 Value: Offsets[I]);
1108 auto *MMO = MF.getMachineMemOperand(PtrInfo, F: MachineMemOperand::MOStore,
1109 MemTy: MRI.getType(Reg: VRegs[I]),
1110 BaseAlignment: commonAlignment(A: BaseAlign, Offset: Offsets[I]));
1111 MIRBuilder.buildStore(Val: VRegs[I], Addr, MMO&: *MMO);
1112 }
1113}
1114
1115void CallLowering::insertSRetIncomingArgument(
1116 const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg,
1117 MachineRegisterInfo &MRI, const DataLayout &DL) const {
1118 unsigned AS = DL.getAllocaAddrSpace();
1119 DemoteReg = MRI.createGenericVirtualRegister(
1120 Ty: LLT::pointer(AddressSpace: AS, SizeInBits: DL.getPointerSizeInBits(AS)));
1121
1122 Type *PtrTy = PointerType::get(C&: F.getContext(), AddressSpace: AS);
1123
1124 SmallVector<EVT, 1> ValueVTs;
1125 ComputeValueVTs(TLI: *TLI, DL, Ty: PtrTy, ValueVTs);
1126
1127 // NOTE: Assume that a pointer won't get split into more than one VT.
1128 assert(ValueVTs.size() == 1);
1129
1130 ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(Context&: PtrTy->getContext()),
1131 ArgInfo::NoArgIndex);
1132 setArgFlags(Arg&: DemoteArg, OpIdx: AttributeList::ReturnIndex, DL, FuncInfo: F);
1133 DemoteArg.Flags[0].setSRet();
1134 SplitArgs.insert(I: SplitArgs.begin(), Elt: DemoteArg);
1135}
1136
1137void CallLowering::insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder,
1138 const CallBase &CB,
1139 CallLoweringInfo &Info) const {
1140 const DataLayout &DL = MIRBuilder.getDataLayout();
1141 Type *RetTy = CB.getType();
1142 unsigned AS = DL.getAllocaAddrSpace();
1143 LLT FramePtrTy = LLT::pointer(AddressSpace: AS, SizeInBits: DL.getPointerSizeInBits(AS));
1144
1145 int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject(
1146 Size: DL.getTypeAllocSize(Ty: RetTy), Alignment: DL.getPrefTypeAlign(Ty: RetTy), isSpillSlot: false);
1147
1148 Register DemoteReg = MIRBuilder.buildFrameIndex(Res: FramePtrTy, Idx: FI).getReg(Idx: 0);
1149 ArgInfo DemoteArg(DemoteReg, PointerType::get(C&: RetTy->getContext(), AddressSpace: AS),
1150 ArgInfo::NoArgIndex);
1151 setArgFlags(Arg&: DemoteArg, OpIdx: AttributeList::ReturnIndex, DL, FuncInfo: CB);
1152 DemoteArg.Flags[0].setSRet();
1153
1154 Info.OrigArgs.insert(I: Info.OrigArgs.begin(), Elt: DemoteArg);
1155 Info.DemoteStackIndex = FI;
1156 Info.DemoteRegister = DemoteReg;
1157}
1158
1159bool CallLowering::checkReturn(CCState &CCInfo,
1160 SmallVectorImpl<BaseArgInfo> &Outs,
1161 CCAssignFn *Fn) const {
1162 for (unsigned I = 0, E = Outs.size(); I < E; ++I) {
1163 MVT VT = MVT::getVT(Ty: Outs[I].Ty);
1164 if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], Outs[I].Ty, CCInfo))
1165 return false;
1166 }
1167 return true;
1168}
1169
1170void CallLowering::getReturnInfo(CallingConv::ID CallConv, Type *RetTy,
1171 AttributeList Attrs,
1172 SmallVectorImpl<BaseArgInfo> &Outs,
1173 const DataLayout &DL) const {
1174 LLVMContext &Context = RetTy->getContext();
1175 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1176
1177 SmallVector<EVT, 4> SplitVTs;
1178 ComputeValueVTs(TLI: *TLI, DL, Ty: RetTy, ValueVTs&: SplitVTs);
1179 addArgFlagsFromAttributes(Flags, Attrs, OpIdx: AttributeList::ReturnIndex);
1180
1181 for (EVT VT : SplitVTs) {
1182 unsigned NumParts =
1183 TLI->getNumRegistersForCallingConv(Context, CC: CallConv, VT);
1184 MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CC: CallConv, VT);
1185 Type *PartTy = EVT(RegVT).getTypeForEVT(Context);
1186
1187 for (unsigned I = 0; I < NumParts; ++I) {
1188 Outs.emplace_back(Args&: PartTy, Args&: Flags);
1189 }
1190 }
1191}
1192
1193bool CallLowering::checkReturnTypeForCallConv(MachineFunction &MF) const {
1194 const auto &F = MF.getFunction();
1195 Type *ReturnType = F.getReturnType();
1196 CallingConv::ID CallConv = F.getCallingConv();
1197
1198 SmallVector<BaseArgInfo, 4> SplitArgs;
1199 getReturnInfo(CallConv, RetTy: ReturnType, Attrs: F.getAttributes(), Outs&: SplitArgs,
1200 DL: MF.getDataLayout());
1201 return canLowerReturn(MF, CallConv, Outs&: SplitArgs, IsVarArg: F.isVarArg());
1202}
1203
1204bool CallLowering::parametersInCSRMatch(
1205 const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask,
1206 const SmallVectorImpl<CCValAssign> &OutLocs,
1207 const SmallVectorImpl<ArgInfo> &OutArgs) const {
1208 for (unsigned i = 0; i < OutLocs.size(); ++i) {
1209 const auto &ArgLoc = OutLocs[i];
1210 // If it's not a register, it's fine.
1211 if (!ArgLoc.isRegLoc())
1212 continue;
1213
1214 MCRegister PhysReg = ArgLoc.getLocReg();
1215
1216 // Only look at callee-saved registers.
1217 if (MachineOperand::clobbersPhysReg(RegMask: CallerPreservedMask, PhysReg))
1218 continue;
1219
1220 LLVM_DEBUG(
1221 dbgs()
1222 << "... Call has an argument passed in a callee-saved register.\n");
1223
1224 // Check if it was copied from.
1225 const ArgInfo &OutInfo = OutArgs[i];
1226
1227 if (OutInfo.Regs.size() > 1) {
1228 LLVM_DEBUG(
1229 dbgs() << "... Cannot handle arguments in multiple registers.\n");
1230 return false;
1231 }
1232
1233 // Check if we copy the register, walking through copies from virtual
1234 // registers. Note that getDefIgnoringCopies does not ignore copies from
1235 // physical registers.
1236 MachineInstr *RegDef = getDefIgnoringCopies(Reg: OutInfo.Regs[0], MRI);
1237 if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) {
1238 LLVM_DEBUG(
1239 dbgs()
1240 << "... Parameter was not copied into a VReg, cannot tail call.\n");
1241 return false;
1242 }
1243
1244 // Got a copy. Verify that it's the same as the register we want.
1245 Register CopyRHS = RegDef->getOperand(i: 1).getReg();
1246 if (CopyRHS != PhysReg) {
1247 LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into "
1248 "VReg, cannot tail call.\n");
1249 return false;
1250 }
1251 }
1252
1253 return true;
1254}
1255
1256bool CallLowering::resultsCompatible(CallLoweringInfo &Info,
1257 MachineFunction &MF,
1258 SmallVectorImpl<ArgInfo> &InArgs,
1259 ValueAssigner &CalleeAssigner,
1260 ValueAssigner &CallerAssigner) const {
1261 const Function &F = MF.getFunction();
1262 CallingConv::ID CalleeCC = Info.CallConv;
1263 CallingConv::ID CallerCC = F.getCallingConv();
1264
1265 if (CallerCC == CalleeCC)
1266 return true;
1267
1268 SmallVector<CCValAssign, 16> ArgLocs1;
1269 CCState CCInfo1(CalleeCC, Info.IsVarArg, MF, ArgLocs1, F.getContext());
1270 if (!determineAssignments(Assigner&: CalleeAssigner, Args&: InArgs, CCInfo&: CCInfo1))
1271 return false;
1272
1273 SmallVector<CCValAssign, 16> ArgLocs2;
1274 CCState CCInfo2(CallerCC, F.isVarArg(), MF, ArgLocs2, F.getContext());
1275 if (!determineAssignments(Assigner&: CallerAssigner, Args&: InArgs, CCInfo&: CCInfo2))
1276 return false;
1277
1278 // We need the argument locations to match up exactly. If there's more in
1279 // one than the other, then we are done.
1280 if (ArgLocs1.size() != ArgLocs2.size())
1281 return false;
1282
1283 // Make sure that each location is passed in exactly the same way.
1284 for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) {
1285 const CCValAssign &Loc1 = ArgLocs1[i];
1286 const CCValAssign &Loc2 = ArgLocs2[i];
1287
1288 // We need both of them to be the same. So if one is a register and one
1289 // isn't, we're done.
1290 if (Loc1.isRegLoc() != Loc2.isRegLoc())
1291 return false;
1292
1293 if (Loc1.isRegLoc()) {
1294 // If they don't have the same register location, we're done.
1295 if (Loc1.getLocReg() != Loc2.getLocReg())
1296 return false;
1297
1298 // They matched, so we can move to the next ArgLoc.
1299 continue;
1300 }
1301
1302 // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match.
1303 if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset())
1304 return false;
1305 }
1306
1307 return true;
1308}
1309
1310LLT CallLowering::ValueHandler::getStackValueStoreType(
1311 const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const {
1312 const MVT ValVT = VA.getValVT();
1313 if (ValVT != MVT::iPTR) {
1314 LLT ValTy(ValVT);
1315
1316 // We lost the pointeriness going through CCValAssign, so try to restore it
1317 // based on the flags.
1318 if (Flags.isPointer()) {
1319 LLT PtrTy = LLT::pointer(AddressSpace: Flags.getPointerAddrSpace(),
1320 SizeInBits: ValTy.getScalarSizeInBits());
1321 if (ValVT.isVector() && ValVT.getVectorNumElements() != 1)
1322 return LLT::vector(EC: ValTy.getElementCount(), ScalarTy: PtrTy);
1323 return PtrTy;
1324 }
1325
1326 return ValTy;
1327 }
1328
1329 unsigned AddrSpace = Flags.getPointerAddrSpace();
1330 return LLT::pointer(AddressSpace: AddrSpace, SizeInBits: DL.getPointerSize(AS: AddrSpace));
1331}
1332
1333void CallLowering::ValueHandler::copyArgumentMemory(
1334 const ArgInfo &Arg, Register DstPtr, Register SrcPtr,
1335 const MachinePointerInfo &DstPtrInfo, Align DstAlign,
1336 const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize,
1337 CCValAssign &VA) const {
1338 MachineFunction &MF = MIRBuilder.getMF();
1339 MachineMemOperand *SrcMMO = MF.getMachineMemOperand(
1340 PtrInfo: SrcPtrInfo,
1341 F: MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable, Size: MemSize,
1342 BaseAlignment: SrcAlign);
1343
1344 MachineMemOperand *DstMMO = MF.getMachineMemOperand(
1345 PtrInfo: DstPtrInfo,
1346 F: MachineMemOperand::MOStore | MachineMemOperand::MODereferenceable,
1347 Size: MemSize, BaseAlignment: DstAlign);
1348
1349 const LLT PtrTy = MRI.getType(Reg: DstPtr);
1350 const LLT SizeTy = LLT::integer(SizeInBits: PtrTy.getSizeInBits());
1351
1352 auto SizeConst = MIRBuilder.buildConstant(Res: SizeTy, Val: MemSize);
1353 MIRBuilder.buildMemCpy(DstPtr, SrcPtr, Size: SizeConst, DstMMO&: *DstMMO, SrcMMO&: *SrcMMO);
1354}
1355
1356Register CallLowering::ValueHandler::extendRegister(Register ValReg,
1357 const CCValAssign &VA,
1358 unsigned MaxSizeBits) {
1359 LLT LocTy{VA.getLocVT()};
1360 LLT ValTy{VA.getValVT()};
1361
1362 if (LocTy.getSizeInBits() == ValTy.getSizeInBits())
1363 return ValReg;
1364
1365 if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) {
1366 if (MaxSizeBits <= ValTy.getSizeInBits())
1367 return ValReg;
1368 LocTy = LLT::scalar(SizeInBits: MaxSizeBits);
1369 }
1370
1371 const LLT ValRegTy = MRI.getType(Reg: ValReg);
1372 if (ValRegTy.isPointer()) {
1373 // The x32 ABI wants to zero extend 32-bit pointers to 64-bit registers, so
1374 // we have to cast to do the extension.
1375 LLT IntPtrTy = LLT::scalar(SizeInBits: ValRegTy.getSizeInBits());
1376 ValReg = MIRBuilder.buildPtrToInt(Dst: IntPtrTy, Src: ValReg).getReg(Idx: 0);
1377 }
1378
1379 switch (VA.getLocInfo()) {
1380 default:
1381 break;
1382 case CCValAssign::Full:
1383 case CCValAssign::BCvt:
1384 case CCValAssign::Indirect:
1385 // FIXME: bitconverting between vector types may or may not be a
1386 // nop in big-endian situations.
1387 return ValReg;
1388 case CCValAssign::AExt: {
1389 auto MIB = MIRBuilder.buildAnyExt(Res: LocTy, Op: ValReg);
1390 return MIB.getReg(Idx: 0);
1391 }
1392 case CCValAssign::SExt: {
1393 Register NewReg = MRI.createGenericVirtualRegister(Ty: LocTy);
1394 MIRBuilder.buildSExt(Res: NewReg, Op: ValReg);
1395 return NewReg;
1396 }
1397 case CCValAssign::ZExt: {
1398 Register NewReg = MRI.createGenericVirtualRegister(Ty: LocTy);
1399 MIRBuilder.buildZExt(Res: NewReg, Op: ValReg);
1400 return NewReg;
1401 }
1402 }
1403 llvm_unreachable("unable to extend register");
1404}
1405
1406void CallLowering::ValueAssigner::anchor() {}
1407
1408Register CallLowering::IncomingValueHandler::buildExtensionHint(
1409 const CCValAssign &VA, Register SrcReg, LLT NarrowTy) {
1410 switch (VA.getLocInfo()) {
1411 case CCValAssign::LocInfo::ZExt: {
1412 return MIRBuilder
1413 .buildAssertZExt(Res: MRI.cloneVirtualRegister(VReg: SrcReg), Op: SrcReg,
1414 Size: NarrowTy.getScalarSizeInBits())
1415 .getReg(Idx: 0);
1416 }
1417 case CCValAssign::LocInfo::SExt: {
1418 return MIRBuilder
1419 .buildAssertSExt(Res: MRI.cloneVirtualRegister(VReg: SrcReg), Op: SrcReg,
1420 Size: NarrowTy.getScalarSizeInBits())
1421 .getReg(Idx: 0);
1422 break;
1423 }
1424 default:
1425 return SrcReg;
1426 }
1427}
1428
1429/// Check if we can use a basic COPY instruction between the two types.
1430///
1431/// We're currently building on top of the infrastructure using MVT, which loses
1432/// pointer information in the CCValAssign. We accept copies from physical
1433/// registers that have been reported as integers if it's to an equivalent sized
1434/// pointer LLT.
1435static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy) {
1436 if (SrcTy == DstTy)
1437 return true;
1438
1439 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1440 return false;
1441
1442 SrcTy = SrcTy.getScalarType();
1443 DstTy = DstTy.getScalarType();
1444
1445 return (SrcTy.isPointer() && DstTy.isScalar()) ||
1446 (DstTy.isPointer() && SrcTy.isScalar());
1447}
1448
1449void CallLowering::IncomingValueHandler::assignValueToReg(
1450 Register ValVReg, Register PhysReg, const CCValAssign &VA,
1451 ISD::ArgFlagsTy Flags) {
1452 const MVT LocVT = VA.getLocVT();
1453 const LLT LocTy = getLLTForMVT(Ty: LocVT);
1454 const LLT RegTy = MRI.getType(Reg: ValVReg);
1455
1456 if (isCopyCompatibleType(SrcTy: RegTy, DstTy: LocTy)) {
1457 MIRBuilder.buildCopy(Res: ValVReg, Op: PhysReg);
1458 return;
1459 }
1460
1461 auto Copy = MIRBuilder.buildCopy(Res: LocTy, Op: PhysReg);
1462 auto Hint = buildExtensionHint(VA, SrcReg: Copy.getReg(Idx: 0), NarrowTy: RegTy);
1463 MIRBuilder.buildTrunc(Res: ValVReg, Op: Hint);
1464}
1465