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