blob: b6d1032806cc18a4cf064a3ee33d768a2a705d94 [file] [log] [blame]
David Netoc5fb5242018-07-30 13:28:31 -04001// Copyright 2018 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <climits>
16#include <map>
17#include <set>
18#include <utility>
19#include <vector>
20
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/UniqueVector.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Module.h"
30#include "llvm/Pass.h"
alan-bakerf26dac92019-11-20 14:41:51 -050031#include "llvm/Support/CommandLine.h"
David Netoc5fb5242018-07-30 13:28:31 -040032#include "llvm/Support/raw_ostream.h"
33
34#include "clspv/Option.h"
David Netoc5fb5242018-07-30 13:28:31 -040035
36#include "ArgKind.h"
alan-bakera71f1932019-04-11 11:04:34 -040037#include "CallGraphOrderedFunctions.h"
Alan Baker202c8c72018-08-13 13:47:44 -040038#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040039#include "Passes.h"
David Netoc5fb5242018-07-30 13:28:31 -040040
41using namespace llvm;
42
43#define DEBUG_TYPE "directresourceaccess"
44
45namespace {
46
47cl::opt<bool> ShowDRA("show-dra", cl::init(false), cl::Hidden,
48 cl::desc("Show direct resource access details"));
49
50using SamplerMapType = llvm::ArrayRef<std::pair<unsigned, std::string>>;
51
52class DirectResourceAccessPass final : public ModulePass {
53public:
54 static char ID;
55 DirectResourceAccessPass() : ModulePass(ID) {}
56 bool runOnModule(Module &M) override;
57
58private:
David Netoc5fb5242018-07-30 13:28:31 -040059 // For each kernel argument that will map to a resource variable (descriptor),
60 // try to rewrite the uses of the argument as a direct access of the resource.
61 // We can only do this if all the callees of the function use the same
62 // resource access value for that argument. Returns true if the module
63 // changed.
64 bool RewriteResourceAccesses(Function *fn);
65
66 // Rewrite uses of this resrouce-based arg if all the callers pass in the
67 // same resource access. Returns true if the module changed.
68 bool RewriteAccessesForArg(Function *fn, int arg_index, Argument &arg);
69};
Diego Novilloa4c44fa2019-04-11 10:56:15 -040070
David Netoc5fb5242018-07-30 13:28:31 -040071} // namespace
72
73char DirectResourceAccessPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -040074INITIALIZE_PASS(DirectResourceAccessPass, "DirectResourceAccessPass",
75 "Direct resource access", false, false)
David Netoc5fb5242018-07-30 13:28:31 -040076
77namespace clspv {
78ModulePass *createDirectResourceAccessPass() {
79 return new DirectResourceAccessPass();
80}
81} // namespace clspv
82
83namespace {
84bool DirectResourceAccessPass::runOnModule(Module &M) {
85 bool Changed = false;
86
87 if (clspv::Option::DirectResourceAccess()) {
alan-bakera71f1932019-04-11 11:04:34 -040088 auto ordered_functions = clspv::CallGraphOrderedFunctions(M);
89 if (ShowDRA) {
90 outs() << "DRA: Ordered functions:\n";
91 for (Function *fun : ordered_functions) {
92 outs() << "DRA: " << fun->getName() << "\n";
93 }
94 }
95
David Netoc5fb5242018-07-30 13:28:31 -040096 for (auto *fn : ordered_functions) {
97 Changed |= RewriteResourceAccesses(fn);
98 }
99 }
100
101 return Changed;
102}
103
David Netoc5fb5242018-07-30 13:28:31 -0400104bool DirectResourceAccessPass::RewriteResourceAccesses(Function *fn) {
105 bool Changed = false;
106 int arg_index = 0;
107 for (Argument &arg : fn->args()) {
108 switch (clspv::GetArgKindForType(arg.getType())) {
109 case clspv::ArgKind::Buffer:
Alan Bakerfcda9482018-10-02 17:09:59 -0400110 case clspv::ArgKind::BufferUBO:
David Netoc5fb5242018-07-30 13:28:31 -0400111 case clspv::ArgKind::ReadOnlyImage:
112 case clspv::ArgKind::WriteOnlyImage:
113 case clspv::ArgKind::Sampler:
Alan Baker202c8c72018-08-13 13:47:44 -0400114 case clspv::ArgKind::Local:
David Netoc5fb5242018-07-30 13:28:31 -0400115 Changed |= RewriteAccessesForArg(fn, arg_index, arg);
116 break;
David Neto3a0df832018-08-03 14:35:42 -0400117 default:
118 // Should not happen
119 break;
David Netoc5fb5242018-07-30 13:28:31 -0400120 }
121 arg_index++;
122 }
123 return Changed;
124}
125
126bool DirectResourceAccessPass::RewriteAccessesForArg(Function *fn,
127 int arg_index,
128 Argument &arg) {
129 bool Changed = false;
130 if (fn->use_empty()) {
131 return false;
132 }
133
134 // We can convert a parameter to a direct resource access if it is
135 // either a direct call to a clspv.resource.var.* or if it a GEP of
136 // such a thing (where the GEP can only have zero indices).
137 struct ParamInfo {
Alan Baker202c8c72018-08-13 13:47:44 -0400138 // The base value. It is either a global variable or a resource-access
139 // builtin function. (@clspv.resource.var.* or @clspv.local.var.*)
140 Value *base;
David Netoc5fb5242018-07-30 13:28:31 -0400141 // The descriptor set.
142 uint32_t set;
143 // The binding.
144 uint32_t binding;
145 // If the parameter is a GEP, then this is the number of zero-indices
146 // the GEP used.
147 unsigned num_gep_zeroes;
148 // An example call fitting
149 CallInst *sample_call;
150 };
151 // The common valid parameter info across all the callers seen soo far.
152
153 bool seen_one = false;
154 ParamInfo common;
155 // Tries to merge the given parameter info into |common|. If it is the first
156 // time we've tried, then save it. Returns true if there is no conflict.
157 auto merge_param_info = [&seen_one, &common](const ParamInfo &pi) {
158 if (!seen_one) {
159 common = pi;
160 seen_one = true;
161 return true;
162 }
Alan Baker202c8c72018-08-13 13:47:44 -0400163 return pi.base == common.base && pi.set == common.set &&
David Netoc5fb5242018-07-30 13:28:31 -0400164 pi.binding == common.binding &&
165 pi.num_gep_zeroes == common.num_gep_zeroes;
166 };
167
168 for (auto &use : fn->uses()) {
169 if (auto *caller = dyn_cast<CallInst>(use.getUser())) {
170 Value *value = caller->getArgOperand(arg_index);
171 // We care about two cases:
172 // - a direct call to clspv.resource.var.*
173 // - a GEP with only zero indices, where the base pointer is
174
175 // Unpack GEPs with zeros, if we can. Rewrite |value| as we go along.
176 unsigned num_gep_zeroes = 0;
David Neto2f450002018-08-01 16:13:03 -0400177 bool first_gep = true;
David Netoc5fb5242018-07-30 13:28:31 -0400178 for (auto *gep = dyn_cast<GetElementPtrInst>(value); gep;
179 gep = dyn_cast<GetElementPtrInst>(value)) {
180 if (!gep->hasAllZeroIndices()) {
181 return false;
182 }
David Neto2f450002018-08-01 16:13:03 -0400183 // If not the first GEP, then ignore the "element" index (which I call
184 // "slide") since that will be combined with the last index of the
185 // previous GEP.
186 num_gep_zeroes += gep->getNumIndices() + (first_gep ? 0 : -1);
David Netoc5fb5242018-07-30 13:28:31 -0400187 value = gep->getPointerOperand();
David Neto2f450002018-08-01 16:13:03 -0400188 first_gep = false;
David Netoc5fb5242018-07-30 13:28:31 -0400189 }
190 if (auto *call = dyn_cast<CallInst>(value)) {
191 // If the call is a call to a @clspv.resource.var.* function, then try
192 // to merge it, assuming the given number of GEP zero-indices so far.
193 if (call->getCalledFunction()->getName().startswith(
Alan Baker202c8c72018-08-13 13:47:44 -0400194 clspv::ResourceAccessorFunction())) {
David Netoc5fb5242018-07-30 13:28:31 -0400195 const auto set = uint32_t(
196 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
197 const auto binding = uint32_t(
198 dyn_cast<ConstantInt>(call->getOperand(1))->getZExtValue());
199 if (!merge_param_info({call->getCalledFunction(), set, binding,
Alan Baker202c8c72018-08-13 13:47:44 -0400200 num_gep_zeroes, call}))
David Netoc5fb5242018-07-30 13:28:31 -0400201 return false;
Alan Baker202c8c72018-08-13 13:47:44 -0400202 } else if (call->getCalledFunction()->getName().startswith(
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400203 clspv::WorkgroupAccessorFunction())) {
Alan Baker202c8c72018-08-13 13:47:44 -0400204 const uint32_t spec_id = uint32_t(
205 dyn_cast<ConstantInt>(call->getOperand(0))->getZExtValue());
206 if (!merge_param_info({call->getCalledFunction(), spec_id, 0,
207 num_gep_zeroes, call}))
208 return false;
David Netoc5fb5242018-07-30 13:28:31 -0400209 } else {
210 // A call but not to a resource access builtin function.
211 return false;
212 }
Alan Baker202c8c72018-08-13 13:47:44 -0400213 } else if (isa<GlobalValue>(value)) {
214 if (!merge_param_info({value, 0, 0, num_gep_zeroes, nullptr}))
215 return false;
David Netoc5fb5242018-07-30 13:28:31 -0400216 } else {
217 // Not a call.
218 return false;
219 }
220 } else {
221 // There isn't enough commonality. Bail out without changing anything.
222 return false;
223 }
224 }
225 if (ShowDRA) {
226 if (seen_one) {
227 outs() << "DRA: Rewrite " << fn->getName() << " arg " << arg_index << " "
Alan Baker202c8c72018-08-13 13:47:44 -0400228 << arg.getName() << ": " << common.base->getName() << " ("
David Netoc5fb5242018-07-30 13:28:31 -0400229 << common.set << "," << common.binding
Alan Bakerfc6888e2018-08-20 20:54:33 -0400230 << ") zeroes: " << common.num_gep_zeroes << " sample-call ";
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400231 if (common.sample_call)
232 outs() << *common.sample_call << "\n";
233 else
234 outs() << "nullptr\n";
David Netoc5fb5242018-07-30 13:28:31 -0400235 }
236 }
237
238 // Now rewrite the argument, using the info in |common|.
239
240 Changed = true;
241 IRBuilder<> Builder(fn->getParent()->getContext());
242 auto *zero = Builder.getInt32(0);
243 Builder.SetInsertPoint(fn->getEntryBlock().getFirstNonPHI());
244
Alan Baker202c8c72018-08-13 13:47:44 -0400245 Value *replacement = common.base;
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400246 if (Function *function = dyn_cast<Function>(replacement)) {
Alan Baker202c8c72018-08-13 13:47:44 -0400247 // Create the call.
248 SmallVector<Value *, 8> args(common.sample_call->arg_begin(),
249 common.sample_call->arg_end());
250 replacement = Builder.CreateCall(function, args);
251 if (ShowDRA) {
252 outs() << "DRA: Replace: call " << *replacement << "\n";
253 }
David Netoc5fb5242018-07-30 13:28:31 -0400254 }
255 if (common.num_gep_zeroes) {
256 SmallVector<Value *, 3> zeroes;
257 for (unsigned i = 0; i < common.num_gep_zeroes; i++) {
258 zeroes.push_back(zero);
259 }
Alan Baker202c8c72018-08-13 13:47:44 -0400260 // Builder.CreateGEP is not used to avoid creating a GEPConstantExpr in the
261 // case of global variables.
262 replacement = GetElementPtrInst::Create(nullptr, replacement, zeroes);
263 Builder.Insert(cast<Instruction>(replacement));
David Netoc5fb5242018-07-30 13:28:31 -0400264 if (ShowDRA) {
265 outs() << "DRA: Replace: gep " << *replacement << "\n";
266 }
267 }
268 arg.replaceAllUsesWith(replacement);
269
270 return Changed;
271}
272
273} // namespace