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 //===----------------------------------------------------------------------===//
37 // Simple Descriptor Constructors and other Methods
38 //===----------------------------------------------------------------------===//
40 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
42 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
43 assert(CurFn && "Invalid function");
44 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
47 // This variable is not inlined function argument if its scope
48 // does not describe current function.
49 return !SP.describes(CurFn);
52 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
53 get()->replaceSubprograms(MDSubprogramArray(Subprograms));
56 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
57 get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
60 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
61 DILexicalBlockFile NewScope) {
62 assert(NewScope && "Expected valid scope");
64 const auto *Old = cast<MDLocation>(DbgNode);
65 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
66 NewScope, Old->getInlinedAt()));
69 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
70 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
71 return ++Ctx.pImpl->DiscriminatorTable[Key];
74 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
75 LLVMContext &VMContext) {
76 return cast<MDLocalVariable>(DV)
77 ->withInline(cast_or_null<MDLocation>(InlinedScope));
80 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
81 return cast<MDLocalVariable>(DV)->withoutInline();
84 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
85 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
86 return LocalScope->getSubprogram();
90 DISubprogram llvm::getDISubprogram(const Function *F) {
91 // We look for the first instr that has a debug annotation leading back to F.
93 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
94 return Inst.getDebugLoc();
98 DebugLoc DLoc = Inst->getDebugLoc();
99 const MDNode *Scope = DLoc.getInlinedAtScope();
100 DISubprogram Subprogram = getDISubprogram(Scope);
101 return Subprogram.describes(F) ? Subprogram : DISubprogram();
104 return DISubprogram();
107 DICompositeType llvm::getDICompositeType(DIType T) {
108 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
111 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
112 // This function is currently used by dragonegg and dragonegg does
113 // not generate identifier for types, so using an empty map to resolve
114 // DerivedFrom should be fine.
115 DITypeIdentifierMap EmptyMap;
116 return getDICompositeType(
117 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
124 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
125 DITypeIdentifierMap Map;
126 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
127 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
128 DIArray Retain = CU.getRetainedTypes();
129 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
130 if (!isa<MDCompositeType>(Retain[Ti]))
132 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
133 if (MDString *TypeId = Ty.getIdentifier()) {
134 // Definition has priority over declaration.
135 // Try to insert (TypeId, Ty) to Map.
136 std::pair<DITypeIdentifierMap::iterator, bool> P =
137 Map.insert(std::make_pair(TypeId, Ty));
138 // If TypeId already exists in Map and this is a definition, replace
139 // whatever we had (declaration or definition) with the definition.
140 if (!P.second && !Ty.isForwardDecl())
141 P.first->second = Ty;
148 //===----------------------------------------------------------------------===//
149 // DebugInfoFinder implementations.
150 //===----------------------------------------------------------------------===//
152 void DebugInfoFinder::reset() {
159 TypeIdentifierMap.clear();
160 TypeMapInitialized = false;
163 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
164 if (!TypeMapInitialized)
165 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
166 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
167 TypeMapInitialized = true;
171 void DebugInfoFinder::processModule(const Module &M) {
172 InitializeTypeMap(M);
173 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
174 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
175 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
177 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
178 if (addGlobalVariable(DIG)) {
179 processScope(DIG.getContext());
180 processType(DIG.getType().resolve(TypeIdentifierMap));
183 for (auto *SP : CU->getSubprograms())
184 processSubprogram(SP);
185 for (auto *ET : CU->getEnumTypes())
187 for (auto *RT : CU->getRetainedTypes())
189 for (DIImportedEntity Import : CU->getImportedEntities()) {
190 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
191 if (auto *T = dyn_cast<MDType>(Entity))
193 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
194 processSubprogram(SP);
195 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
196 processScope(NS->getScope());
202 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
205 InitializeTypeMap(M);
206 processScope(Loc.getScope());
207 processLocation(M, Loc.getOrigLocation());
210 void DebugInfoFinder::processType(DIType DT) {
213 processScope(DT.getContext().resolve(TypeIdentifierMap));
214 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
215 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
216 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
217 for (MDTypeRef Ref : ST->getTypeArray())
218 processType(Ref.resolve(TypeIdentifierMap));
221 for (Metadata *D : DCT->getElements()->operands()) {
222 if (DIType T = dyn_cast<MDType>(D))
224 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
225 processSubprogram(SP);
227 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
228 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
232 void DebugInfoFinder::processScope(DIScope Scope) {
235 if (DIType Ty = dyn_cast<MDType>(Scope)) {
239 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
243 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
244 processSubprogram(SP);
247 if (!addScope(Scope))
249 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
250 processScope(LB.getContext());
251 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
252 processScope(NS.getContext());
256 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
257 if (!addSubprogram(SP))
259 processScope(SP.getContext().resolve(TypeIdentifierMap));
260 processType(SP.getType());
261 for (auto *Element : SP.getTemplateParams()) {
262 if (DITemplateTypeParameter TType =
263 dyn_cast<MDTemplateTypeParameter>(Element)) {
264 processType(TType.getType().resolve(TypeIdentifierMap));
265 } else if (DITemplateValueParameter TVal =
266 dyn_cast<MDTemplateValueParameter>(Element)) {
267 processType(TVal.getType().resolve(TypeIdentifierMap));
272 void DebugInfoFinder::processDeclare(const Module &M,
273 const DbgDeclareInst *DDI) {
274 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
277 InitializeTypeMap(M);
279 DIVariable DV = dyn_cast<MDLocalVariable>(N);
283 if (!NodesSeen.insert(DV).second)
285 processScope(DV.getContext());
286 processType(DV.getType().resolve(TypeIdentifierMap));
289 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
290 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
293 InitializeTypeMap(M);
295 DIVariable DV = dyn_cast<MDLocalVariable>(N);
299 if (!NodesSeen.insert(DV).second)
301 processScope(DV.getContext());
302 processType(DV.getType().resolve(TypeIdentifierMap));
305 bool DebugInfoFinder::addType(DIType DT) {
309 if (!NodesSeen.insert(DT).second)
316 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
319 if (!NodesSeen.insert(CU).second)
326 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
330 if (!NodesSeen.insert(DIG).second)
337 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
341 if (!NodesSeen.insert(SP).second)
348 bool DebugInfoFinder::addScope(DIScope Scope) {
351 // FIXME: Ocaml binding generates a scope with no content, we treat it
353 if (Scope->getNumOperands() == 0)
355 if (!NodesSeen.insert(Scope).second)
357 Scopes.push_back(Scope);
361 //===----------------------------------------------------------------------===//
362 // DIDescriptor: dump routines for all descriptors.
363 //===----------------------------------------------------------------------===//
365 void DIDescriptor::dump() const {
370 void DIDescriptor::print(raw_ostream &OS) const {
376 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
377 const LLVMContext &Ctx) {
381 DIScope Scope = cast<MDScope>(DL.getScope());
382 // Omit the directory, because it's likely to be long and uninteresting.
383 CommentOS << Scope.getFilename();
384 CommentOS << ':' << DL.getLine();
385 if (DL.getCol() != 0)
386 CommentOS << ':' << DL.getCol();
388 DebugLoc InlinedAtDL = DL.getInlinedAt();
393 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
397 void DIVariable::printExtendedName(raw_ostream &OS) const {
398 const LLVMContext &Ctx = DbgNode->getContext();
399 StringRef Res = getName();
401 OS << Res << "," << getLineNumber();
402 if (auto *InlinedAt = get()->getInlinedAt()) {
403 if (DebugLoc InlinedAtDL = InlinedAt) {
405 printDebugLoc(InlinedAtDL, OS, Ctx);
413 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
414 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
417 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
418 return MDScopeRef(Val).resolve(Map);
421 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
422 return MDTypeRef(Val).resolve(Map);
425 bool llvm::stripDebugInfo(Function &F) {
426 bool Changed = false;
427 for (BasicBlock &BB : F) {
428 for (Instruction &I : BB) {
429 if (I.getDebugLoc()) {
431 I.setDebugLoc(DebugLoc());
438 bool llvm::StripDebugInfo(Module &M) {
439 bool Changed = false;
441 // Remove all of the calls to the debugger intrinsics, and remove them from
443 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
444 while (!Declare->use_empty()) {
445 CallInst *CI = cast<CallInst>(Declare->user_back());
446 CI->eraseFromParent();
448 Declare->eraseFromParent();
452 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
453 while (!DbgVal->use_empty()) {
454 CallInst *CI = cast<CallInst>(DbgVal->user_back());
455 CI->eraseFromParent();
457 DbgVal->eraseFromParent();
461 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
462 NME = M.named_metadata_end(); NMI != NME;) {
463 NamedMDNode *NMD = NMI;
465 if (NMD->getName().startswith("llvm.dbg.")) {
466 NMD->eraseFromParent();
471 for (Function &F : M)
472 Changed |= stripDebugInfo(F);
474 if (GVMaterializer *Materializer = M.getMaterializer())
475 Materializer->setStripDebugInfo();
480 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
481 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
482 M.getModuleFlag("Debug Info Version")))
483 return Val->getZExtValue();
487 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
488 llvm::makeSubprogramMap(const Module &M) {
489 DenseMap<const Function *, DISubprogram> R;
491 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
495 for (MDNode *N : CU_Nodes->operands()) {
496 DICompileUnit CUNode = cast<MDCompileUnit>(N);
497 for (DISubprogram SP : CUNode->getSubprograms()) {
498 if (Function *F = SP.getFunction())
499 R.insert(std::make_pair(F, SP));