1//===- LLVMContextImpl.h - The LLVMContextImpl opaque class -----*- C++ -*-===//
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 file declares LLVMContextImpl, the opaque implementation
10// of LLVMContext.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_LIB_IR_LLVMCONTEXTIMPL_H
15#define LLVM_LIB_IR_LLVMCONTEXTIMPL_H
16
17#include "AttributeImpl.h"
18#include "ConstantsContext.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/DenseMapInfo.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/FoldingSet.h"
26#include "llvm/ADT/Hashing.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/BinaryFormat/Dwarf.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DebugInfoMetadata.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/TrackingMDRef.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Support/Allocator.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/LibraryOptionsContext.h"
44#include "llvm/Support/StringSaver.h"
45#include "llvm/Support/VirtualFileSystem.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdint>
50#include <memory>
51#include <optional>
52#include <string>
53#include <utility>
54#include <vector>
55
56namespace llvm {
57
58class BasicBlock;
59struct DiagnosticHandler;
60class DbgMarker;
61class ElementCount;
62class Function;
63class GlobalObject;
64class GlobalValue;
65class InlineAsm;
66class LLVMRemarkStreamer;
67class OptPassGate;
68namespace remarks {
69class RemarkStreamer;
70}
71template <typename T> class StringMapEntry;
72class StringRef;
73class TypedPointerType;
74class ValueHandleBase;
75
76template <> struct DenseMapInfo<APFloat> {
77 static unsigned getHashValue(const APFloat &Key) {
78 return static_cast<unsigned>(hash_value(Arg: Key));
79 }
80
81 static bool isEqual(const APFloat &LHS, const APFloat &RHS) {
82 return LHS.bitwiseIsEqual(RHS);
83 }
84};
85
86struct AnonStructTypeKeyInfo {
87 struct KeyTy {
88 ArrayRef<Type *> ETypes;
89 bool isPacked;
90
91 KeyTy(const ArrayRef<Type *> &E, bool P) : ETypes(E), isPacked(P) {}
92
93 KeyTy(const StructType *ST)
94 : ETypes(ST->elements()), isPacked(ST->isPacked()) {}
95
96 bool operator==(const KeyTy &that) const {
97 if (isPacked != that.isPacked)
98 return false;
99 if (ETypes != that.ETypes)
100 return false;
101 return true;
102 }
103 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
104 };
105
106 static unsigned getHashValue(const KeyTy &Key) {
107 return hash_combine(args: hash_combine_range(R: Key.ETypes), args: Key.isPacked);
108 }
109
110 static unsigned getHashValue(const StructType *ST) {
111 return getHashValue(Key: KeyTy(ST));
112 }
113
114 static bool isEqual(const KeyTy &LHS, const StructType *RHS) {
115 return LHS == KeyTy(RHS);
116 }
117
118 static bool isEqual(const StructType *LHS, const StructType *RHS) {
119 return LHS == RHS;
120 }
121};
122
123struct FunctionTypeKeyInfo {
124 struct KeyTy {
125 const Type *ReturnType;
126 ArrayRef<Type *> Params;
127 bool isVarArg;
128
129 KeyTy(const Type *R, const ArrayRef<Type *> &P, bool V)
130 : ReturnType(R), Params(P), isVarArg(V) {}
131 KeyTy(const FunctionType *FT)
132 : ReturnType(FT->getReturnType()), Params(FT->params()),
133 isVarArg(FT->isVarArg()) {}
134
135 bool operator==(const KeyTy &that) const {
136 if (ReturnType != that.ReturnType)
137 return false;
138 if (isVarArg != that.isVarArg)
139 return false;
140 if (Params != that.Params)
141 return false;
142 return true;
143 }
144 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
145 };
146
147 static unsigned getHashValue(const KeyTy &Key) {
148 return hash_combine(args: Key.ReturnType, args: hash_combine_range(R: Key.Params),
149 args: Key.isVarArg);
150 }
151
152 static unsigned getHashValue(const FunctionType *FT) {
153 return getHashValue(Key: KeyTy(FT));
154 }
155
156 static bool isEqual(const KeyTy &LHS, const FunctionType *RHS) {
157 return LHS == KeyTy(RHS);
158 }
159
160 static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
161 return LHS == RHS;
162 }
163};
164
165struct TargetExtTypeKeyInfo {
166 struct KeyTy {
167 StringRef Name;
168 ArrayRef<Type *> TypeParams;
169 ArrayRef<unsigned> IntParams;
170
171 KeyTy(StringRef N, const ArrayRef<Type *> &TP, const ArrayRef<unsigned> &IP)
172 : Name(N), TypeParams(TP), IntParams(IP) {}
173 KeyTy(const TargetExtType *TT)
174 : Name(TT->getName()), TypeParams(TT->type_params()),
175 IntParams(TT->int_params()) {}
176
177 bool operator==(const KeyTy &that) const {
178 return Name == that.Name && TypeParams == that.TypeParams &&
179 IntParams == that.IntParams;
180 }
181 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
182 };
183
184 static unsigned getHashValue(const KeyTy &Key) {
185 return hash_combine(args: Key.Name, args: hash_combine_range(R: Key.TypeParams),
186 args: hash_combine_range(R: Key.IntParams));
187 }
188
189 static unsigned getHashValue(const TargetExtType *FT) {
190 return getHashValue(Key: KeyTy(FT));
191 }
192
193 static bool isEqual(const KeyTy &LHS, const TargetExtType *RHS) {
194 return LHS == KeyTy(RHS);
195 }
196
197 static bool isEqual(const TargetExtType *LHS, const TargetExtType *RHS) {
198 return LHS == RHS;
199 }
200};
201
202/// Structure for hashing arbitrary MDNode operands.
203class MDNodeOpsKey {
204 ArrayRef<Metadata *> RawOps;
205 ArrayRef<MDOperand> Ops;
206 unsigned Hash;
207
208protected:
209 MDNodeOpsKey(ArrayRef<Metadata *> Ops)
210 : RawOps(Ops), Hash(calculateHash(Ops)) {}
211
212 template <class NodeTy>
213 MDNodeOpsKey(const NodeTy *N, unsigned Offset = 0)
214 : Ops(N->op_begin() + Offset, N->op_end()), Hash(N->getHash()) {}
215
216 template <class NodeTy>
217 bool compareOps(const NodeTy *RHS, unsigned Offset = 0) const {
218 if (getHash() != RHS->getHash())
219 return false;
220
221 assert((RawOps.empty() || Ops.empty()) && "Two sets of operands?");
222 return RawOps.empty() ? compareOps(Ops, RHS, Offset)
223 : compareOps(RawOps, RHS, Offset);
224 }
225
226 static unsigned calculateHash(MDNode *N, unsigned Offset = 0);
227
228private:
229 template <class T>
230 static bool compareOps(ArrayRef<T> Ops, const MDNode *RHS, unsigned Offset) {
231 if (Ops.size() != RHS->getNumOperands() - Offset)
232 return false;
233 return std::equal(Ops.begin(), Ops.end(), RHS->op_begin() + Offset);
234 }
235
236 static unsigned calculateHash(ArrayRef<Metadata *> Ops);
237
238public:
239 unsigned getHash() const { return Hash; }
240};
241
242template <class NodeTy> struct MDNodeKeyImpl;
243
244/// Configuration point for MDNodeInfo::isEqual().
245template <class NodeTy> struct MDNodeSubsetEqualImpl {
246 using KeyTy = MDNodeKeyImpl<NodeTy>;
247
248 static bool isSubsetEqual(const KeyTy &LHS, const NodeTy *RHS) {
249 return false;
250 }
251
252 static bool isSubsetEqual(const NodeTy *LHS, const NodeTy *RHS) {
253 return false;
254 }
255};
256
257/// DenseMapInfo for MDTuple.
258///
259/// Note that we don't need the is-function-local bit, since that's implicit in
260/// the operands.
261template <> struct MDNodeKeyImpl<MDTuple> : MDNodeOpsKey {
262 MDNodeKeyImpl(ArrayRef<Metadata *> Ops) : MDNodeOpsKey(Ops) {}
263 MDNodeKeyImpl(const MDTuple *N) : MDNodeOpsKey(N) {}
264
265 bool isKeyOf(const MDTuple *RHS) const { return compareOps(RHS); }
266
267 unsigned getHashValue() const { return getHash(); }
268
269 static unsigned calculateHash(MDTuple *N) {
270 return MDNodeOpsKey::calculateHash(N);
271 }
272};
273
274/// DenseMapInfo for DILocation.
275template <> struct MDNodeKeyImpl<DILocation> {
276 Metadata *Scope;
277 Metadata *InlinedAt;
278 Metadata *IRLayers;
279 uint64_t AtomGroup : 60;
280 uint64_t AtomRank : 3;
281 unsigned Line;
282 uint16_t Column;
283 bool ImplicitCode;
284
285 MDNodeKeyImpl(unsigned Line, uint16_t Column, Metadata *Scope,
286 Metadata *InlinedAt, bool ImplicitCode, uint64_t AtomGroup,
287 uint8_t AtomRank, Metadata *IRLayers)
288 : Scope(Scope), InlinedAt(InlinedAt), IRLayers(IRLayers),
289 AtomGroup(AtomGroup), AtomRank(AtomRank), Line(Line), Column(Column),
290 ImplicitCode(ImplicitCode) {}
291
292 MDNodeKeyImpl(const DILocation *L)
293 : Scope(L->getRawScope()), InlinedAt(L->getRawInlinedAt()),
294 IRLayers(L->getRawIRLayers()), AtomGroup(L->getAtomGroup()),
295 AtomRank(L->getAtomRank()), Line(L->getLine()), Column(L->getColumn()),
296 ImplicitCode(L->isImplicitCode()) {}
297
298 bool isKeyOf(const DILocation *RHS) const {
299 return Line == RHS->getLine() && Column == RHS->getColumn() &&
300 Scope == RHS->getRawScope() && InlinedAt == RHS->getRawInlinedAt() &&
301 ImplicitCode == RHS->isImplicitCode() &&
302 AtomGroup == RHS->getAtomGroup() && AtomRank == RHS->getAtomRank() &&
303 IRLayers == RHS->getRawIRLayers();
304 }
305
306 unsigned getHashValue() const {
307 uint64_t LineColumnAndImplicitCode =
308 Line | (uint64_t(Column) << 32) | (uint64_t(ImplicitCode) << 48);
309 // Hashing AtomGroup and AtomRank substantially impacts performance whether
310 // Key Instructions is enabled or not. We can't detect whether it's enabled
311 // here cheaply; avoiding hashing zero values is a good approximation. This
312 // affects Key Instruction builds too, but any potential costs incurred by
313 // messing with the hash distribution* appear to still be massively
314 // outweighed by the overall compile time savings by performing this check.
315 // * (hash_combine(x) != hash_combine(x, 0))
316 // irlayers is likewise rare, so it is only mixed in when present to keep
317 // the common no-layers hashes unchanged.
318 if (AtomGroup || AtomRank) {
319 if (IRLayers)
320 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
321 args: AtomGroup | (uint64_t(AtomRank) << 61), args: IRLayers);
322 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
323 args: AtomGroup | (uint64_t(AtomRank) << 61));
324 }
325 if (IRLayers)
326 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
327 args: IRLayers);
328 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt);
329 }
330};
331
332/// DenseMapInfo for DILayerLoc.
333template <> struct MDNodeKeyImpl<DILayerLoc> {
334 Metadata *Kind;
335 Metadata *File;
336 unsigned Line;
337 uint16_t Column;
338
339 MDNodeKeyImpl(Metadata *Kind, Metadata *File, unsigned Line, uint16_t Column)
340 : Kind(Kind), File(File), Line(Line), Column(Column) {}
341 MDNodeKeyImpl(const DILayerLoc *N)
342 : Kind(N->getRawKind()), File(N->getRawFile()), Line(N->getLine()),
343 Column(N->getColumn()) {}
344
345 bool isKeyOf(const DILayerLoc *RHS) const {
346 return Kind == RHS->getRawKind() && File == RHS->getRawFile() &&
347 Line == RHS->getLine() && Column == RHS->getColumn();
348 }
349
350 unsigned getHashValue() const {
351 return hash_combine(args: Kind, args: File, args: Line, args: Column);
352 }
353};
354
355/// DenseMapInfo for DILayerLocList.
356template <> struct MDNodeKeyImpl<DILayerLocList> : MDNodeOpsKey {
357 MDNodeKeyImpl(ArrayRef<Metadata *> Ops) : MDNodeOpsKey(Ops) {}
358 MDNodeKeyImpl(const DILayerLocList *N) : MDNodeOpsKey(N) {}
359
360 bool isKeyOf(const DILayerLocList *RHS) const { return compareOps(RHS); }
361
362 unsigned getHashValue() const { return getHash(); }
363
364 static unsigned calculateHash(DILayerLocList *N) {
365 return MDNodeOpsKey::calculateHash(N);
366 }
367};
368
369/// DenseMapInfo for GenericDINode.
370template <> struct MDNodeKeyImpl<GenericDINode> : MDNodeOpsKey {
371 unsigned Tag;
372 MDString *Header;
373
374 MDNodeKeyImpl(unsigned Tag, MDString *Header, ArrayRef<Metadata *> DwarfOps)
375 : MDNodeOpsKey(DwarfOps), Tag(Tag), Header(Header) {}
376 MDNodeKeyImpl(const GenericDINode *N)
377 : MDNodeOpsKey(N, 1), Tag(N->getTag()), Header(N->getRawHeader()) {}
378
379 bool isKeyOf(const GenericDINode *RHS) const {
380 return Tag == RHS->getTag() && Header == RHS->getRawHeader() &&
381 compareOps(RHS, Offset: 1);
382 }
383
384 unsigned getHashValue() const { return hash_combine(args: getHash(), args: Tag, args: Header); }
385
386 static unsigned calculateHash(GenericDINode *N) {
387 return MDNodeOpsKey::calculateHash(N, Offset: 1);
388 }
389};
390
391template <> struct MDNodeKeyImpl<DISubrange> {
392 Metadata *CountNode;
393 Metadata *LowerBound;
394 Metadata *UpperBound;
395 Metadata *Stride;
396
397 MDNodeKeyImpl(Metadata *CountNode, Metadata *LowerBound, Metadata *UpperBound,
398 Metadata *Stride)
399 : CountNode(CountNode), LowerBound(LowerBound), UpperBound(UpperBound),
400 Stride(Stride) {}
401 MDNodeKeyImpl(const DISubrange *N)
402 : CountNode(N->getRawCountNode()), LowerBound(N->getRawLowerBound()),
403 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()) {}
404
405 bool isKeyOf(const DISubrange *RHS) const {
406 auto BoundsEqual = [=](Metadata *Node1, Metadata *Node2) -> bool {
407 if (Node1 == Node2)
408 return true;
409
410 ConstantAsMetadata *MD1 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node1);
411 ConstantAsMetadata *MD2 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node2);
412 if (MD1 && MD2) {
413 ConstantInt *CV1 = cast<ConstantInt>(Val: MD1->getValue());
414 ConstantInt *CV2 = cast<ConstantInt>(Val: MD2->getValue());
415 if (CV1->getSExtValue() == CV2->getSExtValue())
416 return true;
417 }
418 return false;
419 };
420
421 return BoundsEqual(CountNode, RHS->getRawCountNode()) &&
422 BoundsEqual(LowerBound, RHS->getRawLowerBound()) &&
423 BoundsEqual(UpperBound, RHS->getRawUpperBound()) &&
424 BoundsEqual(Stride, RHS->getRawStride());
425 }
426
427 unsigned getHashValue() const {
428 if (CountNode)
429 if (auto *MD = dyn_cast<ConstantAsMetadata>(Val: CountNode))
430 return hash_combine(args: cast<ConstantInt>(Val: MD->getValue())->getSExtValue(),
431 args: LowerBound, args: UpperBound, args: Stride);
432 return hash_combine(args: CountNode, args: LowerBound, args: UpperBound, args: Stride);
433 }
434};
435
436template <> struct MDNodeKeyImpl<DIGenericSubrange> {
437 Metadata *CountNode;
438 Metadata *LowerBound;
439 Metadata *UpperBound;
440 Metadata *Stride;
441
442 MDNodeKeyImpl(Metadata *CountNode, Metadata *LowerBound, Metadata *UpperBound,
443 Metadata *Stride)
444 : CountNode(CountNode), LowerBound(LowerBound), UpperBound(UpperBound),
445 Stride(Stride) {}
446 MDNodeKeyImpl(const DIGenericSubrange *N)
447 : CountNode(N->getRawCountNode()), LowerBound(N->getRawLowerBound()),
448 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()) {}
449
450 bool isKeyOf(const DIGenericSubrange *RHS) const {
451 return (CountNode == RHS->getRawCountNode()) &&
452 (LowerBound == RHS->getRawLowerBound()) &&
453 (UpperBound == RHS->getRawUpperBound()) &&
454 (Stride == RHS->getRawStride());
455 }
456
457 unsigned getHashValue() const {
458 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(Val: CountNode);
459 if (CountNode && MD)
460 return hash_combine(args: cast<ConstantInt>(Val: MD->getValue())->getSExtValue(),
461 args: LowerBound, args: UpperBound, args: Stride);
462 return hash_combine(args: CountNode, args: LowerBound, args: UpperBound, args: Stride);
463 }
464};
465
466template <> struct MDNodeKeyImpl<DIEnumerator> {
467 APInt Value;
468 MDString *Name;
469 bool IsUnsigned;
470
471 MDNodeKeyImpl(APInt Value, bool IsUnsigned, MDString *Name)
472 : Value(std::move(Value)), Name(Name), IsUnsigned(IsUnsigned) {}
473 MDNodeKeyImpl(int64_t Value, bool IsUnsigned, MDString *Name)
474 : Value(APInt(64, Value, !IsUnsigned)), Name(Name),
475 IsUnsigned(IsUnsigned) {}
476 MDNodeKeyImpl(const DIEnumerator *N)
477 : Value(N->getValue()), Name(N->getRawName()),
478 IsUnsigned(N->isUnsigned()) {}
479
480 bool isKeyOf(const DIEnumerator *RHS) const {
481 return Value.getBitWidth() == RHS->getValue().getBitWidth() &&
482 Value == RHS->getValue() && IsUnsigned == RHS->isUnsigned() &&
483 Name == RHS->getRawName();
484 }
485
486 unsigned getHashValue() const { return hash_combine(args: Value, args: Name); }
487};
488
489template <> struct MDNodeKeyImpl<DIBasicType> {
490 unsigned Tag;
491 MDString *Name;
492 Metadata *File;
493 unsigned LineNo;
494 Metadata *Scope;
495 Metadata *SizeInBits;
496 uint32_t AlignInBits;
497 unsigned Encoding;
498 uint32_t NumExtraInhabitants;
499 uint32_t DataSizeInBits;
500 unsigned Flags;
501
502 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned LineNo,
503 Metadata *Scope, Metadata *SizeInBits, uint32_t AlignInBits,
504 unsigned Encoding, uint32_t NumExtraInhabitants,
505 uint32_t DataSizeInBits, unsigned Flags)
506 : Tag(Tag), Name(Name), File(File), LineNo(LineNo), Scope(Scope),
507 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
508 NumExtraInhabitants(NumExtraInhabitants),
509 DataSizeInBits(DataSizeInBits), Flags(Flags) {}
510 MDNodeKeyImpl(const DIBasicType *N)
511 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
512 LineNo(N->getLine()), Scope(N->getRawScope()),
513 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
514 Encoding(N->getEncoding()),
515 NumExtraInhabitants(N->getNumExtraInhabitants()),
516 DataSizeInBits(N->getDataSizeInBits()), Flags(N->getFlags()) {}
517
518 bool isKeyOf(const DIBasicType *RHS) const {
519 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
520 File == RHS->getRawFile() && LineNo == RHS->getLine() &&
521 Scope == RHS->getRawScope() &&
522 SizeInBits == RHS->getRawSizeInBits() &&
523 AlignInBits == RHS->getAlignInBits() &&
524 Encoding == RHS->getEncoding() &&
525 NumExtraInhabitants == RHS->getNumExtraInhabitants() &&
526 DataSizeInBits == RHS->getDataSizeInBits() &&
527 Flags == RHS->getFlags();
528 }
529
530 unsigned getHashValue() const {
531 return hash_combine(args: Tag, args: Name, args: File, args: LineNo, args: Scope, args: SizeInBits, args: AlignInBits,
532 args: Encoding);
533 }
534};
535
536template <> struct MDNodeKeyImpl<DIFixedPointType> {
537 unsigned Tag;
538 MDString *Name;
539 Metadata *File;
540 unsigned LineNo;
541 Metadata *Scope;
542 Metadata *SizeInBits;
543 uint32_t AlignInBits;
544 unsigned Encoding;
545 unsigned Flags;
546 unsigned Kind;
547 int Factor;
548 APInt Numerator;
549 APInt Denominator;
550
551 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned LineNo,
552 Metadata *Scope, Metadata *SizeInBits, uint32_t AlignInBits,
553 unsigned Encoding, unsigned Flags, unsigned Kind, int Factor,
554 APInt Numerator, APInt Denominator)
555 : Tag(Tag), Name(Name), File(File), LineNo(LineNo), Scope(Scope),
556 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
557 Flags(Flags), Kind(Kind), Factor(Factor), Numerator(Numerator),
558 Denominator(Denominator) {}
559 MDNodeKeyImpl(const DIFixedPointType *N)
560 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
561 LineNo(N->getLine()), Scope(N->getRawScope()),
562 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
563 Encoding(N->getEncoding()), Flags(N->getFlags()), Kind(N->getKind()),
564 Factor(N->getFactorRaw()), Numerator(N->getNumeratorRaw()),
565 Denominator(N->getDenominatorRaw()) {}
566
567 bool isKeyOf(const DIFixedPointType *RHS) const {
568 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
569 LineNo == RHS->getLine() && Scope == RHS->getRawScope() &&
570 SizeInBits == RHS->getRawSizeInBits() &&
571 AlignInBits == RHS->getAlignInBits() && Kind == RHS->getKind() &&
572 (RHS->isRational() ? (Numerator == RHS->getNumerator() &&
573 Denominator == RHS->getDenominator())
574 : Factor == RHS->getFactor());
575 }
576
577 unsigned getHashValue() const {
578 return hash_combine(args: Name, args: File, args: LineNo, args: Scope, args: Flags, args: Kind, args: Factor,
579 args: Numerator, args: Denominator);
580 }
581};
582
583template <> struct MDNodeKeyImpl<DIStringType> {
584 unsigned Tag;
585 MDString *Name;
586 Metadata *StringLength;
587 Metadata *StringLengthExp;
588 Metadata *StringLocationExp;
589 Metadata *SizeInBits;
590 uint32_t AlignInBits;
591 unsigned Encoding;
592 Metadata *CharType;
593
594 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *StringLength,
595 Metadata *StringLengthExp, Metadata *StringLocationExp,
596 Metadata *SizeInBits, uint32_t AlignInBits, unsigned Encoding,
597 Metadata *CharType)
598 : Tag(Tag), Name(Name), StringLength(StringLength),
599 StringLengthExp(StringLengthExp), StringLocationExp(StringLocationExp),
600 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
601 CharType(CharType) {}
602 MDNodeKeyImpl(const DIStringType *N)
603 : Tag(N->getTag()), Name(N->getRawName()),
604 StringLength(N->getRawStringLength()),
605 StringLengthExp(N->getRawStringLengthExp()),
606 StringLocationExp(N->getRawStringLocationExp()),
607 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
608 Encoding(N->getEncoding()), CharType(N->getRawCharType()) {}
609
610 bool isKeyOf(const DIStringType *RHS) const {
611 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
612 StringLength == RHS->getRawStringLength() &&
613 StringLengthExp == RHS->getRawStringLengthExp() &&
614 StringLocationExp == RHS->getRawStringLocationExp() &&
615 SizeInBits == RHS->getRawSizeInBits() &&
616 AlignInBits == RHS->getAlignInBits() &&
617 Encoding == RHS->getEncoding() && CharType == RHS->getRawCharType();
618 }
619 unsigned getHashValue() const {
620 // Intentionally computes the hash on a subset of the operands for
621 // performance reason. The subset has to be significant enough to avoid
622 // collision "most of the time". There is no correctness issue in case of
623 // collision because of the full check above.
624 return hash_combine(args: Tag, args: Name, args: StringLength, args: Encoding, args: CharType);
625 }
626};
627
628template <> struct MDNodeKeyImpl<DIDerivedType> {
629 unsigned Tag;
630 MDString *Name;
631 Metadata *File;
632 unsigned Line;
633 Metadata *Scope;
634 Metadata *BaseType;
635 Metadata *SizeInBits;
636 Metadata *OffsetInBits;
637 uint32_t AlignInBits;
638 std::optional<unsigned> DWARFAddressSpace;
639 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
640 unsigned Flags;
641 Metadata *ExtraData;
642 Metadata *Annotations;
643
644 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
645 Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits,
646 uint32_t AlignInBits, Metadata *OffsetInBits,
647 std::optional<unsigned> DWARFAddressSpace,
648 std::optional<DIDerivedType::PtrAuthData> PtrAuthData,
649 unsigned Flags, Metadata *ExtraData, Metadata *Annotations)
650 : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
651 BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
652 AlignInBits(AlignInBits), DWARFAddressSpace(DWARFAddressSpace),
653 PtrAuthData(PtrAuthData), Flags(Flags), ExtraData(ExtraData),
654 Annotations(Annotations) {}
655 MDNodeKeyImpl(const DIDerivedType *N)
656 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
657 Line(N->getLine()), Scope(N->getRawScope()),
658 BaseType(N->getRawBaseType()), SizeInBits(N->getRawSizeInBits()),
659 OffsetInBits(N->getRawOffsetInBits()), AlignInBits(N->getAlignInBits()),
660 DWARFAddressSpace(N->getDWARFAddressSpace()),
661 PtrAuthData(N->getPtrAuthData()), Flags(N->getFlags()),
662 ExtraData(N->getRawExtraData()), Annotations(N->getRawAnnotations()) {}
663
664 bool isKeyOf(const DIDerivedType *RHS) const {
665 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
666 File == RHS->getRawFile() && Line == RHS->getLine() &&
667 Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
668 SizeInBits == RHS->getRawSizeInBits() &&
669 AlignInBits == RHS->getAlignInBits() &&
670 OffsetInBits == RHS->getRawOffsetInBits() &&
671 DWARFAddressSpace == RHS->getDWARFAddressSpace() &&
672 PtrAuthData == RHS->getPtrAuthData() && Flags == RHS->getFlags() &&
673 ExtraData == RHS->getRawExtraData() &&
674 Annotations == RHS->getRawAnnotations();
675 }
676
677 unsigned getHashValue() const {
678 // If this is a member inside an ODR type, only hash the type and the name.
679 // Otherwise the hash will be stronger than
680 // MDNodeSubsetEqualImpl::isODRMember().
681 if (Tag == dwarf::DW_TAG_member && Name)
682 if (auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope))
683 if (CT->getRawIdentifier())
684 return hash_combine(args: Name, args: Scope);
685
686 // Intentionally computes the hash on a subset of the operands for
687 // performance reason. The subset has to be significant enough to avoid
688 // collision "most of the time". There is no correctness issue in case of
689 // collision because of the full check above.
690 return hash_combine(args: Tag, args: Name, args: File, args: Line, args: Scope, args: BaseType, args: Flags);
691 }
692};
693
694template <> struct MDNodeKeyImpl<DISubrangeType> {
695 MDString *Name;
696 Metadata *File;
697 unsigned Line;
698 Metadata *Scope;
699 Metadata *SizeInBits;
700 uint32_t AlignInBits;
701 unsigned Flags;
702 Metadata *BaseType;
703 Metadata *LowerBound;
704 Metadata *UpperBound;
705 Metadata *Stride;
706 Metadata *Bias;
707
708 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
709 Metadata *SizeInBits, uint32_t AlignInBits, unsigned Flags,
710 Metadata *BaseType, Metadata *LowerBound, Metadata *UpperBound,
711 Metadata *Stride, Metadata *Bias)
712 : Name(Name), File(File), Line(Line), Scope(Scope),
713 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Flags(Flags),
714 BaseType(BaseType), LowerBound(LowerBound), UpperBound(UpperBound),
715 Stride(Stride), Bias(Bias) {}
716 MDNodeKeyImpl(const DISubrangeType *N)
717 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
718 Scope(N->getRawScope()), SizeInBits(N->getRawSizeInBits()),
719 AlignInBits(N->getAlignInBits()), Flags(N->getFlags()),
720 BaseType(N->getRawBaseType()), LowerBound(N->getRawLowerBound()),
721 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()),
722 Bias(N->getRawBias()) {}
723
724 bool isKeyOf(const DISubrangeType *RHS) const {
725 auto BoundsEqual = [=](Metadata *Node1, Metadata *Node2) -> bool {
726 if (Node1 == Node2)
727 return true;
728
729 ConstantAsMetadata *MD1 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node1);
730 ConstantAsMetadata *MD2 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node2);
731 if (MD1 && MD2) {
732 ConstantInt *CV1 = cast<ConstantInt>(Val: MD1->getValue());
733 ConstantInt *CV2 = cast<ConstantInt>(Val: MD2->getValue());
734 if (CV1->getSExtValue() == CV2->getSExtValue())
735 return true;
736 }
737 return false;
738 };
739
740 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
741 Line == RHS->getLine() && Scope == RHS->getRawScope() &&
742 SizeInBits == RHS->getRawSizeInBits() &&
743 AlignInBits == RHS->getAlignInBits() && Flags == RHS->getFlags() &&
744 BaseType == RHS->getRawBaseType() &&
745 BoundsEqual(LowerBound, RHS->getRawLowerBound()) &&
746 BoundsEqual(UpperBound, RHS->getRawUpperBound()) &&
747 BoundsEqual(Stride, RHS->getRawStride()) &&
748 BoundsEqual(Bias, RHS->getRawBias());
749 }
750
751 unsigned getHashValue() const {
752 unsigned val = 0;
753 auto HashBound = [&](Metadata *Node) -> void {
754 ConstantAsMetadata *MD = dyn_cast_or_null<ConstantAsMetadata>(Val: Node);
755 if (MD) {
756 ConstantInt *CV = cast<ConstantInt>(Val: MD->getValue());
757 val = hash_combine(args: val, args: CV->getSExtValue());
758 } else {
759 val = hash_combine(args: val, args: Node);
760 }
761 };
762
763 HashBound(LowerBound);
764 HashBound(UpperBound);
765 HashBound(Stride);
766 HashBound(Bias);
767
768 return hash_combine(args: val, args: Name, args: File, args: Line, args: Scope, args: BaseType, args: Flags);
769 }
770};
771
772template <> struct MDNodeSubsetEqualImpl<DIDerivedType> {
773 using KeyTy = MDNodeKeyImpl<DIDerivedType>;
774
775 static bool isSubsetEqual(const KeyTy &LHS, const DIDerivedType *RHS) {
776 return isODRMember(Tag: LHS.Tag, Scope: LHS.Scope, Name: LHS.Name, RHS);
777 }
778
779 static bool isSubsetEqual(const DIDerivedType *LHS,
780 const DIDerivedType *RHS) {
781 return isODRMember(Tag: LHS->getTag(), Scope: LHS->getRawScope(), Name: LHS->getRawName(),
782 RHS);
783 }
784
785 /// Subprograms compare equal if they declare the same function in an ODR
786 /// type.
787 static bool isODRMember(unsigned Tag, const Metadata *Scope,
788 const MDString *Name, const DIDerivedType *RHS) {
789 // Check whether the LHS is eligible.
790 if (Tag != dwarf::DW_TAG_member || !Name)
791 return false;
792
793 auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope);
794 if (!CT || !CT->getRawIdentifier())
795 return false;
796
797 // Compare to the RHS.
798 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
799 Scope == RHS->getRawScope();
800 }
801};
802
803template <> struct MDNodeKeyImpl<DICompositeType> {
804 unsigned Tag;
805 MDString *Name;
806 Metadata *File;
807 unsigned Line;
808 Metadata *Scope;
809 Metadata *BaseType;
810 Metadata *SizeInBits;
811 Metadata *OffsetInBits;
812 uint32_t AlignInBits;
813 unsigned Flags;
814 Metadata *Elements;
815 unsigned RuntimeLang;
816 Metadata *VTableHolder;
817 Metadata *TemplateParams;
818 MDString *Identifier;
819 Metadata *Discriminator;
820 Metadata *DataLocation;
821 Metadata *Associated;
822 Metadata *Allocated;
823 Metadata *Rank;
824 Metadata *Annotations;
825 Metadata *Specification;
826 uint32_t NumExtraInhabitants;
827 Metadata *BitStride;
828
829 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
830 Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits,
831 uint32_t AlignInBits, Metadata *OffsetInBits, unsigned Flags,
832 Metadata *Elements, unsigned RuntimeLang,
833 Metadata *VTableHolder, Metadata *TemplateParams,
834 MDString *Identifier, Metadata *Discriminator,
835 Metadata *DataLocation, Metadata *Associated,
836 Metadata *Allocated, Metadata *Rank, Metadata *Annotations,
837 Metadata *Specification, uint32_t NumExtraInhabitants,
838 Metadata *BitStride)
839 : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
840 BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
841 AlignInBits(AlignInBits), Flags(Flags), Elements(Elements),
842 RuntimeLang(RuntimeLang), VTableHolder(VTableHolder),
843 TemplateParams(TemplateParams), Identifier(Identifier),
844 Discriminator(Discriminator), DataLocation(DataLocation),
845 Associated(Associated), Allocated(Allocated), Rank(Rank),
846 Annotations(Annotations), Specification(Specification),
847 NumExtraInhabitants(NumExtraInhabitants), BitStride(BitStride) {}
848 MDNodeKeyImpl(const DICompositeType *N)
849 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
850 Line(N->getLine()), Scope(N->getRawScope()),
851 BaseType(N->getRawBaseType()), SizeInBits(N->getRawSizeInBits()),
852 OffsetInBits(N->getRawOffsetInBits()), AlignInBits(N->getAlignInBits()),
853 Flags(N->getFlags()), Elements(N->getRawElements()),
854 RuntimeLang(N->getRuntimeLang()), VTableHolder(N->getRawVTableHolder()),
855 TemplateParams(N->getRawTemplateParams()),
856 Identifier(N->getRawIdentifier()),
857 Discriminator(N->getRawDiscriminator()),
858 DataLocation(N->getRawDataLocation()),
859 Associated(N->getRawAssociated()), Allocated(N->getRawAllocated()),
860 Rank(N->getRawRank()), Annotations(N->getRawAnnotations()),
861 Specification(N->getSpecification()),
862 NumExtraInhabitants(N->getNumExtraInhabitants()),
863 BitStride(N->getRawBitStride()) {}
864
865 bool isKeyOf(const DICompositeType *RHS) const {
866 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
867 File == RHS->getRawFile() && Line == RHS->getLine() &&
868 Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
869 SizeInBits == RHS->getRawSizeInBits() &&
870 AlignInBits == RHS->getAlignInBits() &&
871 OffsetInBits == RHS->getRawOffsetInBits() &&
872 Flags == RHS->getFlags() && Elements == RHS->getRawElements() &&
873 RuntimeLang == RHS->getRuntimeLang() &&
874 VTableHolder == RHS->getRawVTableHolder() &&
875 TemplateParams == RHS->getRawTemplateParams() &&
876 Identifier == RHS->getRawIdentifier() &&
877 Discriminator == RHS->getRawDiscriminator() &&
878 DataLocation == RHS->getRawDataLocation() &&
879 Associated == RHS->getRawAssociated() &&
880 Allocated == RHS->getRawAllocated() && Rank == RHS->getRawRank() &&
881 Annotations == RHS->getRawAnnotations() &&
882 Specification == RHS->getSpecification() &&
883 NumExtraInhabitants == RHS->getNumExtraInhabitants() &&
884 BitStride == RHS->getRawBitStride();
885 }
886
887 unsigned getHashValue() const {
888 // Intentionally computes the hash on a subset of the operands for
889 // performance reason. The subset has to be significant enough to avoid
890 // collision "most of the time". There is no correctness issue in case of
891 // collision because of the full check above.
892 return hash_combine(args: Name, args: File, args: Line, args: BaseType, args: Scope, args: Elements,
893 args: TemplateParams, args: Annotations);
894 }
895};
896
897template <> struct MDNodeKeyImpl<DISubroutineType> {
898 unsigned Flags;
899 uint8_t CC;
900 Metadata *TypeArray;
901
902 MDNodeKeyImpl(unsigned Flags, uint8_t CC, Metadata *TypeArray)
903 : Flags(Flags), CC(CC), TypeArray(TypeArray) {}
904 MDNodeKeyImpl(const DISubroutineType *N)
905 : Flags(N->getFlags()), CC(N->getCC()), TypeArray(N->getRawTypeArray()) {}
906
907 bool isKeyOf(const DISubroutineType *RHS) const {
908 return Flags == RHS->getFlags() && CC == RHS->getCC() &&
909 TypeArray == RHS->getRawTypeArray();
910 }
911
912 unsigned getHashValue() const { return hash_combine(args: Flags, args: CC, args: TypeArray); }
913};
914
915template <> struct MDNodeKeyImpl<DIFile> {
916 MDString *Filename;
917 MDString *Directory;
918 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
919 MDString *Source;
920
921 MDNodeKeyImpl(MDString *Filename, MDString *Directory,
922 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum,
923 MDString *Source)
924 : Filename(Filename), Directory(Directory), Checksum(Checksum),
925 Source(Source) {}
926 MDNodeKeyImpl(const DIFile *N)
927 : Filename(N->getRawFilename()), Directory(N->getRawDirectory()),
928 Checksum(N->getRawChecksum()), Source(N->getRawSource()) {}
929
930 bool isKeyOf(const DIFile *RHS) const {
931 return Filename == RHS->getRawFilename() &&
932 Directory == RHS->getRawDirectory() &&
933 Checksum == RHS->getRawChecksum() && Source == RHS->getRawSource();
934 }
935
936 unsigned getHashValue() const {
937 return hash_combine(args: Filename, args: Directory, args: Checksum ? Checksum->Kind : 0,
938 args: Checksum ? Checksum->Value : nullptr, args: Source);
939 }
940};
941
942template <> struct MDNodeKeyImpl<DISubprogram> {
943 Metadata *Scope;
944 MDString *Name;
945 MDString *LinkageName;
946 Metadata *File;
947 unsigned Line;
948 unsigned ScopeLine;
949 Metadata *Type;
950 Metadata *ContainingType;
951 unsigned VirtualIndex;
952 int ThisAdjustment;
953 unsigned Flags;
954 unsigned SPFlags;
955 Metadata *Unit;
956 Metadata *TemplateParams;
957 Metadata *Declaration;
958 Metadata *RetainedNodes;
959 Metadata *ThrownTypes;
960 Metadata *Annotations;
961 MDString *TargetFuncName;
962 bool UsesKeyInstructions;
963
964 MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
965 Metadata *File, unsigned Line, Metadata *Type,
966 unsigned ScopeLine, Metadata *ContainingType,
967 unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
968 unsigned SPFlags, Metadata *Unit, Metadata *TemplateParams,
969 Metadata *Declaration, Metadata *RetainedNodes,
970 Metadata *ThrownTypes, Metadata *Annotations,
971 MDString *TargetFuncName, bool UsesKeyInstructions)
972 : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
973 Line(Line), ScopeLine(ScopeLine), Type(Type),
974 ContainingType(ContainingType), VirtualIndex(VirtualIndex),
975 ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags),
976 Unit(Unit), TemplateParams(TemplateParams), Declaration(Declaration),
977 RetainedNodes(RetainedNodes), ThrownTypes(ThrownTypes),
978 Annotations(Annotations), TargetFuncName(TargetFuncName),
979 UsesKeyInstructions(UsesKeyInstructions) {}
980 MDNodeKeyImpl(const DISubprogram *N)
981 : Scope(N->getRawScope()), Name(N->getRawName()),
982 LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
983 Line(N->getLine()), ScopeLine(N->getScopeLine()), Type(N->getRawType()),
984 ContainingType(N->getRawContainingType()),
985 VirtualIndex(N->getVirtualIndex()),
986 ThisAdjustment(N->getThisAdjustment()), Flags(N->getFlags()),
987 SPFlags(N->getSPFlags()), Unit(N->getRawUnit()),
988 TemplateParams(N->getRawTemplateParams()),
989 Declaration(N->getRawDeclaration()),
990 RetainedNodes(N->getRawRetainedNodes()),
991 ThrownTypes(N->getRawThrownTypes()),
992 Annotations(N->getRawAnnotations()),
993 TargetFuncName(N->getRawTargetFuncName()),
994 UsesKeyInstructions(N->getKeyInstructionsEnabled()) {}
995
996 bool isKeyOf(const DISubprogram *RHS) const {
997 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
998 LinkageName == RHS->getRawLinkageName() &&
999 File == RHS->getRawFile() && Line == RHS->getLine() &&
1000 Type == RHS->getRawType() && ScopeLine == RHS->getScopeLine() &&
1001 ContainingType == RHS->getRawContainingType() &&
1002 VirtualIndex == RHS->getVirtualIndex() &&
1003 ThisAdjustment == RHS->getThisAdjustment() &&
1004 Flags == RHS->getFlags() && SPFlags == RHS->getSPFlags() &&
1005 Unit == RHS->getUnit() &&
1006 TemplateParams == RHS->getRawTemplateParams() &&
1007 Declaration == RHS->getRawDeclaration() &&
1008 RetainedNodes == RHS->getRawRetainedNodes() &&
1009 ThrownTypes == RHS->getRawThrownTypes() &&
1010 Annotations == RHS->getRawAnnotations() &&
1011 TargetFuncName == RHS->getRawTargetFuncName() &&
1012 UsesKeyInstructions == RHS->getKeyInstructionsEnabled();
1013 }
1014
1015 bool isDefinition() const { return SPFlags & DISubprogram::SPFlagDefinition; }
1016
1017 unsigned getHashValue() const {
1018 // Use the Scope's linkage name instead of using the scope directly, as the
1019 // scope may be a temporary one which can replaced, which would produce a
1020 // different hash for the same DISubprogram.
1021 llvm::StringRef ScopeLinkageName;
1022 if (auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope))
1023 if (auto *ID = CT->getRawIdentifier())
1024 ScopeLinkageName = ID->getString();
1025
1026 // If this is a declaration inside an ODR type, only hash the type and the
1027 // name. Otherwise the hash will be stronger than
1028 // MDNodeSubsetEqualImpl::isDeclarationOfODRMember().
1029 if (!isDefinition() && LinkageName &&
1030 isa_and_nonnull<DICompositeType>(Val: Scope))
1031 return hash_combine(args: LinkageName, args: ScopeLinkageName);
1032
1033 // Intentionally computes the hash on a subset of the operands for
1034 // performance reason. The subset has to be significant enough to avoid
1035 // collision "most of the time". There is no correctness issue in case of
1036 // collision because of the full check above.
1037 return hash_combine(args: Name, args: ScopeLinkageName, args: File, args: Type, args: Line);
1038 }
1039};
1040
1041template <> struct MDNodeSubsetEqualImpl<DISubprogram> {
1042 using KeyTy = MDNodeKeyImpl<DISubprogram>;
1043
1044 static bool isSubsetEqual(const KeyTy &LHS, const DISubprogram *RHS) {
1045 return isDeclarationOfODRMember(IsDefinition: LHS.isDefinition(), Scope: LHS.Scope,
1046 LinkageName: LHS.LinkageName, TemplateParams: LHS.TemplateParams, RHS);
1047 }
1048
1049 static bool isSubsetEqual(const DISubprogram *LHS, const DISubprogram *RHS) {
1050 return isDeclarationOfODRMember(IsDefinition: LHS->isDefinition(), Scope: LHS->getRawScope(),
1051 LinkageName: LHS->getRawLinkageName(),
1052 TemplateParams: LHS->getRawTemplateParams(), RHS);
1053 }
1054
1055 /// Subprograms compare equal if they declare the same function in an ODR
1056 /// type.
1057 static bool isDeclarationOfODRMember(bool IsDefinition, const Metadata *Scope,
1058 const MDString *LinkageName,
1059 const Metadata *TemplateParams,
1060 const DISubprogram *RHS) {
1061 // Check whether the LHS is eligible.
1062 if (IsDefinition || !Scope || !LinkageName)
1063 return false;
1064
1065 auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope);
1066 if (!CT || !CT->getRawIdentifier())
1067 return false;
1068
1069 // Compare to the RHS.
1070 // FIXME: We need to compare template parameters here to avoid incorrect
1071 // collisions in mapMetadata when RF_ReuseAndMutateDistinctMDs and a
1072 // ODR-DISubprogram has a non-ODR template parameter (i.e., a
1073 // DICompositeType that does not have an identifier). Eventually we should
1074 // decouple ODR logic from uniquing logic.
1075 return IsDefinition == RHS->isDefinition() && Scope == RHS->getRawScope() &&
1076 LinkageName == RHS->getRawLinkageName() &&
1077 TemplateParams == RHS->getRawTemplateParams();
1078 }
1079};
1080
1081template <> struct MDNodeKeyImpl<DILexicalBlock> {
1082 Metadata *Scope;
1083 Metadata *File;
1084 unsigned Line;
1085 unsigned Column;
1086
1087 MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Line, unsigned Column)
1088 : Scope(Scope), File(File), Line(Line), Column(Column) {}
1089 MDNodeKeyImpl(const DILexicalBlock *N)
1090 : Scope(N->getRawScope()), File(N->getRawFile()), Line(N->getLine()),
1091 Column(N->getColumn()) {}
1092
1093 bool isKeyOf(const DILexicalBlock *RHS) const {
1094 return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
1095 Line == RHS->getLine() && Column == RHS->getColumn();
1096 }
1097
1098 unsigned getHashValue() const {
1099 return hash_combine(args: Scope, args: File, args: Line, args: Column);
1100 }
1101};
1102
1103template <> struct MDNodeKeyImpl<DILexicalBlockFile> {
1104 Metadata *Scope;
1105 Metadata *File;
1106 unsigned Discriminator;
1107
1108 MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Discriminator)
1109 : Scope(Scope), File(File), Discriminator(Discriminator) {}
1110 MDNodeKeyImpl(const DILexicalBlockFile *N)
1111 : Scope(N->getRawScope()), File(N->getRawFile()),
1112 Discriminator(N->getDiscriminator()) {}
1113
1114 bool isKeyOf(const DILexicalBlockFile *RHS) const {
1115 return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
1116 Discriminator == RHS->getDiscriminator();
1117 }
1118
1119 unsigned getHashValue() const {
1120 return hash_combine(args: Scope, args: File, args: Discriminator);
1121 }
1122};
1123
1124template <> struct MDNodeKeyImpl<DINamespace> {
1125 Metadata *Scope;
1126 MDString *Name;
1127 bool ExportSymbols;
1128
1129 MDNodeKeyImpl(Metadata *Scope, MDString *Name, bool ExportSymbols)
1130 : Scope(Scope), Name(Name), ExportSymbols(ExportSymbols) {}
1131 MDNodeKeyImpl(const DINamespace *N)
1132 : Scope(N->getRawScope()), Name(N->getRawName()),
1133 ExportSymbols(N->getExportSymbols()) {}
1134
1135 bool isKeyOf(const DINamespace *RHS) const {
1136 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1137 ExportSymbols == RHS->getExportSymbols();
1138 }
1139
1140 unsigned getHashValue() const { return hash_combine(args: Scope, args: Name); }
1141};
1142
1143template <> struct MDNodeKeyImpl<DICommonBlock> {
1144 Metadata *Scope;
1145 Metadata *Decl;
1146 MDString *Name;
1147 Metadata *File;
1148 unsigned LineNo;
1149
1150 MDNodeKeyImpl(Metadata *Scope, Metadata *Decl, MDString *Name, Metadata *File,
1151 unsigned LineNo)
1152 : Scope(Scope), Decl(Decl), Name(Name), File(File), LineNo(LineNo) {}
1153 MDNodeKeyImpl(const DICommonBlock *N)
1154 : Scope(N->getRawScope()), Decl(N->getRawDecl()), Name(N->getRawName()),
1155 File(N->getRawFile()), LineNo(N->getLineNo()) {}
1156
1157 bool isKeyOf(const DICommonBlock *RHS) const {
1158 return Scope == RHS->getRawScope() && Decl == RHS->getRawDecl() &&
1159 Name == RHS->getRawName() && File == RHS->getRawFile() &&
1160 LineNo == RHS->getLineNo();
1161 }
1162
1163 unsigned getHashValue() const {
1164 return hash_combine(args: Scope, args: Decl, args: Name, args: File, args: LineNo);
1165 }
1166};
1167
1168template <> struct MDNodeKeyImpl<DIModule> {
1169 Metadata *File;
1170 Metadata *Scope;
1171 MDString *Name;
1172 MDString *ConfigurationMacros;
1173 MDString *IncludePath;
1174 MDString *APINotesFile;
1175 unsigned LineNo;
1176 bool IsDecl;
1177
1178 MDNodeKeyImpl(Metadata *File, Metadata *Scope, MDString *Name,
1179 MDString *ConfigurationMacros, MDString *IncludePath,
1180 MDString *APINotesFile, unsigned LineNo, bool IsDecl)
1181 : File(File), Scope(Scope), Name(Name),
1182 ConfigurationMacros(ConfigurationMacros), IncludePath(IncludePath),
1183 APINotesFile(APINotesFile), LineNo(LineNo), IsDecl(IsDecl) {}
1184 MDNodeKeyImpl(const DIModule *N)
1185 : File(N->getRawFile()), Scope(N->getRawScope()), Name(N->getRawName()),
1186 ConfigurationMacros(N->getRawConfigurationMacros()),
1187 IncludePath(N->getRawIncludePath()),
1188 APINotesFile(N->getRawAPINotesFile()), LineNo(N->getLineNo()),
1189 IsDecl(N->getIsDecl()) {}
1190
1191 bool isKeyOf(const DIModule *RHS) const {
1192 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1193 ConfigurationMacros == RHS->getRawConfigurationMacros() &&
1194 IncludePath == RHS->getRawIncludePath() &&
1195 APINotesFile == RHS->getRawAPINotesFile() &&
1196 File == RHS->getRawFile() && LineNo == RHS->getLineNo() &&
1197 IsDecl == RHS->getIsDecl();
1198 }
1199
1200 unsigned getHashValue() const {
1201 return hash_combine(args: Scope, args: Name, args: ConfigurationMacros, args: IncludePath);
1202 }
1203};
1204
1205template <> struct MDNodeKeyImpl<DITemplateTypeParameter> {
1206 MDString *Name;
1207 Metadata *Type;
1208 bool IsDefault;
1209
1210 MDNodeKeyImpl(MDString *Name, Metadata *Type, bool IsDefault)
1211 : Name(Name), Type(Type), IsDefault(IsDefault) {}
1212 MDNodeKeyImpl(const DITemplateTypeParameter *N)
1213 : Name(N->getRawName()), Type(N->getRawType()),
1214 IsDefault(N->isDefault()) {}
1215
1216 bool isKeyOf(const DITemplateTypeParameter *RHS) const {
1217 return Name == RHS->getRawName() && Type == RHS->getRawType() &&
1218 IsDefault == RHS->isDefault();
1219 }
1220
1221 unsigned getHashValue() const { return hash_combine(args: Name, args: Type, args: IsDefault); }
1222};
1223
1224template <> struct MDNodeKeyImpl<DITemplateValueParameter> {
1225 unsigned Tag;
1226 MDString *Name;
1227 Metadata *Type;
1228 bool IsDefault;
1229 Metadata *Value;
1230
1231 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *Type, bool IsDefault,
1232 Metadata *Value)
1233 : Tag(Tag), Name(Name), Type(Type), IsDefault(IsDefault), Value(Value) {}
1234 MDNodeKeyImpl(const DITemplateValueParameter *N)
1235 : Tag(N->getTag()), Name(N->getRawName()), Type(N->getRawType()),
1236 IsDefault(N->isDefault()), Value(N->getValue()) {}
1237
1238 bool isKeyOf(const DITemplateValueParameter *RHS) const {
1239 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
1240 Type == RHS->getRawType() && IsDefault == RHS->isDefault() &&
1241 Value == RHS->getValue();
1242 }
1243
1244 unsigned getHashValue() const {
1245 return hash_combine(args: Tag, args: Name, args: Type, args: IsDefault, args: Value);
1246 }
1247};
1248
1249template <> struct MDNodeKeyImpl<DIGlobalVariable> {
1250 Metadata *Scope;
1251 MDString *Name;
1252 MDString *LinkageName;
1253 Metadata *File;
1254 unsigned Line;
1255 Metadata *Type;
1256 bool IsLocalToUnit;
1257 bool IsDefinition;
1258 Metadata *StaticDataMemberDeclaration;
1259 Metadata *TemplateParams;
1260 uint32_t AlignInBits;
1261 Metadata *Annotations;
1262
1263 MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
1264 Metadata *File, unsigned Line, Metadata *Type,
1265 bool IsLocalToUnit, bool IsDefinition,
1266 Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
1267 uint32_t AlignInBits, Metadata *Annotations)
1268 : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
1269 Line(Line), Type(Type), IsLocalToUnit(IsLocalToUnit),
1270 IsDefinition(IsDefinition),
1271 StaticDataMemberDeclaration(StaticDataMemberDeclaration),
1272 TemplateParams(TemplateParams), AlignInBits(AlignInBits),
1273 Annotations(Annotations) {}
1274 MDNodeKeyImpl(const DIGlobalVariable *N)
1275 : Scope(N->getRawScope()), Name(N->getRawName()),
1276 LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
1277 Line(N->getLine()), Type(N->getRawType()),
1278 IsLocalToUnit(N->isLocalToUnit()), IsDefinition(N->isDefinition()),
1279 StaticDataMemberDeclaration(N->getRawStaticDataMemberDeclaration()),
1280 TemplateParams(N->getRawTemplateParams()),
1281 AlignInBits(N->getAlignInBits()), Annotations(N->getRawAnnotations()) {}
1282
1283 bool isKeyOf(const DIGlobalVariable *RHS) const {
1284 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1285 LinkageName == RHS->getRawLinkageName() &&
1286 File == RHS->getRawFile() && Line == RHS->getLine() &&
1287 Type == RHS->getRawType() && IsLocalToUnit == RHS->isLocalToUnit() &&
1288 IsDefinition == RHS->isDefinition() &&
1289 StaticDataMemberDeclaration ==
1290 RHS->getRawStaticDataMemberDeclaration() &&
1291 TemplateParams == RHS->getRawTemplateParams() &&
1292 AlignInBits == RHS->getAlignInBits() &&
1293 Annotations == RHS->getRawAnnotations();
1294 }
1295
1296 unsigned getHashValue() const {
1297 // We do not use AlignInBits in hashing function here on purpose:
1298 // in most cases this param for local variable is zero (for function param
1299 // it is always zero). This leads to lots of hash collisions and errors on
1300 // cases with lots of similar variables.
1301 // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
1302 // generated IR is random for each run and test fails with Align included.
1303 // TODO: make hashing work fine with such situations
1304 return hash_combine(args: Scope, args: Name, args: LinkageName, args: File, args: Line, args: Type,
1305 args: IsLocalToUnit, args: IsDefinition, /* AlignInBits, */
1306 args: StaticDataMemberDeclaration, args: Annotations);
1307 }
1308};
1309
1310template <> struct MDNodeKeyImpl<DILocalVariable> {
1311 Metadata *Scope;
1312 MDString *Name;
1313 Metadata *File;
1314 unsigned Line;
1315 Metadata *Type;
1316 unsigned Arg;
1317 unsigned Flags;
1318 uint32_t AlignInBits;
1319 Metadata *Annotations;
1320
1321 MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line,
1322 Metadata *Type, unsigned Arg, unsigned Flags,
1323 uint32_t AlignInBits, Metadata *Annotations)
1324 : Scope(Scope), Name(Name), File(File), Line(Line), Type(Type), Arg(Arg),
1325 Flags(Flags), AlignInBits(AlignInBits), Annotations(Annotations) {}
1326 MDNodeKeyImpl(const DILocalVariable *N)
1327 : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
1328 Line(N->getLine()), Type(N->getRawType()), Arg(N->getArg()),
1329 Flags(N->getFlags()), AlignInBits(N->getAlignInBits()),
1330 Annotations(N->getRawAnnotations()) {}
1331
1332 bool isKeyOf(const DILocalVariable *RHS) const {
1333 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1334 File == RHS->getRawFile() && Line == RHS->getLine() &&
1335 Type == RHS->getRawType() && Arg == RHS->getArg() &&
1336 Flags == RHS->getFlags() && AlignInBits == RHS->getAlignInBits() &&
1337 Annotations == RHS->getRawAnnotations();
1338 }
1339
1340 unsigned getHashValue() const {
1341 // We do not use AlignInBits in hashing function here on purpose:
1342 // in most cases this param for local variable is zero (for function param
1343 // it is always zero). This leads to lots of hash collisions and errors on
1344 // cases with lots of similar variables.
1345 // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
1346 // generated IR is random for each run and test fails with Align included.
1347 // TODO: make hashing work fine with such situations
1348 return hash_combine(args: Scope, args: Name, args: File, args: Line, args: Type, args: Arg, args: Flags, args: Annotations);
1349 }
1350};
1351
1352template <> struct MDNodeKeyImpl<DILabel> {
1353 Metadata *Scope;
1354 MDString *Name;
1355 Metadata *File;
1356 unsigned Line;
1357 unsigned Column;
1358 bool IsArtificial;
1359 std::optional<unsigned> CoroSuspendIdx;
1360
1361 MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line,
1362 unsigned Column, bool IsArtificial,
1363 std::optional<unsigned> CoroSuspendIdx)
1364 : Scope(Scope), Name(Name), File(File), Line(Line), Column(Column),
1365 IsArtificial(IsArtificial), CoroSuspendIdx(CoroSuspendIdx) {}
1366 MDNodeKeyImpl(const DILabel *N)
1367 : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
1368 Line(N->getLine()), Column(N->getColumn()),
1369 IsArtificial(N->isArtificial()),
1370 CoroSuspendIdx(N->getCoroSuspendIdx()) {}
1371
1372 bool isKeyOf(const DILabel *RHS) const {
1373 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1374 File == RHS->getRawFile() && Line == RHS->getLine() &&
1375 Column == RHS->getColumn() && IsArtificial == RHS->isArtificial() &&
1376 CoroSuspendIdx == RHS->getCoroSuspendIdx();
1377 }
1378
1379 /// Using name and line to get hash value. It should already be mostly unique.
1380 unsigned getHashValue() const {
1381 return hash_combine(args: Scope, args: Name, args: Line, args: Column, args: IsArtificial,
1382 args: CoroSuspendIdx);
1383 }
1384};
1385
1386template <> struct MDNodeKeyImpl<DIExpression> {
1387 ArrayRef<uint64_t> Elements;
1388
1389 MDNodeKeyImpl(ArrayRef<uint64_t> Elements) : Elements(Elements) {}
1390 MDNodeKeyImpl(const DIExpression *N) : Elements(N->getElements()) {}
1391
1392 bool isKeyOf(const DIExpression *RHS) const {
1393 return Elements == RHS->getElements();
1394 }
1395
1396 unsigned getHashValue() const { return hash_combine_range(R: Elements); }
1397};
1398
1399template <> struct MDNodeKeyImpl<DIGlobalVariableExpression> {
1400 Metadata *Variable;
1401 Metadata *Expression;
1402
1403 MDNodeKeyImpl(Metadata *Variable, Metadata *Expression)
1404 : Variable(Variable), Expression(Expression) {}
1405 MDNodeKeyImpl(const DIGlobalVariableExpression *N)
1406 : Variable(N->getRawVariable()), Expression(N->getRawExpression()) {}
1407
1408 bool isKeyOf(const DIGlobalVariableExpression *RHS) const {
1409 return Variable == RHS->getRawVariable() &&
1410 Expression == RHS->getRawExpression();
1411 }
1412
1413 unsigned getHashValue() const { return hash_combine(args: Variable, args: Expression); }
1414};
1415
1416template <> struct MDNodeKeyImpl<DIObjCProperty> {
1417 MDString *Name;
1418 Metadata *File;
1419 unsigned Line;
1420 MDString *GetterName;
1421 MDString *SetterName;
1422 unsigned Attributes;
1423 Metadata *Type;
1424
1425 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line,
1426 MDString *GetterName, MDString *SetterName, unsigned Attributes,
1427 Metadata *Type)
1428 : Name(Name), File(File), Line(Line), GetterName(GetterName),
1429 SetterName(SetterName), Attributes(Attributes), Type(Type) {}
1430 MDNodeKeyImpl(const DIObjCProperty *N)
1431 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
1432 GetterName(N->getRawGetterName()), SetterName(N->getRawSetterName()),
1433 Attributes(N->getAttributes()), Type(N->getRawType()) {}
1434
1435 bool isKeyOf(const DIObjCProperty *RHS) const {
1436 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
1437 Line == RHS->getLine() && GetterName == RHS->getRawGetterName() &&
1438 SetterName == RHS->getRawSetterName() &&
1439 Attributes == RHS->getAttributes() && Type == RHS->getRawType();
1440 }
1441
1442 unsigned getHashValue() const {
1443 return hash_combine(args: Name, args: File, args: Line, args: GetterName, args: SetterName, args: Attributes,
1444 args: Type);
1445 }
1446};
1447
1448template <> struct MDNodeKeyImpl<DIProperty> {
1449 MDString *Name;
1450 Metadata *File;
1451 unsigned Line;
1452 Metadata *Type;
1453 Metadata *BackingStorage;
1454
1455 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line, Metadata *Type,
1456 Metadata *BackingStorage)
1457 : Name(Name), File(File), Line(Line), Type(Type),
1458 BackingStorage(BackingStorage) {}
1459 MDNodeKeyImpl(const DIProperty *N)
1460 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
1461 Type(N->getRawType()), BackingStorage(N->getRawBackingStorage()) {}
1462
1463 bool isKeyOf(const DIProperty *RHS) const {
1464 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
1465 Line == RHS->getLine() && Type == RHS->getRawType() &&
1466 BackingStorage == RHS->getRawBackingStorage();
1467 }
1468
1469 unsigned getHashValue() const {
1470 return hash_combine(args: Name, args: File, args: Line, args: Type, args: BackingStorage);
1471 }
1472};
1473
1474template <> struct MDNodeKeyImpl<DIImportedEntity> {
1475 unsigned Tag;
1476 Metadata *Scope;
1477 Metadata *Entity;
1478 Metadata *File;
1479 unsigned Line;
1480 MDString *Name;
1481 Metadata *Elements;
1482
1483 MDNodeKeyImpl(unsigned Tag, Metadata *Scope, Metadata *Entity, Metadata *File,
1484 unsigned Line, MDString *Name, Metadata *Elements)
1485 : Tag(Tag), Scope(Scope), Entity(Entity), File(File), Line(Line),
1486 Name(Name), Elements(Elements) {}
1487 MDNodeKeyImpl(const DIImportedEntity *N)
1488 : Tag(N->getTag()), Scope(N->getRawScope()), Entity(N->getRawEntity()),
1489 File(N->getRawFile()), Line(N->getLine()), Name(N->getRawName()),
1490 Elements(N->getRawElements()) {}
1491
1492 bool isKeyOf(const DIImportedEntity *RHS) const {
1493 return Tag == RHS->getTag() && Scope == RHS->getRawScope() &&
1494 Entity == RHS->getRawEntity() && File == RHS->getFile() &&
1495 Line == RHS->getLine() && Name == RHS->getRawName() &&
1496 Elements == RHS->getRawElements();
1497 }
1498
1499 unsigned getHashValue() const {
1500 return hash_combine(args: Tag, args: Scope, args: Entity, args: File, args: Line, args: Name, args: Elements);
1501 }
1502};
1503
1504template <> struct MDNodeKeyImpl<DIMacro> {
1505 unsigned MIType;
1506 unsigned Line;
1507 MDString *Name;
1508 MDString *Value;
1509
1510 MDNodeKeyImpl(unsigned MIType, unsigned Line, MDString *Name, MDString *Value)
1511 : MIType(MIType), Line(Line), Name(Name), Value(Value) {}
1512 MDNodeKeyImpl(const DIMacro *N)
1513 : MIType(N->getMacinfoType()), Line(N->getLine()), Name(N->getRawName()),
1514 Value(N->getRawValue()) {}
1515
1516 bool isKeyOf(const DIMacro *RHS) const {
1517 return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1518 Name == RHS->getRawName() && Value == RHS->getRawValue();
1519 }
1520
1521 unsigned getHashValue() const {
1522 return hash_combine(args: MIType, args: Line, args: Name, args: Value);
1523 }
1524};
1525
1526template <> struct MDNodeKeyImpl<DIMacroFile> {
1527 unsigned MIType;
1528 unsigned Line;
1529 Metadata *File;
1530 Metadata *Elements;
1531
1532 MDNodeKeyImpl(unsigned MIType, unsigned Line, Metadata *File,
1533 Metadata *Elements)
1534 : MIType(MIType), Line(Line), File(File), Elements(Elements) {}
1535 MDNodeKeyImpl(const DIMacroFile *N)
1536 : MIType(N->getMacinfoType()), Line(N->getLine()), File(N->getRawFile()),
1537 Elements(N->getRawElements()) {}
1538
1539 bool isKeyOf(const DIMacroFile *RHS) const {
1540 return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1541 File == RHS->getRawFile() && Elements == RHS->getRawElements();
1542 }
1543
1544 unsigned getHashValue() const {
1545 return hash_combine(args: MIType, args: Line, args: File, args: Elements);
1546 }
1547};
1548
1549// DIArgLists are not MDNodes, but we still want to unique them in a DenseSet
1550// based on a hash of their arguments.
1551struct DIArgListKeyInfo {
1552 ArrayRef<ValueAsMetadata *> Args;
1553
1554 DIArgListKeyInfo(ArrayRef<ValueAsMetadata *> Args) : Args(Args) {}
1555 DIArgListKeyInfo(const DIArgList *N) : Args(N->getArgs()) {}
1556
1557 bool isKeyOf(const DIArgList *RHS) const { return Args == RHS->getArgs(); }
1558
1559 unsigned getHashValue() const { return hash_combine_range(R: Args); }
1560};
1561
1562/// DenseMapInfo for DIArgList.
1563struct DIArgListInfo {
1564 using KeyTy = DIArgListKeyInfo;
1565
1566 static unsigned getHashValue(const KeyTy &Key) { return Key.getHashValue(); }
1567
1568 static unsigned getHashValue(const DIArgList *N) {
1569 return KeyTy(N).getHashValue();
1570 }
1571
1572 static bool isEqual(const KeyTy &LHS, const DIArgList *RHS) {
1573 return LHS.isKeyOf(RHS);
1574 }
1575
1576 static bool isEqual(const DIArgList *LHS, const DIArgList *RHS) {
1577 return LHS == RHS;
1578 }
1579};
1580
1581/// DenseMapInfo for MDNode subclasses.
1582template <class NodeTy> struct MDNodeInfo {
1583 using KeyTy = MDNodeKeyImpl<NodeTy>;
1584 using SubsetEqualTy = MDNodeSubsetEqualImpl<NodeTy>;
1585
1586 static unsigned getHashValue(const KeyTy &Key) { return Key.getHashValue(); }
1587
1588 static unsigned getHashValue(const NodeTy *N) {
1589 return KeyTy(N).getHashValue();
1590 }
1591
1592 static bool isEqual(const KeyTy &LHS, const NodeTy *RHS) {
1593 return SubsetEqualTy::isSubsetEqual(LHS, RHS) || LHS.isKeyOf(RHS);
1594 }
1595
1596 static bool isEqual(const NodeTy *LHS, const NodeTy *RHS) {
1597 if (LHS == RHS)
1598 return true;
1599 return SubsetEqualTy::isSubsetEqual(LHS, RHS);
1600 }
1601};
1602
1603#define HANDLE_MDNODE_LEAF(CLASS) using CLASS##Info = MDNodeInfo<CLASS>;
1604#include "llvm/IR/Metadata.def"
1605
1606/// Single metadata attachment, forms linked list ended by index 0.
1607struct MDAttachment {
1608 unsigned Next = 0;
1609 unsigned MDKind;
1610 TrackingMDNodeRef Node;
1611};
1612
1613/// Head pointer for a Value's ValueHandleBase doubly-linked list, stored in
1614/// LLVMContextImpl::ValueHandles. The first node's PrevPtr points to Head, so
1615/// relocating the bucket refreshes PrevPtr to the new Head address.
1616class ValueHandleHead {
1617 // Tag Head with true via PointerIntPair so RemoveFromUseList can
1618 // distinguish ValueHandleHead::Head from an untagged ValueHandleBase::Next
1619 // when accessed through *PrevPtr.
1620 using TaggedPtr = PointerIntPair<ValueHandleBase *, 1, bool>;
1621
1622 ValueHandleBase *Head =
1623 static_cast<ValueHandleBase *>(TaggedPtr(nullptr, true).getOpaqueValue());
1624
1625public:
1626 ValueHandleBase *get() const {
1627 return TaggedPtr::getFromOpaqueValue(V: Head).getPointer();
1628 }
1629
1630 ValueHandleBase **getAddress() { return &Head; }
1631
1632 // Replace the pointer in *Slot with NewPtr while preserving its tag bit,
1633 // and return the old TaggedPtr.
1634 static TaggedPtr exchange(ValueHandleBase **Slot, ValueHandleBase *NewPtr) {
1635 TaggedPtr Old = TaggedPtr::getFromOpaqueValue(V: *Slot);
1636 TaggedPtr Updated = Old;
1637 Updated.setPointer(NewPtr);
1638 *Slot = static_cast<ValueHandleBase *>(Updated.getOpaqueValue());
1639 return Old;
1640 }
1641
1642 ValueHandleHead() = default;
1643 ValueHandleHead(ValueHandleHead &&Other) noexcept;
1644 ValueHandleHead &operator=(ValueHandleHead &&) = delete;
1645 ValueHandleHead(const ValueHandleHead &) = delete;
1646 ValueHandleHead &operator=(const ValueHandleHead &) = delete;
1647};
1648
1649class LLVMContextImpl {
1650public:
1651 /// OwnedModules - The set of modules instantiated in this context, and which
1652 /// will be automatically deleted if this context is deleted.
1653 SmallPtrSet<Module *, 4> OwnedModules;
1654
1655 /// MachineFunctionNums - Keep the next available unique number available for
1656 /// a MachineFunction in given module. Module must in OwnedModules.
1657 DenseMap<Module *, unsigned> MachineFunctionNums;
1658
1659 /// The main remark streamer used by all the other streamers (e.g. IR, MIR,
1660 /// frontends, etc.). This should only be used by the specific streamers, and
1661 /// never directly.
1662 std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer;
1663
1664 /// The virtual file system used for inputs.
1665 IntrusiveRefCntPtr<vfs::FileSystem> FS;
1666
1667 std::unique_ptr<DiagnosticHandler> DiagHandler;
1668 bool RespectDiagnosticFilters = false;
1669 bool DiagnosticsHotnessRequested = false;
1670 /// The minimum hotness value a diagnostic needs in order to be included in
1671 /// optimization diagnostics.
1672 ///
1673 /// The threshold is an Optional value, which maps to one of the 3 states:
1674 /// 1). 0 => threshold disabled. All emarks will be printed.
1675 /// 2). positive int => manual threshold by user. Remarks with hotness exceed
1676 /// threshold will be printed.
1677 /// 3). None => 'auto' threshold by user. The actual value is not
1678 /// available at command line, but will be synced with
1679 /// hotness threhold from profile summary during
1680 /// compilation.
1681 ///
1682 /// State 1 and 2 are considered as terminal states. State transition is
1683 /// only allowed from 3 to 2, when the threshold is first synced with profile
1684 /// summary. This ensures that the threshold is set only once and stays
1685 /// constant.
1686 ///
1687 /// If threshold option is not specified, it is disabled (0) by default.
1688 std::optional<uint64_t> DiagnosticsHotnessThreshold = 0;
1689
1690 /// The percentage of difference between profiling branch weights and
1691 /// llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
1692 std::optional<uint32_t> DiagnosticsMisExpectTolerance = 0;
1693 bool MisExpectWarningRequested = false;
1694
1695 /// The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.
1696 std::unique_ptr<LLVMRemarkStreamer> LLVMRS;
1697
1698 LLVMContext::YieldCallbackTy YieldCallback = nullptr;
1699 void *YieldOpaqueHandle = nullptr;
1700
1701 DenseMap<const Value *, ValueName *> ValueNames;
1702
1703 DenseMap<unsigned, std::unique_ptr<ConstantInt>> IntZeroConstants;
1704 DenseMap<unsigned, std::unique_ptr<ConstantInt>> IntOneConstants;
1705 DenseMap<APInt, std::unique_ptr<ConstantInt>> IntConstants;
1706 DenseMap<std::pair<ElementCount, APInt>, std::unique_ptr<ConstantInt>>
1707 IntSplatConstants;
1708
1709 DenseMap<unsigned, std::unique_ptr<ConstantByte>> ByteZeroConstants;
1710 DenseMap<unsigned, std::unique_ptr<ConstantByte>> ByteOneConstants;
1711 DenseMap<APInt, std::unique_ptr<ConstantByte>> ByteConstants;
1712 DenseMap<std::pair<ElementCount, APInt>, std::unique_ptr<ConstantByte>>
1713 ByteSplatConstants;
1714
1715 DenseMap<APFloat, std::unique_ptr<ConstantFP>> FPConstants;
1716 DenseMap<std::pair<ElementCount, APFloat>, std::unique_ptr<ConstantFP>>
1717 FPSplatConstants;
1718
1719 EnumAttributeImpl *EnumAttrs[Attribute::NumEnumAttrKinds] = {};
1720 UniquingSet<IntAttributeImpl> IntAttrs;
1721 UniquingSet<StringAttributeImpl> StringAttrs;
1722 UniquingSet<TypeAttributeImpl> TypeAttrs;
1723 FoldingSet<AttributeImpl> AttrsSet;
1724 UniquingSet<AttributeListImpl> AttrsLists;
1725 UniquingSet<AttributeSetNode> AttrsSetNodes;
1726
1727 StringMap<MDString, BumpPtrAllocator> MDStringCache;
1728 DenseMap<Value *, ValueAsMetadata *> ValuesAsMetadata;
1729 DenseMap<Metadata *, MetadataAsValue *> MetadataAsValues;
1730 DenseSet<DIArgList *, DIArgListInfo> DIArgLists;
1731
1732 uint32_t NextMetadataPrintID = 0;
1733
1734 uint32_t allocateMetadataPrintID() { return NextMetadataPrintID++; }
1735
1736 void getAllMetadataNodes(SmallVectorImpl<MDNode *> &Nodes) const;
1737
1738 uint32_t getMetadataPrintID(const MDNode *N) const {
1739 return N->getHeader().MetadataPrintID;
1740 }
1741
1742 void setMetadataPrintID(MDNode *N, uint32_t ID) {
1743 N->getHeader().MetadataPrintID = ID;
1744 }
1745
1746#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1747 DenseSet<CLASS *, CLASS##Info> CLASS##s;
1748#include "llvm/IR/Metadata.def"
1749
1750 // Optional map for looking up composite types by identifier.
1751 std::optional<DenseMap<const MDString *, DICompositeType *>> DITypeMap;
1752
1753 // MDNodes may be uniqued or not uniqued. When they're not uniqued, they
1754 // aren't in the MDNodeSet, but they're still shared between objects, so no
1755 // one object can destroy them. Keep track of them here so we can delete
1756 // them on context teardown.
1757 std::vector<MDNode *> DistinctMDNodes;
1758
1759 // Temporary nodes are caller-owned, but track live ones for persistent
1760 // metadata print IDs.
1761 DenseSet<MDNode *> TemporaryMDNodes;
1762
1763 // ConstantRangeListAttributeImpl is a TrailingObjects/ArrayRef of
1764 // ConstantRange. Since this is a dynamically sized class, it's not
1765 // possible to use SpecificBumpPtrAllocator. Instead, we use normal Alloc
1766 // for allocation and record all allocated pointers in this vector. In the
1767 // LLVMContext destructor, call the destuctors of everything in the vector.
1768 std::vector<ConstantRangeListAttributeImpl *> ConstantRangeListAttributes;
1769
1770 DenseMap<Type *, std::unique_ptr<ConstantAggregateZero>> CAZConstants;
1771
1772 using ArrayConstantsTy = ConstantUniqueMap<ConstantArray>;
1773 ArrayConstantsTy ArrayConstants;
1774
1775 using StructConstantsTy = ConstantUniqueMap<ConstantStruct>;
1776 StructConstantsTy StructConstants;
1777
1778 using VectorConstantsTy = ConstantUniqueMap<ConstantVector>;
1779 VectorConstantsTy VectorConstants;
1780
1781 DenseMap<Type *, std::unique_ptr<ConstantPointerNull>> CPNConstants;
1782
1783 DenseMap<TargetExtType *, std::unique_ptr<ConstantTargetNone>> CTNConstants;
1784
1785 DenseMap<Type *, std::unique_ptr<UndefValue>> UVConstants;
1786
1787 DenseMap<Type *, std::unique_ptr<PoisonValue>> PVConstants;
1788
1789 StringMap<std::unique_ptr<ConstantDataSequential>> CDSConstants;
1790
1791 DenseMap<const BasicBlock *, BlockAddress *> BlockAddresses;
1792
1793 DenseMap<const GlobalValue *, DSOLocalEquivalent *> DSOLocalEquivalents;
1794
1795 DenseMap<const GlobalValue *, NoCFIValue *> NoCFIValues;
1796
1797 ConstantUniqueMap<ConstantPtrAuth> ConstantPtrAuths;
1798
1799 ConstantUniqueMap<ConstantExpr> ExprConstants;
1800
1801 ConstantUniqueMap<InlineAsm> InlineAsms;
1802
1803 ConstantInt *TheTrueVal = nullptr;
1804 ConstantInt *TheFalseVal = nullptr;
1805
1806 ConstantByte *TheTrueByteVal = nullptr;
1807 ConstantByte *TheFalseByteVal = nullptr;
1808
1809 // Basic type instances.
1810 Type VoidTy, LabelTy, HalfTy, BFloatTy, FloatTy, DoubleTy, MetadataTy,
1811 TokenTy;
1812 Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_AMXTy;
1813 IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty, Int128Ty;
1814 ByteType Byte1Ty, Byte8Ty, Byte16Ty, Byte32Ty, Byte64Ty, Byte128Ty;
1815
1816 std::unique_ptr<ConstantTokenNone> TheNoneToken;
1817
1818 BumpPtrAllocator Alloc;
1819 UniqueStringSaver Saver{Alloc};
1820 SpecificBumpPtrAllocator<ConstantRangeAttributeImpl>
1821 ConstantRangeAttributeAlloc;
1822
1823 DenseMap<unsigned, ByteType *> ByteTypes;
1824 DenseMap<unsigned, IntegerType *> IntegerTypes;
1825
1826 using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
1827 FunctionTypeSet FunctionTypes;
1828 using StructTypeSet = DenseSet<StructType *, AnonStructTypeKeyInfo>;
1829 StructTypeSet AnonStructTypes;
1830 StringMap<StructType *> NamedStructTypes;
1831 unsigned NamedStructTypesUniqueID = 0;
1832
1833 using TargetExtTypeSet = DenseSet<TargetExtType *, TargetExtTypeKeyInfo>;
1834 TargetExtTypeSet TargetExtTypes;
1835
1836 DenseMap<std::pair<Type *, uint64_t>, ArrayType *> ArrayTypes;
1837 DenseMap<std::pair<Type *, ElementCount>, VectorType *> VectorTypes;
1838 PointerType *AS0PointerType = nullptr; // AddrSpace = 0
1839 DenseMap<unsigned, PointerType *> PointerTypes;
1840 DenseMap<std::pair<Type *, unsigned>, TypedPointerType *> ASTypedPointerTypes;
1841
1842 /// ValueHandles - This map keeps track of all of the value handles that are
1843 /// watching a Value*. The Value::HasValueHandle bit is used to know
1844 /// whether or not a value has an entry in this map.
1845 using ValueHandlesTy = DenseMap<Value *, ValueHandleHead>;
1846 ValueHandlesTy ValueHandles;
1847
1848 /// CustomMDKindNames - Map to hold the metadata string to ID mapping.
1849 StringMap<unsigned> CustomMDKindNames;
1850
1851 /// Collection of metadata attachments in this context.
1852 SmallVector<MDAttachment, 0> Metadatas;
1853 /// Index of first free Metadatas entry, linked list via MDAttachment::Next.
1854 unsigned MetadataRecycleHead = 0;
1855 /// Number of currently unused metadata entries. Only used/updated in debug
1856 /// builds to ensure that all metadata attachments are properly freed.
1857 unsigned MetadataRecycleSize = 0;
1858
1859 /// Collection of per-GlobalObject sections used in this context.
1860 DenseMap<const GlobalObject *, StringRef> GlobalObjectSections;
1861
1862 /// Collection of per-GlobalValue partitions used in this context.
1863 DenseMap<const GlobalValue *, StringRef> GlobalValuePartitions;
1864
1865 DenseMap<const GlobalValue *, GlobalValue::SanitizerMetadata>
1866 GlobalValueSanitizerMetadata;
1867
1868 /// DiscriminatorTable - This table maps file:line locations to an
1869 /// integer representing the next DWARF path discriminator to assign to
1870 /// instructions in different blocks at the same location.
1871 DenseMap<std::pair<const char *, unsigned>, unsigned> DiscriminatorTable;
1872
1873 /// A set of interned tags for operand bundles. The StringMap maps
1874 /// bundle tags to their IDs.
1875 ///
1876 /// \see LLVMContext::getOperandBundleTagID
1877 StringMap<uint32_t> BundleTagCache;
1878
1879 StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef Tag);
1880 void getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const;
1881 uint32_t getOperandBundleTagID(StringRef Tag) const;
1882
1883 /// A set of interned synchronization scopes. The StringMap maps
1884 /// synchronization scope names to their respective synchronization scope IDs.
1885 StringMap<SyncScope::ID> SSC;
1886
1887 /// getOrInsertSyncScopeID - Maps synchronization scope name to
1888 /// synchronization scope ID. Every synchronization scope registered with
1889 /// LLVMContext has unique ID except pre-defined ones.
1890 SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
1891
1892 /// getSyncScopeNames - Populates client supplied SmallVector with
1893 /// synchronization scope names registered with LLVMContext. Synchronization
1894 /// scope names are ordered by increasing synchronization scope IDs.
1895 void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
1896
1897 /// getSyncScopeName - Returns the name of a SyncScope::ID
1898 /// registered with LLVMContext, if any.
1899 std::optional<StringRef> getSyncScopeName(SyncScope::ID Id) const;
1900
1901 /// Maintain the GC name for each function.
1902 ///
1903 /// This saves allocating an additional word in Function for programs which
1904 /// do not use GC (i.e., most programs) at the cost of increased overhead for
1905 /// clients which do use GC.
1906 DenseMap<const Function *, std::string> GCNames;
1907
1908 /// Flag to indicate if Value (other than GlobalValue) retains their name or
1909 /// not.
1910 bool DiscardValueNames = false;
1911
1912 LLVMContextImpl(LLVMContext &C);
1913 ~LLVMContextImpl();
1914
1915 mutable OptPassGate *OPG = nullptr;
1916
1917 /// Access the object which can disable optional passes and individual
1918 /// optimizations at compile time.
1919 OptPassGate &getOptPassGate() const;
1920
1921 /// Set the object which can disable optional passes and individual
1922 /// optimizations at compile time.
1923 ///
1924 /// The lifetime of the object must be guaranteed to extend as long as the
1925 /// LLVMContext is used by compilation.
1926 void setOptPassGate(OptPassGate &);
1927
1928 /// Mapping of blocks to collections of "trailing" DbgVariableRecords. As part
1929 /// of the "RemoveDIs" project, debug-info variable location records are going
1930 /// to cease being instructions... which raises the problem of where should
1931 /// they be recorded when we remove the terminator of a blocks, such as:
1932 ///
1933 /// %foo = add i32 0, 0
1934 /// br label %bar
1935 ///
1936 /// If the branch is removed, a legitimate transient state while editing a
1937 /// block, any debug-records between those two instructions will not have a
1938 /// location. Each block thus records any DbgVariableRecord records that
1939 /// "trail" in such a way. These are stored in LLVMContext because typically
1940 /// LLVM only edits a small number of blocks at a time, so there's no need to
1941 /// bloat BasicBlock with such a data structure.
1942 SmallDenseMap<BasicBlock *, DbgMarker *> TrailingDbgRecords;
1943
1944 // Set, get and delete operations for TrailingDbgRecords.
1945 void setTrailingDbgRecords(BasicBlock *B, DbgMarker *M) {
1946 assert(!TrailingDbgRecords.count(B));
1947 TrailingDbgRecords[B] = M;
1948 }
1949
1950 DbgMarker *getTrailingDbgRecords(BasicBlock *B) {
1951 return TrailingDbgRecords.lookup(Val: B);
1952 }
1953
1954 void deleteTrailingDbgRecords(BasicBlock *B) { TrailingDbgRecords.erase(Val: B); }
1955
1956 std::string DefaultTargetCPU;
1957 std::string DefaultTargetFeatures;
1958
1959 cl::LibraryOptionsContext LibraryOptions;
1960
1961 /// The next available source atom group number. The front end is responsible
1962 /// for assigning source atom numbers, but certain optimisations need to
1963 /// assign new group numbers to a set of instructions. Most often code
1964 /// duplication optimisations like loop unroll. Tracking a global maximum
1965 /// value means we can know (cheaply) we're never using a group number that's
1966 /// already used within this function.
1967 ///
1968 /// Start a 1 because 0 means the source location isn't part of an atom group.
1969 uint64_t NextAtomGroup = 1;
1970};
1971
1972} // end namespace llvm
1973
1974#endif // LLVM_LIB_IR_LLVMCONTEXTIMPL_H
1975