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