AArch64CallLowering.cpp 39 KB

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