xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/CallLowering.cpp (revision 35c63d66aaae65a7004d94e0a6668ff19612ba5e)
1 //===-- lib/CodeGen/GlobalISel/CallLowering.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 some simple delegations needed for call lowering.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/Analysis.h"
15 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
16 #include "llvm/CodeGen/GlobalISel/Utils.h"
17 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
18 #include "llvm/CodeGen/MachineOperand.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 
26 #define DEBUG_TYPE "call-lowering"
27 
28 using namespace llvm;
29 
30 void CallLowering::anchor() {}
31 
32 bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, ImmutableCallSite CS,
33                              ArrayRef<Register> ResRegs,
34                              ArrayRef<ArrayRef<Register>> ArgRegs,
35                              Register SwiftErrorVReg,
36                              std::function<unsigned()> GetCalleeReg) const {
37   CallLoweringInfo Info;
38   auto &DL = CS.getParent()->getParent()->getParent()->getDataLayout();
39 
40   // First step is to marshall all the function's parameters into the correct
41   // physregs and memory locations. Gather the sequence of argument types that
42   // we'll pass to the assigner function.
43   unsigned i = 0;
44   unsigned NumFixedArgs = CS.getFunctionType()->getNumParams();
45   for (auto &Arg : CS.args()) {
46     ArgInfo OrigArg{ArgRegs[i], Arg->getType(), ISD::ArgFlagsTy{},
47                     i < NumFixedArgs};
48     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CS);
49     Info.OrigArgs.push_back(OrigArg);
50     ++i;
51   }
52 
53   if (const Function *F = CS.getCalledFunction())
54     Info.Callee = MachineOperand::CreateGA(F, 0);
55   else {
56     // Try looking through a bitcast from one function type to another.
57     // Commonly happens with calls to objc_msgSend().
58     const Value *CalleeV = CS.getCalledValue();
59     if (auto *BC = dyn_cast<ConstantExpr>(CalleeV)) {
60       if (const auto *F = dyn_cast<Function>(BC->getOperand(0))) {
61         Info.Callee = MachineOperand::CreateGA(F, 0);
62       }
63     } else {
64       Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false);
65     }
66   }
67 
68   Info.OrigRet = ArgInfo{ResRegs, CS.getType(), ISD::ArgFlagsTy{}};
69   if (!Info.OrigRet.Ty->isVoidTy())
70     setArgFlags(Info.OrigRet, AttributeList::ReturnIndex, DL, CS);
71 
72   Info.KnownCallees =
73       CS.getInstruction()->getMetadata(LLVMContext::MD_callees);
74   Info.CallConv = CS.getCallingConv();
75   Info.SwiftErrorVReg = SwiftErrorVReg;
76   Info.IsMustTailCall = CS.isMustTailCall();
77   Info.IsTailCall = CS.isTailCall() &&
78                     isInTailCallPosition(CS, MIRBuilder.getMF().getTarget()) &&
79                     (MIRBuilder.getMF()
80                          .getFunction()
81                          .getFnAttribute("disable-tail-calls")
82                          .getValueAsString() != "true");
83   Info.IsVarArg = CS.getFunctionType()->isVarArg();
84   return lowerCall(MIRBuilder, Info);
85 }
86 
87 template <typename FuncInfoTy>
88 void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx,
89                                const DataLayout &DL,
90                                const FuncInfoTy &FuncInfo) const {
91   auto &Flags = Arg.Flags[0];
92   const AttributeList &Attrs = FuncInfo.getAttributes();
93   if (Attrs.hasAttribute(OpIdx, Attribute::ZExt))
94     Flags.setZExt();
95   if (Attrs.hasAttribute(OpIdx, Attribute::SExt))
96     Flags.setSExt();
97   if (Attrs.hasAttribute(OpIdx, Attribute::InReg))
98     Flags.setInReg();
99   if (Attrs.hasAttribute(OpIdx, Attribute::StructRet))
100     Flags.setSRet();
101   if (Attrs.hasAttribute(OpIdx, Attribute::SwiftSelf))
102     Flags.setSwiftSelf();
103   if (Attrs.hasAttribute(OpIdx, Attribute::SwiftError))
104     Flags.setSwiftError();
105   if (Attrs.hasAttribute(OpIdx, Attribute::ByVal))
106     Flags.setByVal();
107   if (Attrs.hasAttribute(OpIdx, Attribute::InAlloca))
108     Flags.setInAlloca();
109 
110   if (Flags.isByVal() || Flags.isInAlloca()) {
111     Type *ElementTy = cast<PointerType>(Arg.Ty)->getElementType();
112 
113     auto Ty = Attrs.getAttribute(OpIdx, Attribute::ByVal).getValueAsType();
114     Flags.setByValSize(DL.getTypeAllocSize(Ty ? Ty : ElementTy));
115 
116     // For ByVal, alignment should be passed from FE.  BE will guess if
117     // this info is not there but there are cases it cannot get right.
118     unsigned FrameAlign;
119     if (FuncInfo.getParamAlignment(OpIdx - 2))
120       FrameAlign = FuncInfo.getParamAlignment(OpIdx - 2);
121     else
122       FrameAlign = getTLI()->getByValTypeAlignment(ElementTy, DL);
123     Flags.setByValAlign(Align(FrameAlign));
124   }
125   if (Attrs.hasAttribute(OpIdx, Attribute::Nest))
126     Flags.setNest();
127   Flags.setOrigAlign(Align(DL.getABITypeAlignment(Arg.Ty)));
128 }
129 
130 template void
131 CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
132                                     const DataLayout &DL,
133                                     const Function &FuncInfo) const;
134 
135 template void
136 CallLowering::setArgFlags<CallInst>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
137                                     const DataLayout &DL,
138                                     const CallInst &FuncInfo) const;
139 
140 Register CallLowering::packRegs(ArrayRef<Register> SrcRegs, Type *PackedTy,
141                                 MachineIRBuilder &MIRBuilder) const {
142   assert(SrcRegs.size() > 1 && "Nothing to pack");
143 
144   const DataLayout &DL = MIRBuilder.getMF().getDataLayout();
145   MachineRegisterInfo *MRI = MIRBuilder.getMRI();
146 
147   LLT PackedLLT = getLLTForType(*PackedTy, DL);
148 
149   SmallVector<LLT, 8> LLTs;
150   SmallVector<uint64_t, 8> Offsets;
151   computeValueLLTs(DL, *PackedTy, LLTs, &Offsets);
152   assert(LLTs.size() == SrcRegs.size() && "Regs / types mismatch");
153 
154   Register Dst = MRI->createGenericVirtualRegister(PackedLLT);
155   MIRBuilder.buildUndef(Dst);
156   for (unsigned i = 0; i < SrcRegs.size(); ++i) {
157     Register NewDst = MRI->createGenericVirtualRegister(PackedLLT);
158     MIRBuilder.buildInsert(NewDst, Dst, SrcRegs[i], Offsets[i]);
159     Dst = NewDst;
160   }
161 
162   return Dst;
163 }
164 
165 void CallLowering::unpackRegs(ArrayRef<Register> DstRegs, Register SrcReg,
166                               Type *PackedTy,
167                               MachineIRBuilder &MIRBuilder) const {
168   assert(DstRegs.size() > 1 && "Nothing to unpack");
169 
170   const DataLayout &DL = MIRBuilder.getMF().getDataLayout();
171 
172   SmallVector<LLT, 8> LLTs;
173   SmallVector<uint64_t, 8> Offsets;
174   computeValueLLTs(DL, *PackedTy, LLTs, &Offsets);
175   assert(LLTs.size() == DstRegs.size() && "Regs / types mismatch");
176 
177   for (unsigned i = 0; i < DstRegs.size(); ++i)
178     MIRBuilder.buildExtract(DstRegs[i], SrcReg, Offsets[i]);
179 }
180 
181 bool CallLowering::handleAssignments(MachineIRBuilder &MIRBuilder,
182                                      SmallVectorImpl<ArgInfo> &Args,
183                                      ValueHandler &Handler) const {
184   MachineFunction &MF = MIRBuilder.getMF();
185   const Function &F = MF.getFunction();
186   SmallVector<CCValAssign, 16> ArgLocs;
187   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
188   return handleAssignments(CCInfo, ArgLocs, MIRBuilder, Args, Handler);
189 }
190 
191 bool CallLowering::handleAssignments(CCState &CCInfo,
192                                      SmallVectorImpl<CCValAssign> &ArgLocs,
193                                      MachineIRBuilder &MIRBuilder,
194                                      SmallVectorImpl<ArgInfo> &Args,
195                                      ValueHandler &Handler) const {
196   MachineFunction &MF = MIRBuilder.getMF();
197   const Function &F = MF.getFunction();
198   const DataLayout &DL = F.getParent()->getDataLayout();
199 
200   unsigned NumArgs = Args.size();
201   for (unsigned i = 0; i != NumArgs; ++i) {
202     MVT CurVT = MVT::getVT(Args[i].Ty);
203     if (Handler.assignArg(i, CurVT, CurVT, CCValAssign::Full, Args[i],
204                           Args[i].Flags[0], CCInfo)) {
205       if (!CurVT.isValid())
206         return false;
207       MVT NewVT = TLI->getRegisterTypeForCallingConv(
208           F.getContext(), F.getCallingConv(), EVT(CurVT));
209 
210       // If we need to split the type over multiple regs, check it's a scenario
211       // we currently support.
212       unsigned NumParts = TLI->getNumRegistersForCallingConv(
213           F.getContext(), F.getCallingConv(), CurVT);
214       if (NumParts > 1) {
215         // For now only handle exact splits.
216         if (NewVT.getSizeInBits() * NumParts != CurVT.getSizeInBits())
217           return false;
218       }
219 
220       // For incoming arguments (physregs to vregs), we could have values in
221       // physregs (or memlocs) which we want to extract and copy to vregs.
222       // During this, we might have to deal with the LLT being split across
223       // multiple regs, so we have to record this information for later.
224       //
225       // If we have outgoing args, then we have the opposite case. We have a
226       // vreg with an LLT which we want to assign to a physical location, and
227       // we might have to record that the value has to be split later.
228       if (Handler.isIncomingArgumentHandler()) {
229         if (NumParts == 1) {
230           // Try to use the register type if we couldn't assign the VT.
231           if (Handler.assignArg(i, NewVT, NewVT, CCValAssign::Full, Args[i],
232                                 Args[i].Flags[0], CCInfo))
233             return false;
234         } else {
235           // We're handling an incoming arg which is split over multiple regs.
236           // E.g. passing an s128 on AArch64.
237           ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
238           Args[i].OrigRegs.push_back(Args[i].Regs[0]);
239           Args[i].Regs.clear();
240           Args[i].Flags.clear();
241           LLT NewLLT = getLLTForMVT(NewVT);
242           // For each split register, create and assign a vreg that will store
243           // the incoming component of the larger value. These will later be
244           // merged to form the final vreg.
245           for (unsigned Part = 0; Part < NumParts; ++Part) {
246             Register Reg =
247                 MIRBuilder.getMRI()->createGenericVirtualRegister(NewLLT);
248             ISD::ArgFlagsTy Flags = OrigFlags;
249             if (Part == 0) {
250               Flags.setSplit();
251             } else {
252               Flags.setOrigAlign(Align(1));
253               if (Part == NumParts - 1)
254                 Flags.setSplitEnd();
255             }
256             Args[i].Regs.push_back(Reg);
257             Args[i].Flags.push_back(Flags);
258             if (Handler.assignArg(i + Part, NewVT, NewVT, CCValAssign::Full,
259                                   Args[i], Args[i].Flags[Part], CCInfo)) {
260               // Still couldn't assign this smaller part type for some reason.
261               return false;
262             }
263           }
264         }
265       } else {
266         // Handling an outgoing arg that might need to be split.
267         if (NumParts < 2)
268           return false; // Don't know how to deal with this type combination.
269 
270         // This type is passed via multiple registers in the calling convention.
271         // We need to extract the individual parts.
272         Register LargeReg = Args[i].Regs[0];
273         LLT SmallTy = LLT::scalar(NewVT.getSizeInBits());
274         auto Unmerge = MIRBuilder.buildUnmerge(SmallTy, LargeReg);
275         assert(Unmerge->getNumOperands() == NumParts + 1);
276         ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
277         // We're going to replace the regs and flags with the split ones.
278         Args[i].Regs.clear();
279         Args[i].Flags.clear();
280         for (unsigned PartIdx = 0; PartIdx < NumParts; ++PartIdx) {
281           ISD::ArgFlagsTy Flags = OrigFlags;
282           if (PartIdx == 0) {
283             Flags.setSplit();
284           } else {
285             Flags.setOrigAlign(Align(1));
286             if (PartIdx == NumParts - 1)
287               Flags.setSplitEnd();
288           }
289           Args[i].Regs.push_back(Unmerge.getReg(PartIdx));
290           Args[i].Flags.push_back(Flags);
291           if (Handler.assignArg(i + PartIdx, NewVT, NewVT, CCValAssign::Full,
292                                 Args[i], Args[i].Flags[PartIdx], CCInfo))
293             return false;
294         }
295       }
296     }
297   }
298 
299   for (unsigned i = 0, e = Args.size(), j = 0; i != e; ++i, ++j) {
300     assert(j < ArgLocs.size() && "Skipped too many arg locs");
301 
302     CCValAssign &VA = ArgLocs[j];
303     assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
304 
305     if (VA.needsCustom()) {
306       j += Handler.assignCustomValue(Args[i], makeArrayRef(ArgLocs).slice(j));
307       continue;
308     }
309 
310     // FIXME: Pack registers if we have more than one.
311     Register ArgReg = Args[i].Regs[0];
312 
313     MVT OrigVT = MVT::getVT(Args[i].Ty);
314     MVT VAVT = VA.getValVT();
315     if (VA.isRegLoc()) {
316       if (Handler.isIncomingArgumentHandler() && VAVT != OrigVT) {
317         if (VAVT.getSizeInBits() < OrigVT.getSizeInBits()) {
318           // Expected to be multiple regs for a single incoming arg.
319           unsigned NumArgRegs = Args[i].Regs.size();
320           if (NumArgRegs < 2)
321             return false;
322 
323           assert((j + (NumArgRegs - 1)) < ArgLocs.size() &&
324                  "Too many regs for number of args");
325           for (unsigned Part = 0; Part < NumArgRegs; ++Part) {
326             // There should be Regs.size() ArgLocs per argument.
327             VA = ArgLocs[j + Part];
328             Handler.assignValueToReg(Args[i].Regs[Part], VA.getLocReg(), VA);
329           }
330           j += NumArgRegs - 1;
331           // Merge the split registers into the expected larger result vreg
332           // of the original call.
333           MIRBuilder.buildMerge(Args[i].OrigRegs[0], Args[i].Regs);
334           continue;
335         }
336         const LLT VATy(VAVT);
337         Register NewReg =
338             MIRBuilder.getMRI()->createGenericVirtualRegister(VATy);
339         Handler.assignValueToReg(NewReg, VA.getLocReg(), VA);
340         // If it's a vector type, we either need to truncate the elements
341         // or do an unmerge to get the lower block of elements.
342         if (VATy.isVector() &&
343             VATy.getNumElements() > OrigVT.getVectorNumElements()) {
344           const LLT OrigTy(OrigVT);
345           // Just handle the case where the VA type is 2 * original type.
346           if (VATy.getNumElements() != OrigVT.getVectorNumElements() * 2) {
347             LLVM_DEBUG(dbgs()
348                        << "Incoming promoted vector arg has too many elts");
349             return false;
350           }
351           auto Unmerge = MIRBuilder.buildUnmerge({OrigTy, OrigTy}, {NewReg});
352           MIRBuilder.buildCopy(ArgReg, Unmerge.getReg(0));
353         } else {
354           MIRBuilder.buildTrunc(ArgReg, {NewReg}).getReg(0);
355         }
356       } else if (!Handler.isIncomingArgumentHandler()) {
357         assert((j + (Args[i].Regs.size() - 1)) < ArgLocs.size() &&
358                "Too many regs for number of args");
359         // This is an outgoing argument that might have been split.
360         for (unsigned Part = 0; Part < Args[i].Regs.size(); ++Part) {
361           // There should be Regs.size() ArgLocs per argument.
362           VA = ArgLocs[j + Part];
363           Handler.assignValueToReg(Args[i].Regs[Part], VA.getLocReg(), VA);
364         }
365         j += Args[i].Regs.size() - 1;
366       } else {
367         Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
368       }
369     } else if (VA.isMemLoc()) {
370       // Don't currently support loading/storing a type that needs to be split
371       // to the stack. Should be easy, just not implemented yet.
372       if (Args[i].Regs.size() > 1) {
373         LLVM_DEBUG(
374             dbgs()
375             << "Load/store a split arg to/from the stack not implemented yet");
376         return false;
377       }
378       MVT VT = MVT::getVT(Args[i].Ty);
379       unsigned Size = VT == MVT::iPTR ? DL.getPointerSize()
380                                       : alignTo(VT.getSizeInBits(), 8) / 8;
381       unsigned Offset = VA.getLocMemOffset();
382       MachinePointerInfo MPO;
383       Register StackAddr = Handler.getStackAddress(Size, Offset, MPO);
384       Handler.assignValueToAddress(ArgReg, StackAddr, Size, MPO, VA);
385     } else {
386       // FIXME: Support byvals and other weirdness
387       return false;
388     }
389   }
390   return true;
391 }
392 
393 bool CallLowering::analyzeArgInfo(CCState &CCState,
394                                   SmallVectorImpl<ArgInfo> &Args,
395                                   CCAssignFn &AssignFnFixed,
396                                   CCAssignFn &AssignFnVarArg) const {
397   for (unsigned i = 0, e = Args.size(); i < e; ++i) {
398     MVT VT = MVT::getVT(Args[i].Ty);
399     CCAssignFn &Fn = Args[i].IsFixed ? AssignFnFixed : AssignFnVarArg;
400     if (Fn(i, VT, VT, CCValAssign::Full, Args[i].Flags[0], CCState)) {
401       // Bail out on anything we can't handle.
402       LLVM_DEBUG(dbgs() << "Cannot analyze " << EVT(VT).getEVTString()
403                         << " (arg number = " << i << "\n");
404       return false;
405     }
406   }
407   return true;
408 }
409 
410 bool CallLowering::resultsCompatible(CallLoweringInfo &Info,
411                                      MachineFunction &MF,
412                                      SmallVectorImpl<ArgInfo> &InArgs,
413                                      CCAssignFn &CalleeAssignFnFixed,
414                                      CCAssignFn &CalleeAssignFnVarArg,
415                                      CCAssignFn &CallerAssignFnFixed,
416                                      CCAssignFn &CallerAssignFnVarArg) const {
417   const Function &F = MF.getFunction();
418   CallingConv::ID CalleeCC = Info.CallConv;
419   CallingConv::ID CallerCC = F.getCallingConv();
420 
421   if (CallerCC == CalleeCC)
422     return true;
423 
424   SmallVector<CCValAssign, 16> ArgLocs1;
425   CCState CCInfo1(CalleeCC, false, MF, ArgLocs1, F.getContext());
426   if (!analyzeArgInfo(CCInfo1, InArgs, CalleeAssignFnFixed,
427                       CalleeAssignFnVarArg))
428     return false;
429 
430   SmallVector<CCValAssign, 16> ArgLocs2;
431   CCState CCInfo2(CallerCC, false, MF, ArgLocs2, F.getContext());
432   if (!analyzeArgInfo(CCInfo2, InArgs, CallerAssignFnFixed,
433                       CalleeAssignFnVarArg))
434     return false;
435 
436   // We need the argument locations to match up exactly. If there's more in
437   // one than the other, then we are done.
438   if (ArgLocs1.size() != ArgLocs2.size())
439     return false;
440 
441   // Make sure that each location is passed in exactly the same way.
442   for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) {
443     const CCValAssign &Loc1 = ArgLocs1[i];
444     const CCValAssign &Loc2 = ArgLocs2[i];
445 
446     // We need both of them to be the same. So if one is a register and one
447     // isn't, we're done.
448     if (Loc1.isRegLoc() != Loc2.isRegLoc())
449       return false;
450 
451     if (Loc1.isRegLoc()) {
452       // If they don't have the same register location, we're done.
453       if (Loc1.getLocReg() != Loc2.getLocReg())
454         return false;
455 
456       // They matched, so we can move to the next ArgLoc.
457       continue;
458     }
459 
460     // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match.
461     if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset())
462       return false;
463   }
464 
465   return true;
466 }
467 
468 Register CallLowering::ValueHandler::extendRegister(Register ValReg,
469                                                     CCValAssign &VA) {
470   LLT LocTy{VA.getLocVT()};
471   if (LocTy.getSizeInBits() == MRI.getType(ValReg).getSizeInBits())
472     return ValReg;
473   switch (VA.getLocInfo()) {
474   default: break;
475   case CCValAssign::Full:
476   case CCValAssign::BCvt:
477     // FIXME: bitconverting between vector types may or may not be a
478     // nop in big-endian situations.
479     return ValReg;
480   case CCValAssign::AExt: {
481     auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg);
482     return MIB.getReg(0);
483   }
484   case CCValAssign::SExt: {
485     Register NewReg = MRI.createGenericVirtualRegister(LocTy);
486     MIRBuilder.buildSExt(NewReg, ValReg);
487     return NewReg;
488   }
489   case CCValAssign::ZExt: {
490     Register NewReg = MRI.createGenericVirtualRegister(LocTy);
491     MIRBuilder.buildZExt(NewReg, ValReg);
492     return NewReg;
493   }
494   }
495   llvm_unreachable("unable to extend register");
496 }
497 
498 void CallLowering::ValueHandler::anchor() {}
499