AArch64CallLowering.cpp 49 KB

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