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;
47 llvm::DEBUG_METADATA_VERSION);
49 const llvm::Triple &targetTriple = llvmModule.getTargetTriple();
50 if (targetTriple.isKnownWindowsMSVCEnvironment()) {
54 llvmModule.addModuleFlag(llvm::Module::Warning,
kCodeViewKey, 1);
60 if (!debugEmissionIsEnabled)
68 llvmFunc.setSubprogram(
translate(spLoc.getMetadata()));
75 llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
85 DebugTranslation::getExpressionAttrOrNull(DIExpressionAttr attr) {
91 llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
92 if (!stringAttr || stringAttr.empty())
102 llvm::map_range(elements, [&](
DINodeAttr attr) -> llvm::Metadata * {
103 if (DIAnnotationAttr annAttr = dyn_cast<DIAnnotationAttr>(attr)) {
104 llvm::Metadata *ops[2] = {
114 llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
116 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
117 attr.getSizeInBits(),
118 0, attr.getEncoding(), llvm::DINode::FlagZero);
121 llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
122 llvm::DIBuilder builder(llvmModule);
123 return builder.createCompileUnit(
124 attr.getSourceLanguage(),
translate(attr.getFile()),
125 attr.getProducer() ? attr.getProducer().getValue() :
"",
126 attr.getIsOptimized(),
128 static_cast<llvm::DICompileUnit::DebugEmissionKind
>(
129 attr.getEmissionKind()),
131 static_cast<llvm::DICompileUnit::DebugNameTableKind
>(
132 attr.getNameTableKind()));
137 template <
class DINodeT,
class... Ts>
140 return DINodeT::getDistinct(std::forward<Ts>(args)...);
144 llvm::TempDICompositeType
145 DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
146 return llvm::DICompositeType::getTemporary(
147 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
nullptr,
148 attr.getLine(),
nullptr,
nullptr, attr.getSizeInBits(),
149 attr.getAlignInBits(),
151 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
152 nullptr, 0, std::nullopt,
156 llvm::TempDISubprogram
157 DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) {
158 return llvm::DISubprogram::getTemporary(
159 llvmCtx,
nullptr, {}, {},
160 nullptr, attr.getLine(),
nullptr,
162 0, llvm::DINode::FlagZero,
163 static_cast<llvm::DISubprogram::DISPFlags
>(attr.getSubprogramFlags()),
167 llvm::DICompositeType *
168 DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
171 bool isDistinct =
false;
172 switch (attr.getTag()) {
173 case llvm::dwarf::DW_TAG_class_type:
174 case llvm::dwarf::DW_TAG_enumeration_type:
175 case llvm::dwarf::DW_TAG_structure_type:
176 case llvm::dwarf::DW_TAG_union_type:
180 return getDistinctOrUnique<llvm::DICompositeType>(
181 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
183 translate(attr.getBaseType()), attr.getSizeInBits(),
184 attr.getAlignInBits(),
186 static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
187 getMDTupleOrNull(attr.getElements()),
188 0, std::nullopt,
nullptr,
191 getExpressionAttrOrNull(attr.getDataLocation()),
192 getExpressionAttrOrNull(attr.getAssociated()),
193 getExpressionAttrOrNull(attr.getAllocated()),
194 getExpressionAttrOrNull(attr.getRank()));
197 llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
199 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
201 nullptr,
translate(attr.getBaseType()), attr.getSizeInBits(),
202 attr.getAlignInBits(), attr.getOffsetInBits(),
203 attr.getDwarfAddressSpace(), std::nullopt,
204 llvm::DINode::FlagZero,
translate(attr.getExtraData()));
207 llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) {
209 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
211 getExpressionAttrOrNull(attr.getStringLengthExp()),
212 getExpressionAttrOrNull(attr.getStringLocationExp()),
213 attr.getSizeInBits(), attr.getAlignInBits(), attr.getEncoding());
216 llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
218 getMDStringOrNull(attr.getDirectory()));
221 llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
223 getMDStringOrNull(attr.getName()),
224 translate(attr.getFile()), attr.getLine());
227 llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
228 return llvm::DILexicalBlock::getDistinct(llvmCtx,
translate(attr.getScope()),
230 attr.getLine(), attr.getColumn());
233 llvm::DILexicalBlockFile *
234 DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
235 return llvm::DILexicalBlockFile::getDistinct(
237 attr.getDiscriminator());
240 llvm::DILocalScope *DebugTranslation::translateImpl(
DILocalScopeAttr attr) {
244 llvm::DIVariable *DebugTranslation::translateImpl(
DIVariableAttr attr) {
248 llvm::DILocalVariable *
249 DebugTranslation::translateImpl(DILocalVariableAttr attr) {
251 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
253 attr.getArg(),
static_cast<llvm::DINode::DIFlags
>(attr.getFlags()),
254 attr.getAlignInBits(),
258 llvm::DIGlobalVariable *
259 DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
260 return llvm::DIGlobalVariable::getDistinct(
261 llvmCtx,
translate(attr.getScope()), getMDStringOrNull(attr.getName()),
262 getMDStringOrNull(attr.getLinkageName()),
translate(attr.getFile()),
263 attr.getLine(),
translate(attr.getType()), attr.getIsLocalToUnit(),
264 attr.getIsDefined(),
nullptr,
nullptr, attr.getAlignInBits(),
nullptr);
268 DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
270 if (
auto *iter = recursiveNodeMap.find(recursiveId);
271 iter != recursiveNodeMap.end()) {
274 assert(!attr.getIsRecSelf() &&
"unbound DI recursive self reference");
276 auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) {
277 recursiveNodeMap.try_emplace(recursiveId, placeholder);
280 llvm::DINode *result =
282 .Case<DICompositeTypeAttr>([&](
auto attr) {
283 auto temporary = translateTemporaryImpl(attr);
284 setRecursivePlaceholder(temporary.get());
287 auto *concrete = translateImpl(attr);
288 temporary->replaceAllUsesWith(concrete);
291 .Case<DISubprogramAttr>([&](
auto attr) {
292 auto temporary = translateTemporaryImpl(attr);
293 setRecursivePlaceholder(temporary.get());
296 auto *concrete = translateImpl(attr);
297 temporary->replaceAllUsesWith(concrete);
301 assert(recursiveNodeMap.back().first == recursiveId &&
302 "internal inconsistency: unexpected recursive translation stack");
303 recursiveNodeMap.pop_back();
308 llvm::DIScope *DebugTranslation::translateImpl(
DIScopeAttr attr) {
312 llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
313 if (
auto iter = distinctAttrToNode.find(attr.getId());
314 iter != distinctAttrToNode.end())
315 return cast<llvm::DISubprogram>(iter->second);
317 llvm::DIScope *scope =
translate(attr.getScope());
318 llvm::DIFile *file =
translate(attr.getFile());
319 llvm::DIType *type =
translate(attr.getType());
320 llvm::DICompileUnit *compileUnit =
translate(attr.getCompileUnit());
324 if (
auto iter = distinctAttrToNode.find(attr.getId());
325 iter != distinctAttrToNode.end())
326 return cast<llvm::DISubprogram>(iter->second);
328 bool isDefinition =
static_cast<bool>(attr.getSubprogramFlags() &
329 LLVM::DISubprogramFlags::Definition);
331 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
332 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
333 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
336 0, llvm::DINode::FlagZero,
337 static_cast<llvm::DISubprogram::DISPFlags
>(attr.getSubprogramFlags()),
338 compileUnit,
nullptr,
nullptr,
339 getMDTupleOrNull(attr.getRetainedNodes()),
nullptr,
340 getMDTupleOrNull(attr.getAnnotations()));
342 distinctAttrToNode.try_emplace(attr.getId(), node);
346 llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
349 getMDStringOrNull(attr.getName()),
350 getMDStringOrNull(attr.getConfigMacros()),
351 getMDStringOrNull(attr.getIncludePath()),
352 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
355 llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
357 getMDStringOrNull(attr.getName()),
358 attr.getExportSymbols());
361 llvm::DIImportedEntity *
362 DebugTranslation::translateImpl(DIImportedEntityAttr attr) {
364 llvmCtx, attr.getTag(),
translate(attr.getScope()),
366 getMDStringOrNull(attr.getName()), getMDTupleOrNull(attr.getElements()));
369 llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
370 auto getMetadataOrNull = [&](
Attribute attr) -> llvm::Metadata * {
374 llvm::Metadata *metadata =
376 .Case([&](IntegerAttr intAttr) {
378 llvm::Type::getInt64Ty(llvmCtx), intAttr.getInt()));
380 .Case([&](LLVM::DIExpressionAttr expr) {
383 .Case([&](LLVM::DILocalVariableAttr local) {
386 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
389 .Default([&](
Attribute attr) {
return nullptr; });
393 getMetadataOrNull(attr.getLowerBound()),
394 getMetadataOrNull(attr.getUpperBound()),
395 getMetadataOrNull(attr.getStride()));
398 llvm::DICommonBlock *DebugTranslation::translateImpl(DICommonBlockAttr attr) {
401 getMDStringOrNull(attr.getName()),
402 translate(attr.getFile()), attr.getLine());
405 llvm::DIGenericSubrange *
406 DebugTranslation::translateImpl(DIGenericSubrangeAttr attr) {
407 auto getMetadataOrNull = [&](
Attribute attr) -> llvm::Metadata * {
411 llvm::Metadata *metadata =
413 .Case([&](LLVM::DIExpressionAttr expr) {
416 .Case([&](LLVM::DILocalVariableAttr local) {
419 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
422 .Default([&](
Attribute attr) {
return nullptr; });
426 getMetadataOrNull(attr.getCount()),
427 getMetadataOrNull(attr.getLowerBound()),
428 getMetadataOrNull(attr.getUpperBound()),
429 getMetadataOrNull(attr.getStride()));
432 llvm::DISubroutineType *
433 DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
439 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
443 llvm::DIType *DebugTranslation::translateImpl(
DITypeAttr attr) {
451 if (llvm::DINode *node = attrToNode.lookup(attr))
454 llvm::DINode *node =
nullptr;
457 if (
auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
458 if (recTypeAttr.getRecId())
459 node = translateRecursive(recTypeAttr);
463 .Case<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
464 DICompositeTypeAttr, DIDerivedTypeAttr, DIFileAttr,
465 DIGenericSubrangeAttr, DIGlobalVariableAttr,
466 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
467 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
468 DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr,
469 DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>(
470 [&](
auto attr) {
return translateImpl(attr); });
472 if (node && !node->isTemporary())
473 attrToNode.insert({attr, node});
482 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
483 llvm::DILocalScope *scope) {
484 if (!debugEmissionIsEnabled)
486 return translateLoc(loc, scope,
nullptr);
490 DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
494 for (
const DIExpressionElemAttr &op : attr.getOperations()) {
495 ops.push_back(op.getOpcode());
496 append_range(ops, op.getArguments());
502 llvm::DIGlobalVariableExpression *
503 DebugTranslation::translateGlobalVariableExpression(
504 LLVM::DIGlobalVariableExpressionAttr attr) {
506 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
510 llvm::DILocation *DebugTranslation::translateLoc(
Location loc,
511 llvm::DILocalScope *scope,
512 llvm::DILocation *inlinedAt) {
514 if (isa<UnknownLoc>(loc))
518 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
519 if (existingIt != locationToLoc.end())
520 return existingIt->second;
522 llvm::DILocation *llvmLoc =
nullptr;
523 if (
auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
525 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
533 callerLoc = inlinedAt;
535 llvmLoc = translateLoc(callLoc.getCallee(),
nullptr, callerLoc);
540 }
else if (
auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
546 scope,
const_cast<llvm::DILocation *
>(inlinedAt));
548 }
else if (
auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
552 if (
auto scopedAttr =
553 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
554 scope = translate(scopedAttr);
557 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
558 for (
Location locIt : locations.drop_front()) {
559 llvmLoc = llvm::DILocation::getMergedLocation(
560 llvmLoc, translateLoc(locIt, scope, inlinedAt));
563 }
else if (
auto nameLoc = dyn_cast<NameLoc>(loc)) {
564 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
566 }
else if (
auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
567 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
569 llvm_unreachable(
"unknown location kind");
572 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
577 llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
578 auto *&file = fileMap[fileName];
583 if (currentWorkingDir.empty())
584 llvm::sys::fs::current_path(currentWorkingDir);
586 StringRef directory = currentWorkingDir;
589 if (llvm::sys::path::is_absolute(fileName)) {
592 auto fileIt = llvm::sys::path::begin(fileName);
593 auto fileE = llvm::sys::path::end(fileName);
594 auto curDirIt = llvm::sys::path::begin(directory);
595 auto curDirE = llvm::sys::path::end(directory);
596 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
597 llvm::sys::path::append(dirBuf, *curDirIt);
598 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
601 directory = StringRef();
603 for (; fileIt != fileE; ++fileIt)
604 llvm::sys::path::append(fileBuf, *fileIt);
static constexpr StringRef kDebugVersionKey
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 constexpr StringRef kCodeViewKey
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 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.
void addModuleFlagsIfNotPresent()
Adds the necessary module flags to the module, if not yet present.
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.
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...