1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
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/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/GVMaterializer.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm::dwarf;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
41 if (!DbgNode || Elt >= DbgNode->getNumOperands())
43 return DbgNode->getOperand(Elt);
46 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
47 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
50 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
51 MDNode *Field = getNodeField(DbgNode, Elt);
52 return DIDescriptor(Field);
55 /// \brief Return the size reported by the variable's type.
56 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
57 DIType Ty = getType().resolve(Map);
58 // Follow derived types until we reach a type that
59 // reports back a size.
60 while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
61 DIDerivedType DT = cast<MDDerivedType>(Ty);
62 Ty = DT.getTypeDerivedFrom().resolve(Map);
64 assert(Ty.getSizeInBits() && "type with size 0");
65 return Ty.getSizeInBits();
68 //===----------------------------------------------------------------------===//
69 // Simple Descriptor Constructors and other Methods
70 //===----------------------------------------------------------------------===//
72 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
73 assert(DbgNode && "Trying to replace an unverified type!");
74 assert(DbgNode->isTemporary() && "Expected temporary node");
75 TempMDNode Temp(get());
77 // Since we use a TrackingVH for the node, its easy for clients to manufacture
78 // legitimate situations where they want to replaceAllUsesWith() on something
79 // which, due to uniquing, has merged with the source. We shield clients from
80 // this detail by allowing a value to be replaced with replaceAllUsesWith()
82 if (Temp.get() == D.get()) {
83 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
87 Temp->replaceAllUsesWith(D.get());
91 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
92 assert(DbgNode && "Trying to replace an unverified type!");
93 assert(DbgNode != D && "This replacement should always happen");
94 assert(DbgNode->isTemporary() && "Expected temporary node");
95 TempMDNode Node(get());
96 Node->replaceAllUsesWith(D);
100 /// \brief Check if a value can be a reference to a type.
101 static bool isTypeRef(const Metadata *MD) {
104 if (auto *S = dyn_cast<MDString>(MD))
105 return !S->getString().empty();
106 return isa<MDType>(MD);
109 /// \brief Check if a value can be a ScopeRef.
110 static bool isScopeRef(const Metadata *MD) {
113 if (auto *S = dyn_cast<MDString>(MD))
114 return !S->getString().empty();
115 return isa<MDScope>(MD);
118 /// \brief Check if a value can be a DescriptorRef.
119 static bool isDescriptorRef(const Metadata *MD) {
122 if (auto *S = dyn_cast<MDString>(MD))
123 return !S->getString().empty();
124 return isa<MDNode>(MD);
128 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
129 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
131 N->replaceElements(cast<MDTuple>(Elements));
133 N->replaceTemplateParams(cast<MDTuple>(TParams));
137 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
139 void DICompositeType::setContainingType(DICompositeType ContainingType) {
140 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
141 N->replaceVTableHolder(MDTypeRef::get(ContainingType));
145 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
146 assert(CurFn && "Invalid function");
147 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
150 // This variable is not inlined function argument if its scope
151 // does not describe current function.
152 return !SP.describes(CurFn);
155 Function *DISubprogram::getFunction() const {
157 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
158 return dyn_cast<Function>(C->getValue());
162 bool DISubprogram::describes(const Function *F) {
163 assert(F && "Invalid function");
164 if (F == getFunction())
166 StringRef Name = getLinkageName();
169 if (F->getName() == Name)
174 GlobalVariable *DIGlobalVariable::getGlobal() const {
175 return dyn_cast_or_null<GlobalVariable>(getConstant());
178 DIScopeRef DIScope::getContext() const {
179 if (DIType T = dyn_cast<MDType>(*this))
180 return T.getContext();
182 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
183 return DIScopeRef(SP.getContext());
185 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
186 return DIScopeRef(LB.getContext());
188 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
189 return DIScopeRef(NS.getContext());
191 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
192 "Unhandled type of scope.");
193 return DIScopeRef(nullptr);
196 StringRef DIScope::getName() const {
197 if (DIType T = dyn_cast<MDType>(*this))
199 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
201 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
203 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
204 isa<MDCompileUnit>(*this)) &&
205 "Unhandled type of scope.");
209 StringRef DIScope::getFilename() const {
211 if (auto *F = N->getFile())
212 return F->getFilename();
216 StringRef DIScope::getDirectory() const {
218 if (auto *F = N->getFile())
219 return F->getDirectory();
223 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
224 get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
227 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
228 get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
231 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
232 DILexicalBlockFile NewScope) {
233 assert(NewScope && "Expected valid scope");
235 const auto *Old = cast<MDLocation>(DbgNode);
236 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
237 NewScope, Old->getInlinedAt()));
240 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
241 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
242 return ++Ctx.pImpl->DiscriminatorTable[Key];
245 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
246 LLVMContext &VMContext) {
247 return cast<MDLocalVariable>(DV)
248 ->withInline(cast_or_null<MDLocation>(InlinedScope));
251 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
252 return cast<MDLocalVariable>(DV)->withoutInline();
255 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
256 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
257 return LocalScope->getSubprogram();
261 DISubprogram llvm::getDISubprogram(const Function *F) {
262 // We look for the first instr that has a debug annotation leading back to F.
263 for (auto &BB : *F) {
264 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
265 return Inst.getDebugLoc();
267 if (Inst == BB.end())
269 DebugLoc DLoc = Inst->getDebugLoc();
270 const MDNode *Scope = DLoc.getInlinedAtScope();
271 DISubprogram Subprogram = getDISubprogram(Scope);
272 return Subprogram.describes(F) ? Subprogram : DISubprogram();
275 return DISubprogram();
278 DICompositeType llvm::getDICompositeType(DIType T) {
279 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
282 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
283 // This function is currently used by dragonegg and dragonegg does
284 // not generate identifier for types, so using an empty map to resolve
285 // DerivedFrom should be fine.
286 DITypeIdentifierMap EmptyMap;
287 return getDICompositeType(
288 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
295 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
296 DITypeIdentifierMap Map;
297 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
298 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
299 DIArray Retain = CU.getRetainedTypes();
300 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
301 if (!isa<MDCompositeType>(Retain.getElement(Ti)))
303 DICompositeType Ty = cast<MDCompositeType>(Retain.getElement(Ti));
304 if (MDString *TypeId = Ty.getIdentifier()) {
305 // Definition has priority over declaration.
306 // Try to insert (TypeId, Ty) to Map.
307 std::pair<DITypeIdentifierMap::iterator, bool> P =
308 Map.insert(std::make_pair(TypeId, Ty));
309 // If TypeId already exists in Map and this is a definition, replace
310 // whatever we had (declaration or definition) with the definition.
311 if (!P.second && !Ty.isForwardDecl())
312 P.first->second = Ty;
319 //===----------------------------------------------------------------------===//
320 // DebugInfoFinder implementations.
321 //===----------------------------------------------------------------------===//
323 void DebugInfoFinder::reset() {
330 TypeIdentifierMap.clear();
331 TypeMapInitialized = false;
334 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
335 if (!TypeMapInitialized)
336 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
337 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
338 TypeMapInitialized = true;
342 void DebugInfoFinder::processModule(const Module &M) {
343 InitializeTypeMap(M);
344 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
345 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
346 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
348 DIArray GVs = CU.getGlobalVariables();
349 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
350 DIGlobalVariable DIG = cast<MDGlobalVariable>(GVs.getElement(i));
351 if (addGlobalVariable(DIG)) {
352 processScope(DIG.getContext());
353 processType(DIG.getType().resolve(TypeIdentifierMap));
356 DIArray SPs = CU.getSubprograms();
357 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
358 processSubprogram(cast<MDSubprogram>(SPs.getElement(i)));
359 DIArray EnumTypes = CU.getEnumTypes();
360 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
361 processType(cast<MDType>(EnumTypes.getElement(i)));
362 DIArray RetainedTypes = CU.getRetainedTypes();
363 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
364 processType(cast<MDType>(RetainedTypes.getElement(i)));
365 DIArray Imports = CU.getImportedEntities();
366 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
367 DIImportedEntity Import = cast<MDImportedEntity>(Imports.getElement(i));
368 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
369 if (auto *T = dyn_cast<MDType>(Entity))
371 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
372 processSubprogram(SP);
373 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
374 processScope(NS->getScope());
380 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
383 InitializeTypeMap(M);
384 processScope(Loc.getScope());
385 processLocation(M, Loc.getOrigLocation());
388 void DebugInfoFinder::processType(DIType DT) {
391 processScope(DT.getContext().resolve(TypeIdentifierMap));
392 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
393 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
394 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
395 DITypeArray DTA = ST.getTypeArray();
396 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
397 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
400 DIArray DA = DCT.getElements();
401 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
402 DIDescriptor D = DA.getElement(i);
403 if (DIType T = dyn_cast<MDType>(D))
405 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
406 processSubprogram(SP);
408 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
409 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
413 void DebugInfoFinder::processScope(DIScope Scope) {
416 if (DIType Ty = dyn_cast<MDType>(Scope)) {
420 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
424 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
425 processSubprogram(SP);
428 if (!addScope(Scope))
430 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
431 processScope(LB.getContext());
432 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
433 processScope(NS.getContext());
437 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
438 if (!addSubprogram(SP))
440 processScope(SP.getContext().resolve(TypeIdentifierMap));
441 processType(SP.getType());
442 DIArray TParams = SP.getTemplateParams();
443 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
444 DIDescriptor Element = TParams.getElement(I);
445 if (DITemplateTypeParameter TType =
446 dyn_cast<MDTemplateTypeParameter>(Element)) {
447 processType(TType.getType().resolve(TypeIdentifierMap));
448 } else if (DITemplateValueParameter TVal =
449 dyn_cast<MDTemplateValueParameter>(Element)) {
450 processType(TVal.getType().resolve(TypeIdentifierMap));
455 void DebugInfoFinder::processDeclare(const Module &M,
456 const DbgDeclareInst *DDI) {
457 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
460 InitializeTypeMap(M);
462 DIVariable DV = dyn_cast<MDLocalVariable>(N);
466 if (!NodesSeen.insert(DV).second)
468 processScope(DV.getContext());
469 processType(DV.getType().resolve(TypeIdentifierMap));
472 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
473 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
476 InitializeTypeMap(M);
478 DIVariable DV = dyn_cast<MDLocalVariable>(N);
482 if (!NodesSeen.insert(DV).second)
484 processScope(DV.getContext());
485 processType(DV.getType().resolve(TypeIdentifierMap));
488 bool DebugInfoFinder::addType(DIType DT) {
492 if (!NodesSeen.insert(DT).second)
499 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
502 if (!NodesSeen.insert(CU).second)
509 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
513 if (!NodesSeen.insert(DIG).second)
520 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
524 if (!NodesSeen.insert(SP).second)
531 bool DebugInfoFinder::addScope(DIScope Scope) {
534 // FIXME: Ocaml binding generates a scope with no content, we treat it
536 if (Scope->getNumOperands() == 0)
538 if (!NodesSeen.insert(Scope).second)
540 Scopes.push_back(Scope);
544 //===----------------------------------------------------------------------===//
545 // DIDescriptor: dump routines for all descriptors.
546 //===----------------------------------------------------------------------===//
548 void DIDescriptor::dump() const {
553 void DIDescriptor::print(raw_ostream &OS) const {
559 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
560 const LLVMContext &Ctx) {
564 DIScope Scope = cast<MDScope>(DL.getScope());
565 // Omit the directory, because it's likely to be long and uninteresting.
566 CommentOS << Scope.getFilename();
567 CommentOS << ':' << DL.getLine();
568 if (DL.getCol() != 0)
569 CommentOS << ':' << DL.getCol();
571 DebugLoc InlinedAtDL = DL.getInlinedAt();
576 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
580 void DIVariable::printExtendedName(raw_ostream &OS) const {
581 const LLVMContext &Ctx = DbgNode->getContext();
582 StringRef Res = getName();
584 OS << Res << "," << getLineNumber();
585 if (auto *InlinedAt = get()->getInlinedAt()) {
586 if (DebugLoc InlinedAtDL = InlinedAt) {
588 printDebugLoc(InlinedAtDL, OS, Ctx);
594 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
595 assert(isDescriptorRef(V) &&
596 "DIDescriptorRef should be a MDString or MDNode");
598 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
599 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
601 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
602 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
606 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
607 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
610 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
611 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
613 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
614 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
619 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
620 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
623 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
624 return MDScopeRef(Val).resolve(Map);
627 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
628 return MDTypeRef(Val).resolve(Map);
631 bool llvm::stripDebugInfo(Function &F) {
632 bool Changed = false;
633 for (BasicBlock &BB : F) {
634 for (Instruction &I : BB) {
635 if (I.getDebugLoc()) {
637 I.setDebugLoc(DebugLoc());
644 bool llvm::StripDebugInfo(Module &M) {
645 bool Changed = false;
647 // Remove all of the calls to the debugger intrinsics, and remove them from
649 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
650 while (!Declare->use_empty()) {
651 CallInst *CI = cast<CallInst>(Declare->user_back());
652 CI->eraseFromParent();
654 Declare->eraseFromParent();
658 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
659 while (!DbgVal->use_empty()) {
660 CallInst *CI = cast<CallInst>(DbgVal->user_back());
661 CI->eraseFromParent();
663 DbgVal->eraseFromParent();
667 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
668 NME = M.named_metadata_end(); NMI != NME;) {
669 NamedMDNode *NMD = NMI;
671 if (NMD->getName().startswith("llvm.dbg.")) {
672 NMD->eraseFromParent();
677 for (Function &F : M)
678 Changed |= stripDebugInfo(F);
680 if (GVMaterializer *Materializer = M.getMaterializer())
681 Materializer->setStripDebugInfo();
686 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
687 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
688 M.getModuleFlag("Debug Info Version")))
689 return Val->getZExtValue();
693 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
694 llvm::makeSubprogramMap(const Module &M) {
695 DenseMap<const Function *, DISubprogram> R;
697 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
701 for (MDNode *N : CU_Nodes->operands()) {
702 DICompileUnit CUNode = cast<MDCompileUnit>(N);
703 DIArray SPs = CUNode.getSubprograms();
704 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
705 DISubprogram SP = cast<MDSubprogram>(SPs.getElement(i));
706 if (Function *F = SP.getFunction())
707 R.insert(std::make_pair(F, SP));