blob: 267a9404841c447ba08a0308e3b3b01d43b06ed3 [file] [log] [blame]
David Netodd992212017-06-23 17:47:55 -04001// Copyright 2017 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
David Neto156783e2017-07-05 15:39:41 -040015// Cluster POD kernel arguments.
16//
17// Collect plain-old-data kernel arguments and place them into a single
18// struct argument, at the end. Other arguments are pointers, and retain
19// their relative order.
20//
21// We will create a kernel function as the new entry point, and change
22// the original kernel function into a regular SPIR function. Key
23// kernel metadata is moved from the old function to the wrapper.
24// We also attach a "kernel_arg_map" metadata node to the function to
25// encode the mapping from old kernel argument to new kernel argument.
26
David Netodd992212017-06-23 17:47:55 -040027#include <cassert>
28
29#include <llvm/IR/Constants.h>
30#include <llvm/IR/DerivedTypes.h>
31#include <llvm/IR/Function.h>
32#include <llvm/IR/Instructions.h>
33#include <llvm/IR/IRBuilder.h>
David Neto156783e2017-07-05 15:39:41 -040034#include <llvm/IR/Metadata.h>
David Netodd992212017-06-23 17:47:55 -040035#include <llvm/IR/Module.h>
36#include <llvm/Pass.h>
David Netod5b3f982017-09-28 14:49:49 -040037#include <llvm/Support/CommandLine.h>
David Netodd992212017-06-23 17:47:55 -040038#include <llvm/Support/raw_ostream.h>
David Netod5b3f982017-09-28 14:49:49 -040039#include <llvm/Transforms/Utils/Cloning.h>
David Netodd992212017-06-23 17:47:55 -040040
David Neto4feb7a42017-10-06 17:29:42 -040041#include "ArgKind.h"
David Netodd992212017-06-23 17:47:55 -040042
43using namespace llvm;
44
45#define DEBUG_TYPE "clusterpodkernelargs"
46
47namespace {
48struct ClusterPodKernelArgumentsPass : public ModulePass {
49 static char ID;
50 ClusterPodKernelArgumentsPass() : ModulePass(ID) {}
51
52 bool runOnModule(Module &M) override;
53};
David Neto48f56a42017-10-06 16:44:25 -040054
David Netodd992212017-06-23 17:47:55 -040055} // namespace
56
57char ClusterPodKernelArgumentsPass::ID = 0;
58static RegisterPass<ClusterPodKernelArgumentsPass>
59 X("ClusterPodKernelArgumentsPass",
60 "Cluster POD Kernel Arguments Pass");
61
62namespace clspv {
63llvm::ModulePass *createClusterPodKernelArgumentsPass() {
64 return new ClusterPodKernelArgumentsPass();
65}
66} // namespace clspv
67
68bool ClusterPodKernelArgumentsPass::runOnModule(Module &M) {
69 bool Changed = false;
70 LLVMContext &Context = M.getContext();
71
72 SmallVector<Function *, 8> WorkList;
73
74 for (Function &F : M) {
75 if (F.isDeclaration() || F.getCallingConv() != CallingConv::SPIR_KERNEL) {
76 continue;
77 }
78 for (Argument &Arg : F.args()) {
79 if (!isa<PointerType>(Arg.getType())) {
80 WorkList.push_back(&F);
81 break;
82 }
83 }
84 }
85
David Netod5b3f982017-09-28 14:49:49 -040086 SmallVector<CallInst*, 8> CallList;
87
David Netodd992212017-06-23 17:47:55 -040088 for (Function* F : WorkList) {
89 Changed = true;
90
David Neto156783e2017-07-05 15:39:41 -040091 // An ArgMapping describes how a kernel argument is remapped.
92 struct ArgMapping {
93 std::string name;
94 // 0-based argument index in the old kernel function.
95 unsigned old_index;
96 // 0-based argument index in the new kernel function.
97 unsigned new_index;
98 // Offset of the argument value within the new kernel argument.
99 // This is always zero for non-POD arguments. For a POD argument,
100 // this is the byte offset within the POD arguments struct.
101 unsigned offset;
David Neto48f56a42017-10-06 16:44:25 -0400102 // Argument type. Same range of values as the result of
David Neto4feb7a42017-10-06 17:29:42 -0400103 // clspv::GetArgKindForType.
104 const char* arg_kind;
David Neto156783e2017-07-05 15:39:41 -0400105 };
106
David Netodd992212017-06-23 17:47:55 -0400107 // In OpenCL, kernel arguments are either pointers or POD. A composite with
108 // an element or memeber that is a pointer is not allowed. So we'll use POD
109 // as a shorthand for non-pointer.
110
111 SmallVector<Type *, 8> PtrArgTys;
112 SmallVector<Type *, 8> PodArgTys;
David Neto156783e2017-07-05 15:39:41 -0400113 SmallVector<ArgMapping, 8> RemapInfo;
114 unsigned arg_index = 0;
David Netodd992212017-06-23 17:47:55 -0400115 for (Argument &Arg : F->args()) {
116 Type *ArgTy = Arg.getType();
117 if (isa<PointerType>(ArgTy)) {
118 PtrArgTys.push_back(ArgTy);
David Neto156783e2017-07-05 15:39:41 -0400119 RemapInfo.push_back({std::string(Arg.getName()), arg_index,
David Neto48f56a42017-10-06 16:44:25 -0400120 unsigned(RemapInfo.size()), 0u,
David Neto4feb7a42017-10-06 17:29:42 -0400121 clspv::GetArgKindForType(ArgTy)});
David Netodd992212017-06-23 17:47:55 -0400122 } else {
123 PodArgTys.push_back(ArgTy);
124 }
David Neto156783e2017-07-05 15:39:41 -0400125 arg_index++;
David Netodd992212017-06-23 17:47:55 -0400126 }
127
David Netodd992212017-06-23 17:47:55 -0400128 // Put the pointer arguments first, and then POD arguments struct last.
David Neto2ded02e2017-10-23 15:30:59 -0400129 // Use StructType::get so we reuse types where possible.
130 auto PodArgsStructTy = StructType::get(Context, PodArgTys);
David Netodd992212017-06-23 17:47:55 -0400131 SmallVector<Type *, 8> NewFuncParamTys(PtrArgTys);
132 NewFuncParamTys.push_back(PodArgsStructTy);
133
David Neto156783e2017-07-05 15:39:41 -0400134 // We've recorded the remapping for pointer arguments. Now record the
135 // remapping for POD arguments.
136 {
137 const auto StructLayout =
138 M.getDataLayout().getStructLayout(PodArgsStructTy);
139 arg_index = 0;
140 int pod_index = 0;
141 const unsigned num_pointer_args = unsigned(RemapInfo.size());
142 for (Argument &Arg : F->args()) {
143 Type *ArgTy = Arg.getType();
144 if (!isa<PointerType>(ArgTy)) {
145 RemapInfo.push_back(
146 {std::string(Arg.getName()), arg_index, num_pointer_args,
David Neto48f56a42017-10-06 16:44:25 -0400147 unsigned(StructLayout->getElementOffset(pod_index++)),
David Neto4feb7a42017-10-06 17:29:42 -0400148 clspv::GetArgKindForType(ArgTy)});
David Neto156783e2017-07-05 15:39:41 -0400149 }
150 arg_index++;
151 }
152 }
153
David Netodd992212017-06-23 17:47:55 -0400154 FunctionType *NewFuncTy =
155 FunctionType::get(F->getReturnType(), NewFuncParamTys, false);
156
157 // Create the new function and set key properties.
158 auto NewFunc = Function::Create(NewFuncTy, F->getLinkage());
159 // The new function adopts the real name so that linkage to the outside
160 // world remains the same.
161 NewFunc->setName(F->getName());
162 F->setName(NewFunc->getName().str() + ".inner");
163
164 NewFunc->setCallingConv(F->getCallingConv());
165 F->setCallingConv(CallingConv::SPIR_FUNC);
166
167 NewFunc->setAttributes(F->getAttributes());
168 // Move OpenCL kernel named attributes.
169 // TODO(dneto): Attributes starting with kernel_arg_* should be rewritten
170 // to reflect change in the argument shape.
171 std::vector<const char *> Metadatas{
172 "reqd_work_group_size", "kernel_arg_addr_space",
173 "kernel_arg_access_qual", "kernel_arg_type",
174 "kernel_arg_base_type", "kernel_arg_type_qual"};
175 for (auto name : Metadatas) {
176 NewFunc->setMetadata(name, F->getMetadata(name));
177 F->setMetadata(name, nullptr);
178 }
179
David Neto156783e2017-07-05 15:39:41 -0400180 IRBuilder<> Builder(BasicBlock::Create(Context, "entry", NewFunc));
181
182 // Set kernel argument mapping metadata.
183 {
184 // Attach a metadata node named "kernel_arg_map" to the new kernel
185 // function. It is a tuple of nodes, each of which is a tuple for
186 // each argument, with members:
187 // - Argument name
188 // - Ordinal index in the original kernel function
189 // - Ordinal index in the new kernel function
190 // - Byte offset within the argument. This is always 0 for pointer
191 // arguments. For POD arguments this is the offest within the POD
192 // argument struct.
David Neto48f56a42017-10-06 16:44:25 -0400193 // - Argument type
David Neto156783e2017-07-05 15:39:41 -0400194 LLVMContext& Context = M.getContext();
195 SmallVector<Metadata*, 8> mappings;
196 for (auto &arg_mapping : RemapInfo) {
197 auto *name_md = MDString::get(Context, arg_mapping.name);
198 auto *old_index_md =
199 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.old_index));
200 auto *new_index_md =
201 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.new_index));
202 auto *offset =
203 ConstantAsMetadata::get(Builder.getInt32(arg_mapping.offset));
David Neto4feb7a42017-10-06 17:29:42 -0400204 auto *argtype_md = MDString::get(Context, arg_mapping.arg_kind);
David Neto48f56a42017-10-06 16:44:25 -0400205 auto *arg_md = MDNode::get(
206 Context, {name_md, old_index_md, new_index_md, offset, argtype_md});
David Neto156783e2017-07-05 15:39:41 -0400207 mappings.push_back(arg_md);
208 }
209
210 NewFunc->setMetadata("kernel_arg_map", MDNode::get(Context, mappings));
211 }
212
David Netodd992212017-06-23 17:47:55 -0400213 // Insert the function after the original, to preserve ordering
214 // in the module as much as possible.
215 auto &FunctionList = M.getFunctionList();
216 for (auto Iter = FunctionList.begin(), IterEnd = FunctionList.end();
217 Iter != IterEnd; ++Iter) {
218 if (&*Iter == F) {
219 FunctionList.insertAfter(Iter, NewFunc);
220 break;
221 }
222 }
223
224 // The body of the wrapper is essentially a call to the original function,
225 // but we have to unwrap the non-pointer arguments from the struct.
David Netodd992212017-06-23 17:47:55 -0400226
227 // Map the wrapper's arguments to the callee's arguments.
228 SmallVector<Argument *, 8> CallerArgs;
229 for (Argument &Arg : NewFunc->args()) {
230 CallerArgs.push_back(&Arg);
231 }
232 Argument *PodArg = CallerArgs.back();
233 PodArg->setName("podargs");
234
235 SmallVector<Value *, 8> CalleeArgs;
236 unsigned podIndex = 0;
237 unsigned ptrIndex = 0;
238 for (const Argument &Arg : F->args()) {
239 if (isa<PointerType>(Arg.getType())) {
240 CalleeArgs.push_back(CallerArgs[ptrIndex++]);
241 } else {
242 CalleeArgs.push_back(Builder.CreateExtractValue(PodArg, {podIndex++}));
243 }
244 CalleeArgs.back()->setName(Arg.getName());
245 }
246 assert(ptrIndex + podIndex == F->arg_size());
247 assert(ptrIndex = PtrArgTys.size());
248 assert(podIndex = PodArgTys.size());
249
250 auto Call = Builder.CreateCall(F, CalleeArgs);
251 Call->setCallingConv(F->getCallingConv());
David Netod5b3f982017-09-28 14:49:49 -0400252 CallList.push_back(Call);
David Netodd992212017-06-23 17:47:55 -0400253
254 Builder.CreateRetVoid();
255 }
256
David Neto482550a2018-03-24 05:21:07 -0700257 // Inline the inner function. It's cleaner to do this.
258 for (CallInst *C : CallList) {
259 InlineFunctionInfo info;
260 Changed |= InlineFunction(C, info);
David Netod5b3f982017-09-28 14:49:49 -0400261 }
262
David Netodd992212017-06-23 17:47:55 -0400263 return Changed;
264}