MLIR 23.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/SmallVectorExtras.h"
12#include "llvm/ADT/TypeSwitch.h"
13#include "llvm/IR/Constants.h"
14#include "llvm/IR/Metadata.h"
15#include "llvm/IR/Module.h"
16#include "llvm/Support/ErrorHandling.h"
17#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/Path.h"
19
20using namespace mlir;
21using namespace mlir::LLVM;
22using namespace mlir::LLVM::detail;
23
24/// A utility walker that interrupts if the operation has valid debug
25/// information.
27 return isa<UnknownLoc>(op->getLoc()) ? WalkResult::advance()
29}
30
31DebugTranslation::DebugTranslation(Operation *module, llvm::Module &llvmModule)
32 : debugEmissionIsEnabled(false), llvmModule(llvmModule),
33 llvmCtx(llvmModule.getContext()) {
34 // If the module has no location information, there is nothing to do.
35 if (!module->walk(interruptIfValidLocation).wasInterrupted())
36 return;
37 debugEmissionIsEnabled = true;
38}
39
40static constexpr StringRef kDebugVersionKey = "Debug Info Version";
41static constexpr StringRef kCodeViewKey = "CodeView";
42
44 // TODO: The version information should be encoded on the LLVM module itself,
45 // not implicitly set here.
46
47 // Mark this module as having debug information.
48 if (!llvmModule.getModuleFlag(kDebugVersionKey))
49 llvmModule.addModuleFlag(llvm::Module::Warning, kDebugVersionKey,
50 llvm::DEBUG_METADATA_VERSION);
51
52 const llvm::Triple &targetTriple = llvmModule.getTargetTriple();
53 if (targetTriple.isKnownWindowsMSVCEnvironment()) {
54 // Dwarf debugging files will be generated by default, unless "CodeView"
55 // is set explicitly. Windows/MSVC should use CodeView instead.
56 if (!llvmModule.getModuleFlag(kCodeViewKey))
57 llvmModule.addModuleFlag(llvm::Module::Warning, kCodeViewKey, 1);
58 }
59}
60
61/// Translate the debug information for the given function.
62void DebugTranslation::translate(LLVMFuncOp func, llvm::Function &llvmFunc) {
63 if (!debugEmissionIsEnabled)
64 return;
65
66 // Look for a sub program attached to the function.
67 auto spLoc =
68 func.getLoc()->findInstanceOf<FusedLocWith<LLVM::DISubprogramAttr>>();
69 if (!spLoc)
70 return;
71 llvmFunc.setSubprogram(translate(spLoc.getMetadata()));
72}
73
74//===----------------------------------------------------------------------===//
75// Attributes
76//===----------------------------------------------------------------------===//
77
78llvm::DIType *DebugTranslation::translateImpl(DINullTypeAttr attr) {
79 // A DINullTypeAttr at the beginning of the subroutine types list models
80 // a void result type. If it is at the end, it models a variadic function.
81 // Translate the explicit DINullTypeAttr to a nullptr since LLVM IR metadata
82 // does not have an explicit void result type nor a variadic type
83 // representation.
84 return nullptr;
85}
86
87llvm::DIExpression *
88DebugTranslation::getExpressionAttrOrNull(DIExpressionAttr attr) {
89 if (!attr)
90 return nullptr;
91 return translateExpression(attr);
92}
93
94llvm::MDString *DebugTranslation::getMDStringOrNull(StringAttr stringAttr) {
95 if (!stringAttr || stringAttr.empty())
96 return nullptr;
97 return llvm::MDString::get(llvmCtx, stringAttr);
98}
99
100llvm::MDTuple *
101DebugTranslation::getMDTupleOrNull(ArrayRef<DINodeAttr> elements) {
102 if (elements.empty())
103 return nullptr;
104 SmallVector<llvm::Metadata *> llvmElements =
105 llvm::map_to_vector(elements, [&](DINodeAttr attr) -> llvm::Metadata * {
106 if (DIAnnotationAttr annAttr = dyn_cast<DIAnnotationAttr>(attr)) {
107 llvm::Metadata *ops[2] = {
108 llvm::MDString::get(llvmCtx, annAttr.getName()),
109 llvm::MDString::get(llvmCtx, annAttr.getValue())};
110 return llvm::MDNode::get(llvmCtx, ops);
111 }
112 return translate(attr);
113 });
114 return llvm::MDNode::get(llvmCtx, llvmElements);
115}
116
117llvm::MDTuple *
118DebugTranslation::getRetainedNodesOrNull(ArrayRef<Attribute> retainedNodes) {
119 if (retainedNodes.empty())
120 return nullptr;
121 SmallVector<llvm::Metadata *> llvmElements = llvm::map_to_vector(
122 retainedNodes, [&](Attribute attr) -> llvm::Metadata * {
123 if (auto GVE = dyn_cast<DIGlobalVariableExpressionAttr>(attr))
125
126 auto diAttr = dyn_cast<DINodeAttr>(attr);
127 if (!diAttr)
128 llvm_unreachable("unknown retained node kind");
129 return translate(diAttr);
130 });
131 return llvm::MDNode::get(llvmCtx, llvmElements);
132}
133
134llvm::DIBasicType *DebugTranslation::translateImpl(DIBasicTypeAttr attr) {
135 return llvm::DIBasicType::get(
136 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
137 attr.getSizeInBits(),
138 /*AlignInBits=*/0, attr.getEncoding(), llvm::DINode::FlagZero);
139}
140
141llvm::TempDICompileUnit
142DebugTranslation::translateTemporaryImpl(DICompileUnitAttr attr) {
143 return llvm::DICompileUnit::getTemporary(
144 llvmCtx,
145 static_cast<llvm::DISourceLanguageName>(attr.getSourceLanguage()),
146 /*File=*/nullptr, "", attr.getIsOptimized(),
147 /*Flags=*/"", /*RuntimeVersion=*/0,
148 /*splitDebugFileName=*/"",
149 static_cast<llvm::DICompileUnit::DebugEmissionKind>(
150 attr.getEmissionKind()),
151 /*EnumTypes=*/nullptr, /*RetainedTypes=*/nullptr,
152 /*GlobalVariables=*/nullptr, /*ImportedEntities=*/nullptr,
153 /*Macros=*/nullptr,
154 /*DWOId=*/0, /*SplitDebugInlining=*/true,
155 attr.getIsDebugInfoForProfiling(),
156 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
157 attr.getNameTableKind()),
158 /*RangesBaseAddress=*/false, /*SysRoot=*/"", /*SDK=*/"");
159}
160
161llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
162 if (attr.getId())
163 if (auto iter = distinctAttrToNode.find(attr.getId());
164 iter != distinctAttrToNode.end())
165 return cast<llvm::DICompileUnit>(iter->second);
166
167 llvm::DIBuilder builder(llvmModule);
168 llvm::DICompileUnit *cu = builder.createCompileUnit(
169 attr.getSourceLanguage(), translate(attr.getFile()),
170 attr.getProducer() ? attr.getProducer().getValue() : "",
171 attr.getIsOptimized(),
172 /*Flags=*/"", /*RV=*/0,
173 attr.getSplitDebugFilename() ? attr.getSplitDebugFilename().getValue()
174 : "",
175 static_cast<llvm::DICompileUnit::DebugEmissionKind>(
176 attr.getEmissionKind()),
177 0, true, attr.getIsDebugInfoForProfiling(),
178 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
179 attr.getNameTableKind()));
180
181 llvm::SmallVector<llvm::Metadata *> importNodes;
182 for (DINodeAttr importNode : attr.getImportedEntities())
183 importNodes.push_back(translate(importNode));
184 if (!importNodes.empty())
185 cu->replaceImportedEntities(llvm::MDTuple::get(llvmCtx, importNodes));
186
187 if (attr.getId())
188 distinctAttrToNode.try_emplace(attr.getId(), cu);
189
190 return cu;
191}
192
193/// Returns a new `DINodeT` that is either distinct or not, depending on
194/// `isDistinct`.
195template <class DINodeT, class... Ts>
196static DINodeT *getDistinctOrUnique(bool isDistinct, Ts &&...args) {
197 if (isDistinct)
198 return DINodeT::getDistinct(std::forward<Ts>(args)...);
199 return DINodeT::get(std::forward<Ts>(args)...);
200}
201
202llvm::TempDICompositeType
203DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
204 return llvm::DICompositeType::getTemporary(
205 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()), nullptr,
206 attr.getLine(), nullptr, nullptr, attr.getSizeInBits(),
207 attr.getAlignInBits(),
208 /*OffsetInBits=*/0,
209 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
210 /*Elements=*/nullptr, /*RuntimeLang=*/0, /*EnumKind=*/std::nullopt,
211 /*VTableHolder=*/nullptr);
212}
213
214llvm::TempDISubprogram
215DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) {
216 return llvm::DISubprogram::getTemporary(
217 llvmCtx, /*Scope=*/nullptr, /*Name=*/{}, /*LinkageName=*/{},
218 /*File=*/nullptr, attr.getLine(), /*Type=*/nullptr,
219 /*ScopeLine=*/0, /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
220 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
221 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
222 /*Unit=*/nullptr);
223}
224
225llvm::DICompositeType *
226DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
227 // TODO: Use distinct attributes to model this, once they have landed.
228 // Depending on the tag, composite types must be distinct.
229 bool isDistinct = false;
230 switch (attr.getTag()) {
231 case llvm::dwarf::DW_TAG_class_type:
232 case llvm::dwarf::DW_TAG_enumeration_type:
233 case llvm::dwarf::DW_TAG_structure_type:
234 case llvm::dwarf::DW_TAG_union_type:
235 isDistinct = true;
236 }
237
239 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
240 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
241 translate(attr.getBaseType()), attr.getSizeInBits(),
242 attr.getAlignInBits(),
243 /*OffsetInBits=*/0,
244 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
245 getMDTupleOrNull(attr.getElements()),
246 /*RuntimeLang=*/0, /*EnumKind*/ std::nullopt, /*VTableHolder=*/nullptr,
247 /*TemplateParams=*/nullptr, getMDStringOrNull(attr.getIdentifier()),
248 translate(attr.getDiscriminator()),
249 getExpressionAttrOrNull(attr.getDataLocation()),
250 getExpressionAttrOrNull(attr.getAssociated()),
251 getExpressionAttrOrNull(attr.getAllocated()),
252 getExpressionAttrOrNull(attr.getRank()));
253}
254
255llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
256 llvm::Metadata *extraData = nullptr;
257 if (Attribute extraDataAttr = attr.getExtraData()) {
258 extraData =
259 llvm::TypeSwitch<Attribute, llvm::Metadata *>(extraDataAttr)
260 .Case([&](DINodeAttr nodeAttr) { return translate(nodeAttr); })
261 .Case([&](IntegerAttr intAttr) {
262 return llvm::ConstantAsMetadata::get(
263 llvm::ConstantInt::get(llvmCtx, intAttr.getValue()));
264 })
265 .Default([](Attribute) -> llvm::Metadata * {
266 llvm_unreachable("verifier guarantees DINodeAttr or IntegerAttr");
267 });
268 }
269
270 return llvm::DIDerivedType::get(
271 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
272 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
273 translate(attr.getBaseType()), attr.getSizeInBits(),
274 attr.getAlignInBits(), attr.getOffsetInBits(),
275 attr.getDwarfAddressSpace(), /*PtrAuthData=*/std::nullopt,
276 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()), extraData);
277}
278
279llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) {
280 return llvm::DIStringType::get(
281 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
282 translate(attr.getStringLength()),
283 getExpressionAttrOrNull(attr.getStringLengthExp()),
284 getExpressionAttrOrNull(attr.getStringLocationExp()),
285 attr.getSizeInBits(), attr.getAlignInBits(), attr.getEncoding());
286}
287
288llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
289 return llvm::DIFile::get(llvmCtx, getMDStringOrNull(attr.getName()),
290 getMDStringOrNull(attr.getDirectory()));
291}
292
293llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
294 return llvm::DILabel::get(llvmCtx, translate(attr.getScope()),
295 getMDStringOrNull(attr.getName()),
296 translate(attr.getFile()), attr.getLine(),
297 /*Column=*/0, /*IsArtificial=*/false,
298 /*CoroSuspendIdx=*/std::nullopt);
299}
300
301llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
302 return llvm::DILexicalBlock::getDistinct(llvmCtx, translate(attr.getScope()),
303 translate(attr.getFile()),
304 attr.getLine(), attr.getColumn());
305}
306
307llvm::DILexicalBlockFile *
308DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
309 return llvm::DILexicalBlockFile::getDistinct(
310 llvmCtx, translate(attr.getScope()), translate(attr.getFile()),
311 attr.getDiscriminator());
312}
313
314llvm::DILocalScope *DebugTranslation::translateImpl(DILocalScopeAttr attr) {
315 return cast<llvm::DILocalScope>(translate(DINodeAttr(attr)));
316}
317
318llvm::DIVariable *DebugTranslation::translateImpl(DIVariableAttr attr) {
319 return cast<llvm::DIVariable>(translate(DINodeAttr(attr)));
320}
321
322llvm::DILocalVariable *
323DebugTranslation::translateImpl(DILocalVariableAttr attr) {
324 return llvm::DILocalVariable::get(
325 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
326 translate(attr.getFile()), attr.getLine(), translate(attr.getType()),
327 attr.getArg(), static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
328 attr.getAlignInBits(),
329 /*Annotations=*/nullptr);
330}
331
332llvm::DIGlobalVariable *
333DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
334 return llvm::DIGlobalVariable::getDistinct(
335 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
336 getMDStringOrNull(attr.getLinkageName()), translate(attr.getFile()),
337 attr.getLine(), translate(attr.getType()), attr.getIsLocalToUnit(),
338 attr.getIsDefined(), nullptr, nullptr, attr.getAlignInBits(), nullptr);
339}
340
341llvm::DINode *
342DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
343 DistinctAttr recursiveId = attr.getRecId();
344 if (auto *iter = recursiveNodeMap.find(recursiveId);
345 iter != recursiveNodeMap.end()) {
346 return iter->second;
347 }
348 assert(!attr.getIsRecSelf() && "unbound DI recursive self reference");
349
350 auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) {
351 recursiveNodeMap.try_emplace(recursiveId, placeholder);
352 };
353
354 llvm::DINode *result =
356 .Case([&](DICompositeTypeAttr attr) {
357 auto temporary = translateTemporaryImpl(attr);
358 setRecursivePlaceholder(temporary.get());
359 // Must call `translateImpl` directly instead of `translate` to
360 // avoid handling the recursive interface again.
361 auto *concrete = translateImpl(attr);
362 temporary->replaceAllUsesWith(concrete);
363 return concrete;
364 })
365 .Case([&](DISubprogramAttr attr) {
366 auto temporary = translateTemporaryImpl(attr);
367 setRecursivePlaceholder(temporary.get());
368 // Must call `translateImpl` directly instead of `translate` to
369 // avoid handling the recursive interface again.
370 auto *concrete = translateImpl(attr);
371 temporary->replaceAllUsesWith(concrete);
372 return concrete;
373 })
374 .Case([&](DICompileUnitAttr attr) {
375 auto temporary = translateTemporaryImpl(attr);
376 setRecursivePlaceholder(temporary.get());
377 auto *concrete = translateImpl(attr);
378 temporary->replaceAllUsesWith(concrete);
379 return concrete;
380 });
381
382 assert(recursiveNodeMap.back().first == recursiveId &&
383 "internal inconsistency: unexpected recursive translation stack");
384 recursiveNodeMap.pop_back();
385
386 return result;
387}
388
389llvm::DIScope *DebugTranslation::translateImpl(DIScopeAttr attr) {
390 return cast<llvm::DIScope>(translate(DINodeAttr(attr)));
391}
392
393llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
394 if (auto iter = distinctAttrToNode.find(attr.getId());
395 iter != distinctAttrToNode.end())
396 return cast<llvm::DISubprogram>(iter->second);
397
398 llvm::DIScope *scope = translate(attr.getScope());
399 llvm::DIFile *file = translate(attr.getFile());
400 llvm::DIType *type = translate(attr.getType());
401 llvm::DICompileUnit *compileUnit = translate(attr.getCompileUnit());
402
403 // Check again after recursive calls in case this distinct node recurses back
404 // to itself.
405 if (auto iter = distinctAttrToNode.find(attr.getId());
406 iter != distinctAttrToNode.end())
407 return cast<llvm::DISubprogram>(iter->second);
408
409 bool isDefinition = static_cast<bool>(attr.getSubprogramFlags() &
410 LLVM::DISubprogramFlags::Definition);
411
412 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
413 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
414 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
415 attr.getScopeLine(),
416 /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
417 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
418 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
419 compileUnit, /*TemplateParams=*/nullptr, /*Declaration=*/nullptr,
420 getRetainedNodesOrNull(attr.getRetainedNodes()), nullptr,
421 getMDTupleOrNull(attr.getAnnotations()));
422 if (attr.getId())
423 distinctAttrToNode.try_emplace(attr.getId(), node);
424 return node;
425}
426
427llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
428 return llvm::DIModule::get(
429 llvmCtx, translate(attr.getFile()), translate(attr.getScope()),
430 getMDStringOrNull(attr.getName()),
431 getMDStringOrNull(attr.getConfigMacros()),
432 getMDStringOrNull(attr.getIncludePath()),
433 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
434}
435
436llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
437 return llvm::DINamespace::get(llvmCtx, translate(attr.getScope()),
438 getMDStringOrNull(attr.getName()),
439 attr.getExportSymbols());
440}
441
442llvm::DIImportedEntity *
443DebugTranslation::translateImpl(DIImportedEntityAttr attr) {
444 return llvm::DIImportedEntity::get(
445 llvmCtx, attr.getTag(), translate(attr.getScope()),
446 translate(attr.getEntity()), translate(attr.getFile()), attr.getLine(),
447 getMDStringOrNull(attr.getName()), getMDTupleOrNull(attr.getElements()));
448}
449
450llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
451 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
452 if (!attr)
453 return nullptr;
454
455 llvm::Metadata *metadata =
456 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
457 .Case([&](IntegerAttr intAttr) {
458 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
459 llvm::Type::getInt64Ty(llvmCtx), intAttr.getInt()));
460 })
461 .Case([&](LLVM::DIExpressionAttr expr) {
462 return translateExpression(expr);
463 })
464 .Case([&](LLVM::DILocalVariableAttr local) {
465 return translate(local);
466 })
467 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
468 return translate(global);
469 })
470 .Default(nullptr);
471 return metadata;
472 };
473 return llvm::DISubrange::get(llvmCtx, getMetadataOrNull(attr.getCount()),
474 getMetadataOrNull(attr.getLowerBound()),
475 getMetadataOrNull(attr.getUpperBound()),
476 getMetadataOrNull(attr.getStride()));
477}
478
479llvm::DICommonBlock *DebugTranslation::translateImpl(DICommonBlockAttr attr) {
480 return llvm::DICommonBlock::get(llvmCtx, translate(attr.getScope()),
481 translate(attr.getDecl()),
482 getMDStringOrNull(attr.getName()),
483 translate(attr.getFile()), attr.getLine());
484}
485
486llvm::DIGenericSubrange *
487DebugTranslation::translateImpl(DIGenericSubrangeAttr attr) {
488 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
489 if (!attr)
490 return nullptr;
491
492 llvm::Metadata *metadata =
493 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
494 .Case([&](LLVM::DIExpressionAttr expr) {
495 return translateExpression(expr);
496 })
497 .Case([&](LLVM::DILocalVariableAttr local) {
498 return translate(local);
499 })
500 .Case([&](LLVM::DIGlobalVariableAttr global) {
501 return translate(global);
502 })
503 .Default(nullptr);
504 return metadata;
505 };
506 return llvm::DIGenericSubrange::get(llvmCtx,
507 getMetadataOrNull(attr.getCount()),
508 getMetadataOrNull(attr.getLowerBound()),
509 getMetadataOrNull(attr.getUpperBound()),
510 getMetadataOrNull(attr.getStride()));
511}
512
513llvm::DISubroutineType *
514DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
515 // Concatenate the result and argument types into a single array.
516 SmallVector<llvm::Metadata *> types;
517 for (DITypeAttr type : attr.getTypes())
518 types.push_back(translate(type));
519 return llvm::DISubroutineType::get(
520 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
521 llvm::DITypeArray(llvm::MDNode::get(llvmCtx, types)));
522}
523
524llvm::DIType *DebugTranslation::translateImpl(DITypeAttr attr) {
525 return cast<llvm::DIType>(translate(DINodeAttr(attr)));
526}
527
529 if (!attr)
530 return nullptr;
531 // Check for a cached instance.
532 if (llvm::DINode *node = attrToNode.lookup(attr))
533 return node;
534
535 llvm::DINode *node = nullptr;
536 // Recursive types go through a dedicated handler. All other types are
537 // dispatched directly to their specific handlers.
538 if (auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
539 if (recTypeAttr.getRecId())
540 node = translateRecursive(recTypeAttr);
541
542 if (!node)
544 .Case<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
545 DICompositeTypeAttr, DIDerivedTypeAttr, DIFileAttr,
546 DIGenericSubrangeAttr, DIGlobalVariableAttr,
547 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
548 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
549 DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr,
550 DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>(
551 [&](auto attr) { return translateImpl(attr); });
552
553 if (node && !node->isTemporary())
554 attrToNode.insert({attr, node});
555 return node;
556}
557
558//===----------------------------------------------------------------------===//
559// Locations
560//===----------------------------------------------------------------------===//
561
562/// Translate the given location to an llvm debug location.
564 llvm::DILocalScope *scope) {
565 if (!debugEmissionIsEnabled)
566 return nullptr;
567 return translateLoc(loc, scope, /*inlinedAt=*/nullptr);
568}
569
570llvm::DIExpression *
571DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
573 if (attr) {
574 // Append operations their operands to the list.
575 for (const DIExpressionElemAttr &op : attr.getOperations()) {
576 ops.push_back(op.getOpcode());
577 append_range(ops, op.getArguments());
578 }
579 }
580 return llvm::DIExpression::get(llvmCtx, ops);
581}
582
583llvm::DIGlobalVariableExpression *
585 LLVM::DIGlobalVariableExpressionAttr attr) {
586 return llvm::DIGlobalVariableExpression::get(
587 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
588}
589
590/// Translate the given location to an llvm DebugLoc.
591llvm::DILocation *DebugTranslation::translateLoc(Location loc,
592 llvm::DILocalScope *scope,
593 llvm::DILocation *inlinedAt) {
594 // LLVM doesn't have a representation for unknown.
595 if (isa<UnknownLoc>(loc))
596 return nullptr;
597
598 // Check for a cached instance.
599 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
600 if (existingIt != locationToLoc.end())
601 return existingIt->second;
602
603 llvm::DILocation *llvmLoc = nullptr;
604 if (auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
605 // For callsites, the caller is fed as the inlinedAt for the callee.
606 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
607 // If the caller scope is not translatable, the overall callsite cannot be
608 // represented in LLVM (the callee scope may not match the parent function).
609 if (!callerLoc) {
610 // If there is an inlinedAt scope (an outer caller), skip to that
611 // directly. Otherwise, cannot translate.
612 if (!inlinedAt)
613 return nullptr;
614 callerLoc = inlinedAt;
615 }
616 llvmLoc = translateLoc(callLoc.getCallee(), nullptr, callerLoc);
617 // Fallback: Ignore callee if it has no debug scope.
618 if (!llvmLoc)
619 llvmLoc = callerLoc;
620
621 } else if (auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
622 // A scope of a DILocation cannot be null.
623 if (!scope)
624 return nullptr;
625 llvmLoc =
626 llvm::DILocation::get(llvmCtx, fileLoc.getLine(), fileLoc.getColumn(),
627 scope, const_cast<llvm::DILocation *>(inlinedAt));
628
629 } else if (auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
630 ArrayRef<Location> locations = fusedLoc.getLocations();
631
632 // Check for a scope encoded with the location.
633 if (auto scopedAttr =
634 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
635 scope = translate(scopedAttr);
636
637 // For fused locations, merge each of the nodes.
638 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
639 for (Location locIt : locations.drop_front()) {
640 llvmLoc = llvm::DILocation::getMergedLocation(
641 llvmLoc, translateLoc(locIt, scope, inlinedAt));
642 }
643
644 } else if (auto nameLoc = dyn_cast<NameLoc>(loc)) {
645 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
646
647 } else if (auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
648 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
649 } else {
650 llvm_unreachable("unknown location kind");
651 }
652
653 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
654 return llvmLoc;
655}
656
657/// Create an llvm debug file for the given file path.
658llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
659 auto *&file = fileMap[fileName];
660 if (file)
661 return file;
662
663 // Make sure the current working directory is up-to-date.
664 if (currentWorkingDir.empty())
665 llvm::sys::fs::current_path(currentWorkingDir);
666
667 StringRef directory = currentWorkingDir;
668 SmallString<128> dirBuf;
669 SmallString<128> fileBuf;
670 if (llvm::sys::path::is_absolute(fileName)) {
671 // Strip the common prefix (if it is more than just "/") from current
672 // directory and FileName for a more space-efficient encoding.
673 auto fileIt = llvm::sys::path::begin(fileName);
674 auto fileE = llvm::sys::path::end(fileName);
675 auto curDirIt = llvm::sys::path::begin(directory);
676 auto curDirE = llvm::sys::path::end(directory);
677 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
678 llvm::sys::path::append(dirBuf, *curDirIt);
679 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
680 // Don't strip the common prefix if it is only the root "/" since that
681 // would make LLVM diagnostic locations confusing.
682 directory = StringRef();
683 } else {
684 for (; fileIt != fileE; ++fileIt)
685 llvm::sys::path::append(fileBuf, *fileIt);
686 directory = dirBuf;
687 fileName = fileBuf;
688 }
689 }
690 return (file = llvm::DIFile::get(llvmCtx, fileName, directory));
691}
static constexpr StringRef kDebugVersionKey
static WalkResult interruptIfValidLocation(Operation *op)
A utility walker that interrupts if the operation has valid debug information.
static constexpr StringRef kCodeViewKey
static DINodeT * getDistinctOrUnique(bool isDistinct, Ts &&...args)
Returns a new DINodeT that is either distinct or not, depending on isDistinct.
b getContext())
false
Parses a map_entries map type from a string format back into its numeric value.
This class represents a fused location whose metadata is known to be an instance of the given type.
Definition Location.h:149
This class represents the base attribute for all debug info attributes.
Definition LLVMAttrs.h:29
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)
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translate the given location to an llvm debug location.
llvm::DIGlobalVariableExpression * translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr)
Translates the given DWARF global variable expression to LLVM.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
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:822
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
Include the generated interface declarations.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:139