153#include "llvm/IR/IntrinsicsNVPTX.h"
163#define DEBUG_TYPE "nvptx-lower-args"
175 return "Lower pointer arguments of CUDA kernels";
183char NVPTXLowerArgsLegacyPass::ID = 1;
186 "Lower arguments (NVPTX)",
false,
false)
216 const auto CloneInstInParamAS = [](
const IP &
I) ->
Value * {
219 LI->setOperand(0,
I.NewParam);
225 GEP->getSourceElementType(),
I.NewParam, Indices,
GEP->getName(),
227 NewGEP->setNoWrapFlags(
GEP->getNoWrapFlags());
233 BC->getName(), BC->getIterator());
242 if (
MI->getRawSource() ==
I.OldUse->get()) {
247 CallInst *
B = Builder.CreateMemTransferInst(
248 ID,
MI->getRawDest(),
MI->getDestAlign(),
I.NewParam,
249 MI->getSourceAlign(),
MI->getLength(),
MI->isVolatile());
250 for (
unsigned I : {0, 1})
251 if (
uint64_t Bytes =
MI->getParamDereferenceableBytes(
I))
252 B->addDereferenceableParamAttr(
I, Bytes);
260 auto ItemsToConvert =
264 while (!ItemsToConvert.empty()) {
265 IP
I = ItemsToConvert.pop_back_val();
266 Value *NewInst = CloneInstInParamAS(
I);
269 if (NewInst && NewInst != OldInst) {
274 ItemsToConvert.push_back({&U, NewInst});
276 InstructionsToDelete.push_back(OldInst);
288 I->eraseFromParent();
296 const Align OptimizedAlign =
300 if (CurrentAlign >= OptimizedAlign)
304 <<
" instead of " << CurrentAlign.
value() <<
" for " << *Arg
310 return OptimizedAlign;
332 std::queue<LoadContext> Worklist;
333 Worklist.push({Val, 0});
335 while (!Worklist.empty()) {
336 LoadContext Ctx = Worklist.front();
339 for (
User *CurUser : Ctx.InitialVal->
users()) {
345 APInt OffsetAccumulated =
348 if (!
I->accumulateConstantOffset(
DL, OffsetAccumulated))
353 assert(
Offset != OffsetLimit &&
"Expect Offset less than UINT64_MAX");
355 Worklist.push({
I, Ctx.Offset +
Offset});
360 for (Load &CurLoad : Loads) {
362 Align CurLoadAlign = CurLoad.Inst->getAlign();
363 CurLoad.Inst->setAlignment(std::max(NewLoadAlign, CurLoadAlign));
374 &Arg, {}, Arg.
getName() +
".param");
381 Arg.
addAttr(Attribute::ReadOnly);
388 using Base = PtrUseVisitor<ArgUseChecker>;
390 SmallPtrSet<Instruction *, 4> Conditionals;
392 ArgUseChecker(
const DataLayout &
DL) : PtrUseVisitor(
DL) {}
394 PtrInfo visitArgPtr(Argument &
A) {
395 assert(
A.getType()->isPointerTy());
397 IsOffsetKnown =
false;
408 while (!(Worklist.empty() || PI.isAborted())) {
409 UseToVisit ToVisit = Worklist.pop_back_val();
410 U = ToVisit.UseAndIsOffsetKnown.getPointer();
416 LLVM_DEBUG(
dbgs() <<
"Argument pointer escaped: " << *PI.getEscapingInst()
418 else if (PI.isAborted())
419 LLVM_DEBUG(
dbgs() <<
"Pointer use needs a copy: " << *PI.getAbortingInst()
422 <<
" conditionals\n");
426 void visitStoreInst(StoreInst &SI) {
428 if (
U->get() ==
SI.getValueOperand())
429 return PI.setEscapedAndAborted(&SI);
434 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
437 return PI.setEscapedAndAborted(&ASC);
443 void visitPHINodeOrSelectInst(Instruction &
I) {
446 Conditionals.insert(&
I);
449 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
450 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
454 void visitMemTransferInst(MemTransferInst &
II) {
455 if (*U ==
II.getRawDest())
459 void visitMemSetInst(MemSetInst &
II) { PI.setAborted(&
II); }
481 IRB.CreateMemCpy(AllocA, AllocA->
getAlign(), ArgInParamAS, AllocA->
getAlign(),
493 if (
II->getIntrinsicID() == Intrinsic::nvvm_internal_addrspace_wrap)
514 ArgUseChecker AUC(
DL);
515 ArgUseChecker::PtrInfo PI = AUC.visitArgPtr(*Arg);
516 const bool ArgUseIsReadOnly = !(PI.isEscaped() || PI.isAborted());
517 if (ArgUseIsReadOnly && AUC.Conditionals.
empty()) {
522 for (
Use *U : UsesToUpdate)
531 LLVM_DEBUG(
dbgs() <<
"Using non-copy pointer to " << *Arg <<
"\n");
552 copyByValParam(*
F, *Arg);
567 assert(InsertPt != InsertPt->getParent()->end() &&
568 "We don't call this function with Ptr being a terminator.");
585 if (!
all_of(V.users(), [](
User *U) { return isa<IntToPtrInst>(U); }))
589 for (
User *U : UsersToUpdate)
608 if (LI->getType()->isPointerTy() || LI->getType()->isIntegerTy()) {
613 if (LI->getType()->isPointerTy())
627 LLVM_DEBUG(
dbgs() <<
"Lowering kernel args of " <<
F.getName() <<
"\n");
637 LLVM_DEBUG(
dbgs() <<
"Lowering function args of " <<
F.getName() <<
"\n");
656bool NVPTXLowerArgsLegacyPass::runOnFunction(
Function &
F) {
657 auto &TM = getAnalysis<TargetPassConfig>().getTM<NVPTXTargetMachine>();
661 return new NVPTXLowerArgsLegacyPass();
665 LLVM_DEBUG(
dbgs() <<
"Creating a copy of byval args of " <<
F.getName()
671 copyByValParam(
F, Arg);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
NVPTX address space definition.
static bool runOnDeviceFunction(const NVPTXTargetMachine &TM, Function &F)
nvptx lower Lower static false void convertToParamAS(ArrayRef< Use * > OldUses, Value *Param)
Recursively convert the users of a param to the param address space.
static CallInst * createNVVMInternalAddrspaceWrap(IRBuilder<> &IRB, Argument &Arg)
static bool copyFunctionByValArgs(Function &F)
static void markPointerAsAS(Value *Ptr, const unsigned AS)
static bool argIsProcessed(Argument *Arg)
static bool processFunction(Function &F, NVPTXTargetMachine &TM)
static bool runOnKernelFunction(const NVPTXTargetMachine &TM, Function &F)
static Align setByValParamAlign(Argument *Arg, const NVPTXTargetLowering *TLI)
static void propagateAlignmentToLoads(Value *Val, Align NewAlign, const DataLayout &DL)
static void handleIntToPtr(Value &V)
static void markPointerAsGlobal(Value *Ptr)
static void handleByValParam(const NVPTXTargetMachine &TM, Argument *Arg)
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file provides a collection of visitors which walk the (instruction) uses of a pointer.
Target-Independent Code Generator Pass Configuration Options pass.
Class for arbitrary precision integers.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
This class represents a conversion between pointers from one address space to another.
unsigned getDestAddressSpace() const
Returns the address space of the result.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
This class represents an incoming formal argument to a Function.
LLVM_ABI void addAttr(Attribute::AttrKind Kind)
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
LLVM_ABI void removeAttr(Attribute::AttrKind Kind)
Remove attributes from an argument.
const Function * getParent() const
LLVM_ABI Type * getParamByValType() const
If this is a byval argument, return its type.
LLVM_ABI MaybeAlign getParamAlign() const
If this is a byval or inalloca argument, return its alignment.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
iterator begin()
Instruction iterator methods.
InstListType::iterator iterator
Instruction iterators...
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
A parsed version of the target data layout string in and methods for querying it.
FunctionPass class - This class is used to implement most global optimizations.
const BasicBlock & getEntryBlock() const
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void visit(Iterator Start, Iterator End)
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
An instruction for reading from memory.
const NVPTXTargetLowering * getTargetLowering() const override
Align getFunctionParamOptimizedAlign(const Function *F, Type *ArgTy, const DataLayout &DL) const
getFunctionParamOptimizedAlign - since function arguments are passed via .param space,...
NVPTX::DrvInterface getDrvInterface() const
const NVPTXSubtarget * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
A base class for visitors over the uses of a pointer value.
void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC)
void visitPtrToIntInst(PtrToIntInst &I)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Target-Independent Code Generator Pass Configuration Options.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
user_iterator user_begin()
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
FunctionPass * createNVPTXLowerArgsPass()
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
bool isParamGridConstant(const Argument &Arg)
bool isKernelFunction(const Function &F)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)