MLIR 24.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
141static llvm::DISourceLanguageName getSourceLanguage(DICompileUnitAttr attr) {
142 DISourceLanguageNameAttr sourceLanguage = attr.getSourceLanguage();
143 // A DW_LNAME value selects the versioned source-language representation;
144 // otherwise, the value is an unversioned DW_LANG value.
145 if (sourceLanguage.getName())
146 return llvm::DISourceLanguageName(
147 static_cast<uint16_t>(sourceLanguage.getName()),
148 *sourceLanguage.getVersion(),
149 static_cast<uint16_t>(sourceLanguage.getDialect()));
150 return llvm::DISourceLanguageName(
151 static_cast<uint16_t>(sourceLanguage.getLanguage()),
152 static_cast<uint16_t>(sourceLanguage.getDialect()));
153}
154
155llvm::TempDICompileUnit
156DebugTranslation::translateTemporaryImpl(DICompileUnitAttr attr) {
157 return llvm::DICompileUnit::getTemporary(
158 llvmCtx, getSourceLanguage(attr),
159 /*File=*/nullptr, "", attr.getIsOptimized(),
160 /*Flags=*/"", /*RuntimeVersion=*/0,
161 /*splitDebugFileName=*/"",
162 static_cast<llvm::DICompileUnit::DebugEmissionKind>(
163 attr.getEmissionKind()),
164 /*EnumTypes=*/nullptr, /*RetainedTypes=*/nullptr,
165 /*GlobalVariables=*/nullptr, /*ImportedEntities=*/nullptr,
166 /*Macros=*/nullptr,
167 /*DWOId=*/0, /*SplitDebugInlining=*/true,
168 attr.getIsDebugInfoForProfiling(),
169 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
170 attr.getNameTableKind()),
171 /*RangesBaseAddress=*/false, /*SysRoot=*/"", /*SDK=*/"");
172}
173
174llvm::DICompileUnit *DebugTranslation::translateImpl(DICompileUnitAttr attr) {
175 if (attr.getId())
176 if (auto iter = distinctAttrToNode.find(attr.getId());
177 iter != distinctAttrToNode.end())
178 return cast<llvm::DICompileUnit>(iter->second);
179
180 llvm::DIBuilder builder(llvmModule);
181 llvm::DICompileUnit *cu = builder.createCompileUnit(
182 getSourceLanguage(attr), translate(attr.getFile()),
183 attr.getProducer() ? attr.getProducer().getValue() : "",
184 attr.getIsOptimized(),
185 /*Flags=*/"", /*RV=*/0,
186 attr.getSplitDebugFilename() ? attr.getSplitDebugFilename().getValue()
187 : "",
188 static_cast<llvm::DICompileUnit::DebugEmissionKind>(
189 attr.getEmissionKind()),
190 0, true, attr.getIsDebugInfoForProfiling(),
191 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
192 attr.getNameTableKind()));
193
194 llvm::SmallVector<llvm::Metadata *> importNodes;
195 for (DINodeAttr importNode : attr.getImportedEntities())
196 importNodes.push_back(translate(importNode));
197 if (!importNodes.empty())
198 cu->replaceImportedEntities(llvm::MDTuple::get(llvmCtx, importNodes));
199
200 if (attr.getId())
201 distinctAttrToNode.try_emplace(attr.getId(), cu);
202
203 return cu;
204}
205
206/// Returns a new `DINodeT` that is either distinct or not, depending on
207/// `isDistinct`.
208template <class DINodeT, class... Ts>
209static DINodeT *getDistinctOrUnique(bool isDistinct, Ts &&...args) {
210 if (isDistinct)
211 return DINodeT::getDistinct(std::forward<Ts>(args)...);
212 return DINodeT::get(std::forward<Ts>(args)...);
213}
214
215llvm::TempDICompositeType
216DebugTranslation::translateTemporaryImpl(DICompositeTypeAttr attr) {
217 return llvm::DICompositeType::getTemporary(
218 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()), nullptr,
219 attr.getLine(), nullptr, nullptr, attr.getSizeInBits(),
220 attr.getAlignInBits(),
221 /*OffsetInBits=*/0,
222 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
223 /*Elements=*/nullptr, /*RuntimeLang=*/0, /*EnumKind=*/std::nullopt,
224 /*VTableHolder=*/nullptr);
225}
226
227llvm::TempDISubprogram
228DebugTranslation::translateTemporaryImpl(DISubprogramAttr attr) {
229 return llvm::DISubprogram::getTemporary(
230 llvmCtx, /*Scope=*/nullptr, /*Name=*/{}, /*LinkageName=*/{},
231 /*File=*/nullptr, attr.getLine(), /*Type=*/nullptr,
232 /*ScopeLine=*/0, /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
233 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
234 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
235 /*Unit=*/nullptr);
236}
237
238llvm::DICompositeType *
239DebugTranslation::translateImpl(DICompositeTypeAttr attr) {
240 // TODO: Use distinct attributes to model this, once they have landed.
241 // Depending on the tag, composite types must be distinct.
242 bool isDistinct = false;
243 switch (attr.getTag()) {
244 case llvm::dwarf::DW_TAG_class_type:
245 case llvm::dwarf::DW_TAG_enumeration_type:
246 case llvm::dwarf::DW_TAG_structure_type:
247 case llvm::dwarf::DW_TAG_union_type:
248 case llvm::dwarf::DW_TAG_variant_part:
249 isDistinct = true;
250 }
251
253 isDistinct, llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
254 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
255 translate(attr.getBaseType()), attr.getSizeInBits(),
256 attr.getAlignInBits(),
257 /*OffsetInBits=*/0,
258 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
259 getMDTupleOrNull(attr.getElements()),
260 /*RuntimeLang=*/0, /*EnumKind*/ std::nullopt, /*VTableHolder=*/nullptr,
261 /*TemplateParams=*/nullptr, getMDStringOrNull(attr.getIdentifier()),
262 translate(attr.getDiscriminator()),
263 getExpressionAttrOrNull(attr.getDataLocation()),
264 getExpressionAttrOrNull(attr.getAssociated()),
265 getExpressionAttrOrNull(attr.getAllocated()),
266 getExpressionAttrOrNull(attr.getRank()));
267}
268
269llvm::DIDerivedType *DebugTranslation::translateImpl(DIDerivedTypeAttr attr) {
270 llvm::Metadata *extraData = nullptr;
271 if (Attribute extraDataAttr = attr.getExtraData()) {
272 extraData =
273 llvm::TypeSwitch<Attribute, llvm::Metadata *>(extraDataAttr)
274 .Case([&](DINodeAttr nodeAttr) { return translate(nodeAttr); })
275 .Case([&](IntegerAttr intAttr) {
276 return llvm::ConstantAsMetadata::get(
277 llvm::ConstantInt::get(llvmCtx, intAttr.getValue()));
278 })
279 .Default([](Attribute) -> llvm::Metadata * {
280 llvm_unreachable("verifier guarantees DINodeAttr or IntegerAttr");
281 });
282 }
283
284 return llvm::DIDerivedType::get(
285 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
286 translate(attr.getFile()), attr.getLine(), translate(attr.getScope()),
287 translate(attr.getBaseType()), attr.getSizeInBits(),
288 attr.getAlignInBits(), attr.getOffsetInBits(),
289 attr.getDwarfAddressSpace(), /*PtrAuthData=*/std::nullopt,
290 /*Flags=*/static_cast<llvm::DINode::DIFlags>(attr.getFlags()), extraData);
291}
292
293llvm::DIStringType *DebugTranslation::translateImpl(DIStringTypeAttr attr) {
294 return llvm::DIStringType::get(
295 llvmCtx, attr.getTag(), getMDStringOrNull(attr.getName()),
296 translate(attr.getStringLength()),
297 getExpressionAttrOrNull(attr.getStringLengthExp()),
298 getExpressionAttrOrNull(attr.getStringLocationExp()),
299 attr.getSizeInBits(), attr.getAlignInBits(), attr.getEncoding());
300}
301
302llvm::DIFile *DebugTranslation::translateImpl(DIFileAttr attr) {
303 return llvm::DIFile::get(llvmCtx, getMDStringOrNull(attr.getName()),
304 getMDStringOrNull(attr.getDirectory()));
305}
306
307llvm::DILabel *DebugTranslation::translateImpl(DILabelAttr attr) {
308 return llvm::DILabel::get(llvmCtx, translate(attr.getScope()),
309 getMDStringOrNull(attr.getName()),
310 translate(attr.getFile()), attr.getLine(),
311 /*Column=*/0, /*IsArtificial=*/false,
312 /*CoroSuspendIdx=*/std::nullopt);
313}
314
315llvm::DILexicalBlock *DebugTranslation::translateImpl(DILexicalBlockAttr attr) {
316 return llvm::DILexicalBlock::getDistinct(llvmCtx, translate(attr.getScope()),
317 translate(attr.getFile()),
318 attr.getLine(), attr.getColumn());
319}
320
321llvm::DILexicalBlockFile *
322DebugTranslation::translateImpl(DILexicalBlockFileAttr attr) {
323 return llvm::DILexicalBlockFile::getDistinct(
324 llvmCtx, translate(attr.getScope()), translate(attr.getFile()),
325 attr.getDiscriminator());
326}
327
328llvm::DILocalScope *DebugTranslation::translateImpl(DILocalScopeAttr attr) {
329 return cast<llvm::DILocalScope>(translate(DINodeAttr(attr)));
330}
331
332llvm::DIVariable *DebugTranslation::translateImpl(DIVariableAttr attr) {
333 return cast<llvm::DIVariable>(translate(DINodeAttr(attr)));
334}
335
336llvm::DILocalVariable *
337DebugTranslation::translateImpl(DILocalVariableAttr attr) {
338 return llvm::DILocalVariable::get(
339 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
340 translate(attr.getFile()), attr.getLine(), translate(attr.getType()),
341 attr.getArg(), static_cast<llvm::DINode::DIFlags>(attr.getFlags()),
342 attr.getAlignInBits(),
343 /*Annotations=*/nullptr);
344}
345
346llvm::DIGlobalVariable *
347DebugTranslation::translateImpl(DIGlobalVariableAttr attr) {
348 return llvm::DIGlobalVariable::getDistinct(
349 llvmCtx, translate(attr.getScope()), getMDStringOrNull(attr.getName()),
350 getMDStringOrNull(attr.getLinkageName()), translate(attr.getFile()),
351 attr.getLine(), translate(attr.getType()), attr.getIsLocalToUnit(),
352 attr.getIsDefined(), nullptr, nullptr, attr.getAlignInBits(), nullptr);
353}
354
355llvm::DINode *
356DebugTranslation::translateRecursive(DIRecursiveTypeAttrInterface attr) {
357 DistinctAttr recursiveId = attr.getRecId();
358 if (auto *iter = recursiveNodeMap.find(recursiveId);
359 iter != recursiveNodeMap.end()) {
360 return iter->second;
361 }
362 assert(!attr.getIsRecSelf() && "unbound DI recursive self reference");
363
364 auto setRecursivePlaceholder = [&](llvm::DINode *placeholder) {
365 recursiveNodeMap.try_emplace(recursiveId, placeholder);
366 };
367
368 llvm::DINode *result =
370 .Case([&](DICompositeTypeAttr attr) {
371 auto temporary = translateTemporaryImpl(attr);
372 setRecursivePlaceholder(temporary.get());
373 // Must call `translateImpl` directly instead of `translate` to
374 // avoid handling the recursive interface again.
375 auto *concrete = translateImpl(attr);
376 temporary->replaceAllUsesWith(concrete);
377 return concrete;
378 })
379 .Case([&](DISubprogramAttr attr) {
380 auto temporary = translateTemporaryImpl(attr);
381 setRecursivePlaceholder(temporary.get());
382 // Must call `translateImpl` directly instead of `translate` to
383 // avoid handling the recursive interface again.
384 auto *concrete = translateImpl(attr);
385 temporary->replaceAllUsesWith(concrete);
386 return concrete;
387 })
388 .Case([&](DICompileUnitAttr attr) {
389 auto temporary = translateTemporaryImpl(attr);
390 setRecursivePlaceholder(temporary.get());
391 auto *concrete = translateImpl(attr);
392 temporary->replaceAllUsesWith(concrete);
393 return concrete;
394 });
395
396 assert(recursiveNodeMap.back().first == recursiveId &&
397 "internal inconsistency: unexpected recursive translation stack");
398 recursiveNodeMap.pop_back();
399
400 return result;
401}
402
403llvm::DIScope *DebugTranslation::translateImpl(DIScopeAttr attr) {
404 return cast<llvm::DIScope>(translate(DINodeAttr(attr)));
405}
406
407llvm::DISubprogram *DebugTranslation::translateImpl(DISubprogramAttr attr) {
408 if (auto iter = distinctAttrToNode.find(attr.getId());
409 iter != distinctAttrToNode.end())
410 return cast<llvm::DISubprogram>(iter->second);
411
412 llvm::DIScope *scope = translate(attr.getScope());
413 llvm::DIFile *file = translate(attr.getFile());
414 llvm::DIType *type = translate(attr.getType());
415 llvm::DICompileUnit *compileUnit = translate(attr.getCompileUnit());
416
417 // Check again after recursive calls in case this distinct node recurses back
418 // to itself.
419 if (auto iter = distinctAttrToNode.find(attr.getId());
420 iter != distinctAttrToNode.end())
421 return cast<llvm::DISubprogram>(iter->second);
422
423 bool isDefinition = static_cast<bool>(attr.getSubprogramFlags() &
424 LLVM::DISubprogramFlags::Definition);
425
426 llvm::DISubprogram *node = getDistinctOrUnique<llvm::DISubprogram>(
427 isDefinition, llvmCtx, scope, getMDStringOrNull(attr.getName()),
428 getMDStringOrNull(attr.getLinkageName()), file, attr.getLine(), type,
429 attr.getScopeLine(),
430 /*ContainingType=*/nullptr, /*VirtualIndex=*/0,
431 /*ThisAdjustment=*/0, llvm::DINode::FlagZero,
432 static_cast<llvm::DISubprogram::DISPFlags>(attr.getSubprogramFlags()),
433 compileUnit, /*TemplateParams=*/nullptr, /*Declaration=*/nullptr,
434 getRetainedNodesOrNull(attr.getRetainedNodes()), nullptr,
435 getMDTupleOrNull(attr.getAnnotations()));
436 if (attr.getId())
437 distinctAttrToNode.try_emplace(attr.getId(), node);
438 return node;
439}
440
441llvm::DIModule *DebugTranslation::translateImpl(DIModuleAttr attr) {
442 return llvm::DIModule::get(
443 llvmCtx, translate(attr.getFile()), translate(attr.getScope()),
444 getMDStringOrNull(attr.getName()),
445 getMDStringOrNull(attr.getConfigMacros()),
446 getMDStringOrNull(attr.getIncludePath()),
447 getMDStringOrNull(attr.getApinotes()), attr.getLine(), attr.getIsDecl());
448}
449
450llvm::DINamespace *DebugTranslation::translateImpl(DINamespaceAttr attr) {
451 return llvm::DINamespace::get(llvmCtx, translate(attr.getScope()),
452 getMDStringOrNull(attr.getName()),
453 attr.getExportSymbols());
454}
455
456llvm::DIImportedEntity *
457DebugTranslation::translateImpl(DIImportedEntityAttr attr) {
458 return llvm::DIImportedEntity::get(
459 llvmCtx, attr.getTag(), translate(attr.getScope()),
460 translate(attr.getEntity()), translate(attr.getFile()), attr.getLine(),
461 getMDStringOrNull(attr.getName()), getMDTupleOrNull(attr.getElements()));
462}
463
464llvm::DISubrange *DebugTranslation::translateImpl(DISubrangeAttr attr) {
465 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
466 if (!attr)
467 return nullptr;
468
469 llvm::Metadata *metadata =
470 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
471 .Case([&](IntegerAttr intAttr) {
472 return llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
473 llvm::Type::getInt64Ty(llvmCtx), intAttr.getInt()));
474 })
475 .Case([&](LLVM::DIExpressionAttr expr) {
476 return translateExpression(expr);
477 })
478 .Case([&](LLVM::DILocalVariableAttr local) {
479 return translate(local);
480 })
481 .Case<>([&](LLVM::DIGlobalVariableAttr global) {
482 return translate(global);
483 })
484 .Default(nullptr);
485 return metadata;
486 };
487 return llvm::DISubrange::get(llvmCtx, getMetadataOrNull(attr.getCount()),
488 getMetadataOrNull(attr.getLowerBound()),
489 getMetadataOrNull(attr.getUpperBound()),
490 getMetadataOrNull(attr.getStride()));
491}
492
493llvm::DICommonBlock *DebugTranslation::translateImpl(DICommonBlockAttr attr) {
494 return llvm::DICommonBlock::get(llvmCtx, translate(attr.getScope()),
495 translate(attr.getDecl()),
496 getMDStringOrNull(attr.getName()),
497 translate(attr.getFile()), attr.getLine());
498}
499
500llvm::DIGenericSubrange *
501DebugTranslation::translateImpl(DIGenericSubrangeAttr attr) {
502 auto getMetadataOrNull = [&](Attribute attr) -> llvm::Metadata * {
503 if (!attr)
504 return nullptr;
505
506 llvm::Metadata *metadata =
507 llvm::TypeSwitch<Attribute, llvm::Metadata *>(attr)
508 .Case([&](LLVM::DIExpressionAttr expr) {
509 return translateExpression(expr);
510 })
511 .Case([&](LLVM::DILocalVariableAttr local) {
512 return translate(local);
513 })
514 .Case([&](LLVM::DIGlobalVariableAttr global) {
515 return translate(global);
516 })
517 .Default(nullptr);
518 return metadata;
519 };
520 return llvm::DIGenericSubrange::get(llvmCtx,
521 getMetadataOrNull(attr.getCount()),
522 getMetadataOrNull(attr.getLowerBound()),
523 getMetadataOrNull(attr.getUpperBound()),
524 getMetadataOrNull(attr.getStride()));
525}
526
527llvm::DISubroutineType *
528DebugTranslation::translateImpl(DISubroutineTypeAttr attr) {
529 // Concatenate the result and argument types into a single array.
530 SmallVector<llvm::Metadata *> types;
531 for (DITypeAttr type : attr.getTypes())
532 types.push_back(translate(type));
533 return llvm::DISubroutineType::get(
534 llvmCtx, llvm::DINode::FlagZero, attr.getCallingConvention(),
535 llvm::DITypeArray(llvm::MDNode::get(llvmCtx, types)));
536}
537
538llvm::DIType *DebugTranslation::translateImpl(DITypeAttr attr) {
539 return cast<llvm::DIType>(translate(DINodeAttr(attr)));
540}
541
543 if (!attr)
544 return nullptr;
545 // Check for a cached instance.
546 if (llvm::DINode *node = attrToNode.lookup(attr))
547 return node;
548
549 llvm::DINode *node = nullptr;
550 // Recursive types go through a dedicated handler. All other types are
551 // dispatched directly to their specific handlers.
552 if (auto recTypeAttr = dyn_cast<DIRecursiveTypeAttrInterface>(attr))
553 if (recTypeAttr.getRecId())
554 node = translateRecursive(recTypeAttr);
555
556 if (!node)
558 .Case<DIBasicTypeAttr, DICommonBlockAttr, DICompileUnitAttr,
559 DICompositeTypeAttr, DIDerivedTypeAttr, DIFileAttr,
560 DIGenericSubrangeAttr, DIGlobalVariableAttr,
561 DIImportedEntityAttr, DILabelAttr, DILexicalBlockAttr,
562 DILexicalBlockFileAttr, DILocalVariableAttr, DIModuleAttr,
563 DINamespaceAttr, DINullTypeAttr, DIStringTypeAttr,
564 DISubprogramAttr, DISubrangeAttr, DISubroutineTypeAttr>(
565 [&](auto attr) { return translateImpl(attr); });
566
567 if (node && !node->isTemporary())
568 attrToNode.insert({attr, node});
569 return node;
570}
571
572//===----------------------------------------------------------------------===//
573// Locations
574//===----------------------------------------------------------------------===//
575
576/// Translate the given location to an llvm debug location.
578 llvm::DILocalScope *scope) {
579 if (!debugEmissionIsEnabled)
580 return nullptr;
581 return translateLoc(loc, scope, /*inlinedAt=*/nullptr);
582}
583
584llvm::DIExpression *
585DebugTranslation::translateExpression(LLVM::DIExpressionAttr attr) {
587 if (attr) {
588 // Append operations their operands to the list.
589 for (const DIExpressionElemAttr &op : attr.getOperations()) {
590 ops.push_back(op.getOpcode());
591 append_range(ops, op.getArguments());
592 }
593 }
594 return llvm::DIExpression::get(llvmCtx, ops);
595}
596
597llvm::DIGlobalVariableExpression *
599 LLVM::DIGlobalVariableExpressionAttr attr) {
600 return llvm::DIGlobalVariableExpression::get(
601 llvmCtx, translate(attr.getVar()), translateExpression(attr.getExpr()));
602}
603
604/// Translate the given location to an llvm DebugLoc.
605llvm::DILocation *DebugTranslation::translateLoc(Location loc,
606 llvm::DILocalScope *scope,
607 llvm::DILocation *inlinedAt) {
608 // LLVM doesn't have a representation for unknown.
609 if (isa<UnknownLoc>(loc))
610 return nullptr;
611
612 // Check for a cached instance.
613 auto existingIt = locationToLoc.find(std::make_tuple(loc, scope, inlinedAt));
614 if (existingIt != locationToLoc.end())
615 return existingIt->second;
616
617 llvm::DILocation *llvmLoc = nullptr;
618 if (auto callLoc = dyn_cast<CallSiteLoc>(loc)) {
619 // For callsites, the caller is fed as the inlinedAt for the callee.
620 auto *callerLoc = translateLoc(callLoc.getCaller(), scope, inlinedAt);
621 // If the caller scope is not translatable, the overall callsite cannot be
622 // represented in LLVM (the callee scope may not match the parent function).
623 if (!callerLoc) {
624 // If there is an inlinedAt scope (an outer caller), skip to that
625 // directly. Otherwise, cannot translate.
626 if (!inlinedAt)
627 return nullptr;
628 callerLoc = inlinedAt;
629 }
630 llvmLoc = translateLoc(callLoc.getCallee(), nullptr, callerLoc);
631 // Fallback: Ignore callee if it has no debug scope.
632 if (!llvmLoc)
633 llvmLoc = callerLoc;
634
635 } else if (auto fileLoc = dyn_cast<FileLineColLoc>(loc)) {
636 // A scope of a DILocation cannot be null.
637 if (!scope)
638 return nullptr;
639 llvmLoc =
640 llvm::DILocation::get(llvmCtx, fileLoc.getLine(), fileLoc.getColumn(),
641 scope, const_cast<llvm::DILocation *>(inlinedAt));
642
643 } else if (auto fusedLoc = dyn_cast<FusedLoc>(loc)) {
644 ArrayRef<Location> locations = fusedLoc.getLocations();
645
646 // Check for a scope encoded with the location.
647 if (auto scopedAttr =
648 dyn_cast_or_null<LLVM::DILocalScopeAttr>(fusedLoc.getMetadata()))
649 scope = translate(scopedAttr);
650
651 // For fused locations, merge each of the nodes.
652 llvmLoc = translateLoc(locations.front(), scope, inlinedAt);
653 for (Location locIt : locations.drop_front()) {
654 llvmLoc = llvm::DILocation::getMergedLocation(
655 llvmLoc, translateLoc(locIt, scope, inlinedAt));
656 }
657
658 } else if (auto nameLoc = dyn_cast<NameLoc>(loc)) {
659 llvmLoc = translateLoc(nameLoc.getChildLoc(), scope, inlinedAt);
660
661 } else if (auto opaqueLoc = dyn_cast<OpaqueLoc>(loc)) {
662 llvmLoc = translateLoc(opaqueLoc.getFallbackLocation(), scope, inlinedAt);
663 } else {
664 llvm_unreachable("unknown location kind");
665 }
666
667 locationToLoc.try_emplace(std::make_tuple(loc, scope, inlinedAt), llvmLoc);
668 return llvmLoc;
669}
670
671/// Create an llvm debug file for the given file path.
672llvm::DIFile *DebugTranslation::translateFile(StringRef fileName) {
673 auto *&file = fileMap[fileName];
674 if (file)
675 return file;
676
677 // Make sure the current working directory is up-to-date.
678 if (currentWorkingDir.empty())
679 llvm::sys::fs::current_path(currentWorkingDir);
680
681 StringRef directory = currentWorkingDir;
682 SmallString<128> dirBuf;
683 SmallString<128> fileBuf;
684 if (llvm::sys::path::is_absolute(fileName)) {
685 // Strip the common prefix (if it is more than just "/") from current
686 // directory and FileName for a more space-efficient encoding.
687 auto fileIt = llvm::sys::path::begin(fileName);
688 auto fileE = llvm::sys::path::end(fileName);
689 auto curDirIt = llvm::sys::path::begin(directory);
690 auto curDirE = llvm::sys::path::end(directory);
691 for (; curDirIt != curDirE && *curDirIt == *fileIt; ++curDirIt, ++fileIt)
692 llvm::sys::path::append(dirBuf, *curDirIt);
693 if (std::distance(llvm::sys::path::begin(directory), curDirIt) == 1) {
694 // Don't strip the common prefix if it is only the root "/" since that
695 // would make LLVM diagnostic locations confusing.
696 directory = StringRef();
697 } else {
698 for (; fileIt != fileE; ++fileIt)
699 llvm::sys::path::append(fileBuf, *fileIt);
700 directory = dirBuf;
701 fileName = fileBuf;
702 }
703 }
704 return (file = llvm::DIFile::get(llvmCtx, fileName, directory));
705}
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.
static llvm::DISourceLanguageName getSourceLanguage(DICompileUnitAttr attr)
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:849
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