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