+
+/// Remove any debug info for global variables/functions in the given module for
+/// which said global variable/function no longer exists (i.e. is null).
+///
+/// Debugging information is encoded in llvm IR using metadata. This is designed
+/// such a way that debug info for symbols preserved even if symbols are
+/// optimized away by the optimizer. This special pass removes debug info for
+/// such symbols.
+bool StripDeadDebugInfo::runOnModule(Module &M) {
+ bool Changed = false;
+
+ LLVMContext &C = M.getContext();
+
+ // Find all debug info in F. This is actually overkill in terms of what we
+ // want to do, but we want to try and be as resilient as possible in the face
+ // of potential debug info changes by using the formal interfaces given to us
+ // as much as possible.
+ DebugInfoFinder F;
+ F.processModule(M);
+
+ // For each compile unit, find the live set of global variables/functions and
+ // replace the current list of potentially dead global variables/functions
+ // with the live list.
+ SmallVector<Metadata *, 64> LiveGlobalVariables;
+ SmallVector<Metadata *, 64> LiveSubprograms;
+ DenseSet<const MDNode *> VisitedSet;
+
+ for (DICompileUnit *DIC : F.compile_units()) {
+ // Create our live subprogram list.
+ bool SubprogramChange = false;
+ for (DISubprogram *DISP : DIC->getSubprograms()) {
+ // Make sure we visit each subprogram only once.
+ if (!VisitedSet.insert(DISP).second)
+ continue;
+
+ // If the function referenced by DISP is not null, the function is live.
+ if (DISP->getFunction())
+ LiveSubprograms.push_back(DISP);
+ else
+ SubprogramChange = true;
+ }
+
+ // Create our live global variable list.
+ bool GlobalVariableChange = false;
+ for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
+ // Make sure we only visit each global variable only once.
+ if (!VisitedSet.insert(DIG).second)
+ continue;
+
+ // If the global variable referenced by DIG is not null, the global
+ // variable is live.
+ if (DIG->getVariable())
+ LiveGlobalVariables.push_back(DIG);
+ else
+ GlobalVariableChange = true;
+ }
+
+ // If we found dead subprograms or global variables, replace the current
+ // subprogram list/global variable list with our new live subprogram/global
+ // variable list.
+ if (SubprogramChange) {
+ DIC->replaceSubprograms(MDTuple::get(C, LiveSubprograms));
+ Changed = true;
+ }
+
+ if (GlobalVariableChange) {
+ DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
+ Changed = true;
+ }
+
+ // Reset lists for the next iteration.
+ LiveSubprograms.clear();
+ LiveGlobalVariables.clear();
+ }
+
+ return Changed;
+}