LLVM 24.0.0git
LVIRReader.cpp
Go to the documentation of this file.
1//===-- LVIRReader.cpp ----------------------------------------------------===//
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// This implements the LVIRReader class.
10// It supports LLVM textual and bitcode IR format.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ScopeExit.h"
24#include "llvm/IR/Module.h"
30
31using namespace llvm;
32using namespace llvm::object;
33using namespace llvm::logicalview;
34
35#define DEBUG_TYPE "IRReader"
36
37namespace {
38
39// Abstract scopes mapped to the associated inlined scopes.
40// When creating inlined scopes, there is no direct information to find
41// the correct lexical scope.
42using LVScopeEntry = std::pair<const DILocalScope *, const DILocation *>;
43using LVInlinedScopes =
44 std::unordered_map<LVScopeEntry, LVScope *,
46LVInlinedScopes InlinedScopes;
47
48void addInlinedScope(const DILocalScope *OriginContext,
49 const DILocation *InlinedAt, LVScope *InlinedScope) {
50 auto Entry = LVScopeEntry(OriginContext, InlinedAt);
51 InlinedScopes.try_emplace(Entry, InlinedScope);
52}
53LVScope *getInlinedScope(const DILocalScope *OriginContext,
54 const DILocation *InlinedAt) {
55 auto Entry = LVScopeEntry(OriginContext, InlinedAt);
56 LVInlinedScopes::const_iterator Iter = InlinedScopes.find(Entry);
57 return Iter != InlinedScopes.end() ? Iter->second : nullptr;
58}
59
60// Used to find the correct location for the inlined lexical blocks that
61// are allocated at their enclosing function level.
62// Keep a link between the inlined scope and its associated origin scope.
63using LVInlinedToOrigin = std::unordered_map<LVScope *, LVScope *>;
64LVInlinedToOrigin InlinedToOrigin;
65
66// Keep a list of inlined scopes created from the same origin scope.
67// The original scope can be inlined multiple times.
69using LVInlinedList = std::unordered_map<LVScope *, LVList>;
70LVInlinedList InlinedList;
71
72void addInlinedInfo(LVScope *Origin, LVScope *Inlined) {
73 // Add the link between the inlined and the origin scopes.
74 InlinedToOrigin.try_emplace(Inlined, Origin);
75
76 // For the given origin scope, add the inlined scope to its inlined list.
77 auto [It, _] = InlinedList.try_emplace(Origin, LVList{});
78 LVList &List = It->second;
79 List.push_back(Inlined);
80}
81
82LVList &getInlinedList(LVScope *Origin) {
83 static LVList EmptyList;
84 auto It = InlinedList.find(Origin);
85 return (It == InlinedList.end()) ? EmptyList : It->second;
86}
87
88#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
89void dumpInlinedInfo(const char *Text, bool Full = false) {
90 // Use 17 as the field length; it corresponds to '{InlinedFunction}'
91 constexpr unsigned LEN = 17;
92
93 auto PrintEntry = [&](auto Text, LVScope *Scope) {
94 std::stringstream SS;
95 SS << Text << hexSquareString(Scope->getID())
96 << hexSquareString(Scope->getParentScope()->getID()) << " "
97 << std::setw(LEN) << std::left << formattedKind(Scope->kind());
98 dbgs() << SS.str();
99 };
100 auto PrintExtra = [&](auto Text, LVScope *Scope) {
101 dbgs() << Text;
102 Scope->dumpCommon();
103 };
104
105 // For each origin scope prints its associated inlined scopes.
106 dbgs() << "\nOrigin -> Inlined list: " << Text << "\n\n";
107 for (auto &Entry : InlinedList) {
108 LVScope *OriginScope = Entry.first;
109 LVList &List = Entry.second;
110 PrintEntry("", OriginScope);
111 dbgs() << "\n";
112 unsigned Count = 0;
113 for (auto &Scope : List) {
114 dbgs() << decString(++Count, /*Width=*/2);
115 PrintEntry(" ", Scope);
116 dbgs() << "\n";
117 }
118 }
119
120 dbgs() << "\nOrigin -> Inlined: " << Text << "\n\n";
121 for (auto &Entry : InlinedToOrigin) {
122 LVScope *InlinedScope = Entry.first;
123 LVScope *OriginScope = Entry.second;
124 PrintEntry("", InlinedScope);
125 dbgs() << " -> ";
126 PrintEntry("", OriginScope);
127 dbgs() << "\n";
128 }
129
130 if (Full) {
131 dbgs() << "\n";
132 for (auto &Entry : InlinedToOrigin) {
133 LVScope *InlinedScope = Entry.first;
134 LVScope *OriginScope = Entry.second;
135 PrintExtra("OriginParent: ", OriginScope->getParentScope());
136 PrintExtra("Origin: ", OriginScope);
137 PrintExtra("InlinedParent: ", InlinedScope->getParentScope());
138 PrintExtra("Inlined: ", InlinedScope);
139 dbgs() << "\n";
140 }
141 }
142}
143#endif
144
145} // namespace
146
147// These flavours of 'DINode's are not implemented but technically possible:
148// DW_TAG_APPLE_property = 0x4200
149// DW_TAG_atomic_type = 0x0047
150// DW_TAG_common_block = 0x001a
151// DW_TAG_file_type = 0x0029
152// DW_TAG_friend = 0x002a
153// DW_TAG_generic_subrange = 0x0045
154// DW_TAG_immutable_type = 0x004b
155// DW_TAG_module = 0x001e
156// DW_TAG_variant_part = 0x0033
157
158// Create a logical element and setup the following information:
159// - Name, DWARF tag, line
160// - Collect any file information
161LVElement *LVIRReader::constructElement(const DINode *DN) {
162 dwarf::Tag Tag = DN->getTag();
163 LVElement *Element = createElement(Tag);
164 if (Element) {
165 Element->setTag(Tag);
166 addMD(DN, Element);
167
168 if (StringRef Name = getMDName(DN); !Name.empty())
169 Element->setName(Name);
170
171 // Record any file information.
172 if (const DIFile *File = getMDFile(DN))
173 getOrCreateSourceID(File);
174 }
175 return Element;
176}
177
178void LVIRReader::setDefaultLowerBound(LVSourceLanguage *SL) {
179 assert(SL && "Invalid language ID.");
180 StringRef LanguageName = SL->getName();
181
182 // Fortran uses 1 as the default lowerbound; other languages use 0.
183 DefaultLowerBound = LanguageName.contains("fortran") ? 1 : 0;
184
185 LLVM_DEBUG({ dbgs() << "Language Name: " << LanguageName << "\n"; });
186}
187
188bool LVIRReader::includeMinimalInlineScopes() const {
189 return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly;
190}
191
192size_t LVIRReader::getOrCreateSourceID(const DIFile *File) {
193 if (!File)
194 return 0;
195
196 LLVM_DEBUG({
197 dbgs() << "\n[getOrCreateSourceID]\n";
198 dbgs() << "File: ";
199 File->dump(TheModule);
200 });
201 addMD(File, CompileUnit);
202
203 LLVM_DEBUG({
204 dbgs() << "Directory: '" << File->getDirectory() << "'\n";
205 dbgs() << "Filename: '" << File->getFilename() << "'\n";
206 });
207
208 size_t FileIndex = getFileIndex(CompileUnit);
209 auto [Iter, Inserted] = CompileUnitFiles.try_emplace(File, ++FileIndex);
210 if (Inserted) {
211 std::string Directory(File->getDirectory());
212 if (Directory.empty())
213 Directory = std::string(CompileUnit->getCompilationDirectory());
214
215 std::string FullName;
216 raw_string_ostream Out(FullName);
217 Out << Directory << "/" << llvm::sys::path::filename(File->getFilename());
218 CompileUnit->addFilename(transformPath(FullName));
219 updateFileIndex(CompileUnit, FileIndex);
220 } else {
221 FileIndex = Iter->second;
222 }
223
224 LLVM_DEBUG({ dbgs() << "FileIndex: " << FileIndex << "\n"; });
225 return FileIndex;
226}
227
228void LVIRReader::addSourceLine(LVElement *Element, unsigned Line,
229 const DIFile *File) {
230 if (Line == 0)
231 return;
232
233 // After the scopes are created, the generic reader traverses the 'Children'
234 // and performs additional setting tasks (resolve types names, references,
235 // etc.). One of those tasks is select the correct string pool index based on
236 // the commmand line options: --attribute=filename or --attribute=pathname.
237 // As the 'Children' do not include logical lines, do that selection now,
238 // by calling 'setFilename' if the logical element is a line.
239 size_t FileID = getOrCreateSourceID(File);
240 if (Element->getIsLine())
241 Element->setFilename(CompileUnit->getFilename(FileID));
242 else
243 Element->setFilenameIndex(FileID);
244 Element->setLineNumber(Line);
245
246 LLVM_DEBUG({
247 dbgs() << "\n[addSourceLine]\n";
248 File->dump(TheModule);
249 dbgs() << "FileIndex: " << Element->getFilenameIndex() << ", ";
250 dbgs() << "ID: " << Element->getID() << ", ";
251 dbgs() << "Kind: " << Element->kind() << ", ";
252 dbgs() << "Line: " << Element->getLineNumber() << ", ";
253 dbgs() << "Name: " << Element->getName() << "\n";
254 });
255}
256
257void LVIRReader::addSourceLine(LVElement *Element, const DIGlobalVariable *G) {
258 assert(G);
259 addSourceLine(Element, G->getLine(), G->getFile());
260}
261
262void LVIRReader::addSourceLine(LVElement *Element, const DIImportedEntity *IE) {
263 assert(IE);
264 addSourceLine(Element, IE->getLine(), IE->getFile());
265}
266
267void LVIRReader::addSourceLine(LVElement *Element, const DILabel *L) {
268 assert(L);
269 addSourceLine(Element, L->getLine(), L->getFile());
270}
271
272void LVIRReader::addSourceLine(LVElement *Element, const DILocalVariable *V) {
273 assert(V);
274 addSourceLine(Element, V->getLine(), V->getFile());
275}
276
277void LVIRReader::addSourceLine(LVElement *Element, const DILocation *DL) {
278 assert(DL);
279 addSourceLine(Element, DL->getLine(), DL->getFile());
280}
281
282void LVIRReader::addSourceLine(LVElement *Element, const DIObjCProperty *OP) {
283 assert(OP);
284 addSourceLine(Element, OP->getLine(), OP->getFile());
285}
286
287void LVIRReader::addSourceLine(LVElement *Element, const DISubprogram *SP) {
288 assert(SP);
289 addSourceLine(Element, SP->getLine(), SP->getFile());
290}
291
292void LVIRReader::addSourceLine(LVElement *Element, const DIType *Ty) {
293 assert(Ty);
294 addSourceLine(Element, Ty->getLine(), Ty->getFile());
295}
296
297void LVIRReader::addConstantValue(LVElement *Element,
298 const DIExpression *DIExpr) {
299 std::optional<DIExpression::SignedOrUnsignedConstant> Constant =
300 DIExpr->isConstant();
301 if (Constant == std::nullopt)
302 return;
303 std::stringstream Stream;
304 uint64_t Value = DIExpr->getElement(1);
306 if (int64_t SignedValue = static_cast<int64_t>(Value); SignedValue < 0) {
307 Stream << "-";
308 Value = static_cast<uint64_t>(-SignedValue);
309 }
310 }
311 Stream << hexString(Value, 2);
312 Element->setValue(Stream.str());
313}
314
315void LVIRReader::addConstantValue(LVElement *Element, const ConstantFP *CFP) {
316 addConstantValue(Element, CFP->getValueAPF().bitcastToAPInt(), true);
317}
318
319void LVIRReader::addConstantValue(LVElement *Element, const ConstantInt *CI,
320 const DIType *Ty) {
321 addConstantValue(Element, CI->getValue(), Ty);
322}
323
324void LVIRReader::addConstantValue(LVElement *Element, uint64_t Val,
325 const DIType *Ty) {
326 addConstantValue(Element, DebugHandlerBase::isUnsignedDIType(Ty), Val);
327}
328
329void LVIRReader::addConstantValue(LVElement *Element, uint64_t Val,
330 bool Unsigned) {
331 addConstantValue(Element, llvm::APInt(64, Val, Unsigned), Unsigned);
332}
333
334void LVIRReader::addConstantValue(LVElement *Element, const APInt &Val,
335 const DIType *Ty) {
336 addConstantValue(Element, Val, DebugHandlerBase::isUnsignedDIType(Ty));
337}
338
339void LVIRReader::addConstantValue(LVElement *Element, const APInt &Value,
340 bool Unsigned) {
341 SmallString<128> StringValue;
342 Value.toString(StringValue, /*Radix=*/16, /*Signed=*/!Unsigned,
343 /*formatAsCLiteral=*/true, /*UpperCase=*/false,
344 /*InsertSeparators=*/false);
345 Element->setValue(StringValue.str());
346}
347
348void LVIRReader::processLocationGaps() {
349 if (options().getAttributeAnyLocation())
350 for (LVSymbol *Symbol : SymbolsWithLocations)
351 Symbol->fillLocationGaps();
352}
353
354void LVIRReader::processScopes() {
355 // - Calculate their location ranges.
356 // - Assign unique offset to the logical scopes, symbols and types,
357 // as the code the handles public names, expects them to have one.
358 // Use an arbitrary increment of 4.
359 // - Resolve any line pattern match.
360 // At this stage the compile unit and the root scopes they have the
361 // same offset, which is incorrect. Update the compile unit offset.
362 LVOffset Offset = OFFSET_INCREASE;
363 auto SetOffset = [&](LVElement *Element) {
364 Element->setOffset(Offset);
365 Offset += OFFSET_INCREASE;
366 };
367
368 std::function<void(LVScope *)> TraverseScope = [&](LVScope *Current) {
370 SetOffset(Current);
371 constructRange(Current);
372
373 if (const LVScopes *Scopes = Current->getScopes())
374 for (LVScope *Scope : *Scopes)
375 TraverseScope(Scope);
376
377 // Set an arbitrary, but strictly-increasing 'Offset' for symbols and types.
378 if (const LVSymbols *Symbols = Current->getSymbols())
379 for (LVSymbol *Symbol : *Symbols)
380 SetOffset(Symbol);
381 if (const LVTypes *Types = Current->getTypes())
382 for (LVType *Type : *Types)
383 SetOffset(Type);
384
385 // Resolve any given pattern.
386 if (const LVLines *Lines = Current->getLines())
387 for (LVLine *Line : *Lines)
389
390 // Calculate contributions to the debug info.
392 if (options().getPrintSizes())
393 CompileUnit->addSize(Current, Lower, Upper);
394 };
395
396 TraverseScope(CompileUnit);
397}
398
401 // At this point we are operating on a logical view item, with no access
402 // to the underlying DWARF data used by LLVM.
403 // We do not support DW_OP_regval_type here.
404 if (Opcode == dwarf::DW_OP_regval_type)
405 return {};
406
407 if (Opcode == dwarf::DW_OP_regx || Opcode == dwarf::DW_OP_bregx) {
408 // If the following trace is enabled, its output will be intermixed
409 // with the logical view output, causing some confusion.
410 // Leaving it here, just for any specific needs.
411 // LLVM_DEBUG({
412 // dbgs() << "Printing Value: " << Operands[0] << " - "
413 // << ValueNameMap.getName(Operands[0]) << "\n";
414 // });
415 // Add an extra space for a better layout when printing locations.
416 return " " + ValueNameMap.getName(Operands[0]);
417 }
418
419 llvm_unreachable("We shouldn't actually have any other reg types here!");
420}
421
422LVScope *LVIRReader::getParentScopeImpl(const DIScope *Context) {
423 if (!Context)
424 return CompileUnit;
425
426 LLVM_DEBUG({
427 dbgs() << "\n[getParentScopeImpl]\n";
428 dbgs() << "Context: ";
429 Context->dump(TheModule);
430 });
431
432 // Check for an already seen scope parent.
433 if (LVScope *Parent = getScopeForSeenMD(Context))
434 return Parent;
435
436 // Traverse the scope hierarchy and construct the required scopes.
437 return traverseParentScope(Context);
438}
439
440// Get the logical parent for the given metadata node.
441LVScope *LVIRReader::getParentScope(const DILocation *DL) {
442 assert(DL && "Invalid metadata node.");
443 LLVM_DEBUG({
444 dbgs() << "\n[getParentScope]\n";
445 dbgs() << "DL: ";
446 DL->dump(TheModule);
447 });
448
449 return getParentScopeImpl(cast<DIScope>(DL->getScope()));
450}
451
452// Get the logical parent for the given metadata node.
453LVScope *LVIRReader::getParentScope(const DINode *DN) {
454 assert(DN && "Invalid metadata node.");
455 LLVM_DEBUG({
456 dbgs() << "\n[getParentScope]\n";
457 dbgs() << "DN: ";
458 DN->dump(TheModule);
459 });
460
461 return getParentScopeImpl(getMDScope(DN));
462}
463
464LVScope *LVIRReader::traverseParentScope(const DIScope *Context) {
465 if (!Context)
466 return CompileUnit;
467
468 LLVM_DEBUG({
469 dbgs() << "\n[traverseParentScope]\n";
470 dbgs() << "Context: \n";
471 Context->dump(TheModule);
472 });
473
474 // Check if the metadata is already seen.
475 if (LVScope *Parent = getScopeForSeenMD(Context))
476 return Parent;
477
478 // Create the scope parent.
479 LVElement *Element = constructElement(Context);
480 if (Element) {
481 const DIScope *ParentContext = nullptr;
482 if (const auto *SP = dyn_cast<DISubprogram>(Context)) {
483 // Check for a specific 'Unit'.
484 if (DICompileUnit *CU = SP->getUnit())
485 ParentContext = getMDScope(SP->getDeclaration() ? CU : Context);
486 } else {
487 ParentContext = getMDScope(Context);
488 }
489 LVScope *Parent = traverseParentScope(ParentContext);
490 if (Parent) {
491 Parent->addElement(Element);
492 constructScope(Element, Context);
493 }
494 }
495
496 return static_cast<LVScope *>(Element);
497}
498
499// DW_TAG_base_type
500// DW_AT_name ("__ARRAY_SIZE_TYPE__")
501// DW_AT_byte_size (0x08)
502// DW_AT_encoding (DW_ATE_unsigned)
503LVType *LVIRReader::getIndexType() {
504 // This function is not meant to be called from multiple threads.
505 if (NodeIndexType)
506 return NodeIndexType;
507
508 // Construct an integer type to use for indexes.
509 NodeIndexType = static_cast<LVType *>(createElement(dwarf::DW_TAG_base_type));
510 if (NodeIndexType) {
511 NodeIndexType->setIsFinalized();
512 NodeIndexType->setName("__ARRAY_SIZE_TYPE__");
513 CompileUnit->addElement(NodeIndexType);
514 }
515
516 return NodeIndexType;
517}
518
519void LVIRReader::addAccess(LVElement *Element, DINode::DIFlags Flags) {
520 assert(Element && "Invalid logical element.");
521 LLVM_DEBUG({
522 dbgs() << "\n[addAccess]\n";
523 dbgs() << "Flags: " << Flags << "\n";
524 });
525
526 const unsigned Accessibility = (Flags & DINode::FlagAccessibility);
527 switch (Accessibility) {
528 case DINode::FlagProtected:
530 return;
531 case DINode::FlagPrivate:
533 return;
534 case DINode::FlagPublic:
536 return;
537 case DINode::FlagZero:
538 // If no explicit access control, provide the default for the parent.
539 LVScope *Parent = Element->getParentScope();
540 if (Parent->getIsClass()) {
542 return;
543 }
544 if (Parent->getIsStructure() || Parent->getIsUnion()) {
546 return;
547 }
548 }
549}
550
551// getFile()
552// DIScope
553// DILocation
554// DIVariable
555// DICommonBlock
556// DILabel
557// DIObjCProperty
558// DIImportedEntity
559// DIMacroFile
560const DIFile *LVIRReader::getMDFile(const MDNode *MD) const {
561 assert(MD && "Invalid metadata node.");
562 LLVM_DEBUG({
563 dbgs() << "\n[getMDFile]\n";
564 dbgs() << "MD: ";
565 MD->dump(TheModule);
566 });
567
568 if (auto *T = dyn_cast<DIScope>(MD))
569 return T->getFile();
570
571 if (auto *T = dyn_cast<DILocation>(MD))
572 return T->getFile();
573
574 if (auto *T = dyn_cast<DIVariable>(MD))
575 return T->getFile();
576
577 if (auto *T = dyn_cast<DICommonBlock>(MD))
578 return T->getFile();
579
580 if (auto *T = dyn_cast<DILabel>(MD))
581 return T->getFile();
582
583 if (auto *T = dyn_cast<DIObjCProperty>(MD))
584 return T->getFile();
585
586 if (auto *T = dyn_cast<DIImportedEntity>(MD))
587 return T->getFile();
588
589 if (auto *T = dyn_cast<DIMacroFile>(MD))
590 return T->getFile();
591
592 return nullptr;
593}
594
595// getMDName()
596// DIScope
597// DIType
598// DISubprogram
599// DINamespace
600// DIModule
601// DITemplateParameter
602// DIVariable
603// DICommonBlock
604// DILabel
605// DIObjCProperty
606// DIImportedEntity
607// DIMacro
608// DIEnumerator
609StringRef LVIRReader::getMDName(const DINode *DN) const {
610 assert(DN && "Invalid metadata node.");
611 LLVM_DEBUG({
612 dbgs() << "\n[getMDName]\n";
613 dbgs() << "DN: ";
614 DN->dump(TheModule);
615 });
616
617 if (auto *T = dyn_cast<DIImportedEntity>(DN))
618 return T->getName();
619
620 if (auto *T = dyn_cast<DICompositeType>(DN))
621 return T->getName();
622
623 if (auto *T = dyn_cast<DIDerivedType>(DN))
624 return T->getName();
625
626 if (auto *T = dyn_cast<DILexicalBlockBase>(DN))
627 return T->getName();
628
629 if (auto *T = dyn_cast<DIEnumerator>(DN))
630 return T->getName();
631
632 if (auto *T = dyn_cast<DIVariable>(DN))
633 return T->getName();
634
635 if (auto *T = dyn_cast<DIScope>(DN))
636 return T->getName();
637
638 if (auto *T = dyn_cast<DITemplateParameter>(DN))
639 return T->getName();
640
641 if (auto *T = dyn_cast<DILabel>(DN))
642 return T->getName();
643
644 if (auto *T = dyn_cast<DIObjCProperty>(DN))
645 return T->getName();
646
647 if (auto *T = dyn_cast<DIMacro>(DN))
648 return T->getName();
649
651 "Unhandled DINode.");
652 return StringRef();
653}
654
655const DIScope *LVIRReader::getMDScope(const DINode *DN) const {
656 assert(DN && "Invalid metadata node.");
657 LLVM_DEBUG({
658 dbgs() << "\n[getMDScope]\n";
659 dbgs() << "DN: ";
660 DN->dump(TheModule);
661 });
662
663 if (dyn_cast<DIBasicType>(DN))
664 return getCUNode();
665
666 if (auto *T = dyn_cast<DINamespace>(DN)) {
667 // The scope for global namespaces is nullptr.
668 const DIScope *Context = T->getScope();
669 if (!Context)
670 Context = getCUNode();
671 return Context;
672 }
673
674 if (auto *T = dyn_cast<DIImportedEntity>(DN))
675 return T->getScope();
676
677 if (auto *T = dyn_cast<DIVariable>(DN))
678 return T->getScope();
679
680 if (auto *T = dyn_cast<DIScope>(DN))
681 return T->getScope();
682
683 assert((isa<DIFile>(DN) || isa<DICompileUnit>(DN)) && "Unhandled DINode.");
684
685 // Assume the scope to be the compile unit.
686 return getCUNode();
687}
688
689//===----------------------------------------------------------------------===//
690// Logical elements construction using IR metadata.
691//===----------------------------------------------------------------------===//
692void LVIRReader::addTemplateParams(LVElement *Element,
693 const DINodeArray TParams) {
694 assert(Element && "Invalid logical element");
695 // assert(TParams && "Invalid metadata node.");
696 LLVM_DEBUG({
697 dbgs() << "\n[addTemplateParams]\n";
698 for (const auto *Entry : TParams) {
699 dbgs() << "Entry: ";
700 Entry->dump(TheModule);
701 }
702 });
703
704 // Add template parameters.
705 for (const auto *Entry : TParams) {
706 if (const auto *TTP = dyn_cast<DITemplateTypeParameter>(Entry))
707 constructTemplateTypeParameter(Element, TTP);
708 else if (const auto *TVP = dyn_cast<DITemplateValueParameter>(Entry))
709 constructTemplateValueParameter(Element, TVP);
710 }
711}
712
713// DISubprogram
714void LVIRReader::applySubprogramAttributes(LVScope *Function,
715 const DISubprogram *SP,
716 bool SkipSPAttributes) {
717 assert(Function && "Invalid logical element");
718 assert(SP && "Invalid metadata node.");
719 LLVM_DEBUG({
720 dbgs() << "\n[applySubprogramAttributes]\n";
721 dbgs() << "SP: ";
722 SP->dump(TheModule);
723 });
724
725 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
726 // and its source location.
727 bool SkipSPSourceLocation =
728 SkipSPAttributes && !getCUNode()->getDebugInfoForProfiling();
729 if (!SkipSPSourceLocation)
730 if (applySubprogramDefinitionAttributes(Function, SP, SkipSPAttributes))
731 return;
732
733 if (!SkipSPSourceLocation)
734 addSourceLine(Function, SP);
735
736 // Skip the rest of the attributes under -gmlt to save space.
737 if (SkipSPAttributes)
738 return;
739
740 DITypeArray Args;
741 if (const DISubroutineType *SPTy = SP->getType())
742 Args = SPTy->getTypeArray();
743
744 // Construct subprogram return type.
745 if (Args.size()) {
746 LVElement *ElementType = getOrCreateType(Args[0]);
747 Function->setType(ElementType);
748 }
749
750 // Add virtuality info if available.
751 Function->setVirtualityCode(SP->getVirtuality());
752
753 if (!SP->isDefinition()) {
754 // Add arguments. Do not add arguments for subprogram definition. They will
755 // be handled while processing variables.
756 constructSubprogramArguments(Function, Args);
757 }
758
759 if (SP->isArtificial())
760 Function->setIsArtificial();
761
762 if (!SP->isLocalToUnit())
763 Function->setIsExternal();
764
765 // Add accessibility info if available.
766 addAccess(Function, SP->getFlags());
767}
768
769// DISubprogram
770bool LVIRReader::applySubprogramDefinitionAttributes(LVScope *Function,
771 const DISubprogram *SP,
772 bool Minimal) {
773 assert(Function && "Invalid logical element");
774 assert(SP && "Invalid metadata node.");
775 LLVM_DEBUG({
776 dbgs() << "\n[applySubprogramDefinitionAttributes]\n";
777 dbgs() << "SP: ";
778 SP->dump(TheModule);
779 });
780
781 LVScope *Reference = nullptr;
782 StringRef DeclLinkageName;
783 if (const DISubprogram *SPDecl = SP->getDeclaration()) {
784 if (!Minimal) {
785 DITypeArray DeclArgs, DefinitionArgs;
786 DeclArgs = SPDecl->getType()->getTypeArray();
787 DefinitionArgs = SP->getType()->getTypeArray();
788
789 // The element zero in 'DefinitionArgs' and 'DeclArgs' arrays is
790 // the subprogram return type. A 'void' return does not have a
791 // type and it is represented by a 'nullptr' value.
792 // For the given test case and its IR:
793 //
794 // 1 struct Bar {
795 // 2 bool foo(int a);
796 // 3 };
797 // 4
798 // 5 bool Bar::foo(int a) {
799 // 6 return false;
800 // 7 }
801 //
802 // !10 = !DISubprogram(name: "foo", line: 5, type: !14,
803 // spFlags: DISPFlagDefinition)
804 // !13 = !DISubprogram(name: "foo", line: 2, type: !14, spFlags: 0)
805 // !14 = !DISubroutineType(types: !15)
806 // !15 = !{!16, !17, !18}
807 // !16 = !DIBasicType(name: "bool", ...)
808 //
809 // '!15' represents both 'DefinitionArgs' and 'DeclArgs' arrays.
810 // For cases where they have a different metadata node, use the
811 // type from the 'DefinitionArgs' array as the correct type.
812 if (DeclArgs.size() && DefinitionArgs.size())
813 if (DefinitionArgs[0] != nullptr && DeclArgs[0] != DefinitionArgs[0]) {
814 LVElement *ElementType = getOrCreateType(DefinitionArgs[0]);
815 Function->setType(ElementType);
816 }
817
818 Reference = getScopeForSeenMD(SPDecl);
819 assert(Reference && "Scope should've already been constructed.");
820 // Look at the Decl's linkage name only if we emitted it.
821 if (useAllLinkageNames())
822 DeclLinkageName = SPDecl->getLinkageName();
823 unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
824 unsigned DefID = getOrCreateSourceID(SP->getFile());
825 if (DeclID != DefID)
826 Function->setFilenameIndex(DefID);
827
828 if (SP->getLine() != SPDecl->getLine())
829 Function->setLineNumber(SP->getLine());
830 }
831 }
832
833 // Add function template parameters.
834 addTemplateParams(Function, SP->getTemplateParams());
835
836 // Add the linkage name if we have one and it isn't in the Decl.
837 StringRef LinkageName = SP->getLinkageName();
838 // Always emit it for abstract subprograms.
839 if (DeclLinkageName != LinkageName && (useAllLinkageNames()))
840 Function->setLinkageName(LinkageName);
841
842 if (!Reference)
843 return false;
844
845 // Refer to the function declaration where all the other attributes
846 // will be found.
847 Function->setReference(Reference);
848 Function->setHasReferenceSpecification();
849
850 return true;
851}
852
853// DICompositeType
854void LVIRReader::constructAggregate(LVScopeAggregate *Aggregate,
855 const DICompositeType *CTy) {
856 assert(Aggregate && "Invalid logical element");
857 assert(CTy && "Invalid metadata node.");
858 LLVM_DEBUG({
859 dbgs() << "\n[constructAggregate]\n";
860 dbgs() << "CTy: ";
861 CTy->dump(TheModule);
862 });
863
864 if (Aggregate->getIsFinalized())
865 return;
866 Aggregate->setIsFinalized();
867
868 dwarf::Tag Tag = Aggregate->getTag();
869
870 // Add template parameters to a class, structure or union types.
871 if (Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
872 Tag == dwarf::DW_TAG_union_type)
873 addTemplateParams(Aggregate, CTy->getTemplateParams());
874
875 // Add elements to aggregate type.
876 for (const auto *Member : CTy->getElements()) {
877 if (!Member)
878 continue;
879 LLVM_DEBUG({
880 dbgs() << "\nMember: ";
881 Member->dump(TheModule);
882 });
883 if (const auto *SP = dyn_cast<DISubprogram>(Member))
884 getOrCreateSubprogram(SP);
885 else if (const DIDerivedType *DT = dyn_cast<DIDerivedType>(Member)) {
886 dwarf::Tag Tag = Member->getTag();
887 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_variable) {
888 if (DT->isStaticMember())
889 getOrCreateStaticMember(Aggregate, DT);
890 else
891 getOrCreateMember(Aggregate, DT);
892 } else {
893 getOrCreateType(Aggregate, DT);
894 }
895 }
896 }
897}
898
899// DICompositeType
900void LVIRReader::constructArray(LVScopeArray *Array,
901 const DICompositeType *CTy) {
902 assert(Array && "Invalid logical element");
903 assert(CTy && "Invalid metadata node.");
904 LLVM_DEBUG({
905 dbgs() << "\n[constructArray]\n";
906 dbgs() << "CTy: ";
907 CTy->dump(TheModule);
908 });
909
910 if (Array->getIsFinalized())
911 return;
912 Array->setIsFinalized();
913
914 if (LVElement *BaseType = getOrCreateType(CTy->getBaseType()))
915 Array->setType(BaseType);
916
917 // Get an anonymous type for index type.
918 LVType *IndexType = getIndexType();
919
920 // Add subranges to array type.
921 DINodeArray Entries = CTy->getElements();
922 for (DINode *DN : Entries) {
923 if (auto *SR = dyn_cast_or_null<DINode>(DN)) {
924 if (SR->getTag() == dwarf::DW_TAG_subrange_type)
925 constructSubrange(Array, cast<DISubrange>(SR), IndexType);
926 else if (SR->getTag() == dwarf::DW_TAG_generic_subrange)
927 constructGenericSubrange(Array, cast<DIGenericSubrange>(SR), IndexType);
928 }
929 }
930}
931
932// DICompositeType
933void LVIRReader::constructEnum(LVScopeEnumeration *Enumeration,
934 const DICompositeType *CTy) {
935 assert(Enumeration && "Invalid logical element");
936 assert(CTy && "Invalid metadata node.");
937 LLVM_DEBUG({
938 dbgs() << "\n[constructEnum]\n";
939 dbgs() << "CTy: ";
940 CTy->dump(TheModule);
941 });
942
943 if (Enumeration->getIsFinalized())
944 return;
945 Enumeration->setIsFinalized();
946
947 const DIType *Ty = CTy->getBaseType();
948 bool IsUnsigned = Ty && DebugHandlerBase::isUnsignedDIType(Ty);
949
950 if (LVElement *BaseType = getOrCreateType(Ty))
951 Enumeration->setType(BaseType);
952
953 if (CTy->getFlags() & DINode::FlagEnumClass)
954 Enumeration->setIsEnumClass();
955
956 // Add enumerators to enumeration type.
957 DINodeArray Entries = CTy->getElements();
958 for (const DINode *DN : Entries) {
959 if (auto *Enum = dyn_cast_or_null<DIEnumerator>(DN)) {
960 if (LVElement *Enumerator = constructElement(Enum)) {
961 Enumerator->setIsFinalized();
962 Enumeration->addElement(Enumerator);
963 addConstantValue(Enumerator, Enum->getValue(), IsUnsigned);
964 }
965 }
966 }
967}
968
969void LVIRReader::constructGenericSubrange(LVScopeArray *Array,
970 const DIGenericSubrange *GSR,
971 LVType *IndexType) {
972 assert(Array && "Invalid logical element");
973 assert(GSR && "Invalid metadata node.");
974 LLVM_DEBUG({
975 dbgs() << "\n[constructGenericSubrange]\n";
976 dbgs() << "GSR: ";
977 GSR->dump(TheModule);
978 });
979
980 LLVM_DEBUG({ dbgs() << "\nNot implemented\n"; });
981}
982
983// DIImportedEntity
984void LVIRReader::constructImportedEntity(LVElement *Element,
985 const DIImportedEntity *IE) {
986 assert(Element && "Invalid logical element");
987 assert(IE && "Invalid metadata node.");
988 LLVM_DEBUG({
989 dbgs() << "\n[constructImportedEntity]\n";
990 dbgs() << "IE: ";
991 IE->dump(TheModule);
992 });
993
994 if (LVElement *Import = constructElement(IE)) {
995 Import->setIsFinalized();
996 addSourceLine(Import, IE);
997 LVScope *Parent = getParentScope(IE);
998 Parent->addElement(Import);
999
1000 const DINode *Entity = IE->getEntity();
1001 LVElement *Target = getElementForSeenMD(Entity);
1002 if (!Target) {
1003 if (const auto *Ty = dyn_cast<DIType>(Entity))
1004 Target = getOrCreateType(Ty);
1005 else if (const auto *SP = dyn_cast<DISubprogram>(Entity))
1006 Target = getOrCreateSubprogram(SP);
1007 else if (const auto *NS = dyn_cast<DINamespace>(Entity))
1008 Target = getOrCreateNamespace(NS);
1009 else if (const auto *M = dyn_cast<DIModule>(Entity))
1010 Target = getOrCreateScope(M);
1011 }
1012 Import->setType(Target);
1013 }
1014}
1015
1016// Traverse the 'inlinedAt' chain and create their associated inlined scopes.
1017LVScope *LVIRReader::getOrCreateInlinedScope(const DILocation *DL) {
1018 assert(DL && "Invalid metadata node.");
1019 LLVM_DEBUG({
1020 dbgs() << "\n[getOrCreateInlinedScope]\n";
1021 dbgs() << "DL: ";
1022 DL->dump(TheModule);
1023 });
1024
1025 const DILocalScope *OriginContext = DL->getScope();
1026 LLVM_DEBUG({
1027 dbgs() << "OriginContext: ";
1028 OriginContext->dump(TheModule);
1029 });
1030
1031 auto CreateScope = [&](const DILocalScope *Context) -> LVScope * {
1032 LVScope *Scope = nullptr;
1033 if (const auto *SP = dyn_cast<DISubprogram>(Context))
1034 Scope = getOrCreateSubprogram(SP);
1035 else
1036 Scope = getOrCreateScope(Context);
1037 LLVM_DEBUG({
1038 dbgs() << "Scope: ";
1039 Scope->dumpCommon();
1040 });
1041
1042 return Scope;
1043 };
1044
1045 const DILocation *InlinedAt = DL->getInlinedAt();
1046 if (!InlinedAt)
1047 return CreateScope(OriginContext);
1048
1049 LLVM_DEBUG({
1050 dbgs() << "InlinedAt: ";
1051 InlinedAt->dump(TheModule);
1052 });
1053
1054 // Check if the inlined scope is already created.
1055 if (LVScope *InlinedScope = getInlinedScope(OriginContext, InlinedAt))
1056 return InlinedScope;
1057
1058 // Get or create the original context, which will be the seed for the
1059 // inlined scope that we intend to create.
1060 LVScope *OriginScope = CreateScope(OriginContext);
1061
1062 dwarf::Tag Tag = OriginScope->getTag();
1063 if (OriginScope->getIsFunction() || OriginScope->getIsInlinedFunction()) {
1064 Tag = dwarf::DW_TAG_inlined_subroutine;
1066 }
1067 LVScope *InlinedScope = static_cast<LVScope *>(createElement(Tag));
1068 if (InlinedScope) {
1069 addInlinedScope(OriginContext, InlinedAt, InlinedScope);
1070 InlinedScope->setTag(Tag);
1071 InlinedScope->setIsFinalized();
1072 InlinedScope->setName(OriginScope->getName());
1073 InlinedScope->setType(OriginScope->getType());
1074
1075 InlinedScope->setCallLineNumber(InlinedAt->getLine());
1076 InlinedScope->setCallFilenameIndex(
1077 getOrCreateSourceID(InlinedAt->getFile()));
1078
1079 InlinedScope->setReference(OriginScope);
1080 InlinedScope->setHasReferenceAbstract();
1081
1082 // Record the link between the origin and the inlined scope, to be
1083 // used to get the correct parent scope for logical lexical scopes.
1084 LLVM_DEBUG({
1085 dbgs() << "Linking\n";
1086 OriginScope->dumpCommon();
1087 InlinedScope->dumpCommon();
1088 });
1089 addInlinedInfo(OriginScope, InlinedScope);
1090
1091 LLVM_DEBUG({
1092 DILocalScope *AbstractContext = InlinedAt->getScope();
1093 dbgs() << "AbstractContext: ";
1094 AbstractContext->dump(TheModule);
1095 });
1096
1097 LVScope *AbstractScope = getOrCreateInlinedScope(InlinedAt);
1098 assert(AbstractScope && "Logical scope is NULL.");
1099 LLVM_DEBUG({
1100 dbgs() << "AbstractScope: ";
1101 AbstractScope->dumpCommon();
1102 });
1103
1104 // Add the created inlined scope.
1105 AbstractScope->addElement(InlinedScope);
1106
1107 LLVM_DEBUG({
1108 dbgs() << "InlinedScope: ";
1109 InlinedScope->dumpCommon();
1110 });
1111 }
1112
1113 return InlinedScope;
1114}
1115
1116LVScope *LVIRReader::getOrCreateAbstractScope(const DILocation *DL) {
1117 assert(DL && "Invalid metadata node.");
1118 LLVM_DEBUG({
1119 dbgs() << "\n[getOrCreateAbstractScope]\n";
1120 dbgs() << "DL: ";
1121 DL->dump(TheModule);
1122 });
1123
1124 // Create the 'inlined' scope.
1125 LVScope *InlinedScope = getOrCreateInlinedScope(DL);
1126 assert(InlinedScope && "InlinedScope is null.");
1127 return InlinedScope;
1128}
1129
1130void LVIRReader::constructLine(LVScope *Scope, const DISubprogram *SP,
1131 Instruction &I,
1132 bool &GenerateLineBeforePrologue) {
1133 assert(Scope && "Invalid logical element");
1134 assert(SP && "Invalid metadata node.");
1135 LLVM_DEBUG({
1136 dbgs() << "\n[constructLine]\n";
1137 dbgs() << "Instruction: ";
1138 I.dump();
1139 dbgs() << "Logical Scope: ";
1140 Scope->dumpCommon();
1141 });
1142
1143 auto AddDebugLine = [&](LVScope *Parent, unsigned ID) -> LVLine * {
1144 assert(Parent && "Invalid logical element");
1145 assert(ID == Metadata::DILocationKind && "Invalid Metadata Object");
1146 LLVM_DEBUG({
1147 dbgs() << "\n[AddDebugLine]\n";
1148 dbgs() << "Parent: ";
1149 Parent->dumpCommon();
1150 });
1151
1152 LVLine *Line = createLineDebug();
1153 if (Line) {
1154 Parent->addElement(Line);
1155
1156 Line->setIsFinalized();
1157 Line->setAddress(CurrentOffset);
1158
1159 // FIXME: How to get discrimination flags:
1160 // IsStmt, BasicBlock, EndSequence, EpilogueBegin, PrologueEnd.
1161 //
1162 // Explore the 'Key Instructions' information added to the metadata:
1163 // !DILocation(line: ..., scope: ..., atomGroup: ..., atomRank: ...)
1164
1165 // Add mapping for this debug line.
1166 CompileUnit->addMapping(Line, /*SectionIndex=*/0);
1167
1168 // Replicate the DWARF reader functionality of adding a linkage
1169 // name to a function with ranges (logical lines), regardless if
1170 // the declaration has already one.
1171 if (!Parent->getLinkageNameIndex() &&
1172 Parent->getHasReferenceSpecification()) {
1173 Parent->setLinkageName(Parent->getReference()->getLinkageName());
1174 }
1175 GenerateLineBeforePrologue = false;
1176 }
1177
1178 return Line;
1179 };
1180
1181 auto AddAssemblerLine = [&](LVScope *Parent) {
1182 assert(Parent && "Invalid logical element");
1183
1184 static const char *WhiteSpace = " \t\n\r\f\v";
1185 static std::string Metadata("metadata ");
1186
1187 auto RemoveAll = [](std::string &Input, std::string &Pattern) {
1188 std::string::size_type Len = Pattern.length();
1189 for (std::string::size_type Index = Input.find(Pattern);
1190 Index != std::string::npos; Index = Input.find(Pattern))
1191 Input.erase(Index, Len);
1192 };
1193
1194 std::string InstructionText;
1195 raw_string_ostream Stream(InstructionText);
1196 Stream << I;
1197 // Remove the 'metadata ' pattern from the instruction text.
1198 RemoveAll(InstructionText, Metadata);
1199 std::string_view Text(InstructionText);
1200 const auto pos(Text.find_first_not_of(WhiteSpace));
1201 Text.remove_prefix(std::min(pos, Text.length()));
1202
1203 // Create an instruction line at the given scope.
1204 if (LVLineAssembler *Line = createLineAssembler()) {
1205 Line->setIsFinalized();
1206 Line->setAddress(CurrentOffset);
1207 Line->setName(Text);
1208 Parent->addElement(Line);
1209 }
1210 };
1211
1212 LVScope *Parent = Scope;
1213 if (const DebugLoc DbgLoc = I.getDebugLoc()) {
1214 const DILocation *DL = DbgLoc.get();
1215 LLVM_DEBUG({
1216 dbgs() << "DL: ";
1217 DL->dump(TheModule);
1218 });
1219
1220 Parent = getOrCreateAbstractScope(DL);
1221 assert(Parent && "Invalid logical element");
1222 LLVM_DEBUG({
1223 dbgs() << "Parent: ";
1224 Parent->dumpCommon();
1225 });
1226
1227 if (options().getPrintLines() && DL->getLine()) {
1228 if (LVLine *Line = AddDebugLine(Parent, DL->getMetadataID())) {
1229 addMD(DL, Line);
1230 addSourceLine(Line, DL);
1231 GenerateLineBeforePrologue = false;
1232 }
1233 }
1234 }
1235
1236 // Generate a logical line before the function prologue.
1237 if (options().getPrintLines() && GenerateLineBeforePrologue) {
1238 if (LVLine *Line = AddDebugLine(Parent, Metadata::DILocationKind)) {
1239 addSourceLine(Line, SP);
1240 GenerateLineBeforePrologue = false;
1241 }
1242 }
1243
1244 // Create assembler line.
1245 if (options().getPrintInstructions())
1246 AddAssemblerLine(Parent);
1247}
1248
1249LVSymbol *LVIRReader::getOrCreateMember(LVScope *Aggregate,
1250 const DIDerivedType *DT) {
1251 assert(Aggregate && "Invalid logical element");
1252 assert(DT && "Invalid metadata node.");
1253 LLVM_DEBUG({
1254 dbgs() << "\n[getOrCreateMember]\n";
1255 dbgs() << "DT: ";
1256 DT->dump(TheModule);
1257 });
1258
1259 LVSymbol *Member = getSymbolForSeenMD(DT);
1260 if (Member && Member->getIsFinalized())
1261 return Member;
1262
1263 if (!options().getPrintSymbols()) {
1264 // Just create the symbol type.
1265 getOrCreateType(DT->getBaseType());
1266 return nullptr;
1267 }
1268
1269 if (!Member)
1270 Member = static_cast<LVSymbol *>(getOrCreateType(Aggregate, DT));
1271 if (Member) {
1272 Member->setIsFinalized();
1273 addSourceLine(Member, DT);
1274 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1275 Member->addLocation(dwarf::DW_AT_data_member_location, /*LowPC=*/0,
1276 /*HighPC=*/-1, /*SectionOffset=*/0,
1277 /*OffsetOnEntry=*/0);
1278 } else {
1279 uint64_t OffsetInBytes = 0;
1280
1281 bool IsBitfield = DT->isBitField();
1282 if (IsBitfield) {
1283 Member->setBitSize(DT->getSizeInBits());
1284 } else {
1285 // This is not a bitfield.
1286 OffsetInBytes = DT->getOffsetInBits() / 8;
1287 }
1288
1289 if (DwarfVersion <= 2) {
1290 // DW_AT_data_member_location:
1291 // DW_FORM_data1, DW_OP_plus_uconst, DW_FORM_udata, OffsetInBytes
1292 Member->addLocation(dwarf::DW_AT_data_member_location, /*LowPC=*/0,
1293 /*HighPC=*/-1, /*SectionOffset=*/0,
1294 /*OffsetOnEntry=*/0);
1295 Member->addLocationOperands(dwarf::DW_OP_plus_uconst, {OffsetInBytes});
1296 } else if (!IsBitfield || DwarfVersion < 4) {
1297 // DW_AT_data_member_location:
1298 // DW_FORM_udata, OffsetInBytes
1299 Member->addLocationConstant(dwarf::DW_AT_data_member_location,
1300 OffsetInBytes,
1301 /*OffsetOnEntry=*/0);
1302 }
1303 }
1304 }
1305
1306 // Add accessibility info if available.
1307 if (!DT->isStaticMember())
1308 addAccess(Member, DT->getFlags());
1309
1310 if (DT->isVirtual())
1311 Member->setVirtualityCode(dwarf::DW_VIRTUALITY_virtual);
1312
1313 if (DT->isArtificial())
1314 Member->setIsArtificial();
1315
1316 return Member;
1317}
1318
1319// DIBasicType
1320// DICommonBlock
1321// DICompileUnit
1322// DICompositeType
1323// DIDerivedType
1324// DIFile
1325// DILexicalBlock
1326// DILexicalBlockFile
1327// DIModule
1328// DINamespace
1329// DISubprogram
1330// DISubroutineType
1331// DIStringType
1332void LVIRReader::constructScope(LVElement *Element, const DIScope *Context) {
1333 assert(Element && "Invalid logical element");
1334 assert(Context && "Invalid metadata node.");
1335 LLVM_DEBUG({
1336 dbgs() << "\n[constructScope]\n";
1337 dbgs() << "Context: ";
1338 Context->dump(TheModule);
1339 });
1340
1341 if (const DICompositeType *CTy =
1343 constructType(static_cast<LVScope *>(Element), CTy);
1344 } else if (const DIDerivedType *DT =
1346 constructType(Element, DT);
1347 } else if (const DISubprogram *SP =
1349 getOrCreateSubprogram(static_cast<LVScope *>(Element), SP);
1351 Element->setIsFinalized();
1353 Element->setIsFinalized();
1354 }
1355}
1356
1357LVSymbol *LVIRReader::getOrCreateStaticMember(LVScope *Aggregate,
1358 const DIDerivedType *DT) {
1359 assert(Aggregate && "Invalid logical element");
1360 assert(DT && "Invalid metadata node.");
1361 LLVM_DEBUG({
1362 dbgs() << "\n[getOrCreateStaticMember]\n";
1363 dbgs() << "DT: ";
1364 DT->dump(TheModule);
1365 });
1366
1367 LVSymbol *Member = getSymbolForSeenMD(DT);
1368 if (Member && Member->getIsFinalized())
1369 return Member;
1370
1371 if (!options().getPrintSymbols()) {
1372 // Just create the symbol type.
1373 getOrCreateType(DT->getBaseType());
1374 return nullptr;
1375 }
1376
1377 if (!Member)
1378 Member = static_cast<LVSymbol *>(getOrCreateType(Aggregate, DT));
1379 if (Member) {
1380 Member->setIsFinalized();
1381 addSourceLine(Member, DT);
1382 Member->setIsExternal();
1383 }
1384
1385 return Member;
1386}
1387
1388// DISubprogram
1389LVScope *LVIRReader::getOrCreateSubprogram(const DISubprogram *SP) {
1390 assert(SP && "Invalid metadata node.");
1391 LLVM_DEBUG({
1392 dbgs() << "\n[getOrCreateSubprogram]\n";
1393 dbgs() << "SP: ";
1394 SP->dump(TheModule);
1395 });
1396
1397 LVScope *Function = getScopeForSeenMD(SP);
1398 if (Function && Function->getIsFinalized())
1399 return Function;
1400
1401 if (!Function)
1402 Function = static_cast<LVScope *>(constructElement(SP));
1403 if (Function) {
1404 // For both member functions (declaration and definition) its parent
1405 // is the containing class. The 'definition' points back to its
1406 // 'declaration' via the 'getDeclaration' return value.
1407 LVScope *Parent = SP->getDeclaration()
1408 ? SP->isLocalToUnit() || SP->isDefinition()
1409 ? CompileUnit
1410 : getParentScope(SP)->getParentScope()
1411 : getParentScope(SP);
1412 // The 'getParentScope' traverses the scope hierarchy and it creates
1413 // the scope chain and any associated types.
1414 // Check that the 'Function' is not already in the parent.
1415 if (!Function->getParent())
1416 Parent->addElement(Function);
1417
1418 getOrCreateSubprogram(Function, SP, includeMinimalInlineScopes());
1419 }
1420
1421 return Function;
1422}
1423
1424// DISubprogram
1425LVScope *LVIRReader::getOrCreateSubprogram(LVScope *Function,
1426 const DISubprogram *SP,
1427 bool Minimal) {
1428 assert(Function && "Invalid logical element");
1429 assert(SP && "Invalid metadata node.");
1430 LLVM_DEBUG({
1431 dbgs() << "\n[getOrCreateSubprogram]\n";
1432 dbgs() << "SP: ";
1433 SP->dump(TheModule);
1434 });
1435
1436 if (Function->getIsFinalized())
1437 return Function;
1438 Function->setIsFinalized();
1439
1440 // Get 'declaration' node in order to generate the DW_AT_specification.
1441 if (const DISubprogram *SPDecl = SP->getDeclaration()) {
1442 if (!Minimal) {
1443 // Build the declaration now to ensure it precedes the definition.
1444 getOrCreateSubprogram(SPDecl);
1445 }
1446 }
1447
1448 // Check for additional retained nodes.
1449 for (const MDNode *DN : SP->getRetainedNodes()) {
1450 if (const auto *IE = dyn_cast<DIImportedEntity>(DN))
1451 constructImportedEntity(Function, IE);
1452 else if (const auto *TTP = dyn_cast<DITemplateTypeParameter>(DN))
1453 constructTemplateTypeParameter(Function, TTP);
1454 else if (const auto *TVP = dyn_cast<DITemplateValueParameter>(DN))
1455 constructTemplateValueParameter(Function, TVP);
1456 else if (const auto *GVE = dyn_cast<DIGlobalVariableExpression>(DN))
1457 getOrCreateVariable(GVE);
1458 }
1459
1460 applySubprogramAttributes(Function, SP);
1461
1462 // Check if we are dealing with the Global Init/Cleanup Function.
1463 if (SP->isArtificial() && SP->isLocalToUnit() && SP->isDefinition() &&
1464 SP->getName().empty())
1465 Function->setName(SP->getLinkageName());
1466
1467 return Function;
1468}
1469
1470void LVIRReader::constructSubprogramArguments(LVScope *Function,
1471 const DITypeArray Args) {
1472 assert(Function && "Invalid logical element");
1473 LLVM_DEBUG({
1474 dbgs() << "\n[constructSubprogramArguments]\n";
1475 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
1476 if (const DIType *Ty = Args[i]) {
1477 dbgs() << "Ty: ";
1478 Ty->dump(TheModule);
1479 }
1480 }
1481 });
1482
1483 for (unsigned I = 1, N = Args.size(); I < N; ++I) {
1484 const DIType *Ty = Args[I];
1485 LVElement *Parameter = nullptr;
1486 if (Ty) {
1487 // Create a formal parameter.
1488 LVElement *ParameterType = getOrCreateType(Ty);
1489 Parameter = createElement(dwarf::DW_TAG_formal_parameter);
1490 if (Parameter) {
1491 Parameter->setType(ParameterType);
1492 if (Ty->isArtificial())
1493 Parameter->setIsArtificial();
1494 }
1495 } else {
1496 // Add an unspecified parameter.
1497 Parameter = createElement(dwarf::DW_TAG_unspecified_parameters);
1498 }
1499 if (Parameter) {
1500 Function->addElement(Parameter);
1501 Parameter->setIsFinalized();
1502 }
1503 }
1504}
1505
1506// DISubrange
1507void LVIRReader::constructSubrange(LVScopeArray *Array, const DISubrange *SR,
1508 LVType *IndexType) {
1509 assert(Array && "Invalid logical element");
1510 assert(SR && "Invalid metadata node.");
1511 LLVM_DEBUG({
1512 dbgs() << "\n[constructSubrange]\n";
1513 dbgs() << "SR: ";
1514 SR->dump(TheModule);
1515 });
1516
1517 // The DISubrange can be shared between different arrays, when they are
1518 // the same. We need to create independent logical elements for each one,
1519 // as they are going to be added to different arrays.
1520 if (LVTypeSubrange *Subrange =
1521 static_cast<LVTypeSubrange *>(constructElement(SR))) {
1522 Subrange->setIsFinalized();
1523 Array->addElement(Subrange);
1524 Subrange->setType(IndexType);
1525
1526 int64_t Count = 0;
1527 // If Subrange has a Count field, use it.
1528 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1529 // where lowerbound is from the LowerBound field of the Subrange,
1530 // or the language default lowerbound if that field is unspecified.
1531 if (auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount()))
1532 Count = CI->getSExtValue();
1533 else if (auto *UI =
1535 // Fortran uses 1 as the default lowerbound; other languages use 0.
1536 int64_t Lowerbound = getDefaultLowerBound();
1538 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1539 Count = UI->getSExtValue() - Lowerbound + 1;
1540 }
1541
1542 Subrange->setCount(Count);
1543 }
1544}
1545
1546// DITemplateTypeParameter
1547void LVIRReader::constructTemplateTypeParameter(
1548 LVElement *Element, const DITemplateTypeParameter *TTP) {
1549 assert(Element && "Invalid logical element");
1550 assert(TTP && "Invalid metadata node.");
1551 LLVM_DEBUG({
1552 dbgs() << "\n[constructTemplateTypeParameter]\n";
1553 dbgs() << "TTP: ";
1554 TTP->dump(TheModule);
1555 });
1556
1557 // The DITemplateTypeParameter can be shared between different subprogram
1558 // in their DITemplateParameterArray describing the template parameters.
1559 // We need to create independent logical elements for each one, as they are
1560 // going to be added to different function.
1561 if (LVElement *Parameter = constructElement(TTP)) {
1562 Parameter->setIsFinalized();
1563 // Add element to parent (always the given Element).
1564 LVScope *Parent = static_cast<LVScope *>(Element);
1565 Parent->addElement(Parameter);
1566 // Mark the parent as template.
1567 Parent->setIsTemplate();
1568
1569 // Add the type if it exists, it could be void and therefore no type.
1570 if (const DIType *Ty = TTP->getType()) {
1571 LVElement *Type = getElementForSeenMD(Ty);
1572 if (!Type)
1573 Type = getOrCreateType(Ty);
1574 Parameter->setType(Type);
1575 }
1576 }
1577}
1578
1579// DITemplateValueParameter
1580void LVIRReader::constructTemplateValueParameter(
1581 LVElement *Element, const DITemplateValueParameter *TVP) {
1582 assert(Element && "Invalid logical element");
1583 assert(TVP && "Invalid metadata node.");
1584 LLVM_DEBUG({
1585 dbgs() << "\n[constructTemplateValueParameter]\n";
1586 dbgs() << "TVP: ";
1587 TVP->dump(TheModule);
1588 });
1589
1590 // The DITemplateValueParameter can be shared between different subprogram
1591 // in their DITemplateParameterArray describing the template parameters.
1592 // We need to create independent logical elements for each one, as they are
1593 // going to be added to different function.
1594 if (LVElement *Parameter = constructElement(TVP)) {
1595 Parameter->setIsFinalized();
1596 // Add element to parent (always the given Element).
1597 LVScope *Parent = static_cast<LVScope *>(Element);
1598 Parent->addElement(Parameter);
1599 // Mark the parent as template.
1600 Parent->setIsTemplate();
1601
1602 // Add the type if there is one, template template and template parameter
1603 // packs will not have a type.
1604 if (TVP->getTag() == dwarf::DW_TAG_template_value_parameter) {
1605 LVElement *Type = getOrCreateType(TVP->getType());
1606 Parameter->setType(Type);
1607 }
1608 if (Metadata *Value = TVP->getValue()) {
1609 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Value))
1610 addConstantValue(Parameter, CI, TVP->getType());
1611 else if (ConstantFP *CF = mdconst::dyn_extract<ConstantFP>(Value))
1612 addConstantValue(Parameter, CF);
1614 // We cannot describe the location of dllimport'd entities: the
1615 // computation of their address requires loads from the IAT.
1616 Parameter->setValue("Unable to describe global value");
1617 } else if (TVP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1619 // Add the value for dwarf::DW_AT_GNU_template_name.
1620 Parameter->setValue(cast<MDString>(Value)->getString());
1621 } else if (TVP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1622 addTemplateParams(Parameter, cast<MDTuple>(Value));
1623 }
1624 }
1625 }
1626}
1627
1628// DICompositeType
1629// DW_TAG_array_type
1630// DW_TAG_class_type
1631// DW_TAG_enumeration_type
1632// DW_TAG_structure_type
1633// DW_TAG_union_type
1634void LVIRReader::constructType(LVScope *Scope, const DICompositeType *CTy) {
1635 assert(Scope && "Invalid logical element");
1636 assert(CTy && "Invalid metadata node.");
1637 LLVM_DEBUG({
1638 dbgs() << "\n[constructType]\n";
1639 dbgs() << "CTy: ";
1640 CTy->dump(TheModule);
1641 });
1642
1643 dwarf::Tag Tag = Scope->getTag();
1644 switch (Tag) {
1645 case dwarf::DW_TAG_array_type:
1646 constructArray(static_cast<LVScopeArray *>(Scope), CTy);
1647 break;
1648 case dwarf::DW_TAG_enumeration_type:
1649 constructEnum(static_cast<LVScopeEnumeration *>(Scope), CTy);
1650 break;
1651 // FIXME: Not implemented.
1652 case dwarf::DW_TAG_variant_part:
1653 case dwarf::DW_TAG_namelist:
1654 break;
1655 case dwarf::DW_TAG_structure_type:
1656 case dwarf::DW_TAG_union_type:
1657 case dwarf::DW_TAG_class_type: {
1658 constructAggregate(static_cast<LVScopeAggregate *>(Scope), CTy);
1659 break;
1660 }
1661 default:
1662 break;
1663 }
1664
1665 if (Tag == dwarf::DW_TAG_enumeration_type ||
1666 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1667 Tag == dwarf::DW_TAG_union_type) {
1668 // Add accessibility info if available.
1669 addAccess(Scope, CTy->getFlags());
1670
1671 // Add source line info if available.
1672 if (!CTy->isForwardDecl())
1673 addSourceLine(Scope, CTy);
1674 }
1675}
1676
1677// DIDerivedType
1678// DW_TAG_atomic_type
1679// DW_TAG_const_type
1680// DW_TAG_friend
1681// DW_TAG_inheritance
1682// DW_TAG_member
1683// DW_TAG_immutable_type
1684// DW_TAG_pointer_type
1685// DW_TAG_ptr_to_member_type
1686// DW_TAG_reference_type
1687// DW_TAG_restrict_type
1688// DW_TAG_typedef
1689// DW_TAG_volatile_type
1690void LVIRReader::constructType(LVElement *Element, const DIDerivedType *DT) {
1691 assert(Element && "Invalid logical element");
1692 assert(DT && "Invalid metadata node.");
1693 LLVM_DEBUG({
1694 dbgs() << "\n[constructType]\n";
1695 dbgs() << "DT: ";
1696 DT->dump(TheModule);
1697 });
1698
1699 // For DW_TAG_member, the flag is set during the construction of the
1700 // aggregate type (DICompositeType).
1701 if (DT->getTag() != dwarf::DW_TAG_member)
1702 Element->setIsFinalized();
1703
1704 LVElement *BaseType = getOrCreateType(DT->getBaseType());
1705 Element->setType(BaseType);
1706
1707 // Add accessibility info if available.
1708 if (!DT->isStaticMember())
1709 addAccess(Element, DT->getFlags());
1710
1711 if (DT->isVirtual())
1712 Element->setVirtualityCode(dwarf::DW_VIRTUALITY_virtual);
1713
1714 if (DT->isArtificial())
1715 Element->setIsArtificial();
1716
1717 // Add source line info if available and TyDesc is not a forward declaration.
1718 if (!DT->isForwardDecl())
1719 addSourceLine(Element, DT);
1720}
1721
1722// DISubroutineType
1723void LVIRReader::constructType(LVScope *Function,
1724 const DISubroutineType *SPTy) {
1725 assert(Function && "Invalid logical element");
1726 assert(SPTy && "Invalid metadata node.");
1727 LLVM_DEBUG({
1728 dbgs() << "\n[constructType]\n";
1729 dbgs() << "SPTy: ";
1730 SPTy->dump(TheModule);
1731 });
1732
1733 if (Function->getIsFinalized())
1734 return;
1735 Function->setIsFinalized();
1736
1737 // For DISubprogram, the DISubroutineType contains the types for:
1738 // return type, param 1 type, ..., param n type
1739 DITypeArray Args = SPTy->getTypeArray();
1740 if (Args.size()) {
1741 LVElement *ElementType = getOrCreateType(Args[0]);
1742 Function->setType(ElementType);
1743 }
1744
1745 constructSubprogramArguments(Function, Args);
1746}
1747
1748// DINamespace
1749LVScope *LVIRReader::getOrCreateNamespace(const DINamespace *NS) {
1750 LLVM_DEBUG({
1751 dbgs() << "\n[getOrCreateNamespace]\n";
1752 dbgs() << "NS: ";
1753 NS->dump(TheModule);
1754 });
1755
1756 LVScope *Scope = getOrCreateScope(NS);
1757 if (Scope) {
1758 StringRef Name = NS->getName();
1759 if (Name.empty())
1760 Scope->setName("(anonymous namespace)");
1761 }
1762
1763 return Scope;
1764}
1765
1766LVScope *LVIRReader::getOrCreateScope(const DIScope *Context) {
1767 assert(Context && "Invalid metadata node.");
1768 LLVM_DEBUG({
1769 dbgs() << "\n[getOrCreateScope]\n";
1770 dbgs() << "Context: ";
1771 Context->dump(TheModule);
1772 });
1773
1774 // Check if the scope is already created.
1775 LVScope *Scope = getScopeForSeenMD(Context);
1776 if (Scope)
1777 return Scope;
1778
1779 Scope = static_cast<LVScope *>(constructElement(Context));
1780 if (Scope) {
1781 // Add element to parent.
1782 LVScope *Parent = getParentScope(Context);
1783 Parent->addElement(Scope);
1784 }
1785
1786 return Scope;
1787}
1788
1789// DICompositeType
1790// DIDerivedType
1791// DISubroutineType
1792LVElement *LVIRReader::getOrCreateType(LVScope *Scope, const DIType *Ty) {
1793 if (!Ty)
1794 return nullptr;
1795
1796 LLVM_DEBUG({
1797 dbgs() << "\n[getOrCreateType]\n";
1798 dbgs() << "Ty :";
1799 Ty->dump(TheModule);
1800 });
1801
1802 // Check if the element is already created.
1803 LVElement *Element = getElementForSeenMD(Ty);
1804 if (Element)
1805 return Element;
1806
1807 Element = constructElement(Ty);
1808 if (Element) {
1809 // Add element to parent.
1810 LVScope *Parent = Scope ? Scope : getParentScope(Ty);
1811 Parent->addElement(Element);
1812
1813 if (isa<DIBasicType>(Ty)) {
1814 Element->setIsFinalized();
1815 } else if (const DIDerivedType *DT = dyn_cast<DIDerivedType>(Ty)) {
1816 constructType(Element, DT);
1817 } else if (const DICompositeType *CTy = dyn_cast<DICompositeType>(Ty)) {
1818 constructType(static_cast<LVScope *>(Element), CTy);
1819 } else if (const DISubroutineType *SPTy = dyn_cast<DISubroutineType>(Ty)) {
1820 constructType(static_cast<LVScope *>(Element), SPTy);
1821 }
1822 }
1823
1824 return Element;
1825}
1826
1827// DIGlobalVariableExpression
1828LVSymbol *
1829LVIRReader::getOrCreateVariable(const DIGlobalVariableExpression *GVE) {
1830 assert(GVE && "Invalid metadata node.");
1831 LLVM_DEBUG({
1832 dbgs() << "\n[getOrCreateVariable]\n";
1833 dbgs() << "GVE: ";
1834 GVE->dump(TheModule);
1835 });
1836
1837 const DIGlobalVariable *DIGV = GVE->getVariable();
1838 LVSymbol *Symbol = getSymbolForSeenMD(DIGV);
1839 if (!Symbol)
1840 Symbol = getOrCreateVariable(DIGV);
1841
1842 if (Symbol) {
1843 // Add location and operation entries.
1844 Symbol->addLocation(dwarf::DW_AT_location, /*LowPC=*/0, /*HighPC=*/-1,
1845 /*SectionOffset=*/0, /*OffsetOnEntry=*/0);
1846 Symbol->addLocationOperands(dwarf::DW_OP_addrx, PoolAddressIndex++);
1847 if (const DIExpression *DIExpr = GVE->getExpression())
1848 addConstantValue(Symbol, DIExpr);
1849 }
1850 return Symbol;
1851}
1852
1853LVSymbol *LVIRReader::getOrCreateInlinedVariable(LVSymbol *OriginSymbol,
1854 const DILocation *DL) {
1855 assert(OriginSymbol && "Invalid logical element");
1856 assert(DL && "Invalid metadata node.");
1857 LLVM_DEBUG({
1858 dbgs() << "\n[getOrCreateInlinedVariable]\n";
1859 dbgs() << "DL: ";
1860 DL->dump(TheModule);
1861 });
1862
1863 const DILocation *InlinedAt = DL->getInlinedAt();
1864 if (!InlinedAt) {
1865 return nullptr;
1866 }
1867
1868 dwarf::Tag Tag = OriginSymbol->getTag();
1869 LVSymbol *InlinedSymbol = static_cast<LVSymbol *>(createElement(Tag));
1870 if (InlinedSymbol) {
1871 InlinedSymbol->setTag(Tag);
1872 InlinedSymbol->setIsFinalized();
1873 InlinedSymbol->setName(OriginSymbol->getName());
1874 InlinedSymbol->setType(OriginSymbol->getType());
1875
1876 InlinedSymbol->setCallLineNumber(InlinedAt->getLine());
1877 InlinedSymbol->setCallFilenameIndex(
1878 getOrCreateSourceID(InlinedAt->getFile()));
1879
1880 OriginSymbol->setInlineCode(dwarf::DW_INL_inlined);
1881 InlinedSymbol->setReference(OriginSymbol);
1882 InlinedSymbol->setHasReferenceAbstract();
1883
1884 if (OriginSymbol->getIsParameter())
1885 InlinedSymbol->setIsParameter();
1886
1887 // Get or create the local scope associated with the location.
1888 LVScope *InlinedScope = getOrCreateInlinedScope(DL);
1889 assert(InlinedScope && "Invalid logical element");
1890
1891 // Add the created inlined scope.
1892 InlinedScope->addElement(InlinedSymbol);
1893 }
1894
1895 return InlinedSymbol;
1896}
1897
1898// DIGlobalVariable
1899// DILocalVariable
1900LVSymbol *LVIRReader::getOrCreateVariable(const DIVariable *Var,
1901 const DILocation *DL) {
1902 assert(Var && "Invalid metadata node.");
1903 LLVM_DEBUG({
1904 dbgs() << "\n[getOrCreateVariable]\n";
1905 dbgs() << "Var: ";
1906 Var->dump(TheModule);
1907 if (DL) {
1908 dbgs() << "DL: ";
1909 DL->dump(TheModule);
1910 }
1911 });
1912
1913 // Use the 'InlinedAt' information to identify a symbol that is being
1914 // inlined. Its abstract representation is created just once.
1915 const DILocation *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
1916
1917 LVSymbol *Symbol = getSymbolForSeenMD(Var);
1918 if (Symbol && Symbol->getIsFinalized() && !InlinedAt)
1919 return Symbol;
1920
1921 if (!options().getPrintSymbols()) {
1922 // Just create the symbol type.
1923 getOrCreateType(Var->getType());
1924 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Var)) {
1925 if (MDTuple *TP = GV->getTemplateParams())
1926 addTemplateParams(Symbol, DINodeArray(TP));
1927 }
1928 return nullptr;
1929 }
1930
1931 if (!Symbol)
1932 Symbol = static_cast<LVSymbol *>(constructElement(Var));
1933 if (Symbol && !Symbol->getIsFinalized()) {
1934 Symbol->setIsFinalized();
1935 LVScope *Parent = getParentScope(Var);
1936 Parent->addElement(Symbol);
1937
1938 Symbol->setName(Var->getName());
1939
1940 // Create symbol type.
1941 if (LVElement *SymbolType = getOrCreateType(Var->getType()))
1942 Symbol->setType(SymbolType);
1943
1944 if (const DILocalVariable *LV = dyn_cast<DILocalVariable>(Var)) {
1945 // Add line number info.
1946 addSourceLine(Symbol, LV);
1947 if (LV->isParameter()) {
1948 Symbol->setIsParameter();
1949 if (LV->isArtificial())
1950 Symbol->setIsArtificial();
1951 }
1952 } else {
1953 const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Var);
1954 if (useAllLinkageNames())
1955 Symbol->setLinkageName(GV->getLinkageName());
1956
1957 // Get 'declaration' node in order to generate the DW_AT_specification.
1958 if (const DIDerivedType *GVDecl = GV->getStaticDataMemberDeclaration()) {
1959 LVSymbol *Reference = static_cast<LVSymbol *>(getOrCreateType(GVDecl));
1960 if (Reference) {
1961 Symbol->setReference(Reference);
1962 Symbol->setHasReferenceSpecification();
1963 }
1964 } else {
1965 if (!GV->isLocalToUnit())
1966 Symbol->setIsExternal();
1967 // Add line number info.
1968 addSourceLine(Symbol, GV);
1969 }
1970
1971 if (MDTuple *TP = GV->getTemplateParams())
1972 addTemplateParams(Symbol, DINodeArray(TP));
1973 }
1974 }
1975
1976 // Create the 'inlined' symbol.
1977 if (DL)
1978 getOrCreateInlinedVariable(Symbol, DL);
1979
1980 return Symbol;
1981}
1982
1983#ifdef LLVM_DEBUG
1984void LVIRReader::printAllInstructions(BasicBlock *BB) {
1985 const Function *F = BB->getParent();
1986 if (!F)
1987 return;
1988 LLVM_DEBUG({
1989 const DISubprogram *SP = cast<DISubprogram>(F->getSubprogram());
1990 dbgs() << "\nBegin all instructions: '" << SP->getName() << "'\n";
1991 for (Instruction &I : *BB) {
1992 dbgs() << "I: '" << I << "'\n";
1993 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1994 dbgs() << " Var: ";
1995 DVR.getVariable()->dump(TheModule);
1996 }
1997 if (const auto *DL =
1998 cast_or_null<DILocation>(I.getMetadata(LLVMContext::MD_dbg))) {
1999 dbgs() << " DL: ";
2000 DL->dump(TheModule);
2001 }
2002 }
2003 dbgs() << "End all instructions: '" << SP->getName() << "'\n\n";
2004 });
2005}
2006#endif
2007
2008void LVIRReader::processBasicBlocks(Function &F) {
2009 const DISubprogram *SP = cast_or_null<DISubprogram>(F.getSubprogram());
2010 if (!SP)
2011 return;
2012
2013 LLVM_DEBUG({
2014 dbgs() << "\n[processBasicBlocks]\n";
2015 dbgs() << "SP: ";
2016 SP->dump(TheModule);
2017 });
2018
2019 // Check if we need to add a dwarf::DW_TAG_unspecified_parameters.
2020 bool AddUnspecifiedParameters = false;
2021 if (const DISubroutineType *SPTy = SP->getType()) {
2022 DITypeArray Args = SPTy->getTypeArray();
2023 unsigned N = Args.size();
2024 if (N > 1) {
2025 const DIType *Ty = Args[N - 1];
2026 if (!Ty)
2027 AddUnspecifiedParameters = true;
2028 }
2029 }
2030
2031 LVScope *Scope = getOrCreateSubprogram(SP);
2032
2034
2035 // Handle dbg.values and dbg.declare.
2036 auto HandleDbgVariable = [&](auto *DbgVar) {
2037 LLVM_DEBUG({
2038 dbgs() << "\n[HandleDbgVariable]\n";
2039 dbgs() << "DbgVar: ";
2040 DbgVar->dump();
2041 });
2042
2043 DebugVariableAggregate DVA(DbgVar);
2044 if (!DbgValueRanges->hasVariableEntry(DVA)) {
2045 DbgValueRanges->addVariable(&F, DVA);
2046 SeenVars.push_back(DVA);
2047 }
2048
2049 // Skip undefined values.
2050 if (!DbgVar->isKillLocation())
2051 getOrCreateVariable(DbgVar->getVariable(), DbgVar->getDebugLoc().get());
2052 };
2053
2054 // Generate logical debug line before prologue.
2055 bool GenerateLineBeforePrologue = true;
2056 for (BasicBlock &BB : F) {
2058
2059 for (Instruction &I : BB) {
2060 LLVM_DEBUG(dbgs() << "\nInstruction: '" << I << "'\n");
2061
2062 if (const auto *DL =
2063 cast_or_null<DILocation>(I.getMetadata(LLVMContext::MD_dbg))) {
2064 LLVM_DEBUG({
2065 dbgs() << " Location: ";
2066 DL->dump(TheModule);
2067 });
2068 getOrCreateAbstractScope(DL);
2069 }
2070
2071 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
2072 HandleDbgVariable(&DVR);
2073
2074 if (options().getPrintAnyLine())
2075 constructLine(Scope, SP, I, GenerateLineBeforePrologue);
2076
2077 InstrLineAddrMap[I.getIterator().getNodePtr()] = CurrentOffset;
2078
2079 // Update code offset.
2080 updateLineOffset();
2081 }
2082 InstrLineAddrMap[BB.end().getNodePtr()] = CurrentOffset;
2083 }
2084 GenerateLineBeforePrologue = false;
2085
2086 if (AddUnspecifiedParameters) {
2087 LVElement *Parameter = createElement(dwarf::DW_TAG_unspecified_parameters);
2088 if (Parameter) {
2089 Parameter->setIsFinalized();
2090 Scope->addElement(Parameter);
2091 }
2092 }
2093
2094 LLVM_DEBUG({ dbgs() << "\nTraverse seen debug variables\n"; });
2095 for (const DebugVariableAggregate &DVA : SeenVars) {
2096 LLVM_DEBUG({ DbgValueRanges->printValues(DVA, dbgs()); });
2097 DILocalVariable *LV = const_cast<DILocalVariable *>(DVA.getVariable());
2098 LVSymbol *Symbol = getSymbolForSeenMD(LV);
2099 // Undefined only value, ignore.
2100 if (!Symbol)
2101 continue;
2102
2103 LLVM_DEBUG({
2104 DIType *Ty = LV->getType();
2105 uint64_t Size = Ty ? Ty->getSizeInBits() / CHAR_BIT : 1;
2106 LV->dump(TheModule);
2107 Ty->dump(TheModule);
2108 dbgs() << "Type size: " << Size << "\n";
2109 });
2110
2111 auto AddLocationOp = [&](Value *V, bool IsMem) {
2112 uint64_t RegValue = ValueNameMap.addValue(V);
2113 if (IsMem)
2114 Symbol->addLocationOperands(dwarf::DW_OP_bregx, {RegValue, 0});
2115 else
2116 Symbol->addLocationOperands(dwarf::DW_OP_regx, RegValue);
2117 };
2118
2119 auto AddLocation = [&](DbgValueDef DV) {
2120 bool IsMem = DV.IsMemory;
2121 DIExpression *CanonicalExpr = const_cast<DIExpression *>(
2123 RawLocationWrapper Locations(DV.Locations);
2124 for (DIExpression::ExprOperand ExprOp : CanonicalExpr->expr_ops()) {
2125 if (auto Arg = dyn_cast<DIExpression::ArgOp>(ExprOp)) {
2126 AddLocationOp(Locations.getVariableLocationOp(Arg.getIndex()), IsMem);
2127 } else {
2128 if (ExprOp.getOp() > std::numeric_limits<uint8_t>::max())
2129 LLVM_DEBUG(dbgs() << "Bad DWARF op: " << ExprOp.getOp() << "\n");
2130 uint8_t ShortOp = (uint8_t)ExprOp.getOp();
2131 Symbol->addLocationOperands(
2132 ShortOp,
2133 ArrayRef<uint64_t>(std::next(ExprOp.get()), ExprOp.getNumArgs()));
2134 }
2135 }
2136 };
2137
2138 if (DbgValueRanges->hasSingleLocEntry(DVA)) {
2139 DbgValueDef DV = DbgValueRanges->getSingleLoc(DVA);
2140 Symbol->addLocation(llvm::dwarf::DW_AT_location, /*LowPC=*/0,
2141 /*HighPC=*/-1, /*SectionOffset=*/0,
2142 /*OffsetOnEntry=*/0);
2143 assert(DV.IsMemory && "Single location should be memory!");
2144 AddLocation(DV);
2145 } else {
2146 for (const DbgRangeEntry &Entry :
2147 DbgValueRanges->getVariableRanges(DVA)) {
2148 // These line addresses should have already been inserted into the
2149 // InstrLineAddrMap, so we assume they are present here.
2150 LVOffset Start = InstrLineAddrMap.at(Entry.Start.getNodePtr());
2151 LVOffset End = InstrLineAddrMap.at(Entry.End.getNodePtr());
2152 Symbol->addLocation(llvm::dwarf::DW_AT_location, Start, End,
2153 /*SectionOffset=*/0, /*OffsetOnEntry=*/0);
2154 DbgValueDef DV = Entry.Value;
2155 AddLocation(DV);
2156 }
2157 }
2158 }
2159}
2160
2161//===----------------------------------------------------------------------===//
2162// IR Reader entry point.
2163//===----------------------------------------------------------------------===//
2165 LLVM_DEBUG({
2166 W.startLine() << "\n";
2167 W.printString("File", getFilename());
2168 W.printString("Format", FileFormatName);
2169 });
2170
2171 // The IR Reader supports only debug records.
2172 // We identify the debug input format and if it is intrinsics, it is
2173 // converted to the debug records.
2174 if (Error Err = LVReader::createScopes())
2175 return Err;
2176
2177 LLVMContext Context;
2178 SMDiagnostic Err;
2179 std::unique_ptr<Module> M =
2180 parseIR(isa<IRObjectFile *>(InputFile)
2181 ? cast<IRObjectFile *>(InputFile)->getMemoryBufferRef()
2182 : *(cast<MemoryBufferRef *>(InputFile)),
2183 Err, Context);
2184 if (!M) {
2185 // Print explanatory error message.
2186 if (options().getWarningAll())
2187 Err.print("", outs());
2189 "Could not create IR module for: %s",
2190 getFilename().str().c_str());
2191 }
2192
2193 TheModule = M.get();
2194 if (!TheModule->getNamedMetadata("llvm.dbg.cu")) {
2195 LLVM_DEBUG(dbgs() << "Skipping module without debug info\n");
2196 return Error::success();
2197 }
2198
2199 DwarfVersion = TheModule->getDwarfVersion();
2200
2201 LLVM_DEBUG({ dbgs() << "\nProcess CompileUnits\n"; });
2202 for (const DICompileUnit *CU : TheModule->debug_compile_units()) {
2203 LLVM_DEBUG({
2204 dbgs() << "\nCU: ";
2205 CU->dump(TheModule);
2206 });
2207
2208 CompileUnit = static_cast<LVScopeCompileUnit *>(constructElement(CU));
2209 CUNode = const_cast<DICompileUnit *>(CU);
2210
2211 const DIFile *File = CU->getFile();
2212 CompileUnit->setName(File->getFilename());
2213 CompileUnit->setCompilationDirectory(File->getDirectory());
2214 CompileUnit->setIsFinalized();
2215
2216 Root->addElement(CompileUnit);
2217
2218 // As the IR format uses the DWARF symbolic constants, the setting
2219 // of the source language must use the DWARF language definitions.
2220 uint16_t LanguageName = CU->getSourceLanguage().getName();
2222 static_cast<llvm::dwarf::SourceLanguage>(LanguageName));
2223 setDefaultLowerBound(&SL);
2224
2225 if (options().getAttributeLanguage())
2226 CompileUnit->setSourceLanguage(SL);
2227
2228 if (options().getAttributeProducer())
2229 CompileUnit->setProducer(CU->getProducer());
2230
2231 // Global Variables.
2232 LLVM_DEBUG({ dbgs() << "\nGlobal Variables\n"; });
2233 for (const DIGlobalVariableExpression *GVE : CU->getGlobalVariables())
2234 getOrCreateVariable(GVE);
2235
2236 // The enumeration types need to be created, regardless if they are
2237 // nested to any other aggregate type, as they are not included in
2238 // their elements. But their scope is correct (aggregate).
2239 LLVM_DEBUG({ dbgs() << "\nEnumeration Types\n"; });
2240 for (auto *ET : CU->getEnumTypes())
2241 getOrCreateType(ET);
2242
2243 // Retained types.
2244 LLVM_DEBUG({ dbgs() << "\nRetained Types\n"; });
2245 for (const auto *RT : CU->getRetainedTypes()) {
2246 if (const auto *Ty = dyn_cast<DIType>(RT)) {
2247 getOrCreateType(Ty);
2248 } else {
2249 getOrCreateSubprogram(cast<DISubprogram>(RT));
2250 }
2251 }
2252
2253 // Imported entities.
2254 LLVM_DEBUG({ dbgs() << "\nImported Entities\n"; });
2255 for (const auto *IE : CU->getImportedEntities())
2256 constructImportedEntity(CompileUnit, IE);
2257 }
2258
2259 // Traverse Functions.
2260 LLVM_DEBUG({
2261 dbgs() << "\nFunctions\n";
2262 for (Function &F : M->getFunctionList())
2263 if (const auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
2264 SP->dump(TheModule);
2265 });
2266
2267 for (Function &F : M->getFunctionList())
2268 processBasicBlocks(F);
2269
2270 // Perform extra tasks on the created scopes.
2271 resolveInlinedLexicalScopes();
2272 removeEmptyScopes();
2273
2274 processLocationGaps();
2275 processScopes();
2276
2277 if (options().getInternalIntegrity())
2278 checkScopes(CompileUnit);
2279
2280 TheModule = nullptr;
2281 return Error::success();
2282}
2283
2284void LVIRReader::constructRange(LVScope *Scope, LVAddress LowPC,
2285 LVAddress HighPC) {
2286 assert(Scope && "Invalid logical element");
2287 LLVM_DEBUG({
2288 dbgs() << "\n[constructRange]\n";
2289 dbgs() << "ID: " << hexString(Scope->getID()) << " ";
2290 dbgs() << "LowPC: " << hexString(LowPC) << " ";
2291 dbgs() << "HighPC: " << hexString(HighPC) << " ";
2292 dbgs() << "Name: " << Scope->getName() << "\n";
2293 });
2294
2295 // Process ranges base on logical lines.
2296 Scope->addObject(LowPC, HighPC);
2297 if (!Scope->getIsCompileUnit()) {
2298 // If the scope is a function, add it to the public names.
2299 if ((options().getAttributePublics() || options().getPrintAnyLine()) &&
2300 Scope->getIsFunction() && !Scope->getIsInlinedFunction())
2301 CompileUnit->addPublicName(Scope, LowPC, HighPC);
2302 }
2303 addSectionRange(/*SectionIndex=*/0, Scope, LowPC, HighPC);
2304
2305 // Replicate DWARF reader funtionality of processing DW_AT_ranges for
2306 // the compilation unit.
2307 CompileUnit->addObject(LowPC, HighPC);
2308 addSectionRange(/*SectionIndex=*/0, CompileUnit, LowPC, HighPC);
2309}
2310
2311// Create the location ranges for the given scope and in the case of
2312// functions, generate an entry in the public names set.
2313void LVIRReader::constructRange(LVScope *Scope) {
2314 LLVM_DEBUG({
2315 dbgs() << "\n[constructRange]\n";
2316 dbgs() << "ID: " << hexString(Scope->getID()) << " ";
2317 dbgs() << "Name: " << Scope->getName() << "\n\n";
2318 });
2319
2320 auto NextRange = [&](LVAddress Offset) -> LVAddress {
2321 return Offset + OFFSET_INCREASE - 1;
2322 };
2323
2324 // Get any logical lines.
2325 const LVLines *Lines = Scope->getLines();
2326 if (!Lines)
2327 return;
2328
2329 // Traverse the logical lines and build the logical ranges.
2330 LVAddress Lower = 0;
2331 LVAddress Upper = 0;
2332 LVAddress Current = 0;
2333 LVAddress Previous = 0;
2334 for (const LVLine *Line : *Lines) {
2335 LLVM_DEBUG({
2336 dbgs() << "[" << hexString(Line->getAddress()) << "] ";
2337 dbgs() << "LineNo: " << decString(Line->getLineNumber()) << "\n";
2338 dbgs() << "Lower: " << hexString(Lower) << " ";
2339 dbgs() << "Upper: " << hexString(Upper) << " ";
2340 dbgs() << "Previous: " << hexString(Previous) << " ";
2341 dbgs() << "Current: " << hexString(Current) << "\n";
2342 });
2343 if (!Upper) {
2344 // First line in range.
2345 Lower = Line->getAddress();
2346 Upper = NextRange(Lower);
2347 Current = Lower;
2348 continue;
2349 }
2350 Previous = Current;
2351 Current = Line->getAddress();
2352 if (Current == Previous) {
2353 // Contiguous lines at the same address (Debug and its assembler).
2354 continue;
2355 }
2356 if (Current == Upper + 1) {
2357 // There is no gap.
2358 Upper = NextRange(Current);
2359 } else {
2360 // There is a gap.
2361 constructRange(Scope, Lower, Upper);
2362 Lower = Current;
2363 Upper = NextRange(Lower);
2364 }
2365 }
2366 constructRange(Scope, Lower, Upper);
2367}
2368
2369// At this point, all scopes for the compile unit have been created.
2370// The following aditional steps need to be performed on them:
2371// - If the lexical block doesn't have non-scope children, skip its
2372// emission and put its children directly to the parent scope.
2373// The '--internal=id' is turned on just for debugging traces. Then
2374// it is turned to its previous state.
2375void LVIRReader::removeEmptyScopes() {
2376 LLVM_DEBUG({ dbgs() << "\n[removeEmptyScopes]\n"; });
2377
2378 SmallVector<LVScope *> EmptyScopes;
2379
2380 // Delete lexically empty scopes.
2381 auto DeleteEmptyScopes = [&]() {
2382 if (EmptyScopes.empty())
2383 return;
2384
2385 LLVM_DEBUG({
2386 dbgs() << "\n** Collected empty scopes **\n";
2387 for (auto Scope : EmptyScopes)
2388 Scope->print(dbgs());
2389 });
2390
2391 LVScope *Parent = nullptr;
2392 for (auto Scope : EmptyScopes) {
2393 Parent = Scope->getParentScope();
2394 LLVM_DEBUG({
2395 dbgs() << "Scope: " << Scope->getID() << ", ";
2396 dbgs() << "Parent: " << Parent->getID() << "\n";
2397 });
2398
2399 // If the target scope has lines, move them to the scope parent.
2400 const LVLines *Lines = Scope->getLines();
2401 if (Lines) {
2402 LVLines Pack;
2403 std::copy(Lines->begin(), Lines->end(), std::back_inserter(Pack));
2404 for (LVLine *Line : Pack) {
2405 if (Scope->removeElement(Line)) {
2406 LLVM_DEBUG({ dbgs() << "Line: " << Line->getID() << "\n"; });
2407 Line->resetParent();
2408 Parent->addElement(Line);
2409 Line->updateLevel(Parent, /*Moved=*/false);
2410 }
2411 }
2412 }
2413
2414 if (Parent->removeElement(Scope)) {
2415 const LVScopes *Scopes = Scope->getScopes();
2416 if (Scopes) {
2417 for (LVScope *Child : *Scopes) {
2418 LLVM_DEBUG({ dbgs() << "Child: " << Child->getID() << "\n"; });
2419 Child->resetParent();
2420 Parent->addElement(Child);
2421 Child->updateLevel(Parent, /*Moved=*/false);
2422 }
2423 }
2424 }
2425 }
2426 };
2427
2428 // Traverse the scopes tree and collect those lexical blocks that do not
2429 // have non-scope children. Do not include the lines as they are included
2430 // in the logical view as a way to show their associated logical scope.
2431 std::function<void(LVScope *)> TraverseScope = [&](LVScope *Current) {
2432 auto IsEmpty = [](LVScope *Scope) -> bool {
2433 return !Scope->getSymbols() && !Scope->getTypes() && !Scope->getRanges();
2434 };
2435
2436 if (const LVScopes *Scopes = Current->getScopes()) {
2437 for (LVScope *Scope : *Scopes) {
2438 if (Scope->getIsLexicalBlock() && IsEmpty(Scope))
2439 EmptyScopes.push_back(Scope);
2440 TraverseScope(Scope);
2441 }
2442 }
2443 };
2444
2445 // Preserve current setting for '--internal=id'.
2446 bool InternalID = options().getInternalID();
2447 llvm::scope_exit ResetSetting([&] {
2448 // Restore setting for '--internal=id'.
2449 if (!InternalID)
2450 options().resetInternalID();
2451 });
2452 options().setInternalID();
2453
2454 LLVM_DEBUG({
2455 dbgs() << "\nBefore - RemoveEmptyScopes\n";
2457 });
2458
2459 TraverseScope(CompileUnit);
2460 DeleteEmptyScopes();
2461
2462 LLVM_DEBUG({
2463 dbgs() << "\nAfter - RemoveEmptyScopes\n";
2465 });
2466}
2467
2468// The IR generated by Clang, allocates the inlined lexical scopes
2469// at the enclosing function level. Move them to the correct scope.
2470void LVIRReader::resolveInlinedLexicalScopes() {
2471 LLVM_DEBUG({ dbgs() << "\n[resolveInlinedLexicalScopes]\n"; });
2472 LLVM_DEBUG({ dumpInlinedInfo("Before", /*Full=*/false); });
2473
2474 std::function<void(LVScope * Scope)> TraverseChildren = [&](LVScope *Parent) {
2475 LLVM_DEBUG({
2476 dbgs() << "\nParent Scope: ";
2477 Parent->dumpCommon();
2478 });
2479
2480 // Get associated inlined scopes for the parent scope.
2481 LVList &ParentInlinedList = getInlinedList(Parent);
2482
2483 // Check if the inlined scope parent is in the ParentInlinedList.
2484 auto CheckInlinedScope = [&](LVList &ScopeInlinedList) -> bool {
2485 bool Matched = true;
2486 for (auto &InlinedScope : ScopeInlinedList) {
2487 LLVM_DEBUG({
2488 dbgs() << "Inlined Scope: ";
2489 InlinedScope->dumpCommon();
2490 });
2491 LVScope *ParentScope = InlinedScope->getParentScope();
2492 for (auto &ParentInlinedScope : ParentInlinedList) {
2493 if (ParentInlinedScope != ParentScope) {
2494 // If the parent for the inlined scope is not the Parent Inlined
2495 // list, it means the lexical scope is incorrect.
2496 // Stop the traversal as the other inlined scopes will have the
2497 // same problem as they were created from the same original scope.
2498 LLVM_DEBUG({
2499 dbgs() << "\nIncorrect parent scope\n";
2500 dbgs() << "ParentInlinedScope: ";
2501 ParentInlinedScope->dumpCommon();
2502 dbgs() << "ParentScope: ";
2503 ParentScope->dumpCommon();
2504 dbgs() << "\n";
2505 });
2506 Matched = false;
2507 break;
2508 }
2509 }
2510 if (!Matched)
2511 break;
2512 }
2513 return Matched;
2514 };
2515
2516 // Adjust the inlined scopes based on the ParentInlinedList.
2517 auto AdjustInlinedScope = [&](LVList &ScopeInlinedList) {
2518 assert(ScopeInlinedList.size() == ParentInlinedList.size() &&
2519 "Scope list do not have same number of items.");
2520
2521 LLVM_DEBUG({ dbgs() << "Begin scope adjustment\n"; });
2522 LVScope *CurrentParent = nullptr;
2523 LVScope *TargetParent = nullptr;
2524 LVScope *InlinedScope = nullptr;
2525 auto ItInlined = ScopeInlinedList.begin();
2526 auto ItParent = ParentInlinedList.begin();
2527 while (ItInlined != ScopeInlinedList.end()) {
2528 TargetParent = *ItParent;
2529 InlinedScope = *ItInlined;
2530 CurrentParent = InlinedScope->getParentScope();
2531
2532 LLVM_DEBUG({
2533 dbgs() << "Target Parent: ";
2534 TargetParent->dumpCommon();
2535 dbgs() << "Current Parent: ";
2536 CurrentParent->dumpCommon();
2537 dbgs() << "Inlined: ";
2538 InlinedScope->dumpCommon();
2539 });
2540
2541 // Correct lexical scope.
2542 if (CurrentParent->removeElement(InlinedScope)) {
2543 TargetParent->addElement(InlinedScope);
2544 InlinedScope->updateLevel(TargetParent, /*Moved=*/false);
2545 }
2546 ++ItInlined;
2547 ++ItParent;
2548 }
2549 LLVM_DEBUG({ dbgs() << "End scope adjustment\n"; });
2550 };
2551
2552 // Traverse the scope children.
2553 if (const LVScopes *Children = Parent->getScopes())
2554 for (LVScope *Scope : *Children) {
2555 LLVM_DEBUG({
2556 dbgs() << "\nOrigin Scope: ";
2557 Scope->dumpCommon();
2558 });
2559
2560 // Get associated inlined scopes for the scope.
2561 LVList &ScopeInlinedList = getInlinedList(Scope);
2562 if (!CheckInlinedScope(ScopeInlinedList)) {
2563 // AdjustInlinedScope to the correct lexical scope.
2564 AdjustInlinedScope(ScopeInlinedList);
2565 }
2566 TraverseChildren(Scope);
2567 }
2568 };
2569
2570 // Traverse the origin scopes and for each function scope, analyze their
2571 // associated inlined scopes to see if they have to be move to their
2572 // correct lexical scope.
2573 for (auto &Entry : InlinedList) {
2574 LVScope *OriginScope = Entry.first;
2575 if (OriginScope->getIsFunction())
2576 TraverseChildren(OriginScope);
2577 }
2578
2579 LLVM_DEBUG({ dumpInlinedInfo("After", /*Full=*/false); });
2580}
2581
2582// During the IR-to-logical-view construction, traverse all the logical
2583// elements to check if they have been properly constructed (finalized).
2584void LVIRReader::checkScopes(LVScope *Scope) {
2585 LLVM_DEBUG({ dbgs() << "\n[checkScopes]\n"; });
2586
2587 auto PrintElement = [](LVElement *Element) {
2588 LLVM_DEBUG({
2589 dwarf::Tag Tag = Element->getTag();
2590 size_t ID = Element->getID();
2591 const char *Kind = Element->kind();
2592 StringRef Name = Element->getName();
2593 uint32_t LineNumber = Element->getLineNumber();
2594 dbgs() << "Tag: "
2595 << formatv("{0} ", fmt_align(Tag, AlignStyle::Left, 35));
2596 dbgs() << "ID: " << formatv("{0} ", fmt_align(ID, AlignStyle::Left, 5));
2597 dbgs() << "Kind: "
2598 << formatv("{0} ", fmt_align(Kind, AlignStyle::Left, 15));
2599 dbgs() << "Line: "
2600 << formatv("{0} ", fmt_align(LineNumber, AlignStyle::Left, 5));
2601 dbgs() << "Name: '" << std::string(Name) << "' ";
2602 dbgs() << "\n";
2603 });
2604 };
2605
2606 std::function<void(LVScope * Parent)> Traverse = [&](LVScope *Current) {
2607 auto Check = [&](auto *Entry) {
2608 if (Entry)
2609 if (!Entry->getIsFinalized())
2610 PrintElement(Entry);
2611 };
2612
2613 for (LVElement *Element : Current->getChildren())
2614 Check(Element);
2615
2616 if (Current->getScopes())
2617 for (LVScope *Scope : *Current->getScopes())
2618 Traverse(Scope);
2619 };
2620
2621 // Start traversing the scopes root and check its integrity.
2622 Traverse(Scope);
2623}
2624
2625void LVIRReader::sortScopes() { Root->sort(); }
2626
2628 OS << "LVIRReader\n";
2629 LLVM_DEBUG(dbgs() << "CreateReaders\n");
2630}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
dxil translate DXIL Translate Metadata
#define Check(C,...)
#define _
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
SI Fold Operands
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
#define OP(OPC)
Definition Instruction.h:46
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
#define LLVM_DEBUG(...)
Definition Debug.h:119
APInt bitcastToAPInt() const
Definition APFloat.h:1475
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const APFloat & getValueAPF() const
Definition Constants.h:463
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
DINodeArray getElements() const
DITemplateParameterArray getTemplateParams() const
DIType * getBaseType() const
iterator_range< expr_op_iterator > expr_ops() const
static LLVM_ABI const DIExpression * convertToVariadicExpression(const DIExpression *Expr)
If Expr is a non-variadic expression (i.e.
uint64_t getElement(unsigned I) const
LLVM_ABI std::optional< SignedOrUnsignedConstant > isConstant() const
Determine whether this represents a constant value, if so.
A pair of DIGlobalVariable and DIExpression.
DIGlobalVariable * getVariable() const
DIDerivedType * getStaticDataMemberDeclaration() const
MDTuple * getTemplateParams() const
StringRef getLinkageName() const
A scope for locals.
StringRef getName() const
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
DIFlags
Debug info flags.
Base class for scope-like contexts.
DIFile * getFile() const
LLVM_ABI BoundType getUpperBound() const
LLVM_ABI BoundType getLowerBound() const
LLVM_ABI BoundType getCount() const
DITypeArray getTypeArray() const
bool isBitField() const
bool isStaticMember() const
bool isVirtual() const
uint64_t getOffsetInBits() const
DIFlags getFlags() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
unsigned getLine() const
bool isArtificial() const
DIType * getType() const
StringRef getName() const
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void dump() const
LLVM_ABI void dump() const
User-friendly dump.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:308
StringRef str() const
Explicit conversion to StringRef.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
Stores all information relating to a compile unit, be it in its original instance in the object file ...
virtual void setCallLineNumber(uint32_t Number)
Definition LVElement.h:241
virtual void setLinkageName(StringRef LinkageName)
Definition LVElement.h:236
virtual void setValue(StringRef Value)
Definition LVElement.h:274
void setFilename(StringRef Filename)
void setInlineCode(uint32_t Code)
Definition LVElement.h:292
virtual void setReference(LVElement *Element)
Definition LVElement.h:231
virtual StringRef getLinkageName() const
Definition LVElement.h:237
void setName(StringRef ElementName) override
Definition LVElement.cpp:95
StringRef getName() const override
Definition LVElement.h:192
LVElement * getType() const
Definition LVElement.h:311
void setAccessibilityCode(uint32_t Access)
Definition LVElement.h:279
void setVirtualityCode(uint32_t Virtuality)
Definition LVElement.h:297
void setType(LVElement *Element=nullptr)
Definition LVElement.h:315
void setFilenameIndex(size_t Index)
Definition LVElement.h:245
size_t getFilenameIndex() const
Definition LVElement.h:244
virtual void setCallFilenameIndex(size_t Index)
Definition LVElement.h:243
virtual size_t getLinkageNameIndex() const
Definition LVElement.h:238
void print(raw_ostream &OS) const
std::string getRegisterName(LVSmall Opcode, ArrayRef< uint64_t > Operands) override
void printAllInstructions(BasicBlock *BB)
Definition LVIRReader.h:293
uint32_t getID() const
Definition LVObject.h:320
virtual const char * kind() const
Definition LVObject.h:277
LVScope * getParentScope() const
Definition LVObject.h:255
dwarf::Tag getTag() const
Definition LVObject.h:232
uint32_t getLineNumber() const
Definition LVObject.h:274
void setOffset(LVOffset DieOffset)
Definition LVObject.h:241
void setLineNumber(uint32_t Number)
Definition LVObject.h:275
void setTag(dwarf::Tag Tag)
Definition LVObject.h:233
void resolvePatternMatch(LVLine *Line)
Definition LVOptions.h:609
LVElement * createElement(dwarf::Tag Tag)
Definition LVReader.cpp:247
void printCollectedElements(LVScope *Root)
Definition LVReader.cpp:26
StringRef getFilename() const
Definition LVReader.h:266
LVScopeCompileUnit * CompileUnit
Definition LVReader.h:149
void addSectionRange(LVSectionIndex SectionIndex, LVScope *Scope)
Definition LVReader.cpp:225
virtual Error createScopes()
Definition LVReader.h:167
virtual LVScope * getReference() const
Definition LVScope.h:277
void addElement(LVElement *Element)
Definition LVScope.cpp:122
void updateLevel(LVScope *Parent, bool Moved) override
Definition LVScope.cpp:353
void setReference(LVSymbol *Symbol) override
Definition LVSymbol.h:98
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ DW_INL_inlined
Definition Dwarf.h:860
@ DW_ACCESS_private
Definition Dwarf.h:187
@ DW_ACCESS_protected
Definition Dwarf.h:186
@ DW_ACCESS_public
Definition Dwarf.h:185
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
std::string decString(uint64_t Value, size_t Width=DEC_WIDTH)
Definition LVSupport.h:128
std::string hexString(uint64_t Value, size_t Width=HEX_WIDTH)
Definition LVSupport.h:142
uint64_t LVOffset
Definition LVObject.h:39
LVPatterns & patterns()
Definition LVOptions.h:645
std::string formattedKind(StringRef Kind)
Definition LVSupport.h:249
SmallVector< LVScope *, 8 > LVScopes
Definition LVObject.h:80
std::string hexSquareString(uint64_t Value)
Definition LVSupport.h:150
SmallVector< LVSymbol *, 8 > LVSymbols
Definition LVObject.h:81
LLVM_ABI std::string transformPath(StringRef Path)
Definition LVSupport.cpp:31
uint8_t LVSmall
Definition LVObject.h:42
SmallVector< LVLine *, 8 > LVLines
Definition LVObject.h:77
uint64_t LVAddress
Definition LVObject.h:36
LVOptions & options()
Definition LVOptions.h:448
SmallVector< LVType *, 8 > LVTypes
Definition LVObject.h:82
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1134
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scope_exit(Callable) -> scope_exit< Callable >
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
@ Import
Import information from summary.
Definition IPO.h:39
auto cast_or_null(const Y &Val)
Definition Casting.h:714
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
@ invalid_argument
Definition Errc.h:56
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI std::unique_ptr< Module > parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context, ParserCallbacks Callbacks={}, AsmParserContext *ParserContext=nullptr)
If the given MemoryBuffer holds a bitcode image, return a Module for it.
Definition IRReader.cpp:67
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
support::detail::AlignAdapter< T > fmt_align(T &&Item, AlignStyle Where, size_t Amount, char Fill=' ')
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
#define N
A source language supported by any of the debug info representations.
LLVM_ABI StringRef getName() const