Attributes.h revision 29fce9ad39636d38f43add5d7c23e83d9d1cc249
1//===-- llvm/Attributes.h - Container for Attributes ------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file contains the simple types necessary to represent the
12/// attributes associated with functions and their calls.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_IR_ATTRIBUTES_H
17#define LLVM_IR_ATTRIBUTES_H
18
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/FoldingSet.h"
21#include "llvm/Support/PointerLikeTypeTraits.h"
22#include <bitset>
23#include <cassert>
24#include <map>
25#include <string>
26
27namespace llvm {
28
29class AttrBuilder;
30class AttributeImpl;
31class AttributeSetImpl;
32class AttributeSetNode;
33class Constant;
34template<typename T> struct DenseMapInfo;
35class LLVMContext;
36class Type;
37
38//===----------------------------------------------------------------------===//
39/// \class
40/// \brief Functions, function parameters, and return types can have attributes
41/// to indicate how they should be treated by optimizations and code
42/// generation. This class represents one of those attributes. It's light-weight
43/// and should be passed around by-value.
44class Attribute {
45public:
46  /// This enumeration lists the attributes that can be associated with
47  /// parameters, function results, or the function itself.
48  ///
49  /// Note: The `uwtable' attribute is about the ABI or the user mandating an
50  /// entry in the unwind table. The `nounwind' attribute is about an exception
51  /// passing by the function.
52  ///
53  /// In a theoretical system that uses tables for profiling and SjLj for
54  /// exceptions, they would be fully independent. In a normal system that uses
55  /// tables for both, the semantics are:
56  ///
57  /// nil                = Needs an entry because an exception might pass by.
58  /// nounwind           = No need for an entry
59  /// uwtable            = Needs an entry because the ABI says so and because
60  ///                      an exception might pass by.
61  /// uwtable + nounwind = Needs an entry because the ABI says so.
62
63  enum AttrKind {
64    // IR-Level Attributes
65    None,                  ///< No attributes have been set
66    Alignment,             ///< Alignment of parameter (5 bits)
67                           ///< stored as log2 of alignment with +1 bias
68                           ///< 0 means unaligned (different from align(1))
69    AlwaysInline,          ///< inline=always
70    ByVal,                 ///< Pass structure by value
71    InlineHint,            ///< Source said inlining was desirable
72    InReg,                 ///< Force argument to be passed in register
73    MinSize,               ///< Function must be optimized for size first
74    Naked,                 ///< Naked function
75    Nest,                  ///< Nested function static chain
76    NoAlias,               ///< Considered to not alias after call
77    NoBuiltin,             ///< Callee isn't recognized as a builtin
78    NoCapture,             ///< Function creates no aliases of pointer
79    NoDuplicate,           ///< Call cannot be duplicated
80    NoImplicitFloat,       ///< Disable implicit floating point insts
81    NoInline,              ///< inline=never
82    NonLazyBind,           ///< Function is called early and/or
83                           ///< often, so lazy binding isn't worthwhile
84    NoRedZone,             ///< Disable redzone
85    NoReturn,              ///< Mark the function as not returning
86    NoUnwind,              ///< Function doesn't unwind stack
87    OptimizeForSize,       ///< opt_size
88    ReadNone,              ///< Function does not access memory
89    ReadOnly,              ///< Function only reads from memory
90    Returned,              ///< Return value is always equal to this argument
91    ReturnsTwice,          ///< Function can return twice
92    SExt,                  ///< Sign extended before/after call
93    StackAlignment,        ///< Alignment of stack for function (3 bits)
94                           ///< stored as log2 of alignment with +1 bias 0
95                           ///< means unaligned (different from
96                           ///< alignstack=(1))
97    StackProtect,          ///< Stack protection.
98    StackProtectReq,       ///< Stack protection required.
99    StackProtectStrong,    ///< Strong Stack protection.
100    StructRet,             ///< Hidden pointer to structure to return
101    SanitizeAddress,       ///< AddressSanitizer is on.
102    SanitizeThread,        ///< ThreadSanitizer is on.
103    SanitizeMemory,        ///< MemorySanitizer is on.
104    UWTable,               ///< Function must be in a unwind table
105    ZExt,                  ///< Zero extended before/after call
106
107    EndAttrKinds           ///< Sentinal value useful for loops
108  };
109private:
110  AttributeImpl *pImpl;
111  Attribute(AttributeImpl *A) : pImpl(A) {}
112public:
113  Attribute() : pImpl(0) {}
114
115  //===--------------------------------------------------------------------===//
116  // Attribute Construction
117  //===--------------------------------------------------------------------===//
118
119  /// \brief Return a uniquified Attribute object.
120  static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val = 0);
121  static Attribute get(LLVMContext &Context, StringRef Kind,
122                       StringRef Val = StringRef());
123
124  /// \brief Return a uniquified Attribute object that has the specific
125  /// alignment set.
126  static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align);
127  static Attribute getWithStackAlignment(LLVMContext &Context, uint64_t Align);
128
129  //===--------------------------------------------------------------------===//
130  // Attribute Accessors
131  //===--------------------------------------------------------------------===//
132
133  /// \brief Return true if the attribute is an Attribute::AttrKind type.
134  bool isEnumAttribute() const;
135
136  /// \brief Return true if the attribute is an alignment attribute.
137  bool isAlignAttribute() const;
138
139  /// \brief Return true if the attribute is a string (target-dependent)
140  /// attribute.
141  bool isStringAttribute() const;
142
143  /// \brief Return true if the attribute is present.
144  bool hasAttribute(AttrKind Val) const;
145
146  /// \brief Return true if the target-dependent attribute is present.
147  bool hasAttribute(StringRef Val) const;
148
149  /// \brief Return the attribute's kind as an enum (Attribute::AttrKind). This
150  /// requires the attribute to be an enum or alignment attribute.
151  Attribute::AttrKind getKindAsEnum() const;
152
153  /// \brief Return the attribute's value as an integer. This requires that the
154  /// attribute be an alignment attribute.
155  uint64_t getValueAsInt() const;
156
157  /// \brief Return the attribute's kind as a string. This requires the
158  /// attribute to be a string attribute.
159  StringRef getKindAsString() const;
160
161  /// \brief Return the attribute's value as a string. This requires the
162  /// attribute to be a string attribute.
163  StringRef getValueAsString() const;
164
165  /// \brief Returns the alignment field of an attribute as a byte alignment
166  /// value.
167  unsigned getAlignment() const;
168
169  /// \brief Returns the stack alignment field of an attribute as a byte
170  /// alignment value.
171  unsigned getStackAlignment() const;
172
173  /// \brief The Attribute is converted to a string of equivalent mnemonic. This
174  /// is, presumably, for writing out the mnemonics for the assembly writer.
175  std::string getAsString(bool InAttrGrp = false) const;
176
177  /// \brief Equality and non-equality operators.
178  bool operator==(Attribute A) const { return pImpl == A.pImpl; }
179  bool operator!=(Attribute A) const { return pImpl != A.pImpl; }
180
181  /// \brief Less-than operator. Useful for sorting the attributes list.
182  bool operator<(Attribute A) const;
183
184  void Profile(FoldingSetNodeID &ID) const {
185    ID.AddPointer(pImpl);
186  }
187};
188
189//===----------------------------------------------------------------------===//
190/// \class
191/// \brief This class holds the attributes for a function, its return value, and
192/// its parameters. You access the attributes for each of them via an index into
193/// the AttributeSet object. The function attributes are at index
194/// `AttributeSet::FunctionIndex', the return value is at index
195/// `AttributeSet::ReturnIndex', and the attributes for the parameters start at
196/// index `1'.
197class AttributeSet {
198public:
199  enum AttrIndex {
200    ReturnIndex = 0U,
201    FunctionIndex = ~0U
202  };
203private:
204  friend class AttrBuilder;
205  friend class AttributeSetImpl;
206  template <typename Ty> friend struct DenseMapInfo;
207
208  /// \brief The attributes that we are managing. This can be null to represent
209  /// the empty attributes list.
210  AttributeSetImpl *pImpl;
211
212  /// \brief The attributes for the specified index are returned.
213  AttributeSetNode *getAttributes(unsigned Index) const;
214
215  /// \brief Create an AttributeSet with the specified parameters in it.
216  static AttributeSet get(LLVMContext &C,
217                          ArrayRef<std::pair<unsigned, Attribute> > Attrs);
218  static AttributeSet get(LLVMContext &C,
219                          ArrayRef<std::pair<unsigned,
220                                             AttributeSetNode*> > Attrs);
221
222  static AttributeSet getImpl(LLVMContext &C,
223                              ArrayRef<std::pair<unsigned,
224                                                 AttributeSetNode*> > Attrs);
225
226
227  explicit AttributeSet(AttributeSetImpl *LI) : pImpl(LI) {}
228public:
229  AttributeSet() : pImpl(0) {}
230
231  //===--------------------------------------------------------------------===//
232  // AttributeSet Construction and Mutation
233  //===--------------------------------------------------------------------===//
234
235  /// \brief Return an AttributeSet with the specified parameters in it.
236  static AttributeSet get(LLVMContext &C, ArrayRef<AttributeSet> Attrs);
237  static AttributeSet get(LLVMContext &C, unsigned Index,
238                          ArrayRef<Attribute::AttrKind> Kind);
239  static AttributeSet get(LLVMContext &C, unsigned Index, AttrBuilder &B);
240
241  /// \brief Add an attribute to the attribute set at the given index. Since
242  /// attribute sets are immutable, this returns a new set.
243  AttributeSet addAttribute(LLVMContext &C, unsigned Index,
244                            Attribute::AttrKind Attr) const;
245
246  /// \brief Add an attribute to the attribute set at the given index. Since
247  /// attribute sets are immutable, this returns a new set.
248  AttributeSet addAttribute(LLVMContext &C, unsigned Index,
249                            StringRef Kind) const;
250
251  /// \brief Add attributes to the attribute set at the given index. Since
252  /// attribute sets are immutable, this returns a new set.
253  AttributeSet addAttributes(LLVMContext &C, unsigned Index,
254                             AttributeSet Attrs) const;
255
256  /// \brief Remove the specified attribute at the specified index from this
257  /// attribute list. Since attribute lists are immutable, this returns the new
258  /// list.
259  AttributeSet removeAttribute(LLVMContext &C, unsigned Index,
260                               Attribute::AttrKind Attr) const;
261
262  /// \brief Remove the specified attributes at the specified index from this
263  /// attribute list. Since attribute lists are immutable, this returns the new
264  /// list.
265  AttributeSet removeAttributes(LLVMContext &C, unsigned Index,
266                                AttributeSet Attrs) const;
267
268  //===--------------------------------------------------------------------===//
269  // AttributeSet Accessors
270  //===--------------------------------------------------------------------===//
271
272  /// \brief Retrieve the LLVM context.
273  LLVMContext &getContext() const;
274
275  /// \brief The attributes for the specified index are returned.
276  AttributeSet getParamAttributes(unsigned Index) const;
277
278  /// \brief The attributes for the ret value are returned.
279  AttributeSet getRetAttributes() const;
280
281  /// \brief The function attributes are returned.
282  AttributeSet getFnAttributes() const;
283
284  /// \brief Return true if the attribute exists at the given index.
285  bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const;
286
287  /// \brief Return true if the attribute exists at the given index.
288  bool hasAttribute(unsigned Index, StringRef Kind) const;
289
290  /// \brief Return true if attribute exists at the given index.
291  bool hasAttributes(unsigned Index) const;
292
293  /// \brief Return true if the specified attribute is set for at least one
294  /// parameter or for the return value.
295  bool hasAttrSomewhere(Attribute::AttrKind Attr) const;
296
297  /// \brief Return the attribute object that exists at the given index.
298  Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const;
299
300  /// \brief Return the attribute object that exists at the given index.
301  Attribute getAttribute(unsigned Index, StringRef Kind) const;
302
303  /// \brief Return the alignment for the specified function parameter.
304  unsigned getParamAlignment(unsigned Index) const;
305
306  /// \brief Get the stack alignment.
307  unsigned getStackAlignment(unsigned Index) const;
308
309  /// \brief Return the attributes at the index as a string.
310  std::string getAsString(unsigned Index, bool InAttrGrp = false) const;
311
312  typedef ArrayRef<Attribute>::iterator iterator;
313
314  iterator begin(unsigned Slot) const;
315  iterator end(unsigned Slot) const;
316
317  /// operator==/!= - Provide equality predicates.
318  bool operator==(const AttributeSet &RHS) const {
319    return pImpl == RHS.pImpl;
320  }
321  bool operator!=(const AttributeSet &RHS) const {
322    return pImpl != RHS.pImpl;
323  }
324
325  //===--------------------------------------------------------------------===//
326  // AttributeSet Introspection
327  //===--------------------------------------------------------------------===//
328
329  // FIXME: Remove this.
330  uint64_t Raw(unsigned Index) const;
331
332  /// \brief Return a raw pointer that uniquely identifies this attribute list.
333  void *getRawPointer() const {
334    return pImpl;
335  }
336
337  /// \brief Return true if there are no attributes.
338  bool isEmpty() const {
339    return getNumSlots() == 0;
340  }
341
342  /// \brief Return the number of slots used in this attribute list.  This is
343  /// the number of arguments that have an attribute set on them (including the
344  /// function itself).
345  unsigned getNumSlots() const;
346
347  /// \brief Return the index for the given slot.
348  uint64_t getSlotIndex(unsigned Slot) const;
349
350  /// \brief Return the attributes at the given slot.
351  AttributeSet getSlotAttributes(unsigned Slot) const;
352
353  void dump() const;
354};
355
356//===----------------------------------------------------------------------===//
357/// \class
358/// \brief Provide DenseMapInfo for AttributeSet.
359template<> struct DenseMapInfo<AttributeSet> {
360  static inline AttributeSet getEmptyKey() {
361    uintptr_t Val = static_cast<uintptr_t>(-1);
362    Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
363    return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
364  }
365  static inline AttributeSet getTombstoneKey() {
366    uintptr_t Val = static_cast<uintptr_t>(-2);
367    Val <<= PointerLikeTypeTraits<void*>::NumLowBitsAvailable;
368    return AttributeSet(reinterpret_cast<AttributeSetImpl*>(Val));
369  }
370  static unsigned getHashValue(AttributeSet AS) {
371    return (unsigned((uintptr_t)AS.pImpl) >> 4) ^
372           (unsigned((uintptr_t)AS.pImpl) >> 9);
373  }
374  static bool isEqual(AttributeSet LHS, AttributeSet RHS) { return LHS == RHS; }
375};
376
377//===----------------------------------------------------------------------===//
378/// \class
379/// \brief This class is used in conjunction with the Attribute::get method to
380/// create an Attribute object. The object itself is uniquified. The Builder's
381/// value, however, is not. So this can be used as a quick way to test for
382/// equality, presence of attributes, etc.
383class AttrBuilder {
384  std::bitset<Attribute::EndAttrKinds> Attrs;
385  std::map<std::string, std::string> TargetDepAttrs;
386  uint64_t Alignment;
387  uint64_t StackAlignment;
388public:
389  AttrBuilder() : Attrs(0), Alignment(0), StackAlignment(0) {}
390  explicit AttrBuilder(uint64_t Val)
391    : Attrs(0), Alignment(0), StackAlignment(0) {
392    addRawValue(Val);
393  }
394  AttrBuilder(const Attribute &A) : Attrs(0), Alignment(0), StackAlignment(0) {
395    addAttribute(A);
396  }
397  AttrBuilder(AttributeSet AS, unsigned Idx);
398  AttrBuilder(const AttrBuilder &B)
399    : Attrs(B.Attrs),
400      TargetDepAttrs(B.TargetDepAttrs.begin(), B.TargetDepAttrs.end()),
401      Alignment(B.Alignment), StackAlignment(B.StackAlignment) {}
402
403  void clear();
404
405  /// \brief Add an attribute to the builder.
406  AttrBuilder &addAttribute(Attribute::AttrKind Val);
407
408  /// \brief Add the Attribute object to the builder.
409  AttrBuilder &addAttribute(Attribute A);
410
411  /// \brief Add the target-dependent attribute to the builder.
412  AttrBuilder &addAttribute(StringRef A, StringRef V = StringRef());
413
414  /// \brief Remove an attribute from the builder.
415  AttrBuilder &removeAttribute(Attribute::AttrKind Val);
416
417  /// \brief Remove the attributes from the builder.
418  AttrBuilder &removeAttributes(AttributeSet A, uint64_t Index);
419
420  /// \brief Remove the target-dependent attribute to the builder.
421  AttrBuilder &removeAttribute(StringRef A);
422
423  /// \brief Add the attributes from the builder.
424  AttrBuilder &merge(const AttrBuilder &B);
425
426  /// \brief Return true if the builder has the specified attribute.
427  bool contains(Attribute::AttrKind A) const {
428    assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!");
429    return Attrs[A];
430  }
431
432  /// \brief Return true if the builder has the specified target-dependent
433  /// attribute.
434  bool contains(StringRef A) const;
435
436  /// \brief Return true if the builder has IR-level attributes.
437  bool hasAttributes() const;
438
439  /// \brief Return true if the builder has any attribute that's in the
440  /// specified attribute.
441  bool hasAttributes(AttributeSet A, uint64_t Index) const;
442
443  /// \brief Return true if the builder has an alignment attribute.
444  bool hasAlignmentAttr() const;
445
446  /// \brief Retrieve the alignment attribute, if it exists.
447  uint64_t getAlignment() const { return Alignment; }
448
449  /// \brief Retrieve the stack alignment attribute, if it exists.
450  uint64_t getStackAlignment() const { return StackAlignment; }
451
452  /// \brief This turns an int alignment (which must be a power of 2) into the
453  /// form used internally in Attribute.
454  AttrBuilder &addAlignmentAttr(unsigned Align);
455
456  /// \brief This turns an int stack alignment (which must be a power of 2) into
457  /// the form used internally in Attribute.
458  AttrBuilder &addStackAlignmentAttr(unsigned Align);
459
460  /// \brief Return true if the builder contains no target-independent
461  /// attributes.
462  bool empty() const { return Attrs.none(); }
463
464  // Iterators for target-dependent attributes.
465  typedef std::pair<std::string, std::string>                td_type;
466  typedef std::map<std::string, std::string>::iterator       td_iterator;
467  typedef std::map<std::string, std::string>::const_iterator td_const_iterator;
468
469  td_iterator td_begin()             { return TargetDepAttrs.begin(); }
470  td_iterator td_end()               { return TargetDepAttrs.end(); }
471
472  td_const_iterator td_begin() const { return TargetDepAttrs.begin(); }
473  td_const_iterator td_end() const   { return TargetDepAttrs.end(); }
474
475  bool td_empty() const              { return TargetDepAttrs.empty(); }
476
477  bool operator==(const AttrBuilder &B);
478  bool operator!=(const AttrBuilder &B) {
479    return !(*this == B);
480  }
481
482  // FIXME: Remove this in 4.0.
483
484  /// \brief Add the raw value to the internal representation.
485  AttrBuilder &addRawValue(uint64_t Val);
486};
487
488namespace AttributeFuncs {
489
490/// \brief Which attributes cannot be applied to a type.
491AttributeSet typeIncompatible(Type *Ty, uint64_t Index);
492
493} // end AttributeFuncs namespace
494
495} // end llvm namespace
496
497#endif
498