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