1 //===- llvm/Attributes.h - Container for Attributes -------------*- 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 /// \file
10 /// This file contains the simple types necessary to represent the
11 /// attributes associated with functions and their calls.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_ATTRIBUTES_H
16 #define LLVM_IR_ATTRIBUTES_H
17 
18 #include "llvm-c/Types.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/Support/Alignment.h"
26 #include "llvm/Support/PointerLikeTypeTraits.h"
27 #include <bitset>
28 #include <cassert>
29 #include <cstdint>
30 #include <map>
31 #include <string>
32 #include <utility>
33 
34 namespace llvm {
35 
36 class AttrBuilder;
37 class AttributeImpl;
38 class AttributeListImpl;
39 class AttributeSetNode;
40 template<typename T> struct DenseMapInfo;
41 class FoldingSetNodeID;
42 class Function;
43 class LLVMContext;
44 class Type;
45 
46 //===----------------------------------------------------------------------===//
47 /// \class
48 /// Functions, function parameters, and return types can have attributes
49 /// to indicate how they should be treated by optimizations and code
50 /// generation. This class represents one of those attributes. It's light-weight
51 /// and should be passed around by-value.
52 class Attribute {
53 public:
54   /// This enumeration lists the attributes that can be associated with
55   /// parameters, function results, or the function itself.
56   ///
57   /// Note: The `uwtable' attribute is about the ABI or the user mandating an
58   /// entry in the unwind table. The `nounwind' attribute is about an exception
59   /// passing by the function.
60   ///
61   /// In a theoretical system that uses tables for profiling and SjLj for
62   /// exceptions, they would be fully independent. In a normal system that uses
63   /// tables for both, the semantics are:
64   ///
65   /// nil                = Needs an entry because an exception might pass by.
66   /// nounwind           = No need for an entry
67   /// uwtable            = Needs an entry because the ABI says so and because
68   ///                      an exception might pass by.
69   /// uwtable + nounwind = Needs an entry because the ABI says so.
70 
71   enum AttrKind {
72     // IR-Level Attributes
73     None,                  ///< No attributes have been set
74     #define GET_ATTR_ENUM
75     #include "llvm/IR/Attributes.inc"
76     EndAttrKinds,          ///< Sentinal value useful for loops
77     EmptyKey,              ///< Use as Empty key for DenseMap of AttrKind
78     TombstoneKey,          ///< Use as Tombstone key for DenseMap of AttrKind
79   };
80 
81   static const unsigned NumTypeAttrKinds = LastTypeAttr - FirstTypeAttr + 1;
82 
83   static bool isEnumAttrKind(AttrKind Kind) {
84     return Kind >= FirstEnumAttr && Kind <= LastEnumAttr;
85   }
86   static bool isIntAttrKind(AttrKind Kind) {
87     return Kind >= FirstIntAttr && Kind <= LastIntAttr;
88   }
89   static bool isTypeAttrKind(AttrKind Kind) {
90     return Kind >= FirstTypeAttr && Kind <= LastTypeAttr;
91   }
92 
93   static bool canUseAsFnAttr(AttrKind Kind);
94   static bool canUseAsParamAttr(AttrKind Kind);
95   static bool canUseAsRetAttr(AttrKind Kind);
96 
97 private:
98   AttributeImpl *pImpl = nullptr;
99 
100   Attribute(AttributeImpl *A) : pImpl(A) {}
101 
102 public:
103   Attribute() = default;
104 
105   //===--------------------------------------------------------------------===//
106   // Attribute Construction
107   //===--------------------------------------------------------------------===//
108 
109   /// Return a uniquified Attribute object.
110   static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
111   static Attribute get(LLVMContext &Context, StringRef Kind,
112                        StringRef Val = StringRef());
113   static Attribute get(LLVMContext &Context, AttrKind Kind, Type *Ty);
114 
115   /// Return a uniquified Attribute object that has the specific
116   /// alignment set.
117   static Attribute getWithAlignment(LLVMContext &Context, Align Alignment);
118   static Attribute getWithStackAlignment(LLVMContext &Context, Align Alignment);
119   static Attribute getWithDereferenceableBytes(LLVMContext &Context,
120                                               uint64_t Bytes);
121   static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context,
122                                                      uint64_t Bytes);
123   static Attribute getWithAllocSizeArgs(LLVMContext &Context,
124                                         unsigned ElemSizeArg,
125                                         const Optional<unsigned> &NumElemsArg);
126   static Attribute getWithVScaleRangeArgs(LLVMContext &Context,
127                                           unsigned MinValue, unsigned MaxValue);
128   static Attribute getWithByValType(LLVMContext &Context, Type *Ty);
129   static Attribute getWithStructRetType(LLVMContext &Context, Type *Ty);
130   static Attribute getWithByRefType(LLVMContext &Context, Type *Ty);
131   static Attribute getWithPreallocatedType(LLVMContext &Context, Type *Ty);
132   static Attribute getWithInAllocaType(LLVMContext &Context, Type *Ty);
133 
134   /// For a typed attribute, return the equivalent attribute with the type
135   /// changed to \p ReplacementTy.
136   Attribute getWithNewType(LLVMContext &Context, Type *ReplacementTy) {
137     assert(isTypeAttribute() && "this requires a typed attribute");
138     return get(Context, getKindAsEnum(), ReplacementTy);
139   }
140 
141   static Attribute::AttrKind getAttrKindFromName(StringRef AttrName);
142 
143   static StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind);
144 
145   /// Return true if the provided string matches the IR name of an attribute.
146   /// example: "noalias" return true but not "NoAlias"
147   static bool isExistingAttribute(StringRef Name);
148 
149   //===--------------------------------------------------------------------===//
150   // Attribute Accessors
151   //===--------------------------------------------------------------------===//
152 
153   /// Return true if the attribute is an Attribute::AttrKind type.
154   bool isEnumAttribute() const;
155 
156   /// Return true if the attribute is an integer attribute.
157   bool isIntAttribute() const;
158 
159   /// Return true if the attribute is a string (target-dependent)
160   /// attribute.
161   bool isStringAttribute() const;
162 
163   /// Return true if the attribute is a type attribute.
164   bool isTypeAttribute() const;
165 
166   /// Return true if the attribute is any kind of attribute.
167   bool isValid() const { return pImpl; }
168 
169   /// Return true if the attribute is present.
170   bool hasAttribute(AttrKind Val) const;
171 
172   /// Return true if the target-dependent attribute is present.
173   bool hasAttribute(StringRef Val) const;
174 
175   /// Return the attribute's kind as an enum (Attribute::AttrKind). This
176   /// requires the attribute to be an enum, integer, or type attribute.
177   Attribute::AttrKind getKindAsEnum() const;
178 
179   /// Return the attribute's value as an integer. This requires that the
180   /// attribute be an integer attribute.
181   uint64_t getValueAsInt() const;
182 
183   /// Return the attribute's value as a boolean. This requires that the
184   /// attribute be a string attribute.
185   bool getValueAsBool() const;
186 
187   /// Return the attribute's kind as a string. This requires the
188   /// attribute to be a string attribute.
189   StringRef getKindAsString() const;
190 
191   /// Return the attribute's value as a string. This requires the
192   /// attribute to be a string attribute.
193   StringRef getValueAsString() const;
194 
195   /// Return the attribute's value as a Type. This requires the attribute to be
196   /// a type attribute.
197   Type *getValueAsType() const;
198 
199   /// Returns the alignment field of an attribute as a byte alignment
200   /// value.
201   MaybeAlign getAlignment() const;
202 
203   /// Returns the stack alignment field of an attribute as a byte
204   /// alignment value.
205   MaybeAlign getStackAlignment() const;
206 
207   /// Returns the number of dereferenceable bytes from the
208   /// dereferenceable attribute.
209   uint64_t getDereferenceableBytes() const;
210 
211   /// Returns the number of dereferenceable_or_null bytes from the
212   /// dereferenceable_or_null attribute.
213   uint64_t getDereferenceableOrNullBytes() const;
214 
215   /// Returns the argument numbers for the allocsize attribute (or pair(0, 0)
216   /// if not known).
217   std::pair<unsigned, Optional<unsigned>> getAllocSizeArgs() const;
218 
219   /// Returns the argument numbers for the vscale_range attribute (or pair(0, 0)
220   /// if not known).
221   std::pair<unsigned, unsigned> getVScaleRangeArgs() const;
222 
223   /// The Attribute is converted to a string of equivalent mnemonic. This
224   /// is, presumably, for writing out the mnemonics for the assembly writer.
225   std::string getAsString(bool InAttrGrp = false) const;
226 
227   /// Return true if this attribute belongs to the LLVMContext.
228   bool hasParentContext(LLVMContext &C) const;
229 
230   /// Equality and non-equality operators.
231   bool operator==(Attribute A) const { return pImpl == A.pImpl; }
232   bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
233 
234   /// Less-than operator. Useful for sorting the attributes list.
235   bool operator<(Attribute A) const;
236 
237   void Profile(FoldingSetNodeID &ID) const;
238 
239   /// Return a raw pointer that uniquely identifies this attribute.
240   void *getRawPointer() const {
241     return pImpl;
242   }
243 
244   /// Get an attribute from a raw pointer created by getRawPointer.
245   static Attribute fromRawPointer(void *RawPtr) {
246     return Attribute(reinterpret_cast<AttributeImpl*>(RawPtr));
247   }
248 };
249 
250 // Specialized opaque value conversions.
251 inline LLVMAttributeRef wrap(Attribute Attr) {
252   return reinterpret_cast<LLVMAttributeRef>(Attr.getRawPointer());
253 }
254 
255 // Specialized opaque value conversions.
256 inline Attribute unwrap(LLVMAttributeRef Attr) {
257   return Attribute::fromRawPointer(Attr);
258 }
259 
260 //===----------------------------------------------------------------------===//
261 /// \class
262 /// This class holds the attributes for a particular argument, parameter,
263 /// function, or return value. It is an immutable value type that is cheap to
264 /// copy. Adding and removing enum attributes is intended to be fast, but adding
265 /// and removing string or integer attributes involves a FoldingSet lookup.
266 class AttributeSet {
267   friend AttributeListImpl;
268   template <typename Ty> friend struct DenseMapInfo;
269 
270   // TODO: Extract AvailableAttrs from AttributeSetNode and store them here.
271   // This will allow an efficient implementation of addAttribute and
272   // removeAttribute for enum attrs.
273 
274   /// Private implementation pointer.
275   AttributeSetNode *SetNode = nullptr;
276 
277 private:
278   explicit AttributeSet(AttributeSetNode *ASN) : SetNode(ASN) {}
279 
280 public:
281   /// AttributeSet is a trivially copyable value type.
282   AttributeSet() = default;
283   AttributeSet(const AttributeSet &) = default;
284   ~AttributeSet() = default;
285 
286   static AttributeSet get(LLVMContext &C, const AttrBuilder &B);
287   static AttributeSet get(LLVMContext &C, ArrayRef<Attribute> Attrs);
288 
289   bool operator==(const AttributeSet &O) const { return SetNode == O.SetNode; }
290   bool operator!=(const AttributeSet &O) const { return !(*this == O); }
291 
292   /// Add an argument attribute. Returns a new set because attribute sets are
293   /// immutable.
294   LLVM_NODISCARD AttributeSet addAttribute(LLVMContext &C,
295                                            Attribute::AttrKind Kind) const;
296 
297   /// Add a target-dependent attribute. Returns a new set because attribute sets
298   /// are immutable.
299   LLVM_NODISCARD AttributeSet addAttribute(LLVMContext &C, StringRef Kind,
300                                            StringRef Value = StringRef()) const;
301 
302   /// Add attributes to the attribute set. Returns a new set because attribute
303   /// sets are immutable.
304   LLVM_NODISCARD AttributeSet addAttributes(LLVMContext &C,
305                                             AttributeSet AS) const;
306 
307   /// Remove the specified attribute from this set. Returns a new set because
308   /// attribute sets are immutable.
309   LLVM_NODISCARD AttributeSet removeAttribute(LLVMContext &C,
310                                               Attribute::AttrKind Kind) const;
311 
312   /// Remove the specified attribute from this set. Returns a new set because
313   /// attribute sets are immutable.
314   LLVM_NODISCARD AttributeSet removeAttribute(LLVMContext &C,
315                                               StringRef Kind) const;
316 
317   /// Remove the specified attributes from this set. Returns a new set because
318   /// attribute sets are immutable.
319   LLVM_NODISCARD AttributeSet
320   removeAttributes(LLVMContext &C, const AttrBuilder &AttrsToRemove) const;
321 
322   /// Return the number of attributes in this set.
323   unsigned getNumAttributes() const;
324 
325   /// Return true if attributes exists in this set.
326   bool hasAttributes() const { return SetNode != nullptr; }
327 
328   /// Return true if the attribute exists in this set.
329   bool hasAttribute(Attribute::AttrKind Kind) const;
330 
331   /// Return true if the attribute exists in this set.
332   bool hasAttribute(StringRef Kind) const;
333 
334   /// Return the attribute object.
335   Attribute getAttribute(Attribute::AttrKind Kind) const;
336 
337   /// Return the target-dependent attribute object.
338   Attribute getAttribute(StringRef Kind) const;
339 
340   MaybeAlign getAlignment() const;
341   MaybeAlign getStackAlignment() const;
342   uint64_t getDereferenceableBytes() const;
343   uint64_t getDereferenceableOrNullBytes() const;
344   Type *getByValType() const;
345   Type *getStructRetType() const;
346   Type *getByRefType() const;
347   Type *getPreallocatedType() const;
348   Type *getInAllocaType() const;
349   Type *getElementType() const;
350   std::pair<unsigned, Optional<unsigned>> getAllocSizeArgs() const;
351   std::pair<unsigned, unsigned> getVScaleRangeArgs() const;
352   std::string getAsString(bool InAttrGrp = false) const;
353 
354   /// Return true if this attribute set belongs to the LLVMContext.
355   bool hasParentContext(LLVMContext &C) const;
356 
357   using iterator = const Attribute *;
358 
359   iterator begin() const;
360   iterator end() const;
361 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
362   void dump() const;
363 #endif
364 };
365 
366 //===----------------------------------------------------------------------===//
367 /// \class
368 /// Provide DenseMapInfo for AttributeSet.
369 template <> struct DenseMapInfo<AttributeSet> {
370   static AttributeSet getEmptyKey() {
371     auto Val = static_cast<uintptr_t>(-1);
372     Val <<= PointerLikeTypeTraits<void *>::NumLowBitsAvailable;
373     return AttributeSet(reinterpret_cast<AttributeSetNode *>(Val));
374   }
375 
376   static AttributeSet getTombstoneKey() {
377     auto Val = static_cast<uintptr_t>(-2);
378     Val <<= PointerLikeTypeTraits<void *>::NumLowBitsAvailable;
379     return AttributeSet(reinterpret_cast<AttributeSetNode *>(Val));
380   }
381 
382   static unsigned getHashValue(AttributeSet AS) {
383     return (unsigned((uintptr_t)AS.SetNode) >> 4) ^
384            (unsigned((uintptr_t)AS.SetNode) >> 9);
385   }
386 
387   static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
388 };
389 
390 //===----------------------------------------------------------------------===//
391 /// \class
392 /// This class holds the attributes for a function, its return value, and
393 /// its parameters. You access the attributes for each of them via an index into
394 /// the AttributeList object. The function attributes are at index
395 /// `AttributeList::FunctionIndex', the return value is at index
396 /// `AttributeList::ReturnIndex', and the attributes for the parameters start at
397 /// index `AttributeList::FirstArgIndex'.
398 class AttributeList {
399 public:
400   enum AttrIndex : unsigned {
401     ReturnIndex = 0U,
402     FunctionIndex = ~0U,
403     FirstArgIndex = 1,
404   };
405 
406 private:
407   friend class AttrBuilder;
408   friend class AttributeListImpl;
409   friend class AttributeSet;
410   friend class AttributeSetNode;
411   template <typename Ty> friend struct DenseMapInfo;
412 
413   /// The attributes that we are managing. This can be null to represent
414   /// the empty attributes list.
415   AttributeListImpl *pImpl = nullptr;
416 
417 public:
418   /// Create an AttributeList with the specified parameters in it.
419   static AttributeList get(LLVMContext &C,
420                            ArrayRef<std::pair<unsigned, Attribute>> Attrs);
421   static AttributeList get(LLVMContext &C,
422                            ArrayRef<std::pair<unsigned, AttributeSet>> Attrs);
423 
424   /// Create an AttributeList from attribute sets for a function, its
425   /// return value, and all of its arguments.
426   static AttributeList get(LLVMContext &C, AttributeSet FnAttrs,
427                            AttributeSet RetAttrs,
428                            ArrayRef<AttributeSet> ArgAttrs);
429 
430 private:
431   explicit AttributeList(AttributeListImpl *LI) : pImpl(LI) {}
432 
433   static AttributeList getImpl(LLVMContext &C, ArrayRef<AttributeSet> AttrSets);
434 
435   AttributeList setAttributes(LLVMContext &C, unsigned Index,
436                               AttributeSet Attrs) const;
437 
438 public:
439   AttributeList() = default;
440 
441   //===--------------------------------------------------------------------===//
442   // AttributeList Construction and Mutation
443   //===--------------------------------------------------------------------===//
444 
445   /// Return an AttributeList with the specified parameters in it.
446   static AttributeList get(LLVMContext &C, ArrayRef<AttributeList> Attrs);
447   static AttributeList get(LLVMContext &C, unsigned Index,
448                            ArrayRef<Attribute::AttrKind> Kinds);
449   static AttributeList get(LLVMContext &C, unsigned Index,
450                            ArrayRef<Attribute::AttrKind> Kinds,
451                            ArrayRef<uint64_t> Values);
452   static AttributeList get(LLVMContext &C, unsigned Index,
453                            ArrayRef<StringRef> Kind);
454   static AttributeList get(LLVMContext &C, unsigned Index,
455                            const AttrBuilder &B);
456 
457   /// Add an attribute to the attribute set at the given index.
458   /// Returns a new list because attribute lists are immutable.
459   LLVM_NODISCARD AttributeList addAttribute(LLVMContext &C, unsigned Index,
460                                             Attribute::AttrKind Kind) const;
461 
462   /// Add an attribute to the attribute set at the given index.
463   /// Returns a new list because attribute lists are immutable.
464   LLVM_NODISCARD AttributeList
465   addAttribute(LLVMContext &C, unsigned Index, StringRef Kind,
466                StringRef Value = StringRef()) const;
467 
468   /// Add an attribute to the attribute set at the given index.
469   /// Returns a new list because attribute lists are immutable.
470   LLVM_NODISCARD AttributeList addAttribute(LLVMContext &C, unsigned Index,
471                                             Attribute A) const;
472 
473   /// Add attributes to the attribute set at the given index.
474   /// Returns a new list because attribute lists are immutable.
475   LLVM_NODISCARD AttributeList addAttributes(LLVMContext &C, unsigned Index,
476                                              const AttrBuilder &B) const;
477 
478   /// Add an argument attribute to the list. Returns a new list because
479   /// attribute lists are immutable.
480   LLVM_NODISCARD AttributeList addParamAttribute(
481       LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const {
482     return addAttribute(C, ArgNo + FirstArgIndex, Kind);
483   }
484 
485   /// Add an argument attribute to the list. Returns a new list because
486   /// attribute lists are immutable.
487   LLVM_NODISCARD AttributeList
488   addParamAttribute(LLVMContext &C, unsigned ArgNo, StringRef Kind,
489                     StringRef Value = StringRef()) const {
490     return addAttribute(C, ArgNo + FirstArgIndex, Kind, Value);
491   }
492 
493   /// Add an attribute to the attribute list at the given arg indices. Returns a
494   /// new list because attribute lists are immutable.
495   LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C,
496                                                  ArrayRef<unsigned> ArgNos,
497                                                  Attribute A) const;
498 
499   /// Add an argument attribute to the list. Returns a new list because
500   /// attribute lists are immutable.
501   LLVM_NODISCARD AttributeList addParamAttributes(LLVMContext &C,
502                                                   unsigned ArgNo,
503                                                   const AttrBuilder &B) const {
504     return addAttributes(C, ArgNo + FirstArgIndex, B);
505   }
506 
507   /// Remove the specified attribute at the specified index from this
508   /// attribute list. Returns a new list because attribute lists are immutable.
509   LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index,
510                                                Attribute::AttrKind Kind) const;
511 
512   /// Remove the specified attribute at the specified index from this
513   /// attribute list. Returns a new list because attribute lists are immutable.
514   LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index,
515                                                StringRef Kind) const;
516 
517   /// Remove the specified attributes at the specified index from this
518   /// attribute list. Returns a new list because attribute lists are immutable.
519   LLVM_NODISCARD AttributeList removeAttributes(
520       LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const;
521 
522   /// Remove all attributes at the specified index from this
523   /// attribute list. Returns a new list because attribute lists are immutable.
524   LLVM_NODISCARD AttributeList removeAttributes(LLVMContext &C,
525                                                 unsigned Index) const;
526 
527   /// Remove the specified attribute at the specified arg index from this
528   /// attribute list. Returns a new list because attribute lists are immutable.
529   LLVM_NODISCARD AttributeList removeParamAttribute(
530       LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const {
531     return removeAttribute(C, ArgNo + FirstArgIndex, Kind);
532   }
533 
534   /// Remove the specified attribute at the specified arg index from this
535   /// attribute list. Returns a new list because attribute lists are immutable.
536   LLVM_NODISCARD AttributeList removeParamAttribute(LLVMContext &C,
537                                                     unsigned ArgNo,
538                                                     StringRef Kind) const {
539     return removeAttribute(C, ArgNo + FirstArgIndex, Kind);
540   }
541 
542   /// Remove the specified attribute at the specified arg index from this
543   /// attribute list. Returns a new list because attribute lists are immutable.
544   LLVM_NODISCARD AttributeList removeParamAttributes(
545       LLVMContext &C, unsigned ArgNo, const AttrBuilder &AttrsToRemove) const {
546     return removeAttributes(C, ArgNo + FirstArgIndex, AttrsToRemove);
547   }
548 
549   /// Remove all attributes at the specified arg index from this
550   /// attribute list. Returns a new list because attribute lists are immutable.
551   LLVM_NODISCARD AttributeList removeParamAttributes(LLVMContext &C,
552                                                      unsigned ArgNo) const {
553     return removeAttributes(C, ArgNo + FirstArgIndex);
554   }
555 
556   /// Replace the type contained by attribute \p AttrKind at index \p ArgNo wih
557   /// \p ReplacementTy, preserving all other attributes.
558   LLVM_NODISCARD AttributeList replaceAttributeType(LLVMContext &C,
559                                                     unsigned ArgNo,
560                                                     Attribute::AttrKind Kind,
561                                                     Type *ReplacementTy) const {
562     Attribute Attr = getAttribute(ArgNo, Kind);
563     auto Attrs = removeAttribute(C, ArgNo, Kind);
564     return Attrs.addAttribute(C, ArgNo, Attr.getWithNewType(C, ReplacementTy));
565   }
566 
567   /// \brief Add the dereferenceable attribute to the attribute set at the given
568   /// index. Returns a new list because attribute lists are immutable.
569   LLVM_NODISCARD AttributeList addDereferenceableAttr(LLVMContext &C,
570                                                       unsigned Index,
571                                                       uint64_t Bytes) const;
572 
573   /// \brief Add the dereferenceable attribute to the attribute set at the given
574   /// arg index. Returns a new list because attribute lists are immutable.
575   LLVM_NODISCARD AttributeList addDereferenceableParamAttr(
576       LLVMContext &C, unsigned ArgNo, uint64_t Bytes) const {
577     return addDereferenceableAttr(C, ArgNo + FirstArgIndex, Bytes);
578   }
579 
580   /// Add the dereferenceable_or_null attribute to the attribute set at
581   /// the given index. Returns a new list because attribute lists are immutable.
582   LLVM_NODISCARD AttributeList addDereferenceableOrNullAttr(
583       LLVMContext &C, unsigned Index, uint64_t Bytes) const;
584 
585   /// Add the dereferenceable_or_null attribute to the attribute set at
586   /// the given arg index. Returns a new list because attribute lists are
587   /// immutable.
588   LLVM_NODISCARD AttributeList addDereferenceableOrNullParamAttr(
589       LLVMContext &C, unsigned ArgNo, uint64_t Bytes) const {
590     return addDereferenceableOrNullAttr(C, ArgNo + FirstArgIndex, Bytes);
591   }
592 
593   /// Add the allocsize attribute to the attribute set at the given index.
594   /// Returns a new list because attribute lists are immutable.
595   LLVM_NODISCARD AttributeList
596   addAllocSizeAttr(LLVMContext &C, unsigned Index, unsigned ElemSizeArg,
597                    const Optional<unsigned> &NumElemsArg);
598 
599   /// Add the allocsize attribute to the attribute set at the given arg index.
600   /// Returns a new list because attribute lists are immutable.
601   LLVM_NODISCARD AttributeList
602   addAllocSizeParamAttr(LLVMContext &C, unsigned ArgNo, unsigned ElemSizeArg,
603                         const Optional<unsigned> &NumElemsArg) {
604     return addAllocSizeAttr(C, ArgNo + FirstArgIndex, ElemSizeArg, NumElemsArg);
605   }
606 
607   /// Add the vscale_range attribute to the attribute set at the given index.
608   /// Returns a new list because attribute lists are immutable.
609   LLVM_NODISCARD AttributeList addVScaleRangeAttr(LLVMContext &C,
610                                                   unsigned Index,
611                                                   unsigned MinValue,
612                                                   unsigned MaxValue);
613 
614   //===--------------------------------------------------------------------===//
615   // AttributeList Accessors
616   //===--------------------------------------------------------------------===//
617 
618   /// The attributes for the specified index are returned.
619   AttributeSet getAttributes(unsigned Index) const;
620 
621   /// The attributes for the argument or parameter at the given index are
622   /// returned.
623   AttributeSet getParamAttributes(unsigned ArgNo) const;
624 
625   /// The attributes for the ret value are returned.
626   AttributeSet getRetAttributes() const;
627 
628   /// The function attributes are returned.
629   AttributeSet getFnAttributes() const;
630 
631   /// Return true if the attribute exists at the given index.
632   bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
633 
634   /// Return true if the attribute exists at the given index.
635   bool hasAttribute(unsigned Index, StringRef Kind) const;
636 
637   /// Return true if attribute exists at the given index.
638   bool hasAttributes(unsigned Index) const;
639 
640   /// Return true if the attribute exists for the given argument
641   bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
642     return hasAttribute(ArgNo + FirstArgIndex, Kind);
643   }
644 
645   /// Return true if the attribute exists for the given argument
646   bool hasParamAttr(unsigned ArgNo, StringRef Kind) const {
647     return hasAttribute(ArgNo + FirstArgIndex, Kind);
648   }
649 
650   /// Return true if attributes exists for the given argument
651   bool hasParamAttrs(unsigned ArgNo) const {
652     return hasAttributes(ArgNo + FirstArgIndex);
653   }
654 
655   /// Equivalent to hasAttribute(AttributeList::FunctionIndex, Kind) but
656   /// may be faster.
657   bool hasFnAttribute(Attribute::AttrKind Kind) const;
658 
659   /// Equivalent to hasAttribute(AttributeList::FunctionIndex, Kind) but
660   /// may be faster.
661   bool hasFnAttribute(StringRef Kind) const;
662 
663   /// Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
664   bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const;
665 
666   /// Return true if the specified attribute is set for at least one
667   /// parameter or for the return value. If Index is not nullptr, the index
668   /// of a parameter with the specified attribute is provided.
669   bool hasAttrSomewhere(Attribute::AttrKind Kind,
670                         unsigned *Index = nullptr) const;
671 
672   /// Return the attribute object that exists at the given index.
673   Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
674 
675   /// Return the attribute object that exists at the given index.
676   Attribute getAttribute(unsigned Index, StringRef Kind) const;
677 
678   /// Return the attribute object that exists at the arg index.
679   Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
680     return getAttribute(ArgNo + FirstArgIndex, Kind);
681   }
682 
683   /// Return the attribute object that exists at the given index.
684   Attribute getParamAttr(unsigned ArgNo, StringRef Kind) const {
685     return getAttribute(ArgNo + FirstArgIndex, Kind);
686   }
687 
688   /// Return the alignment of the return value.
689   MaybeAlign getRetAlignment() const;
690 
691   /// Return the alignment for the specified function parameter.
692   MaybeAlign getParamAlignment(unsigned ArgNo) const;
693 
694   /// Return the stack alignment for the specified function parameter.
695   MaybeAlign getParamStackAlignment(unsigned ArgNo) const;
696 
697   /// Return the byval type for the specified function parameter.
698   Type *getParamByValType(unsigned ArgNo) const;
699 
700   /// Return the sret type for the specified function parameter.
701   Type *getParamStructRetType(unsigned ArgNo) const;
702 
703   /// Return the byref type for the specified function parameter.
704   Type *getParamByRefType(unsigned ArgNo) const;
705 
706   /// Return the preallocated type for the specified function parameter.
707   Type *getParamPreallocatedType(unsigned ArgNo) const;
708 
709   /// Return the inalloca type for the specified function parameter.
710   Type *getParamInAllocaType(unsigned ArgNo) const;
711 
712   /// Return the elementtype type for the specified function parameter.
713   Type *getParamElementType(unsigned ArgNo) const;
714 
715   /// Get the stack alignment.
716   MaybeAlign getStackAlignment(unsigned Index) const;
717 
718   /// Get the number of dereferenceable bytes (or zero if unknown).
719   uint64_t getDereferenceableBytes(unsigned Index) const;
720 
721   /// Get the number of dereferenceable bytes (or zero if unknown) of an
722   /// arg.
723   uint64_t getParamDereferenceableBytes(unsigned ArgNo) const {
724     return getDereferenceableBytes(ArgNo + FirstArgIndex);
725   }
726 
727   /// Get the number of dereferenceable_or_null bytes (or zero if
728   /// unknown).
729   uint64_t getDereferenceableOrNullBytes(unsigned Index) const;
730 
731   /// Get the number of dereferenceable_or_null bytes (or zero if
732   /// unknown) of an arg.
733   uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const {
734     return getDereferenceableOrNullBytes(ArgNo + FirstArgIndex);
735   }
736 
737   /// Get the allocsize argument numbers (or pair(0, 0) if unknown).
738   std::pair<unsigned, Optional<unsigned>>
739   getAllocSizeArgs(unsigned Index) const;
740 
741   /// Get the vscale_range argument numbers (or pair(0, 0) if unknown).
742   std::pair<unsigned, unsigned> getVScaleRangeArgs(unsigned Index) const;
743 
744   /// Return the attributes at the index as a string.
745   std::string getAsString(unsigned Index, bool InAttrGrp = false) const;
746 
747   /// Return true if this attribute list belongs to the LLVMContext.
748   bool hasParentContext(LLVMContext &C) const;
749 
750   //===--------------------------------------------------------------------===//
751   // AttributeList Introspection
752   //===--------------------------------------------------------------------===//
753 
754   using iterator = const AttributeSet *;
755 
756   iterator begin() const;
757   iterator end() const;
758 
759   unsigned getNumAttrSets() const;
760 
761   /// Use these to iterate over the valid attribute indices.
762   unsigned index_begin() const { return AttributeList::FunctionIndex; }
763   unsigned index_end() const { return getNumAttrSets() - 1; }
764 
765   /// operator==/!= - Provide equality predicates.
766   bool operator==(const AttributeList &RHS) const { return pImpl == RHS.pImpl; }
767   bool operator!=(const AttributeList &RHS) const { return pImpl != RHS.pImpl; }
768 
769   /// Return a raw pointer that uniquely identifies this attribute list.
770   void *getRawPointer() const {
771     return pImpl;
772   }
773 
774   /// Return true if there are no attributes.
775   bool isEmpty() const { return pImpl == nullptr; }
776 
777   void print(raw_ostream &O) const;
778 
779   void dump() const;
780 };
781 
782 //===----------------------------------------------------------------------===//
783 /// \class
784 /// Provide DenseMapInfo for AttributeList.
785 template <> struct DenseMapInfo<AttributeList> {
786   static AttributeList getEmptyKey() {
787     auto Val = static_cast<uintptr_t>(-1);
788     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
789     return AttributeList(reinterpret_cast<AttributeListImpl *>(Val));
790   }
791 
792   static AttributeList getTombstoneKey() {
793     auto Val = static_cast<uintptr_t>(-2);
794     Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
795     return AttributeList(reinterpret_cast<AttributeListImpl *>(Val));
796   }
797 
798   static unsigned getHashValue(AttributeList AS) {
799     return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
800            (unsigned((uintptr_t)AS.pImpl) >> 9);
801   }
802 
803   static bool isEqual(AttributeList LHS, AttributeList RHS) {
804     return LHS == RHS;
805   }
806 };
807 
808 //===----------------------------------------------------------------------===//
809 /// \class
810 /// This class is used in conjunction with the Attribute::get method to
811 /// create an Attribute object. The object itself is uniquified. The Builder's
812 /// value, however, is not. So this can be used as a quick way to test for
813 /// equality, presence of attributes, etc.
814 class AttrBuilder {
815   std::bitset<Attribute::EndAttrKinds> Attrs;
816   std::map<SmallString<32>, SmallString<32>, std::less<>> TargetDepAttrs;
817   MaybeAlign Alignment;
818   MaybeAlign StackAlignment;
819   uint64_t DerefBytes = 0;
820   uint64_t DerefOrNullBytes = 0;
821   uint64_t AllocSizeArgs = 0;
822   uint64_t VScaleRangeArgs = 0;
823   std::array<Type *, Attribute::NumTypeAttrKinds> TypeAttrs = {};
824 
825   Optional<unsigned> kindToTypeIndex(Attribute::AttrKind Kind) const;
826 
827 public:
828   AttrBuilder() = default;
829 
830   AttrBuilder(const Attribute &A) {
831     addAttribute(A);
832   }
833 
834   AttrBuilder(AttributeList AS, unsigned Idx);
835   AttrBuilder(AttributeSet AS);
836 
837   void clear();
838 
839   /// Add an attribute to the builder.
840   AttrBuilder &addAttribute(Attribute::AttrKind Val) {
841     assert((unsigned)Val < Attribute::EndAttrKinds &&
842            "Attribute out of range!");
843     assert(Attribute::isEnumAttrKind(Val) &&
844            "Adding integer/type attribute without an argument!");
845     Attrs[Val] = true;
846     return *this;
847   }
848 
849   /// Add the Attribute object to the builder.
850   AttrBuilder &addAttribute(Attribute A);
851 
852   /// Add the target-dependent attribute to the builder.
853   AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
854 
855   /// Remove an attribute from the builder.
856   AttrBuilder &removeAttribute(Attribute::AttrKind Val);
857 
858   /// Remove the attributes from the builder.
859   AttrBuilder &removeAttributes(AttributeList A, uint64_t WithoutIndex);
860 
861   /// Remove the target-dependent attribute to the builder.
862   AttrBuilder &removeAttribute(StringRef A);
863 
864   /// Add the attributes from the builder.
865   AttrBuilder &merge(const AttrBuilder &B);
866 
867   /// Remove the attributes from the builder.
868   AttrBuilder &remove(const AttrBuilder &B);
869 
870   /// Return true if the builder has any attribute that's in the
871   /// specified builder.
872   bool overlaps(const AttrBuilder &B) const;
873 
874   /// Return true if the builder has the specified attribute.
875   bool contains(Attribute::AttrKind A) const {
876     assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
877     return Attrs[A];
878   }
879 
880   /// Return true if the builder has the specified target-dependent
881   /// attribute.
882   bool contains(StringRef A) const;
883 
884   /// Return true if the builder has IR-level attributes.
885   bool hasAttributes() const;
886 
887   /// Return true if the builder has any attribute that's in the
888   /// specified attribute.
889   bool hasAttributes(AttributeList A, uint64_t Index) const;
890 
891   /// Return true if the builder has an alignment attribute.
892   bool hasAlignmentAttr() const;
893 
894   /// Retrieve the alignment attribute, if it exists.
895   MaybeAlign getAlignment() const { return Alignment; }
896 
897   /// Retrieve the stack alignment attribute, if it exists.
898   MaybeAlign getStackAlignment() const { return StackAlignment; }
899 
900   /// Retrieve the number of dereferenceable bytes, if the
901   /// dereferenceable attribute exists (zero is returned otherwise).
902   uint64_t getDereferenceableBytes() const { return DerefBytes; }
903 
904   /// Retrieve the number of dereferenceable_or_null bytes, if the
905   /// dereferenceable_or_null attribute exists (zero is returned otherwise).
906   uint64_t getDereferenceableOrNullBytes() const { return DerefOrNullBytes; }
907 
908   /// Retrieve type for the given type attribute.
909   Type *getTypeAttr(Attribute::AttrKind Kind) const;
910 
911   /// Retrieve the byval type.
912   Type *getByValType() const { return getTypeAttr(Attribute::ByVal); }
913 
914   /// Retrieve the sret type.
915   Type *getStructRetType() const { return getTypeAttr(Attribute::StructRet); }
916 
917   /// Retrieve the byref type.
918   Type *getByRefType() const { return getTypeAttr(Attribute::ByRef); }
919 
920   /// Retrieve the preallocated type.
921   Type *getPreallocatedType() const {
922     return getTypeAttr(Attribute::Preallocated);
923   }
924 
925   /// Retrieve the inalloca type.
926   Type *getInAllocaType() const { return getTypeAttr(Attribute::InAlloca); }
927 
928   /// Retrieve the allocsize args, if the allocsize attribute exists.  If it
929   /// doesn't exist, pair(0, 0) is returned.
930   std::pair<unsigned, Optional<unsigned>> getAllocSizeArgs() const;
931 
932   /// Retrieve the vscale_range args, if the vscale_range attribute exists.  If
933   /// it doesn't exist, pair(0, 0) is returned.
934   std::pair<unsigned, unsigned> getVScaleRangeArgs() const;
935 
936   /// This turns an alignment into the form used internally in Attribute.
937   /// This call has no effect if Align is not set.
938   AttrBuilder &addAlignmentAttr(MaybeAlign Align);
939 
940   /// This turns an int alignment (which must be a power of 2) into the
941   /// form used internally in Attribute.
942   /// This call has no effect if Align is 0.
943   /// Deprecated, use the version using a MaybeAlign.
944   inline AttrBuilder &addAlignmentAttr(unsigned Align) {
945     return addAlignmentAttr(MaybeAlign(Align));
946   }
947 
948   /// This turns a stack alignment into the form used internally in Attribute.
949   /// This call has no effect if Align is not set.
950   AttrBuilder &addStackAlignmentAttr(MaybeAlign Align);
951 
952   /// This turns an int stack alignment (which must be a power of 2) into
953   /// the form used internally in Attribute.
954   /// This call has no effect if Align is 0.
955   /// Deprecated, use the version using a MaybeAlign.
956   inline AttrBuilder &addStackAlignmentAttr(unsigned Align) {
957     return addStackAlignmentAttr(MaybeAlign(Align));
958   }
959 
960   /// This turns the number of dereferenceable bytes into the form used
961   /// internally in Attribute.
962   AttrBuilder &addDereferenceableAttr(uint64_t Bytes);
963 
964   /// This turns the number of dereferenceable_or_null bytes into the
965   /// form used internally in Attribute.
966   AttrBuilder &addDereferenceableOrNullAttr(uint64_t Bytes);
967 
968   /// This turns one (or two) ints into the form used internally in Attribute.
969   AttrBuilder &addAllocSizeAttr(unsigned ElemSizeArg,
970                                 const Optional<unsigned> &NumElemsArg);
971 
972   /// This turns two ints into the form used internally in Attribute.
973   AttrBuilder &addVScaleRangeAttr(unsigned MinValue, unsigned MaxValue);
974 
975   /// Add a type attribute with the given type.
976   AttrBuilder &addTypeAttr(Attribute::AttrKind Kind, Type *Ty);
977 
978   /// This turns a byval type into the form used internally in Attribute.
979   AttrBuilder &addByValAttr(Type *Ty);
980 
981   /// This turns a sret type into the form used internally in Attribute.
982   AttrBuilder &addStructRetAttr(Type *Ty);
983 
984   /// This turns a byref type into the form used internally in Attribute.
985   AttrBuilder &addByRefAttr(Type *Ty);
986 
987   /// This turns a preallocated type into the form used internally in Attribute.
988   AttrBuilder &addPreallocatedAttr(Type *Ty);
989 
990   /// This turns an inalloca type into the form used internally in Attribute.
991   AttrBuilder &addInAllocaAttr(Type *Ty);
992 
993   /// Add an allocsize attribute, using the representation returned by
994   /// Attribute.getIntValue().
995   AttrBuilder &addAllocSizeAttrFromRawRepr(uint64_t RawAllocSizeRepr);
996 
997   /// Add a vscale_range attribute, using the representation returned by
998   /// Attribute.getIntValue().
999   AttrBuilder &addVScaleRangeAttrFromRawRepr(uint64_t RawVScaleRangeRepr);
1000 
1001   /// Return true if the builder contains no target-independent
1002   /// attributes.
1003   bool empty() const { return Attrs.none(); }
1004 
1005   // Iterators for target-dependent attributes.
1006   using td_type = decltype(TargetDepAttrs)::value_type;
1007   using td_iterator = decltype(TargetDepAttrs)::iterator;
1008   using td_const_iterator = decltype(TargetDepAttrs)::const_iterator;
1009   using td_range = iterator_range<td_iterator>;
1010   using td_const_range = iterator_range<td_const_iterator>;
1011 
1012   td_iterator td_begin() { return TargetDepAttrs.begin(); }
1013   td_iterator td_end() { return TargetDepAttrs.end(); }
1014 
1015   td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
1016   td_const_iterator td_end() const { return TargetDepAttrs.end(); }
1017 
1018   td_range td_attrs() { return td_range(td_begin(), td_end()); }
1019 
1020   td_const_range td_attrs() const {
1021     return td_const_range(td_begin(), td_end());
1022   }
1023 
1024   bool td_empty() const { return TargetDepAttrs.empty(); }
1025 
1026   bool operator==(const AttrBuilder &B) const;
1027   bool operator!=(const AttrBuilder &B) const { return !(*this == B); }
1028 };
1029 
1030 namespace AttributeFuncs {
1031 
1032 /// Which attributes cannot be applied to a type.
1033 AttrBuilder typeIncompatible(Type *Ty);
1034 
1035 /// Get param/return attributes which imply immediate undefined behavior if an
1036 /// invalid value is passed. For example, this includes noundef (where undef
1037 /// implies UB), but not nonnull (where null implies poison). It also does not
1038 /// include attributes like nocapture, which constrain the function
1039 /// implementation rather than the passed value.
1040 AttrBuilder getUBImplyingAttributes();
1041 
1042 /// \returns Return true if the two functions have compatible target-independent
1043 /// attributes for inlining purposes.
1044 bool areInlineCompatible(const Function &Caller, const Function &Callee);
1045 
1046 
1047 /// Checks  if there are any incompatible function attributes between
1048 /// \p A and \p B.
1049 ///
1050 /// \param [in] A - The first function to be compared with.
1051 /// \param [in] B - The second function to be compared with.
1052 /// \returns true if the functions have compatible attributes.
1053 bool areOutlineCompatible(const Function &A, const Function &B);
1054 
1055 /// Merge caller's and callee's attributes.
1056 void mergeAttributesForInlining(Function &Caller, const Function &Callee);
1057 
1058 /// Merges the functions attributes from \p ToMerge into function \p Base.
1059 ///
1060 /// \param [in,out] Base - The function being merged into.
1061 /// \param [in] ToMerge - The function to merge attributes from.
1062 void mergeAttributesForOutlining(Function &Base, const Function &ToMerge);
1063 
1064 } // end namespace AttributeFuncs
1065 
1066 } // end namespace llvm
1067 
1068 #endif // LLVM_IR_ATTRIBUTES_H
1069