blob: b34383f5ada9240a771260fcfe54940e06fc1bf7 [file] [log] [blame]
Eugene Zelenkof53a7b42017-05-05 22:30:37 +00001//===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
Bill Wendling523bea82013-11-08 08:13:15 +00002//
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
whitequark789164d2017-11-01 22:18:52 +000015#include "llvm-c/DebugInfo.h"
16#include "LLVMContextImpl.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000017#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/None.h"
whitequark789164d2017-11-01 22:18:52 +000020#include "llvm/ADT/STLExtras.h"
Bill Wendling523bea82013-11-08 08:13:15 +000021#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000022#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/IR/BasicBlock.h"
Bill Wendling523bea82013-11-08 08:13:15 +000025#include "llvm/IR/Constants.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000026#include "llvm/IR/DebugInfoMetadata.h"
27#include "llvm/IR/DebugLoc.h"
whitequark789164d2017-11-01 22:18:52 +000028#include "llvm/IR/DebugInfo.h"
29#include "llvm/IR/DIBuilder.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000030#include "llvm/IR/Function.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000031#include "llvm/IR/GVMaterializer.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000032#include "llvm/IR/Instruction.h"
Bill Wendling523bea82013-11-08 08:13:15 +000033#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000034#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Metadata.h"
Bill Wendling523bea82013-11-08 08:13:15 +000036#include "llvm/IR/Module.h"
Eugene Zelenkof53a7b42017-05-05 22:30:37 +000037#include "llvm/Support/Casting.h"
38#include <algorithm>
39#include <cassert>
40#include <utility>
41
Bill Wendling523bea82013-11-08 08:13:15 +000042using namespace llvm;
43using namespace llvm::dwarf;
44
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +000045DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
46 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
Duncan P. N. Exon Smithdd77af82015-03-31 02:06:28 +000047 return LocalScope->getSubprogram();
48 return nullptr;
Bill Wendling523bea82013-11-08 08:13:15 +000049}
50
Bill Wendling523bea82013-11-08 08:13:15 +000051//===----------------------------------------------------------------------===//
52// DebugInfoFinder implementations.
53//===----------------------------------------------------------------------===//
54
55void DebugInfoFinder::reset() {
56 CUs.clear();
57 SPs.clear();
58 GVs.clear();
59 TYs.clear();
60 Scopes.clear();
61 NodesSeen.clear();
Bill Wendling523bea82013-11-08 08:13:15 +000062}
63
Bill Wendling523bea82013-11-08 08:13:15 +000064void DebugInfoFinder::processModule(const Module &M) {
Adrian Prantl5992a722016-04-08 22:43:03 +000065 for (auto *CU : M.debug_compile_units()) {
66 addCompileUnit(CU);
Adrian Prantlbceaaa92016-12-20 02:09:43 +000067 for (auto DIG : CU->getGlobalVariables()) {
68 if (!addGlobalVariable(DIG))
69 continue;
70 auto *GV = DIG->getVariable();
71 processScope(GV->getScope());
72 processType(GV->getType().resolve());
Adrian Prantl5992a722016-04-08 22:43:03 +000073 }
Adrian Prantl5992a722016-04-08 22:43:03 +000074 for (auto *ET : CU->getEnumTypes())
75 processType(ET);
76 for (auto *RT : CU->getRetainedTypes())
Adrian Prantl75819ae2016-04-15 15:57:41 +000077 if (auto *T = dyn_cast<DIType>(RT))
78 processType(T);
79 else
80 processSubprogram(cast<DISubprogram>(RT));
Adrian Prantl5992a722016-04-08 22:43:03 +000081 for (auto *Import : CU->getImportedEntities()) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +000082 auto *Entity = Import->getEntity().resolve();
Adrian Prantl5992a722016-04-08 22:43:03 +000083 if (auto *T = dyn_cast<DIType>(Entity))
84 processType(T);
85 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +000086 processSubprogram(SP);
Adrian Prantl5992a722016-04-08 22:43:03 +000087 else if (auto *NS = dyn_cast<DINamespace>(Entity))
88 processScope(NS->getScope());
89 else if (auto *M = dyn_cast<DIModule>(Entity))
90 processScope(M->getScope());
Bill Wendling523bea82013-11-08 08:13:15 +000091 }
92 }
Keno Fischer30779772017-04-11 13:32:11 +000093 for (auto &F : M.functions()) {
Adrian Prantl75819ae2016-04-15 15:57:41 +000094 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
95 processSubprogram(SP);
Keno Fischer30779772017-04-11 13:32:11 +000096 // There could be subprograms from inlined functions referenced from
97 // instructions only. Walk the function to find them.
98 for (const BasicBlock &BB : F) {
99 for (const Instruction &I : BB) {
100 if (!I.getDebugLoc())
101 continue;
102 processLocation(M, I.getDebugLoc().get());
103 }
104 }
105 }
Bill Wendling523bea82013-11-08 08:13:15 +0000106}
107
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000108void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
Bill Wendling523bea82013-11-08 08:13:15 +0000109 if (!Loc)
110 return;
Duncan P. N. Exon Smithb7e221b2015-04-14 01:35:55 +0000111 processScope(Loc->getScope());
112 processLocation(M, Loc->getInlinedAt());
Bill Wendling523bea82013-11-08 08:13:15 +0000113}
114
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000115void DebugInfoFinder::processType(DIType *DT) {
Bill Wendling523bea82013-11-08 08:13:15 +0000116 if (!addType(DT))
117 return;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000118 processScope(DT->getScope().resolve());
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000119 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
120 for (DITypeRef Ref : ST->getTypeArray())
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000121 processType(Ref.resolve());
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000122 return;
123 }
124 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000125 processType(DCT->getBaseType().resolve());
Anders Waldenborg1433fd42015-04-14 09:18:17 +0000126 for (Metadata *D : DCT->getElements()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000127 if (auto *T = dyn_cast<DIType>(D))
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000128 processType(T);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000129 else if (auto *SP = dyn_cast<DISubprogram>(D))
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000130 processSubprogram(SP);
Bill Wendling523bea82013-11-08 08:13:15 +0000131 }
Duncan P. N. Exon Smith260fa8a2015-07-24 20:56:10 +0000132 return;
133 }
134 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000135 processType(DDT->getBaseType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000136 }
137}
138
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000139void DebugInfoFinder::processScope(DIScope *Scope) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000140 if (!Scope)
141 return;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000142 if (auto *Ty = dyn_cast<DIType>(Scope)) {
Bill Wendling523bea82013-11-08 08:13:15 +0000143 processType(Ty);
144 return;
145 }
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000146 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000147 addCompileUnit(CU);
Bill Wendling523bea82013-11-08 08:13:15 +0000148 return;
149 }
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000150 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000151 processSubprogram(SP);
Bill Wendling523bea82013-11-08 08:13:15 +0000152 return;
153 }
154 if (!addScope(Scope))
155 return;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000156 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000157 processScope(LB->getScope());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000158 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
Duncan P. N. Exon Smith20caafb2015-04-14 03:01:27 +0000159 processScope(NS->getScope());
Adrian Prantlab1243f2015-06-29 23:03:47 +0000160 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
161 processScope(M->getScope());
Bill Wendling523bea82013-11-08 08:13:15 +0000162 }
163}
164
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000165void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
Bill Wendling523bea82013-11-08 08:13:15 +0000166 if (!addSubprogram(SP))
167 return;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000168 processScope(SP->getScope().resolve());
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000169 processType(SP->getType());
170 for (auto *Element : SP->getTemplateParams()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000171 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000172 processType(TType->getType().resolve());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000173 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000174 processType(TVal->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000175 }
176 }
177}
178
Manman Ren2085ccc2013-11-17 18:42:37 +0000179void DebugInfoFinder::processDeclare(const Module &M,
180 const DbgDeclareInst *DDI) {
Duncan P. N. Exon Smithed557b52015-04-17 23:20:10 +0000181 auto *N = dyn_cast<MDNode>(DDI->getVariable());
Bill Wendling523bea82013-11-08 08:13:15 +0000182 if (!N)
183 return;
184
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000185 auto *DV = dyn_cast<DILocalVariable>(N);
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000186 if (!DV)
Bill Wendling523bea82013-11-08 08:13:15 +0000187 return;
188
David Blaikie70573dc2014-11-19 07:49:26 +0000189 if (!NodesSeen.insert(DV).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000190 return;
Duncan P. N. Exon Smith7348dda2015-04-14 02:22:36 +0000191 processScope(DV->getScope());
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000192 processType(DV->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000193}
194
Manman Ren2085ccc2013-11-17 18:42:37 +0000195void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
Duncan P. N. Exon Smithed557b52015-04-17 23:20:10 +0000196 auto *N = dyn_cast<MDNode>(DVI->getVariable());
Bill Wendling523bea82013-11-08 08:13:15 +0000197 if (!N)
198 return;
199
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000200 auto *DV = dyn_cast<DILocalVariable>(N);
Duncan P. N. Exon Smith9d1cf4c2015-04-06 23:18:49 +0000201 if (!DV)
Bill Wendling523bea82013-11-08 08:13:15 +0000202 return;
203
David Blaikie70573dc2014-11-19 07:49:26 +0000204 if (!NodesSeen.insert(DV).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000205 return;
Duncan P. N. Exon Smith7348dda2015-04-14 02:22:36 +0000206 processScope(DV->getScope());
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000207 processType(DV->getType().resolve());
Bill Wendling523bea82013-11-08 08:13:15 +0000208}
209
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000210bool DebugInfoFinder::addType(DIType *DT) {
Bill Wendling523bea82013-11-08 08:13:15 +0000211 if (!DT)
212 return false;
213
David Blaikie70573dc2014-11-19 07:49:26 +0000214 if (!NodesSeen.insert(DT).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000215 return false;
216
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000217 TYs.push_back(const_cast<DIType *>(DT));
Bill Wendling523bea82013-11-08 08:13:15 +0000218 return true;
219}
220
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000221bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
Bill Wendling523bea82013-11-08 08:13:15 +0000222 if (!CU)
223 return false;
David Blaikie70573dc2014-11-19 07:49:26 +0000224 if (!NodesSeen.insert(CU).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000225 return false;
226
227 CUs.push_back(CU);
228 return true;
229}
230
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000231bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
David Blaikie70573dc2014-11-19 07:49:26 +0000232 if (!NodesSeen.insert(DIG).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000233 return false;
234
235 GVs.push_back(DIG);
236 return true;
237}
238
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000239bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
Bill Wendling523bea82013-11-08 08:13:15 +0000240 if (!SP)
241 return false;
242
David Blaikie70573dc2014-11-19 07:49:26 +0000243 if (!NodesSeen.insert(SP).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000244 return false;
245
246 SPs.push_back(SP);
247 return true;
248}
249
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000250bool DebugInfoFinder::addScope(DIScope *Scope) {
Bill Wendling523bea82013-11-08 08:13:15 +0000251 if (!Scope)
252 return false;
253 // FIXME: Ocaml binding generates a scope with no content, we treat it
254 // as null for now.
255 if (Scope->getNumOperands() == 0)
256 return false;
David Blaikie70573dc2014-11-19 07:49:26 +0000257 if (!NodesSeen.insert(Scope).second)
Bill Wendling523bea82013-11-08 08:13:15 +0000258 return false;
259 Scopes.push_back(Scope);
260 return true;
261}
262
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000263static MDNode *stripDebugLocFromLoopID(MDNode *N) {
Daniel Sandersb96a9452017-01-28 11:22:05 +0000264 assert(N->op_begin() != N->op_end() && "Missing self reference?");
Daniel Sandersb96a9452017-01-28 11:22:05 +0000265
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000266 // if there is no debug location, we do not have to rewrite this MDNode.
267 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
268 return isa<DILocation>(Op.get());
269 }))
Daniel Sandersb96a9452017-01-28 11:22:05 +0000270 return N;
271
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000272 // If there is only the debug location without any actual loop metadata, we
Daniel Sandersb96a9452017-01-28 11:22:05 +0000273 // can remove the metadata.
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000274 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
275 return !isa<DILocation>(Op.get());
276 }))
Daniel Sandersb96a9452017-01-28 11:22:05 +0000277 return nullptr;
278
279 SmallVector<Metadata *, 4> Args;
280 // Reserve operand 0 for loop id self reference.
281 auto TempNode = MDNode::getTemporary(N->getContext(), None);
282 Args.push_back(TempNode.get());
Teresa Johnson9b4b8c82017-03-19 13:54:57 +0000283 // Add all non-debug location operands back.
284 for (auto Op = N->op_begin() + 1; Op != N->op_end(); Op++) {
285 if (!isa<DILocation>(*Op))
286 Args.push_back(*Op);
287 }
Daniel Sandersb96a9452017-01-28 11:22:05 +0000288
289 // Set the first operand to itself.
290 MDNode *LoopID = MDNode::get(N->getContext(), Args);
291 LoopID->replaceOperandWith(0, LoopID);
292 return LoopID;
293}
294
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000295bool llvm::stripDebugInfo(Function &F) {
296 bool Changed = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000297 if (F.getMetadata(LLVMContext::MD_dbg)) {
Peter Collingbourned4bff302015-11-05 22:03:56 +0000298 Changed = true;
299 F.setSubprogram(nullptr);
300 }
Mehdi Amini581f0e12016-05-07 04:10:52 +0000301
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000302 DenseMap<MDNode*, MDNode*> LoopIDsMap;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000303 for (BasicBlock &BB : F) {
Mehdi Amini581f0e12016-05-07 04:10:52 +0000304 for (auto II = BB.begin(), End = BB.end(); II != End;) {
305 Instruction &I = *II++; // We may delete the instruction, increment now.
Mehdi Aminidb8dd552016-05-14 04:58:35 +0000306 if (isa<DbgInfoIntrinsic>(&I)) {
307 I.eraseFromParent();
Mehdi Amini581f0e12016-05-07 04:10:52 +0000308 Changed = true;
Mehdi Aminibbedb142016-05-07 05:07:47 +0000309 continue;
Mehdi Amini581f0e12016-05-07 04:10:52 +0000310 }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000311 if (I.getDebugLoc()) {
312 Changed = true;
313 I.setDebugLoc(DebugLoc());
314 }
315 }
Daniel Sandersb96a9452017-01-28 11:22:05 +0000316
317 auto *TermInst = BB.getTerminator();
Justin Bognerb29bebe2017-08-18 21:38:03 +0000318 if (!TermInst)
319 // This is invalid IR, but we may not have run the verifier yet
320 continue;
Daniel Sandersb96a9452017-01-28 11:22:05 +0000321 if (auto *LoopID = TermInst->getMetadata(LLVMContext::MD_loop)) {
322 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
323 if (!NewLoopID)
324 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
325 if (NewLoopID != LoopID)
326 TermInst->setMetadata(LLVMContext::MD_loop, NewLoopID);
327 }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000328 }
329 return Changed;
330}
331
Manman Rencb14bbc2013-11-22 22:06:31 +0000332bool llvm::StripDebugInfo(Module &M) {
Manman Rencb14bbc2013-11-22 22:06:31 +0000333 bool Changed = false;
334
Manman Rencb14bbc2013-11-22 22:06:31 +0000335 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
336 NME = M.named_metadata_end(); NMI != NME;) {
Duncan P. N. Exon Smith52888a62015-10-08 23:49:46 +0000337 NamedMDNode *NMD = &*NMI;
Manman Rencb14bbc2013-11-22 22:06:31 +0000338 ++NMI;
Davide Italiano84bd58e2016-10-17 20:05:35 +0000339
340 // We're stripping debug info, and without them, coverage information
341 // doesn't quite make sense.
342 if (NMD->getName().startswith("llvm.dbg.") ||
343 NMD->getName() == "llvm.gcov") {
Manman Rencb14bbc2013-11-22 22:06:31 +0000344 NMD->eraseFromParent();
345 Changed = true;
346 }
347 }
348
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000349 for (Function &F : M)
350 Changed |= stripDebugInfo(F);
351
Adrian Prantl3bfe1092016-10-10 17:53:33 +0000352 for (auto &GV : M.globals()) {
353 SmallVector<MDNode *, 1> MDs;
354 GV.getMetadata(LLVMContext::MD_dbg, MDs);
355 if (!MDs.empty()) {
356 GV.eraseMetadata(LLVMContext::MD_dbg);
357 Changed = true;
358 }
359 }
360
Rafael Espindola468b8682015-04-01 14:44:59 +0000361 if (GVMaterializer *Materializer = M.getMaterializer())
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000362 Materializer->setStripDebugInfo();
Manman Rencb14bbc2013-11-22 22:06:31 +0000363
364 return Changed;
365}
Manman Ren8b4306c2013-12-02 21:29:56 +0000366
Michael Ilsemane5428042016-10-25 18:44:13 +0000367namespace {
368
369/// Helper class to downgrade -g metadata to -gline-tables-only metadata.
370class DebugTypeInfoRemoval {
371 DenseMap<Metadata *, Metadata *> Replacements;
372
373public:
374 /// The (void)() type.
375 MDNode *EmptySubroutineType;
376
377private:
378 /// Remember what linkage name we originally had before stripping. If we end
379 /// up making two subprograms identical who originally had different linkage
380 /// names, then we need to make one of them distinct, to avoid them getting
381 /// uniqued. Maps the new node to the old linkage name.
382 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
383
384 // TODO: Remember the distinct subprogram we created for a given linkage name,
385 // so that we can continue to unique whenever possible. Map <newly created
386 // node, old linkage name> to the first (possibly distinct) mdsubprogram
387 // created for that combination. This is not strictly needed for correctness,
388 // but can cut down on the number of MDNodes and let us diff cleanly with the
389 // output of -gline-tables-only.
390
391public:
392 DebugTypeInfoRemoval(LLVMContext &C)
393 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
394 MDNode::get(C, {}))) {}
395
396 Metadata *map(Metadata *M) {
397 if (!M)
398 return nullptr;
399 auto Replacement = Replacements.find(M);
400 if (Replacement != Replacements.end())
401 return Replacement->second;
402
403 return M;
404 }
405 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
406
407 /// Recursively remap N and all its referenced children. Does a DF post-order
408 /// traversal, so as to remap bottoms up.
409 void traverseAndRemap(MDNode *N) { traverse(N); }
410
411private:
412 // Create a new DISubprogram, to replace the one given.
413 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
414 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
415 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
416 DISubprogram *Declaration = nullptr;
417 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
418 DITypeRef ContainingType(map(MDS->getContainingType()));
419 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
420 auto Variables = nullptr;
421 auto TemplateParams = nullptr;
422
423 // Make a distinct DISubprogram, for situations that warrent it.
424 auto distinctMDSubprogram = [&]() {
425 return DISubprogram::getDistinct(
426 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
427 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
428 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
429 MDS->getVirtuality(), MDS->getVirtualIndex(),
430 MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit,
431 TemplateParams, Declaration, Variables);
432 };
433
434 if (MDS->isDistinct())
435 return distinctMDSubprogram();
436
437 auto *NewMDS = DISubprogram::get(
438 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
439 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
440 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
441 MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(),
442 MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration,
443 Variables);
444
445 StringRef OldLinkageName = MDS->getLinkageName();
446
447 // See if we need to make a distinct one.
448 auto OrigLinkage = NewToLinkageName.find(NewMDS);
449 if (OrigLinkage != NewToLinkageName.end()) {
450 if (OrigLinkage->second == OldLinkageName)
451 // We're good.
452 return NewMDS;
453
454 // Otherwise, need to make a distinct one.
455 // TODO: Query the map to see if we already have one.
456 return distinctMDSubprogram();
457 }
458
459 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
460 return NewMDS;
461 }
462
463 /// Create a new compile unit, to replace the one given
464 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
465 // Drop skeleton CUs.
466 if (CU->getDWOId())
467 return nullptr;
468
469 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
470 MDTuple *EnumTypes = nullptr;
471 MDTuple *RetainedTypes = nullptr;
472 MDTuple *GlobalVariables = nullptr;
473 MDTuple *ImportedEntities = nullptr;
474 return DICompileUnit::getDistinct(
475 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
476 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
477 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
478 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
Dehao Chen0944a8c2017-02-01 22:45:09 +0000479 CU->getDWOId(), CU->getSplitDebugInlining(),
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000480 CU->getDebugInfoForProfiling(), CU->getGnuPubnames());
Michael Ilsemane5428042016-10-25 18:44:13 +0000481 }
482
483 DILocation *getReplacementMDLocation(DILocation *MLD) {
484 auto *Scope = map(MLD->getScope());
485 auto *InlinedAt = map(MLD->getInlinedAt());
486 if (MLD->isDistinct())
487 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
488 MLD->getColumn(), Scope, InlinedAt);
489 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
490 Scope, InlinedAt);
491 }
492
493 /// Create a new generic MDNode, to replace the one given
494 MDNode *getReplacementMDNode(MDNode *N) {
495 SmallVector<Metadata *, 8> Ops;
496 Ops.reserve(N->getNumOperands());
497 for (auto &I : N->operands())
498 if (I)
499 Ops.push_back(map(I));
500 auto *Ret = MDNode::get(N->getContext(), Ops);
501 return Ret;
502 }
503
504 /// Attempt to re-map N to a newly created node.
505 void remap(MDNode *N) {
506 if (Replacements.count(N))
507 return;
508
509 auto doRemap = [&](MDNode *N) -> MDNode * {
510 if (!N)
511 return nullptr;
512 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
513 remap(MDSub->getUnit());
514 return getReplacementSubprogram(MDSub);
515 }
516 if (isa<DISubroutineType>(N))
517 return EmptySubroutineType;
518 if (auto *CU = dyn_cast<DICompileUnit>(N))
519 return getReplacementCU(CU);
520 if (isa<DIFile>(N))
521 return N;
522 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
523 // Remap to our referenced scope (recursively).
524 return mapNode(MDLB->getScope());
525 if (auto *MLD = dyn_cast<DILocation>(N))
526 return getReplacementMDLocation(MLD);
527
528 // Otherwise, if we see these, just drop them now. Not strictly necessary,
529 // but this speeds things up a little.
530 if (isa<DINode>(N))
531 return nullptr;
532
533 return getReplacementMDNode(N);
534 };
535 Replacements[N] = doRemap(N);
536 }
537
538 /// Do the remapping traversal.
539 void traverse(MDNode *);
540};
541
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000542} // end anonymous namespace
Michael Ilsemane5428042016-10-25 18:44:13 +0000543
544void DebugTypeInfoRemoval::traverse(MDNode *N) {
545 if (!N || Replacements.count(N))
546 return;
547
548 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
549 // parts of the graph.
550 auto prune = [](MDNode *Parent, MDNode *Child) {
551 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
552 return Child == MDS->getVariables().get();
553 return false;
554 };
555
556 SmallVector<MDNode *, 16> ToVisit;
557 DenseSet<MDNode *> Opened;
558
559 // Visit each node starting at N in post order, and map them.
560 ToVisit.push_back(N);
561 while (!ToVisit.empty()) {
562 auto *N = ToVisit.back();
563 if (!Opened.insert(N).second) {
564 // Close it.
565 remap(N);
566 ToVisit.pop_back();
567 continue;
568 }
569 for (auto &I : N->operands())
570 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
571 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
572 !isa<DICompileUnit>(MDN))
573 ToVisit.push_back(MDN);
574 }
575}
576
577bool llvm::stripNonLineTableDebugInfo(Module &M) {
578 bool Changed = false;
579
580 // First off, delete the debug intrinsics.
581 auto RemoveUses = [&](StringRef Name) {
582 if (auto *DbgVal = M.getFunction(Name)) {
583 while (!DbgVal->use_empty())
584 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
585 DbgVal->eraseFromParent();
586 Changed = true;
587 }
588 };
589 RemoveUses("llvm.dbg.declare");
590 RemoveUses("llvm.dbg.value");
591
592 // Delete non-CU debug info named metadata nodes.
593 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
594 NMI != NME;) {
595 NamedMDNode *NMD = &*NMI;
596 ++NMI;
597 // Specifically keep dbg.cu around.
598 if (NMD->getName() == "llvm.dbg.cu")
599 continue;
600 }
601
602 // Drop all dbg attachments from global variables.
603 for (auto &GV : M.globals())
604 GV.eraseMetadata(LLVMContext::MD_dbg);
605
606 DebugTypeInfoRemoval Mapper(M.getContext());
Eugene Zelenkof53a7b42017-05-05 22:30:37 +0000607 auto remap = [&](MDNode *Node) -> MDNode * {
Michael Ilsemane5428042016-10-25 18:44:13 +0000608 if (!Node)
609 return nullptr;
610 Mapper.traverseAndRemap(Node);
611 auto *NewNode = Mapper.mapNode(Node);
612 Changed |= Node != NewNode;
613 Node = NewNode;
614 return NewNode;
615 };
616
617 // Rewrite the DebugLocs to be equivalent to what
618 // -gline-tables-only would have created.
619 for (auto &F : M) {
620 if (auto *SP = F.getSubprogram()) {
621 Mapper.traverseAndRemap(SP);
622 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
623 Changed |= SP != NewSP;
624 F.setSubprogram(NewSP);
625 }
626 for (auto &BB : F) {
627 for (auto &I : BB) {
Adrian Prantl346dcaf2017-03-30 20:10:56 +0000628 auto remapDebugLoc = [&](DebugLoc DL) -> DebugLoc {
629 auto *Scope = DL.getScope();
630 MDNode *InlinedAt = DL.getInlinedAt();
631 Scope = remap(Scope);
632 InlinedAt = remap(InlinedAt);
633 return DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt);
634 };
Michael Ilsemane5428042016-10-25 18:44:13 +0000635
Adrian Prantl346dcaf2017-03-30 20:10:56 +0000636 if (I.getDebugLoc() != DebugLoc())
637 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
638
639 // Remap DILocations in untyped MDNodes (e.g., llvm.loop).
640 SmallVector<std::pair<unsigned, MDNode *>, 2> MDs;
641 I.getAllMetadata(MDs);
642 for (auto Attachment : MDs)
643 if (auto *T = dyn_cast_or_null<MDTuple>(Attachment.second))
644 for (unsigned N = 0; N < T->getNumOperands(); ++N)
645 if (auto *Loc = dyn_cast_or_null<DILocation>(T->getOperand(N)))
646 if (Loc != DebugLoc())
647 T->replaceOperandWith(N, remapDebugLoc(Loc));
Michael Ilsemane5428042016-10-25 18:44:13 +0000648 }
649 }
650 }
651
652 // Create a new llvm.dbg.cu, which is equivalent to the one
653 // -gline-tables-only would have created.
654 for (auto &NMD : M.getNamedMDList()) {
655 SmallVector<MDNode *, 8> Ops;
656 for (MDNode *Op : NMD.operands())
657 Ops.push_back(remap(Op));
658
659 if (!Changed)
660 continue;
661
662 NMD.clearOperands();
663 for (auto *Op : Ops)
664 if (Op)
665 NMD.addOperand(Op);
666 }
667 return Changed;
668}
669
Manman Renbd4daf82013-12-03 00:12:14 +0000670unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
David Majnemere7a9cdb2015-02-16 06:04:53 +0000671 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000672 M.getModuleFlag("Debug Info Version")))
673 return Val->getZExtValue();
674 return 0;
Manman Ren8b4306c2013-12-02 21:29:56 +0000675}
Dehao Chenf4646272017-10-02 18:13:14 +0000676
677void Instruction::applyMergedLocation(const DILocation *LocA,
678 const DILocation *LocB) {
679 if (LocA && LocB && (LocA == LocB || !LocA->canDiscriminate(*LocB))) {
680 setDebugLoc(LocA);
681 return;
682 }
683 if (!LocA || !LocB || !isa<CallInst>(this)) {
684 setDebugLoc(nullptr);
685 return;
686 }
687 SmallPtrSet<DILocation *, 5> InlinedLocationsA;
688 for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
689 InlinedLocationsA.insert(L);
690 const DILocation *Result = LocB;
691 for (DILocation *L = LocB->getInlinedAt(); L; L = L->getInlinedAt()) {
692 Result = L;
693 if (InlinedLocationsA.count(L))
694 break;
695 }
696 setDebugLoc(DILocation::get(
697 Result->getContext(), 0, 0, Result->getScope(), Result->getInlinedAt()));
698}
whitequark789164d2017-11-01 22:18:52 +0000699
700//===----------------------------------------------------------------------===//
701// LLVM C API implementations.
702//===----------------------------------------------------------------------===//
703
704static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
705 switch (lang) {
706#define HANDLE_DW_LANG(ID, NAME, VERSION, VENDOR) \
707case LLVMDWARFSourceLanguage##NAME: return ID;
708#include "llvm/BinaryFormat/Dwarf.def"
709#undef HANDLE_DW_LANG
710 }
711 llvm_unreachable("Unhandled Tag");
712}
713
714unsigned LLVMDebugMetadataVersion() {
715 return DEBUG_METADATA_VERSION;
716}
717
718LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
719 return wrap(new DIBuilder(*unwrap(M), false));
720}
721
722LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
723 return wrap(new DIBuilder(*unwrap(M)));
724}
725
726unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
727 return getDebugMetadataVersionFromModule(*unwrap(M));
728}
729
730LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
731 return StripDebugInfo(*unwrap(M));
732}
733
734void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
735 delete unwrap(Builder);
736}
737
738void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
739 unwrap(Builder)->finalize();
740}
741
742LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
743 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
744 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
745 LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
746 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
747 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
748 LLVMBool DebugInfoForProfiling) {
749 auto File = unwrap<DIFile>(FileRef);
750
751 return wrap(unwrap(Builder)->createCompileUnit(
752 map_from_llvmDWARFsourcelanguage(Lang), File,
753 StringRef(Producer, ProducerLen), isOptimized,
754 StringRef(Flags, FlagsLen), RuntimeVer,
755 StringRef(SplitName, SplitNameLen),
756 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
757 SplitDebugInlining, DebugInfoForProfiling));
758}
759
760LLVMMetadataRef
761LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
762 size_t FilenameLen, const char *Directory,
763 size_t DirectoryLen) {
764 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
765 StringRef(Directory, DirectoryLen)));
766}
767
768LLVMMetadataRef
769LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
770 unsigned Column, LLVMMetadataRef Scope,
771 LLVMMetadataRef InlinedAt) {
772 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
773 unwrap(InlinedAt)));
774}