LLVM  7.0.0
AMDGPUAnnotateUniformValues.cpp
Go to the documentation of this file.
1 //===-- AMDGPUAnnotateUniformValues.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
11 /// This pass adds amdgpu.uniform metadata to IR values so this information
12 /// can be used during instruction selection.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "AMDGPU.h"
17 #include "AMDGPUIntrinsicInfo.h"
18 #include "llvm/ADT/SetVector.h"
20 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/InstVisitor.h"
24 #include "llvm/Support/Debug.h"
26 
27 #define DEBUG_TYPE "amdgpu-annotate-uniform"
28 
29 using namespace llvm;
30 
31 namespace {
32 
33 class AMDGPUAnnotateUniformValues : public FunctionPass,
34  public InstVisitor<AMDGPUAnnotateUniformValues> {
37  LoopInfo *LI;
39  bool isKernelFunc;
40  AMDGPUAS AMDGPUASI;
41 
42 public:
43  static char ID;
44  AMDGPUAnnotateUniformValues() :
45  FunctionPass(ID) { }
46  bool doInitialization(Module &M) override;
47  bool runOnFunction(Function &F) override;
48  StringRef getPassName() const override {
49  return "AMDGPU Annotate Uniform Values";
50  }
51  void getAnalysisUsage(AnalysisUsage &AU) const override {
55  AU.setPreservesAll();
56  }
57 
58  void visitBranchInst(BranchInst &I);
59  void visitLoadInst(LoadInst &I);
60  bool isClobberedInFunction(LoadInst * Load);
61 };
62 
63 } // End anonymous namespace
64 
65 INITIALIZE_PASS_BEGIN(AMDGPUAnnotateUniformValues, DEBUG_TYPE,
66  "Add AMDGPU uniform metadata", false, false)
70 INITIALIZE_PASS_END(AMDGPUAnnotateUniformValues, DEBUG_TYPE,
72 
73 char AMDGPUAnnotateUniformValues::ID = 0;
74 
76  I->setMetadata("amdgpu.uniform", MDNode::get(I->getContext(), {}));
77 }
79  I->setMetadata("amdgpu.noclobber", MDNode::get(I->getContext(), {}));
80 }
81 
82 static void DFS(BasicBlock *Root, SetVector<BasicBlock*> & Set) {
83  for (auto I : predecessors(Root))
84  if (Set.insert(I))
85  DFS(I, Set);
86 }
87 
88 bool AMDGPUAnnotateUniformValues::isClobberedInFunction(LoadInst * Load) {
89  // 1. get Loop for the Load->getparent();
90  // 2. if it exists, collect all the BBs from the most outer
91  // loop and check for the writes. If NOT - start DFS over all preds.
92  // 3. Start DFS over all preds from the most outer loop header.
93  SetVector<BasicBlock *> Checklist;
94  BasicBlock *Start = Load->getParent();
95  Checklist.insert(Start);
96  const Value *Ptr = Load->getPointerOperand();
97  const Loop *L = LI->getLoopFor(Start);
98  if (L) {
99  const Loop *P = L;
100  do {
101  L = P;
102  P = P->getParentLoop();
103  } while (P);
104  Checklist.insert(L->block_begin(), L->block_end());
105  Start = L->getHeader();
106  }
107 
108  DFS(Start, Checklist);
109  for (auto &BB : Checklist) {
110  BasicBlock::iterator StartIt = (!L && (BB == Load->getParent())) ?
111  BasicBlock::iterator(Load) : BB->end();
112  auto Q = MDR->getPointerDependencyFrom(MemoryLocation(Ptr), true,
113  StartIt, BB, Load);
114  if (Q.isClobber() || Q.isUnknown())
115  return true;
116  }
117  return false;
118 }
119 
120 void AMDGPUAnnotateUniformValues::visitBranchInst(BranchInst &I) {
121  if (I.isUnconditional())
122  return;
123 
124  Value *Cond = I.getCondition();
125  if (!DA->isUniform(Cond))
126  return;
127 
129 }
130 
131 void AMDGPUAnnotateUniformValues::visitLoadInst(LoadInst &I) {
132  Value *Ptr = I.getPointerOperand();
133  if (!DA->isUniform(Ptr))
134  return;
135  auto isGlobalLoad = [&](LoadInst &Load)->bool {
136  return Load.getPointerAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS;
137  };
138  // We're tracking up to the Function boundaries
139  // We cannot go beyond because of FunctionPass restrictions
140  // Thus we can ensure that memory not clobbered for memory
141  // operations that live in kernel only.
142  bool NotClobbered = isKernelFunc && !isClobberedInFunction(&I);
143  Instruction *PtrI = dyn_cast<Instruction>(Ptr);
144  if (!PtrI && NotClobbered && isGlobalLoad(I)) {
145  if (isa<Argument>(Ptr) || isa<GlobalValue>(Ptr)) {
146  // Lookup for the existing GEP
147  if (noClobberClones.count(Ptr)) {
148  PtrI = noClobberClones[Ptr];
149  } else {
150  // Create GEP of the Value
151  Function *F = I.getParent()->getParent();
153  Type::getInt32Ty(Ptr->getContext()), APInt(64, 0));
154  // Insert GEP at the entry to make it dominate all uses
156  Ptr->getType()->getPointerElementType(), Ptr,
158  }
159  I.replaceUsesOfWith(Ptr, PtrI);
160  }
161  }
162 
163  if (PtrI) {
164  setUniformMetadata(PtrI);
165  if (NotClobbered)
166  setNoClobberMetadata(PtrI);
167  }
168 }
169 
170 bool AMDGPUAnnotateUniformValues::doInitialization(Module &M) {
171  AMDGPUASI = AMDGPU::getAMDGPUAS(M);
172  return false;
173 }
174 
176  if (skipFunction(F))
177  return false;
178 
179  DA = &getAnalysis<DivergenceAnalysis>();
180  MDR = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
181  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
182  isKernelFunc = F.getCallingConv() == CallingConv::AMDGPU_KERNEL;
183 
184  visit(F);
185  noClobberClones.clear();
186  return true;
187 }
188 
189 FunctionPass *
191  return new AMDGPUAnnotateUniformValues();
192 }
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM&#39;s alias analysis passes.
Base class for instruction visitors.
Definition: InstVisitor.h:81
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:867
AMDGPUAS getAMDGPUAS(const Module &M)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:714
F(f)
An instruction for reading from memory.
Definition: Instructions.h:168
Value * getCondition() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Type * getPointerElementType() const
Definition: Type.h:376
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
OpenCL uses address spaces to differentiate between various memory regions on the hardware...
Definition: AMDGPU.h:224
T uniform(GenT &Gen, T Min, T Max)
Return a uniformly distributed random value between Min and Max.
Definition: Random.h:22
BlockT * getHeader() const
Definition: LoopInfo.h:100
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:21
const BasicBlock & getEntryBlock() const
Definition: Function.h:626
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
static bool runOnFunction(Function &F, bool PostInlining)
#define P(N)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:189
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
Conditional or Unconditional Branch instruction.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
Value * getPointerOperand()
Definition: Instructions.h:274
static void setNoClobberMetadata(Instruction *I)
#define DEBUG_TYPE
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Add AMDGPU uniform metadata
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1226
FunctionPass * createAMDGPUAnnotateUniformValues()
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:305
Representation for a specific memory location.
Iterator for intrusive lists based on ilist_node.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition: Function.h:199
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:113
INITIALIZE_PASS_BEGIN(AMDGPUAnnotateUniformValues, DEBUG_TYPE, "Add AMDGPU uniform metadata", false, false) INITIALIZE_PASS_END(AMDGPUAnnotateUniformValues
Class for arbitrary precision integers.
Definition: APInt.h:69
Interface for the AMDGPU Implementation of the Intrinsic Info class.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:201
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:91
static void DFS(BasicBlock *Root, SetVector< BasicBlock *> &Set)
LoopT * getParentLoop() const
Definition: LoopInfo.h:101
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:459
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
#define I(x, y, z)
Definition: MD5.cpp:58
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
block_iterator block_end() const
Definition: LoopInfo.h:155
bool isUnconditional() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:280
LLVM Value Representation.
Definition: Value.h:73
A vector that has set insertion semantics.
Definition: SetVector.h:41
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:964
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:138
block_iterator block_begin() const
Definition: LoopInfo.h:154
static void setUniformMetadata(Instruction *I)
const BasicBlock * getParent() const
Definition: Instruction.h:67