1 //===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a function which calls the Generic Delta pass in order
10 // to reduce uninteresting Arguments from defined functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ReduceInstructions.h"
15 #include "llvm/IR/Constants.h"
16 
17 using namespace llvm;
18 
19 /// Removes out-of-chunk arguments from functions, and modifies their calls
20 /// accordingly. It also removes allocations of out-of-chunk arguments.
21 static void extractInstrFromModule(Oracle &O, Module &Program) {
22   std::vector<Instruction *> InitInstToKeep;
23 
24   for (auto &F : Program)
25     for (auto &BB : F) {
26       // Removing the terminator would make the block invalid. Only iterate over
27       // instructions before the terminator.
28       InitInstToKeep.push_back(BB.getTerminator());
29       for (auto &Inst : make_range(BB.begin(), std::prev(BB.end())))
30         if (O.shouldKeep())
31           InitInstToKeep.push_back(&Inst);
32     }
33 
34   // We create a vector first, then convert it to a set, so that we don't have
35   // to pay the cost of rebalancing the set frequently if the order we insert
36   // the elements doesn't match the order they should appear inside the set.
37   std::set<Instruction *> InstToKeep(InitInstToKeep.begin(),
38                                      InitInstToKeep.end());
39 
40   std::vector<Instruction *> InstToDelete;
41   for (auto &F : Program)
42     for (auto &BB : F)
43       for (auto &Inst : BB)
44         if (!InstToKeep.count(&Inst)) {
45           Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
46           InstToDelete.push_back(&Inst);
47         }
48 
49   for (auto &I : InstToDelete)
50     I->eraseFromParent();
51 }
52 
53 void llvm::reduceInstructionsDeltaPass(TestRunner &Test) {
54   outs() << "*** Reducing Instructions...\n";
55   runDeltaPass(Test, extractInstrFromModule);
56 }
57