1 //===-- ElimAvailExtern.cpp - DCE unreachable internal functions
2 //----------------===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This transform is designed to eliminate available external global
12 // definitions from the program, turning them into declarations.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Transforms/Utils/GlobalStatus.h"
21 #include "llvm/Pass.h"
22 using namespace llvm;
23 
24 #define DEBUG_TYPE "elim-avail-extern"
25 
26 STATISTIC(NumFunctions, "Number of functions removed");
27 STATISTIC(NumVariables, "Number of global variables removed");
28 
29 namespace {
30 struct EliminateAvailableExternally : public ModulePass {
31   static char ID; // Pass identification, replacement for typeid
32   EliminateAvailableExternally() : ModulePass(ID) {
33     initializeEliminateAvailableExternallyPass(
34         *PassRegistry::getPassRegistry());
35   }
36 
37   // run - Do the EliminateAvailableExternally pass on the specified module,
38   // optionally updating the specified callgraph to reflect the changes.
39   //
40   bool runOnModule(Module &M) override;
41 };
42 }
43 
44 char EliminateAvailableExternally::ID = 0;
45 INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
46                 "Eliminate Available Externally Globals", false, false)
47 
48 ModulePass *llvm::createEliminateAvailableExternallyPass() {
49   return new EliminateAvailableExternally();
50 }
51 
52 bool EliminateAvailableExternally::runOnModule(Module &M) {
53   if (skipModule(M))
54     return false;
55 
56   bool Changed = false;
57 
58   // Drop initializers of available externally global variables.
59   for (GlobalVariable &GV : M.globals()) {
60     if (!GV.hasAvailableExternallyLinkage())
61       continue;
62     if (GV.hasInitializer()) {
63       Constant *Init = GV.getInitializer();
64       GV.setInitializer(nullptr);
65       if (isSafeToDestroyConstant(Init))
66         Init->destroyConstant();
67     }
68     GV.removeDeadConstantUsers();
69     GV.setLinkage(GlobalValue::ExternalLinkage);
70     NumVariables++;
71     Changed = true;
72   }
73 
74   // Drop the bodies of available externally functions.
75   for (Function &F : M) {
76     if (!F.hasAvailableExternallyLinkage())
77       continue;
78     if (!F.isDeclaration())
79       // This will set the linkage to external
80       F.deleteBody();
81     F.removeDeadConstantUsers();
82     NumFunctions++;
83     Changed = true;
84   }
85 
86   return Changed;
87 }
88