1 //===- ReduceSpecialGlobals.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 special globals, like @llvm.used, in the provided Module.
11 //
12 // For more details about special globals, see
13 // https://llvm.org/docs/LangRef.html#intrinsic-global-variables
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "ReduceSpecialGlobals.h"
18 #include "Delta.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/GlobalValue.h"
22 
23 using namespace llvm;
24 
25 static StringRef SpecialGlobalNames[] = {"llvm.used", "llvm.compiler.used"};
26 
27 /// Removes all special globals aren't inside any of the
28 /// desired Chunks.
29 static void
extractSpecialGlobalsFromModule(const std::vector<Chunk> & ChunksToKeep,Module * Program)30 extractSpecialGlobalsFromModule(const std::vector<Chunk> &ChunksToKeep,
31                                 Module *Program) {
32   Oracle O(ChunksToKeep);
33 
34   for (StringRef Name : SpecialGlobalNames) {
35     if (auto *Used = Program->getNamedGlobal(Name)) {
36       Used->replaceAllUsesWith(UndefValue::get(Used->getType()));
37       Used->eraseFromParent();
38     }
39   }
40 }
41 
42 /// Counts the amount of special globals and prints their
43 /// respective name & index
countSpecialGlobals(Module * Program)44 static int countSpecialGlobals(Module *Program) {
45   // TODO: Silence index with --quiet flag
46   errs() << "----------------------------\n";
47   errs() << "Special Globals Index Reference:\n";
48   int Count = 0;
49   for (StringRef Name : SpecialGlobalNames) {
50     if (auto *Used = Program->getNamedGlobal(Name))
51       errs() << "\t" << ++Count << ": " << Used->getName() << "\n";
52   }
53   errs() << "----------------------------\n";
54   return Count;
55 }
56 
reduceSpecialGlobalsDeltaPass(TestRunner & Test)57 void llvm::reduceSpecialGlobalsDeltaPass(TestRunner &Test) {
58   errs() << "*** Reducing Special Globals ...\n";
59   int Functions = countSpecialGlobals(Test.getProgram());
60   runDeltaPass(Test, Functions, extractSpecialGlobalsFromModule);
61   errs() << "----------------------------\n";
62 }
63