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