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