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