LLVM 24.0.0git
AMDGPURewriteOutArguments.cpp
Go to the documentation of this file.
1//===- AMDGPURewriteOutArgumentsPass.cpp - Create struct returns ----------===//
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 This pass attempts to replace out argument usage with a return of a
10/// struct.
11///
12/// We can support returning a lot of values directly in registers, but
13/// idiomatic C code frequently uses a pointer argument to return a second value
14/// rather than returning a struct by value. GPU stack access is also quite
15/// painful, so we want to avoid that if possible. Passing a stack object
16/// pointer to a function also requires an additional address expansion code
17/// sequence to convert the pointer to be relative to the kernel's scratch wave
18/// offset register since the callee doesn't know what stack frame the incoming
19/// pointer is relative to.
20///
21/// The goal is to try rewriting code that looks like this:
22///
23/// int foo(int a, int b, int* out) {
24/// *out = bar();
25/// return a + b;
26/// }
27///
28/// into something like this:
29///
30/// std::pair<int, int> foo(int a, int b) {
31/// return std::pair(a + b, bar());
32/// }
33///
34/// Typically the incoming pointer is a simple alloca for a temporary variable
35/// to use the API, which if replaced with a struct return will be easily SROA'd
36/// out when the stub function we create is inlined
37///
38/// This pass introduces the struct return, but leaves the unused pointer
39/// arguments and introduces a new stub function calling the struct returning
40/// body. DeadArgumentElimination should be run after this to clean these up.
41//
42//===----------------------------------------------------------------------===//
43
44#include "AMDGPU.h"
46#include "llvm/ADT/Statistic.h"
50#include "llvm/IR/Attributes.h"
51#include "llvm/IR/IRBuilder.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
57
58#define DEBUG_TYPE "amdgpu-rewrite-out-arguments"
59
60using namespace llvm;
61
62STATISTIC(NumOutArgumentsReplaced,
63 "Number out arguments moved to struct return values");
64STATISTIC(NumOutArgumentFunctionsReplaced,
65 "Number of functions with out arguments moved to struct return values");
66
67namespace {
68
69class AMDGPURewriteOutArguments : public FunctionPass {
70private:
71 const AMDGPUOptions *CLOpts = nullptr;
72 const DataLayout *DL = nullptr;
73 MemorySSA *MSSA = nullptr;
74 MemorySSAUpdater *MSSAU = nullptr;
75 AAResults *AA = nullptr;
76
77 Type *getStoredType(Value &Arg) const;
78 Type *getOutArgumentType(Argument &Arg) const;
79
80public:
81 static char ID;
82
83 AMDGPURewriteOutArguments() : FunctionPass(ID) {}
84
85 void getAnalysisUsage(AnalysisUsage &AU) const override {
86 AU.addRequired<MemorySSAWrapperPass>();
87 AU.addRequired<AAResultsWrapperPass>();
88 FunctionPass::getAnalysisUsage(AU);
89 }
90
91 bool doInitialization(Module &M) override;
92 bool runOnFunction(Function &F) override;
93};
94
95} // end anonymous namespace
96
97INITIALIZE_PASS_BEGIN(AMDGPURewriteOutArguments, DEBUG_TYPE,
98 "AMDGPU Rewrite Out Arguments", false, false)
100INITIALIZE_PASS_END(AMDGPURewriteOutArguments, DEBUG_TYPE,
101 "AMDGPU Rewrite Out Arguments", false, false)
102
103char AMDGPURewriteOutArguments::ID = 0;
104
105Type *AMDGPURewriteOutArguments::getStoredType(Value &Arg) const {
106 const int MaxUses = 10;
107 int UseCount = 0;
108
109 SmallVector<Use *> Worklist(llvm::make_pointer_range(Arg.uses()));
110
111 Type *StoredType = nullptr;
112 while (!Worklist.empty()) {
113 Use *U = Worklist.pop_back_val();
114
115 if (auto *BCI = dyn_cast<BitCastInst>(U->getUser())) {
116 for (Use &U : BCI->uses())
117 Worklist.push_back(&U);
118 continue;
119 }
120
121 if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
122 if (UseCount++ > MaxUses)
123 return nullptr;
124
125 if (!SI->isSimple() ||
126 U->getOperandNo() != StoreInst::getPointerOperandIndex())
127 return nullptr;
128
129 if (StoredType && StoredType != SI->getValueOperand()->getType())
130 return nullptr; // More than one type.
131 StoredType = SI->getValueOperand()->getType();
132 continue;
133 }
134
135 // Unsupported user.
136 return nullptr;
137 }
138
139 return StoredType;
140}
141
142Type *AMDGPURewriteOutArguments::getOutArgumentType(Argument &Arg) const {
143 const unsigned MaxOutArgSizeBytes = 4 * CLOpts->max_return_arg_num_regs;
145
146 // TODO: It might be useful for any out arguments, not just privates.
147 if (!ArgTy ||
148 (ArgTy->getAddressSpace() != DL->getAllocaAddrSpace() &&
149 !CLOpts->any_address_space_out_arguments) ||
150 Arg.hasByValAttr() || Arg.hasStructRetAttr()) {
151 return nullptr;
152 }
153
154 Type *StoredType = getStoredType(Arg);
155 if (!StoredType || DL->getTypeStoreSize(StoredType) > MaxOutArgSizeBytes)
156 return nullptr;
157
158 return StoredType;
159}
160
161bool AMDGPURewriteOutArguments::doInitialization(Module &M) {
162 DL = &M.getDataLayout();
163 return false;
164}
165
167 MemorySSA &MSSA,
168 BatchAAResults &BAA) {
170 const auto *Accesses = MSSA.getBlockAccesses(BB);
171 if (!Accesses)
172 return nullptr;
173
174 for (const MemoryAccess &Access : reverse(*Accesses)) {
175 const auto *UseOrDef = dyn_cast<MemoryUseOrDef>(&Access);
176 if (!UseOrDef)
177 continue;
178
179 Instruction *I = UseOrDef->getMemoryInst();
180
181 // Return the must-alias store to the out argument.
182 if (auto *Store = dyn_cast<StoreInst>(I))
183 if (Store->getPointerOperand() == OutArg)
184 return Store;
185
186 if (auto *FI = dyn_cast<FenceInst>(I))
187 if (FI->getOrdering() == AtomicOrdering::Release)
188 continue;
189
190 if (auto *LI = dyn_cast<LoadInst>(I)) {
191 if (LI->isAtomic()) {
192 // May-alias reads with monotonic ordering are ignored.
193 if (isStrongerThan(LI->getOrdering(), AtomicOrdering::Monotonic))
194 return nullptr;
195 continue;
196 }
197 }
198
199 // Any other memory access that may read or write the location prevents the
200 // rewrite.
201 if (isModOrRefSet(BAA.getModRefInfo(I, ArgLoc)))
202 return nullptr;
203 }
204
205 return nullptr;
206}
207
208bool AMDGPURewriteOutArguments::runOnFunction(Function &F) {
209 if (skipFunction(F))
210 return false;
211
212 CLOpts = &F.getContext().getLibraryOptions().get<AMDGPUOptions>();
213 const unsigned MaxNumRetRegs = CLOpts->max_return_arg_num_regs;
214
215 // TODO: Could probably handle variadic functions.
216 if (F.isVarArg() || F.hasStructRetAttr() ||
217 AMDGPU::isEntryFunctionCC(F.getCallingConv()))
218 return false;
219
220 unsigned ReturnNumRegs = 0;
221 // Maps an out-argument number to its field index in the return struct.
222 // Fields are in processing order, which the retry loop below can reorder
223 // relative to argument order, so the index must be tracked, not recomputed.
224 SmallDenseMap<unsigned, unsigned, 4> OutArgIndexes;
225 SmallVector<Type *, 4> ReturnTypes;
226 Type *RetTy = F.getReturnType();
227 if (!RetTy->isVoidTy()) {
228 ReturnNumRegs = DL->getTypeStoreSize(RetTy) / 4;
229
230 if (ReturnNumRegs >= MaxNumRetRegs)
231 return false;
232
233 ReturnTypes.push_back(RetTy);
234 }
235
237 for (Argument &Arg : F.args()) {
238 if (Type *Ty = getOutArgumentType(Arg)) {
239 LLVM_DEBUG(dbgs() << "Found possible out argument " << Arg
240 << " in function " << F.getName() << '\n');
241 OutArgs.push_back({&Arg, Ty});
242 }
243 }
244
245 if (OutArgs.empty())
246 return false;
247
248 using ReplacementVec = SmallVector<std::pair<Argument *, Value *>, 4>;
249
250 DenseMap<ReturnInst *, ReplacementVec> Replacements;
251
253 for (BasicBlock &BB : F) {
254 if (ReturnInst *RI = dyn_cast<ReturnInst>(&BB.back()))
255 Returns.push_back(RI);
256 }
257
258 if (Returns.empty())
259 return false;
260
261 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
262 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
263
264 BatchAAResults BatchAA(*AA);
265 MemorySSAUpdater MSSAUpdater(MSSA);
266 MSSAU = &MSSAUpdater;
267
268 bool Changing;
269
270 do {
271 Changing = false;
272
273 // Keep retrying if we are able to successfully eliminate an argument. This
274 // helps with cases with multiple arguments which may alias, such as in a
275 // sincos implementation. With 2 stores to may-aliasing arguments, MDA
276 // returns the second store for the first argument too; the identity guard
277 // below rejects it, and a later iteration folds the first argument once the
278 // second store has been removed.
279 for (const auto &Pair : OutArgs) {
280 bool ThisReplaceable = true;
282
283 Argument *OutArg = Pair.first;
284 Type *ArgTy = Pair.second;
285
286 // Skip this argument if converting it will push us over the register
287 // count to return limit.
288
289 // TODO: This is an approximation. When legalized this could be more. We
290 // can ask TLI for exactly how many.
291 unsigned ArgNumRegs = DL->getTypeStoreSize(ArgTy) / 4;
292 if (ArgNumRegs + ReturnNumRegs > MaxNumRetRegs)
293 continue;
294
295 // An argument is convertible only if all exit blocks are able to replace
296 // it.
297 for (ReturnInst *RI : Returns) {
298 BasicBlock *BB = RI->getParent();
299
300 StoreInst *SI = findStoreForOutArgument(BB, OutArg, *MSSA, BatchAA);
301 if (SI) {
302 LLVM_DEBUG(dbgs() << "Found out argument store: " << *SI << '\n');
303 ReplaceableStores.emplace_back(RI, SI);
304 } else {
305 ThisReplaceable = false;
306 break;
307 }
308 }
309
310 if (!ThisReplaceable)
311 continue; // Try the next argument candidate.
312
313 for (std::pair<ReturnInst *, StoreInst *> Store : ReplaceableStores) {
314 Value *ReplVal = Store.second->getValueOperand();
315
316 auto &ValVec = Replacements[Store.first];
317 if (llvm::is_contained(llvm::make_first_range(ValVec), OutArg)) {
319 << "Saw multiple out arg stores" << *OutArg << '\n');
320 // It is possible to see stores to the same argument multiple times,
321 // but we expect these would have been optimized out already.
322 ThisReplaceable = false;
323 break;
324 }
325
326 ValVec.emplace_back(OutArg, ReplVal);
327 MSSAU->removeMemoryAccess(Store.second);
328 Store.second->eraseFromParent();
329 }
330
331 if (ThisReplaceable) {
332 OutArgIndexes.insert({OutArg->getArgNo(), ReturnTypes.size()});
333 ReturnTypes.push_back(ArgTy);
334 ++NumOutArgumentsReplaced;
335 Changing = true;
336 }
337 }
338 } while (Changing);
339
340 if (Replacements.empty())
341 return false;
342
343 LLVMContext &Ctx = F.getContext();
344 StructType *NewRetTy = StructType::create(Ctx, ReturnTypes, F.getName());
345
346 FunctionType *NewFuncTy = FunctionType::get(NewRetTy,
347 F.getFunctionType()->params(),
348 F.isVarArg());
349
350 LLVM_DEBUG(dbgs() << "Computed new return type: " << *NewRetTy << '\n');
351
352 Function *NewFunc = Function::Create(NewFuncTy, Function::PrivateLinkage,
353 F.getName() + ".body");
354 F.getParent()->getFunctionList().insert(F.getIterator(), NewFunc);
355 NewFunc->copyAttributesFrom(&F);
356 NewFunc->setComdat(F.getComdat());
357
358 // We want to preserve the function and param attributes, but need to strip
359 // off any return attributes, e.g. zeroext doesn't make sense with a struct.
360 NewFunc->stealArgumentListFrom(F);
361
362 NewFunc->removeRetAttrs(AttributeFuncs::typeIncompatible(
363 NewRetTy, NewFunc->getAttributes().getRetAttrs()));
364 // TODO: How to preserve metadata?
365
366 // Move the body of the function into the new rewritten function, and replace
367 // this function with a stub.
368 NewFunc->splice(NewFunc->begin(), &F);
369
370 for (auto &Replacement : Replacements) {
371 ReturnInst *RI = Replacement.first;
372 IRBuilder<> B(RI);
373 B.SetCurrentDebugLocation(RI->getDebugLoc());
374
375 Value *NewRetVal = PoisonValue::get(NewRetTy);
376
377 Value *RetVal = RI->getReturnValue();
378 if (RetVal)
379 NewRetVal = B.CreateInsertValue(NewRetVal, RetVal, 0);
380
381 // Use OutArgIndexes so body and stub agree on the field for each argument.
382 for (std::pair<Argument *, Value *> ReturnPoint : Replacement.second) {
383 unsigned FieldIdx = OutArgIndexes.lookup(ReturnPoint.first->getArgNo());
384 NewRetVal = B.CreateInsertValue(NewRetVal, ReturnPoint.second, FieldIdx);
385 }
386
387 if (RetVal)
388 RI->setOperand(0, NewRetVal);
389 else {
390 B.CreateRet(NewRetVal);
391 RI->eraseFromParent();
392 }
393 }
394
395 SmallVector<Value *, 16> StubCallArgs;
396 for (Argument &Arg : F.args()) {
397 if (OutArgIndexes.count(Arg.getArgNo())) {
398 // It's easier to preserve the type of the argument list. We rely on
399 // DeadArgumentElimination to take care of these.
400 StubCallArgs.push_back(PoisonValue::get(Arg.getType()));
401 } else {
402 StubCallArgs.push_back(&Arg);
403 }
404 }
405
406 BasicBlock *StubBB = BasicBlock::Create(Ctx, "", &F);
407 IRBuilder<> B(StubBB);
408 CallInst *StubCall = B.CreateCall(NewFunc, StubCallArgs);
409
410 for (Argument &Arg : F.args()) {
411 auto It = OutArgIndexes.find(Arg.getArgNo());
412 if (It == OutArgIndexes.end())
413 continue;
414
415 unsigned FieldIdx = It->second;
416 Type *EltTy = NewRetTy->getElementType(FieldIdx);
417 const auto Align =
418 DL->getValueOrABITypeAlignment(Arg.getParamAlign(), EltTy);
419
420 Value *Val = B.CreateExtractValue(StubCall, FieldIdx);
421 B.CreateAlignedStore(Val, &Arg, Align);
422 }
423
424 if (!RetTy->isVoidTy()) {
425 B.CreateRet(B.CreateExtractValue(StubCall, 0));
426 } else {
427 B.CreateRetVoid();
428 }
429
430 // The function is now a stub we want to inline.
431 F.addFnAttr(Attribute::AlwaysInline);
432
433 ++NumOutArgumentFunctionsReplaced;
434 return true;
435}
static StoreInst * findStoreForOutArgument(BasicBlock *BB, Argument *OutArg, MemorySSA &MSSA, BatchAAResults &BAA)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
DXIL Resource Access
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
Definition Function.cpp:126
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
Definition Function.cpp:209
LLVM_ABI bool hasStructRetAttr() const
Return true if this argument has the sret attribute.
Definition Function.cpp:281
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:755
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
iterator begin()
Definition Function.h:847
void stealArgumentListFrom(Function &Src)
Steal arguments from another function.
Definition Function.cpp:570
void removeRetAttrs(const AttributeMask &Attrs)
removes the attributes from the return value list of attributes.
Definition Function.cpp:709
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Representation for a specific memory location.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:971
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:689
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:745
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:662
Type * getElementType(unsigned N) const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
iterator_range< use_iterator > uses()
Definition Value.h:382
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...