1 //===--- 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 15 #include "llvm/IR/DebugInfo.h" 16 #include "LLVMContextImpl.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DIBuilder.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/GVMaterializer.h" 23 #include "llvm/IR/Instructions.h" 24 #include "llvm/IR/IntrinsicInst.h" 25 #include "llvm/IR/Intrinsics.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/IR/ValueHandle.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/Dwarf.h" 30 #include "llvm/Support/raw_ostream.h" 31 using namespace llvm; 32 using namespace llvm::dwarf; 33 34 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) { 35 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope)) 36 return LocalScope->getSubprogram(); 37 return nullptr; 38 } 39 40 //===----------------------------------------------------------------------===// 41 // DebugInfoFinder implementations. 42 //===----------------------------------------------------------------------===// 43 44 void DebugInfoFinder::reset() { 45 CUs.clear(); 46 SPs.clear(); 47 GVs.clear(); 48 TYs.clear(); 49 Scopes.clear(); 50 NodesSeen.clear(); 51 } 52 53 void DebugInfoFinder::processModule(const Module &M) { 54 for (auto *CU : M.debug_compile_units()) { 55 addCompileUnit(CU); 56 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()); 62 } 63 for (auto *ET : CU->getEnumTypes()) 64 processType(ET); 65 for (auto *RT : CU->getRetainedTypes()) 66 if (auto *T = dyn_cast<DIType>(RT)) 67 processType(T); 68 else 69 processSubprogram(cast<DISubprogram>(RT)); 70 for (auto *Import : CU->getImportedEntities()) { 71 auto *Entity = Import->getEntity().resolve(); 72 if (auto *T = dyn_cast<DIType>(Entity)) 73 processType(T); 74 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 75 processSubprogram(SP); 76 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()); 80 } 81 } 82 for (auto &F : M.functions()) 83 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram())) 84 processSubprogram(SP); 85 } 86 87 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) { 88 if (!Loc) 89 return; 90 processScope(Loc->getScope()); 91 processLocation(M, Loc->getInlinedAt()); 92 } 93 94 void DebugInfoFinder::processType(DIType *DT) { 95 if (!addType(DT)) 96 return; 97 processScope(DT->getScope().resolve()); 98 if (auto *ST = dyn_cast<DISubroutineType>(DT)) { 99 for (DITypeRef Ref : ST->getTypeArray()) 100 processType(Ref.resolve()); 101 return; 102 } 103 if (auto *DCT = dyn_cast<DICompositeType>(DT)) { 104 processType(DCT->getBaseType().resolve()); 105 for (Metadata *D : DCT->getElements()) { 106 if (auto *T = dyn_cast<DIType>(D)) 107 processType(T); 108 else if (auto *SP = dyn_cast<DISubprogram>(D)) 109 processSubprogram(SP); 110 } 111 return; 112 } 113 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) { 114 processType(DDT->getBaseType().resolve()); 115 } 116 } 117 118 void DebugInfoFinder::processScope(DIScope *Scope) { 119 if (!Scope) 120 return; 121 if (auto *Ty = dyn_cast<DIType>(Scope)) { 122 processType(Ty); 123 return; 124 } 125 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) { 126 addCompileUnit(CU); 127 return; 128 } 129 if (auto *SP = dyn_cast<DISubprogram>(Scope)) { 130 processSubprogram(SP); 131 return; 132 } 133 if (!addScope(Scope)) 134 return; 135 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) { 136 processScope(LB->getScope()); 137 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) { 138 processScope(NS->getScope()); 139 } else if (auto *M = dyn_cast<DIModule>(Scope)) { 140 processScope(M->getScope()); 141 } 142 } 143 144 void DebugInfoFinder::processSubprogram(DISubprogram *SP) { 145 if (!addSubprogram(SP)) 146 return; 147 processScope(SP->getScope().resolve()); 148 processType(SP->getType()); 149 for (auto *Element : SP->getTemplateParams()) { 150 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) { 151 processType(TType->getType().resolve()); 152 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) { 153 processType(TVal->getType().resolve()); 154 } 155 } 156 } 157 158 void DebugInfoFinder::processDeclare(const Module &M, 159 const DbgDeclareInst *DDI) { 160 auto *N = dyn_cast<MDNode>(DDI->getVariable()); 161 if (!N) 162 return; 163 164 auto *DV = dyn_cast<DILocalVariable>(N); 165 if (!DV) 166 return; 167 168 if (!NodesSeen.insert(DV).second) 169 return; 170 processScope(DV->getScope()); 171 processType(DV->getType().resolve()); 172 } 173 174 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) { 175 auto *N = dyn_cast<MDNode>(DVI->getVariable()); 176 if (!N) 177 return; 178 179 auto *DV = dyn_cast<DILocalVariable>(N); 180 if (!DV) 181 return; 182 183 if (!NodesSeen.insert(DV).second) 184 return; 185 processScope(DV->getScope()); 186 processType(DV->getType().resolve()); 187 } 188 189 bool DebugInfoFinder::addType(DIType *DT) { 190 if (!DT) 191 return false; 192 193 if (!NodesSeen.insert(DT).second) 194 return false; 195 196 TYs.push_back(const_cast<DIType *>(DT)); 197 return true; 198 } 199 200 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) { 201 if (!CU) 202 return false; 203 if (!NodesSeen.insert(CU).second) 204 return false; 205 206 CUs.push_back(CU); 207 return true; 208 } 209 210 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) { 211 if (!NodesSeen.insert(DIG).second) 212 return false; 213 214 GVs.push_back(DIG); 215 return true; 216 } 217 218 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) { 219 if (!SP) 220 return false; 221 222 if (!NodesSeen.insert(SP).second) 223 return false; 224 225 SPs.push_back(SP); 226 return true; 227 } 228 229 bool DebugInfoFinder::addScope(DIScope *Scope) { 230 if (!Scope) 231 return false; 232 // FIXME: Ocaml binding generates a scope with no content, we treat it 233 // as null for now. 234 if (Scope->getNumOperands() == 0) 235 return false; 236 if (!NodesSeen.insert(Scope).second) 237 return false; 238 Scopes.push_back(Scope); 239 return true; 240 } 241 242 bool llvm::stripDebugInfo(Function &F) { 243 bool Changed = false; 244 if (F.getSubprogram()) { 245 Changed = true; 246 F.setSubprogram(nullptr); 247 } 248 249 for (BasicBlock &BB : F) { 250 for (auto II = BB.begin(), End = BB.end(); II != End;) { 251 Instruction &I = *II++; // We may delete the instruction, increment now. 252 if (isa<DbgInfoIntrinsic>(&I)) { 253 I.eraseFromParent(); 254 Changed = true; 255 continue; 256 } 257 if (I.getDebugLoc()) { 258 Changed = true; 259 I.setDebugLoc(DebugLoc()); 260 } 261 } 262 } 263 return Changed; 264 } 265 266 bool llvm::StripDebugInfo(Module &M) { 267 bool Changed = false; 268 269 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(), 270 NME = M.named_metadata_end(); NMI != NME;) { 271 NamedMDNode *NMD = &*NMI; 272 ++NMI; 273 274 // We're stripping debug info, and without them, coverage information 275 // doesn't quite make sense. 276 if (NMD->getName().startswith("llvm.dbg.") || 277 NMD->getName() == "llvm.gcov") { 278 NMD->eraseFromParent(); 279 Changed = true; 280 } 281 } 282 283 for (Function &F : M) 284 Changed |= stripDebugInfo(F); 285 286 for (auto &GV : M.globals()) { 287 SmallVector<MDNode *, 1> MDs; 288 GV.getMetadata(LLVMContext::MD_dbg, MDs); 289 if (!MDs.empty()) { 290 GV.eraseMetadata(LLVMContext::MD_dbg); 291 Changed = true; 292 } 293 } 294 295 if (GVMaterializer *Materializer = M.getMaterializer()) 296 Materializer->setStripDebugInfo(); 297 298 return Changed; 299 } 300 301 namespace { 302 303 /// Helper class to downgrade -g metadata to -gline-tables-only metadata. 304 class DebugTypeInfoRemoval { 305 DenseMap<Metadata *, Metadata *> Replacements; 306 307 public: 308 /// The (void)() type. 309 MDNode *EmptySubroutineType; 310 311 private: 312 /// Remember what linkage name we originally had before stripping. If we end 313 /// up making two subprograms identical who originally had different linkage 314 /// names, then we need to make one of them distinct, to avoid them getting 315 /// uniqued. Maps the new node to the old linkage name. 316 DenseMap<DISubprogram *, StringRef> NewToLinkageName; 317 318 // TODO: Remember the distinct subprogram we created for a given linkage name, 319 // so that we can continue to unique whenever possible. Map <newly created 320 // node, old linkage name> to the first (possibly distinct) mdsubprogram 321 // created for that combination. This is not strictly needed for correctness, 322 // but can cut down on the number of MDNodes and let us diff cleanly with the 323 // output of -gline-tables-only. 324 325 public: 326 DebugTypeInfoRemoval(LLVMContext &C) 327 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0, 328 MDNode::get(C, {}))) {} 329 330 Metadata *map(Metadata *M) { 331 if (!M) 332 return nullptr; 333 auto Replacement = Replacements.find(M); 334 if (Replacement != Replacements.end()) 335 return Replacement->second; 336 337 return M; 338 } 339 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); } 340 341 /// Recursively remap N and all its referenced children. Does a DF post-order 342 /// traversal, so as to remap bottoms up. 343 void traverseAndRemap(MDNode *N) { traverse(N); } 344 345 private: 346 // Create a new DISubprogram, to replace the one given. 347 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) { 348 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile())); 349 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : ""; 350 DISubprogram *Declaration = nullptr; 351 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType())); 352 DITypeRef ContainingType(map(MDS->getContainingType())); 353 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit())); 354 auto Variables = nullptr; 355 auto TemplateParams = nullptr; 356 357 // Make a distinct DISubprogram, for situations that warrent it. 358 auto distinctMDSubprogram = [&]() { 359 return DISubprogram::getDistinct( 360 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 361 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(), 362 MDS->isDefinition(), MDS->getScopeLine(), ContainingType, 363 MDS->getVirtuality(), MDS->getVirtualIndex(), 364 MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit, 365 TemplateParams, Declaration, Variables); 366 }; 367 368 if (MDS->isDistinct()) 369 return distinctMDSubprogram(); 370 371 auto *NewMDS = DISubprogram::get( 372 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 373 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(), 374 MDS->isDefinition(), MDS->getScopeLine(), ContainingType, 375 MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(), 376 MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration, 377 Variables); 378 379 StringRef OldLinkageName = MDS->getLinkageName(); 380 381 // See if we need to make a distinct one. 382 auto OrigLinkage = NewToLinkageName.find(NewMDS); 383 if (OrigLinkage != NewToLinkageName.end()) { 384 if (OrigLinkage->second == OldLinkageName) 385 // We're good. 386 return NewMDS; 387 388 // Otherwise, need to make a distinct one. 389 // TODO: Query the map to see if we already have one. 390 return distinctMDSubprogram(); 391 } 392 393 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()}); 394 return NewMDS; 395 } 396 397 /// Create a new compile unit, to replace the one given 398 DICompileUnit *getReplacementCU(DICompileUnit *CU) { 399 // Drop skeleton CUs. 400 if (CU->getDWOId()) 401 return nullptr; 402 403 auto *File = cast_or_null<DIFile>(map(CU->getFile())); 404 MDTuple *EnumTypes = nullptr; 405 MDTuple *RetainedTypes = nullptr; 406 MDTuple *GlobalVariables = nullptr; 407 MDTuple *ImportedEntities = nullptr; 408 return DICompileUnit::getDistinct( 409 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(), 410 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(), 411 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes, 412 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(), 413 CU->getDWOId(), CU->getSplitDebugInlining()); 414 } 415 416 DILocation *getReplacementMDLocation(DILocation *MLD) { 417 auto *Scope = map(MLD->getScope()); 418 auto *InlinedAt = map(MLD->getInlinedAt()); 419 if (MLD->isDistinct()) 420 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(), 421 MLD->getColumn(), Scope, InlinedAt); 422 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(), 423 Scope, InlinedAt); 424 } 425 426 /// Create a new generic MDNode, to replace the one given 427 MDNode *getReplacementMDNode(MDNode *N) { 428 SmallVector<Metadata *, 8> Ops; 429 Ops.reserve(N->getNumOperands()); 430 for (auto &I : N->operands()) 431 if (I) 432 Ops.push_back(map(I)); 433 auto *Ret = MDNode::get(N->getContext(), Ops); 434 return Ret; 435 } 436 437 /// Attempt to re-map N to a newly created node. 438 void remap(MDNode *N) { 439 if (Replacements.count(N)) 440 return; 441 442 auto doRemap = [&](MDNode *N) -> MDNode * { 443 if (!N) 444 return nullptr; 445 if (auto *MDSub = dyn_cast<DISubprogram>(N)) { 446 remap(MDSub->getUnit()); 447 return getReplacementSubprogram(MDSub); 448 } 449 if (isa<DISubroutineType>(N)) 450 return EmptySubroutineType; 451 if (auto *CU = dyn_cast<DICompileUnit>(N)) 452 return getReplacementCU(CU); 453 if (isa<DIFile>(N)) 454 return N; 455 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N)) 456 // Remap to our referenced scope (recursively). 457 return mapNode(MDLB->getScope()); 458 if (auto *MLD = dyn_cast<DILocation>(N)) 459 return getReplacementMDLocation(MLD); 460 461 // Otherwise, if we see these, just drop them now. Not strictly necessary, 462 // but this speeds things up a little. 463 if (isa<DINode>(N)) 464 return nullptr; 465 466 return getReplacementMDNode(N); 467 }; 468 Replacements[N] = doRemap(N); 469 } 470 471 /// Do the remapping traversal. 472 void traverse(MDNode *); 473 }; 474 475 } // Anonymous namespace. 476 477 void DebugTypeInfoRemoval::traverse(MDNode *N) { 478 if (!N || Replacements.count(N)) 479 return; 480 481 // To avoid cycles, as well as for efficiency sake, we will sometimes prune 482 // parts of the graph. 483 auto prune = [](MDNode *Parent, MDNode *Child) { 484 if (auto *MDS = dyn_cast<DISubprogram>(Parent)) 485 return Child == MDS->getVariables().get(); 486 return false; 487 }; 488 489 SmallVector<MDNode *, 16> ToVisit; 490 DenseSet<MDNode *> Opened; 491 492 // Visit each node starting at N in post order, and map them. 493 ToVisit.push_back(N); 494 while (!ToVisit.empty()) { 495 auto *N = ToVisit.back(); 496 if (!Opened.insert(N).second) { 497 // Close it. 498 remap(N); 499 ToVisit.pop_back(); 500 continue; 501 } 502 for (auto &I : N->operands()) 503 if (auto *MDN = dyn_cast_or_null<MDNode>(I)) 504 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) && 505 !isa<DICompileUnit>(MDN)) 506 ToVisit.push_back(MDN); 507 } 508 } 509 510 bool llvm::stripNonLineTableDebugInfo(Module &M) { 511 bool Changed = false; 512 513 // First off, delete the debug intrinsics. 514 auto RemoveUses = [&](StringRef Name) { 515 if (auto *DbgVal = M.getFunction(Name)) { 516 while (!DbgVal->use_empty()) 517 cast<Instruction>(DbgVal->user_back())->eraseFromParent(); 518 DbgVal->eraseFromParent(); 519 Changed = true; 520 } 521 }; 522 RemoveUses("llvm.dbg.declare"); 523 RemoveUses("llvm.dbg.value"); 524 525 // Delete non-CU debug info named metadata nodes. 526 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end(); 527 NMI != NME;) { 528 NamedMDNode *NMD = &*NMI; 529 ++NMI; 530 // Specifically keep dbg.cu around. 531 if (NMD->getName() == "llvm.dbg.cu") 532 continue; 533 } 534 535 // Drop all dbg attachments from global variables. 536 for (auto &GV : M.globals()) 537 GV.eraseMetadata(LLVMContext::MD_dbg); 538 539 DebugTypeInfoRemoval Mapper(M.getContext()); 540 auto remap = [&](llvm::MDNode *Node) -> llvm::MDNode * { 541 if (!Node) 542 return nullptr; 543 Mapper.traverseAndRemap(Node); 544 auto *NewNode = Mapper.mapNode(Node); 545 Changed |= Node != NewNode; 546 Node = NewNode; 547 return NewNode; 548 }; 549 550 // Rewrite the DebugLocs to be equivalent to what 551 // -gline-tables-only would have created. 552 for (auto &F : M) { 553 if (auto *SP = F.getSubprogram()) { 554 Mapper.traverseAndRemap(SP); 555 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP)); 556 Changed |= SP != NewSP; 557 F.setSubprogram(NewSP); 558 } 559 for (auto &BB : F) { 560 for (auto &I : BB) { 561 if (I.getDebugLoc() == DebugLoc()) 562 continue; 563 564 // Make a replacement. 565 auto &DL = I.getDebugLoc(); 566 auto *Scope = DL.getScope(); 567 MDNode *InlinedAt = DL.getInlinedAt(); 568 Scope = remap(Scope); 569 InlinedAt = remap(InlinedAt); 570 I.setDebugLoc( 571 DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt)); 572 } 573 } 574 } 575 576 // Create a new llvm.dbg.cu, which is equivalent to the one 577 // -gline-tables-only would have created. 578 for (auto &NMD : M.getNamedMDList()) { 579 SmallVector<MDNode *, 8> Ops; 580 for (MDNode *Op : NMD.operands()) 581 Ops.push_back(remap(Op)); 582 583 if (!Changed) 584 continue; 585 586 NMD.clearOperands(); 587 for (auto *Op : Ops) 588 if (Op) 589 NMD.addOperand(Op); 590 } 591 return Changed; 592 } 593 594 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) { 595 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>( 596 M.getModuleFlag("Debug Info Version"))) 597 return Val->getZExtValue(); 598 return 0; 599 } 600