LLVM 19.0.0git
AArch64CallLowering.cpp
Go to the documentation of this file.
1//===--- AArch64CallLowering.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 "AArch64CallLowering.h"
16#include "AArch64ISelLowering.h"
18#include "AArch64RegisterInfo.h"
19#include "AArch64Subtarget.h"
20#include "llvm/ADT/ArrayRef.h"
40#include "llvm/IR/Argument.h"
41#include "llvm/IR/Attributes.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/Type.h"
44#include "llvm/IR/Value.h"
45#include <algorithm>
46#include <cassert>
47#include <cstdint>
48#include <iterator>
49
50#define DEBUG_TYPE "aarch64-call-lowering"
51
52using namespace llvm;
53
55 : CallLowering(&TLI) {}
56
57static void applyStackPassedSmallTypeDAGHack(EVT OrigVT, MVT &ValVT,
58 MVT &LocVT) {
59 // If ValVT is i1/i8/i16, we should set LocVT to i8/i8/i16. This is a legacy
60 // hack because the DAG calls the assignment function with pre-legalized
61 // register typed values, not the raw type.
62 //
63 // This hack is not applied to return values which are not passed on the
64 // stack.
65 if (OrigVT == MVT::i1 || OrigVT == MVT::i8)
66 ValVT = LocVT = MVT::i8;
67 else if (OrigVT == MVT::i16)
68 ValVT = LocVT = MVT::i16;
69}
70
71// Account for i1/i8/i16 stack passed value hack
73 const MVT ValVT = VA.getValVT();
74 return (ValVT == MVT::i8 || ValVT == MVT::i16) ? LLT(ValVT)
75 : LLT(VA.getLocVT());
76}
77
78namespace {
79
80struct AArch64IncomingValueAssigner
82 AArch64IncomingValueAssigner(CCAssignFn *AssignFn_,
83 CCAssignFn *AssignFnVarArg_)
84 : IncomingValueAssigner(AssignFn_, AssignFnVarArg_) {}
85
86 bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
89 CCState &State) override {
90 applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
91 return IncomingValueAssigner::assignArg(ValNo, OrigVT, ValVT, LocVT,
92 LocInfo, Info, Flags, State);
93 }
94};
95
96struct AArch64OutgoingValueAssigner
98 const AArch64Subtarget &Subtarget;
99
100 /// Track if this is used for a return instead of function argument
101 /// passing. We apply a hack to i1/i8/i16 stack passed values, but do not use
102 /// stack passed returns for them and cannot apply the type adjustment.
103 bool IsReturn;
104
105 AArch64OutgoingValueAssigner(CCAssignFn *AssignFn_,
106 CCAssignFn *AssignFnVarArg_,
107 const AArch64Subtarget &Subtarget_,
108 bool IsReturn)
109 : OutgoingValueAssigner(AssignFn_, AssignFnVarArg_),
110 Subtarget(Subtarget_), IsReturn(IsReturn) {}
111
112 bool assignArg(unsigned ValNo, EVT OrigVT, MVT ValVT, MVT LocVT,
113 CCValAssign::LocInfo LocInfo,
115 CCState &State) override {
116 bool IsCalleeWin = Subtarget.isCallingConvWin64(State.getCallingConv());
117 bool UseVarArgsCCForFixed = IsCalleeWin && State.isVarArg();
118
119 bool Res;
120 if (Info.IsFixed && !UseVarArgsCCForFixed) {
121 if (!IsReturn)
122 applyStackPassedSmallTypeDAGHack(OrigVT, ValVT, LocVT);
123 Res = AssignFn(ValNo, ValVT, LocVT, LocInfo, Flags, State);
124 } else
125 Res = AssignFnVarArg(ValNo, ValVT, LocVT, LocInfo, Flags, State);
126
127 StackSize = State.getStackSize();
128 return Res;
129 }
130};
131
132struct IncomingArgHandler : public CallLowering::IncomingValueHandler {
133 IncomingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI)
134 : IncomingValueHandler(MIRBuilder, MRI) {}
135
136 Register getStackAddress(uint64_t Size, int64_t Offset,
138 ISD::ArgFlagsTy Flags) override {
139 auto &MFI = MIRBuilder.getMF().getFrameInfo();
140
141 // Byval is assumed to be writable memory, but other stack passed arguments
142 // are not.
143 const bool IsImmutable = !Flags.isByVal();
144
145 int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
146 MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
147 auto AddrReg = MIRBuilder.buildFrameIndex(LLT::pointer(0, 64), FI);
148 return AddrReg.getReg(0);
149 }
150
151 LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
152 ISD::ArgFlagsTy Flags) const override {
153 // For pointers, we just need to fixup the integer types reported in the
154 // CCValAssign.
155 if (Flags.isPointer())
158 }
159
160 void assignValueToReg(Register ValVReg, Register PhysReg,
161 const CCValAssign &VA) override {
162 markPhysRegUsed(PhysReg);
163 IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
164 }
165
166 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
167 const MachinePointerInfo &MPO,
168 const CCValAssign &VA) override {
169 MachineFunction &MF = MIRBuilder.getMF();
170
171 LLT ValTy(VA.getValVT());
172 LLT LocTy(VA.getLocVT());
173
174 // Fixup the types for the DAG compatibility hack.
175 if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16)
176 std::swap(ValTy, LocTy);
177 else {
178 // The calling code knows if this is a pointer or not, we're only touching
179 // the LocTy for the i8/i16 hack.
180 assert(LocTy.getSizeInBits() == MemTy.getSizeInBits());
181 LocTy = MemTy;
182 }
183
184 auto MMO = MF.getMachineMemOperand(
186 inferAlignFromPtrInfo(MF, MPO));
187
188 switch (VA.getLocInfo()) {
189 case CCValAssign::LocInfo::ZExt:
190 MIRBuilder.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, ValVReg, Addr, *MMO);
191 return;
192 case CCValAssign::LocInfo::SExt:
193 MIRBuilder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, ValVReg, Addr, *MMO);
194 return;
195 default:
196 MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
197 return;
198 }
199 }
200
201 /// How the physical register gets marked varies between formal
202 /// parameters (it's a basic-block live-in), and a call instruction
203 /// (it's an implicit-def of the BL).
204 virtual void markPhysRegUsed(MCRegister PhysReg) = 0;
205};
206
207struct FormalArgHandler : public IncomingArgHandler {
209 : IncomingArgHandler(MIRBuilder, MRI) {}
210
211 void markPhysRegUsed(MCRegister PhysReg) override {
212 MIRBuilder.getMRI()->addLiveIn(PhysReg);
213 MIRBuilder.getMBB().addLiveIn(PhysReg);
214 }
215};
216
217struct CallReturnHandler : public IncomingArgHandler {
218 CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
220 : IncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
221
222 void markPhysRegUsed(MCRegister PhysReg) override {
223 MIB.addDef(PhysReg, RegState::Implicit);
224 }
225
227};
228
229/// A special return arg handler for "returned" attribute arg calls.
230struct ReturnedArgCallReturnHandler : public CallReturnHandler {
231 ReturnedArgCallReturnHandler(MachineIRBuilder &MIRBuilder,
234 : CallReturnHandler(MIRBuilder, MRI, MIB) {}
235
236 void markPhysRegUsed(MCRegister PhysReg) override {}
237};
238
239struct OutgoingArgHandler : public CallLowering::OutgoingValueHandler {
240 OutgoingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
241 MachineInstrBuilder MIB, bool IsTailCall = false,
242 int FPDiff = 0)
243 : OutgoingValueHandler(MIRBuilder, MRI), MIB(MIB), IsTailCall(IsTailCall),
244 FPDiff(FPDiff),
245 Subtarget(MIRBuilder.getMF().getSubtarget<AArch64Subtarget>()) {}
246
247 Register getStackAddress(uint64_t Size, int64_t Offset,
249 ISD::ArgFlagsTy Flags) override {
250 MachineFunction &MF = MIRBuilder.getMF();
251 LLT p0 = LLT::pointer(0, 64);
252 LLT s64 = LLT::scalar(64);
253
254 if (IsTailCall) {
255 assert(!Flags.isByVal() && "byval unhandled with tail calls");
256
257 Offset += FPDiff;
258 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
259 auto FIReg = MIRBuilder.buildFrameIndex(p0, FI);
261 return FIReg.getReg(0);
262 }
263
264 if (!SPReg)
265 SPReg = MIRBuilder.buildCopy(p0, Register(AArch64::SP)).getReg(0);
266
267 auto OffsetReg = MIRBuilder.buildConstant(s64, Offset);
268
269 auto AddrReg = MIRBuilder.buildPtrAdd(p0, SPReg, OffsetReg);
270
272 return AddrReg.getReg(0);
273 }
274
275 /// We need to fixup the reported store size for certain value types because
276 /// we invert the interpretation of ValVT and LocVT in certain cases. This is
277 /// for compatability with the DAG call lowering implementation, which we're
278 /// currently building on top of.
279 LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA,
280 ISD::ArgFlagsTy Flags) const override {
281 if (Flags.isPointer())
284 }
285
286 void assignValueToReg(Register ValVReg, Register PhysReg,
287 const CCValAssign &VA) override {
288 MIB.addUse(PhysReg, RegState::Implicit);
289 Register ExtReg = extendRegister(ValVReg, VA);
290 MIRBuilder.buildCopy(PhysReg, ExtReg);
291 }
292
293 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
294 const MachinePointerInfo &MPO,
295 const CCValAssign &VA) override {
296 MachineFunction &MF = MIRBuilder.getMF();
297 auto MMO = MF.getMachineMemOperand(MPO, MachineMemOperand::MOStore, MemTy,
298 inferAlignFromPtrInfo(MF, MPO));
299 MIRBuilder.buildStore(ValVReg, Addr, *MMO);
300 }
301
302 void assignValueToAddress(const CallLowering::ArgInfo &Arg, unsigned RegIndex,
303 Register Addr, LLT MemTy,
304 const MachinePointerInfo &MPO,
305 const CCValAssign &VA) override {
306 unsigned MaxSize = MemTy.getSizeInBytes() * 8;
307 // For varargs, we always want to extend them to 8 bytes, in which case
308 // we disable setting a max.
309 if (!Arg.IsFixed)
310 MaxSize = 0;
311
312 Register ValVReg = Arg.Regs[RegIndex];
313 if (VA.getLocInfo() != CCValAssign::LocInfo::FPExt) {
314 MVT LocVT = VA.getLocVT();
315 MVT ValVT = VA.getValVT();
316
317 if (VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16) {
318 std::swap(ValVT, LocVT);
319 MemTy = LLT(VA.getValVT());
320 }
321
322 ValVReg = extendRegister(ValVReg, VA, MaxSize);
323 } else {
324 // The store does not cover the full allocated stack slot.
325 MemTy = LLT(VA.getValVT());
326 }
327
328 assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
329 }
330
332
333 bool IsTailCall;
334
335 /// For tail calls, the byte offset of the call's argument area from the
336 /// callee's. Unused elsewhere.
337 int FPDiff;
338
339 // Cache the SP register vreg if we need it more than once in this call site.
340 Register SPReg;
341
342 const AArch64Subtarget &Subtarget;
343};
344} // namespace
345
346static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt) {
347 return (CallConv == CallingConv::Fast && TailCallOpt) ||
348 CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
349}
350
352 const Value *Val,
353 ArrayRef<Register> VRegs,
355 Register SwiftErrorVReg) const {
356 auto MIB = MIRBuilder.buildInstrNoInsert(AArch64::RET_ReallyLR);
357 assert(((Val && !VRegs.empty()) || (!Val && VRegs.empty())) &&
358 "Return value without a vreg");
359
360 bool Success = true;
361 if (!FLI.CanLowerReturn) {
362 insertSRetStores(MIRBuilder, Val->getType(), VRegs, FLI.DemoteRegister);
363 } else if (!VRegs.empty()) {
364 MachineFunction &MF = MIRBuilder.getMF();
365 const Function &F = MF.getFunction();
366 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
367
369 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
370 CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(F.getCallingConv());
371 auto &DL = F.getParent()->getDataLayout();
372 LLVMContext &Ctx = Val->getType()->getContext();
373
374 SmallVector<EVT, 4> SplitEVTs;
375 ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
376 assert(VRegs.size() == SplitEVTs.size() &&
377 "For each split Type there should be exactly one VReg.");
378
379 SmallVector<ArgInfo, 8> SplitArgs;
380 CallingConv::ID CC = F.getCallingConv();
381
382 for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
383 Register CurVReg = VRegs[i];
384 ArgInfo CurArgInfo = ArgInfo{CurVReg, SplitEVTs[i].getTypeForEVT(Ctx), 0};
386
387 // i1 is a special case because SDAG i1 true is naturally zero extended
388 // when widened using ANYEXT. We need to do it explicitly here.
389 auto &Flags = CurArgInfo.Flags[0];
390 if (MRI.getType(CurVReg).getSizeInBits() == 1 && !Flags.isSExt() &&
391 !Flags.isZExt()) {
392 CurVReg = MIRBuilder.buildZExt(LLT::scalar(8), CurVReg).getReg(0);
393 } else if (TLI.getNumRegistersForCallingConv(Ctx, CC, SplitEVTs[i]) ==
394 1) {
395 // Some types will need extending as specified by the CC.
396 MVT NewVT = TLI.getRegisterTypeForCallingConv(Ctx, CC, SplitEVTs[i]);
397 if (EVT(NewVT) != SplitEVTs[i]) {
398 unsigned ExtendOp = TargetOpcode::G_ANYEXT;
399 if (F.getAttributes().hasRetAttr(Attribute::SExt))
400 ExtendOp = TargetOpcode::G_SEXT;
401 else if (F.getAttributes().hasRetAttr(Attribute::ZExt))
402 ExtendOp = TargetOpcode::G_ZEXT;
403
404 LLT NewLLT(NewVT);
405 LLT OldLLT(MVT::getVT(CurArgInfo.Ty));
406 CurArgInfo.Ty = EVT(NewVT).getTypeForEVT(Ctx);
407 // Instead of an extend, we might have a vector type which needs
408 // padding with more elements, e.g. <2 x half> -> <4 x half>.
409 if (NewVT.isVector()) {
410 if (OldLLT.isVector()) {
411 if (NewLLT.getNumElements() > OldLLT.getNumElements()) {
412
413 CurVReg =
414 MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
415 .getReg(0);
416 } else {
417 // Just do a vector extend.
418 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
419 .getReg(0);
420 }
421 } else if (NewLLT.getNumElements() >= 2 &&
422 NewLLT.getNumElements() <= 8) {
423 // We need to pad a <1 x S> type to <2/4/8 x S>. Since we don't
424 // have <1 x S> vector types in GISel we use a build_vector
425 // instead of a vector merge/concat.
426 CurVReg =
427 MIRBuilder.buildPadVectorWithUndefElements(NewLLT, CurVReg)
428 .getReg(0);
429 } else {
430 LLVM_DEBUG(dbgs() << "Could not handle ret ty\n");
431 return false;
432 }
433 } else {
434 // If the split EVT was a <1 x T> vector, and NewVT is T, then we
435 // don't have to do anything since we don't distinguish between the
436 // two.
437 if (NewLLT != MRI.getType(CurVReg)) {
438 // A scalar extend.
439 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
440 .getReg(0);
441 }
442 }
443 }
444 }
445 if (CurVReg != CurArgInfo.Regs[0]) {
446 CurArgInfo.Regs[0] = CurVReg;
447 // Reset the arg flags after modifying CurVReg.
449 }
450 splitToValueTypes(CurArgInfo, SplitArgs, DL, CC);
451 }
452
453 AArch64OutgoingValueAssigner Assigner(AssignFn, AssignFn, Subtarget,
454 /*IsReturn*/ true);
455 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB);
456 Success = determineAndHandleAssignments(Handler, Assigner, SplitArgs,
457 MIRBuilder, CC, F.isVarArg());
458 }
459
460 if (SwiftErrorVReg) {
461 MIB.addUse(AArch64::X21, RegState::Implicit);
462 MIRBuilder.buildCopy(AArch64::X21, SwiftErrorVReg);
463 }
464
465 MIRBuilder.insertInstr(MIB);
466 return Success;
467}
468
470 CallingConv::ID CallConv,
472 bool IsVarArg) const {
474 const auto &TLI = *getTLI<AArch64TargetLowering>();
475 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
476 MF.getFunction().getContext());
477
478 return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv));
479}
480
481/// Helper function to compute forwarded registers for musttail calls. Computes
482/// the forwarded registers, sets MBB liveness, and emits COPY instructions that
483/// can be used to save + restore registers later.
485 CCAssignFn *AssignFn) {
486 MachineBasicBlock &MBB = MIRBuilder.getMBB();
487 MachineFunction &MF = MIRBuilder.getMF();
488 MachineFrameInfo &MFI = MF.getFrameInfo();
489
490 if (!MFI.hasMustTailInVarArgFunc())
491 return;
492
494 const Function &F = MF.getFunction();
495 assert(F.isVarArg() && "Expected F to be vararg?");
496
497 // Compute the set of forwarded registers. The rest are scratch.
499 CCState CCInfo(F.getCallingConv(), /*IsVarArg=*/true, MF, ArgLocs,
500 F.getContext());
501 SmallVector<MVT, 2> RegParmTypes;
502 RegParmTypes.push_back(MVT::i64);
503 RegParmTypes.push_back(MVT::f128);
504
505 // Later on, we can use this vector to restore the registers if necessary.
508 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, AssignFn);
509
510 // Conservatively forward X8, since it might be used for an aggregate
511 // return.
512 if (!CCInfo.isAllocated(AArch64::X8)) {
513 Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
514 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
515 }
516
517 // Add the forwards to the MachineBasicBlock and MachineFunction.
518 for (const auto &F : Forwards) {
519 MBB.addLiveIn(F.PReg);
520 MIRBuilder.buildCopy(Register(F.VReg), Register(F.PReg));
521 }
522}
523
525 auto &F = MF.getFunction();
526 if (F.getReturnType()->isScalableTy() ||
527 llvm::any_of(F.args(), [](const Argument &A) {
528 return A.getType()->isScalableTy();
529 }))
530 return true;
531 const auto &ST = MF.getSubtarget<AArch64Subtarget>();
532 if (!ST.hasNEON() || !ST.hasFPARMv8()) {
533 LLVM_DEBUG(dbgs() << "Falling back to SDAG because we don't support no-NEON\n");
534 return true;
535 }
536
537 SMEAttrs Attrs(F);
538 if (Attrs.hasZAState() || Attrs.hasZT0State() ||
539 Attrs.hasStreamingInterfaceOrBody() ||
540 Attrs.hasStreamingCompatibleInterface())
541 return true;
542
543 return false;
544}
545
546void AArch64CallLowering::saveVarArgRegisters(
548 CCState &CCInfo) const {
551
552 MachineFunction &MF = MIRBuilder.getMF();
554 MachineFrameInfo &MFI = MF.getFrameInfo();
556 auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
557 bool IsWin64CC =
558 Subtarget.isCallingConvWin64(CCInfo.getCallingConv());
559 const LLT p0 = LLT::pointer(0, 64);
560 const LLT s64 = LLT::scalar(64);
561
562 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
563 unsigned NumVariadicGPRArgRegs = GPRArgRegs.size() - FirstVariadicGPR + 1;
564
565 unsigned GPRSaveSize = 8 * (GPRArgRegs.size() - FirstVariadicGPR);
566 int GPRIdx = 0;
567 if (GPRSaveSize != 0) {
568 if (IsWin64CC) {
569 GPRIdx = MFI.CreateFixedObject(GPRSaveSize,
570 -static_cast<int>(GPRSaveSize), false);
571 if (GPRSaveSize & 15)
572 // The extra size here, if triggered, will always be 8.
573 MFI.CreateFixedObject(16 - (GPRSaveSize & 15),
574 -static_cast<int>(alignTo(GPRSaveSize, 16)),
575 false);
576 } else
577 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
578
579 auto FIN = MIRBuilder.buildFrameIndex(p0, GPRIdx);
580 auto Offset =
581 MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 8);
582
583 for (unsigned i = FirstVariadicGPR; i < GPRArgRegs.size(); ++i) {
584 Register Val = MRI.createGenericVirtualRegister(s64);
585 Handler.assignValueToReg(
586 Val, GPRArgRegs[i],
588 GPRArgRegs[i], MVT::i64, CCValAssign::Full));
589 auto MPO = IsWin64CC ? MachinePointerInfo::getFixedStack(
590 MF, GPRIdx, (i - FirstVariadicGPR) * 8)
591 : MachinePointerInfo::getStack(MF, i * 8);
592 MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
593
594 FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
595 FIN.getReg(0), Offset);
596 }
597 }
598 FuncInfo->setVarArgsGPRIndex(GPRIdx);
599 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
600
601 if (Subtarget.hasFPARMv8() && !IsWin64CC) {
602 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
603
604 unsigned FPRSaveSize = 16 * (FPRArgRegs.size() - FirstVariadicFPR);
605 int FPRIdx = 0;
606 if (FPRSaveSize != 0) {
607 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
608
609 auto FIN = MIRBuilder.buildFrameIndex(p0, FPRIdx);
610 auto Offset =
611 MIRBuilder.buildConstant(MRI.createGenericVirtualRegister(s64), 16);
612
613 for (unsigned i = FirstVariadicFPR; i < FPRArgRegs.size(); ++i) {
614 Register Val = MRI.createGenericVirtualRegister(LLT::scalar(128));
615 Handler.assignValueToReg(
616 Val, FPRArgRegs[i],
618 i + MF.getFunction().getNumOperands() + NumVariadicGPRArgRegs,
619 MVT::f128, FPRArgRegs[i], MVT::f128, CCValAssign::Full));
620
621 auto MPO = MachinePointerInfo::getStack(MF, i * 16);
622 MIRBuilder.buildStore(Val, FIN, MPO, inferAlignFromPtrInfo(MF, MPO));
623
624 FIN = MIRBuilder.buildPtrAdd(MRI.createGenericVirtualRegister(p0),
625 FIN.getReg(0), Offset);
626 }
627 }
628 FuncInfo->setVarArgsFPRIndex(FPRIdx);
629 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
630 }
631}
632
634 MachineIRBuilder &MIRBuilder, const Function &F,
636 MachineFunction &MF = MIRBuilder.getMF();
637 MachineBasicBlock &MBB = MIRBuilder.getMBB();
639 auto &DL = F.getParent()->getDataLayout();
640 auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
641
642 // Arm64EC has extra requirements for varargs calls which are only implemented
643 // in SelectionDAG; bail out for now.
644 if (F.isVarArg() && Subtarget.isWindowsArm64EC())
645 return false;
646
647 // Arm64EC thunks have a special calling convention which is only implemented
648 // in SelectionDAG; bail out for now.
649 if (F.getCallingConv() == CallingConv::ARM64EC_Thunk_Native ||
650 F.getCallingConv() == CallingConv::ARM64EC_Thunk_X64)
651 return false;
652
653 bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv()) && !Subtarget.isWindowsArm64EC();
654
655 SmallVector<ArgInfo, 8> SplitArgs;
657
658 // Insert the hidden sret parameter if the return value won't fit in the
659 // return registers.
660 if (!FLI.CanLowerReturn)
662
663 unsigned i = 0;
664 for (auto &Arg : F.args()) {
665 if (DL.getTypeStoreSize(Arg.getType()).isZero())
666 continue;
667
668 ArgInfo OrigArg{VRegs[i], Arg, i};
670
671 // i1 arguments are zero-extended to i8 by the caller. Emit a
672 // hint to reflect this.
673 if (OrigArg.Ty->isIntegerTy(1)) {
674 assert(OrigArg.Regs.size() == 1 &&
675 MRI.getType(OrigArg.Regs[0]).getSizeInBits() == 1 &&
676 "Unexpected registers used for i1 arg");
677
678 auto &Flags = OrigArg.Flags[0];
679 if (!Flags.isZExt() && !Flags.isSExt()) {
680 // Lower i1 argument as i8, and insert AssertZExt + Trunc later.
681 Register OrigReg = OrigArg.Regs[0];
682 Register WideReg = MRI.createGenericVirtualRegister(LLT::scalar(8));
683 OrigArg.Regs[0] = WideReg;
684 BoolArgs.push_back({OrigReg, WideReg});
685 }
686 }
687
688 if (Arg.hasAttribute(Attribute::SwiftAsync))
689 MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
690
691 splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv());
692 ++i;
693 }
694
695 if (!MBB.empty())
696 MIRBuilder.setInstr(*MBB.begin());
697
698 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
699 CCAssignFn *AssignFn = TLI.CCAssignFnForCall(F.getCallingConv(), IsWin64 && F.isVarArg());
700
701 AArch64IncomingValueAssigner Assigner(AssignFn, AssignFn);
702 FormalArgHandler Handler(MIRBuilder, MRI);
704 CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
705 if (!determineAssignments(Assigner, SplitArgs, CCInfo) ||
706 !handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, MIRBuilder))
707 return false;
708
709 if (!BoolArgs.empty()) {
710 for (auto &KV : BoolArgs) {
711 Register OrigReg = KV.first;
712 Register WideReg = KV.second;
713 LLT WideTy = MRI.getType(WideReg);
714 assert(MRI.getType(OrigReg).getScalarSizeInBits() == 1 &&
715 "Unexpected bit size of a bool arg");
716 MIRBuilder.buildTrunc(
717 OrigReg, MIRBuilder.buildAssertZExt(WideTy, WideReg, 1).getReg(0));
718 }
719 }
720
722 uint64_t StackSize = Assigner.StackSize;
723 if (F.isVarArg()) {
724 if ((!Subtarget.isTargetDarwin() && !Subtarget.isWindowsArm64EC()) || IsWin64) {
725 // The AAPCS variadic function ABI is identical to the non-variadic
726 // one. As a result there may be more arguments in registers and we should
727 // save them for future reference.
728 // Win64 variadic functions also pass arguments in registers, but all
729 // float arguments are passed in integer registers.
730 saveVarArgRegisters(MIRBuilder, Handler, CCInfo);
731 } else if (Subtarget.isWindowsArm64EC()) {
732 return false;
733 }
734
735 // We currently pass all varargs at 8-byte alignment, or 4 in ILP32.
736 StackSize = alignTo(Assigner.StackSize, Subtarget.isTargetILP32() ? 4 : 8);
737
738 auto &MFI = MIRBuilder.getMF().getFrameInfo();
739 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackSize, true));
740 }
741
742 if (doesCalleeRestoreStack(F.getCallingConv(),
744 // We have a non-standard ABI, so why not make full use of the stack that
745 // we're going to pop? It must be aligned to 16 B in any case.
746 StackSize = alignTo(StackSize, 16);
747
748 // If we're expected to restore the stack (e.g. fastcc), then we'll be
749 // adding a multiple of 16.
750 FuncInfo->setArgumentStackToRestore(StackSize);
751
752 // Our own callers will guarantee that the space is free by giving an
753 // aligned value to CALLSEQ_START.
754 }
755
756 // When we tail call, we need to check if the callee's arguments
757 // will fit on the caller's stack. So, whenever we lower formal arguments,
758 // we should keep track of this information, since we might lower a tail call
759 // in this function later.
760 FuncInfo->setBytesInStackArgArea(StackSize);
761
762 if (Subtarget.hasCustomCallingConv())
763 Subtarget.getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
764
765 handleMustTailForwardedRegisters(MIRBuilder, AssignFn);
766
767 // Move back to the end of the basic block.
768 MIRBuilder.setMBB(MBB);
769
770 return true;
771}
772
773/// Return true if the calling convention is one that we can guarantee TCO for.
774static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
775 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
777}
778
779/// Return true if we might ever do TCO for calls with this calling convention.
781 switch (CC) {
782 case CallingConv::C:
789 return true;
790 default:
791 return false;
792 }
793}
794
795/// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
796/// CC.
797static std::pair<CCAssignFn *, CCAssignFn *>
799 return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
800}
801
802bool AArch64CallLowering::doCallerAndCalleePassArgsTheSameWay(
803 CallLoweringInfo &Info, MachineFunction &MF,
804 SmallVectorImpl<ArgInfo> &InArgs) const {
805 const Function &CallerF = MF.getFunction();
806 CallingConv::ID CalleeCC = Info.CallConv;
807 CallingConv::ID CallerCC = CallerF.getCallingConv();
808
809 // If the calling conventions match, then everything must be the same.
810 if (CalleeCC == CallerCC)
811 return true;
812
813 // Check if the caller and callee will handle arguments in the same way.
814 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
815 CCAssignFn *CalleeAssignFnFixed;
816 CCAssignFn *CalleeAssignFnVarArg;
817 std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
818 getAssignFnsForCC(CalleeCC, TLI);
819
820 CCAssignFn *CallerAssignFnFixed;
821 CCAssignFn *CallerAssignFnVarArg;
822 std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
823 getAssignFnsForCC(CallerCC, TLI);
824
825 AArch64IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
826 CalleeAssignFnVarArg);
827 AArch64IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
828 CallerAssignFnVarArg);
829
830 if (!resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner))
831 return false;
832
833 // Make sure that the caller and callee preserve all of the same registers.
834 auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
835 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
836 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
838 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
839 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
840 }
841
842 return TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved);
843}
844
845bool AArch64CallLowering::areCalleeOutgoingArgsTailCallable(
846 CallLoweringInfo &Info, MachineFunction &MF,
847 SmallVectorImpl<ArgInfo> &OrigOutArgs) const {
848 // If there are no outgoing arguments, then we are done.
849 if (OrigOutArgs.empty())
850 return true;
851
852 const Function &CallerF = MF.getFunction();
853 LLVMContext &Ctx = CallerF.getContext();
854 CallingConv::ID CalleeCC = Info.CallConv;
855 CallingConv::ID CallerCC = CallerF.getCallingConv();
856 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
857 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
858
859 CCAssignFn *AssignFnFixed;
860 CCAssignFn *AssignFnVarArg;
861 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
862
863 // We have outgoing arguments. Make sure that we can tail call with them.
865 CCState OutInfo(CalleeCC, false, MF, OutLocs, Ctx);
866
867 AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
868 Subtarget, /*IsReturn*/ false);
869 // determineAssignments() may modify argument flags, so make a copy.
871 append_range(OutArgs, OrigOutArgs);
872 if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo)) {
873 LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
874 return false;
875 }
876
877 // Make sure that they can fit on the caller's stack.
878 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
879 if (OutInfo.getStackSize() > FuncInfo->getBytesInStackArgArea()) {
880 LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
881 return false;
882 }
883
884 // Verify that the parameters in callee-saved registers match.
885 // TODO: Port this over to CallLowering as general code once swiftself is
886 // supported.
887 auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
888 const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
890
891 if (Info.IsVarArg) {
892 // Be conservative and disallow variadic memory operands to match SDAG's
893 // behaviour.
894 // FIXME: If the caller's calling convention is C, then we can
895 // potentially use its argument area. However, for cases like fastcc,
896 // we can't do anything.
897 for (unsigned i = 0; i < OutLocs.size(); ++i) {
898 auto &ArgLoc = OutLocs[i];
899 if (ArgLoc.isRegLoc())
900 continue;
901
903 dbgs()
904 << "... Cannot tail call vararg function with stack arguments\n");
905 return false;
906 }
907 }
908
909 return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
910}
911
913 MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
915 SmallVectorImpl<ArgInfo> &OutArgs) const {
916
917 // Must pass all target-independent checks in order to tail call optimize.
918 if (!Info.IsTailCall)
919 return false;
920
921 CallingConv::ID CalleeCC = Info.CallConv;
922 MachineFunction &MF = MIRBuilder.getMF();
923 const Function &CallerF = MF.getFunction();
924
925 LLVM_DEBUG(dbgs() << "Attempting to lower call as tail call\n");
926
927 if (Info.SwiftErrorVReg) {
928 // TODO: We should handle this.
929 // Note that this is also handled by the check for no outgoing arguments.
930 // Proactively disabling this though, because the swifterror handling in
931 // lowerCall inserts a COPY *after* the location of the call.
932 LLVM_DEBUG(dbgs() << "... Cannot handle tail calls with swifterror yet.\n");
933 return false;
934 }
935
936 if (!mayTailCallThisCC(CalleeCC)) {
937 LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
938 return false;
939 }
940
941 // Byval parameters hand the function a pointer directly into the stack area
942 // we want to reuse during a tail call. Working around this *is* possible (see
943 // X86).
944 //
945 // FIXME: In AArch64ISelLowering, this isn't worked around. Can/should we try
946 // it?
947 //
948 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
949 // In this case, it is necessary to save/restore X0 in the callee. Tail
950 // call opt interferes with this. So we disable tail call opt when the
951 // caller has an argument with "inreg" attribute.
952 //
953 // FIXME: Check whether the callee also has an "inreg" argument.
954 //
955 // When the caller has a swifterror argument, we don't want to tail call
956 // because would have to move into the swifterror register before the
957 // tail call.
958 if (any_of(CallerF.args(), [](const Argument &A) {
959 return A.hasByValAttr() || A.hasInRegAttr() || A.hasSwiftErrorAttr();
960 })) {
961 LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval, "
962 "inreg, or swifterror arguments\n");
963 return false;
964 }
965
966 // Externally-defined functions with weak linkage should not be
967 // tail-called on AArch64 when the OS does not support dynamic
968 // pre-emption of symbols, as the AAELF spec requires normal calls
969 // to undefined weak functions to be replaced with a NOP or jump to the
970 // next instruction. The behaviour of branch instructions in this
971 // situation (as used for tail calls) is implementation-defined, so we
972 // cannot rely on the linker replacing the tail call with a return.
973 if (Info.Callee.isGlobal()) {
974 const GlobalValue *GV = Info.Callee.getGlobal();
975 const Triple &TT = MF.getTarget().getTargetTriple();
976 if (GV->hasExternalWeakLinkage() &&
977 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
978 TT.isOSBinFormatMachO())) {
979 LLVM_DEBUG(dbgs() << "... Cannot tail call externally-defined function "
980 "with weak linkage for this OS.\n");
981 return false;
982 }
983 }
984
985 // If we have -tailcallopt, then we're done.
987 return CalleeCC == CallerF.getCallingConv();
988
989 // We don't have -tailcallopt, so we're allowed to change the ABI (sibcall).
990 // Try to find cases where we can do that.
991
992 // I want anyone implementing a new calling convention to think long and hard
993 // about this assert.
994 assert((!Info.IsVarArg || CalleeCC == CallingConv::C) &&
995 "Unexpected variadic calling convention");
996
997 // Verify that the incoming and outgoing arguments from the callee are
998 // safe to tail call.
999 if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1000 LLVM_DEBUG(
1001 dbgs()
1002 << "... Caller and callee have incompatible calling conventions.\n");
1003 return false;
1004 }
1005
1006 if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1007 return false;
1008
1009 LLVM_DEBUG(
1010 dbgs() << "... Call is eligible for tail call optimization.\n");
1011 return true;
1012}
1013
1014static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
1015 bool IsTailCall) {
1016 const AArch64FunctionInfo *FuncInfo = CallerF.getInfo<AArch64FunctionInfo>();
1017
1018 if (!IsTailCall)
1019 return IsIndirect ? getBLRCallOpcode(CallerF) : (unsigned)AArch64::BL;
1020
1021 if (!IsIndirect)
1022 return AArch64::TCRETURNdi;
1023
1024 // When BTI or PAuthLR are enabled, there are restrictions on using x16 and
1025 // x17 to hold the function pointer.
1026 if (FuncInfo->branchTargetEnforcement()) {
1027 if (FuncInfo->branchProtectionPAuthLR())
1028 return AArch64::TCRETURNrix17;
1029 else
1030 return AArch64::TCRETURNrix16x17;
1031 } else if (FuncInfo->branchProtectionPAuthLR())
1032 return AArch64::TCRETURNrinotx16;
1033
1034 return AArch64::TCRETURNri;
1035}
1036
1037static const uint32_t *
1041 const uint32_t *Mask;
1042 if (!OutArgs.empty() && OutArgs[0].Flags[0].isReturned()) {
1043 // For 'this' returns, use the X0-preserving mask if applicable
1044 Mask = TRI.getThisReturnPreservedMask(MF, Info.CallConv);
1045 if (!Mask) {
1046 OutArgs[0].Flags[0].setReturned(false);
1047 Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1048 }
1049 } else {
1050 Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
1051 }
1052 return Mask;
1053}
1054
1055bool AArch64CallLowering::lowerTailCall(
1056 MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1057 SmallVectorImpl<ArgInfo> &OutArgs) const {
1058 MachineFunction &MF = MIRBuilder.getMF();
1059 const Function &F = MF.getFunction();
1061 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1063
1064 // True when we're tail calling, but without -tailcallopt.
1065 bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt &&
1066 Info.CallConv != CallingConv::Tail &&
1067 Info.CallConv != CallingConv::SwiftTail;
1068
1069 // TODO: Right now, regbankselect doesn't know how to handle the rtcGPR64
1070 // register class. Until we can do that, we should fall back here.
1072 LLVM_DEBUG(
1073 dbgs() << "Cannot lower indirect tail calls with BTI enabled yet.\n");
1074 return false;
1075 }
1076
1077 // Find out which ABI gets to decide where things go.
1078 CallingConv::ID CalleeCC = Info.CallConv;
1079 CCAssignFn *AssignFnFixed;
1080 CCAssignFn *AssignFnVarArg;
1081 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1082
1083 MachineInstrBuilder CallSeqStart;
1084 if (!IsSibCall)
1085 CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1086
1087 unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
1088 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1089 MIB.add(Info.Callee);
1090
1091 // Byte offset for the tail call. When we are sibcalling, this will always
1092 // be 0.
1093 MIB.addImm(0);
1094
1095 // Tell the call which registers are clobbered.
1096 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1097 auto TRI = Subtarget.getRegisterInfo();
1098 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1099 if (Subtarget.hasCustomCallingConv())
1100 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1101 MIB.addRegMask(Mask);
1102
1103 if (Info.CFIType)
1104 MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1105
1106 if (TRI->isAnyArgRegReserved(MF))
1107 TRI->emitReservedArgRegCallError(MF);
1108
1109 // FPDiff is the byte offset of the call's argument area from the callee's.
1110 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1111 // by this amount for a tail call. In a sibling call it must be 0 because the
1112 // caller will deallocate the entire stack and the callee still expects its
1113 // arguments to begin at SP+0.
1114 int FPDiff = 0;
1115
1116 // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1117 // by -tailcallopt. For sibcalls, the memory operands for the call are
1118 // already available in the caller's incoming argument space.
1119 unsigned NumBytes = 0;
1120 if (!IsSibCall) {
1121 // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1122 // before handling assignments, because FPDiff must be known for memory
1123 // arguments.
1124 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1126 CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1127
1128 AArch64OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg,
1129 Subtarget, /*IsReturn*/ false);
1130 if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1131 return false;
1132
1133 // The callee will pop the argument stack as a tail call. Thus, we must
1134 // keep it 16-byte aligned.
1135 NumBytes = alignTo(OutInfo.getStackSize(), 16);
1136
1137 // FPDiff will be negative if this tail call requires more space than we
1138 // would automatically have in our incoming argument space. Positive if we
1139 // actually shrink the stack.
1140 FPDiff = NumReusableBytes - NumBytes;
1141
1142 // Update the required reserved area if this is the tail call requiring the
1143 // most argument stack space.
1144 if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
1145 FuncInfo->setTailCallReservedStack(-FPDiff);
1146
1147 // The stack pointer must be 16-byte aligned at all times it's used for a
1148 // memory operation, which in practice means at *all* times and in
1149 // particular across call boundaries. Therefore our own arguments started at
1150 // a 16-byte aligned SP and the delta applied for the tail call should
1151 // satisfy the same constraint.
1152 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1153 }
1154
1155 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
1156
1157 AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1158 Subtarget, /*IsReturn*/ false);
1159
1160 // Do the actual argument marshalling.
1161 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB,
1162 /*IsTailCall*/ true, FPDiff);
1163 if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1164 CalleeCC, Info.IsVarArg))
1165 return false;
1166
1167 Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1168
1169 if (Info.IsVarArg && Info.IsMustTailCall) {
1170 // Now we know what's being passed to the function. Add uses to the call for
1171 // the forwarded registers that we *aren't* passing as parameters. This will
1172 // preserve the copies we build earlier.
1173 for (const auto &F : Forwards) {
1174 Register ForwardedReg = F.PReg;
1175 // If the register is already passed, or aliases a register which is
1176 // already being passed, then skip it.
1177 if (any_of(MIB->uses(), [&ForwardedReg, &TRI](const MachineOperand &Use) {
1178 if (!Use.isReg())
1179 return false;
1180 return TRI->regsOverlap(Use.getReg(), ForwardedReg);
1181 }))
1182 continue;
1183
1184 // We aren't passing it already, so we should add it to the call.
1185 MIRBuilder.buildCopy(ForwardedReg, Register(F.VReg));
1186 MIB.addReg(ForwardedReg, RegState::Implicit);
1187 }
1188 }
1189
1190 // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1191 // sequence start and end here.
1192 if (!IsSibCall) {
1193 MIB->getOperand(1).setImm(FPDiff);
1194 CallSeqStart.addImm(0).addImm(0);
1195 // End the call sequence *before* emitting the call. Normally, we would
1196 // tidy the frame up after the call. However, here, we've laid out the
1197 // parameters so that when SP is reset, they will be in the correct
1198 // location.
1199 MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP).addImm(0).addImm(0);
1200 }
1201
1202 // Now we can add the actual call instruction to the correct basic block.
1203 MIRBuilder.insertInstr(MIB);
1204
1205 // If Callee is a reg, since it is used by a target specific instruction,
1206 // it must have a register class matching the constraint of that instruction.
1207 if (MIB->getOperand(0).isReg())
1209 *MF.getSubtarget().getRegBankInfo(), *MIB,
1210 MIB->getDesc(), MIB->getOperand(0), 0);
1211
1213 Info.LoweredTailCall = true;
1214 return true;
1215}
1216
1218 CallLoweringInfo &Info) const {
1219 MachineFunction &MF = MIRBuilder.getMF();
1220 const Function &F = MF.getFunction();
1222 auto &DL = F.getParent()->getDataLayout();
1223 const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
1224 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1225
1226 // Arm64EC has extra requirements for varargs calls; bail out for now.
1227 //
1228 // Arm64EC has special mangling rules for calls; bail out on all calls for
1229 // now.
1230 if (Subtarget.isWindowsArm64EC())
1231 return false;
1232
1233 // Arm64EC thunks have a special calling convention which is only implemented
1234 // in SelectionDAG; bail out for now.
1235 if (Info.CallConv == CallingConv::ARM64EC_Thunk_Native ||
1237 return false;
1238
1240 for (auto &OrigArg : Info.OrigArgs) {
1241 splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1242 // AAPCS requires that we zero-extend i1 to 8 bits by the caller.
1243 auto &Flags = OrigArg.Flags[0];
1244 if (OrigArg.Ty->isIntegerTy(1) && !Flags.isSExt() && !Flags.isZExt()) {
1245 ArgInfo &OutArg = OutArgs.back();
1246 assert(OutArg.Regs.size() == 1 &&
1247 MRI.getType(OutArg.Regs[0]).getSizeInBits() == 1 &&
1248 "Unexpected registers used for i1 arg");
1249
1250 // We cannot use a ZExt ArgInfo flag here, because it will
1251 // zero-extend the argument to i32 instead of just i8.
1252 OutArg.Regs[0] =
1253 MIRBuilder.buildZExt(LLT::scalar(8), OutArg.Regs[0]).getReg(0);
1254 LLVMContext &Ctx = MF.getFunction().getContext();
1255 OutArg.Ty = Type::getInt8Ty(Ctx);
1256 }
1257 }
1258
1260 if (!Info.OrigRet.Ty->isVoidTy())
1261 splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1262
1263 // If we can lower as a tail call, do that instead.
1264 bool CanTailCallOpt =
1265 isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1266
1267 // We must emit a tail call if we have musttail.
1268 if (Info.IsMustTailCall && !CanTailCallOpt) {
1269 // There are types of incoming/outgoing arguments we can't handle yet, so
1270 // it doesn't make sense to actually die here like in ISelLowering. Instead,
1271 // fall back to SelectionDAG and let it try to handle this.
1272 LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1273 return false;
1274 }
1275
1276 Info.IsTailCall = CanTailCallOpt;
1277 if (CanTailCallOpt)
1278 return lowerTailCall(MIRBuilder, Info, OutArgs);
1279
1280 // Find out which ABI gets to decide where things go.
1281 CCAssignFn *AssignFnFixed;
1282 CCAssignFn *AssignFnVarArg;
1283 std::tie(AssignFnFixed, AssignFnVarArg) =
1284 getAssignFnsForCC(Info.CallConv, TLI);
1285
1286 MachineInstrBuilder CallSeqStart;
1287 CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
1288
1289 // Create a temporarily-floating call instruction so we can add the implicit
1290 // uses of arg registers.
1291
1292 unsigned Opc = 0;
1293 // Calls with operand bundle "clang.arc.attachedcall" are special. They should
1294 // be expanded to the call, directly followed by a special marker sequence and
1295 // a call to an ObjC library function.
1297 Opc = AArch64::BLR_RVMARKER;
1298 // A call to a returns twice function like setjmp must be followed by a bti
1299 // instruction.
1300 else if (Info.CB && Info.CB->hasFnAttr(Attribute::ReturnsTwice) &&
1301 !Subtarget.noBTIAtReturnTwice() &&
1303 Opc = AArch64::BLR_BTI;
1304 else {
1305 // For an intrinsic call (e.g. memset), use GOT if "RtLibUseGOT" (-fno-plt)
1306 // is set.
1307 if (Info.Callee.isSymbol() && F.getParent()->getRtLibUseGOT()) {
1308 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_GLOBAL_VALUE);
1309 DstOp(getLLTForType(*F.getType(), DL)).addDefToMIB(MRI, MIB);
1310 MIB.addExternalSymbol(Info.Callee.getSymbolName(), AArch64II::MO_GOT);
1311 Info.Callee = MachineOperand::CreateReg(MIB.getReg(0), false);
1312 }
1313 Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
1314 }
1315
1316 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1317 unsigned CalleeOpNo = 0;
1318
1319 if (Opc == AArch64::BLR_RVMARKER) {
1320 // Add a target global address for the retainRV/claimRV runtime function
1321 // just before the call target.
1323 MIB.addGlobalAddress(ARCFn);
1324 ++CalleeOpNo;
1325 } else if (Info.CFIType) {
1326 MIB->setCFIType(MF, Info.CFIType->getZExtValue());
1327 }
1328
1329 MIB.add(Info.Callee);
1330
1331 // Tell the call which registers are clobbered.
1332 const uint32_t *Mask;
1333 const auto *TRI = Subtarget.getRegisterInfo();
1334
1335 AArch64OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg,
1336 Subtarget, /*IsReturn*/ false);
1337 // Do the actual argument marshalling.
1338 OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, /*IsReturn*/ false);
1339 if (!determineAndHandleAssignments(Handler, Assigner, OutArgs, MIRBuilder,
1340 Info.CallConv, Info.IsVarArg))
1341 return false;
1342
1343 Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1344
1346 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1347 MIB.addRegMask(Mask);
1348
1349 if (TRI->isAnyArgRegReserved(MF))
1350 TRI->emitReservedArgRegCallError(MF);
1351
1352 // Now we can add the actual call instruction to the correct basic block.
1353 MIRBuilder.insertInstr(MIB);
1354
1355 uint64_t CalleePopBytes =
1358 ? alignTo(Assigner.StackSize, 16)
1359 : 0;
1360
1361 CallSeqStart.addImm(Assigner.StackSize).addImm(0);
1362 MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP)
1363 .addImm(Assigner.StackSize)
1364 .addImm(CalleePopBytes);
1365
1366 // If Callee is a reg, since it is used by a target specific
1367 // instruction, it must have a register class matching the
1368 // constraint of that instruction.
1369 if (MIB->getOperand(CalleeOpNo).isReg())
1370 constrainOperandRegClass(MF, *TRI, MRI, *Subtarget.getInstrInfo(),
1371 *Subtarget.getRegBankInfo(), *MIB, MIB->getDesc(),
1372 MIB->getOperand(CalleeOpNo), CalleeOpNo);
1373
1374 // Finally we can copy the returned value back into its virtual-register. In
1375 // symmetry with the arguments, the physical register must be an
1376 // implicit-define of the call instruction.
1377 if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1378 CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv);
1379 CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1380 bool UsingReturnedArg =
1381 !OutArgs.empty() && OutArgs[0].Flags[0].isReturned();
1382
1383 AArch64OutgoingValueAssigner Assigner(RetAssignFn, RetAssignFn, Subtarget,
1384 /*IsReturn*/ false);
1385 ReturnedArgCallReturnHandler ReturnedArgHandler(MIRBuilder, MRI, MIB);
1387 UsingReturnedArg ? ReturnedArgHandler : Handler, Assigner, InArgs,
1388 MIRBuilder, Info.CallConv, Info.IsVarArg,
1389 UsingReturnedArg ? ArrayRef(OutArgs[0].Regs) : std::nullopt))
1390 return false;
1391 }
1392
1393 if (Info.SwiftErrorVReg) {
1394 MIB.addDef(AArch64::X21, RegState::Implicit);
1395 MIRBuilder.buildCopy(Info.SwiftErrorVReg, Register(AArch64::X21));
1396 }
1397
1398 if (!Info.CanLowerReturn) {
1399 insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1400 Info.DemoteRegister, Info.DemoteStackIndex);
1401 }
1402 return true;
1403}
1404
1406 return Ty.getSizeInBits() == 64;
1407}
unsigned const MachineRegisterInfo * MRI
static void handleMustTailForwardedRegisters(MachineIRBuilder &MIRBuilder, CCAssignFn *AssignFn)
Helper function to compute forwarded registers for musttail calls.
static LLT getStackValueStoreTypeHack(const CCValAssign &VA)
static const uint32_t * getMaskForArgs(SmallVectorImpl< AArch64CallLowering::ArgInfo > &OutArgs, AArch64CallLowering::CallLoweringInfo &Info, const AArch64RegisterInfo &TRI, MachineFunction &MF)
static void applyStackPassedSmallTypeDAGHack(EVT OrigVT, MVT &ValVT, MVT &LocVT)
static std::pair< CCAssignFn *, CCAssignFn * > getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI)
Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for CC.
static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect, bool IsTailCall)
static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt)
This file describes how to lower LLVM calls to machine code calls.
#define Success
static const MCPhysReg GPRArgRegs[]
static const MCPhysReg FPRArgRegs[]
static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls)
Return true if the calling convention is one that we can guarantee TCO for.
static bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
uint64_t Size
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition: MD5.cpp:55
This file declares the MachineIRBuilder class.
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
This file defines ARC utility functions which are used by various parts of the compiler.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
bool lowerReturn(MachineIRBuilder &MIRBuilder, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI, Register SwiftErrorVReg) const override
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
bool canLowerReturn(MachineFunction &MF, CallingConv::ID CallConv, SmallVectorImpl< BaseArgInfo > &Outs, bool IsVarArg) const override
This hook must be implemented to check whether the return values described by Outs can fit into the r...
bool fallBackToDAGISel(const MachineFunction &MF) const override
bool isTypeIsValidForThisReturn(EVT Ty) const override
For targets which support the "returned" parameter attribute, returns true if the given type is a val...
bool isEligibleForTailCallOptimization(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info, SmallVectorImpl< ArgInfo > &InArgs, SmallVectorImpl< ArgInfo > &OutArgs) const
Returns true if the call can be lowered as a tail call.
AArch64CallLowering(const AArch64TargetLowering &TLI)
bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const override
This hook must be implemented to lower the given call instruction, including argument and return valu...
bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function &F, ArrayRef< ArrayRef< Register > > VRegs, FunctionLoweringInfo &FLI) const override
This hook must be implemented to lower the incoming (formal) arguments, described by VRegs,...
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
void setTailCallReservedStack(unsigned bytes)
SmallVectorImpl< ForwardedRegister > & getForwardedMustTailRegParms()
void setBytesInStackArgArea(unsigned bytes)
void setArgumentStackToRestore(unsigned bytes)
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
bool isCallingConvWin64(CallingConv::ID CC) const
const RegisterBankInfo * getRegBankInfo() const override
bool hasCustomCallingConv() const
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
CCAssignFn * CCAssignFnForReturn(CallingConv::ID CC) const
Selects the correct CCAssignFn for a given CallingConvention value.
CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg) const
Selects the correct CCAssignFn for a given CallingConvention value.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
void analyzeMustTailForwardedRegisters(SmallVectorImpl< ForwardedRegister > &Forwards, ArrayRef< MVT > RegParmTypes, CCAssignFn Fn)
Compute the set of registers that need to be preserved and forwarded to any musttail calls.
CallingConv::ID getCallingConv() const
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
bool isVarArg() const
bool isAllocated(MCRegister Reg) const
isAllocated - Return true if the specified register (or an alias) is allocated.
CCValAssign - Represent assignment of one arg/retval to a location.
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, unsigned RegNo, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool handleAssignments(ValueHandler &Handler, SmallVectorImpl< ArgInfo > &Args, CCState &CCState, SmallVectorImpl< CCValAssign > &ArgLocs, MachineIRBuilder &MIRBuilder, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Use Handler to insert code to handle the argument/return values represented by Args.
void insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg, int FI) const
Load the returned value from the stack into virtual registers in VRegs.
bool determineAndHandleAssignments(ValueHandler &Handler, ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, bool IsVarArg, ArrayRef< Register > ThisReturnRegs=std::nullopt) const
Invoke ValueAssigner::assignArg on each of the given Args and then use Handler to move them to the as...
bool resultsCompatible(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &InArgs, ValueAssigner &CalleeAssigner, ValueAssigner &CallerAssigner) const
void splitToValueTypes(const ArgInfo &OrigArgInfo, SmallVectorImpl< ArgInfo > &SplitArgs, const DataLayout &DL, CallingConv::ID CallConv, SmallVectorImpl< uint64_t > *Offsets=nullptr) const
Break OrigArgInfo into one or more pieces the calling convention can process, returned in SplitArgs.
void insertSRetIncomingArgument(const Function &F, SmallVectorImpl< ArgInfo > &SplitArgs, Register &DemoteReg, MachineRegisterInfo &MRI, const DataLayout &DL) const
Insert the hidden sret ArgInfo to the beginning of SplitArgs.
void insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg) const
Store the return value given by VRegs into stack starting at the offset specified in DemoteReg.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< ArgInfo > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
bool determineAssignments(ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, CCState &CCInfo) const
Analyze the argument list in Args, using Assigner to populate CCInfo.
bool checkReturn(CCState &CCInfo, SmallVectorImpl< BaseArgInfo > &Outs, CCAssignFn *Fn) const
void setArgFlags(ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const FuncInfoTy &FuncInfo) const
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
void addDefToMIB(MachineRegisterInfo &MRI, MachineInstrBuilder &MIB) const
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Register DemoteRegister
DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg allocated to hold a pointer to ...
bool CanLowerReturn
CanLowerReturn - true iff the function's return value can be lowered to registers.
iterator_range< arg_iterator > args()
Definition: Function.h:838
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:263
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:356
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:529
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
Definition: LowLevelType.h:42
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
Definition: LowLevelType.h:159
constexpr bool isVector() const
Definition: LowLevelType.h:148
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Definition: LowLevelType.h:57
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
Definition: LowLevelType.h:193
constexpr TypeSize getSizeInBytes() const
Returns the total size of the type in bytes, i.e.
Definition: LowLevelType.h:203
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
Machine Value Type.
bool isVector() const
Return true if this is a vector value type.
static MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:585
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setHasTailCall(bool V=true)
bool hasMustTailInVarArgFunc() const
Returns true if the function is variadic and contains a musttail call.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
Helper class to build MachineInstr.
MachineInstrBuilder insertInstr(MachineInstrBuilder MIB)
Insert an existing instruction at the insertion point.
void setInstr(MachineInstr &MI)
Set the insertion point to before MI.
MachineInstrBuilder buildAssertZExt(const DstOp &Res, const SrcOp &Op, unsigned Size)
Build and insert Res = G_ASSERT_ZEXT Op, Size.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildPadVectorWithUndefElements(const DstOp &Res, const SrcOp &Op0)
Build and insert a, b, ..., x = G_UNMERGE_VALUES Op0 Res = G_BUILD_VECTOR a, b, .....
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineInstrBuilder buildZExt(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ZEXT Op.
MachineFunction & getMF()
Getter for the function we currently build.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_TRUNC Op.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:556
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SMEAttrs is a utility class to parse the SME ACLE attributes on functions.
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
const Triple & getTargetTriple() const
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
virtual const RegisterBankInfo * getRegBankInfo() const
If the information for the register banks is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static IntegerType * getInt8Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
@ MO_GOT
MO_GOT - This flag indicates that a symbol operand represents the address of the GOT entry for the sy...
ArrayRef< MCPhysReg > getFPRArgRegs()
ArrayRef< MCPhysReg > getGPRArgRegs()
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ ARM64EC_Thunk_Native
Calling convention used in the ARM64EC ABI to implement calls between ARM64 code and thunks.
Definition: CallingConv.h:265
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition: CallingConv.h:63
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition: CallingConv.h:66
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition: CallingConv.h:76
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition: CallingConv.h:87
@ ARM64EC_Thunk_X64
Calling convention used in the ARM64EC ABI to implement calls between x64 code and thunks.
Definition: CallingConv.h:260
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Implicit
Not emitted register (e.g. carry, or temporary result).
std::optional< Function * > getAttachedARCFunction(const CallBase *CB)
This function returns operand bundle clang_arc_attachedcall's argument, which is the address of the A...
Definition: ObjCARCUtil.h:43
bool hasAttachedCallOpBundle(const CallBase *CB)
Definition: ObjCARCUtil.h:29
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition: Utils.cpp:54
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2073
unsigned getBLRCallOpcode(const MachineFunction &MF)
Return opcode to be used for indirect calls.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition: Analysis.cpp:79
LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition: Utils.cpp:865
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
SmallVector< Register, 4 > Regs
Definition: CallLowering.h:63
SmallVector< ISD::ArgFlagsTy, 4 > Flags
Definition: CallLowering.h:51
Base class for ValueHandlers used for arguments coming into the current function, or for return value...
Definition: CallLowering.h:323
void assignValueToReg(Register ValVReg, Register PhysReg, const CCValAssign &VA) override
Provides a default implementation for argument handling.
Base class for ValueHandlers used for arguments passed to a function call, or for return values.
Definition: CallLowering.h:339
MachineRegisterInfo & MRI
Definition: CallLowering.h:236
virtual LLT getStackValueStoreType(const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const
Return the in-memory size to write for the argument at VA.
Extended Value Type.
Definition: ValueTypes.h:34
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:358
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:202
Describes a register that needs to be forwarded from the prologue to a musttail call.
This class contains a discriminated union of information about pointers in memory operands,...
static MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.