MLIR  19.0.0git
DebugTranslation.cpp
Go to the documentation of this file.
1 //===- DebugTranslation.cpp - MLIR to LLVM Debug conversion ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DebugTranslation.h"
11 #include "llvm/ADT/TypeSwitch.h"
12 #include "llvm/IR/Metadata.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/Path.h"
16 
17 using namespace mlir;
18 using namespace mlir::LLVM;
19 using namespace mlir::LLVM::detail;
20 
21 /// A utility walker that interrupts if the operation has valid debug
22 /// information.
24  return isa<UnknownLoc>(op->getLoc()) ? WalkResult::advance()
26 }
27 
28 DebugTranslation::DebugTranslation(Operation *module, llvm::Module &llvmModule)
29  : debugEmissionIsEnabled(false), llvmModule(llvmModule),
30  llvmCtx(llvmModule.getContext()) {
31  // If the module has no location information, there is nothing to do.
32  if (!module->walk(interruptIfValidLocation).wasInterrupted())
33  return;
34  debugEmissionIsEnabled = true;
35 
36  // TODO: The version information should be encoded on the LLVM module itself,
37  // not implicitly set here.
38 
39  // Mark this module as having debug information.
40  StringRef debugVersionKey = "Debug Info Version";
41  if (!llvmModule.getModuleFlag(debugVersionKey))
42  llvmModule.addModuleFlag(llvm::Module::Warning, debugVersionKey,
43  llvm::DEBUG_METADATA_VERSION);
44 
45  if (auto targetTripleAttr = module->getDiscardableAttr(
46  LLVM::LLVMDialect::getTargetTripleAttrName())) {
47  auto targetTriple =
48  llvm::Triple(cast<StringAttr>(targetTripleAttr).getValue());
49  if (targetTriple.isKnownWindowsMSVCEnvironment()) {
50  // Dwarf debugging files will be generated by default, unless "CodeView"
51  // is set explicitly. Windows/MSVC should use CodeView instead.
52  llvmModule.addModuleFlag(llvm::Module::Warning, "CodeView", 1);
53  }
54  }
55 }
56 
57 /// Finalize the translation of debug information.
59 
60 /// Translate the debug information for the given function.
61 void DebugTranslation::translate(LLVMFuncOp func, llvm::Function &llvmFunc) {
62  if (!debugEmissionIsEnabled)
63  return;
64 
65  // Look for a sub program attached to the function.
66  auto spLoc =
67  func.getLoc()->findInstanceOf<FusedLocWith<LLVM::DISubprogramAttr>>();
68  if (!spLoc)
69  return;
70  llvmFunc.setSubprogram(translate(spLoc.getMetadata()));
71 }
72 
73 //===----------------------------------------------------------------------===//
74 // Attributes
75 //===----------------------------------------------------------------------===//
76 
77 llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
78  // A DINullTypeAttr at the beginning of the subroutine types list models
79  // a void result type. If it is at the end, it models a variadic function.
80  // Translate the explicit DINullTypeAttr to a nullptr since LLVM IR metadata
81  // does not have an explicit void result type nor a variadic type
82  // representation.
83  return nullptr;
84 }
85 
86 llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
87  if (!stringAttr || stringAttr.empty())
88  return nullptr;
89  return llvm::MDString::get(llvmCtx, stringAttr);
90 }
91 
92 llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
94  llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
95  attr.getSizeInBits(),
96  /*AlignInBits=*/0, attr.getEncoding(), llvm::DINode::FlagZero);
97 }
98 
99 llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
100  llvm::DIBuilder builder(llvmModule);
101  return builder.createCompileUnit(
102  attr.getSourceLanguage(), translate(attr.getFile()),
103  attr.getProducer() ? attr.getProducer().getValue() : "",
104  attr.getIsOptimized(),
105  /*Flags=*/"", /*RV=*/0, /*SplitName=*/{},
106  static_cast<llvm::DICompileUnit::DebugEmissionKind>(
107  attr.getEmissionKind()),
108  0, true, false,
109  static_cast<llvm::DICompileUnit::DebugNameTableKind>(
110  attr.getNameTableKind()));
111 }
112 
113 /// Returns a new `DINodeT` that is either distinct or not, depending on
114 /// `isDistinct`.
115 template <class DINodeT, class... Ts>
116 static DINodeT *getDistinctOrUnique(bool isDistinct, Ts &&...args) {
117  if (isDistinct)
118  return DINodeT::getDistinct(std::forward<Ts>(args)...);
119  return DINodeT::get(std::forward<Ts>(args)...);
120 }
121 
122 llvm::TempDICompositeType
123 DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
124  return llvm::DICompositeType::getTemporary(
125  llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()), nullptr,
126  attr.getLine(), nullptr, nullptr, attr.getSizeInBits(),
127  attr.getAlignInBits(),
128  /*OffsetInBits=*/0,
129  /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
130  /*Elements=*/nullptr, /*RuntimeLang=*/0,
131  /*VTableHolder=*/nullptr);
132 }
133 
134 llvm::DICompositeType *
135 DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
136  // TODO: Use distinct attributes to model this, once they have landed.
137  // Depending on the tag, composite types must be distinct.
138  bool isDistinct = false;
139  switch (attr.getTag()) {
140  case llvm::dwarf::DW_TAG_class_type:
141  case llvm::dwarf::DW_TAG_enumeration_type:
142  case llvm::dwarf::DW_TAG_structure_type:
143  case llvm::dwarf::DW_TAG_union_type:
144  isDistinct = true;
145  }
146 
148  for (DINodeAttr member : attr.getElements())
149  elements.push_back(translate(member));
150 
151  return getDistinctOrUnique<llvm::DICompositeType>(
152  isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
153  translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
154  translate(attr.getBaseType()), attr.getSizeInBits(),
155  attr.getAlignInBits(),
156  /*OffsetInBits=*/0,
157  /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
158  llvm::MDNode::get(llvmCtx, elements),
159  /*RuntimeLang=*/0, /*VTableHolder=*/nullptr);
160 }
161 
162 llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
164  llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
165  /*File=*/nullptr, /*Line=*/0,
166  /*Scope=*/nullptr, translate(attr.getBaseType()), attr.getSizeInBits(),
167  attr.getAlignInBits(), attr.getOffsetInBits(),
168  attr.getDwarfAddressSpace(), /*PtrAuthData=*/std::nullopt,
169  /*Flags=*/llvm::DINode::FlagZero, translate(attr.getExtraData()));
170 }
171 
172 llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
173  return llvm::DIFile::get(llvmCtx, getMDStringOrNull(attr.getName()),
174  getMDStringOrNull(attr.getDirectory()));
175 }
176 
177 llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
178  return llvm::DILabel::get(llvmCtx, translate(attr.getScope()),
179  getMDStringOrNull(attr.getName()),
180  translate(attr.getFile()), attr.getLine());
181 }
182 
183 llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
184  return llvm::DILexicalBlock::getDistinct(llvmCtx, translate(attr.getScope()),
185  translate(attr.getFile()),
186  attr.getLine(), attr.getColumn());
187 }
188 
189 llvm::DILexicalBlockFile *
190 DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
191  return llvm::DILexicalBlockFile::getDistinct(
192  llvmCtx, translate(attr.getScope()), translate(attr.getFile()),
193  attr.getDiscriminator());
194 }
195 
196 llvm::DILocalScope *DebugTranslation::translateImpl(DILocalScopeAttr attr) {
197  return cast<llvm::DILocalScope>(translate(DINodeAttr(attr)));
198 }
199 
200 llvm::DILocalVariable *
201 DebugTranslation::translateImpl(DILocalVariableAttr attr) {
203  llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
204  translate(attr.getFile()), attr.getLine(), translate(attr.getType()),
205  attr.getArg(),
206  /*Flags=*/llvm::DINode::FlagZero, attr.getAlignInBits(),
207  /*Annotations=*/nullptr);
208 }
209 
210 llvm::DIGlobalVariable *
211 DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
212  return llvm::DIGlobalVariable::getDistinct(
213  llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
214  getMDStringOrNull(attr.getLinkageName()), translate(attr.getFile()),
215  attr.getLine(), translate(attr.getType()), attr.getIsLocalToUnit(),
216  attr.getIsDefined(), nullptr, nullptr, attr.getAlignInBits(), nullptr);
217 }
218 
219 llvm::DIType *
220 DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
221  DistinctAttr recursiveId = attr.getRecId();
222  if (auto *iter = recursiveTypeMap.find(recursiveId);
223  iter != recursiveTypeMap.end()) {
224  return iter->second;
225  } else {
226  assert(!attr.isRecSelf() && "unbound DI recursive self type");
227  }
228 
229  auto setRecursivePlaceholder = [&](llvm::DIType *placeholder) {
230  recursiveTypeMap.try_emplace(recursiveId, placeholder);
231  };
232 
233  llvm::DIType *result =
235  .Case<DICompositeTypeAttr>([&](auto attr) {
236  auto temporary = translateTemporaryImpl(attr);
237  setRecursivePlaceholder(temporary.get());
238  // Must call `translateImpl` directly instead of `translate` to
239  // avoid handling the recursive interface again.
240  auto *concrete = translateImpl(attr);
241  temporary->replaceAllUsesWith(concrete);
242  return concrete;
243  });
244 
245  assert(recursiveTypeMap.back().first == recursiveId &&
246  "internal inconsistency: unexpected recursive translation stack");
247  recursiveTypeMap.pop_back();
248 
249  return result;
250 }
251 
252 llvm::DIScope *DebugTranslation::translateImpl(DIScopeAttr attr) {
253  return cast<llvm::DIScope>(translate(DINodeAttr(attr)));
254 }
255 
256 llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
257  if (auto iter = distinctAttrToNode.find(attr.getId());
258  iter != distinctAttrToNode.end())
259  return cast<llvm::DISubprogram>(iter->second);
260 
261  llvm::DIScope *scope = translate(attr.getScope());
262  llvm::DIFile *file = translate(attr.getFile());
263  llvm::DIType *type = translate(attr.getType());
264  llvm::DICompileUnit *compileUnit = translate(attr.getCompileUnit());
265 
266  // Check again after recursive calls in case this distinct node recurses back
267  // to itself.
268  if (auto iter = distinctAttrToNode.find(attr.getId());
269  iter != distinctAttrToNode.end())
270  return cast<llvm::DISubprogram>(iter->second);
271 
272  bool isDefinition = static_cast<bool>(attr.getSubprogramFlags() &
273  LLVM::DISubprogramFlags::Definition);
274  llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
275  isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
276  getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
277  attr.getScopeLine(),
278  /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
279  /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
280  static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
281  compileUnit);
282 
283  if (attr.getId())
284  distinctAttrToNode.try_emplace(attr.getId(), node);
285  return node;
286 }
287 
288 llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
289  return llvm::DIModule::get(
290  llvmCtx, translate(attr.getFile()), translate(attr.getScope()),
291  getMDStringOrNull(attr.getName()),
292  getMDStringOrNull(attr.getConfigMacros()),
293  getMDStringOrNull(attr.getIncludePath()),
294  getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
295 }
296 
297 llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
298  return llvm::DINamespace::get(llvmCtx, translate(attr.getScope()),
299  getMDStringOrNull(attr.getName()),
300  attr.getExportSymbols());
301 }
302 
303 llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
304  auto getMetadataOrNull = [&](IntegerAttr attr) -> llvm::Metadata * {
305  if (!attr)
306  return nullptr;
307  return llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
308  llvm::Type::getInt64Ty(llvmCtx), attr.getInt()));
309  };
310  return llvm::DISubrange::get(llvmCtx, getMetadataOrNull(attr.getCount()),
311  getMetadataOrNull(attr.getLowerBound()),
312  getMetadataOrNull(attr.getUpperBound()),
313  getMetadataOrNull(attr.getStride()));
314 }
315 
316 llvm::DISubroutineType *
317 DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
318  // Concatenate the result and argument types into a single array.
320  for (DITypeAttr type : attr.getTypes())
321  types.push_back(translate(type));
323  llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
324  llvm::DITypeRefArray(llvm::MDNode::get(llvmCtx, types)));
325 }
326 
327 llvm::DIType *DebugTranslation::translateImpl(DITypeAttr attr) {
328  return cast<llvm::DIType>(translate(DINodeAttr(attr)));
329 }
330 
332  if (!attr)
333  return nullptr;
334  // Check for a cached instance.
335  if (llvm::DINode *node = attrToNode.lookup(attr))
336  return node;
337 
338  llvm::DINode *node = nullptr;
339  // Recursive types go through a dedicated handler. All other types are
340  // dispatched directly to their specific handlers.
341  if (auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
342  if (recTypeAttr.getRecId())
343  node = translateRecursive(recTypeAttr);
344 
345  if (!node)
347  .Case<DIBasicTypeAttr, DICompileUnitAttr, DICompositeTypeAttr,
348  DIDerivedTypeAttr, DIFileAttr, DIGlobalVariableAttr,
349  DILabelAttr, DILexicalBlockAttr, DILexicalBlockFileAttr,
350  DILocalVariableAttr, DIModuleAttr, DINamespaceAttr,
351  DINullTypeAttr, DISubprogramAttr, DISubrangeAttr,
352  DISubroutineTypeAttr>(
353  [&](auto attr) { return translateImpl(attr); });
354 
355  if (node && !node->isTemporary())
356  attrToNode.insert({attr, node});
357  return node;
358 }
359 
360 //===----------------------------------------------------------------------===//
361 // Locations
362 //===----------------------------------------------------------------------===//
363 
364 /// Translate the given location to an llvm debug location.
365 llvm::DILocation *DebugTranslation::translateLoc(Location loc,
366  llvm::DILocalScope *scope) {
367  if (!debugEmissionIsEnabled)
368  return nullptr;
369  return translateLoc(loc, scope, /*inlinedAt=*/nullptr);
370 }
371 
372 llvm::DIExpression *
373 DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
375  if (attr) {
376  // Append operations their operands to the list.
377  for (const DIExpressionElemAttr &op : attr.getOperations()) {
378  ops.push_back(op.getOpcode());
379  append_range(ops, op.getArguments());
380  }
381  }
382  return llvm::DIExpression::get(llvmCtx, ops);
383 }
384 
385 llvm::DIGlobalVariableExpression *
386 DebugTranslation::translateGlobalVariableExpression(
387  LLVM::DIGlobalVariableExpressionAttr attr) {
389  llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
390 }
391 
392 /// Translate the given location to an llvm DebugLoc.
393 llvm::DILocation *DebugTranslation::translateLoc(Location loc,
394  llvm::DILocalScope *scope,
395  llvm::DILocation *inlinedAt) {
396  // LLVM doesn't have a representation for unknown.
397  if (isa<UnknownLoc>(loc))
398  return nullptr;
399 
400  // Check for a cached instance.
401  auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
402  if (existingIt != locationToLoc.end())
403  return existingIt->second;
404 
405  llvm::DILocation *llvmLoc = nullptr;
406  if (auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
407  // For callsites, the caller is fed as the inlinedAt for the callee.
408  auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
409  // If the caller scope is not translatable, the overall callsite cannot be
410  // represented in LLVM (the callee scope may not match the parent function).
411  if (!callerLoc) {
412  // If there is an inlinedAt scope (an outer caller), skip to that
413  // directly. Otherwise, cannot translate.
414  if (!inlinedAt)
415  return nullptr;
416  callerLoc = inlinedAt;
417  }
418  llvmLoc = translateLoc(callLoc.getCallee(), nullptr, callerLoc);
419  // Fallback: Ignore callee if it has no debug scope.
420  if (!llvmLoc)
421  llvmLoc = callerLoc;
422 
423  } else if (auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
424  // A scope of a DILocation cannot be null.
425  if (!scope)
426  return nullptr;
427  llvmLoc =
428  llvm::DILocation::get(llvmCtx, fileLoc.getLine(), fileLoc.getColumn(),
429  scope, const_cast<llvm::DILocation *>(inlinedAt));
430 
431  } else if (auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
432  ArrayRef<Location> locations = fusedLoc.getLocations();
433 
434  // Check for a scope encoded with the location.
435  if (auto scopedAttr =
436  dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
437  scope = translate(scopedAttr);
438 
439  // For fused locations, merge each of the nodes.
440  llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
441  for (Location locIt : locations.drop_front()) {
442  llvmLoc = llvm::DILocation::getMergedLocation(
443  llvmLoc, translateLoc(locIt, scope, inlinedAt));
444  }
445 
446  } else if (auto nameLoc = dyn_cast<NameLoc>(loc)) {
447  llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
448 
449  } else if (auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
450  llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
451  } else {
452  llvm_unreachable("unknown location kind");
453  }
454 
455  locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
456  return llvmLoc;
457 }
458 
459 /// Create an llvm debug file for the given file path.
460 llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
461  auto *&file = fileMap[fileName];
462  if (file)
463  return file;
464 
465  // Make sure the current working directory is up-to-date.
466  if (currentWorkingDir.empty())
467  llvm::sys::fs::current_path(currentWorkingDir);
468 
469  StringRef directory = currentWorkingDir;
470  SmallString<128> dirBuf;
471  SmallString<128> fileBuf;
472  if (llvm::sys::path::is_absolute(fileName)) {
473  // Strip the common prefix (if it is more than just "/") from current
474  // directory and FileName for a more space-efficient encoding.
475  auto fileIt = llvm::sys::path::begin(fileName);
476  auto fileE = llvm::sys::path::end(fileName);
477  auto curDirIt = llvm::sys::path::begin(directory);
478  auto curDirE = llvm::sys::path::end(directory);
479  for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
480  llvm::sys::path::append(dirBuf, *curDirIt);
481  if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
482  // Don't strip the common prefix if it is only the root "/" since that
483  // would make LLVM diagnostic locations confusing.
484  directory = StringRef();
485  } else {
486  for (; fileIt != fileE; ++fileIt)
487  llvm::sys::path::append(fileBuf, *fileIt);
488  directory = dirBuf;
489  fileName = fileBuf;
490  }
491  }
492  return (file = llvm::DIFile::get(llvmCtx, fileName, directory));
493 }
static DINodeT * getDistinctOrUnique(bool isDistinct, Ts &&...args)
Returns a new DINodeT that is either distinct or not, depending on isDistinct.
static WalkResult interruptIfValidLocation(Operation *op)
A utility walker that interrupts if the operation has valid debug information.
static MLIRContext * getContext(OpFoldResult val)
An attribute that associates a referenced attribute with a unique identifier.
This class represents a fused location whose metadata is known to be an instance of the given type.
Definition: Location.h:148
This class represents a LLVM attribute that describes a local debug info scope.
Definition: LLVMAttrs.h:46
This class represents the base attribute for all debug info attributes.
Definition: LLVMAttrs.h:27
This class represents a LLVM attribute that describes a debug info scope.
Definition: LLVMAttrs.h:36
This class represents a LLVM attribute that describes a debug info type.
Definition: LLVMAttrs.h:55
void finalize()
Finalize the translation of debug information.
void translate(LLVMFuncOp func, llvm::Function &llvmFunc)
Translate the debug information for the given function.
DebugTranslation(Operation *module, llvm::Module &llvmModule)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns an null Attribute if the discardable attribute does n...
Definition: Operation.h:448
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition: Operation.h:793
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
A utility result that is used to signal how to proceed with an ongoing walk:
Definition: Visitors.h:34
static WalkResult advance()
Definition: Visitors.h:52
static WalkResult interrupt()
Definition: Visitors.h:51
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...