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