1 //===- ReduceInstructions.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 Instructions from defined functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ReduceInstructions.h"
15 #include "Utils.h"
16 #include "llvm/IR/Constants.h"
17 
18 using namespace llvm;
19 
20 /// Removes out-of-chunk arguments from functions, and modifies their calls
21 /// accordingly. It also removes allocations of out-of-chunk arguments.
extractInstrFromModule(Oracle & O,Module & Program)22 static void extractInstrFromModule(Oracle &O, Module &Program) {
23   std::vector<Instruction *> InitInstToKeep;
24 
25   for (auto &F : Program)
26     for (auto &BB : F) {
27       // Removing the terminator would make the block invalid. Only iterate over
28       // instructions before the terminator.
29       InitInstToKeep.push_back(BB.getTerminator());
30       for (auto &Inst : make_range(BB.begin(), std::prev(BB.end())))
31         if (O.shouldKeep())
32           InitInstToKeep.push_back(&Inst);
33     }
34 
35   // We create a vector first, then convert it to a set, so that we don't have
36   // to pay the cost of rebalancing the set frequently if the order we insert
37   // the elements doesn't match the order they should appear inside the set.
38   std::set<Instruction *> InstToKeep(InitInstToKeep.begin(),
39                                      InitInstToKeep.end());
40 
41   std::vector<Instruction *> InstToDelete;
42   for (auto &F : Program)
43     for (auto &BB : F)
44       for (auto &Inst : BB)
45         if (!InstToKeep.count(&Inst)) {
46           Inst.replaceAllUsesWith(getDefaultValue(Inst.getType()));
47           InstToDelete.push_back(&Inst);
48         }
49 
50   for (auto &I : InstToDelete)
51     I->eraseFromParent();
52 }
53 
reduceInstructionsDeltaPass(TestRunner & Test)54 void llvm::reduceInstructionsDeltaPass(TestRunner &Test) {
55   outs() << "*** Reducing Instructions...\n";
56   runDeltaPass(Test, extractInstrFromModule);
57 }
58