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"
17 #include "AArch64MachineFunctionInfo.h"
18 #include "AArch64Subtarget.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
24 #include "llvm/CodeGen/GlobalISel/Utils.h"
25 #include "llvm/CodeGen/LowLevelType.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineOperand.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/TargetRegisterInfo.h"
34 #include "llvm/CodeGen/TargetSubtargetInfo.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/Argument.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Support/MachineValueType.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 
47 #define DEBUG_TYPE "aarch64-call-lowering"
48 
49 using namespace llvm;
50 
51 AArch64CallLowering::AArch64CallLowering(const AArch64TargetLowering &TLI)
52   : CallLowering(&TLI) {}
53 
54 namespace {
55 struct IncomingArgHandler : public CallLowering::IncomingValueHandler {
56   IncomingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
57                      CCAssignFn *AssignFn)
58       : IncomingValueHandler(MIRBuilder, MRI, AssignFn), StackUsed(0) {}
59 
60   Register getStackAddress(uint64_t Size, int64_t Offset,
61                            MachinePointerInfo &MPO,
62                            ISD::ArgFlagsTy Flags) override {
63     auto &MFI = MIRBuilder.getMF().getFrameInfo();
64 
65     // Byval is assumed to be writable memory, but other stack passed arguments
66     // are not.
67     const bool IsImmutable = !Flags.isByVal();
68 
69     int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
70     MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
71     auto AddrReg = MIRBuilder.buildFrameIndex(LLT::pointer(0, 64), FI);
72     StackUsed = std::max(StackUsed, Size + Offset);
73     return AddrReg.getReg(0);
74   }
75 
76   void assignValueToReg(Register ValVReg, Register PhysReg,
77                         CCValAssign &VA) override {
78     markPhysRegUsed(PhysReg);
79     IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
80   }
81 
82   void assignValueToAddress(Register ValVReg, Register Addr, uint64_t MemSize,
83                             MachinePointerInfo &MPO, CCValAssign &VA) override {
84     MachineFunction &MF = MIRBuilder.getMF();
85 
86     // The reported memory location may be wider than the value.
87     const LLT RegTy = MRI.getType(ValVReg);
88     MemSize = std::min(static_cast<uint64_t>(RegTy.getSizeInBytes()), MemSize);
89 
90     auto MMO = MF.getMachineMemOperand(
91         MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
92         MemSize, inferAlignFromPtrInfo(MF, MPO));
93     const LLT LocVT = LLT{VA.getLocVT()};
94 
95     if (RegTy.getScalarSizeInBits() < LocVT.getScalarSizeInBits()) {
96       auto LocInfo = VA.getLocInfo();
97       if (LocInfo == CCValAssign::LocInfo::ZExt) {
98         // We know the parameter is zero-extended. Perform a load into LocVT,
99         // and use G_ASSERT_ZEXT to communicate that this was zero-extended from
100         // the parameter type. Move down to the parameter type using G_TRUNC.
101         MIRBuilder.buildTrunc(
102             ValVReg, MIRBuilder.buildAssertZExt(
103                          LocVT, MIRBuilder.buildLoad(LocVT, Addr, *MMO),
104                          RegTy.getScalarSizeInBits()));
105         return;
106       }
107 
108       if (LocInfo == CCValAssign::LocInfo::SExt) {
109         // Same as the ZExt case, but use G_ASSERT_SEXT instead.
110         MIRBuilder.buildTrunc(
111             ValVReg, MIRBuilder.buildAssertSExt(
112                          LocVT, MIRBuilder.buildLoad(LocVT, Addr, *MMO),
113                          RegTy.getScalarSizeInBits()));
114         return;
115       }
116     }
117 
118     // No extension information, or no extension necessary. Load into the
119     // incoming parameter type directly.
120     MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
121   }
122 
123   /// How the physical register gets marked varies between formal
124   /// parameters (it's a basic-block live-in), and a call instruction
125   /// (it's an implicit-def of the BL).
126   virtual void markPhysRegUsed(MCRegister PhysReg) = 0;
127 
128   uint64_t StackUsed;
129 };
130 
131 struct FormalArgHandler : public IncomingArgHandler {
132   FormalArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
133                    CCAssignFn *AssignFn)
134     : IncomingArgHandler(MIRBuilder, MRI, AssignFn) {}
135 
136   void markPhysRegUsed(MCRegister PhysReg) override {
137     MIRBuilder.getMRI()->addLiveIn(PhysReg);
138     MIRBuilder.getMBB().addLiveIn(PhysReg);
139   }
140 };
141 
142 struct CallReturnHandler : public IncomingArgHandler {
143   CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
144                     MachineInstrBuilder MIB, CCAssignFn *AssignFn)
145     : IncomingArgHandler(MIRBuilder, MRI, AssignFn), MIB(MIB) {}
146 
147   void markPhysRegUsed(MCRegister PhysReg) override {
148     MIB.addDef(PhysReg, RegState::Implicit);
149   }
150 
151   MachineInstrBuilder MIB;
152 };
153 
154 /// A special return arg handler for "returned" attribute arg calls.
155 struct ReturnedArgCallReturnHandler : public CallReturnHandler {
156   ReturnedArgCallReturnHandler(MachineIRBuilder &MIRBuilder,
157                                MachineRegisterInfo &MRI,
158                                MachineInstrBuilder MIB, CCAssignFn *AssignFn)
159       : CallReturnHandler(MIRBuilder, MRI, MIB, AssignFn) {}
160 
161   void markPhysRegUsed(MCRegister PhysReg) override {}
162 };
163 
164 struct OutgoingArgHandler : public CallLowering::OutgoingValueHandler {
165   OutgoingArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
166                      MachineInstrBuilder MIB, CCAssignFn *AssignFn,
167                      CCAssignFn *AssignFnVarArg, bool IsVarArg,
168                      bool IsTailCall = false, int FPDiff = 0)
169       : OutgoingValueHandler(MIRBuilder, MRI, AssignFn), MIB(MIB),
170         AssignFnVarArg(AssignFnVarArg), IsTailCall(IsTailCall), FPDiff(FPDiff),
171         StackSize(0), SPReg(0) {
172     MachineFunction &MF = MIRBuilder.getMF();
173     const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
174     bool IsWin =
175         Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
176     UseVarArgsCCForFixed = IsVarArg && IsWin;
177   }
178 
179   Register getStackAddress(uint64_t Size, int64_t Offset,
180                            MachinePointerInfo &MPO,
181                            ISD::ArgFlagsTy Flags) override {
182     MachineFunction &MF = MIRBuilder.getMF();
183     LLT p0 = LLT::pointer(0, 64);
184     LLT s64 = LLT::scalar(64);
185 
186     if (IsTailCall) {
187       assert(!Flags.isByVal() && "byval unhandled with tail calls");
188 
189       Offset += FPDiff;
190       int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
191       auto FIReg = MIRBuilder.buildFrameIndex(p0, FI);
192       MPO = MachinePointerInfo::getFixedStack(MF, FI);
193       return FIReg.getReg(0);
194     }
195 
196     if (!SPReg)
197       SPReg = MIRBuilder.buildCopy(p0, Register(AArch64::SP)).getReg(0);
198 
199     auto OffsetReg = MIRBuilder.buildConstant(s64, Offset);
200 
201     auto AddrReg = MIRBuilder.buildPtrAdd(p0, SPReg, OffsetReg);
202 
203     MPO = MachinePointerInfo::getStack(MF, Offset);
204     return AddrReg.getReg(0);
205   }
206 
207   void assignValueToReg(Register ValVReg, Register PhysReg,
208                         CCValAssign &VA) override {
209     MIB.addUse(PhysReg, RegState::Implicit);
210     Register ExtReg = extendRegister(ValVReg, VA);
211     MIRBuilder.buildCopy(PhysReg, ExtReg);
212   }
213 
214   void assignValueToAddress(Register ValVReg, Register Addr, uint64_t Size,
215                             MachinePointerInfo &MPO, CCValAssign &VA) override {
216     MachineFunction &MF = MIRBuilder.getMF();
217     auto MMO = MF.getMachineMemOperand(MPO, MachineMemOperand::MOStore, Size,
218                                        inferAlignFromPtrInfo(MF, MPO));
219     MIRBuilder.buildStore(ValVReg, Addr, *MMO);
220   }
221 
222   void assignValueToAddress(const CallLowering::ArgInfo &Arg, unsigned RegIndex,
223                             Register Addr, uint64_t Size,
224                             MachinePointerInfo &MPO, CCValAssign &VA) override {
225     unsigned MaxSize = Size * 8;
226     // For varargs, we always want to extend them to 8 bytes, in which case
227     // we disable setting a max.
228     if (!Arg.IsFixed)
229       MaxSize = 0;
230 
231     Register ValVReg = VA.getLocInfo() != CCValAssign::LocInfo::FPExt
232                            ? extendRegister(Arg.Regs[RegIndex], VA, MaxSize)
233                            : Arg.Regs[0];
234 
235     // If we extended we might need to adjust the MMO's Size.
236     const LLT RegTy = MRI.getType(ValVReg);
237     if (RegTy.getSizeInBytes() > Size)
238       Size = RegTy.getSizeInBytes();
239 
240     assignValueToAddress(ValVReg, Addr, Size, MPO, VA);
241   }
242 
243   bool assignArg(unsigned ValNo, MVT ValVT, MVT LocVT,
244                  CCValAssign::LocInfo LocInfo,
245                  const CallLowering::ArgInfo &Info,
246                  ISD::ArgFlagsTy Flags,
247                  CCState &State) override {
248     bool Res;
249     if (Info.IsFixed && !UseVarArgsCCForFixed)
250       Res = AssignFn(ValNo, ValVT, LocVT, LocInfo, Flags, State);
251     else
252       Res = AssignFnVarArg(ValNo, ValVT, LocVT, LocInfo, Flags, State);
253 
254     StackSize = State.getNextStackOffset();
255     return Res;
256   }
257 
258   MachineInstrBuilder MIB;
259   CCAssignFn *AssignFnVarArg;
260   bool IsTailCall;
261   bool UseVarArgsCCForFixed;
262 
263   /// For tail calls, the byte offset of the call's argument area from the
264   /// callee's. Unused elsewhere.
265   int FPDiff;
266   uint64_t StackSize;
267 
268   // Cache the SP register vreg if we need it more than once in this call site.
269   Register SPReg;
270 };
271 } // namespace
272 
273 static bool doesCalleeRestoreStack(CallingConv::ID CallConv, bool TailCallOpt) {
274   return CallConv == CallingConv::Fast && TailCallOpt;
275 }
276 
277 bool AArch64CallLowering::lowerReturn(MachineIRBuilder &MIRBuilder,
278                                       const Value *Val,
279                                       ArrayRef<Register> VRegs,
280                                       FunctionLoweringInfo &FLI,
281                                       Register SwiftErrorVReg) const {
282   auto MIB = MIRBuilder.buildInstrNoInsert(AArch64::RET_ReallyLR);
283   assert(((Val && !VRegs.empty()) || (!Val && VRegs.empty())) &&
284          "Return value without a vreg");
285 
286   bool Success = true;
287   if (!VRegs.empty()) {
288     MachineFunction &MF = MIRBuilder.getMF();
289     const Function &F = MF.getFunction();
290 
291     MachineRegisterInfo &MRI = MF.getRegInfo();
292     const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
293     CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(F.getCallingConv());
294     auto &DL = F.getParent()->getDataLayout();
295     LLVMContext &Ctx = Val->getType()->getContext();
296 
297     SmallVector<EVT, 4> SplitEVTs;
298     ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
299     assert(VRegs.size() == SplitEVTs.size() &&
300            "For each split Type there should be exactly one VReg.");
301 
302     SmallVector<ArgInfo, 8> SplitArgs;
303     CallingConv::ID CC = F.getCallingConv();
304 
305     for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
306       if (TLI.getNumRegistersForCallingConv(Ctx, CC, SplitEVTs[i]) > 1) {
307         LLVM_DEBUG(dbgs() << "Can't handle extended arg types which need split");
308         return false;
309       }
310 
311       Register CurVReg = VRegs[i];
312       ArgInfo CurArgInfo = ArgInfo{CurVReg, SplitEVTs[i].getTypeForEVT(Ctx)};
313       setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
314 
315       // i1 is a special case because SDAG i1 true is naturally zero extended
316       // when widened using ANYEXT. We need to do it explicitly here.
317       if (MRI.getType(CurVReg).getSizeInBits() == 1) {
318         CurVReg = MIRBuilder.buildZExt(LLT::scalar(8), CurVReg).getReg(0);
319       } else {
320         // Some types will need extending as specified by the CC.
321         MVT NewVT = TLI.getRegisterTypeForCallingConv(Ctx, CC, SplitEVTs[i]);
322         if (EVT(NewVT) != SplitEVTs[i]) {
323           unsigned ExtendOp = TargetOpcode::G_ANYEXT;
324           if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
325                                              Attribute::SExt))
326             ExtendOp = TargetOpcode::G_SEXT;
327           else if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
328                                                   Attribute::ZExt))
329             ExtendOp = TargetOpcode::G_ZEXT;
330 
331           LLT NewLLT(NewVT);
332           LLT OldLLT(MVT::getVT(CurArgInfo.Ty));
333           CurArgInfo.Ty = EVT(NewVT).getTypeForEVT(Ctx);
334           // Instead of an extend, we might have a vector type which needs
335           // padding with more elements, e.g. <2 x half> -> <4 x half>.
336           if (NewVT.isVector()) {
337             if (OldLLT.isVector()) {
338               if (NewLLT.getNumElements() > OldLLT.getNumElements()) {
339                 // We don't handle VA types which are not exactly twice the
340                 // size, but can easily be done in future.
341                 if (NewLLT.getNumElements() != OldLLT.getNumElements() * 2) {
342                   LLVM_DEBUG(dbgs() << "Outgoing vector ret has too many elts");
343                   return false;
344                 }
345                 auto Undef = MIRBuilder.buildUndef({OldLLT});
346                 CurVReg =
347                     MIRBuilder.buildMerge({NewLLT}, {CurVReg, Undef}).getReg(0);
348               } else {
349                 // Just do a vector extend.
350                 CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
351                               .getReg(0);
352               }
353             } else if (NewLLT.getNumElements() == 2) {
354               // We need to pad a <1 x S> type to <2 x S>. Since we don't have
355               // <1 x S> vector types in GISel we use a build_vector instead
356               // of a vector merge/concat.
357               auto Undef = MIRBuilder.buildUndef({OldLLT});
358               CurVReg =
359                   MIRBuilder
360                       .buildBuildVector({NewLLT}, {CurVReg, Undef.getReg(0)})
361                       .getReg(0);
362             } else {
363               LLVM_DEBUG(dbgs() << "Could not handle ret ty");
364               return false;
365             }
366           } else {
367             // If the split EVT was a <1 x T> vector, and NewVT is T, then we
368             // don't have to do anything since we don't distinguish between the
369             // two.
370             if (NewLLT != MRI.getType(CurVReg)) {
371               // A scalar extend.
372               CurVReg = MIRBuilder.buildInstr(ExtendOp, {NewLLT}, {CurVReg})
373                             .getReg(0);
374             }
375           }
376         }
377       }
378       if (CurVReg != CurArgInfo.Regs[0]) {
379         CurArgInfo.Regs[0] = CurVReg;
380         // Reset the arg flags after modifying CurVReg.
381         setArgFlags(CurArgInfo, AttributeList::ReturnIndex, DL, F);
382       }
383       splitToValueTypes(CurArgInfo, SplitArgs, DL, CC);
384     }
385 
386     OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFn, AssignFn,
387                                F.isVarArg());
388     Success =
389         handleAssignments(MIRBuilder, SplitArgs, Handler, CC, F.isVarArg());
390   }
391 
392   if (SwiftErrorVReg) {
393     MIB.addUse(AArch64::X21, RegState::Implicit);
394     MIRBuilder.buildCopy(AArch64::X21, SwiftErrorVReg);
395   }
396 
397   MIRBuilder.insertInstr(MIB);
398   return Success;
399 }
400 
401 /// Helper function to compute forwarded registers for musttail calls. Computes
402 /// the forwarded registers, sets MBB liveness, and emits COPY instructions that
403 /// can be used to save + restore registers later.
404 static void handleMustTailForwardedRegisters(MachineIRBuilder &MIRBuilder,
405                                              CCAssignFn *AssignFn) {
406   MachineBasicBlock &MBB = MIRBuilder.getMBB();
407   MachineFunction &MF = MIRBuilder.getMF();
408   MachineFrameInfo &MFI = MF.getFrameInfo();
409 
410   if (!MFI.hasMustTailInVarArgFunc())
411     return;
412 
413   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
414   const Function &F = MF.getFunction();
415   assert(F.isVarArg() && "Expected F to be vararg?");
416 
417   // Compute the set of forwarded registers. The rest are scratch.
418   SmallVector<CCValAssign, 16> ArgLocs;
419   CCState CCInfo(F.getCallingConv(), /*IsVarArg=*/true, MF, ArgLocs,
420                  F.getContext());
421   SmallVector<MVT, 2> RegParmTypes;
422   RegParmTypes.push_back(MVT::i64);
423   RegParmTypes.push_back(MVT::f128);
424 
425   // Later on, we can use this vector to restore the registers if necessary.
426   SmallVectorImpl<ForwardedRegister> &Forwards =
427       FuncInfo->getForwardedMustTailRegParms();
428   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, AssignFn);
429 
430   // Conservatively forward X8, since it might be used for an aggregate
431   // return.
432   if (!CCInfo.isAllocated(AArch64::X8)) {
433     Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
434     Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
435   }
436 
437   // Add the forwards to the MachineBasicBlock and MachineFunction.
438   for (const auto &F : Forwards) {
439     MBB.addLiveIn(F.PReg);
440     MIRBuilder.buildCopy(Register(F.VReg), Register(F.PReg));
441   }
442 }
443 
444 bool AArch64CallLowering::fallBackToDAGISel(const MachineFunction &MF) const {
445   auto &F = MF.getFunction();
446   if (isa<ScalableVectorType>(F.getReturnType()))
447     return true;
448   if (llvm::any_of(F.args(), [](const Argument &A) {
449         return isa<ScalableVectorType>(A.getType());
450       }))
451     return true;
452   const auto &ST = MF.getSubtarget<AArch64Subtarget>();
453   LLVM_DEBUG(dbgs() << "Falling back to SDAG because we don't support no-NEON");
454   if (!ST.hasNEON() || !ST.hasFPARMv8())
455     return true;
456   return false;
457 }
458 
459 bool AArch64CallLowering::lowerFormalArguments(
460     MachineIRBuilder &MIRBuilder, const Function &F,
461     ArrayRef<ArrayRef<Register>> VRegs, FunctionLoweringInfo &FLI) const {
462   MachineFunction &MF = MIRBuilder.getMF();
463   MachineBasicBlock &MBB = MIRBuilder.getMBB();
464   MachineRegisterInfo &MRI = MF.getRegInfo();
465   auto &DL = F.getParent()->getDataLayout();
466 
467   SmallVector<ArgInfo, 8> SplitArgs;
468   unsigned i = 0;
469   for (auto &Arg : F.args()) {
470     if (DL.getTypeStoreSize(Arg.getType()).isZero())
471       continue;
472 
473     ArgInfo OrigArg{VRegs[i], Arg};
474     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, F);
475 
476     splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv());
477     ++i;
478   }
479 
480   if (!MBB.empty())
481     MIRBuilder.setInstr(*MBB.begin());
482 
483   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
484   CCAssignFn *AssignFn =
485       TLI.CCAssignFnForCall(F.getCallingConv(), /*IsVarArg=*/false);
486 
487   FormalArgHandler Handler(MIRBuilder, MRI, AssignFn);
488   if (!handleAssignments(MIRBuilder, SplitArgs, Handler, F.getCallingConv(),
489                          F.isVarArg()))
490     return false;
491 
492   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
493   uint64_t StackOffset = Handler.StackUsed;
494   if (F.isVarArg()) {
495     auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
496     if (!Subtarget.isTargetDarwin()) {
497         // FIXME: we need to reimplement saveVarArgsRegisters from
498       // AArch64ISelLowering.
499       return false;
500     }
501 
502     // We currently pass all varargs at 8-byte alignment, or 4 in ILP32.
503     StackOffset = alignTo(Handler.StackUsed, Subtarget.isTargetILP32() ? 4 : 8);
504 
505     auto &MFI = MIRBuilder.getMF().getFrameInfo();
506     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
507   }
508 
509   if (doesCalleeRestoreStack(F.getCallingConv(),
510                              MF.getTarget().Options.GuaranteedTailCallOpt)) {
511     // We have a non-standard ABI, so why not make full use of the stack that
512     // we're going to pop? It must be aligned to 16 B in any case.
513     StackOffset = alignTo(StackOffset, 16);
514 
515     // If we're expected to restore the stack (e.g. fastcc), then we'll be
516     // adding a multiple of 16.
517     FuncInfo->setArgumentStackToRestore(StackOffset);
518 
519     // Our own callers will guarantee that the space is free by giving an
520     // aligned value to CALLSEQ_START.
521   }
522 
523   // When we tail call, we need to check if the callee's arguments
524   // will fit on the caller's stack. So, whenever we lower formal arguments,
525   // we should keep track of this information, since we might lower a tail call
526   // in this function later.
527   FuncInfo->setBytesInStackArgArea(StackOffset);
528 
529   auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
530   if (Subtarget.hasCustomCallingConv())
531     Subtarget.getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
532 
533   handleMustTailForwardedRegisters(MIRBuilder, AssignFn);
534 
535   // Move back to the end of the basic block.
536   MIRBuilder.setMBB(MBB);
537 
538   return true;
539 }
540 
541 /// Return true if the calling convention is one that we can guarantee TCO for.
542 static bool canGuaranteeTCO(CallingConv::ID CC) {
543   return CC == CallingConv::Fast;
544 }
545 
546 /// Return true if we might ever do TCO for calls with this calling convention.
547 static bool mayTailCallThisCC(CallingConv::ID CC) {
548   switch (CC) {
549   case CallingConv::C:
550   case CallingConv::PreserveMost:
551   case CallingConv::Swift:
552     return true;
553   default:
554     return canGuaranteeTCO(CC);
555   }
556 }
557 
558 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
559 /// CC.
560 static std::pair<CCAssignFn *, CCAssignFn *>
561 getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI) {
562   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
563 }
564 
565 bool AArch64CallLowering::doCallerAndCalleePassArgsTheSameWay(
566     CallLoweringInfo &Info, MachineFunction &MF,
567     SmallVectorImpl<ArgInfo> &InArgs) const {
568   const Function &CallerF = MF.getFunction();
569   CallingConv::ID CalleeCC = Info.CallConv;
570   CallingConv::ID CallerCC = CallerF.getCallingConv();
571 
572   // If the calling conventions match, then everything must be the same.
573   if (CalleeCC == CallerCC)
574     return true;
575 
576   // Check if the caller and callee will handle arguments in the same way.
577   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
578   CCAssignFn *CalleeAssignFnFixed;
579   CCAssignFn *CalleeAssignFnVarArg;
580   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
581       getAssignFnsForCC(CalleeCC, TLI);
582 
583   CCAssignFn *CallerAssignFnFixed;
584   CCAssignFn *CallerAssignFnVarArg;
585   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
586       getAssignFnsForCC(CallerCC, TLI);
587 
588   if (!resultsCompatible(Info, MF, InArgs, *CalleeAssignFnFixed,
589                          *CalleeAssignFnVarArg, *CallerAssignFnFixed,
590                          *CallerAssignFnVarArg))
591     return false;
592 
593   // Make sure that the caller and callee preserve all of the same registers.
594   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
595   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
596   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
597   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv()) {
598     TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
599     TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
600   }
601 
602   return TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved);
603 }
604 
605 bool AArch64CallLowering::areCalleeOutgoingArgsTailCallable(
606     CallLoweringInfo &Info, MachineFunction &MF,
607     SmallVectorImpl<ArgInfo> &OutArgs) const {
608   // If there are no outgoing arguments, then we are done.
609   if (OutArgs.empty())
610     return true;
611 
612   const Function &CallerF = MF.getFunction();
613   CallingConv::ID CalleeCC = Info.CallConv;
614   CallingConv::ID CallerCC = CallerF.getCallingConv();
615   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
616 
617   CCAssignFn *AssignFnFixed;
618   CCAssignFn *AssignFnVarArg;
619   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
620 
621   // We have outgoing arguments. Make sure that we can tail call with them.
622   SmallVector<CCValAssign, 16> OutLocs;
623   CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
624 
625   if (!analyzeArgInfo(OutInfo, OutArgs, *AssignFnFixed, *AssignFnVarArg)) {
626     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
627     return false;
628   }
629 
630   // Make sure that they can fit on the caller's stack.
631   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
632   if (OutInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) {
633     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
634     return false;
635   }
636 
637   // Verify that the parameters in callee-saved registers match.
638   // TODO: Port this over to CallLowering as general code once swiftself is
639   // supported.
640   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
641   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
642   MachineRegisterInfo &MRI = MF.getRegInfo();
643 
644   if (Info.IsVarArg) {
645     // Be conservative and disallow variadic memory operands to match SDAG's
646     // behaviour.
647     // FIXME: If the caller's calling convention is C, then we can
648     // potentially use its argument area. However, for cases like fastcc,
649     // we can't do anything.
650     for (unsigned i = 0; i < OutLocs.size(); ++i) {
651       auto &ArgLoc = OutLocs[i];
652       if (ArgLoc.isRegLoc())
653         continue;
654 
655       LLVM_DEBUG(
656           dbgs()
657           << "... Cannot tail call vararg function with stack arguments\n");
658       return false;
659     }
660   }
661 
662   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
663 }
664 
665 bool AArch64CallLowering::isEligibleForTailCallOptimization(
666     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
667     SmallVectorImpl<ArgInfo> &InArgs,
668     SmallVectorImpl<ArgInfo> &OutArgs) const {
669 
670   // Must pass all target-independent checks in order to tail call optimize.
671   if (!Info.IsTailCall)
672     return false;
673 
674   CallingConv::ID CalleeCC = Info.CallConv;
675   MachineFunction &MF = MIRBuilder.getMF();
676   const Function &CallerF = MF.getFunction();
677 
678   LLVM_DEBUG(dbgs() << "Attempting to lower call as tail call\n");
679 
680   if (Info.SwiftErrorVReg) {
681     // TODO: We should handle this.
682     // Note that this is also handled by the check for no outgoing arguments.
683     // Proactively disabling this though, because the swifterror handling in
684     // lowerCall inserts a COPY *after* the location of the call.
685     LLVM_DEBUG(dbgs() << "... Cannot handle tail calls with swifterror yet.\n");
686     return false;
687   }
688 
689   if (!mayTailCallThisCC(CalleeCC)) {
690     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
691     return false;
692   }
693 
694   // Byval parameters hand the function a pointer directly into the stack area
695   // we want to reuse during a tail call. Working around this *is* possible (see
696   // X86).
697   //
698   // FIXME: In AArch64ISelLowering, this isn't worked around. Can/should we try
699   // it?
700   //
701   // On Windows, "inreg" attributes signify non-aggregate indirect returns.
702   // In this case, it is necessary to save/restore X0 in the callee. Tail
703   // call opt interferes with this. So we disable tail call opt when the
704   // caller has an argument with "inreg" attribute.
705   //
706   // FIXME: Check whether the callee also has an "inreg" argument.
707   //
708   // When the caller has a swifterror argument, we don't want to tail call
709   // because would have to move into the swifterror register before the
710   // tail call.
711   if (any_of(CallerF.args(), [](const Argument &A) {
712         return A.hasByValAttr() || A.hasInRegAttr() || A.hasSwiftErrorAttr();
713       })) {
714     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval, "
715                          "inreg, or swifterror arguments\n");
716     return false;
717   }
718 
719   // Externally-defined functions with weak linkage should not be
720   // tail-called on AArch64 when the OS does not support dynamic
721   // pre-emption of symbols, as the AAELF spec requires normal calls
722   // to undefined weak functions to be replaced with a NOP or jump to the
723   // next instruction. The behaviour of branch instructions in this
724   // situation (as used for tail calls) is implementation-defined, so we
725   // cannot rely on the linker replacing the tail call with a return.
726   if (Info.Callee.isGlobal()) {
727     const GlobalValue *GV = Info.Callee.getGlobal();
728     const Triple &TT = MF.getTarget().getTargetTriple();
729     if (GV->hasExternalWeakLinkage() &&
730         (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
731          TT.isOSBinFormatMachO())) {
732       LLVM_DEBUG(dbgs() << "... Cannot tail call externally-defined function "
733                            "with weak linkage for this OS.\n");
734       return false;
735     }
736   }
737 
738   // If we have -tailcallopt, then we're done.
739   if (MF.getTarget().Options.GuaranteedTailCallOpt)
740     return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();
741 
742   // We don't have -tailcallopt, so we're allowed to change the ABI (sibcall).
743   // Try to find cases where we can do that.
744 
745   // I want anyone implementing a new calling convention to think long and hard
746   // about this assert.
747   assert((!Info.IsVarArg || CalleeCC == CallingConv::C) &&
748          "Unexpected variadic calling convention");
749 
750   // Verify that the incoming and outgoing arguments from the callee are
751   // safe to tail call.
752   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
753     LLVM_DEBUG(
754         dbgs()
755         << "... Caller and callee have incompatible calling conventions.\n");
756     return false;
757   }
758 
759   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
760     return false;
761 
762   LLVM_DEBUG(
763       dbgs() << "... Call is eligible for tail call optimization.\n");
764   return true;
765 }
766 
767 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
768                               bool IsTailCall) {
769   if (!IsTailCall)
770     return IsIndirect ? getBLRCallOpcode(CallerF) : (unsigned)AArch64::BL;
771 
772   if (!IsIndirect)
773     return AArch64::TCRETURNdi;
774 
775   // When BTI is enabled, we need to use TCRETURNriBTI to make sure that we use
776   // x16 or x17.
777   if (CallerF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement())
778     return AArch64::TCRETURNriBTI;
779 
780   return AArch64::TCRETURNri;
781 }
782 
783 static const uint32_t *
784 getMaskForArgs(SmallVectorImpl<AArch64CallLowering::ArgInfo> &OutArgs,
785                AArch64CallLowering::CallLoweringInfo &Info,
786                const AArch64RegisterInfo &TRI, MachineFunction &MF) {
787   const uint32_t *Mask;
788   if (!OutArgs.empty() && OutArgs[0].Flags[0].isReturned()) {
789     // For 'this' returns, use the X0-preserving mask if applicable
790     Mask = TRI.getThisReturnPreservedMask(MF, Info.CallConv);
791     if (!Mask) {
792       OutArgs[0].Flags[0].setReturned(false);
793       Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
794     }
795   } else {
796     Mask = TRI.getCallPreservedMask(MF, Info.CallConv);
797   }
798   return Mask;
799 }
800 
801 bool AArch64CallLowering::lowerTailCall(
802     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
803     SmallVectorImpl<ArgInfo> &OutArgs) const {
804   MachineFunction &MF = MIRBuilder.getMF();
805   const Function &F = MF.getFunction();
806   MachineRegisterInfo &MRI = MF.getRegInfo();
807   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
808   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
809 
810   // True when we're tail calling, but without -tailcallopt.
811   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
812 
813   // TODO: Right now, regbankselect doesn't know how to handle the rtcGPR64
814   // register class. Until we can do that, we should fall back here.
815   if (MF.getInfo<AArch64FunctionInfo>()->branchTargetEnforcement()) {
816     LLVM_DEBUG(
817         dbgs() << "Cannot lower indirect tail calls with BTI enabled yet.\n");
818     return false;
819   }
820 
821   // Find out which ABI gets to decide where things go.
822   CallingConv::ID CalleeCC = Info.CallConv;
823   CCAssignFn *AssignFnFixed;
824   CCAssignFn *AssignFnVarArg;
825   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
826 
827   MachineInstrBuilder CallSeqStart;
828   if (!IsSibCall)
829     CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
830 
831   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
832   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
833   MIB.add(Info.Callee);
834 
835   // Byte offset for the tail call. When we are sibcalling, this will always
836   // be 0.
837   MIB.addImm(0);
838 
839   // Tell the call which registers are clobbered.
840   auto TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
841   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
842   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv())
843     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
844   MIB.addRegMask(Mask);
845 
846   if (TRI->isAnyArgRegReserved(MF))
847     TRI->emitReservedArgRegCallError(MF);
848 
849   // FPDiff is the byte offset of the call's argument area from the callee's.
850   // Stores to callee stack arguments will be placed in FixedStackSlots offset
851   // by this amount for a tail call. In a sibling call it must be 0 because the
852   // caller will deallocate the entire stack and the callee still expects its
853   // arguments to begin at SP+0.
854   int FPDiff = 0;
855 
856   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
857   // by -tailcallopt. For sibcalls, the memory operands for the call are
858   // already available in the caller's incoming argument space.
859   unsigned NumBytes = 0;
860   if (!IsSibCall) {
861     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
862     // before handling assignments, because FPDiff must be known for memory
863     // arguments.
864     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
865     SmallVector<CCValAssign, 16> OutLocs;
866     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
867     analyzeArgInfo(OutInfo, OutArgs, *AssignFnFixed, *AssignFnVarArg);
868 
869     // The callee will pop the argument stack as a tail call. Thus, we must
870     // keep it 16-byte aligned.
871     NumBytes = alignTo(OutInfo.getNextStackOffset(), 16);
872 
873     // FPDiff will be negative if this tail call requires more space than we
874     // would automatically have in our incoming argument space. Positive if we
875     // actually shrink the stack.
876     FPDiff = NumReusableBytes - NumBytes;
877 
878     // The stack pointer must be 16-byte aligned at all times it's used for a
879     // memory operation, which in practice means at *all* times and in
880     // particular across call boundaries. Therefore our own arguments started at
881     // a 16-byte aligned SP and the delta applied for the tail call should
882     // satisfy the same constraint.
883     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
884   }
885 
886   const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
887 
888   // Do the actual argument marshalling.
889   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFnFixed,
890                              AssignFnVarArg, Info.IsVarArg, true, FPDiff);
891   if (!handleAssignments(MIRBuilder, OutArgs, Handler, CalleeCC, Info.IsVarArg))
892     return false;
893 
894   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
895 
896   if (Info.IsVarArg && Info.IsMustTailCall) {
897     // Now we know what's being passed to the function. Add uses to the call for
898     // the forwarded registers that we *aren't* passing as parameters. This will
899     // preserve the copies we build earlier.
900     for (const auto &F : Forwards) {
901       Register ForwardedReg = F.PReg;
902       // If the register is already passed, or aliases a register which is
903       // already being passed, then skip it.
904       if (any_of(MIB->uses(), [&ForwardedReg, &TRI](const MachineOperand &Use) {
905             if (!Use.isReg())
906               return false;
907             return TRI->regsOverlap(Use.getReg(), ForwardedReg);
908           }))
909         continue;
910 
911       // We aren't passing it already, so we should add it to the call.
912       MIRBuilder.buildCopy(ForwardedReg, Register(F.VReg));
913       MIB.addReg(ForwardedReg, RegState::Implicit);
914     }
915   }
916 
917   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
918   // sequence start and end here.
919   if (!IsSibCall) {
920     MIB->getOperand(1).setImm(FPDiff);
921     CallSeqStart.addImm(NumBytes).addImm(0);
922     // End the call sequence *before* emitting the call. Normally, we would
923     // tidy the frame up after the call. However, here, we've laid out the
924     // parameters so that when SP is reset, they will be in the correct
925     // location.
926     MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP).addImm(NumBytes).addImm(0);
927   }
928 
929   // Now we can add the actual call instruction to the correct basic block.
930   MIRBuilder.insertInstr(MIB);
931 
932   // If Callee is a reg, since it is used by a target specific instruction,
933   // it must have a register class matching the constraint of that instruction.
934   if (Info.Callee.isReg())
935     constrainOperandRegClass(MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
936                              *MF.getSubtarget().getRegBankInfo(), *MIB,
937                              MIB->getDesc(), Info.Callee, 0);
938 
939   MF.getFrameInfo().setHasTailCall();
940   Info.LoweredTailCall = true;
941   return true;
942 }
943 
944 bool AArch64CallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
945                                     CallLoweringInfo &Info) const {
946   MachineFunction &MF = MIRBuilder.getMF();
947   const Function &F = MF.getFunction();
948   MachineRegisterInfo &MRI = MF.getRegInfo();
949   auto &DL = F.getParent()->getDataLayout();
950   const AArch64TargetLowering &TLI = *getTLI<AArch64TargetLowering>();
951 
952   SmallVector<ArgInfo, 8> OutArgs;
953   for (auto &OrigArg : Info.OrigArgs) {
954     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
955     // AAPCS requires that we zero-extend i1 to 8 bits by the caller.
956     if (OrigArg.Ty->isIntegerTy(1))
957       OutArgs.back().Flags[0].setZExt();
958   }
959 
960   SmallVector<ArgInfo, 8> InArgs;
961   if (!Info.OrigRet.Ty->isVoidTy())
962     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
963 
964   // If we can lower as a tail call, do that instead.
965   bool CanTailCallOpt =
966       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
967 
968   // We must emit a tail call if we have musttail.
969   if (Info.IsMustTailCall && !CanTailCallOpt) {
970     // There are types of incoming/outgoing arguments we can't handle yet, so
971     // it doesn't make sense to actually die here like in ISelLowering. Instead,
972     // fall back to SelectionDAG and let it try to handle this.
973     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
974     return false;
975   }
976 
977   if (CanTailCallOpt)
978     return lowerTailCall(MIRBuilder, Info, OutArgs);
979 
980   // Find out which ABI gets to decide where things go.
981   CCAssignFn *AssignFnFixed;
982   CCAssignFn *AssignFnVarArg;
983   std::tie(AssignFnFixed, AssignFnVarArg) =
984       getAssignFnsForCC(Info.CallConv, TLI);
985 
986   MachineInstrBuilder CallSeqStart;
987   CallSeqStart = MIRBuilder.buildInstr(AArch64::ADJCALLSTACKDOWN);
988 
989   // Create a temporarily-floating call instruction so we can add the implicit
990   // uses of arg registers.
991   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
992 
993   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
994   MIB.add(Info.Callee);
995 
996   // Tell the call which registers are clobbered.
997   const uint32_t *Mask;
998   const auto *TRI = MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
999 
1000   // Do the actual argument marshalling.
1001   OutgoingArgHandler Handler(MIRBuilder, MRI, MIB, AssignFnFixed,
1002                              AssignFnVarArg, Info.IsVarArg, false);
1003   if (!handleAssignments(MIRBuilder, OutArgs, Handler, Info.CallConv,
1004                          Info.IsVarArg))
1005     return false;
1006 
1007   Mask = getMaskForArgs(OutArgs, Info, *TRI, MF);
1008 
1009   if (MF.getSubtarget<AArch64Subtarget>().hasCustomCallingConv())
1010     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
1011   MIB.addRegMask(Mask);
1012 
1013   if (TRI->isAnyArgRegReserved(MF))
1014     TRI->emitReservedArgRegCallError(MF);
1015 
1016   // Now we can add the actual call instruction to the correct basic block.
1017   MIRBuilder.insertInstr(MIB);
1018 
1019   // If Callee is a reg, since it is used by a target specific
1020   // instruction, it must have a register class matching the
1021   // constraint of that instruction.
1022   if (Info.Callee.isReg())
1023     constrainOperandRegClass(MF, *TRI, MRI, *MF.getSubtarget().getInstrInfo(),
1024                              *MF.getSubtarget().getRegBankInfo(), *MIB,
1025                              MIB->getDesc(), Info.Callee, 0);
1026 
1027   // Finally we can copy the returned value back into its virtual-register. In
1028   // symmetry with the arguments, the physical register must be an
1029   // implicit-define of the call instruction.
1030   if (!Info.OrigRet.Ty->isVoidTy()) {
1031     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv);
1032     CallReturnHandler Handler(MIRBuilder, MRI, MIB, RetAssignFn);
1033     bool UsingReturnedArg =
1034         !OutArgs.empty() && OutArgs[0].Flags[0].isReturned();
1035     ReturnedArgCallReturnHandler ReturnedArgHandler(MIRBuilder, MRI, MIB,
1036                                                     RetAssignFn);
1037     if (!handleAssignments(MIRBuilder, InArgs,
1038                            UsingReturnedArg ? ReturnedArgHandler : Handler,
1039                            Info.CallConv, Info.IsVarArg,
1040                            UsingReturnedArg ? OutArgs[0].Regs[0] : Register()))
1041       return false;
1042   }
1043 
1044   if (Info.SwiftErrorVReg) {
1045     MIB.addDef(AArch64::X21, RegState::Implicit);
1046     MIRBuilder.buildCopy(Info.SwiftErrorVReg, Register(AArch64::X21));
1047   }
1048 
1049   uint64_t CalleePopBytes =
1050       doesCalleeRestoreStack(Info.CallConv,
1051                              MF.getTarget().Options.GuaranteedTailCallOpt)
1052           ? alignTo(Handler.StackSize, 16)
1053           : 0;
1054 
1055   CallSeqStart.addImm(Handler.StackSize).addImm(0);
1056   MIRBuilder.buildInstr(AArch64::ADJCALLSTACKUP)
1057       .addImm(Handler.StackSize)
1058       .addImm(CalleePopBytes);
1059 
1060   return true;
1061 }
1062 
1063 bool AArch64CallLowering::isTypeIsValidForThisReturn(EVT Ty) const {
1064   return Ty.getSizeInBits() == 64;
1065 }
1066