1 //===--- DebugIR.cpp - Transform debug metadata to allow debugging IR -----===//
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 // A Module transform pass that emits a succinct version of the IR and replaces
11 // the source file metadata to allow debuggers to step through the IR.
13 // FIXME: instead of replacing debug metadata, this pass should allow for
14 // additional metadata to be used to point capable debuggers to the IR file
15 // without destroying the mapping to the original source file.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "debug-ir"
21 #include "llvm/ADT/ValueMap.h"
23 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
24 #include "llvm/DIBuilder.h"
25 #include "llvm/DebugInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/InstVisitor.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include "llvm/Transforms/Instrumentation.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
40 #define STR_HELPER(x) #x
41 #define STR(x) STR_HELPER(x)
47 /// Builds a map of Value* to line numbers on which the Value appears in a
48 /// textual representation of the IR by plugging into the AssemblyWriter by
49 /// masquerading as an AssemblyAnnotationWriter.
50 class ValueToLineMap : public AssemblyAnnotationWriter {
51 ValueMap<const Value *, unsigned int> Lines;
52 typedef ValueMap<const Value *, unsigned int>::const_iterator LineIter;
54 void addEntry(const Value *V, formatted_raw_ostream &Out) {
56 Lines.insert(std::make_pair(V, Out.getLine() + 1));
61 /// Prints Module to a null buffer in order to build the map of Value pointers
63 ValueToLineMap(const Module *M) {
64 raw_null_ostream ThrowAway;
65 M->print(ThrowAway, this);
68 // This function is called after an Instruction, GlobalValue, or GlobalAlias
70 void printInfoComment(const Value &V, formatted_raw_ostream &Out) {
74 void emitFunctionAnnot(const Function *F, formatted_raw_ostream &Out) {
78 /// If V appears on a line in the textual IR representation, sets Line to the
79 /// line number and returns true, otherwise returns false.
80 bool getLine(const Value *V, unsigned int &Line) const {
81 LineIter i = Lines.find(V);
82 if (i != Lines.end()) {
90 /// Removes debug intrisncs like llvm.dbg.declare and llvm.dbg.value.
91 class DebugIntrinsicsRemover : public InstVisitor<DebugIntrinsicsRemover> {
92 void remove(Instruction &I) { I.eraseFromParent(); }
95 static void process(Module &M) {
96 DebugIntrinsicsRemover Remover;
99 void visitDbgDeclareInst(DbgDeclareInst &I) { remove(I); }
100 void visitDbgValueInst(DbgValueInst &I) { remove(I); }
101 void visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) { remove(I); }
104 /// Removes debug metadata (!dbg) nodes from all instructions, and optionally
105 /// metadata named "llvm.dbg.cu" if RemoveNamedInfo is true.
106 class DebugMetadataRemover : public InstVisitor<DebugMetadataRemover> {
107 bool RemoveNamedInfo;
110 static void process(Module &M, bool RemoveNamedInfo = true) {
111 DebugMetadataRemover Remover(RemoveNamedInfo);
115 DebugMetadataRemover(bool RemoveNamedInfo)
116 : RemoveNamedInfo(RemoveNamedInfo) {}
118 void visitInstruction(Instruction &I) {
119 if (I.getMetadata(LLVMContext::MD_dbg))
120 I.setMetadata(LLVMContext::MD_dbg, 0);
123 void run(Module *M) {
124 // Remove debug metadata attached to instructions
127 if (RemoveNamedInfo) {
128 // Remove CU named metadata (and all children nodes)
129 NamedMDNode *Node = M->getNamedMetadata("llvm.dbg.cu");
131 M->eraseNamedMetadata(Node);
136 /// Updates debug metadata in a Module:
137 /// - changes Filename/Directory to values provided on construction
138 /// - adds/updates line number (DebugLoc) entries associated with each
139 /// instruction to reflect the instruction's location in an LLVM IR file
140 class DIUpdater : public InstVisitor<DIUpdater> {
141 /// Builder of debug information
144 /// Helper for type attributes/sizes/etc
147 /// Map of Value* to line numbers
148 const ValueToLineMap LineTable;
150 /// Map of Value* (in original Module) to Value* (in optional cloned Module)
151 const ValueToValueMapTy *VMap;
153 /// Directory of debug metadata
154 DebugInfoFinder Finder;
156 /// Source filename and directory
160 // CU nodes needed when creating DI subprograms
162 MDNode *LexicalBlockFileNode;
163 const MDNode *CUNode;
165 ValueMap<const Function *, MDNode *> SubprogramDescriptors;
166 DenseMap<const Type *, MDNode *> TypeDescriptors;
169 DIUpdater(Module &M, StringRef Filename = StringRef(),
170 StringRef Directory = StringRef(), const Module *DisplayM = 0,
171 const ValueToValueMapTy *VMap = 0)
172 : Builder(M), Layout(&M), LineTable(DisplayM ? DisplayM : &M), VMap(VMap),
173 Finder(), Filename(Filename), Directory(Directory), FileNode(0),
174 LexicalBlockFileNode(0), CUNode(0) {
175 Finder.processModule(M);
179 ~DIUpdater() { Builder.finalize(); }
181 void visitModule(Module &M) {
182 if (Finder.compile_unit_count() > 1)
183 report_fatal_error("DebugIR pass supports only a signle compile unit per "
186 Finder.compile_unit_count() == 1 ? *Finder.compile_unit_begin() : 0);
189 void visitFunction(Function &F) {
190 if (F.isDeclaration() || findDISubprogram(&F))
193 StringRef MangledName = F.getName();
194 DICompositeType Sig = createFunctionSignature(&F);
196 // find line of function declaration
198 if (!findLine(&F, Line)) {
199 DEBUG(dbgs() << "WARNING: No line for Function " << F.getName().str()
204 Instruction *FirstInst = F.begin()->begin();
205 unsigned ScopeLine = 0;
206 if (!findLine(FirstInst, ScopeLine)) {
207 DEBUG(dbgs() << "WARNING: No line for 1st Instruction in Function "
208 << F.getName().str() << "\n");
212 bool Local = F.hasInternalLinkage();
213 bool IsDefinition = !F.isDeclaration();
214 bool IsOptimized = false;
216 int FuncFlags = llvm::DIDescriptor::FlagPrototyped;
217 assert(CUNode && FileNode);
218 DISubprogram Sub = Builder.createFunction(
219 DICompileUnit(CUNode), F.getName(), MangledName, DIFile(FileNode), Line,
220 Sig, Local, IsDefinition, ScopeLine, FuncFlags, IsOptimized, &F);
221 assert(Sub.isSubprogram());
222 DEBUG(dbgs() << "create subprogram mdnode " << *Sub << ": "
225 SubprogramDescriptors.insert(std::make_pair(&F, Sub));
228 void visitInstruction(Instruction &I) {
229 DebugLoc Loc(I.getDebugLoc());
231 /// If a ValueToValueMap is provided, use it to get the real instruction as
232 /// the line table was generated on a clone of the module on which we are
236 RealInst = VMap->lookup(&I);
241 unsigned Col = 0; // FIXME: support columns
243 if (!LineTable.getLine(RealInst, Line)) {
244 // Instruction has no line, it may have been removed (in the module that
245 // will be passed to the debugger) so there is nothing to do here.
246 DEBUG(dbgs() << "WARNING: no LineTable entry for instruction " << RealInst
248 DEBUG(RealInst->dump());
253 if (!Loc.isUnknown())
254 // I had a previous debug location: re-use the DebugLoc
255 NewLoc = DebugLoc::get(Line, Col, Loc.getScope(RealInst->getContext()),
256 Loc.getInlinedAt(RealInst->getContext()));
257 else if (MDNode *scope = findScope(&I))
258 NewLoc = DebugLoc::get(Line, Col, scope, 0);
260 DEBUG(dbgs() << "WARNING: no valid scope for instruction " << &I
261 << ". no DebugLoc will be present."
266 addDebugLocation(I, NewLoc);
271 void createCompileUnit(MDNode *CUToReplace) {
273 bool IsOptimized = false;
275 unsigned RuntimeVersion(0);
279 // save fields from existing CU to re-use in the new CU
280 DICompileUnit ExistingCU(CUToReplace);
281 Producer = ExistingCU.getProducer();
282 IsOptimized = ExistingCU.isOptimized();
283 Flags = ExistingCU.getFlags();
284 RuntimeVersion = ExistingCU.getRunTimeVersion();
285 SplitName = ExistingCU.getSplitDebugFilename();
288 "LLVM Version " STR(LLVM_VERSION_MAJOR) "." STR(LLVM_VERSION_MINOR);
292 Builder.createCompileUnit(dwarf::DW_LANG_C99, Filename, Directory,
293 Producer, IsOptimized, Flags, RuntimeVersion);
296 CUToReplace->replaceAllUsesWith(const_cast<MDNode *>(CUNode));
298 DICompileUnit CU(CUNode);
299 FileNode = Builder.createFile(Filename, Directory);
300 LexicalBlockFileNode = Builder.createLexicalBlockFile(CU, DIFile(FileNode));
303 /// Returns the MDNode* that represents the DI scope to associate with I
304 MDNode *findScope(const Instruction *I) {
305 const Function *F = I->getParent()->getParent();
306 if (MDNode *ret = findDISubprogram(F))
309 DEBUG(dbgs() << "WARNING: Using fallback lexical block file scope "
310 << LexicalBlockFileNode << " as scope for instruction " << I
312 return LexicalBlockFileNode;
315 /// Returns the MDNode* that is the descriptor for F
316 MDNode *findDISubprogram(const Function *F) {
317 typedef ValueMap<const Function *, MDNode *>::const_iterator FuncNodeIter;
318 FuncNodeIter i = SubprogramDescriptors.find(F);
319 if (i != SubprogramDescriptors.end())
322 DEBUG(dbgs() << "searching for DI scope node for Function " << F
323 << " in a list of " << Finder.subprogram_count()
324 << " subprogram nodes"
327 for (DebugInfoFinder::iterator i = Finder.subprogram_begin(),
328 e = Finder.subprogram_end();
331 if (S.getFunction() == F) {
332 DEBUG(dbgs() << "Found DISubprogram " << *i << " for function "
333 << S.getFunction() << "\n");
337 DEBUG(dbgs() << "unable to find DISubprogram node for function "
338 << F->getName().str() << "\n");
342 /// Sets Line to the line number on which V appears and returns true. If a
343 /// line location for V is not found, returns false.
344 bool findLine(const Value *V, unsigned &Line) {
345 if (LineTable.getLine(V, Line))
349 Value *mapped = VMap->lookup(V);
350 if (mapped && LineTable.getLine(mapped, Line))
356 std::string getTypeName(Type *T) {
357 std::string TypeName;
358 raw_string_ostream TypeStream(TypeName);
359 T->print(TypeStream);
364 /// Returns the MDNode that represents type T if it is already created, or 0
366 MDNode *getType(const Type *T) {
367 typedef DenseMap<const Type *, MDNode *>::const_iterator TypeNodeIter;
368 TypeNodeIter i = TypeDescriptors.find(T);
369 if (i != TypeDescriptors.end())
374 /// Returns a DebugInfo type from an LLVM type T.
375 DIDerivedType getOrCreateType(Type *T) {
376 MDNode *N = getType(T);
378 return DIDerivedType(N);
379 else if (T->isVoidTy())
380 return DIDerivedType(0);
381 else if (T->isStructTy()) {
382 N = Builder.createStructType(
383 DIScope(LexicalBlockFileNode), T->getStructName(), DIFile(FileNode),
384 0, Layout.getTypeSizeInBits(T), Layout.getABITypeAlignment(T), 0,
385 DIType(0), DIArray(0)); // filled in later
387 // N is added to the map (early) so that element search below can find it,
388 // so as to avoid infinite recursion for structs that contain pointers to
390 TypeDescriptors[T] = N;
391 DICompositeType StructDescriptor(N);
393 SmallVector<Value *, 4> Elements;
394 for (unsigned i = 0; i < T->getStructNumElements(); ++i)
395 Elements.push_back(getOrCreateType(T->getStructElementType(i)));
397 // set struct elements
398 StructDescriptor.setTypeArray(Builder.getOrCreateArray(Elements));
399 } else if (T->isPointerTy()) {
400 Type *PointeeTy = T->getPointerElementType();
401 if (!(N = getType(PointeeTy)))
402 N = Builder.createPointerType(
403 getOrCreateType(PointeeTy), Layout.getPointerTypeSizeInBits(T),
404 Layout.getPrefTypeAlignment(T), getTypeName(T));
405 } else if (T->isArrayTy()) {
406 SmallVector<Value *, 1> Subrange;
408 Builder.getOrCreateSubrange(0, T->getArrayNumElements() - 1));
410 N = Builder.createArrayType(Layout.getTypeSizeInBits(T),
411 Layout.getPrefTypeAlignment(T),
412 getOrCreateType(T->getArrayElementType()),
413 Builder.getOrCreateArray(Subrange));
415 int encoding = llvm::dwarf::DW_ATE_signed;
416 if (T->isIntegerTy())
417 encoding = llvm::dwarf::DW_ATE_unsigned;
418 else if (T->isFloatingPointTy())
419 encoding = llvm::dwarf::DW_ATE_float;
421 N = Builder.createBasicType(getTypeName(T), T->getPrimitiveSizeInBits(),
424 TypeDescriptors[T] = N;
425 return DIDerivedType(N);
428 /// Returns a DebugInfo type that represents a function signature for Func.
429 DICompositeType createFunctionSignature(const Function *Func) {
430 SmallVector<Value *, 4> Params;
431 DIDerivedType ReturnType(getOrCreateType(Func->getReturnType()));
432 Params.push_back(ReturnType);
434 const Function::ArgumentListType &Args(Func->getArgumentList());
435 for (Function::ArgumentListType::const_iterator i = Args.begin(),
438 Type *T(i->getType());
439 Params.push_back(getOrCreateType(T));
442 DIArray ParamArray = Builder.getOrCreateArray(Params);
443 return Builder.createSubroutineType(DIFile(FileNode), ParamArray);
446 /// Associates Instruction I with debug location Loc.
447 void addDebugLocation(Instruction &I, DebugLoc Loc) {
448 MDNode *MD = Loc.getAsMDNode(I.getContext());
449 I.setMetadata(LLVMContext::MD_dbg, MD);
453 /// Sets Filename/Directory from the Module identifier and returns true, or
454 /// false if source information is not present.
455 bool getSourceInfoFromModule(const Module &M, std::string &Directory,
456 std::string &Filename) {
457 std::string PathStr(M.getModuleIdentifier());
458 if (PathStr.length() == 0 || PathStr == "<stdin>")
461 Filename = sys::path::filename(PathStr);
462 SmallVector<char, 16> Path(PathStr.begin(), PathStr.end());
463 sys::path::remove_filename(Path);
464 Directory = StringRef(Path.data(), Path.size());
468 // Sets Filename/Directory from debug information in M and returns true, or
469 // false if no debug information available, or cannot be parsed.
470 bool getSourceInfoFromDI(const Module &M, std::string &Directory,
471 std::string &Filename) {
472 NamedMDNode *CUNode = M.getNamedMetadata("llvm.dbg.cu");
473 if (!CUNode || CUNode->getNumOperands() == 0)
476 DICompileUnit CU(CUNode->getOperand(0));
480 Filename = CU.getFilename();
481 Directory = CU.getDirectory();
485 } // anonymous namespace
489 bool DebugIR::getSourceInfo(const Module &M) {
490 ParsedPath = getSourceInfoFromDI(M, Directory, Filename) ||
491 getSourceInfoFromModule(M, Directory, Filename);
495 bool DebugIR::updateExtension(StringRef NewExtension) {
496 size_t dot = Filename.find_last_of(".");
497 if (dot == std::string::npos)
501 Filename += NewExtension.str();
505 void DebugIR::generateFilename(OwningPtr<int> &fd) {
506 SmallVector<char, 16> PathVec;
508 sys::fs::createTemporaryFile("debug-ir", "ll", *fd, PathVec);
509 StringRef Path(PathVec.data(), PathVec.size());
510 Filename = sys::path::filename(Path);
511 sys::path::remove_filename(PathVec);
512 Directory = StringRef(PathVec.data(), PathVec.size());
514 GeneratedPath = true;
517 std::string DebugIR::getPath() {
518 SmallVector<char, 16> Path;
519 sys::path::append(Path, Directory, Filename);
520 Path.resize(Filename.size() + Directory.size() + 2);
521 Path[Filename.size() + Directory.size() + 1] = '\0';
522 return std::string(Path.data());
525 void DebugIR::writeDebugBitcode(const Module *M, int *fd) {
526 OwningPtr<raw_fd_ostream> Out;
530 std::string Path = getPath();
531 Out.reset(new raw_fd_ostream(Path.c_str(), error));
532 DEBUG(dbgs() << "WRITING debug bitcode from Module " << M << " to file "
535 DEBUG(dbgs() << "WRITING debug bitcode from Module " << M << " to fd "
537 Out.reset(new raw_fd_ostream(*fd, true));
544 void DebugIR::createDebugInfo(Module &M, OwningPtr<Module> &DisplayM) {
545 if (M.getFunctionList().size() == 0)
546 // no functions -- no debug info needed
549 OwningPtr<ValueToValueMapTy> VMap;
551 if (WriteSourceToDisk && (HideDebugIntrinsics || HideDebugMetadata)) {
552 VMap.reset(new ValueToValueMapTy);
553 DisplayM.reset(CloneModule(&M, *VMap));
555 if (HideDebugIntrinsics)
556 DebugIntrinsicsRemover::process(*DisplayM);
558 if (HideDebugMetadata)
559 DebugMetadataRemover::process(*DisplayM);
562 DIUpdater R(M, Filename, Directory, DisplayM.get(), VMap.get());
565 bool DebugIR::isMissingPath() { return Filename.empty() || Directory.empty(); }
567 bool DebugIR::runOnModule(Module &M) {
570 if (isMissingPath() && !getSourceInfo(M)) {
571 if (!WriteSourceToDisk)
572 report_fatal_error("DebugIR unable to determine file name in input. "
573 "Ensure Module contains an identifier, a valid "
574 "DICompileUnit, or construct DebugIR with "
575 "non-empty Filename/Directory parameters.");
577 generateFilename(fd);
580 if (!GeneratedPath && WriteSourceToDisk)
581 updateExtension(".debug-ll");
583 // Clear line numbers. Keep debug info (if any) if we were able to read the
584 // file name from the DICompileUnit descriptor.
585 DebugMetadataRemover::process(M, !ParsedPath);
587 OwningPtr<Module> DisplayM;
588 createDebugInfo(M, DisplayM);
589 if (WriteSourceToDisk) {
590 Module *OutputM = DisplayM.get() ? DisplayM.get() : &M;
591 writeDebugBitcode(OutputM, fd.get());
598 bool DebugIR::runOnModule(Module &M, std::string &Path) {
599 bool result = runOnModule(M);
606 char DebugIR::ID = 0;
607 INITIALIZE_PASS(DebugIR, "debug-ir", "Enable debugging IR", false, false)
609 ModulePass *llvm::createDebugIRPass(bool HideDebugIntrinsics,
610 bool HideDebugMetadata, StringRef Directory,
611 StringRef Filename) {
612 return new DebugIR(HideDebugIntrinsics, HideDebugMetadata, Directory,
616 ModulePass *llvm::createDebugIRPass() { return new DebugIR(); }