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