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