blob: c5d39c5443049d0edf70a27349bf438db64bc635 [file] [log] [blame]
Bill Wendling523bea82013-11-08 08:13:15 +00001//===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the helper classes used to build and interpret debug
11// information in LLVM IR form.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000015#include "llvm/IR/DebugInfo.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000016#include "LLVMContextImpl.h"
Bill Wendling523bea82013-11-08 08:13:15 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
Bill Wendling523bea82013-11-08 08:13:15 +000019#include "llvm/IR/Constants.h"
Adrian Prantlb1416832014-08-01 22:11:58 +000020#include "llvm/IR/DIBuilder.h"
Bill Wendling523bea82013-11-08 08:13:15 +000021#include "llvm/IR/DerivedTypes.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000022#include "llvm/IR/GVMaterializer.h"
Bill Wendling523bea82013-11-08 08:13:15 +000023#include "llvm/IR/Instructions.h"
24#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000027#include "llvm/IR/ValueHandle.h"
Bill Wendling523bea82013-11-08 08:13:15 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/Dwarf.h"
Bill Wendling523bea82013-11-08 08:13:15 +000030#include "llvm/Support/raw_ostream.h"
31using namespace llvm;
32using namespace llvm::dwarf;
33
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +000034DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
35 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
Duncan P. N. Exon Smithdd77af82015-03-31 02:06:28 +000036 return LocalScope->getSubprogram();
37 return nullptr;
Bill Wendling523bea82013-11-08 08:13:15 +000038}
39
Bill Wendling523bea82013-11-08 08:13:15 +000040//===----------------------------------------------------------------------===//
41// DebugInfoFinder implementations.
42//===----------------------------------------------------------------------===//
43
44void DebugInfoFinder::reset() {
45 CUs.clear();
46 SPs.clear();
47 GVs.clear();
48 TYs.clear();
49 Scopes.clear();
50 NodesSeen.clear();
Bill Wendling523bea82013-11-08 08:13:15 +000051}
52
Bill Wendling523bea82013-11-08 08:13:15 +000053void DebugInfoFinder::processModule(const Module &M) {
Adrian Prantl5992a722016-04-08 22:43:03 +000054 for (auto *CU : M.debug_compile_units()) {
55 addCompileUnit(CU);
Adrian Prantlbceaaa92016-12-20 02:09:43 +000056 for (auto DIG : CU->getGlobalVariables()) {
57 if (!addGlobalVariable(DIG))
58 continue;
59 auto *GV = DIG->getVariable();
60 processScope(GV->getScope());
61 processType(GV->getType().resolve());
Adrian Prantl5992a722016-04-08 22:43:03 +000062 }
Adrian Prantl5992a722016-04-08 22:43:03 +000063 for (auto *ET : CU->getEnumTypes())
64 processType(ET);
65 for (auto *RT : CU->getRetainedTypes())
Adrian Prantl75819ae2016-04-15 15:57:41 +000066 if (auto *T = dyn_cast<DIType>(RT))
67 processType(T);
68 else
69 processSubprogram(cast<DISubprogram>(RT));
Adrian Prantl5992a722016-04-08 22:43:03 +000070 for (auto *Import : CU->getImportedEntities()) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +000071 auto *Entity = Import->getEntity().resolve();
Adrian Prantl5992a722016-04-08 22:43:03 +000072 if (auto *T = dyn_cast<DIType>(Entity))
73 processType(T);
74 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +000075 processSubprogram(SP);
Adrian Prantl5992a722016-04-08 22:43:03 +000076 else if (auto *NS = dyn_cast<DINamespace>(Entity))
77 processScope(NS->getScope());
78 else if (auto *M = dyn_cast<DIModule>(Entity))
79 processScope(M->getScope());
Bill Wendling523bea82013-11-08 08:13:15 +000080 }
81 }
Keno Fischer30779772017-04-11 13:32:11 +000082 for (auto &F : M.functions()) {
Adrian Prantl75819ae2016-04-15 15:57:41 +000083 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
84 processSubprogram(SP);
Keno Fischer30779772017-04-11 13:32:11 +000085 // There could be subprograms from inlined functions referenced from
86 // instructions only. Walk the function to find them.
87 for (const BasicBlock &BB : F) {
88 for (const Instruction &I : BB) {
89 if (!I.getDebugLoc())
90 continue;
91 processLocation(M, I.getDebugLoc().get());
92 }
93 }
94 }
Bill Wendling523bea82013-11-08 08:13:15 +000095}
96
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +000097void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
Bill Wendling523bea82013-11-08 08:13:15 +000098 if (!Loc)
99 return;
Duncan P. N. Exon Smithb7e221b2015-04-14 01:35:55 +0000100 processScope(Loc->getScope());
101 processLocation(M, Loc->getInlinedAt());
Bill Wendling523bea82013-11-08 08:13:15 +0000102}
103
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000104void DebugInfoFinder::processType(DIType *DT) {
Bill Wendling523bea82013-11-08 08:13:15 +0000105 if (!addType(DT))
106 return;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000107 processScope(DT->getScope().resolve());
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000108 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
109 for (DITypeRef Ref : ST->getTypeArray())
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000110 processType(Ref.resolve());
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000111 return;
112 }
113 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000114 processType(DCT->getBaseType().resolve());
Anders Waldenborg1433fd42015-04-14 09:18:17 +0000115 for (Metadata *D : DCT->getElements()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000116 if (auto *T = dyn_cast<DIType>(D))
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000117 processType(T);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000118 else if (auto *SP = dyn_cast<DISubprogram>(D))
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000119 processSubprogram(SP);
Bill Wendling523bea82013-11-08 08:13:15 +0000120 }
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000121 return;
122 }
123 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000124 processType(DDT->getBaseType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000125 }
126}
127
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000128void DebugInfoFinder::processScope(DIScope *Scope) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000129 if (!Scope)
130 return;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000131 if (auto *Ty = dyn_cast<DIType>(Scope)) {
Bill Wendling523bea82013-11-08 08:13:15 +0000132 processType(Ty);
133 return;
134 }
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000135 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000136 addCompileUnit(CU);
Bill Wendling523bea82013-11-08 08:13:15 +0000137 return;
138 }
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000139 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000140 processSubprogram(SP);
Bill Wendling523bea82013-11-08 08:13:15 +0000141 return;
142 }
143 if (!addScope(Scope))
144 return;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000145 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000146 processScope(LB->getScope());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000147 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
Duncan P. N. Exon Smith20caafb2015-04-14 03:01:27 +0000148 processScope(NS->getScope());
Adrian Prantlab1243f2015-06-29 23:03:47 +0000149 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
150 processScope(M->getScope());
Bill Wendling523bea82013-11-08 08:13:15 +0000151 }
152}
153
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000154void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
Bill Wendling523bea82013-11-08 08:13:15 +0000155 if (!addSubprogram(SP))
156 return;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000157 processScope(SP->getScope().resolve());
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000158 processType(SP->getType());
159 for (auto *Element : SP->getTemplateParams()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000160 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000161 processType(TType->getType().resolve());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000162 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000163 processType(TVal->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000164 }
165 }
166}
167
Manman Ren2085ccc2013-11-17 18:42:37 +0000168void DebugInfoFinder::processDeclare(const Module &M,
169 const DbgDeclareInst *DDI) {
Duncan P. N. Exon Smithed557b52015-04-17 23:20:10 +0000170 auto *N = dyn_cast<MDNode>(DDI->getVariable());
Bill Wendling523bea82013-11-08 08:13:15 +0000171 if (!N)
172 return;
173
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000174 auto *DV = dyn_cast<DILocalVariable>(N);
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000175 if (!DV)
Bill Wendling523bea82013-11-08 08:13:15 +0000176 return;
177
David Blaikie70573dc2014-11-19 07:49:26 +0000178 if (!NodesSeen.insert(DV).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000179 return;
Duncan P. N. Exon Smith7348dda2015-04-14 02:22:36 +0000180 processScope(DV->getScope());
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000181 processType(DV->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000182}
183
Manman Ren2085ccc2013-11-17 18:42:37 +0000184void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
Duncan P. N. Exon Smithed557b52015-04-17 23:20:10 +0000185 auto *N = dyn_cast<MDNode>(DVI->getVariable());
Bill Wendling523bea82013-11-08 08:13:15 +0000186 if (!N)
187 return;
188
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000189 auto *DV = dyn_cast<DILocalVariable>(N);
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000190 if (!DV)
Bill Wendling523bea82013-11-08 08:13:15 +0000191 return;
192
David Blaikie70573dc2014-11-19 07:49:26 +0000193 if (!NodesSeen.insert(DV).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000194 return;
Duncan P. N. Exon Smith7348dda2015-04-14 02:22:36 +0000195 processScope(DV->getScope());
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000196 processType(DV->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000197}
198
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000199bool DebugInfoFinder::addType(DIType *DT) {
Bill Wendling523bea82013-11-08 08:13:15 +0000200 if (!DT)
201 return false;
202
David Blaikie70573dc2014-11-19 07:49:26 +0000203 if (!NodesSeen.insert(DT).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000204 return false;
205
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000206 TYs.push_back(const_cast<DIType *>(DT));
Bill Wendling523bea82013-11-08 08:13:15 +0000207 return true;
208}
209
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000210bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
Bill Wendling523bea82013-11-08 08:13:15 +0000211 if (!CU)
212 return false;
David Blaikie70573dc2014-11-19 07:49:26 +0000213 if (!NodesSeen.insert(CU).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000214 return false;
215
216 CUs.push_back(CU);
217 return true;
218}
219
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000220bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
David Blaikie70573dc2014-11-19 07:49:26 +0000221 if (!NodesSeen.insert(DIG).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000222 return false;
223
224 GVs.push_back(DIG);
225 return true;
226}
227
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000228bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
Bill Wendling523bea82013-11-08 08:13:15 +0000229 if (!SP)
230 return false;
231
David Blaikie70573dc2014-11-19 07:49:26 +0000232 if (!NodesSeen.insert(SP).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000233 return false;
234
235 SPs.push_back(SP);
236 return true;
237}
238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000239bool DebugInfoFinder::addScope(DIScope *Scope) {
Bill Wendling523bea82013-11-08 08:13:15 +0000240 if (!Scope)
241 return false;
242 // FIXME: Ocaml binding generates a scope with no content, we treat it
243 // as null for now.
244 if (Scope->getNumOperands() == 0)
245 return false;
David Blaikie70573dc2014-11-19 07:49:26 +0000246 if (!NodesSeen.insert(Scope).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000247 return false;
248 Scopes.push_back(Scope);
249 return true;
250}
251
Daniel Sandersb96a9452017-01-28 11:22:05 +0000252static llvm::MDNode *stripDebugLocFromLoopID(llvm::MDNode *N) {
253 assert(N->op_begin() != N->op_end() && "Missing self reference?");
Daniel Sandersb96a9452017-01-28 11:22:05 +0000254
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000255 // if there is no debug location, we do not have to rewrite this MDNode.
256 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
257 return isa<DILocation>(Op.get());
258 }))
Daniel Sandersb96a9452017-01-28 11:22:05 +0000259 return N;
260
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000261 // If there is only the debug location without any actual loop metadata, we
Daniel Sandersb96a9452017-01-28 11:22:05 +0000262 // can remove the metadata.
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000263 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
264 return !isa<DILocation>(Op.get());
265 }))
Daniel Sandersb96a9452017-01-28 11:22:05 +0000266 return nullptr;
267
268 SmallVector<Metadata *, 4> Args;
269 // Reserve operand 0 for loop id self reference.
270 auto TempNode = MDNode::getTemporary(N->getContext(), None);
271 Args.push_back(TempNode.get());
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000272 // Add all non-debug location operands back.
273 for (auto Op = N->op_begin() + 1; Op != N->op_end(); Op++) {
274 if (!isa<DILocation>(*Op))
275 Args.push_back(*Op);
276 }
Daniel Sandersb96a9452017-01-28 11:22:05 +0000277
278 // Set the first operand to itself.
279 MDNode *LoopID = MDNode::get(N->getContext(), Args);
280 LoopID->replaceOperandWith(0, LoopID);
281 return LoopID;
282}
283
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000284bool llvm::stripDebugInfo(Function &F) {
285 bool Changed = false;
Peter Collingbourned4bff302015-11-05 22:03:56 +0000286 if (F.getSubprogram()) {
287 Changed = true;
288 F.setSubprogram(nullptr);
289 }
Mehdi Amini581f0e12016-05-07 04:10:52 +0000290
Daniel Sandersb96a9452017-01-28 11:22:05 +0000291 llvm::DenseMap<llvm::MDNode*, llvm::MDNode*> LoopIDsMap;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000292 for (BasicBlock &BB : F) {
Mehdi Amini581f0e12016-05-07 04:10:52 +0000293 for (auto II = BB.begin(), End = BB.end(); II != End;) {
294 Instruction &I = *II++; // We may delete the instruction, increment now.
Mehdi Aminidb8dd552016-05-14 04:58:35 +0000295 if (isa<DbgInfoIntrinsic>(&I)) {
296 I.eraseFromParent();
Mehdi Amini581f0e12016-05-07 04:10:52 +0000297 Changed = true;
Mehdi Aminibbedb142016-05-07 05:07:47 +0000298 continue;
Mehdi Amini581f0e12016-05-07 04:10:52 +0000299 }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000300 if (I.getDebugLoc()) {
301 Changed = true;
302 I.setDebugLoc(DebugLoc());
303 }
304 }
Daniel Sandersb96a9452017-01-28 11:22:05 +0000305
306 auto *TermInst = BB.getTerminator();
307 if (auto *LoopID = TermInst->getMetadata(LLVMContext::MD_loop)) {
308 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
309 if (!NewLoopID)
310 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
311 if (NewLoopID != LoopID)
312 TermInst->setMetadata(LLVMContext::MD_loop, NewLoopID);
313 }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000314 }
315 return Changed;
316}
317
Manman Rencb14bbc2013-11-22 22:06:31 +0000318bool llvm::StripDebugInfo(Module &M) {
Manman Rencb14bbc2013-11-22 22:06:31 +0000319 bool Changed = false;
320
Manman Rencb14bbc2013-11-22 22:06:31 +0000321 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
322 NME = M.named_metadata_end(); NMI != NME;) {
Duncan P. N. Exon Smith52888a62015-10-08 23:49:46 +0000323 NamedMDNode *NMD = &*NMI;
Manman Rencb14bbc2013-11-22 22:06:31 +0000324 ++NMI;
Davide Italiano84bd58e2016-10-17 20:05:35 +0000325
326 // We're stripping debug info, and without them, coverage information
327 // doesn't quite make sense.
328 if (NMD->getName().startswith("llvm.dbg.") ||
329 NMD->getName() == "llvm.gcov") {
Manman Rencb14bbc2013-11-22 22:06:31 +0000330 NMD->eraseFromParent();
331 Changed = true;
332 }
333 }
334
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000335 for (Function &F : M)
336 Changed |= stripDebugInfo(F);
337
Adrian Prantl3bfe1092016-10-10 17:53:33 +0000338 for (auto &GV : M.globals()) {
339 SmallVector<MDNode *, 1> MDs;
340 GV.getMetadata(LLVMContext::MD_dbg, MDs);
341 if (!MDs.empty()) {
342 GV.eraseMetadata(LLVMContext::MD_dbg);
343 Changed = true;
344 }
345 }
346
Rafael Espindola468b8682015-04-01 14:44:59 +0000347 if (GVMaterializer *Materializer = M.getMaterializer())
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000348 Materializer->setStripDebugInfo();
Manman Rencb14bbc2013-11-22 22:06:31 +0000349
350 return Changed;
351}
Manman Ren8b4306c2013-12-02 21:29:56 +0000352
Michael Ilsemane5428042016-10-25 18:44:13 +0000353namespace {
354
355/// Helper class to downgrade -g metadata to -gline-tables-only metadata.
356class DebugTypeInfoRemoval {
357 DenseMap<Metadata *, Metadata *> Replacements;
358
359public:
360 /// The (void)() type.
361 MDNode *EmptySubroutineType;
362
363private:
364 /// Remember what linkage name we originally had before stripping. If we end
365 /// up making two subprograms identical who originally had different linkage
366 /// names, then we need to make one of them distinct, to avoid them getting
367 /// uniqued. Maps the new node to the old linkage name.
368 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
369
370 // TODO: Remember the distinct subprogram we created for a given linkage name,
371 // so that we can continue to unique whenever possible. Map <newly created
372 // node, old linkage name> to the first (possibly distinct) mdsubprogram
373 // created for that combination. This is not strictly needed for correctness,
374 // but can cut down on the number of MDNodes and let us diff cleanly with the
375 // output of -gline-tables-only.
376
377public:
378 DebugTypeInfoRemoval(LLVMContext &C)
379 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
380 MDNode::get(C, {}))) {}
381
382 Metadata *map(Metadata *M) {
383 if (!M)
384 return nullptr;
385 auto Replacement = Replacements.find(M);
386 if (Replacement != Replacements.end())
387 return Replacement->second;
388
389 return M;
390 }
391 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
392
393 /// Recursively remap N and all its referenced children. Does a DF post-order
394 /// traversal, so as to remap bottoms up.
395 void traverseAndRemap(MDNode *N) { traverse(N); }
396
397private:
398 // Create a new DISubprogram, to replace the one given.
399 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
400 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
401 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
402 DISubprogram *Declaration = nullptr;
403 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
404 DITypeRef ContainingType(map(MDS->getContainingType()));
405 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
406 auto Variables = nullptr;
407 auto TemplateParams = nullptr;
408
409 // Make a distinct DISubprogram, for situations that warrent it.
410 auto distinctMDSubprogram = [&]() {
411 return DISubprogram::getDistinct(
412 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
413 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
414 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
415 MDS->getVirtuality(), MDS->getVirtualIndex(),
416 MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit,
417 TemplateParams, Declaration, Variables);
418 };
419
420 if (MDS->isDistinct())
421 return distinctMDSubprogram();
422
423 auto *NewMDS = DISubprogram::get(
424 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
425 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
426 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
427 MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(),
428 MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration,
429 Variables);
430
431 StringRef OldLinkageName = MDS->getLinkageName();
432
433 // See if we need to make a distinct one.
434 auto OrigLinkage = NewToLinkageName.find(NewMDS);
435 if (OrigLinkage != NewToLinkageName.end()) {
436 if (OrigLinkage->second == OldLinkageName)
437 // We're good.
438 return NewMDS;
439
440 // Otherwise, need to make a distinct one.
441 // TODO: Query the map to see if we already have one.
442 return distinctMDSubprogram();
443 }
444
445 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
446 return NewMDS;
447 }
448
449 /// Create a new compile unit, to replace the one given
450 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
451 // Drop skeleton CUs.
452 if (CU->getDWOId())
453 return nullptr;
454
455 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
456 MDTuple *EnumTypes = nullptr;
457 MDTuple *RetainedTypes = nullptr;
458 MDTuple *GlobalVariables = nullptr;
459 MDTuple *ImportedEntities = nullptr;
460 return DICompileUnit::getDistinct(
461 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
462 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
463 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
464 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
Dehao Chen0944a8c2017-02-01 22:45:09 +0000465 CU->getDWOId(), CU->getSplitDebugInlining(),
466 CU->getDebugInfoForProfiling());
Michael Ilsemane5428042016-10-25 18:44:13 +0000467 }
468
469 DILocation *getReplacementMDLocation(DILocation *MLD) {
470 auto *Scope = map(MLD->getScope());
471 auto *InlinedAt = map(MLD->getInlinedAt());
472 if (MLD->isDistinct())
473 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
474 MLD->getColumn(), Scope, InlinedAt);
475 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
476 Scope, InlinedAt);
477 }
478
479 /// Create a new generic MDNode, to replace the one given
480 MDNode *getReplacementMDNode(MDNode *N) {
481 SmallVector<Metadata *, 8> Ops;
482 Ops.reserve(N->getNumOperands());
483 for (auto &I : N->operands())
484 if (I)
485 Ops.push_back(map(I));
486 auto *Ret = MDNode::get(N->getContext(), Ops);
487 return Ret;
488 }
489
490 /// Attempt to re-map N to a newly created node.
491 void remap(MDNode *N) {
492 if (Replacements.count(N))
493 return;
494
495 auto doRemap = [&](MDNode *N) -> MDNode * {
496 if (!N)
497 return nullptr;
498 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
499 remap(MDSub->getUnit());
500 return getReplacementSubprogram(MDSub);
501 }
502 if (isa<DISubroutineType>(N))
503 return EmptySubroutineType;
504 if (auto *CU = dyn_cast<DICompileUnit>(N))
505 return getReplacementCU(CU);
506 if (isa<DIFile>(N))
507 return N;
508 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
509 // Remap to our referenced scope (recursively).
510 return mapNode(MDLB->getScope());
511 if (auto *MLD = dyn_cast<DILocation>(N))
512 return getReplacementMDLocation(MLD);
513
514 // Otherwise, if we see these, just drop them now. Not strictly necessary,
515 // but this speeds things up a little.
516 if (isa<DINode>(N))
517 return nullptr;
518
519 return getReplacementMDNode(N);
520 };
521 Replacements[N] = doRemap(N);
522 }
523
524 /// Do the remapping traversal.
525 void traverse(MDNode *);
526};
527
528} // Anonymous namespace.
529
530void DebugTypeInfoRemoval::traverse(MDNode *N) {
531 if (!N || Replacements.count(N))
532 return;
533
534 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
535 // parts of the graph.
536 auto prune = [](MDNode *Parent, MDNode *Child) {
537 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
538 return Child == MDS->getVariables().get();
539 return false;
540 };
541
542 SmallVector<MDNode *, 16> ToVisit;
543 DenseSet<MDNode *> Opened;
544
545 // Visit each node starting at N in post order, and map them.
546 ToVisit.push_back(N);
547 while (!ToVisit.empty()) {
548 auto *N = ToVisit.back();
549 if (!Opened.insert(N).second) {
550 // Close it.
551 remap(N);
552 ToVisit.pop_back();
553 continue;
554 }
555 for (auto &I : N->operands())
556 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
557 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
558 !isa<DICompileUnit>(MDN))
559 ToVisit.push_back(MDN);
560 }
561}
562
563bool llvm::stripNonLineTableDebugInfo(Module &M) {
564 bool Changed = false;
565
566 // First off, delete the debug intrinsics.
567 auto RemoveUses = [&](StringRef Name) {
568 if (auto *DbgVal = M.getFunction(Name)) {
569 while (!DbgVal->use_empty())
570 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
571 DbgVal->eraseFromParent();
572 Changed = true;
573 }
574 };
575 RemoveUses("llvm.dbg.declare");
576 RemoveUses("llvm.dbg.value");
577
578 // Delete non-CU debug info named metadata nodes.
579 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
580 NMI != NME;) {
581 NamedMDNode *NMD = &*NMI;
582 ++NMI;
583 // Specifically keep dbg.cu around.
584 if (NMD->getName() == "llvm.dbg.cu")
585 continue;
586 }
587
588 // Drop all dbg attachments from global variables.
589 for (auto &GV : M.globals())
590 GV.eraseMetadata(LLVMContext::MD_dbg);
591
592 DebugTypeInfoRemoval Mapper(M.getContext());
593 auto remap = [&](llvm::MDNode *Node) -> llvm::MDNode * {
594 if (!Node)
595 return nullptr;
596 Mapper.traverseAndRemap(Node);
597 auto *NewNode = Mapper.mapNode(Node);
598 Changed |= Node != NewNode;
599 Node = NewNode;
600 return NewNode;
601 };
602
603 // Rewrite the DebugLocs to be equivalent to what
604 // -gline-tables-only would have created.
605 for (auto &F : M) {
606 if (auto *SP = F.getSubprogram()) {
607 Mapper.traverseAndRemap(SP);
608 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
609 Changed |= SP != NewSP;
610 F.setSubprogram(NewSP);
611 }
612 for (auto &BB : F) {
613 for (auto &I : BB) {
Adrian Prantl346dcaf2017-03-30 20:10:56 +0000614 auto remapDebugLoc = [&](DebugLoc DL) -> DebugLoc {
615 auto *Scope = DL.getScope();
616 MDNode *InlinedAt = DL.getInlinedAt();
617 Scope = remap(Scope);
618 InlinedAt = remap(InlinedAt);
619 return DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt);
620 };
Michael Ilsemane5428042016-10-25 18:44:13 +0000621
Adrian Prantl346dcaf2017-03-30 20:10:56 +0000622 if (I.getDebugLoc() != DebugLoc())
623 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
624
625 // Remap DILocations in untyped MDNodes (e.g., llvm.loop).
626 SmallVector<std::pair<unsigned, MDNode *>, 2> MDs;
627 I.getAllMetadata(MDs);
628 for (auto Attachment : MDs)
629 if (auto *T = dyn_cast_or_null<MDTuple>(Attachment.second))
630 for (unsigned N = 0; N < T->getNumOperands(); ++N)
631 if (auto *Loc = dyn_cast_or_null<DILocation>(T->getOperand(N)))
632 if (Loc != DebugLoc())
633 T->replaceOperandWith(N, remapDebugLoc(Loc));
Michael Ilsemane5428042016-10-25 18:44:13 +0000634 }
635 }
636 }
637
638 // Create a new llvm.dbg.cu, which is equivalent to the one
639 // -gline-tables-only would have created.
640 for (auto &NMD : M.getNamedMDList()) {
641 SmallVector<MDNode *, 8> Ops;
642 for (MDNode *Op : NMD.operands())
643 Ops.push_back(remap(Op));
644
645 if (!Changed)
646 continue;
647
648 NMD.clearOperands();
649 for (auto *Op : Ops)
650 if (Op)
651 NMD.addOperand(Op);
652 }
653 return Changed;
654}
655
Manman Renbd4daf82013-12-03 00:12:14 +0000656unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
David Majnemere7a9cdb2015-02-16 06:04:53 +0000657 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658 M.getModuleFlag("Debug Info Version")))
659 return Val->getZExtValue();
660 return 0;
Manman Ren8b4306c2013-12-02 21:29:56 +0000661}