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