CallLowering.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. #include "llvm/CodeGen/Analysis.h"
  14. #include "llvm/CodeGen/CallingConvLower.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. #include "llvm/Target/TargetMachine.h"
  26. #define DEBUG_TYPE "call-lowering"
  27. using namespace llvm;
  28. void CallLowering::anchor() {}
  29. /// Helper function which updates \p Flags when \p AttrFn returns true.
  30. static void
  31. addFlagsUsingAttrFn(ISD::ArgFlagsTy &Flags,
  32. const std::function<bool(Attribute::AttrKind)> &AttrFn) {
  33. if (AttrFn(Attribute::SExt))
  34. Flags.setSExt();
  35. if (AttrFn(Attribute::ZExt))
  36. Flags.setZExt();
  37. if (AttrFn(Attribute::InReg))
  38. Flags.setInReg();
  39. if (AttrFn(Attribute::StructRet))
  40. Flags.setSRet();
  41. if (AttrFn(Attribute::Nest))
  42. Flags.setNest();
  43. if (AttrFn(Attribute::ByVal))
  44. Flags.setByVal();
  45. if (AttrFn(Attribute::Preallocated))
  46. Flags.setPreallocated();
  47. if (AttrFn(Attribute::InAlloca))
  48. Flags.setInAlloca();
  49. if (AttrFn(Attribute::Returned))
  50. Flags.setReturned();
  51. if (AttrFn(Attribute::SwiftSelf))
  52. Flags.setSwiftSelf();
  53. if (AttrFn(Attribute::SwiftAsync))
  54. Flags.setSwiftAsync();
  55. if (AttrFn(Attribute::SwiftError))
  56. Flags.setSwiftError();
  57. }
  58. ISD::ArgFlagsTy CallLowering::getAttributesForArgIdx(const CallBase &Call,
  59. unsigned ArgIdx) const {
  60. ISD::ArgFlagsTy Flags;
  61. addFlagsUsingAttrFn(Flags, [&Call, &ArgIdx](Attribute::AttrKind Attr) {
  62. return Call.paramHasAttr(ArgIdx, Attr);
  63. });
  64. return Flags;
  65. }
  66. void CallLowering::addArgFlagsFromAttributes(ISD::ArgFlagsTy &Flags,
  67. const AttributeList &Attrs,
  68. unsigned OpIdx) const {
  69. addFlagsUsingAttrFn(Flags, [&Attrs, &OpIdx](Attribute::AttrKind Attr) {
  70. return Attrs.hasAttributeAtIndex(OpIdx, Attr);
  71. });
  72. }
  73. bool CallLowering::lowerCall(MachineIRBuilder &MIRBuilder, const CallBase &CB,
  74. ArrayRef<Register> ResRegs,
  75. ArrayRef<ArrayRef<Register>> ArgRegs,
  76. Register SwiftErrorVReg,
  77. std::function<unsigned()> GetCalleeReg) const {
  78. CallLoweringInfo Info;
  79. const DataLayout &DL = MIRBuilder.getDataLayout();
  80. MachineFunction &MF = MIRBuilder.getMF();
  81. MachineRegisterInfo &MRI = MF.getRegInfo();
  82. bool CanBeTailCalled = CB.isTailCall() &&
  83. isInTailCallPosition(CB, MF.getTarget()) &&
  84. (MF.getFunction()
  85. .getFnAttribute("disable-tail-calls")
  86. .getValueAsString() != "true");
  87. CallingConv::ID CallConv = CB.getCallingConv();
  88. Type *RetTy = CB.getType();
  89. bool IsVarArg = CB.getFunctionType()->isVarArg();
  90. SmallVector<BaseArgInfo, 4> SplitArgs;
  91. getReturnInfo(CallConv, RetTy, CB.getAttributes(), SplitArgs, DL);
  92. Info.CanLowerReturn = canLowerReturn(MF, CallConv, SplitArgs, IsVarArg);
  93. if (!Info.CanLowerReturn) {
  94. // Callee requires sret demotion.
  95. insertSRetOutgoingArgument(MIRBuilder, CB, Info);
  96. // The sret demotion isn't compatible with tail-calls, since the sret
  97. // argument points into the caller's stack frame.
  98. CanBeTailCalled = false;
  99. }
  100. // First step is to marshall all the function's parameters into the correct
  101. // physregs and memory locations. Gather the sequence of argument types that
  102. // we'll pass to the assigner function.
  103. unsigned i = 0;
  104. unsigned NumFixedArgs = CB.getFunctionType()->getNumParams();
  105. for (auto &Arg : CB.args()) {
  106. ArgInfo OrigArg{ArgRegs[i], *Arg.get(), i, getAttributesForArgIdx(CB, i),
  107. i < NumFixedArgs};
  108. setArgFlags(OrigArg, i + AttributeList::FirstArgIndex, DL, CB);
  109. // If we have an explicit sret argument that is an Instruction, (i.e., it
  110. // might point to function-local memory), we can't meaningfully tail-call.
  111. if (OrigArg.Flags[0].isSRet() && isa<Instruction>(&Arg))
  112. CanBeTailCalled = false;
  113. Info.OrigArgs.push_back(OrigArg);
  114. ++i;
  115. }
  116. // Try looking through a bitcast from one function type to another.
  117. // Commonly happens with calls to objc_msgSend().
  118. const Value *CalleeV = CB.getCalledOperand()->stripPointerCasts();
  119. if (const Function *F = dyn_cast<Function>(CalleeV))
  120. Info.Callee = MachineOperand::CreateGA(F, 0);
  121. else
  122. Info.Callee = MachineOperand::CreateReg(GetCalleeReg(), false);
  123. Register ReturnHintAlignReg;
  124. Align ReturnHintAlign;
  125. Info.OrigRet = ArgInfo{ResRegs, RetTy, 0, ISD::ArgFlagsTy{}};
  126. if (!Info.OrigRet.Ty->isVoidTy()) {
  127. setArgFlags(Info.OrigRet, AttributeList::ReturnIndex, DL, CB);
  128. if (MaybeAlign Alignment = CB.getRetAlign()) {
  129. if (*Alignment > Align(1)) {
  130. ReturnHintAlignReg = MRI.cloneVirtualRegister(ResRegs[0]);
  131. Info.OrigRet.Regs[0] = ReturnHintAlignReg;
  132. ReturnHintAlign = *Alignment;
  133. }
  134. }
  135. }
  136. Info.CB = &CB;
  137. Info.KnownCallees = CB.getMetadata(LLVMContext::MD_callees);
  138. Info.CallConv = CallConv;
  139. Info.SwiftErrorVReg = SwiftErrorVReg;
  140. Info.IsMustTailCall = CB.isMustTailCall();
  141. Info.IsTailCall = CanBeTailCalled;
  142. Info.IsVarArg = IsVarArg;
  143. if (!lowerCall(MIRBuilder, Info))
  144. return false;
  145. if (ReturnHintAlignReg && !Info.IsTailCall) {
  146. MIRBuilder.buildAssertAlign(ResRegs[0], ReturnHintAlignReg,
  147. ReturnHintAlign);
  148. }
  149. return true;
  150. }
  151. template <typename FuncInfoTy>
  152. void CallLowering::setArgFlags(CallLowering::ArgInfo &Arg, unsigned OpIdx,
  153. const DataLayout &DL,
  154. const FuncInfoTy &FuncInfo) const {
  155. auto &Flags = Arg.Flags[0];
  156. const AttributeList &Attrs = FuncInfo.getAttributes();
  157. addArgFlagsFromAttributes(Flags, Attrs, OpIdx);
  158. PointerType *PtrTy = dyn_cast<PointerType>(Arg.Ty->getScalarType());
  159. if (PtrTy) {
  160. Flags.setPointer();
  161. Flags.setPointerAddrSpace(PtrTy->getPointerAddressSpace());
  162. }
  163. Align MemAlign = DL.getABITypeAlign(Arg.Ty);
  164. if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
  165. assert(OpIdx >= AttributeList::FirstArgIndex);
  166. unsigned ParamIdx = OpIdx - AttributeList::FirstArgIndex;
  167. Type *ElementTy = FuncInfo.getParamByValType(ParamIdx);
  168. if (!ElementTy)
  169. ElementTy = FuncInfo.getParamInAllocaType(ParamIdx);
  170. if (!ElementTy)
  171. ElementTy = FuncInfo.getParamPreallocatedType(ParamIdx);
  172. assert(ElementTy && "Must have byval, inalloca or preallocated type");
  173. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  174. // For ByVal, alignment should be passed from FE. BE will guess if
  175. // this info is not there but there are cases it cannot get right.
  176. if (auto ParamAlign = FuncInfo.getParamStackAlign(ParamIdx))
  177. MemAlign = *ParamAlign;
  178. else if ((ParamAlign = FuncInfo.getParamAlign(ParamIdx)))
  179. MemAlign = *ParamAlign;
  180. else
  181. MemAlign = Align(getTLI()->getByValTypeAlignment(ElementTy, DL));
  182. } else if (OpIdx >= AttributeList::FirstArgIndex) {
  183. if (auto ParamAlign =
  184. FuncInfo.getParamStackAlign(OpIdx - AttributeList::FirstArgIndex))
  185. MemAlign = *ParamAlign;
  186. }
  187. Flags.setMemAlign(MemAlign);
  188. Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty));
  189. // Don't try to use the returned attribute if the argument is marked as
  190. // swiftself, since it won't be passed in x0.
  191. if (Flags.isSwiftSelf())
  192. Flags.setReturned(false);
  193. }
  194. template void
  195. CallLowering::setArgFlags<Function>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
  196. const DataLayout &DL,
  197. const Function &FuncInfo) const;
  198. template void
  199. CallLowering::setArgFlags<CallBase>(CallLowering::ArgInfo &Arg, unsigned OpIdx,
  200. const DataLayout &DL,
  201. const CallBase &FuncInfo) const;
  202. void CallLowering::splitToValueTypes(const ArgInfo &OrigArg,
  203. SmallVectorImpl<ArgInfo> &SplitArgs,
  204. const DataLayout &DL,
  205. CallingConv::ID CallConv,
  206. SmallVectorImpl<uint64_t> *Offsets) const {
  207. LLVMContext &Ctx = OrigArg.Ty->getContext();
  208. SmallVector<EVT, 4> SplitVTs;
  209. ComputeValueVTs(*TLI, DL, OrigArg.Ty, SplitVTs, Offsets, 0);
  210. if (SplitVTs.size() == 0)
  211. return;
  212. if (SplitVTs.size() == 1) {
  213. // No splitting to do, but we want to replace the original type (e.g. [1 x
  214. // double] -> double).
  215. SplitArgs.emplace_back(OrigArg.Regs[0], SplitVTs[0].getTypeForEVT(Ctx),
  216. OrigArg.OrigArgIndex, OrigArg.Flags[0],
  217. OrigArg.IsFixed, OrigArg.OrigValue);
  218. return;
  219. }
  220. // Create one ArgInfo for each virtual register in the original ArgInfo.
  221. assert(OrigArg.Regs.size() == SplitVTs.size() && "Regs / types mismatch");
  222. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  223. OrigArg.Ty, CallConv, false, DL);
  224. for (unsigned i = 0, e = SplitVTs.size(); i < e; ++i) {
  225. Type *SplitTy = SplitVTs[i].getTypeForEVT(Ctx);
  226. SplitArgs.emplace_back(OrigArg.Regs[i], SplitTy, OrigArg.OrigArgIndex,
  227. OrigArg.Flags[0], OrigArg.IsFixed);
  228. if (NeedsRegBlock)
  229. SplitArgs.back().Flags[0].setInConsecutiveRegs();
  230. }
  231. SplitArgs.back().Flags[0].setInConsecutiveRegsLast();
  232. }
  233. /// Pack values \p SrcRegs to cover the vector type result \p DstRegs.
  234. static MachineInstrBuilder
  235. mergeVectorRegsToResultRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs,
  236. ArrayRef<Register> SrcRegs) {
  237. MachineRegisterInfo &MRI = *B.getMRI();
  238. LLT LLTy = MRI.getType(DstRegs[0]);
  239. LLT PartLLT = MRI.getType(SrcRegs[0]);
  240. // Deal with v3s16 split into v2s16
  241. LLT LCMTy = getCoverTy(LLTy, PartLLT);
  242. if (LCMTy == LLTy) {
  243. // Common case where no padding is needed.
  244. assert(DstRegs.size() == 1);
  245. return B.buildConcatVectors(DstRegs[0], SrcRegs);
  246. }
  247. // We need to create an unmerge to the result registers, which may require
  248. // widening the original value.
  249. Register UnmergeSrcReg;
  250. if (LCMTy != PartLLT) {
  251. assert(DstRegs.size() == 1);
  252. return B.buildDeleteTrailingVectorElements(DstRegs[0],
  253. B.buildMerge(LCMTy, SrcRegs));
  254. } else {
  255. // We don't need to widen anything if we're extracting a scalar which was
  256. // promoted to a vector e.g. s8 -> v4s8 -> s8
  257. assert(SrcRegs.size() == 1);
  258. UnmergeSrcReg = SrcRegs[0];
  259. }
  260. int NumDst = LCMTy.getSizeInBits() / LLTy.getSizeInBits();
  261. SmallVector<Register, 8> PadDstRegs(NumDst);
  262. std::copy(DstRegs.begin(), DstRegs.end(), PadDstRegs.begin());
  263. // Create the excess dead defs for the unmerge.
  264. for (int I = DstRegs.size(); I != NumDst; ++I)
  265. PadDstRegs[I] = MRI.createGenericVirtualRegister(LLTy);
  266. if (PadDstRegs.size() == 1)
  267. return B.buildDeleteTrailingVectorElements(DstRegs[0], UnmergeSrcReg);
  268. return B.buildUnmerge(PadDstRegs, UnmergeSrcReg);
  269. }
  270. /// Create a sequence of instructions to combine pieces split into register
  271. /// typed values to the original IR value. \p OrigRegs contains the destination
  272. /// value registers of type \p LLTy, and \p Regs contains the legalized pieces
  273. /// with type \p PartLLT. This is used for incoming values (physregs to vregs).
  274. static void buildCopyFromRegs(MachineIRBuilder &B, ArrayRef<Register> OrigRegs,
  275. ArrayRef<Register> Regs, LLT LLTy, LLT PartLLT,
  276. const ISD::ArgFlagsTy Flags) {
  277. MachineRegisterInfo &MRI = *B.getMRI();
  278. if (PartLLT == LLTy) {
  279. // We should have avoided introducing a new virtual register, and just
  280. // directly assigned here.
  281. assert(OrigRegs[0] == Regs[0]);
  282. return;
  283. }
  284. if (PartLLT.getSizeInBits() == LLTy.getSizeInBits() && OrigRegs.size() == 1 &&
  285. Regs.size() == 1) {
  286. B.buildBitcast(OrigRegs[0], Regs[0]);
  287. return;
  288. }
  289. // A vector PartLLT needs extending to LLTy's element size.
  290. // E.g. <2 x s64> = G_SEXT <2 x s32>.
  291. if (PartLLT.isVector() == LLTy.isVector() &&
  292. PartLLT.getScalarSizeInBits() > LLTy.getScalarSizeInBits() &&
  293. (!PartLLT.isVector() ||
  294. PartLLT.getNumElements() == LLTy.getNumElements()) &&
  295. OrigRegs.size() == 1 && Regs.size() == 1) {
  296. Register SrcReg = Regs[0];
  297. LLT LocTy = MRI.getType(SrcReg);
  298. if (Flags.isSExt()) {
  299. SrcReg = B.buildAssertSExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
  300. .getReg(0);
  301. } else if (Flags.isZExt()) {
  302. SrcReg = B.buildAssertZExt(LocTy, SrcReg, LLTy.getScalarSizeInBits())
  303. .getReg(0);
  304. }
  305. // Sometimes pointers are passed zero extended.
  306. LLT OrigTy = MRI.getType(OrigRegs[0]);
  307. if (OrigTy.isPointer()) {
  308. LLT IntPtrTy = LLT::scalar(OrigTy.getSizeInBits());
  309. B.buildIntToPtr(OrigRegs[0], B.buildTrunc(IntPtrTy, SrcReg));
  310. return;
  311. }
  312. B.buildTrunc(OrigRegs[0], SrcReg);
  313. return;
  314. }
  315. if (!LLTy.isVector() && !PartLLT.isVector()) {
  316. assert(OrigRegs.size() == 1);
  317. LLT OrigTy = MRI.getType(OrigRegs[0]);
  318. unsigned SrcSize = PartLLT.getSizeInBits().getFixedSize() * Regs.size();
  319. if (SrcSize == OrigTy.getSizeInBits())
  320. B.buildMerge(OrigRegs[0], Regs);
  321. else {
  322. auto Widened = B.buildMerge(LLT::scalar(SrcSize), Regs);
  323. B.buildTrunc(OrigRegs[0], Widened);
  324. }
  325. return;
  326. }
  327. if (PartLLT.isVector()) {
  328. assert(OrigRegs.size() == 1);
  329. SmallVector<Register> CastRegs(Regs.begin(), Regs.end());
  330. // If PartLLT is a mismatched vector in both number of elements and element
  331. // size, e.g. PartLLT == v2s64 and LLTy is v3s32, then first coerce it to
  332. // have the same elt type, i.e. v4s32.
  333. if (PartLLT.getSizeInBits() > LLTy.getSizeInBits() &&
  334. PartLLT.getScalarSizeInBits() == LLTy.getScalarSizeInBits() * 2 &&
  335. Regs.size() == 1) {
  336. LLT NewTy = PartLLT.changeElementType(LLTy.getElementType())
  337. .changeElementCount(PartLLT.getElementCount() * 2);
  338. CastRegs[0] = B.buildBitcast(NewTy, Regs[0]).getReg(0);
  339. PartLLT = NewTy;
  340. }
  341. if (LLTy.getScalarType() == PartLLT.getElementType()) {
  342. mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
  343. } else {
  344. unsigned I = 0;
  345. LLT GCDTy = getGCDType(LLTy, PartLLT);
  346. // We are both splitting a vector, and bitcasting its element types. Cast
  347. // the source pieces into the appropriate number of pieces with the result
  348. // element type.
  349. for (Register SrcReg : CastRegs)
  350. CastRegs[I++] = B.buildBitcast(GCDTy, SrcReg).getReg(0);
  351. mergeVectorRegsToResultRegs(B, OrigRegs, CastRegs);
  352. }
  353. return;
  354. }
  355. assert(LLTy.isVector() && !PartLLT.isVector());
  356. LLT DstEltTy = LLTy.getElementType();
  357. // Pointer information was discarded. We'll need to coerce some register types
  358. // to avoid violating type constraints.
  359. LLT RealDstEltTy = MRI.getType(OrigRegs[0]).getElementType();
  360. assert(DstEltTy.getSizeInBits() == RealDstEltTy.getSizeInBits());
  361. if (DstEltTy == PartLLT) {
  362. // Vector was trivially scalarized.
  363. if (RealDstEltTy.isPointer()) {
  364. for (Register Reg : Regs)
  365. MRI.setType(Reg, RealDstEltTy);
  366. }
  367. B.buildBuildVector(OrigRegs[0], Regs);
  368. } else if (DstEltTy.getSizeInBits() > PartLLT.getSizeInBits()) {
  369. // Deal with vector with 64-bit elements decomposed to 32-bit
  370. // registers. Need to create intermediate 64-bit elements.
  371. SmallVector<Register, 8> EltMerges;
  372. int PartsPerElt = DstEltTy.getSizeInBits() / PartLLT.getSizeInBits();
  373. assert(DstEltTy.getSizeInBits() % PartLLT.getSizeInBits() == 0);
  374. for (int I = 0, NumElts = LLTy.getNumElements(); I != NumElts; ++I) {
  375. auto Merge = B.buildMerge(RealDstEltTy, Regs.take_front(PartsPerElt));
  376. // Fix the type in case this is really a vector of pointers.
  377. MRI.setType(Merge.getReg(0), RealDstEltTy);
  378. EltMerges.push_back(Merge.getReg(0));
  379. Regs = Regs.drop_front(PartsPerElt);
  380. }
  381. B.buildBuildVector(OrigRegs[0], EltMerges);
  382. } else {
  383. // Vector was split, and elements promoted to a wider type.
  384. // FIXME: Should handle floating point promotions.
  385. LLT BVType = LLT::fixed_vector(LLTy.getNumElements(), PartLLT);
  386. auto BV = B.buildBuildVector(BVType, Regs);
  387. B.buildTrunc(OrigRegs[0], BV);
  388. }
  389. }
  390. /// Create a sequence of instructions to expand the value in \p SrcReg (of type
  391. /// \p SrcTy) to the types in \p DstRegs (of type \p PartTy). \p ExtendOp should
  392. /// contain the type of scalar value extension if necessary.
  393. ///
  394. /// This is used for outgoing values (vregs to physregs)
  395. static void buildCopyToRegs(MachineIRBuilder &B, ArrayRef<Register> DstRegs,
  396. Register SrcReg, LLT SrcTy, LLT PartTy,
  397. unsigned ExtendOp = TargetOpcode::G_ANYEXT) {
  398. // We could just insert a regular copy, but this is unreachable at the moment.
  399. assert(SrcTy != PartTy && "identical part types shouldn't reach here");
  400. const unsigned PartSize = PartTy.getSizeInBits();
  401. if (PartTy.isVector() == SrcTy.isVector() &&
  402. PartTy.getScalarSizeInBits() > SrcTy.getScalarSizeInBits()) {
  403. assert(DstRegs.size() == 1);
  404. B.buildInstr(ExtendOp, {DstRegs[0]}, {SrcReg});
  405. return;
  406. }
  407. if (SrcTy.isVector() && !PartTy.isVector() &&
  408. PartSize > SrcTy.getElementType().getSizeInBits()) {
  409. // Vector was scalarized, and the elements extended.
  410. auto UnmergeToEltTy = B.buildUnmerge(SrcTy.getElementType(), SrcReg);
  411. for (int i = 0, e = DstRegs.size(); i != e; ++i)
  412. B.buildAnyExt(DstRegs[i], UnmergeToEltTy.getReg(i));
  413. return;
  414. }
  415. LLT GCDTy = getGCDType(SrcTy, PartTy);
  416. if (GCDTy == PartTy) {
  417. // If this already evenly divisible, we can create a simple unmerge.
  418. B.buildUnmerge(DstRegs, SrcReg);
  419. return;
  420. }
  421. MachineRegisterInfo &MRI = *B.getMRI();
  422. LLT DstTy = MRI.getType(DstRegs[0]);
  423. LLT LCMTy = getCoverTy(SrcTy, PartTy);
  424. const unsigned DstSize = DstTy.getSizeInBits();
  425. const unsigned SrcSize = SrcTy.getSizeInBits();
  426. unsigned CoveringSize = LCMTy.getSizeInBits();
  427. Register UnmergeSrc = SrcReg;
  428. if (!LCMTy.isVector() && CoveringSize != SrcSize) {
  429. // For scalars, it's common to be able to use a simple extension.
  430. if (SrcTy.isScalar() && DstTy.isScalar()) {
  431. CoveringSize = alignTo(SrcSize, DstSize);
  432. LLT CoverTy = LLT::scalar(CoveringSize);
  433. UnmergeSrc = B.buildInstr(ExtendOp, {CoverTy}, {SrcReg}).getReg(0);
  434. } else {
  435. // Widen to the common type.
  436. // FIXME: This should respect the extend type
  437. Register Undef = B.buildUndef(SrcTy).getReg(0);
  438. SmallVector<Register, 8> MergeParts(1, SrcReg);
  439. for (unsigned Size = SrcSize; Size != CoveringSize; Size += SrcSize)
  440. MergeParts.push_back(Undef);
  441. UnmergeSrc = B.buildMerge(LCMTy, MergeParts).getReg(0);
  442. }
  443. }
  444. if (LCMTy.isVector() && CoveringSize != SrcSize)
  445. UnmergeSrc = B.buildPadVectorWithUndefElements(LCMTy, SrcReg).getReg(0);
  446. B.buildUnmerge(DstRegs, UnmergeSrc);
  447. }
  448. bool CallLowering::determineAndHandleAssignments(
  449. ValueHandler &Handler, ValueAssigner &Assigner,
  450. SmallVectorImpl<ArgInfo> &Args, MachineIRBuilder &MIRBuilder,
  451. CallingConv::ID CallConv, bool IsVarArg,
  452. ArrayRef<Register> ThisReturnRegs) const {
  453. MachineFunction &MF = MIRBuilder.getMF();
  454. const Function &F = MF.getFunction();
  455. SmallVector<CCValAssign, 16> ArgLocs;
  456. CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, F.getContext());
  457. if (!determineAssignments(Assigner, Args, CCInfo))
  458. return false;
  459. return handleAssignments(Handler, Args, CCInfo, ArgLocs, MIRBuilder,
  460. ThisReturnRegs);
  461. }
  462. static unsigned extendOpFromFlags(llvm::ISD::ArgFlagsTy Flags) {
  463. if (Flags.isSExt())
  464. return TargetOpcode::G_SEXT;
  465. if (Flags.isZExt())
  466. return TargetOpcode::G_ZEXT;
  467. return TargetOpcode::G_ANYEXT;
  468. }
  469. bool CallLowering::determineAssignments(ValueAssigner &Assigner,
  470. SmallVectorImpl<ArgInfo> &Args,
  471. CCState &CCInfo) const {
  472. LLVMContext &Ctx = CCInfo.getContext();
  473. const CallingConv::ID CallConv = CCInfo.getCallingConv();
  474. unsigned NumArgs = Args.size();
  475. for (unsigned i = 0; i != NumArgs; ++i) {
  476. EVT CurVT = EVT::getEVT(Args[i].Ty);
  477. MVT NewVT = TLI->getRegisterTypeForCallingConv(Ctx, CallConv, CurVT);
  478. // If we need to split the type over multiple regs, check it's a scenario
  479. // we currently support.
  480. unsigned NumParts =
  481. TLI->getNumRegistersForCallingConv(Ctx, CallConv, CurVT);
  482. if (NumParts == 1) {
  483. // Try to use the register type if we couldn't assign the VT.
  484. if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
  485. Args[i].Flags[0], CCInfo))
  486. return false;
  487. continue;
  488. }
  489. // For incoming arguments (physregs to vregs), we could have values in
  490. // physregs (or memlocs) which we want to extract and copy to vregs.
  491. // During this, we might have to deal with the LLT being split across
  492. // multiple regs, so we have to record this information for later.
  493. //
  494. // If we have outgoing args, then we have the opposite case. We have a
  495. // vreg with an LLT which we want to assign to a physical location, and
  496. // we might have to record that the value has to be split later.
  497. // We're handling an incoming arg which is split over multiple regs.
  498. // E.g. passing an s128 on AArch64.
  499. ISD::ArgFlagsTy OrigFlags = Args[i].Flags[0];
  500. Args[i].Flags.clear();
  501. for (unsigned Part = 0; Part < NumParts; ++Part) {
  502. ISD::ArgFlagsTy Flags = OrigFlags;
  503. if (Part == 0) {
  504. Flags.setSplit();
  505. } else {
  506. Flags.setOrigAlign(Align(1));
  507. if (Part == NumParts - 1)
  508. Flags.setSplitEnd();
  509. }
  510. Args[i].Flags.push_back(Flags);
  511. if (Assigner.assignArg(i, CurVT, NewVT, NewVT, CCValAssign::Full, Args[i],
  512. Args[i].Flags[Part], CCInfo)) {
  513. // Still couldn't assign this smaller part type for some reason.
  514. return false;
  515. }
  516. }
  517. }
  518. return true;
  519. }
  520. bool CallLowering::handleAssignments(ValueHandler &Handler,
  521. SmallVectorImpl<ArgInfo> &Args,
  522. CCState &CCInfo,
  523. SmallVectorImpl<CCValAssign> &ArgLocs,
  524. MachineIRBuilder &MIRBuilder,
  525. ArrayRef<Register> ThisReturnRegs) const {
  526. MachineFunction &MF = MIRBuilder.getMF();
  527. MachineRegisterInfo &MRI = MF.getRegInfo();
  528. const Function &F = MF.getFunction();
  529. const DataLayout &DL = F.getParent()->getDataLayout();
  530. const unsigned NumArgs = Args.size();
  531. // Stores thunks for outgoing register assignments. This is used so we delay
  532. // generating register copies until mem loc assignments are done. We do this
  533. // so that if the target is using the delayed stack protector feature, we can
  534. // find the split point of the block accurately. E.g. if we have:
  535. // G_STORE %val, %memloc
  536. // $x0 = COPY %foo
  537. // $x1 = COPY %bar
  538. // CALL func
  539. // ... then the split point for the block will correctly be at, and including,
  540. // the copy to $x0. If instead the G_STORE instruction immediately precedes
  541. // the CALL, then we'd prematurely choose the CALL as the split point, thus
  542. // generating a split block with a CALL that uses undefined physregs.
  543. SmallVector<std::function<void()>> DelayedOutgoingRegAssignments;
  544. for (unsigned i = 0, j = 0; i != NumArgs; ++i, ++j) {
  545. assert(j < ArgLocs.size() && "Skipped too many arg locs");
  546. CCValAssign &VA = ArgLocs[j];
  547. assert(VA.getValNo() == i && "Location doesn't correspond to current arg");
  548. if (VA.needsCustom()) {
  549. std::function<void()> Thunk;
  550. unsigned NumArgRegs = Handler.assignCustomValue(
  551. Args[i], makeArrayRef(ArgLocs).slice(j), &Thunk);
  552. if (Thunk)
  553. DelayedOutgoingRegAssignments.emplace_back(Thunk);
  554. if (!NumArgRegs)
  555. return false;
  556. j += NumArgRegs;
  557. continue;
  558. }
  559. const MVT ValVT = VA.getValVT();
  560. const MVT LocVT = VA.getLocVT();
  561. const LLT LocTy(LocVT);
  562. const LLT ValTy(ValVT);
  563. const LLT NewLLT = Handler.isIncomingArgumentHandler() ? LocTy : ValTy;
  564. const EVT OrigVT = EVT::getEVT(Args[i].Ty);
  565. const LLT OrigTy = getLLTForType(*Args[i].Ty, DL);
  566. // Expected to be multiple regs for a single incoming arg.
  567. // There should be Regs.size() ArgLocs per argument.
  568. // This should be the same as getNumRegistersForCallingConv
  569. const unsigned NumParts = Args[i].Flags.size();
  570. // Now split the registers into the assigned types.
  571. Args[i].OrigRegs.assign(Args[i].Regs.begin(), Args[i].Regs.end());
  572. if (NumParts != 1 || NewLLT != OrigTy) {
  573. // If we can't directly assign the register, we need one or more
  574. // intermediate values.
  575. Args[i].Regs.resize(NumParts);
  576. // For each split register, create and assign a vreg that will store
  577. // the incoming component of the larger value. These will later be
  578. // merged to form the final vreg.
  579. for (unsigned Part = 0; Part < NumParts; ++Part)
  580. Args[i].Regs[Part] = MRI.createGenericVirtualRegister(NewLLT);
  581. }
  582. assert((j + (NumParts - 1)) < ArgLocs.size() &&
  583. "Too many regs for number of args");
  584. // Coerce into outgoing value types before register assignment.
  585. if (!Handler.isIncomingArgumentHandler() && OrigTy != ValTy) {
  586. assert(Args[i].OrigRegs.size() == 1);
  587. buildCopyToRegs(MIRBuilder, Args[i].Regs, Args[i].OrigRegs[0], OrigTy,
  588. ValTy, extendOpFromFlags(Args[i].Flags[0]));
  589. }
  590. for (unsigned Part = 0; Part < NumParts; ++Part) {
  591. Register ArgReg = Args[i].Regs[Part];
  592. // There should be Regs.size() ArgLocs per argument.
  593. VA = ArgLocs[j + Part];
  594. const ISD::ArgFlagsTy Flags = Args[i].Flags[Part];
  595. if (VA.isMemLoc() && !Flags.isByVal()) {
  596. // Individual pieces may have been spilled to the stack and others
  597. // passed in registers.
  598. // TODO: The memory size may be larger than the value we need to
  599. // store. We may need to adjust the offset for big endian targets.
  600. LLT MemTy = Handler.getStackValueStoreType(DL, VA, Flags);
  601. MachinePointerInfo MPO;
  602. Register StackAddr = Handler.getStackAddress(
  603. MemTy.getSizeInBytes(), VA.getLocMemOffset(), MPO, Flags);
  604. Handler.assignValueToAddress(Args[i], Part, StackAddr, MemTy, MPO, VA);
  605. continue;
  606. }
  607. if (VA.isMemLoc() && Flags.isByVal()) {
  608. assert(Args[i].Regs.size() == 1 &&
  609. "didn't expect split byval pointer");
  610. if (Handler.isIncomingArgumentHandler()) {
  611. // We just need to copy the frame index value to the pointer.
  612. MachinePointerInfo MPO;
  613. Register StackAddr = Handler.getStackAddress(
  614. Flags.getByValSize(), VA.getLocMemOffset(), MPO, Flags);
  615. MIRBuilder.buildCopy(Args[i].Regs[0], StackAddr);
  616. } else {
  617. // For outgoing byval arguments, insert the implicit copy byval
  618. // implies, such that writes in the callee do not modify the caller's
  619. // value.
  620. uint64_t MemSize = Flags.getByValSize();
  621. int64_t Offset = VA.getLocMemOffset();
  622. MachinePointerInfo DstMPO;
  623. Register StackAddr =
  624. Handler.getStackAddress(MemSize, Offset, DstMPO, Flags);
  625. MachinePointerInfo SrcMPO(Args[i].OrigValue);
  626. if (!Args[i].OrigValue) {
  627. // We still need to accurately track the stack address space if we
  628. // don't know the underlying value.
  629. const LLT PtrTy = MRI.getType(StackAddr);
  630. SrcMPO = MachinePointerInfo(PtrTy.getAddressSpace());
  631. }
  632. Align DstAlign = std::max(Flags.getNonZeroByValAlign(),
  633. inferAlignFromPtrInfo(MF, DstMPO));
  634. Align SrcAlign = std::max(Flags.getNonZeroByValAlign(),
  635. inferAlignFromPtrInfo(MF, SrcMPO));
  636. Handler.copyArgumentMemory(Args[i], StackAddr, Args[i].Regs[0],
  637. DstMPO, DstAlign, SrcMPO, SrcAlign,
  638. MemSize, VA);
  639. }
  640. continue;
  641. }
  642. assert(!VA.needsCustom() && "custom loc should have been handled already");
  643. if (i == 0 && !ThisReturnRegs.empty() &&
  644. Handler.isIncomingArgumentHandler() &&
  645. isTypeIsValidForThisReturn(ValVT)) {
  646. Handler.assignValueToReg(ArgReg, ThisReturnRegs[Part], VA);
  647. continue;
  648. }
  649. if (Handler.isIncomingArgumentHandler())
  650. Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
  651. else {
  652. DelayedOutgoingRegAssignments.emplace_back([=, &Handler]() {
  653. Handler.assignValueToReg(ArgReg, VA.getLocReg(), VA);
  654. });
  655. }
  656. }
  657. // Now that all pieces have been assigned, re-pack the register typed values
  658. // into the original value typed registers.
  659. if (Handler.isIncomingArgumentHandler() && OrigVT != LocVT) {
  660. // Merge the split registers into the expected larger result vregs of
  661. // the original call.
  662. buildCopyFromRegs(MIRBuilder, Args[i].OrigRegs, Args[i].Regs, OrigTy,
  663. LocTy, Args[i].Flags[0]);
  664. }
  665. j += NumParts - 1;
  666. }
  667. for (auto &Fn : DelayedOutgoingRegAssignments)
  668. Fn();
  669. return true;
  670. }
  671. void CallLowering::insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy,
  672. ArrayRef<Register> VRegs, Register DemoteReg,
  673. int FI) const {
  674. MachineFunction &MF = MIRBuilder.getMF();
  675. MachineRegisterInfo &MRI = MF.getRegInfo();
  676. const DataLayout &DL = MF.getDataLayout();
  677. SmallVector<EVT, 4> SplitVTs;
  678. SmallVector<uint64_t, 4> Offsets;
  679. ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
  680. assert(VRegs.size() == SplitVTs.size());
  681. unsigned NumValues = SplitVTs.size();
  682. Align BaseAlign = DL.getPrefTypeAlign(RetTy);
  683. Type *RetPtrTy = RetTy->getPointerTo(DL.getAllocaAddrSpace());
  684. LLT OffsetLLTy = getLLTForType(*DL.getIntPtrType(RetPtrTy), DL);
  685. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
  686. for (unsigned I = 0; I < NumValues; ++I) {
  687. Register Addr;
  688. MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
  689. auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
  690. MRI.getType(VRegs[I]),
  691. commonAlignment(BaseAlign, Offsets[I]));
  692. MIRBuilder.buildLoad(VRegs[I], Addr, *MMO);
  693. }
  694. }
  695. void CallLowering::insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy,
  696. ArrayRef<Register> VRegs,
  697. Register DemoteReg) const {
  698. MachineFunction &MF = MIRBuilder.getMF();
  699. MachineRegisterInfo &MRI = MF.getRegInfo();
  700. const DataLayout &DL = MF.getDataLayout();
  701. SmallVector<EVT, 4> SplitVTs;
  702. SmallVector<uint64_t, 4> Offsets;
  703. ComputeValueVTs(*TLI, DL, RetTy, SplitVTs, &Offsets, 0);
  704. assert(VRegs.size() == SplitVTs.size());
  705. unsigned NumValues = SplitVTs.size();
  706. Align BaseAlign = DL.getPrefTypeAlign(RetTy);
  707. unsigned AS = DL.getAllocaAddrSpace();
  708. LLT OffsetLLTy =
  709. getLLTForType(*DL.getIntPtrType(RetTy->getPointerTo(AS)), DL);
  710. MachinePointerInfo PtrInfo(AS);
  711. for (unsigned I = 0; I < NumValues; ++I) {
  712. Register Addr;
  713. MIRBuilder.materializePtrAdd(Addr, DemoteReg, OffsetLLTy, Offsets[I]);
  714. auto *MMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
  715. MRI.getType(VRegs[I]),
  716. commonAlignment(BaseAlign, Offsets[I]));
  717. MIRBuilder.buildStore(VRegs[I], Addr, *MMO);
  718. }
  719. }
  720. void CallLowering::insertSRetIncomingArgument(
  721. const Function &F, SmallVectorImpl<ArgInfo> &SplitArgs, Register &DemoteReg,
  722. MachineRegisterInfo &MRI, const DataLayout &DL) const {
  723. unsigned AS = DL.getAllocaAddrSpace();
  724. DemoteReg = MRI.createGenericVirtualRegister(
  725. LLT::pointer(AS, DL.getPointerSizeInBits(AS)));
  726. Type *PtrTy = PointerType::get(F.getReturnType(), AS);
  727. SmallVector<EVT, 1> ValueVTs;
  728. ComputeValueVTs(*TLI, DL, PtrTy, ValueVTs);
  729. // NOTE: Assume that a pointer won't get split into more than one VT.
  730. assert(ValueVTs.size() == 1);
  731. ArgInfo DemoteArg(DemoteReg, ValueVTs[0].getTypeForEVT(PtrTy->getContext()),
  732. ArgInfo::NoArgIndex);
  733. setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, F);
  734. DemoteArg.Flags[0].setSRet();
  735. SplitArgs.insert(SplitArgs.begin(), DemoteArg);
  736. }
  737. void CallLowering::insertSRetOutgoingArgument(MachineIRBuilder &MIRBuilder,
  738. const CallBase &CB,
  739. CallLoweringInfo &Info) const {
  740. const DataLayout &DL = MIRBuilder.getDataLayout();
  741. Type *RetTy = CB.getType();
  742. unsigned AS = DL.getAllocaAddrSpace();
  743. LLT FramePtrTy = LLT::pointer(AS, DL.getPointerSizeInBits(AS));
  744. int FI = MIRBuilder.getMF().getFrameInfo().CreateStackObject(
  745. DL.getTypeAllocSize(RetTy), DL.getPrefTypeAlign(RetTy), false);
  746. Register DemoteReg = MIRBuilder.buildFrameIndex(FramePtrTy, FI).getReg(0);
  747. ArgInfo DemoteArg(DemoteReg, PointerType::get(RetTy, AS),
  748. ArgInfo::NoArgIndex);
  749. setArgFlags(DemoteArg, AttributeList::ReturnIndex, DL, CB);
  750. DemoteArg.Flags[0].setSRet();
  751. Info.OrigArgs.insert(Info.OrigArgs.begin(), DemoteArg);
  752. Info.DemoteStackIndex = FI;
  753. Info.DemoteRegister = DemoteReg;
  754. }
  755. bool CallLowering::checkReturn(CCState &CCInfo,
  756. SmallVectorImpl<BaseArgInfo> &Outs,
  757. CCAssignFn *Fn) const {
  758. for (unsigned I = 0, E = Outs.size(); I < E; ++I) {
  759. MVT VT = MVT::getVT(Outs[I].Ty);
  760. if (Fn(I, VT, VT, CCValAssign::Full, Outs[I].Flags[0], CCInfo))
  761. return false;
  762. }
  763. return true;
  764. }
  765. void CallLowering::getReturnInfo(CallingConv::ID CallConv, Type *RetTy,
  766. AttributeList Attrs,
  767. SmallVectorImpl<BaseArgInfo> &Outs,
  768. const DataLayout &DL) const {
  769. LLVMContext &Context = RetTy->getContext();
  770. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  771. SmallVector<EVT, 4> SplitVTs;
  772. ComputeValueVTs(*TLI, DL, RetTy, SplitVTs);
  773. addArgFlagsFromAttributes(Flags, Attrs, AttributeList::ReturnIndex);
  774. for (EVT VT : SplitVTs) {
  775. unsigned NumParts =
  776. TLI->getNumRegistersForCallingConv(Context, CallConv, VT);
  777. MVT RegVT = TLI->getRegisterTypeForCallingConv(Context, CallConv, VT);
  778. Type *PartTy = EVT(RegVT).getTypeForEVT(Context);
  779. for (unsigned I = 0; I < NumParts; ++I) {
  780. Outs.emplace_back(PartTy, Flags);
  781. }
  782. }
  783. }
  784. bool CallLowering::checkReturnTypeForCallConv(MachineFunction &MF) const {
  785. const auto &F = MF.getFunction();
  786. Type *ReturnType = F.getReturnType();
  787. CallingConv::ID CallConv = F.getCallingConv();
  788. SmallVector<BaseArgInfo, 4> SplitArgs;
  789. getReturnInfo(CallConv, ReturnType, F.getAttributes(), SplitArgs,
  790. MF.getDataLayout());
  791. return canLowerReturn(MF, CallConv, SplitArgs, F.isVarArg());
  792. }
  793. bool CallLowering::parametersInCSRMatch(
  794. const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask,
  795. const SmallVectorImpl<CCValAssign> &OutLocs,
  796. const SmallVectorImpl<ArgInfo> &OutArgs) const {
  797. for (unsigned i = 0; i < OutLocs.size(); ++i) {
  798. auto &ArgLoc = OutLocs[i];
  799. // If it's not a register, it's fine.
  800. if (!ArgLoc.isRegLoc())
  801. continue;
  802. MCRegister PhysReg = ArgLoc.getLocReg();
  803. // Only look at callee-saved registers.
  804. if (MachineOperand::clobbersPhysReg(CallerPreservedMask, PhysReg))
  805. continue;
  806. LLVM_DEBUG(
  807. dbgs()
  808. << "... Call has an argument passed in a callee-saved register.\n");
  809. // Check if it was copied from.
  810. const ArgInfo &OutInfo = OutArgs[i];
  811. if (OutInfo.Regs.size() > 1) {
  812. LLVM_DEBUG(
  813. dbgs() << "... Cannot handle arguments in multiple registers.\n");
  814. return false;
  815. }
  816. // Check if we copy the register, walking through copies from virtual
  817. // registers. Note that getDefIgnoringCopies does not ignore copies from
  818. // physical registers.
  819. MachineInstr *RegDef = getDefIgnoringCopies(OutInfo.Regs[0], MRI);
  820. if (!RegDef || RegDef->getOpcode() != TargetOpcode::COPY) {
  821. LLVM_DEBUG(
  822. dbgs()
  823. << "... Parameter was not copied into a VReg, cannot tail call.\n");
  824. return false;
  825. }
  826. // Got a copy. Verify that it's the same as the register we want.
  827. Register CopyRHS = RegDef->getOperand(1).getReg();
  828. if (CopyRHS != PhysReg) {
  829. LLVM_DEBUG(dbgs() << "... Callee-saved register was not copied into "
  830. "VReg, cannot tail call.\n");
  831. return false;
  832. }
  833. }
  834. return true;
  835. }
  836. bool CallLowering::resultsCompatible(CallLoweringInfo &Info,
  837. MachineFunction &MF,
  838. SmallVectorImpl<ArgInfo> &InArgs,
  839. ValueAssigner &CalleeAssigner,
  840. ValueAssigner &CallerAssigner) const {
  841. const Function &F = MF.getFunction();
  842. CallingConv::ID CalleeCC = Info.CallConv;
  843. CallingConv::ID CallerCC = F.getCallingConv();
  844. if (CallerCC == CalleeCC)
  845. return true;
  846. SmallVector<CCValAssign, 16> ArgLocs1;
  847. CCState CCInfo1(CalleeCC, Info.IsVarArg, MF, ArgLocs1, F.getContext());
  848. if (!determineAssignments(CalleeAssigner, InArgs, CCInfo1))
  849. return false;
  850. SmallVector<CCValAssign, 16> ArgLocs2;
  851. CCState CCInfo2(CallerCC, F.isVarArg(), MF, ArgLocs2, F.getContext());
  852. if (!determineAssignments(CallerAssigner, InArgs, CCInfo2))
  853. return false;
  854. // We need the argument locations to match up exactly. If there's more in
  855. // one than the other, then we are done.
  856. if (ArgLocs1.size() != ArgLocs2.size())
  857. return false;
  858. // Make sure that each location is passed in exactly the same way.
  859. for (unsigned i = 0, e = ArgLocs1.size(); i < e; ++i) {
  860. const CCValAssign &Loc1 = ArgLocs1[i];
  861. const CCValAssign &Loc2 = ArgLocs2[i];
  862. // We need both of them to be the same. So if one is a register and one
  863. // isn't, we're done.
  864. if (Loc1.isRegLoc() != Loc2.isRegLoc())
  865. return false;
  866. if (Loc1.isRegLoc()) {
  867. // If they don't have the same register location, we're done.
  868. if (Loc1.getLocReg() != Loc2.getLocReg())
  869. return false;
  870. // They matched, so we can move to the next ArgLoc.
  871. continue;
  872. }
  873. // Loc1 wasn't a RegLoc, so they both must be MemLocs. Check if they match.
  874. if (Loc1.getLocMemOffset() != Loc2.getLocMemOffset())
  875. return false;
  876. }
  877. return true;
  878. }
  879. LLT CallLowering::ValueHandler::getStackValueStoreType(
  880. const DataLayout &DL, const CCValAssign &VA, ISD::ArgFlagsTy Flags) const {
  881. const MVT ValVT = VA.getValVT();
  882. if (ValVT != MVT::iPTR) {
  883. LLT ValTy(ValVT);
  884. // We lost the pointeriness going through CCValAssign, so try to restore it
  885. // based on the flags.
  886. if (Flags.isPointer()) {
  887. LLT PtrTy = LLT::pointer(Flags.getPointerAddrSpace(),
  888. ValTy.getScalarSizeInBits());
  889. if (ValVT.isVector())
  890. return LLT::vector(ValTy.getElementCount(), PtrTy);
  891. return PtrTy;
  892. }
  893. return ValTy;
  894. }
  895. unsigned AddrSpace = Flags.getPointerAddrSpace();
  896. return LLT::pointer(AddrSpace, DL.getPointerSize(AddrSpace));
  897. }
  898. void CallLowering::ValueHandler::copyArgumentMemory(
  899. const ArgInfo &Arg, Register DstPtr, Register SrcPtr,
  900. const MachinePointerInfo &DstPtrInfo, Align DstAlign,
  901. const MachinePointerInfo &SrcPtrInfo, Align SrcAlign, uint64_t MemSize,
  902. CCValAssign &VA) const {
  903. MachineFunction &MF = MIRBuilder.getMF();
  904. MachineMemOperand *SrcMMO = MF.getMachineMemOperand(
  905. SrcPtrInfo,
  906. MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable, MemSize,
  907. SrcAlign);
  908. MachineMemOperand *DstMMO = MF.getMachineMemOperand(
  909. DstPtrInfo,
  910. MachineMemOperand::MOStore | MachineMemOperand::MODereferenceable,
  911. MemSize, DstAlign);
  912. const LLT PtrTy = MRI.getType(DstPtr);
  913. const LLT SizeTy = LLT::scalar(PtrTy.getSizeInBits());
  914. auto SizeConst = MIRBuilder.buildConstant(SizeTy, MemSize);
  915. MIRBuilder.buildMemCpy(DstPtr, SrcPtr, SizeConst, *DstMMO, *SrcMMO);
  916. }
  917. Register CallLowering::ValueHandler::extendRegister(Register ValReg,
  918. CCValAssign &VA,
  919. unsigned MaxSizeBits) {
  920. LLT LocTy{VA.getLocVT()};
  921. LLT ValTy{VA.getValVT()};
  922. if (LocTy.getSizeInBits() == ValTy.getSizeInBits())
  923. return ValReg;
  924. if (LocTy.isScalar() && MaxSizeBits && MaxSizeBits < LocTy.getSizeInBits()) {
  925. if (MaxSizeBits <= ValTy.getSizeInBits())
  926. return ValReg;
  927. LocTy = LLT::scalar(MaxSizeBits);
  928. }
  929. const LLT ValRegTy = MRI.getType(ValReg);
  930. if (ValRegTy.isPointer()) {
  931. // The x32 ABI wants to zero extend 32-bit pointers to 64-bit registers, so
  932. // we have to cast to do the extension.
  933. LLT IntPtrTy = LLT::scalar(ValRegTy.getSizeInBits());
  934. ValReg = MIRBuilder.buildPtrToInt(IntPtrTy, ValReg).getReg(0);
  935. }
  936. switch (VA.getLocInfo()) {
  937. default: break;
  938. case CCValAssign::Full:
  939. case CCValAssign::BCvt:
  940. // FIXME: bitconverting between vector types may or may not be a
  941. // nop in big-endian situations.
  942. return ValReg;
  943. case CCValAssign::AExt: {
  944. auto MIB = MIRBuilder.buildAnyExt(LocTy, ValReg);
  945. return MIB.getReg(0);
  946. }
  947. case CCValAssign::SExt: {
  948. Register NewReg = MRI.createGenericVirtualRegister(LocTy);
  949. MIRBuilder.buildSExt(NewReg, ValReg);
  950. return NewReg;
  951. }
  952. case CCValAssign::ZExt: {
  953. Register NewReg = MRI.createGenericVirtualRegister(LocTy);
  954. MIRBuilder.buildZExt(NewReg, ValReg);
  955. return NewReg;
  956. }
  957. }
  958. llvm_unreachable("unable to extend register");
  959. }
  960. void CallLowering::ValueAssigner::anchor() {}
  961. Register CallLowering::IncomingValueHandler::buildExtensionHint(CCValAssign &VA,
  962. Register SrcReg,
  963. LLT NarrowTy) {
  964. switch (VA.getLocInfo()) {
  965. case CCValAssign::LocInfo::ZExt: {
  966. return MIRBuilder
  967. .buildAssertZExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
  968. NarrowTy.getScalarSizeInBits())
  969. .getReg(0);
  970. }
  971. case CCValAssign::LocInfo::SExt: {
  972. return MIRBuilder
  973. .buildAssertSExt(MRI.cloneVirtualRegister(SrcReg), SrcReg,
  974. NarrowTy.getScalarSizeInBits())
  975. .getReg(0);
  976. break;
  977. }
  978. default:
  979. return SrcReg;
  980. }
  981. }
  982. /// Check if we can use a basic COPY instruction between the two types.
  983. ///
  984. /// We're currently building on top of the infrastructure using MVT, which loses
  985. /// pointer information in the CCValAssign. We accept copies from physical
  986. /// registers that have been reported as integers if it's to an equivalent sized
  987. /// pointer LLT.
  988. static bool isCopyCompatibleType(LLT SrcTy, LLT DstTy) {
  989. if (SrcTy == DstTy)
  990. return true;
  991. if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
  992. return false;
  993. SrcTy = SrcTy.getScalarType();
  994. DstTy = DstTy.getScalarType();
  995. return (SrcTy.isPointer() && DstTy.isScalar()) ||
  996. (DstTy.isScalar() && SrcTy.isPointer());
  997. }
  998. void CallLowering::IncomingValueHandler::assignValueToReg(Register ValVReg,
  999. Register PhysReg,
  1000. CCValAssign VA) {
  1001. const MVT LocVT = VA.getLocVT();
  1002. const LLT LocTy(LocVT);
  1003. const LLT RegTy = MRI.getType(ValVReg);
  1004. if (isCopyCompatibleType(RegTy, LocTy)) {
  1005. MIRBuilder.buildCopy(ValVReg, PhysReg);
  1006. return;
  1007. }
  1008. auto Copy = MIRBuilder.buildCopy(LocTy, PhysReg);
  1009. auto Hint = buildExtensionHint(VA, Copy.getReg(0), RegTy);
  1010. MIRBuilder.buildTrunc(ValVReg, Hint);
  1011. }