LLVM  7.0.0
AMDGPULowerKernelArguments.cpp
Go to the documentation of this file.
1 //===-- AMDGPULowerKernelArguments.cpp ------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This pass replaces accesses to kernel arguments with loads from
11 /// offsets from the kernarg base pointer.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/Loads.h"
21 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstrTypes.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/Casting.h"
40 
41 #define DEBUG_TYPE "amdgpu-lower-kernel-arguments"
42 
43 using namespace llvm;
44 
45 namespace {
46 
47 class AMDGPULowerKernelArguments : public FunctionPass{
48 public:
49  static char ID;
50 
51  AMDGPULowerKernelArguments() : FunctionPass(ID) {}
52 
53  bool runOnFunction(Function &F) override;
54 
55  void getAnalysisUsage(AnalysisUsage &AU) const override {
57  AU.setPreservesAll();
58  }
59 };
60 
61 } // end anonymous namespace
62 
65  if (CC != CallingConv::AMDGPU_KERNEL || F.arg_empty())
66  return false;
67 
68  auto &TPC = getAnalysis<TargetPassConfig>();
69 
70  const TargetMachine &TM = TPC.getTM<TargetMachine>();
71  const GCNSubtarget &ST = TM.getSubtarget<GCNSubtarget>(F);
72  LLVMContext &Ctx = F.getParent()->getContext();
73  const DataLayout &DL = F.getParent()->getDataLayout();
74  BasicBlock &EntryBlock = *F.begin();
75  IRBuilder<> Builder(&*EntryBlock.begin());
76 
77  const unsigned KernArgBaseAlign = 16; // FIXME: Increase if necessary
78  const uint64_t BaseOffset = ST.getExplicitKernelArgOffset(F);
79 
80  unsigned MaxAlign;
81  // FIXME: Alignment is broken broken with explicit arg offset.;
82  const uint64_t TotalKernArgSize = ST.getKernArgSegmentSize(F, MaxAlign);
83  if (TotalKernArgSize == 0)
84  return false;
85 
86  CallInst *KernArgSegment =
87  Builder.CreateIntrinsic(Intrinsic::amdgcn_kernarg_segment_ptr, nullptr,
88  F.getName() + ".kernarg.segment");
89 
90  KernArgSegment->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
92  Attribute::getWithDereferenceableBytes(Ctx, TotalKernArgSize));
93 
94  unsigned AS = KernArgSegment->getType()->getPointerAddressSpace();
95  uint64_t ExplicitArgOffset = 0;
96 
97  for (Argument &Arg : F.args()) {
98  Type *ArgTy = Arg.getType();
99  unsigned Align = DL.getABITypeAlignment(ArgTy);
100  unsigned Size = DL.getTypeSizeInBits(ArgTy);
101  unsigned AllocSize = DL.getTypeAllocSize(ArgTy);
102 
103  uint64_t EltOffset = alignTo(ExplicitArgOffset, Align) + BaseOffset;
104  ExplicitArgOffset = alignTo(ExplicitArgOffset, Align) + AllocSize;
105 
106  if (Arg.use_empty())
107  continue;
108 
109  if (PointerType *PT = dyn_cast<PointerType>(ArgTy)) {
110  // FIXME: Hack. We rely on AssertZext to be able to fold DS addressing
111  // modes on SI to know the high bits are 0 so pointer adds don't wrap. We
112  // can't represent this with range metadata because it's only allowed for
113  // integer types.
114  if (PT->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
115  ST.getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS)
116  continue;
117 
118  // FIXME: We can replace this with equivalent alias.scope/noalias
119  // metadata, but this appears to be a lot of work.
120  if (Arg.hasNoAliasAttr())
121  continue;
122  }
123 
124  VectorType *VT = dyn_cast<VectorType>(ArgTy);
125  bool IsV3 = VT && VT->getNumElements() == 3;
126  VectorType *V4Ty = nullptr;
127 
128  int64_t AlignDownOffset = alignDown(EltOffset, 4);
129  int64_t OffsetDiff = EltOffset - AlignDownOffset;
130  unsigned AdjustedAlign = MinAlign(KernArgBaseAlign, AlignDownOffset);
131 
132  Value *ArgPtr;
133  if (Size < 32 && !ArgTy->isAggregateType()) { // FIXME: Handle aggregate types
134  // Since we don't have sub-dword scalar loads, avoid doing an extload by
135  // loading earlier than the argument address, and extracting the relevant
136  // bits.
137  //
138  // Additionally widen any sub-dword load to i32 even if suitably aligned,
139  // so that CSE between different argument loads works easily.
140 
141  ArgPtr = Builder.CreateConstInBoundsGEP1_64(
142  KernArgSegment,
143  AlignDownOffset,
144  Arg.getName() + ".kernarg.offset.align.down");
145  ArgPtr = Builder.CreateBitCast(ArgPtr,
146  Builder.getInt32Ty()->getPointerTo(AS),
147  ArgPtr->getName() + ".cast");
148  } else {
149  ArgPtr = Builder.CreateConstInBoundsGEP1_64(
150  KernArgSegment,
151  AlignDownOffset,
152  Arg.getName() + ".kernarg.offset");
153  ArgPtr = Builder.CreateBitCast(ArgPtr, ArgTy->getPointerTo(AS),
154  ArgPtr->getName() + ".cast");
155  }
156 
157  if (IsV3 && Size >= 32) {
158  V4Ty = VectorType::get(VT->getVectorElementType(), 4);
159  // Use the hack that clang uses to avoid SelectionDAG ruining v3 loads
160  ArgPtr = Builder.CreateBitCast(ArgPtr, V4Ty->getPointerTo(AS));
161  }
162 
163  LoadInst *Load = Builder.CreateAlignedLoad(ArgPtr, AdjustedAlign);
165 
166  MDBuilder MDB(Ctx);
167 
168  if (isa<PointerType>(ArgTy)) {
169  if (Arg.hasNonNullAttr())
171 
172  uint64_t DerefBytes = Arg.getDereferenceableBytes();
173  if (DerefBytes != 0) {
174  Load->setMetadata(
176  MDNode::get(Ctx,
177  MDB.createConstant(
178  ConstantInt::get(Builder.getInt64Ty(), DerefBytes))));
179  }
180 
181  uint64_t DerefOrNullBytes = Arg.getDereferenceableOrNullBytes();
182  if (DerefOrNullBytes != 0) {
183  Load->setMetadata(
185  MDNode::get(Ctx,
186  MDB.createConstant(ConstantInt::get(Builder.getInt64Ty(),
187  DerefOrNullBytes))));
188  }
189 
190  unsigned ParamAlign = Arg.getParamAlignment();
191  if (ParamAlign != 0) {
192  Load->setMetadata(
194  MDNode::get(Ctx,
195  MDB.createConstant(ConstantInt::get(Builder.getInt64Ty(),
196  ParamAlign))));
197  }
198  }
199 
200  // TODO: Convert noalias arg to !noalias
201 
202  if (Size < 32 && !ArgTy->isAggregateType()) {
203  Value *ExtractBits = OffsetDiff == 0 ?
204  Load : Builder.CreateLShr(Load, OffsetDiff * 8);
205 
206  IntegerType *ArgIntTy = Builder.getIntNTy(Size);
207  Value *Trunc = Builder.CreateTrunc(ExtractBits, ArgIntTy);
208  Value *NewVal = Builder.CreateBitCast(Trunc, ArgTy,
209  Arg.getName() + ".load");
210  Arg.replaceAllUsesWith(NewVal);
211  } else if (IsV3) {
212  Value *Shuf = Builder.CreateShuffleVector(Load, UndefValue::get(V4Ty),
213  {0, 1, 2},
214  Arg.getName() + ".load");
215  Arg.replaceAllUsesWith(Shuf);
216  } else {
217  Load->setName(Arg.getName() + ".load");
218  Arg.replaceAllUsesWith(Load);
219  }
220  }
221 
222  KernArgSegment->addAttribute(
224  Attribute::getWithAlignment(Ctx, std::max(KernArgBaseAlign, MaxAlign)));
225 
226  return true;
227 }
228 
229 INITIALIZE_PASS_BEGIN(AMDGPULowerKernelArguments, DEBUG_TYPE,
230  "AMDGPU Lower Kernel Arguments", false, false)
232  false, false)
233 
234 char AMDGPULowerKernelArguments::ID = 0;
235 
237  return new AMDGPULowerKernelArguments();
238 }
Type * getVectorElementType() const
Definition: Type.h:371
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
AMDGPU specific subclass of TargetSubtarget.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:25
static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align)
Return a uniquified Attribute object that has the specific alignment set.
Definition: Attributes.cpp:125
static Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
Definition: Attributes.cpp:138
This class represents a function call, abstracting a target machine&#39;s calling convention.
This file contains the declarations for metadata subclasses.
#define DEBUG_TYPE
F(f)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:685
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
An instruction for reading from memory.
Definition: Instructions.h:168
Address space for local memory.
Definition: AMDGPU.h:236
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:264
uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the largest uint64_t less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:718
AnalysisUsage & addRequired()
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:242
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:639
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:731
This file contains the simple types necessary to represent the attributes associated with functions a...
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:295
uint64_t getNumElements() const
Definition: DerivedTypes.h:359
Target-Independent Code Generator Pass Configuration Options.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool arg_empty() const
Definition: Function.h:685
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:439
iterator begin()
Definition: Function.h:642
Class to represent pointers.
Definition: DerivedTypes.h:467
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:610
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
static bool runOnFunction(Function &F, bool PostInlining)
FunctionPass * createAMDGPULowerKernelArgumentsPass()
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
This file contains the declarations for the subclasses of Constant, which represent the different fla...
AMDGPU Lower Kernel Arguments
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
Class to represent integer types.
Definition: DerivedTypes.h:40
The AMDGPU TargetMachine interface definition for hw codgen targets.
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1392
const AMDGPUAS & AS
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1226
INITIALIZE_PASS_BEGIN(AMDGPULowerKernelArguments, DEBUG_TYPE, "AMDGPU Lower Kernel Arguments", false, false) INITIALIZE_PASS_END(AMDGPULowerKernelArguments
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:199
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:722
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
Class to represent vector types.
Definition: DerivedTypes.h:393
void setPreservesAll()
Set by analyses that do not transform their input at all.
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:201
amdgpu Simplify well known AMD library false Value Value * Arg
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:560
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:593
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:59
bool use_empty() const
Definition: Value.h:322
iterator_range< arg_iterator > args()
Definition: Function.h:675