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"
29 : debugEmissionIsEnabled(false), llvmModule(llvmModule),
34 debugEmissionIsEnabled =
true;
40 StringRef debugVersionKey =
"Debug Info Version";
41 if (!llvmModule.getModuleFlag(debugVersionKey))
42 llvmModule.addModuleFlag(llvm::Module::Warning, debugVersionKey,
43 llvm::DEBUG_METADATA_VERSION);
46 LLVM::LLVMDialect::getTargetTripleAttrName())) {
48 llvm::Triple(cast<StringAttr>(targetTripleAttr).getValue());
49 if (targetTriple.isKnownWindowsMSVCEnvironment()) {
52 llvmModule.addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
62 if (!debugEmissionIsEnabled)
70 llvmFunc.setSubprogram(
translate(spLoc.getMetadata()));
77 llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
87 DebugTranslation::getExpressionAttrOrNull(DIExpressionAttr attr) {
93 llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
94 if (!stringAttr || stringAttr.empty())
101 if (elements.empty())
104 llvm::map_range(elements, [&](
DINodeAttr attr) -> llvm::Metadata * {
110 llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
112 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
113 attr.getSizeInBits(),
114 0, attr.getEncoding(), llvm::DINode::FlagZero);
117 llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
118 llvm::DIBuilder builder(llvmModule);
119 return builder.createCompileUnit(
120 attr.getSourceLanguage(),
translate(attr.getFile()),
121 attr.getProducer() ? attr.getProducer().getValue() :
"",
122 attr.getIsOptimized(),
124 static_cast<llvm::DICompileUnit::DebugEmissionKind
>(
125 attr.getEmissionKind()),
127 static_cast<llvm::DICompileUnit::DebugNameTableKind
>(
128 attr.getNameTableKind()));
133 template <
class DINodeT,
class... Ts>
136 return DINodeT::getDistinct(std::forward<Ts>(args)...);
140 llvm::TempDICompositeType
141 DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
142 return llvm::DICompositeType::getTemporary(
143 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
nullptr,
144 attr.getLine(),
nullptr,
nullptr, attr.getSizeInBits(),
145 attr.getAlignInBits(),
147 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
152 llvm::TempDISubprogram
153 DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) {
154 return llvm::DISubprogram::getTemporary(
155 llvmCtx,
nullptr, {}, {},
156 nullptr, attr.getLine(),
nullptr,
158 0, llvm::DINode::FlagZero,
159 static_cast<llvm::DISubprogram::DISPFlags
>(attr.getSubprogramFlags()),
163 llvm::DICompositeType *
164 DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
167 bool isDistinct =
false;
168 switch (attr.getTag()) {
169 case llvm::dwarf::DW_TAG_class_type:
170 case llvm::dwarf::DW_TAG_enumeration_type:
171 case llvm::dwarf::DW_TAG_structure_type:
172 case llvm::dwarf::DW_TAG_union_type:
176 return getDistinctOrUnique<llvm::DICompositeType>(
177 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
179 translate(attr.getBaseType()), attr.getSizeInBits(),
180 attr.getAlignInBits(),
182 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
183 getMDTupleOrNull(attr.getElements()),
187 getExpressionAttrOrNull(attr.getDataLocation()),
188 getExpressionAttrOrNull(attr.getAssociated()),
189 getExpressionAttrOrNull(attr.getAllocated()),
190 getExpressionAttrOrNull(attr.getRank()));
193 llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
195 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
197 nullptr,
translate(attr.getBaseType()), attr.getSizeInBits(),
198 attr.getAlignInBits(), attr.getOffsetInBits(),
199 attr.getDwarfAddressSpace(), std::nullopt,
200 llvm::DINode::FlagZero,
translate(attr.getExtraData()));
203 llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) {
205 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
207 getExpressionAttrOrNull(attr.getStringLengthExp()),
208 getExpressionAttrOrNull(attr.getStringLocationExp()),
209 attr.getSizeInBits(), attr.getAlignInBits(), attr.getEncoding());
212 llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
214 getMDStringOrNull(attr.getDirectory()));
217 llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
219 getMDStringOrNull(attr.getName()),
220 translate(attr.getFile()), attr.getLine());
223 llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
224 return llvm::DILexicalBlock::getDistinct(llvmCtx,
translate(attr.getScope()),
226 attr.getLine(), attr.getColumn());
229 llvm::DILexicalBlockFile *
230 DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
231 return llvm::DILexicalBlockFile::getDistinct(
233 attr.getDiscriminator());
236 llvm::DILocalScope *DebugTranslation::translateImpl(
DILocalScopeAttr attr) {
240 llvm::DIVariable *DebugTranslation::translateImpl(
DIVariableAttr attr) {
244 llvm::DILocalVariable *
245 DebugTranslation::translateImpl(DILocalVariableAttr attr) {
247 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
249 attr.getArg(),
static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
250 attr.getAlignInBits(),
254 llvm::DIGlobalVariable *
255 DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
256 return llvm::DIGlobalVariable::getDistinct(
257 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
258 getMDStringOrNull(attr.getLinkageName()),
translate(attr.getFile()),
259 attr.getLine(),
translate(attr.getType()), attr.getIsLocalToUnit(),
260 attr.getIsDefined(),
nullptr,
nullptr, attr.getAlignInBits(),
nullptr);
264 DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
266 if (
auto *iter = recursiveNodeMap.find(recursiveId);
267 iter != recursiveNodeMap.end()) {
270 assert(!attr.getIsRecSelf() &&
"unbound DI recursive self reference");
272 auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) {
273 recursiveNodeMap.try_emplace(recursiveId, placeholder);
276 llvm::DINode *result =
278 .Case<DICompositeTypeAttr>([&](
auto attr) {
279 auto temporary = translateTemporaryImpl(attr);
280 setRecursivePlaceholder(temporary.get());
283 auto *concrete = translateImpl(attr);
284 temporary->replaceAllUsesWith(concrete);
287 .Case<DISubprogramAttr>([&](
auto attr) {
288 auto temporary = translateTemporaryImpl(attr);
289 setRecursivePlaceholder(temporary.get());
292 auto *concrete = translateImpl(attr);
293 temporary->replaceAllUsesWith(concrete);
297 assert(recursiveNodeMap.back().first == recursiveId &&
298 "internal inconsistency: unexpected recursive translation stack");
299 recursiveNodeMap.pop_back();
304 llvm::DIScope *DebugTranslation::translateImpl(
DIScopeAttr attr) {
308 llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
309 if (
auto iter = distinctAttrToNode.find(attr.getId());
310 iter != distinctAttrToNode.end())
311 return cast<llvm::DISubprogram>(iter->second);
313 llvm::DIScope *scope =
translate(attr.getScope());
314 llvm::DIFile *file =
translate(attr.getFile());
315 llvm::DIType *type =
translate(attr.getType());
316 llvm::DICompileUnit *compileUnit =
translate(attr.getCompileUnit());
320 if (
auto iter = distinctAttrToNode.find(attr.getId());
321 iter != distinctAttrToNode.end())
322 return cast<llvm::DISubprogram>(iter->second);
324 bool isDefinition =
static_cast<bool>(attr.getSubprogramFlags() &
325 LLVM::DISubprogramFlags::Definition);
327 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
328 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
329 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
332 0, llvm::DINode::FlagZero,
333 static_cast<llvm::DISubprogram::DISPFlags
>(attr.getSubprogramFlags()),
334 compileUnit,
nullptr,
nullptr,
335 getMDTupleOrNull(attr.getRetainedNodes()));
337 distinctAttrToNode.try_emplace(attr.getId(), node);
341 llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
344 getMDStringOrNull(attr.getName()),
345 getMDStringOrNull(attr.getConfigMacros()),
346 getMDStringOrNull(attr.getIncludePath()),
347 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
350 llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
352 getMDStringOrNull(attr.getName()),
353 attr.getExportSymbols());
356 llvm::DIImportedEntity *
357 DebugTranslation::translateImpl(DIImportedEntityAttr attr) {
359 llvmCtx, attr.getTag(),
translate(attr.getScope()),
361 getMDStringOrNull(attr.getName()), getMDTupleOrNull(attr.getElements()));
364 llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
365 auto getMetadataOrNull = [&](
Attribute attr) -> llvm::Metadata * {
369 llvm::Metadata *metadata =
371 .Case([&](IntegerAttr intAttr) {
373 llvm::Type::getInt64Ty(llvmCtx), intAttr.getInt()));
375 .Case([&](LLVM::DIExpressionAttr expr) {
378 .Case([&](LLVM::DILocalVariableAttr local) {
381 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
384 .Default([&](
Attribute attr) {
return nullptr; });
388 getMetadataOrNull(attr.getLowerBound()),
389 getMetadataOrNull(attr.getUpperBound()),
390 getMetadataOrNull(attr.getStride()));
393 llvm::DISubroutineType *
394 DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
400 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
404 llvm::DIType *DebugTranslation::translateImpl(
DITypeAttr attr) {
412 if (llvm::DINode *node = attrToNode.lookup(attr))
415 llvm::DINode *node =
nullptr;
418 if (
auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
419 if (recTypeAttr.getRecId())
420 node = translateRecursive(recTypeAttr);
424 .Case<DIBasicTypeAttr, DICompileUnitAttr, DICompositeTypeAttr,
425 DIDerivedTypeAttr, DIFileAttr, DIGlobalVariableAttr,
426 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
427 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
428 DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr,
429 DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>(
430 [&](
auto attr) {
return translateImpl(attr); });
432 if (node && !node->isTemporary())
433 attrToNode.insert({attr, node});
442 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
443 llvm::DILocalScope *scope) {
444 if (!debugEmissionIsEnabled)
446 return translateLoc(loc, scope,
nullptr);
450 DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
454 for (
const DIExpressionElemAttr &op : attr.getOperations()) {
455 ops.push_back(op.getOpcode());
456 append_range(ops, op.getArguments());
462 llvm::DIGlobalVariableExpression *
463 DebugTranslation::translateGlobalVariableExpression(
464 LLVM::DIGlobalVariableExpressionAttr attr) {
466 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
470 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
471 llvm::DILocalScope *scope,
472 llvm::DILocation *inlinedAt) {
474 if (isa<UnknownLoc>(loc))
478 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
479 if (existingIt != locationToLoc.end())
480 return existingIt->second;
482 llvm::DILocation *llvmLoc =
nullptr;
483 if (
auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
485 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
493 callerLoc = inlinedAt;
495 llvmLoc = translateLoc(callLoc.getCallee(),
nullptr, callerLoc);
500 }
else if (
auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
506 scope,
const_cast<llvm::DILocation *
>(inlinedAt));
508 }
else if (
auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
512 if (
auto scopedAttr =
513 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
514 scope = translate(scopedAttr);
517 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
518 for (
Location locIt : locations.drop_front()) {
519 llvmLoc = llvm::DILocation::getMergedLocation(
520 llvmLoc, translateLoc(locIt, scope, inlinedAt));
523 }
else if (
auto nameLoc = dyn_cast<NameLoc>(loc)) {
524 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
526 }
else if (
auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
527 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
529 llvm_unreachable(
"unknown location kind");
532 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
537 llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
538 auto *&file = fileMap[fileName];
543 if (currentWorkingDir.empty())
544 llvm::sys::fs::current_path(currentWorkingDir);
546 StringRef directory = currentWorkingDir;
549 if (llvm::sys::path::is_absolute(fileName)) {
552 auto fileIt = llvm::sys::path::begin(fileName);
553 auto fileE = llvm::sys::path::end(fileName);
554 auto curDirIt = llvm::sys::path::begin(directory);
555 auto curDirE = llvm::sys::path::end(directory);
556 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
557 llvm::sys::path::append(dirBuf, *curDirIt);
558 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
561 directory = StringRef();
563 for (; fileIt != fileE; ++fileIt)
564 llvm::sys::path::append(fileBuf, *fileIt);
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)
Attributes are known-constant values of operations.
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.
This class represents a LLVM attribute that describes a local debug info scope.
This class represents the base attribute for all debug info attributes.
This class represents a LLVM attribute that describes a debug info scope.
This class represents a LLVM attribute that describes a debug info type.
This class represents a LLVM attribute that describes a debug info variable.
void finalize()
Finalize the translation of debug information.
void translate(LLVMFuncOp func, llvm::Function &llvmFunc)
Translate the debug information for the given function.
llvm::DIExpression * translateExpression(LLVM::DIExpressionAttr attr)
Translates the given DWARF expression metadata to to LLVM.
DebugTranslation(Operation *module, llvm::Module &llvmModule)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns an null Attribute if the discardable attribute does n...
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),...
Location getLoc()
The source location the operation was defined or derived from.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static WalkResult interrupt()
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...