blob: 371131a1a8f69925aa0afd5558c9e3eff28a611d [file] [log] [blame]
David Netoab03f432017-11-03 17:00:44 -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
15#include <string>
David Neto8e39bd12017-11-14 21:08:12 -050016#include <utility>
David Netoab03f432017-11-03 17:00:44 -040017
David Neto118188e2018-08-24 11:27:54 -040018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/UniqueVector.h"
21#include "llvm/IR/Attributes.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/raw_ostream.h"
David Netoab03f432017-11-03 17:00:44 -040030
David Neto482550a2018-03-24 05:21:07 -070031#include "clspv/Option.h"
32
David Netoab03f432017-11-03 17:00:44 -040033using namespace llvm;
34using std::string;
35
David Neto8e39bd12017-11-14 21:08:12 -050036#define DEBUG_TYPE "rewriteinserts"
David Netoab03f432017-11-03 17:00:44 -040037
David Netoab03f432017-11-03 17:00:44 -040038namespace {
39
40const char* kCompositeConstructFunctionPrefix = "clspv.composite_construct.";
41
42class RewriteInsertsPass : public ModulePass {
43 public:
44 static char ID;
45 RewriteInsertsPass() : ModulePass(ID) {}
46
47 bool runOnModule(Module &M) override;
48
49 private:
Alan Bakerabc935e2018-09-06 11:33:53 -040050 using InsertionVector = SmallVector<Instruction *, 4>;
David Netoab03f432017-11-03 17:00:44 -040051
David Neto8e39bd12017-11-14 21:08:12 -050052 // Replaces chains of insertions that cover the entire value.
53 // Such a change always reduces the number of instructions, so
54 // we always perform these. Returns true if the module was modified.
55 bool ReplaceCompleteInsertionChains(Module &M);
56
57 // Replaces all InsertValue instructions, even if they aren't part
58 // of a complete insetion chain. Returns true if the module was modified.
59 bool ReplacePartialInsertions(Module &M);
60
61 // Load |values| and |chain| with the members of the struct value produced
62 // by a chain of InsertValue instructions ending with |iv|, and following
63 // the aggregate operand. Return the start of the chain: the aggregate
64 // value which is not an InsertValue instruction, or an InsertValue
65 // instruction which inserts a component that is replaced later in the
66 // chain. The |values| vector will match the order of struct members and
67 // is initialized to all nullptr members. The |chain| vector will list
68 // the chain of InsertValue instructions, listed in the order we discover
69 // them, e.g. begining with |iv|.
70 Value *LoadValuesEndingWithInsertion(InsertValueInst *iv,
71 std::vector<Value *> *values,
72 InsertionVector *chain) {
73 auto *structTy = dyn_cast<StructType>(iv->getType());
74 assert(structTy);
75 const auto numElems = structTy->getNumElements();
76
77 // Walk backward from the tail to an instruction we don't want to
78 // replace.
79 Value *frontier = iv;
80 while (auto *insertion = dyn_cast<InsertValueInst>(frontier)) {
81 chain->push_back(insertion);
82 // Only handle single-index insertions.
83 if (insertion->getNumIndices() == 1) {
84 // Try to replace this one.
85
86 unsigned index = insertion->getIndices()[0];
87 assert(index < numElems);
88 if ((*values)[index] != nullptr) {
89 // We already have a value for this slot. Stop now.
90 break;
91 }
92 (*values)[index] = insertion->getInsertedValueOperand();
93 frontier = insertion->getAggregateOperand();
94 } else {
95 break;
96 }
97 }
98 return frontier;
99 }
100
Alan Bakerabc935e2018-09-06 11:33:53 -0400101 // Returns the number of elements in the struct or array.
102 unsigned GetNumElements(Type *type) {
103 // CompositeType doesn't implement getNumElements(), but its inheritors
104 // do.
105 if (auto *struct_ty = dyn_cast<StructType>(type)) {
106 return struct_ty->getNumElements();
107 } else if (auto *seq_ty = dyn_cast<SequentialType>(type)) {
108 return seq_ty->getNumElements();
109 }
110 return 0;
111 }
112
113
David Netoab03f432017-11-03 17:00:44 -0400114 // If this is the tail of a chain of InsertValueInst instructions
115 // that covers the entire composite, then return a small vector
116 // containing the insertion instructions, in member order.
Alan Bakerabc935e2018-09-06 11:33:53 -0400117 // Otherwise returns nullptr.
David Netoab03f432017-11-03 17:00:44 -0400118 InsertionVector *CompleteInsertionChain(InsertValueInst *iv) {
119 if (iv->getNumIndices() == 1) {
Alan Bakerf8661412018-08-29 10:18:16 -0400120 auto numElems = GetNumElements(iv->getType());
121 if (numElems != 0) {
David Netoab03f432017-11-03 17:00:44 -0400122 // Only handle single-index insertions.
123 unsigned index = iv->getIndices()[0];
124 if (index + 1u != numElems) {
125 // Not the last in the chain.
126 return nullptr;
127 }
128 InsertionVector candidates(numElems, nullptr);
129 for (unsigned i = index;
130 iv->getNumIndices() == 1 && i == iv->getIndices()[0]; --i) {
131 // iv inserts the i'th member
132 candidates[i] = iv;
133
134 if (i == 0) {
135 // We're done!
136 return new InsertionVector(candidates);
137 }
138
139 if (InsertValueInst *agg =
140 dyn_cast<InsertValueInst>(iv->getAggregateOperand())) {
141 iv = agg;
142 } else {
143 // The chain is broken.
144 break;
145 }
146 }
147 }
148 }
149 return nullptr;
150 }
151
Alan Bakerabc935e2018-09-06 11:33:53 -0400152 // If this is the tail of a chain of InsertElementInst instructions
153 // that covers the entire vector, then return a small vector
154 // containing the insertion instructions, in member order.
155 // Otherwise returns nullptr. Only handle insertions into vectors.
156 InsertionVector *CompleteInsertionChain(InsertElementInst *ie) {
157 // Don't handle i8 vectors. Only <4 x i8> is supported and it is
158 // translated as i32. Only handle single-index insertions.
159 if (auto vec_ty = dyn_cast<VectorType>(ie->getType())) {
160 if (vec_ty->getVectorElementType() == Type::getInt8Ty(ie->getContext())) {
161 return nullptr;
162 }
163 }
164
165 // Only handle single-index insertions.
166 if (ie->getNumOperands() == 3) {
167 auto numElems = GetNumElements(ie->getType());
168 if (numElems != 0) {
169 if (auto *const_value = dyn_cast<ConstantInt>(ie->getOperand(2))) {
170 uint64_t index = const_value->getZExtValue();
171 if (index + 1u != numElems) {
172 // Not the last in the chain.
173 return nullptr;
174 }
175 InsertionVector candidates(numElems, nullptr);
176 Value *value = ie;
177 uint64_t i = index;
178 while (auto *insert = dyn_cast<InsertElementInst>(value)) {
179 if (insert->getNumOperands() != 3) break;
180 if (auto *index_const = dyn_cast<ConstantInt>(insert->getOperand(2))) {
181 if (i != index_const->getZExtValue()) break;
182
183 candidates[i] = insert;
184 if (i == 0) {
185 // We're done!
186 return new InsertionVector(candidates);
187 }
188
189 value = insert->getOperand(0);
190 --i;
191 } else {
192 break;
193 }
194 }
195 } else {
196 return nullptr;
197 }
198 }
199 }
200 return nullptr;
201 }
David Neto8e39bd12017-11-14 21:08:12 -0500202
David Netoab03f432017-11-03 17:00:44 -0400203 // Return the name for the wrap function for the given type.
204 string &WrapFunctionNameForType(Type *type) {
205 auto where = function_for_type_.find(type);
206 if (where == function_for_type_.end()) {
207 // Insert it.
208 auto &result = function_for_type_[type] =
209 string(kCompositeConstructFunctionPrefix) +
210 std::to_string(function_for_type_.size());
211 return result;
212 } else {
213 return where->second;
214 }
215 }
216
David Neto8e39bd12017-11-14 21:08:12 -0500217 // Get or create the composite construct function definition.
Alan Bakerabc935e2018-09-06 11:33:53 -0400218 Function *GetConstructFunction(Module &M, CompositeType *constructed_type) {
David Neto8e39bd12017-11-14 21:08:12 -0500219 // Get or create the composite construct function definition.
220 const string &fn_name = WrapFunctionNameForType(constructed_type);
221 Function *fn = M.getFunction(fn_name);
222 if (!fn) {
223 // Make the function.
Alan Bakerf8661412018-08-29 10:18:16 -0400224 SmallVector<Type*, 16> elements;
Alan Bakerabc935e2018-09-06 11:33:53 -0400225 unsigned num_elements = GetNumElements(constructed_type);
Alan Bakerf8661412018-08-29 10:18:16 -0400226 for (unsigned i = 0; i != num_elements; ++i)
227 elements.push_back(constructed_type->getTypeAtIndex(i));
David Neto8e39bd12017-11-14 21:08:12 -0500228 FunctionType *fnTy = FunctionType::get(
Alan Bakerf8661412018-08-29 10:18:16 -0400229 constructed_type, elements, false);
David Neto8e39bd12017-11-14 21:08:12 -0500230 auto fn_constant = M.getOrInsertFunction(fn_name, fnTy);
alan-bakerbccf62c2019-03-29 10:32:41 -0400231 fn = cast<Function>(fn_constant.getCallee());
David Neto8e39bd12017-11-14 21:08:12 -0500232 fn->addFnAttr(Attribute::ReadOnly);
David Neto8e39bd12017-11-14 21:08:12 -0500233 }
234 return fn;
235 }
236
David Netoab03f432017-11-03 17:00:44 -0400237 // Maps a loaded type to the name of the wrap function for that type.
238 DenseMap<Type *, string> function_for_type_;
239};
240} // namespace
241
242char RewriteInsertsPass::ID = 0;
243static RegisterPass<RewriteInsertsPass>
244 X("RewriteInserts",
245 "Rewrite chains of insertvalue to as composite-construction");
246
247namespace clspv {
248llvm::ModulePass *createRewriteInsertsPass() {
249 return new RewriteInsertsPass();
250}
251} // namespace clspv
252
253bool RewriteInsertsPass::runOnModule(Module &M) {
David Neto8e39bd12017-11-14 21:08:12 -0500254 bool Changed = ReplaceCompleteInsertionChains(M);
255
David Neto482550a2018-03-24 05:21:07 -0700256 if (clspv::Option::HackInserts()) {
David Neto8e39bd12017-11-14 21:08:12 -0500257 Changed |= ReplacePartialInsertions(M);
258 }
259
260 return Changed;
261}
262
263bool RewriteInsertsPass::ReplaceCompleteInsertionChains(Module &M) {
David Netoab03f432017-11-03 17:00:44 -0400264 bool Changed = false;
265
266 SmallVector<InsertionVector *, 16> WorkList;
267 for (Function &F : M) {
268 for (BasicBlock &BB : F) {
269 for (Instruction &I : BB) {
270 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
271 if (InsertionVector *insertions = CompleteInsertionChain(iv)) {
272 WorkList.push_back(insertions);
273 }
Alan Bakerabc935e2018-09-06 11:33:53 -0400274 } else if (InsertElementInst *ie = dyn_cast<InsertElementInst>(&I)) {
275 if (InsertionVector *insertions = CompleteInsertionChain(ie)) {
276 WorkList.push_back(insertions);
277 }
David Netoab03f432017-11-03 17:00:44 -0400278 }
279 }
280 }
281 }
282
283 if (WorkList.size() == 0) {
284 return Changed;
285 }
286
287 for (InsertionVector *insertions : WorkList) {
288 Changed = true;
289
290 // Gather the member values and types.
291 SmallVector<Value*, 4> values;
Alan Bakerabc935e2018-09-06 11:33:53 -0400292 for (Instruction* inst : *insertions) {
293 if (auto *insert_value = dyn_cast<InsertValueInst>(inst)) {
294 values.push_back(insert_value->getInsertedValueOperand());
295 } else if (auto *insert_element = dyn_cast<InsertElementInst>(inst)) {
296 values.push_back(insert_element->getOperand(1));
297 } else {
298 llvm_unreachable("Unhandled insertion instruction");
299 }
David Netoab03f432017-11-03 17:00:44 -0400300 }
301
Alan Bakerf8661412018-08-29 10:18:16 -0400302 CompositeType *resultTy = cast<CompositeType>(insertions->back()->getType());
Alan Bakerabc935e2018-09-06 11:33:53 -0400303 Function *fn = GetConstructFunction(M, resultTy);
David Netoab03f432017-11-03 17:00:44 -0400304
305 // Replace the chain.
306 auto call = CallInst::Create(fn, values);
307 call->insertAfter(insertions->back());
308 insertions->back()->replaceAllUsesWith(call);
309
310 // Remove the insertions if we can. Go from the tail back to
311 // the head, since the tail uses the previous insertion, etc.
312 for (auto iter = insertions->rbegin(), end = insertions->rend();
313 iter != end; ++iter) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400314 Instruction *insertion = *iter;
David Netoab03f432017-11-03 17:00:44 -0400315 if (!insertion->hasNUsesOrMore(1)) {
316 insertion->eraseFromParent();
317 }
318 }
319
320 delete insertions;
321 }
322
323 return Changed;
324}
David Neto8e39bd12017-11-14 21:08:12 -0500325
326bool RewriteInsertsPass::ReplacePartialInsertions(Module &M) {
327 bool Changed = false;
328
329 // First find candidates. Collect all InsertValue instructions
330 // into struct type, but track their interdependencies. To minimize
331 // the number of new instructions, generate a construction for each
332 // tail of an insertion chain.
333
334 UniqueVector<InsertValueInst *> insertions;
335 for (Function &F : M) {
336 for (BasicBlock &BB : F) {
337 for (Instruction &I : BB) {
338 if (InsertValueInst *iv = dyn_cast<InsertValueInst>(&I)) {
339 if (iv->getType()->isStructTy()) {
340 insertions.insert(iv);
341 }
342 }
343 }
344 }
345 }
346
347 // Now count how many times each InsertValue is used by another InsertValue.
348 // The |num_uses| vector is indexed by the unique id that |insertions|
349 // assigns to it.
350 std::vector<unsigned> num_uses(insertions.size() + 1);
351 // Count from the user's perspective.
352 for (InsertValueInst *insertion : insertions) {
353 if (auto *agg =
354 dyn_cast<InsertValueInst>(insertion->getAggregateOperand())) {
355 ++(num_uses[insertions.idFor(agg)]);
356 }
357 }
358
359 // Proceed in rounds. Each round rewrites any chains ending with an
360 // insertion that is not used by another insertion.
361
362 // Get the first list of insertion tails.
363 InsertionVector WorkList;
364 for (InsertValueInst *insertion : insertions) {
365 if (num_uses[insertions.idFor(insertion)] == 0) {
366 WorkList.push_back(insertion);
367 }
368 }
369
370 // This records insertions in the order they should be removed.
371 // In this list, an insertion preceds any insertions it uses.
372 // (This is post-dominance order.)
373 InsertionVector ordered_candidates_for_removal;
374
375 // Proceed in rounds.
376 while (WorkList.size()) {
377 Changed = true;
378
379 // Record the list of tails for the next round.
380 InsertionVector NextRoundWorkList;
381
Alan Bakerabc935e2018-09-06 11:33:53 -0400382 for (Instruction *inst : WorkList) {
383 InsertValueInst *insertion = cast<InsertValueInst>(inst);
David Neto8e39bd12017-11-14 21:08:12 -0500384 // Rewrite |insertion|.
385
386 StructType *resultTy = cast<StructType>(insertion->getType());
387
388 const unsigned num_members = resultTy->getNumElements();
389 std::vector<Value*> members(num_members, nullptr);
390 InsertionVector chain;
391 // Gather the member values. Walk backward from the insertion.
392 Value *base = LoadValuesEndingWithInsertion(insertion, &members, &chain);
393
394 // Populate remaining entries in |values| by extracting elements
395 // from |base|. Only make a new extractvalue instruction if we can't
396 // make a constant or undef. New instructions are inserted before
397 // the insertion we plan to remove.
398 for (unsigned i = 0; i < num_members; ++i) {
399 if (!members[i]) {
400 Type *memberTy = resultTy->getTypeAtIndex(i);
401 if (isa<UndefValue>(base)) {
402 members[i] = UndefValue::get(memberTy);
403 } else if (const auto *caz = dyn_cast<ConstantAggregateZero>(base)) {
404 members[i] = caz->getElementValue(i);
405 } else if (const auto *ca = dyn_cast<ConstantAggregate>(base)) {
406 members[i] = ca->getOperand(i);
407 } else {
408 members[i] = ExtractValueInst::Create(base, {i}, "", insertion);
409 }
410 }
411 }
412
413 // Create the call. It's dominated by any extractions we've just
414 // created.
Alan Bakerabc935e2018-09-06 11:33:53 -0400415 Function *construct_fn = GetConstructFunction(M, resultTy);
David Neto8e39bd12017-11-14 21:08:12 -0500416 auto *call = CallInst::Create(construct_fn, members, "", insertion);
417
418 // Disconnect this insertion. We'll remove it later.
419 insertion->replaceAllUsesWith(call);
420
421 // Trace backward through the chain, removing uses and deleting where
422 // we can. Stop at the first element that has a remaining use.
423 for (auto* chainElem : chain) {
424 if (chainElem->hasNUsesOrMore(1)) {
Alan Bakerabc935e2018-09-06 11:33:53 -0400425 unsigned &use_count = num_uses[insertions.idFor(cast<InsertValueInst>(chainElem))];
David Neto8e39bd12017-11-14 21:08:12 -0500426 assert(use_count > 0);
427 --use_count;
428 if (use_count == 0) {
429 NextRoundWorkList.push_back(chainElem);
430 }
431 break;
432 } else {
433 chainElem->eraseFromParent();
434 }
435 }
436 }
437 WorkList = std::move(NextRoundWorkList);
438 }
439
440 return Changed;
441}