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