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#include <set>
18
19using namespace llvm;
20
21/// Filter out cases where deleting the instruction will likely cause the
22/// user/def of the instruction to fail the verifier.
23//
24// TODO: Technically the verifier only enforces preallocated token usage and
25// there is a none token.
26static bool shouldAlwaysKeep(const Instruction &I) {
27 return I.isEHPad() || I.getType()->isTokenTy() || I.isSwiftError();
28}
29
30/// Removes out-of-chunk arguments from functions, and modifies their calls
31/// accordingly. It also removes allocations of out-of-chunk arguments.
32static void extractInstrFromModule(Oracle &O, ReducerWorkItem &WorkItem) {
33 Module &Program = WorkItem.getModule();
34 std::vector<Instruction *> InitInstToKeep;
35
36 for (auto &F : Program)
37 for (auto &BB : F) {
38 // Removing the terminator would make the block invalid. Only iterate over
39 // instructions before the terminator.
40 InitInstToKeep.push_back(x: BB.getTerminator());
41 for (auto &Inst : make_range(x: BB.begin(), y: std::prev(x: BB.end()))) {
42 if (shouldAlwaysKeep(I: Inst) || O.shouldKeep())
43 InitInstToKeep.push_back(x: &Inst);
44 }
45 }
46
47 // We create a vector first, then convert it to a set, so that we don't have
48 // to pay the cost of rebalancing the set frequently if the order we insert
49 // the elements doesn't match the order they should appear inside the set.
50 std::set<Instruction *> InstToKeep(InitInstToKeep.begin(),
51 InitInstToKeep.end());
52
53 std::vector<Instruction *> InstToDelete;
54 for (auto &F : Program)
55 for (auto &BB : F)
56 for (auto &Inst : BB)
57 if (!InstToKeep.count(x: &Inst)) {
58 Inst.replaceAllUsesWith(V: getDefaultValue(T: Inst.getType()));
59 InstToDelete.push_back(x: &Inst);
60 }
61
62 for (auto &I : InstToDelete)
63 I->eraseFromParent();
64}
65
66void llvm::reduceInstructionsDeltaPass(TestRunner &Test) {
67 runDeltaPass(Test, ExtractChunksFromModule: extractInstrFromModule, Message: "Reducing Instructions");
68}
69