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