Add comments.
[oota-llvm.git] / include / llvm / 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 // This file contains the simple types necessary to represent the
11 // attributes associated with functions and their calls.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ATTRIBUTES_H
16 #define LLVM_ATTRIBUTES_H
17
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include <cassert>
21 #include <string>
22
23 namespace llvm {
24
25 class LLVMContext;
26 class Type;
27
28 /// AttributeImpl - The internal representation of the Attributes class. This is
29 /// uniquified.
30 class AttributesImpl;
31
32 /// Attributes - A bitset of attributes.
33 class Attributes {
34 public:
35   /// Function parameters and results can have attributes to indicate how they
36   /// should be treated by optimizations and code generation. This enumeration
37   /// lists the attributes that can be associated with parameters, function
38   /// results or the function itself.
39   /// 
40   /// Note that uwtable is about the ABI or the user mandating an entry in the
41   /// unwind table. The nounwind attribute is about an exception passing by the
42   /// function.
43   /// 
44   /// In a theoretical system that uses tables for profiling and sjlj for
45   /// exceptions, they would be fully independent. In a normal system that uses
46   /// tables for both, the semantics are:
47   /// 
48   /// nil                = Needs an entry because an exception might pass by.
49   /// nounwind           = No need for an entry
50   /// uwtable            = Needs an entry because the ABI says so and because
51   ///                      an exception might pass by.
52   /// uwtable + nounwind = Needs an entry because the ABI says so.
53
54   enum AttrVal {
55     // IR-Level Attributes
56     None            = 0,   ///< No attributes have been set
57     AddressSafety   = 1,   ///< Address safety checking is on.
58     Alignment       = 2,   ///< Alignment of parameter (5 bits)
59                            ///< stored as log2 of alignment with +1 bias
60                            ///< 0 means unaligned different from align 1
61     AlwaysInline    = 3,   ///< inline=always
62     ByVal           = 4,   ///< Pass structure by value
63     InlineHint      = 5,   ///< Source said inlining was desirable
64     InReg           = 6,   ///< Force argument to be passed in register
65     Naked           = 7,   ///< Naked function
66     Nest            = 8,   ///< Nested function static chain
67     NoAlias         = 9,   ///< Considered to not alias after call
68     NoCapture       = 10,  ///< Function creates no aliases of pointer
69     NoImplicitFloat = 11,  ///< Disable implicit floating point insts
70     NoInline        = 12,  ///< inline=never
71     NonLazyBind     = 13,  ///< Function is called early and/or
72                            ///< often, so lazy binding isn't worthwhile
73     NoRedZone       = 14,  ///< Disable redzone
74     NoReturn        = 15,  ///< Mark the function as not returning
75     NoUnwind        = 16,  ///< Function doesn't unwind stack
76     OptimizeForSize = 17,  ///< opt_size
77     ReadNone        = 18,  ///< Function does not access memory
78     ReadOnly        = 19,  ///< Function only reads from memory
79     ReturnsTwice    = 20,  ///< Function can return twice
80     SExt            = 21,  ///< Sign extended before/after call
81     StackAlignment  = 22,  ///< Alignment of stack for function (3 bits)
82                            ///< stored as log2 of alignment with +1 bias 0
83                            ///< means unaligned (different from
84                            ///< alignstack={1))
85     StackProtect    = 23,  ///< Stack protection.
86     StackProtectReq = 24,  ///< Stack protection required.
87     StructRet       = 25,  ///< Hidden pointer to structure to return
88     UWTable         = 26,  ///< Function must be in a unwind table
89     ZExt            = 27   ///< Zero extended before/after call
90   };
91 private:
92   AttributesImpl *Attrs;
93   Attributes(AttributesImpl *A);
94 public:
95   Attributes() : Attrs(0) {}
96   Attributes(const Attributes &A);
97   Attributes &operator=(const Attributes &A) {
98     Attrs = A.Attrs;
99     return *this;
100   }
101
102   /// get - Return a uniquified Attributes object. This takes the uniquified
103   /// value from the Builder and wraps it in the Attributes class.
104   class Builder;
105   static Attributes get(LLVMContext &Context, ArrayRef<AttrVal> Vals);
106   static Attributes get(LLVMContext &Context, Builder &B);
107
108   //===--------------------------------------------------------------------===//
109   /// Attributes::Builder - This class is used in conjunction with the
110   /// Attributes::get method to create an Attributes object. The object itself
111   /// is uniquified. The Builder's value, however, is not. So this can be used
112   /// as a quick way to test for equality, presence of attributes, etc.
113   class Builder {
114     friend class Attributes;
115     uint64_t Bits;
116   public:
117     Builder() : Bits(0) {}
118     explicit Builder(uint64_t B) : Bits(B) {}
119     Builder(const Attributes &A) : Bits(A.Raw()) {}
120     Builder(const Builder &B) : Bits(B.Bits) {}
121
122     void clear() { Bits = 0; }
123
124     /// addAttribute - Add an attribute to the builder.
125     Builder &addAttribute(Attributes::AttrVal Val);
126
127     /// removeAttribute - Remove an attribute from the builder.
128     Builder &removeAttribute(Attributes::AttrVal Val);
129
130     /// addAttribute - Add the attributes from A to the builder.
131     Builder &addAttributes(const Attributes &A);
132
133     /// removeAttribute - Remove the attributes from A from the builder.
134     Builder &removeAttributes(const Attributes &A);
135
136     /// hasAttribute - Return true if the builder has the specified attribute.
137     bool hasAttribute(Attributes::AttrVal A) const;
138
139     /// hasAttributes - Return true if the builder has IR-level attributes.
140     bool hasAttributes() const;
141
142     /// hasAttributes - Return true if the builder has any attribute that's in
143     /// the specified attribute.
144     bool hasAttributes(const Attributes &A) const;
145
146     /// hasAlignmentAttr - Return true if the builder has an alignment
147     /// attribute.
148     bool hasAlignmentAttr() const;
149
150     /// getAlignment - Retrieve the alignment attribute, if it exists.
151     uint64_t getAlignment() const;
152
153     /// getStackAlignment - Retrieve the stack alignment attribute, if it
154     /// exists.
155     uint64_t getStackAlignment() const;
156
157     /// addAlignmentAttr - This turns an int alignment (which must be a power of
158     /// 2) into the form used internally in Attributes.
159     Builder &addAlignmentAttr(unsigned Align);
160
161     /// addStackAlignmentAttr - This turns an int stack alignment (which must be
162     /// a power of 2) into the form used internally in Attributes.
163     Builder &addStackAlignmentAttr(unsigned Align);
164
165     /// addRawValue - Add the raw value to the internal representation.
166     /// N.B. This should be used ONLY for decoding LLVM bitcode!
167     Builder &addRawValue(uint64_t Val);
168
169     /// @brief Remove attributes that are used on functions only.
170     void removeFunctionOnlyAttrs() {
171       removeAttribute(Attributes::NoReturn)
172         .removeAttribute(Attributes::NoUnwind)
173         .removeAttribute(Attributes::ReadNone)
174         .removeAttribute(Attributes::ReadOnly)
175         .removeAttribute(Attributes::NoInline)
176         .removeAttribute(Attributes::AlwaysInline)
177         .removeAttribute(Attributes::OptimizeForSize)
178         .removeAttribute(Attributes::StackProtect)
179         .removeAttribute(Attributes::StackProtectReq)
180         .removeAttribute(Attributes::NoRedZone)
181         .removeAttribute(Attributes::NoImplicitFloat)
182         .removeAttribute(Attributes::Naked)
183         .removeAttribute(Attributes::InlineHint)
184         .removeAttribute(Attributes::StackAlignment)
185         .removeAttribute(Attributes::UWTable)
186         .removeAttribute(Attributes::NonLazyBind)
187         .removeAttribute(Attributes::ReturnsTwice)
188         .removeAttribute(Attributes::AddressSafety);
189     }
190
191     bool operator==(const Builder &B) {
192       return Bits == B.Bits;
193     }
194     bool operator!=(const Builder &B) {
195       return Bits != B.Bits;
196     }
197   };
198
199   /// @brief Return true if the attribute is present.
200   bool hasAttribute(AttrVal Val) const;
201
202   /// @brief Return true if attributes exist
203   bool hasAttributes() const;
204
205   /// @brief Return true if the attributes are a non-null intersection.
206   bool hasAttributes(const Attributes &A) const;
207
208   /// @brief Returns the alignment field of an attribute as a byte alignment
209   /// value.
210   unsigned getAlignment() const;
211
212   /// @brief Returns the stack alignment field of an attribute as a byte
213   /// alignment value.
214   unsigned getStackAlignment() const;
215
216   /// @brief Parameter attributes that do not apply to vararg call arguments.
217   bool hasIncompatibleWithVarArgsAttrs() const {
218     return hasAttribute(Attributes::StructRet);
219   }
220
221   /// @brief Attributes that only apply to function parameters.
222   bool hasParameterOnlyAttrs() const {
223     return hasAttribute(Attributes::ByVal) ||
224       hasAttribute(Attributes::Nest) ||
225       hasAttribute(Attributes::StructRet) ||
226       hasAttribute(Attributes::NoCapture);
227   }
228
229   /// @brief Attributes that may be applied to the function itself.  These cannot
230   /// be used on return values or function parameters.
231   bool hasFunctionOnlyAttrs() const {
232     return hasAttribute(Attributes::NoReturn) ||
233       hasAttribute(Attributes::NoUnwind) ||
234       hasAttribute(Attributes::ReadNone) ||
235       hasAttribute(Attributes::ReadOnly) ||
236       hasAttribute(Attributes::NoInline) ||
237       hasAttribute(Attributes::AlwaysInline) ||
238       hasAttribute(Attributes::OptimizeForSize) ||
239       hasAttribute(Attributes::StackProtect) ||
240       hasAttribute(Attributes::StackProtectReq) ||
241       hasAttribute(Attributes::NoRedZone) ||
242       hasAttribute(Attributes::NoImplicitFloat) ||
243       hasAttribute(Attributes::Naked) ||
244       hasAttribute(Attributes::InlineHint) ||
245       hasAttribute(Attributes::StackAlignment) ||
246       hasAttribute(Attributes::UWTable) ||
247       hasAttribute(Attributes::NonLazyBind) ||
248       hasAttribute(Attributes::ReturnsTwice) ||
249       hasAttribute(Attributes::AddressSafety);
250   }
251
252   bool operator==(const Attributes &A) const {
253     return Attrs == A.Attrs;
254   }
255   bool operator!=(const Attributes &A) const {
256     return Attrs != A.Attrs;
257   }
258
259   uint64_t Raw() const;
260
261   /// @brief Which attributes cannot be applied to a type.
262   static Attributes typeIncompatible(Type *Ty);
263
264   /// encodeLLVMAttributesForBitcode - This returns an integer containing an
265   /// encoding of all the LLVM attributes found in the given attribute bitset.
266   /// Any change to this encoding is a breaking change to bitcode compatibility.
267   static uint64_t encodeLLVMAttributesForBitcode(Attributes Attrs) {
268     // FIXME: It doesn't make sense to store the alignment information as an
269     // expanded out value, we should store it as a log2 value.  However, we
270     // can't just change that here without breaking bitcode compatibility.  If
271     // this ever becomes a problem in practice, we should introduce new tag
272     // numbers in the bitcode file and have those tags use a more efficiently
273     // encoded alignment field.
274
275     // Store the alignment in the bitcode as a 16-bit raw value instead of a
276     // 5-bit log2 encoded value. Shift the bits above the alignment up by 11
277     // bits.
278     uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
279     if (Attrs.hasAttribute(Attributes::Alignment))
280       EncodedAttrs |= Attrs.getAlignment() << 16;
281     EncodedAttrs |= (Attrs.Raw() & (0xfffULL << 21)) << 11;
282     return EncodedAttrs;
283   }
284
285   /// decodeLLVMAttributesForBitcode - This returns an attribute bitset
286   /// containing the LLVM attributes that have been decoded from the given
287   /// integer.  This function must stay in sync with
288   /// 'encodeLLVMAttributesForBitcode'.
289   static Attributes decodeLLVMAttributesForBitcode(LLVMContext &C,
290                                                    uint64_t EncodedAttrs) {
291     // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
292     // the bits above 31 down by 11 bits.
293     unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
294     assert((!Alignment || isPowerOf2_32(Alignment)) &&
295            "Alignment must be a power of two.");
296
297     Attributes::Builder B(EncodedAttrs & 0xffff);
298     if (Alignment)
299       B.addAlignmentAttr(Alignment);
300     B.addRawValue((EncodedAttrs & (0xfffULL << 32)) >> 11);
301     return Attributes::get(C, B);
302   }
303
304   /// getAsString - The set of Attributes set in Attributes is converted to a
305   /// string of equivalent mnemonics. This is, presumably, for writing out the
306   /// mnemonics for the assembly writer.
307   /// @brief Convert attribute bits to text
308   std::string getAsString() const;
309 };
310
311 //===----------------------------------------------------------------------===//
312 // AttributeWithIndex
313 //===----------------------------------------------------------------------===//
314
315 /// AttributeWithIndex - This is just a pair of values to associate a set of
316 /// attributes with an index.
317 struct AttributeWithIndex {
318   Attributes Attrs;  ///< The attributes that are set, or'd together.
319   unsigned Index;    ///< Index of the parameter for which the attributes apply.
320                      ///< Index 0 is used for return value attributes.
321                      ///< Index ~0U is used for function attributes.
322
323   static AttributeWithIndex get(LLVMContext &C, unsigned Idx,
324                                 ArrayRef<Attributes::AttrVal> Attrs) {
325     Attributes::Builder B;
326
327     for (ArrayRef<Attributes::AttrVal>::iterator I = Attrs.begin(),
328            E = Attrs.end(); I != E; ++I)
329       B.addAttribute(*I);
330
331     AttributeWithIndex P;
332     P.Index = Idx;
333     P.Attrs = Attributes::get(C, B);
334     return P;
335   }
336   static AttributeWithIndex get(unsigned Idx, Attributes Attrs) {
337     AttributeWithIndex P;
338     P.Index = Idx;
339     P.Attrs = Attrs;
340     return P;
341   }
342 };
343
344 //===----------------------------------------------------------------------===//
345 // AttrListPtr Smart Pointer
346 //===----------------------------------------------------------------------===//
347
348 class AttributeListImpl;
349
350 /// AttrListPtr - This class manages the ref count for the opaque
351 /// AttributeListImpl object and provides accessors for it.
352 class AttrListPtr {
353 public:
354   enum AttrIndex {
355     ReturnIndex = 0U,
356     FunctionIndex = ~0U
357   };
358 private:
359   /// AttrList - The attributes that we are managing.  This can be null
360   /// to represent the empty attributes list.
361   AttributeListImpl *AttrList;
362 public:
363   AttrListPtr() : AttrList(0) {}
364   AttrListPtr(const AttrListPtr &P);
365   const AttrListPtr &operator=(const AttrListPtr &RHS);
366   ~AttrListPtr();
367
368   //===--------------------------------------------------------------------===//
369   // Attribute List Construction and Mutation
370   //===--------------------------------------------------------------------===//
371
372   /// get - Return a Attributes list with the specified parameters in it.
373   static AttrListPtr get(ArrayRef<AttributeWithIndex> Attrs);
374
375   /// addAttr - Add the specified attribute at the specified index to this
376   /// attribute list.  Since attribute lists are immutable, this
377   /// returns the new list.
378   AttrListPtr addAttr(LLVMContext &C, unsigned Idx, Attributes Attrs) const;
379
380   /// removeAttr - Remove the specified attribute at the specified index from
381   /// this attribute list.  Since attribute lists are immutable, this
382   /// returns the new list.
383   AttrListPtr removeAttr(LLVMContext &C, unsigned Idx, Attributes Attrs) const;
384
385   //===--------------------------------------------------------------------===//
386   // Attribute List Accessors
387   //===--------------------------------------------------------------------===//
388   /// getParamAttributes - The attributes for the specified index are
389   /// returned.
390   Attributes getParamAttributes(unsigned Idx) const {
391     return getAttributes(Idx);
392   }
393
394   /// getRetAttributes - The attributes for the ret value are
395   /// returned.
396   Attributes getRetAttributes() const {
397     return getAttributes(ReturnIndex);
398   }
399
400   /// getFnAttributes - The function attributes are returned.
401   Attributes getFnAttributes() const {
402     return getAttributes(FunctionIndex);
403   }
404
405   /// paramHasAttr - Return true if the specified parameter index has the
406   /// specified attribute set.
407   bool paramHasAttr(unsigned Idx, Attributes Attr) const {
408     return getAttributes(Idx).hasAttributes(Attr);
409   }
410
411   /// getParamAlignment - Return the alignment for the specified function
412   /// parameter.
413   unsigned getParamAlignment(unsigned Idx) const {
414     return getAttributes(Idx).getAlignment();
415   }
416
417   /// hasAttrSomewhere - Return true if the specified attribute is set for at
418   /// least one parameter or for the return value.
419   bool hasAttrSomewhere(Attributes::AttrVal Attr) const;
420
421   unsigned getNumAttrs() const;
422   Attributes &getAttributesAtIndex(unsigned i) const;
423
424   /// operator==/!= - Provide equality predicates.
425   bool operator==(const AttrListPtr &RHS) const
426   { return AttrList == RHS.AttrList; }
427   bool operator!=(const AttrListPtr &RHS) const
428   { return AttrList != RHS.AttrList; }
429
430   void dump() const;
431
432   //===--------------------------------------------------------------------===//
433   // Attribute List Introspection
434   //===--------------------------------------------------------------------===//
435
436   /// getRawPointer - Return a raw pointer that uniquely identifies this
437   /// attribute list.
438   void *getRawPointer() const {
439     return AttrList;
440   }
441
442   // Attributes are stored as a dense set of slots, where there is one
443   // slot for each argument that has an attribute.  This allows walking over the
444   // dense set instead of walking the sparse list of attributes.
445
446   /// isEmpty - Return true if there are no attributes.
447   ///
448   bool isEmpty() const {
449     return AttrList == 0;
450   }
451
452   /// getNumSlots - Return the number of slots used in this attribute list.
453   /// This is the number of arguments that have an attribute set on them
454   /// (including the function itself).
455   unsigned getNumSlots() const;
456
457   /// getSlot - Return the AttributeWithIndex at the specified slot.  This
458   /// holds a index number plus a set of attributes.
459   const AttributeWithIndex &getSlot(unsigned Slot) const;
460
461 private:
462   explicit AttrListPtr(AttributeListImpl *L);
463
464   /// getAttributes - The attributes for the specified index are
465   /// returned.  Attributes for the result are denoted with Idx = 0.
466   Attributes getAttributes(unsigned Idx) const;
467 };
468
469 } // End llvm namespace
470
471 #endif