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 DINode *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 }
1458
1459 applySubprogramAttributes(Function, SP);
1460
1461 // Check if we are dealing with the Global Init/Cleanup Function.
1462 if (SP->isArtificial() && SP->isLocalToUnit() && SP->isDefinition() &&
1463 SP->getName().empty())
1464 Function->setName(SP->getLinkageName());
1465
1466 return Function;
1467}
1468
1469void LVIRReader::constructSubprogramArguments(LVScope *Function,
1470 const DITypeArray Args) {
1471 assert(Function && "Invalid logical element");
1472 LLVM_DEBUG({
1473 dbgs() << "\n[constructSubprogramArguments]\n";
1474 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
1475 if (const DIType *Ty = Args[i]) {
1476 dbgs() << "Ty: ";
1477 Ty->dump(TheModule);
1478 }
1479 }
1480 });
1481
1482 for (unsigned I = 1, N = Args.size(); I < N; ++I) {
1483 const DIType *Ty = Args[I];
1484 LVElement *Parameter = nullptr;
1485 if (Ty) {
1486 // Create a formal parameter.
1487 LVElement *ParameterType = getOrCreateType(Ty);
1488 Parameter = createElement(dwarf::DW_TAG_formal_parameter);
1489 if (Parameter) {
1490 Parameter->setType(ParameterType);
1491 if (Ty->isArtificial())
1492 Parameter->setIsArtificial();
1493 }
1494 } else {
1495 // Add an unspecified parameter.
1496 Parameter = createElement(dwarf::DW_TAG_unspecified_parameters);
1497 }
1498 if (Parameter) {
1499 Function->addElement(Parameter);
1500 Parameter->setIsFinalized();
1501 }
1502 }
1503}
1504
1505// DISubrange
1506void LVIRReader::constructSubrange(LVScopeArray *Array, const DISubrange *SR,
1507 LVType *IndexType) {
1508 assert(Array && "Invalid logical element");
1509 assert(SR && "Invalid metadata node.");
1510 LLVM_DEBUG({
1511 dbgs() << "\n[constructSubrange]\n";
1512 dbgs() << "SR: ";
1513 SR->dump(TheModule);
1514 });
1515
1516 // The DISubrange can be shared between different arrays, when they are
1517 // the same. We need to create independent logical elements for each one,
1518 // as they are going to be added to different arrays.
1519 if (LVTypeSubrange *Subrange =
1520 static_cast<LVTypeSubrange *>(constructElement(SR))) {
1521 Subrange->setIsFinalized();
1522 Array->addElement(Subrange);
1523 Subrange->setType(IndexType);
1524
1525 int64_t Count = 0;
1526 // If Subrange has a Count field, use it.
1527 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1528 // where lowerbound is from the LowerBound field of the Subrange,
1529 // or the language default lowerbound if that field is unspecified.
1530 if (auto *CI = dyn_cast_if_present<ConstantInt *>(SR->getCount()))
1531 Count = CI->getSExtValue();
1532 else if (auto *UI =
1534 // Fortran uses 1 as the default lowerbound; other languages use 0.
1535 int64_t Lowerbound = getDefaultLowerBound();
1537 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1538 Count = UI->getSExtValue() - Lowerbound + 1;
1539 }
1540
1541 Subrange->setCount(Count);
1542 }
1543}
1544
1545// DITemplateTypeParameter
1546void LVIRReader::constructTemplateTypeParameter(
1547 LVElement *Element, const DITemplateTypeParameter *TTP) {
1548 assert(Element && "Invalid logical element");
1549 assert(TTP && "Invalid metadata node.");
1550 LLVM_DEBUG({
1551 dbgs() << "\n[constructTemplateTypeParameter]\n";
1552 dbgs() << "TTP: ";
1553 TTP->dump(TheModule);
1554 });
1555
1556 // The DITemplateTypeParameter can be shared between different subprogram
1557 // in their DITemplateParameterArray describing the template parameters.
1558 // We need to create independent logical elements for each one, as they are
1559 // going to be added to different function.
1560 if (LVElement *Parameter = constructElement(TTP)) {
1561 Parameter->setIsFinalized();
1562 // Add element to parent (always the given Element).
1563 LVScope *Parent = static_cast<LVScope *>(Element);
1564 Parent->addElement(Parameter);
1565 // Mark the parent as template.
1566 Parent->setIsTemplate();
1567
1568 // Add the type if it exists, it could be void and therefore no type.
1569 if (const DIType *Ty = TTP->getType()) {
1570 LVElement *Type = getElementForSeenMD(Ty);
1571 if (!Type)
1572 Type = getOrCreateType(Ty);
1573 Parameter->setType(Type);
1574 }
1575 }
1576}
1577
1578// DITemplateValueParameter
1579void LVIRReader::constructTemplateValueParameter(
1580 LVElement *Element, const DITemplateValueParameter *TVP) {
1581 assert(Element && "Invalid logical element");
1582 assert(TVP && "Invalid metadata node.");
1583 LLVM_DEBUG({
1584 dbgs() << "\n[constructTemplateValueParameter]\n";
1585 dbgs() << "TVP: ";
1586 TVP->dump(TheModule);
1587 });
1588
1589 // The DITemplateValueParameter can be shared between different subprogram
1590 // in their DITemplateParameterArray describing the template parameters.
1591 // We need to create independent logical elements for each one, as they are
1592 // going to be added to different function.
1593 if (LVElement *Parameter = constructElement(TVP)) {
1594 Parameter->setIsFinalized();
1595 // Add element to parent (always the given Element).
1596 LVScope *Parent = static_cast<LVScope *>(Element);
1597 Parent->addElement(Parameter);
1598 // Mark the parent as template.
1599 Parent->setIsTemplate();
1600
1601 // Add the type if there is one, template template and template parameter
1602 // packs will not have a type.
1603 if (TVP->getTag() == dwarf::DW_TAG_template_value_parameter) {
1604 LVElement *Type = getOrCreateType(TVP->getType());
1605 Parameter->setType(Type);
1606 }
1607 if (Metadata *Value = TVP->getValue()) {
1608 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Value))
1609 addConstantValue(Parameter, CI, TVP->getType());
1610 else if (ConstantFP *CF = mdconst::dyn_extract<ConstantFP>(Value))
1611 addConstantValue(Parameter, CF);
1613 // We cannot describe the location of dllimport'd entities: the
1614 // computation of their address requires loads from the IAT.
1615 Parameter->setValue("Unable to describe global value");
1616 } else if (TVP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1618 // Add the value for dwarf::DW_AT_GNU_template_name.
1619 Parameter->setValue(cast<MDString>(Value)->getString());
1620 } else if (TVP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1621 addTemplateParams(Parameter, cast<MDTuple>(Value));
1622 }
1623 }
1624 }
1625}
1626
1627// DICompositeType
1628// DW_TAG_array_type
1629// DW_TAG_class_type
1630// DW_TAG_enumeration_type
1631// DW_TAG_structure_type
1632// DW_TAG_union_type
1633void LVIRReader::constructType(LVScope *Scope, const DICompositeType *CTy) {
1634 assert(Scope && "Invalid logical element");
1635 assert(CTy && "Invalid metadata node.");
1636 LLVM_DEBUG({
1637 dbgs() << "\n[constructType]\n";
1638 dbgs() << "CTy: ";
1639 CTy->dump(TheModule);
1640 });
1641
1642 dwarf::Tag Tag = Scope->getTag();
1643 switch (Tag) {
1644 case dwarf::DW_TAG_array_type:
1645 constructArray(static_cast<LVScopeArray *>(Scope), CTy);
1646 break;
1647 case dwarf::DW_TAG_enumeration_type:
1648 constructEnum(static_cast<LVScopeEnumeration *>(Scope), CTy);
1649 break;
1650 // FIXME: Not implemented.
1651 case dwarf::DW_TAG_variant_part:
1652 case dwarf::DW_TAG_namelist:
1653 break;
1654 case dwarf::DW_TAG_structure_type:
1655 case dwarf::DW_TAG_union_type:
1656 case dwarf::DW_TAG_class_type: {
1657 constructAggregate(static_cast<LVScopeAggregate *>(Scope), CTy);
1658 break;
1659 }
1660 default:
1661 break;
1662 }
1663
1664 if (Tag == dwarf::DW_TAG_enumeration_type ||
1665 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
1666 Tag == dwarf::DW_TAG_union_type) {
1667 // Add accessibility info if available.
1668 addAccess(Scope, CTy->getFlags());
1669
1670 // Add source line info if available.
1671 if (!CTy->isForwardDecl())
1672 addSourceLine(Scope, CTy);
1673 }
1674}
1675
1676// DIDerivedType
1677// DW_TAG_atomic_type
1678// DW_TAG_const_type
1679// DW_TAG_friend
1680// DW_TAG_inheritance
1681// DW_TAG_member
1682// DW_TAG_immutable_type
1683// DW_TAG_pointer_type
1684// DW_TAG_ptr_to_member_type
1685// DW_TAG_reference_type
1686// DW_TAG_restrict_type
1687// DW_TAG_typedef
1688// DW_TAG_volatile_type
1689void LVIRReader::constructType(LVElement *Element, const DIDerivedType *DT) {
1690 assert(Element && "Invalid logical element");
1691 assert(DT && "Invalid metadata node.");
1692 LLVM_DEBUG({
1693 dbgs() << "\n[constructType]\n";
1694 dbgs() << "DT: ";
1695 DT->dump(TheModule);
1696 });
1697
1698 // For DW_TAG_member, the flag is set during the construction of the
1699 // aggregate type (DICompositeType).
1700 if (DT->getTag() != dwarf::DW_TAG_member)
1701 Element->setIsFinalized();
1702
1703 LVElement *BaseType = getOrCreateType(DT->getBaseType());
1704 Element->setType(BaseType);
1705
1706 // Add accessibility info if available.
1707 if (!DT->isStaticMember())
1708 addAccess(Element, DT->getFlags());
1709
1710 if (DT->isVirtual())
1711 Element->setVirtualityCode(dwarf::DW_VIRTUALITY_virtual);
1712
1713 if (DT->isArtificial())
1714 Element->setIsArtificial();
1715
1716 // Add source line info if available and TyDesc is not a forward declaration.
1717 if (!DT->isForwardDecl())
1718 addSourceLine(Element, DT);
1719}
1720
1721// DISubroutineType
1722void LVIRReader::constructType(LVScope *Function,
1723 const DISubroutineType *SPTy) {
1724 assert(Function && "Invalid logical element");
1725 assert(SPTy && "Invalid metadata node.");
1726 LLVM_DEBUG({
1727 dbgs() << "\n[constructType]\n";
1728 dbgs() << "SPTy: ";
1729 SPTy->dump(TheModule);
1730 });
1731
1732 if (Function->getIsFinalized())
1733 return;
1734 Function->setIsFinalized();
1735
1736 // For DISubprogram, the DISubroutineType contains the types for:
1737 // return type, param 1 type, ..., param n type
1738 DITypeArray Args = SPTy->getTypeArray();
1739 if (Args.size()) {
1740 LVElement *ElementType = getOrCreateType(Args[0]);
1741 Function->setType(ElementType);
1742 }
1743
1744 constructSubprogramArguments(Function, Args);
1745}
1746
1747// DINamespace
1748LVScope *LVIRReader::getOrCreateNamespace(const DINamespace *NS) {
1749 LLVM_DEBUG({
1750 dbgs() << "\n[getOrCreateNamespace]\n";
1751 dbgs() << "NS: ";
1752 NS->dump(TheModule);
1753 });
1754
1755 LVScope *Scope = getOrCreateScope(NS);
1756 if (Scope) {
1757 StringRef Name = NS->getName();
1758 if (Name.empty())
1759 Scope->setName("(anonymous namespace)");
1760 }
1761
1762 return Scope;
1763}
1764
1765LVScope *LVIRReader::getOrCreateScope(const DIScope *Context) {
1766 assert(Context && "Invalid metadata node.");
1767 LLVM_DEBUG({
1768 dbgs() << "\n[getOrCreateScope]\n";
1769 dbgs() << "Context: ";
1770 Context->dump(TheModule);
1771 });
1772
1773 // Check if the scope is already created.
1774 LVScope *Scope = getScopeForSeenMD(Context);
1775 if (Scope)
1776 return Scope;
1777
1778 Scope = static_cast<LVScope *>(constructElement(Context));
1779 if (Scope) {
1780 // Add element to parent.
1781 LVScope *Parent = getParentScope(Context);
1782 Parent->addElement(Scope);
1783 }
1784
1785 return Scope;
1786}
1787
1788// DICompositeType
1789// DIDerivedType
1790// DISubroutineType
1791LVElement *LVIRReader::getOrCreateType(LVScope *Scope, const DIType *Ty) {
1792 if (!Ty)
1793 return nullptr;
1794
1795 LLVM_DEBUG({
1796 dbgs() << "\n[getOrCreateType]\n";
1797 dbgs() << "Ty :";
1798 Ty->dump(TheModule);
1799 });
1800
1801 // Check if the element is already created.
1802 LVElement *Element = getElementForSeenMD(Ty);
1803 if (Element)
1804 return Element;
1805
1806 Element = constructElement(Ty);
1807 if (Element) {
1808 // Add element to parent.
1809 LVScope *Parent = Scope ? Scope : getParentScope(Ty);
1810 Parent->addElement(Element);
1811
1812 if (isa<DIBasicType>(Ty)) {
1813 Element->setIsFinalized();
1814 } else if (const DIDerivedType *DT = dyn_cast<DIDerivedType>(Ty)) {
1815 constructType(Element, DT);
1816 } else if (const DICompositeType *CTy = dyn_cast<DICompositeType>(Ty)) {
1817 constructType(static_cast<LVScope *>(Element), CTy);
1818 } else if (const DISubroutineType *SPTy = dyn_cast<DISubroutineType>(Ty)) {
1819 constructType(static_cast<LVScope *>(Element), SPTy);
1820 }
1821 }
1822
1823 return Element;
1824}
1825
1826// DIGlobalVariableExpression
1827LVSymbol *
1828LVIRReader::getOrCreateVariable(const DIGlobalVariableExpression *GVE) {
1829 assert(GVE && "Invalid metadata node.");
1830 LLVM_DEBUG({
1831 dbgs() << "\n[getOrCreateVariable]\n";
1832 dbgs() << "GVE: ";
1833 GVE->dump(TheModule);
1834 });
1835
1836 const DIGlobalVariable *DIGV = GVE->getVariable();
1837 LVSymbol *Symbol = getSymbolForSeenMD(DIGV);
1838 if (!Symbol)
1839 Symbol = getOrCreateVariable(DIGV);
1840
1841 if (Symbol) {
1842 // Add location and operation entries.
1843 Symbol->addLocation(dwarf::DW_AT_location, /*LowPC=*/0, /*HighPC=*/-1,
1844 /*SectionOffset=*/0, /*OffsetOnEntry=*/0);
1845 Symbol->addLocationOperands(dwarf::DW_OP_addrx, PoolAddressIndex++);
1846 if (const DIExpression *DIExpr = GVE->getExpression())
1847 addConstantValue(Symbol, DIExpr);
1848 }
1849 return Symbol;
1850}
1851
1852LVSymbol *LVIRReader::getOrCreateInlinedVariable(LVSymbol *OriginSymbol,
1853 const DILocation *DL) {
1854 assert(OriginSymbol && "Invalid logical element");
1855 assert(DL && "Invalid metadata node.");
1856 LLVM_DEBUG({
1857 dbgs() << "\n[getOrCreateInlinedVariable]\n";
1858 dbgs() << "DL: ";
1859 DL->dump(TheModule);
1860 });
1861
1862 const DILocation *InlinedAt = DL->getInlinedAt();
1863 if (!InlinedAt) {
1864 return nullptr;
1865 }
1866
1867 dwarf::Tag Tag = OriginSymbol->getTag();
1868 LVSymbol *InlinedSymbol = static_cast<LVSymbol *>(createElement(Tag));
1869 if (InlinedSymbol) {
1870 InlinedSymbol->setTag(Tag);
1871 InlinedSymbol->setIsFinalized();
1872 InlinedSymbol->setName(OriginSymbol->getName());
1873 InlinedSymbol->setType(OriginSymbol->getType());
1874
1875 InlinedSymbol->setCallLineNumber(InlinedAt->getLine());
1876 InlinedSymbol->setCallFilenameIndex(
1877 getOrCreateSourceID(InlinedAt->getFile()));
1878
1879 OriginSymbol->setInlineCode(dwarf::DW_INL_inlined);
1880 InlinedSymbol->setReference(OriginSymbol);
1881 InlinedSymbol->setHasReferenceAbstract();
1882
1883 if (OriginSymbol->getIsParameter())
1884 InlinedSymbol->setIsParameter();
1885
1886 // Get or create the local scope associated with the location.
1887 LVScope *InlinedScope = getOrCreateInlinedScope(DL);
1888 assert(InlinedScope && "Invalid logical element");
1889
1890 // Add the created inlined scope.
1891 InlinedScope->addElement(InlinedSymbol);
1892 }
1893
1894 return InlinedSymbol;
1895}
1896
1897// DIGlobalVariable
1898// DILocalVariable
1899LVSymbol *LVIRReader::getOrCreateVariable(const DIVariable *Var,
1900 const DILocation *DL) {
1901 assert(Var && "Invalid metadata node.");
1902 LLVM_DEBUG({
1903 dbgs() << "\n[getOrCreateVariable]\n";
1904 dbgs() << "Var: ";
1905 Var->dump(TheModule);
1906 if (DL) {
1907 dbgs() << "DL: ";
1908 DL->dump(TheModule);
1909 }
1910 });
1911
1912 // Use the 'InlinedAt' information to identify a symbol that is being
1913 // inlined. Its abstract representation is created just once.
1914 const DILocation *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
1915
1916 LVSymbol *Symbol = getSymbolForSeenMD(Var);
1917 if (Symbol && Symbol->getIsFinalized() && !InlinedAt)
1918 return Symbol;
1919
1920 if (!options().getPrintSymbols()) {
1921 // Just create the symbol type.
1922 getOrCreateType(Var->getType());
1923 if (const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Var)) {
1924 if (MDTuple *TP = GV->getTemplateParams())
1925 addTemplateParams(Symbol, DINodeArray(TP));
1926 }
1927 return nullptr;
1928 }
1929
1930 if (!Symbol)
1931 Symbol = static_cast<LVSymbol *>(constructElement(Var));
1932 if (Symbol && !Symbol->getIsFinalized()) {
1933 Symbol->setIsFinalized();
1934 LVScope *Parent = getParentScope(Var);
1935 Parent->addElement(Symbol);
1936
1937 Symbol->setName(Var->getName());
1938
1939 // Create symbol type.
1940 if (LVElement *SymbolType = getOrCreateType(Var->getType()))
1941 Symbol->setType(SymbolType);
1942
1943 if (const DILocalVariable *LV = dyn_cast<DILocalVariable>(Var)) {
1944 // Add line number info.
1945 addSourceLine(Symbol, LV);
1946 if (LV->isParameter()) {
1947 Symbol->setIsParameter();
1948 if (LV->isArtificial())
1949 Symbol->setIsArtificial();
1950 }
1951 } else {
1952 const DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Var);
1953 if (useAllLinkageNames())
1954 Symbol->setLinkageName(GV->getLinkageName());
1955
1956 // Get 'declaration' node in order to generate the DW_AT_specification.
1957 if (const DIDerivedType *GVDecl = GV->getStaticDataMemberDeclaration()) {
1958 LVSymbol *Reference = static_cast<LVSymbol *>(getOrCreateType(GVDecl));
1959 if (Reference) {
1960 Symbol->setReference(Reference);
1961 Symbol->setHasReferenceSpecification();
1962 }
1963 } else {
1964 if (!GV->isLocalToUnit())
1965 Symbol->setIsExternal();
1966 // Add line number info.
1967 addSourceLine(Symbol, GV);
1968 }
1969
1970 if (MDTuple *TP = GV->getTemplateParams())
1971 addTemplateParams(Symbol, DINodeArray(TP));
1972 }
1973 }
1974
1975 // Create the 'inlined' symbol.
1976 if (DL)
1977 getOrCreateInlinedVariable(Symbol, DL);
1978
1979 return Symbol;
1980}
1981
1982#ifdef LLVM_DEBUG
1983void LVIRReader::printAllInstructions(BasicBlock *BB) {
1984 const Function *F = BB->getParent();
1985 if (!F)
1986 return;
1987 LLVM_DEBUG({
1988 const DISubprogram *SP = cast<DISubprogram>(F->getSubprogram());
1989 dbgs() << "\nBegin all instructions: '" << SP->getName() << "'\n";
1990 for (Instruction &I : *BB) {
1991 dbgs() << "I: '" << I << "'\n";
1992 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1993 dbgs() << " Var: ";
1994 DVR.getVariable()->dump(TheModule);
1995 }
1996 if (const auto *DL =
1997 cast_or_null<DILocation>(I.getMetadata(LLVMContext::MD_dbg))) {
1998 dbgs() << " DL: ";
1999 DL->dump(TheModule);
2000 }
2001 }
2002 dbgs() << "End all instructions: '" << SP->getName() << "'\n\n";
2003 });
2004}
2005#endif
2006
2007void LVIRReader::processBasicBlocks(Function &F) {
2008 const DISubprogram *SP = cast_or_null<DISubprogram>(F.getSubprogram());
2009 if (!SP)
2010 return;
2011
2012 LLVM_DEBUG({
2013 dbgs() << "\n[processBasicBlocks]\n";
2014 dbgs() << "SP: ";
2015 SP->dump(TheModule);
2016 });
2017
2018 // Check if we need to add a dwarf::DW_TAG_unspecified_parameters.
2019 bool AddUnspecifiedParameters = false;
2020 if (const DISubroutineType *SPTy = SP->getType()) {
2021 DITypeArray Args = SPTy->getTypeArray();
2022 unsigned N = Args.size();
2023 if (N > 1) {
2024 const DIType *Ty = Args[N - 1];
2025 if (!Ty)
2026 AddUnspecifiedParameters = true;
2027 }
2028 }
2029
2030 LVScope *Scope = getOrCreateSubprogram(SP);
2031
2033
2034 // Handle dbg.values and dbg.declare.
2035 auto HandleDbgVariable = [&](auto *DbgVar) {
2036 LLVM_DEBUG({
2037 dbgs() << "\n[HandleDbgVariable]\n";
2038 dbgs() << "DbgVar: ";
2039 DbgVar->dump();
2040 });
2041
2042 DebugVariableAggregate DVA(DbgVar);
2043 if (!DbgValueRanges->hasVariableEntry(DVA)) {
2044 DbgValueRanges->addVariable(&F, DVA);
2045 SeenVars.push_back(DVA);
2046 }
2047
2048 // Skip undefined values.
2049 if (!DbgVar->isKillLocation())
2050 getOrCreateVariable(DbgVar->getVariable(), DbgVar->getDebugLoc().get());
2051 };
2052
2053 // Generate logical debug line before prologue.
2054 bool GenerateLineBeforePrologue = true;
2055 for (BasicBlock &BB : F) {
2057
2058 for (Instruction &I : BB) {
2059 LLVM_DEBUG(dbgs() << "\nInstruction: '" << I << "'\n");
2060
2061 if (const auto *DL =
2062 cast_or_null<DILocation>(I.getMetadata(LLVMContext::MD_dbg))) {
2063 LLVM_DEBUG({
2064 dbgs() << " Location: ";
2065 DL->dump(TheModule);
2066 });
2067 getOrCreateAbstractScope(DL);
2068 }
2069
2070 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
2071 HandleDbgVariable(&DVR);
2072
2073 if (options().getPrintAnyLine())
2074 constructLine(Scope, SP, I, GenerateLineBeforePrologue);
2075
2076 InstrLineAddrMap[I.getIterator().getNodePtr()] = CurrentOffset;
2077
2078 // Update code offset.
2079 updateLineOffset();
2080 }
2081 InstrLineAddrMap[BB.end().getNodePtr()] = CurrentOffset;
2082 }
2083 GenerateLineBeforePrologue = false;
2084
2085 if (AddUnspecifiedParameters) {
2086 LVElement *Parameter = createElement(dwarf::DW_TAG_unspecified_parameters);
2087 if (Parameter) {
2088 Parameter->setIsFinalized();
2089 Scope->addElement(Parameter);
2090 }
2091 }
2092
2093 LLVM_DEBUG({ dbgs() << "\nTraverse seen debug variables\n"; });
2094 for (const DebugVariableAggregate &DVA : SeenVars) {
2095 LLVM_DEBUG({ DbgValueRanges->printValues(DVA, dbgs()); });
2096 DILocalVariable *LV = const_cast<DILocalVariable *>(DVA.getVariable());
2097 LVSymbol *Symbol = getSymbolForSeenMD(LV);
2098 // Undefined only value, ignore.
2099 if (!Symbol)
2100 continue;
2101
2102 LLVM_DEBUG({
2103 DIType *Ty = LV->getType();
2104 uint64_t Size = Ty ? Ty->getSizeInBits() / CHAR_BIT : 1;
2105 LV->dump(TheModule);
2106 Ty->dump(TheModule);
2107 dbgs() << "Type size: " << Size << "\n";
2108 });
2109
2110 auto AddLocationOp = [&](Value *V, bool IsMem) {
2111 uint64_t RegValue = ValueNameMap.addValue(V);
2112 if (IsMem)
2113 Symbol->addLocationOperands(dwarf::DW_OP_bregx, {RegValue, 0});
2114 else
2115 Symbol->addLocationOperands(dwarf::DW_OP_regx, RegValue);
2116 };
2117
2118 auto AddLocation = [&](DbgValueDef DV) {
2119 bool IsMem = DV.IsMemory;
2120 DIExpression *CanonicalExpr = const_cast<DIExpression *>(
2122 RawLocationWrapper Locations(DV.Locations);
2123 for (DIExpression::ExprOperand ExprOp : CanonicalExpr->expr_ops()) {
2124 if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg) {
2125 AddLocationOp(Locations.getVariableLocationOp(ExprOp.getArg(0)),
2126 IsMem);
2127 } else {
2128 if (ExprOp.getOp() > std::numeric_limits<uint8_t>::max())
2129 LLVM_DEBUG(dbgs() << "Bad DWARF op: " << ExprOp.getOp() << "\n");
2130 uint8_t ShortOp = (uint8_t)ExprOp.getOp();
2131 Symbol->addLocationOperands(
2132 ShortOp,
2133 ArrayRef<uint64_t>(std::next(ExprOp.get()), ExprOp.getNumArgs()));
2134 }
2135 }
2136 };
2137
2138 if (DbgValueRanges->hasSingleLocEntry(DVA)) {
2139 DbgValueDef DV = DbgValueRanges->getSingleLoc(DVA);
2140 Symbol->addLocation(llvm::dwarf::DW_AT_location, /*LowPC=*/0,
2141 /*HighPC=*/-1, /*SectionOffset=*/0,
2142 /*OffsetOnEntry=*/0);
2143 assert(DV.IsMemory && "Single location should be memory!");
2144 AddLocation(DV);
2145 } else {
2146 for (const DbgRangeEntry &Entry :
2147 DbgValueRanges->getVariableRanges(DVA)) {
2148 // These line addresses should have already been inserted into the
2149 // InstrLineAddrMap, so we assume they are present here.
2150 LVOffset Start = InstrLineAddrMap.at(Entry.Start.getNodePtr());
2151 LVOffset End = InstrLineAddrMap.at(Entry.End.getNodePtr());
2152 Symbol->addLocation(llvm::dwarf::DW_AT_location, Start, End,
2153 /*SectionOffset=*/0, /*OffsetOnEntry=*/0);
2154 DbgValueDef DV = Entry.Value;
2155 AddLocation(DV);
2156 }
2157 }
2158 }
2159}
2160
2161//===----------------------------------------------------------------------===//
2162// IR Reader entry point.
2163//===----------------------------------------------------------------------===//
2165 LLVM_DEBUG({
2166 W.startLine() << "\n";
2167 W.printString("File", getFilename());
2168 W.printString("Format", FileFormatName);
2169 });
2170
2171 // The IR Reader supports only debug records.
2172 // We identify the debug input format and if it is intrinsics, it is
2173 // converted to the debug records.
2174 if (Error Err = LVReader::createScopes())
2175 return Err;
2176
2177 LLVMContext Context;
2178 SMDiagnostic Err;
2179 std::unique_ptr<Module> M =
2180 parseIR(isa<IRObjectFile *>(InputFile)
2181 ? cast<IRObjectFile *>(InputFile)->getMemoryBufferRef()
2182 : *(cast<MemoryBufferRef *>(InputFile)),
2183 Err, Context);
2184 if (!M) {
2185 // Print explanatory error message.
2186 if (options().getWarningAll())
2187 Err.print("", outs());
2189 "Could not create IR module for: %s",
2190 getFilename().str().c_str());
2191 }
2192
2193 TheModule = M.get();
2194 if (!TheModule->getNamedMetadata("llvm.dbg.cu")) {
2195 LLVM_DEBUG(dbgs() << "Skipping module without debug info\n");
2196 return Error::success();
2197 }
2198
2199 DwarfVersion = TheModule->getDwarfVersion();
2200
2201 LLVM_DEBUG({ dbgs() << "\nProcess CompileUnits\n"; });
2202 for (const DICompileUnit *CU : TheModule->debug_compile_units()) {
2203 LLVM_DEBUG({
2204 dbgs() << "\nCU: ";
2205 CU->dump(TheModule);
2206 });
2207
2208 CompileUnit = static_cast<LVScopeCompileUnit *>(constructElement(CU));
2209 CUNode = const_cast<DICompileUnit *>(CU);
2210
2211 const DIFile *File = CU->getFile();
2212 CompileUnit->setName(File->getFilename());
2213 CompileUnit->setCompilationDirectory(File->getDirectory());
2214 CompileUnit->setIsFinalized();
2215
2216 Root->addElement(CompileUnit);
2217
2218 // As the IR format uses the DWARF symbolic constants, the setting
2219 // of the source language must use the DWARF language definitions.
2220 uint16_t LanguageName = CU->getSourceLanguage().getName();
2222 static_cast<llvm::dwarf::SourceLanguage>(LanguageName));
2223 setDefaultLowerBound(&SL);
2224
2225 if (options().getAttributeLanguage())
2226 CompileUnit->setSourceLanguage(SL);
2227
2228 if (options().getAttributeProducer())
2229 CompileUnit->setProducer(CU->getProducer());
2230
2231 // Global Variables.
2232 LLVM_DEBUG({ dbgs() << "\nGlobal Variables\n"; });
2233 for (const DIGlobalVariableExpression *GVE : CU->getGlobalVariables())
2234 getOrCreateVariable(GVE);
2235
2236 // The enumeration types need to be created, regardless if they are
2237 // nested to any other aggregate type, as they are not included in
2238 // their elements. But their scope is correct (aggregate).
2239 LLVM_DEBUG({ dbgs() << "\nEnumeration Types\n"; });
2240 for (auto *ET : CU->getEnumTypes())
2241 getOrCreateType(ET);
2242
2243 // Retained types.
2244 LLVM_DEBUG({ dbgs() << "\nRetained Types\n"; });
2245 for (const auto *RT : CU->getRetainedTypes()) {
2246 if (const auto *Ty = dyn_cast<DIType>(RT)) {
2247 getOrCreateType(Ty);
2248 } else {
2249 getOrCreateSubprogram(cast<DISubprogram>(RT));
2250 }
2251 }
2252
2253 // Imported entities.
2254 LLVM_DEBUG({ dbgs() << "\nImported Entities\n"; });
2255 for (const auto *IE : CU->getImportedEntities())
2256 constructImportedEntity(CompileUnit, IE);
2257 }
2258
2259 // Traverse Functions.
2260 LLVM_DEBUG({
2261 dbgs() << "\nFunctions\n";
2262 for (Function &F : M->getFunctionList())
2263 if (const auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
2264 SP->dump(TheModule);
2265 });
2266
2267 for (Function &F : M->getFunctionList())
2268 processBasicBlocks(F);
2269
2270 // Perform extra tasks on the created scopes.
2271 resolveInlinedLexicalScopes();
2272 removeEmptyScopes();
2273
2274 processLocationGaps();
2275 processScopes();
2276
2277 if (options().getInternalIntegrity())
2278 checkScopes(CompileUnit);
2279
2280 TheModule = nullptr;
2281 return Error::success();
2282}
2283
2284void LVIRReader::constructRange(LVScope *Scope, LVAddress LowPC,
2285 LVAddress HighPC) {
2286 assert(Scope && "Invalid logical element");
2287 LLVM_DEBUG({
2288 dbgs() << "\n[constructRange]\n";
2289 dbgs() << "ID: " << hexString(Scope->getID()) << " ";
2290 dbgs() << "LowPC: " << hexString(LowPC) << " ";
2291 dbgs() << "HighPC: " << hexString(HighPC) << " ";
2292 dbgs() << "Name: " << Scope->getName() << "\n";
2293 });
2294
2295 // Process ranges base on logical lines.
2296 Scope->addObject(LowPC, HighPC);
2297 if (!Scope->getIsCompileUnit()) {
2298 // If the scope is a function, add it to the public names.
2299 if ((options().getAttributePublics() || options().getPrintAnyLine()) &&
2300 Scope->getIsFunction() && !Scope->getIsInlinedFunction())
2301 CompileUnit->addPublicName(Scope, LowPC, HighPC);
2302 }
2303 addSectionRange(/*SectionIndex=*/0, Scope, LowPC, HighPC);
2304
2305 // Replicate DWARF reader funtionality of processing DW_AT_ranges for
2306 // the compilation unit.
2307 CompileUnit->addObject(LowPC, HighPC);
2308 addSectionRange(/*SectionIndex=*/0, CompileUnit, LowPC, HighPC);
2309}
2310
2311// Create the location ranges for the given scope and in the case of
2312// functions, generate an entry in the public names set.
2313void LVIRReader::constructRange(LVScope *Scope) {
2314 LLVM_DEBUG({
2315 dbgs() << "\n[constructRange]\n";
2316 dbgs() << "ID: " << hexString(Scope->getID()) << " ";
2317 dbgs() << "Name: " << Scope->getName() << "\n\n";
2318 });
2319
2320 auto NextRange = [&](LVAddress Offset) -> LVAddress {
2321 return Offset + OFFSET_INCREASE - 1;
2322 };
2323
2324 // Get any logical lines.
2325 const LVLines *Lines = Scope->getLines();
2326 if (!Lines)
2327 return;
2328
2329 // Traverse the logical lines and build the logical ranges.
2330 LVAddress Lower = 0;
2331 LVAddress Upper = 0;
2332 LVAddress Current = 0;
2333 LVAddress Previous = 0;
2334 for (const LVLine *Line : *Lines) {
2335 LLVM_DEBUG({
2336 dbgs() << "[" << hexString(Line->getAddress()) << "] ";
2337 dbgs() << "LineNo: " << decString(Line->getLineNumber()) << "\n";
2338 dbgs() << "Lower: " << hexString(Lower) << " ";
2339 dbgs() << "Upper: " << hexString(Upper) << " ";
2340 dbgs() << "Previous: " << hexString(Previous) << " ";
2341 dbgs() << "Current: " << hexString(Current) << "\n";
2342 });
2343 if (!Upper) {
2344 // First line in range.
2345 Lower = Line->getAddress();
2346 Upper = NextRange(Lower);
2347 Current = Lower;
2348 continue;
2349 }
2350 Previous = Current;
2351 Current = Line->getAddress();
2352 if (Current == Previous) {
2353 // Contiguous lines at the same address (Debug and its assembler).
2354 continue;
2355 }
2356 if (Current == Upper + 1) {
2357 // There is no gap.
2358 Upper = NextRange(Current);
2359 } else {
2360 // There is a gap.
2361 constructRange(Scope, Lower, Upper);
2362 Lower = Current;
2363 Upper = NextRange(Lower);
2364 }
2365 }
2366 constructRange(Scope, Lower, Upper);
2367}
2368
2369// At this point, all scopes for the compile unit have been created.
2370// The following aditional steps need to be performed on them:
2371// - If the lexical block doesn't have non-scope children, skip its
2372// emission and put its children directly to the parent scope.
2373// The '--internal=id' is turned on just for debugging traces. Then
2374// it is turned to its previous state.
2375void LVIRReader::removeEmptyScopes() {
2376 LLVM_DEBUG({ dbgs() << "\n[removeEmptyScopes]\n"; });
2377
2378 SmallVector<LVScope *> EmptyScopes;
2379
2380 // Delete lexically empty scopes.
2381 auto DeleteEmptyScopes = [&]() {
2382 if (EmptyScopes.empty())
2383 return;
2384
2385 LLVM_DEBUG({
2386 dbgs() << "\n** Collected empty scopes **\n";
2387 for (auto Scope : EmptyScopes)
2388 Scope->print(dbgs());
2389 });
2390
2391 LVScope *Parent = nullptr;
2392 for (auto Scope : EmptyScopes) {
2393 Parent = Scope->getParentScope();
2394 LLVM_DEBUG({
2395 dbgs() << "Scope: " << Scope->getID() << ", ";
2396 dbgs() << "Parent: " << Parent->getID() << "\n";
2397 });
2398
2399 // If the target scope has lines, move them to the scope parent.
2400 const LVLines *Lines = Scope->getLines();
2401 if (Lines) {
2402 LVLines Pack;
2403 std::copy(Lines->begin(), Lines->end(), std::back_inserter(Pack));
2404 for (LVLine *Line : Pack) {
2405 if (Scope->removeElement(Line)) {
2406 LLVM_DEBUG({ dbgs() << "Line: " << Line->getID() << "\n"; });
2407 Line->resetParent();
2408 Parent->addElement(Line);
2409 Line->updateLevel(Parent, /*Moved=*/false);
2410 }
2411 }
2412 }
2413
2414 if (Parent->removeElement(Scope)) {
2415 const LVScopes *Scopes = Scope->getScopes();
2416 if (Scopes) {
2417 for (LVScope *Child : *Scopes) {
2418 LLVM_DEBUG({ dbgs() << "Child: " << Child->getID() << "\n"; });
2419 Child->resetParent();
2420 Parent->addElement(Child);
2421 Child->updateLevel(Parent, /*Moved=*/false);
2422 }
2423 }
2424 }
2425 }
2426 };
2427
2428 // Traverse the scopes tree and collect those lexical blocks that do not
2429 // have non-scope children. Do not include the lines as they are included
2430 // in the logical view as a way to show their associated logical scope.
2431 std::function<void(LVScope *)> TraverseScope = [&](LVScope *Current) {
2432 auto IsEmpty = [](LVScope *Scope) -> bool {
2433 return !Scope->getSymbols() && !Scope->getTypes() && !Scope->getRanges();
2434 };
2435
2436 if (const LVScopes *Scopes = Current->getScopes()) {
2437 for (LVScope *Scope : *Scopes) {
2438 if (Scope->getIsLexicalBlock() && IsEmpty(Scope))
2439 EmptyScopes.push_back(Scope);
2440 TraverseScope(Scope);
2441 }
2442 }
2443 };
2444
2445 // Preserve current setting for '--internal=id'.
2446 bool InternalID = options().getInternalID();
2447 llvm::scope_exit ResetSetting([&] {
2448 // Restore setting for '--internal=id'.
2449 if (!InternalID)
2450 options().resetInternalID();
2451 });
2452 options().setInternalID();
2453
2454 LLVM_DEBUG({
2455 dbgs() << "\nBefore - RemoveEmptyScopes\n";
2457 });
2458
2459 TraverseScope(CompileUnit);
2460 DeleteEmptyScopes();
2461
2462 LLVM_DEBUG({
2463 dbgs() << "\nAfter - RemoveEmptyScopes\n";
2465 });
2466}
2467
2468// The IR generated by Clang, allocates the inlined lexical scopes
2469// at the enclosing function level. Move them to the correct scope.
2470void LVIRReader::resolveInlinedLexicalScopes() {
2471 LLVM_DEBUG({ dbgs() << "\n[resolveInlinedLexicalScopes]\n"; });
2472 LLVM_DEBUG({ dumpInlinedInfo("Before", /*Full=*/false); });
2473
2474 std::function<void(LVScope * Scope)> TraverseChildren = [&](LVScope *Parent) {
2475 LLVM_DEBUG({
2476 dbgs() << "\nParent Scope: ";
2477 Parent->dumpCommon();
2478 });
2479
2480 // Get associated inlined scopes for the parent scope.
2481 LVList &ParentInlinedList = getInlinedList(Parent);
2482
2483 // Check if the inlined scope parent is in the ParentInlinedList.
2484 auto CheckInlinedScope = [&](LVList &ScopeInlinedList) -> bool {
2485 bool Matched = true;
2486 for (auto &InlinedScope : ScopeInlinedList) {
2487 LLVM_DEBUG({
2488 dbgs() << "Inlined Scope: ";
2489 InlinedScope->dumpCommon();
2490 });
2491 LVScope *ParentScope = InlinedScope->getParentScope();
2492 for (auto &ParentInlinedScope : ParentInlinedList) {
2493 if (ParentInlinedScope != ParentScope) {
2494 // If the parent for the inlined scope is not the Parent Inlined
2495 // list, it means the lexical scope is incorrect.
2496 // Stop the traversal as the other inlined scopes will have the
2497 // same problem as they were created from the same original scope.
2498 LLVM_DEBUG({
2499 dbgs() << "\nIncorrect parent scope\n";
2500 dbgs() << "ParentInlinedScope: ";
2501 ParentInlinedScope->dumpCommon();
2502 dbgs() << "ParentScope: ";
2503 ParentScope->dumpCommon();
2504 dbgs() << "\n";
2505 });
2506 Matched = false;
2507 break;
2508 }
2509 }
2510 if (!Matched)
2511 break;
2512 }
2513 return Matched;
2514 };
2515
2516 // Adjust the inlined scopes based on the ParentInlinedList.
2517 auto AdjustInlinedScope = [&](LVList &ScopeInlinedList) {
2518 assert(ScopeInlinedList.size() == ParentInlinedList.size() &&
2519 "Scope list do not have same number of items.");
2520
2521 LLVM_DEBUG({ dbgs() << "Begin scope adjustment\n"; });
2522 LVScope *CurrentParent = nullptr;
2523 LVScope *TargetParent = nullptr;
2524 LVScope *InlinedScope = nullptr;
2525 auto ItInlined = ScopeInlinedList.begin();
2526 auto ItParent = ParentInlinedList.begin();
2527 while (ItInlined != ScopeInlinedList.end()) {
2528 TargetParent = *ItParent;
2529 InlinedScope = *ItInlined;
2530 CurrentParent = InlinedScope->getParentScope();
2531
2532 LLVM_DEBUG({
2533 dbgs() << "Target Parent: ";
2534 TargetParent->dumpCommon();
2535 dbgs() << "Current Parent: ";
2536 CurrentParent->dumpCommon();
2537 dbgs() << "Inlined: ";
2538 InlinedScope->dumpCommon();
2539 });
2540
2541 // Correct lexical scope.
2542 if (CurrentParent->removeElement(InlinedScope)) {
2543 TargetParent->addElement(InlinedScope);
2544 InlinedScope->updateLevel(TargetParent, /*Moved=*/false);
2545 }
2546 ++ItInlined;
2547 ++ItParent;
2548 }
2549 LLVM_DEBUG({ dbgs() << "End scope adjustment\n"; });
2550 };
2551
2552 // Traverse the scope children.
2553 if (const LVScopes *Children = Parent->getScopes())
2554 for (LVScope *Scope : *Children) {
2555 LLVM_DEBUG({
2556 dbgs() << "\nOrigin Scope: ";
2557 Scope->dumpCommon();
2558 });
2559
2560 // Get associated inlined scopes for the scope.
2561 LVList &ScopeInlinedList = getInlinedList(Scope);
2562 if (!CheckInlinedScope(ScopeInlinedList)) {
2563 // AdjustInlinedScope to the correct lexical scope.
2564 AdjustInlinedScope(ScopeInlinedList);
2565 }
2566 TraverseChildren(Scope);
2567 }
2568 };
2569
2570 // Traverse the origin scopes and for each function scope, analyze their
2571 // associated inlined scopes to see if they have to be move to their
2572 // correct lexical scope.
2573 for (auto &Entry : InlinedList) {
2574 LVScope *OriginScope = Entry.first;
2575 if (OriginScope->getIsFunction())
2576 TraverseChildren(OriginScope);
2577 }
2578
2579 LLVM_DEBUG({ dumpInlinedInfo("After", /*Full=*/false); });
2580}
2581
2582// During the IR-to-logical-view construction, traverse all the logical
2583// elements to check if they have been properly constructed (finalized).
2584void LVIRReader::checkScopes(LVScope *Scope) {
2585 LLVM_DEBUG({ dbgs() << "\n[checkScopes]\n"; });
2586
2587 auto PrintElement = [](LVElement *Element) {
2588 LLVM_DEBUG({
2589 dwarf::Tag Tag = Element->getTag();
2590 size_t ID = Element->getID();
2591 const char *Kind = Element->kind();
2592 StringRef Name = Element->getName();
2593 uint32_t LineNumber = Element->getLineNumber();
2594 dbgs() << "Tag: "
2595 << formatv("{0} ", fmt_align(Tag, AlignStyle::Left, 35));
2596 dbgs() << "ID: " << formatv("{0} ", fmt_align(ID, AlignStyle::Left, 5));
2597 dbgs() << "Kind: "
2598 << formatv("{0} ", fmt_align(Kind, AlignStyle::Left, 15));
2599 dbgs() << "Line: "
2600 << formatv("{0} ", fmt_align(LineNumber, AlignStyle::Left, 5));
2601 dbgs() << "Name: '" << std::string(Name) << "' ";
2602 dbgs() << "\n";
2603 });
2604 };
2605
2606 std::function<void(LVScope * Parent)> Traverse = [&](LVScope *Current) {
2607 auto Check = [&](auto *Entry) {
2608 if (Entry)
2609 if (!Entry->getIsFinalized())
2610 PrintElement(Entry);
2611 };
2612
2613 for (LVElement *Element : Current->getChildren())
2614 Check(Element);
2615
2616 if (Current->getScopes())
2617 for (LVScope *Scope : *Current->getScopes())
2618 Traverse(Scope);
2619 };
2620
2621 // Start traversing the scopes root and check its integrity.
2622 Traverse(Scope);
2623}
2624
2625void LVIRReader::sortScopes() { Root->sort(); }
2626
2628 OS << "LVIRReader\n";
2629 LLVM_DEBUG(dbgs() << "CreateReaders\n");
2630}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:1436
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