xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/CallLowering.cpp (revision 6e07f16fae605c42014aa4f1f2babf3e7767c95c)
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/GlobalISel/CallLowering.h"
15 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 
23 #define DEBUG_TYPE "call-lowering"
24 
25 using namespace llvm;
26 
27 void CallLowering::anchor() {}
28 
29 bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, ImmutableCallSite CS,
30                              unsigned ResReg, ArrayRef<unsigned> ArgRegs,
31                              unsigned SwiftErrorVReg,
32                              std::function<unsigned()> GetCalleeReg) const {
33   auto &DL = CS.getParent()->getParent()->getParent()->getDataLayout();
34 
35   // First step is to marshall all the function's parameters into the correct
36   // physregs and memory locations. Gather the sequence of argument types that
37   // we'll pass to the assigner function.
38   SmallVector<ArgInfo, 8> OrigArgs;
39   unsigned i = 0;
40   unsigned NumFixedArgs = CS.getFunctionType()->getNumParams();
41   for (auto &Arg : CS.args()) {
42     ArgInfo OrigArg{ArgRegs[i], Arg->getType(), ISD::ArgFlagsTy{},
43                     i < NumFixedArgs};
44     setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CS);
45     // We don't currently support swiftself args.
46     if (OrigArg.Flags.isSwiftSelf())
47       return false;
48     OrigArgs.push_back(OrigArg);
49     ++i;
50   }
51 
52   MachineOperand Callee = MachineOperand::CreateImm(0);
53   if (const Function *F = CS.getCalledFunction())
54     Callee = MachineOperand::CreateGA(F, 0);
55   else
56     Callee = MachineOperand::CreateReg(GetCalleeReg(), false);
57 
58   ArgInfo OrigRet{ResReg, CS.getType(), ISD::ArgFlagsTy{}};
59   if (!OrigRet.Ty->isVoidTy())
60     setArgFlags(OrigRet, AttributeList::ReturnIndex, DL, CS);
61 
62   return lowerCall(MIRBuilder, CS.getCallingConv(), Callee, OrigRet, OrigArgs,
63                    SwiftErrorVReg);
64 }
65 
66 template <typename FuncInfoTy>
67 void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx,
68                                const DataLayout &DL,
69                                const FuncInfoTy &FuncInfo) const {
70   const AttributeList &Attrs = FuncInfo.getAttributes();
71   if (Attrs.hasAttribute(OpIdx, Attribute::ZExt))
72     Arg.Flags.setZExt();
73   if (Attrs.hasAttribute(OpIdx, Attribute::SExt))
74     Arg.Flags.setSExt();
75   if (Attrs.hasAttribute(OpIdx, Attribute::InReg))
76     Arg.Flags.setInReg();
77   if (Attrs.hasAttribute(OpIdx, Attribute::StructRet))
78     Arg.Flags.setSRet();
79   if (Attrs.hasAttribute(OpIdx, Attribute::SwiftSelf))
80     Arg.Flags.setSwiftSelf();
81   if (Attrs.hasAttribute(OpIdx, Attribute::SwiftError))
82     Arg.Flags.setSwiftError();
83   if (Attrs.hasAttribute(OpIdx, Attribute::ByVal))
84     Arg.Flags.setByVal();
85   if (Attrs.hasAttribute(OpIdx, Attribute::InAlloca))
86     Arg.Flags.setInAlloca();
87 
88   if (Arg.Flags.isByVal() || Arg.Flags.isInAlloca()) {
89     Type *ElementTy = cast<PointerType>(Arg.Ty)->getElementType();
90 
91     auto Ty = Attrs.getAttribute(OpIdx, Attribute::ByVal).getValueAsType();
92     Arg.Flags.setByValSize(DL.getTypeAllocSize(Ty ? Ty : ElementTy));
93 
94     // For ByVal, alignment should be passed from FE.  BE will guess if
95     // this info is not there but there are cases it cannot get right.
96     unsigned FrameAlign;
97     if (FuncInfo.getParamAlignment(OpIdx - 2))
98       FrameAlign = FuncInfo.getParamAlignment(OpIdx - 2);
99     else
100       FrameAlign = getTLI()->getByValTypeAlignment(ElementTy, DL);
101     Arg.Flags.setByValAlign(FrameAlign);
102   }
103   if (Attrs.hasAttribute(OpIdx, Attribute::Nest))
104     Arg.Flags.setNest();
105   Arg.Flags.setOrigAlign(DL.getABITypeAlignment(Arg.Ty));
106 }
107 
108 template void
109 CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
110                                     const DataLayout &DL,
111                                     const Function &FuncInfo) const;
112 
113 template void
114 CallLowering::setArgFlags<CallInst>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
115                                     const DataLayout &DL,
116                                     const CallInst &FuncInfo) const;
117 
118 bool CallLowering::handleAssignments(MachineIRBuilder &MIRBuilder,
119                                      ArrayRef<ArgInfo> Args,
120                                      ValueHandler &Handler) const {
121   MachineFunction &MF = MIRBuilder.getMF();
122   const Function &F = MF.getFunction();
123   const DataLayout &DL = F.getParent()->getDataLayout();
124 
125   SmallVector<CCValAssign, 16> ArgLocs;
126   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
127 
128   unsigned NumArgs = Args.size();
129   for (unsigned i = 0; i != NumArgs; ++i) {
130     MVT CurVT = MVT::getVT(Args[i].Ty);
131     if (Handler.assignArg(i, CurVT, CurVT, CCValAssign::Full, Args[i], CCInfo)) {
132       // Try to use the register type if we couldn't assign the VT.
133       if (!Handler.isArgumentHandler() || !CurVT.isValid())
134         return false;
135       CurVT = TLI->getRegisterTypeForCallingConv(
136           F.getContext(), F.getCallingConv(), EVT(CurVT));
137       if (Handler.assignArg(i, CurVT, CurVT, CCValAssign::Full, Args[i], CCInfo))
138         return false;
139     }
140   }
141 
142   for (unsigned i = 0, e = Args.size(), j = 0; i != e; ++i, ++j) {
143     assert(j < ArgLocs.size() && "Skipped too many arg locs");
144 
145     CCValAssign &VA = ArgLocs[j];
146     assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
147 
148     if (VA.needsCustom()) {
149       j += Handler.assignCustomValue(Args[i], makeArrayRef(ArgLocs).slice(j));
150       continue;
151     }
152 
153     if (VA.isRegLoc()) {
154       MVT OrigVT = MVT::getVT(Args[i].Ty);
155       MVT VAVT = VA.getValVT();
156       if (Handler.isArgumentHandler() && VAVT != OrigVT) {
157         if (VAVT.getSizeInBits() < OrigVT.getSizeInBits())
158           return false; // Can't handle this type of arg yet.
159         const LLT VATy(VAVT);
160         unsigned NewReg =
161             MIRBuilder.getMRI()->createGenericVirtualRegister(VATy);
162         Handler.assignValueToReg(NewReg, VA.getLocReg(), VA);
163         // If it's a vector type, we either need to truncate the elements
164         // or do an unmerge to get the lower block of elements.
165         if (VATy.isVector() &&
166             VATy.getNumElements() > OrigVT.getVectorNumElements()) {
167           const LLT OrigTy(OrigVT);
168           // Just handle the case where the VA type is 2 * original type.
169           if (VATy.getNumElements() != OrigVT.getVectorNumElements() * 2) {
170             LLVM_DEBUG(dbgs()
171                        << "Incoming promoted vector arg has too many elts");
172             return false;
173           }
174           auto Unmerge = MIRBuilder.buildUnmerge({OrigTy, OrigTy}, {NewReg});
175           MIRBuilder.buildCopy(Args[i].Reg, Unmerge.getReg(0));
176         } else {
177           MIRBuilder.buildTrunc(Args[i].Reg, {NewReg}).getReg(0);
178         }
179       } else {
180         Handler.assignValueToReg(Args[i].Reg, VA.getLocReg(), VA);
181       }
182     } else if (VA.isMemLoc()) {
183       MVT VT = MVT::getVT(Args[i].Ty);
184       unsigned Size = VT == MVT::iPTR ? DL.getPointerSize()
185                                       : alignTo(VT.getSizeInBits(), 8) / 8;
186       unsigned Offset = VA.getLocMemOffset();
187       MachinePointerInfo MPO;
188       unsigned StackAddr = Handler.getStackAddress(Size, Offset, MPO);
189       Handler.assignValueToAddress(Args[i].Reg, StackAddr, Size, MPO, VA);
190     } else {
191       // FIXME: Support byvals and other weirdness
192       return false;
193     }
194   }
195   return true;
196 }
197 
198 unsigned CallLowering::ValueHandler::extendRegister(unsigned ValReg,
199                                                     CCValAssign &VA) {
200   LLT LocTy{VA.getLocVT()};
201   if (LocTy.getSizeInBits() == MRI.getType(ValReg).getSizeInBits())
202     return ValReg;
203   switch (VA.getLocInfo()) {
204   default: break;
205   case CCValAssign::Full:
206   case CCValAssign::BCvt:
207     // FIXME: bitconverting between vector types may or may not be a
208     // nop in big-endian situations.
209     return ValReg;
210   case CCValAssign::AExt: {
211     auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg);
212     return MIB->getOperand(0).getReg();
213   }
214   case CCValAssign::SExt: {
215     unsigned NewReg = MRI.createGenericVirtualRegister(LocTy);
216     MIRBuilder.buildSExt(NewReg, ValReg);
217     return NewReg;
218   }
219   case CCValAssign::ZExt: {
220     unsigned NewReg = MRI.createGenericVirtualRegister(LocTy);
221     MIRBuilder.buildZExt(NewReg, ValReg);
222     return NewReg;
223   }
224   }
225   llvm_unreachable("unable to extend register");
226 }
227 
228 void CallLowering::ValueHandler::anchor() {}
229