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