1 //===- ReduceFunctions.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 functions (and any instruction that calls it) in the provided
11 // Module.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ReduceFunctions.h"
16 #include "Delta.h"
17 #include "llvm/ADT/SetVector.h"
18 #include <set>
19 
20 using namespace llvm;
21 
22 /// Removes all the Defined Functions (as well as their calls)
23 /// that aren't inside any of the desired Chunks.
24 static void extractFunctionsFromModule(const std::vector<Chunk> &ChunksToKeep,
25                                        Module *Program) {
26   // Get functions inside desired chunks
27   std::set<Function *> FuncsToKeep;
28   int I = 0, FunctionCount = 0;
29   for (auto &F : *Program)
30     if (I < (int)ChunksToKeep.size()) {
31       if (ChunksToKeep[I].contains(++FunctionCount))
32         FuncsToKeep.insert(&F);
33       if (FunctionCount == ChunksToKeep[I].end)
34         ++I;
35     }
36 
37   // Delete out-of-chunk functions, and replace their calls with undef
38   std::vector<Function *> FuncsToRemove;
39   SetVector<CallInst *> CallsToRemove;
40   for (auto &F : *Program)
41     if (!FuncsToKeep.count(&F)) {
42       for (auto U : F.users())
43         if (auto *Call = dyn_cast<CallInst>(U)) {
44           Call->replaceAllUsesWith(UndefValue::get(Call->getType()));
45           CallsToRemove.insert(Call);
46         }
47       F.replaceAllUsesWith(UndefValue::get(F.getType()));
48       FuncsToRemove.push_back(&F);
49     }
50 
51   for (auto *C : CallsToRemove)
52     C->eraseFromParent();
53 
54   for (auto *F : FuncsToRemove)
55     F->eraseFromParent();
56 }
57 
58 /// Counts the amount of non-declaration functions and prints their
59 /// respective name & index
60 static int countFunctions(Module *Program) {
61   // TODO: Silence index with --quiet flag
62   errs() << "----------------------------\n";
63   errs() << "Function Index Reference:\n";
64   int FunctionCount = 0;
65   for (auto &F : *Program)
66     errs() << "\t" << ++FunctionCount << ": " << F.getName() << "\n";
67 
68   errs() << "----------------------------\n";
69   return FunctionCount;
70 }
71 
72 void llvm::reduceFunctionsDeltaPass(TestRunner &Test) {
73   errs() << "*** Reducing Functions...\n";
74   int Functions = countFunctions(Test.getProgram());
75   runDeltaPass(Test, Functions, extractFunctionsFromModule);
76   errs() << "----------------------------\n";
77 }
78