Attributes Rewrite
[oota-llvm.git] / lib / VMCore / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
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 implements the AttributesList class and Attribute utilities.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Attributes.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/Type.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/Support/Atomic.h"
20 #include "llvm/Support/Mutex.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // Attributes Implementation
28 //===----------------------------------------------------------------------===//
29
30 Attributes::Attributes(LLVMContext &C, ArrayRef<AttrVal> Vals) {
31   Attributes::Builder B;
32   for (ArrayRef<AttrVal>::iterator I = Vals.begin(), E = Vals.end();
33        I != E; ++I)
34     B.addAttribute(*I);
35   Attrs = Attributes::get(C, B).Attrs;
36 }
37
38 Attributes::Attributes(AttributesImpl *A) : Attrs(A) {}
39
40 Attributes::Attributes(const Attributes &A) : Attrs(A.Attrs) {}
41
42 Attributes Attributes::get(LLVMContext &Context, Attributes::Builder &B) {
43   // If there are no attributes, return an empty Attributes class.
44   if (B.Bits == 0)
45     return Attributes();
46
47   // Otherwise, build a key to look up the existing attributes.
48   LLVMContextImpl *pImpl = Context.pImpl;
49   FoldingSetNodeID ID;
50   ID.AddInteger(B.Bits);
51
52   void *InsertPoint;
53   AttributesImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
54
55   if (!PA) {
56     // If we didn't find any existing attributes of the same shape then create a
57     // new one and insert it.
58     PA = new AttributesImpl(B.Bits);
59     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
60   }
61
62   // Return the AttributesList that we found or created.
63   return Attributes(PA);
64 }
65
66 bool Attributes::hasAttribute(AttrVal Val) const {
67   return Attrs && Attrs->hasAttribute(Val);
68 }
69
70 bool Attributes::hasAttributes(const Attributes &A) const {
71   return Attrs && Attrs->hasAttributes(A);
72 }
73
74 /// This returns the alignment field of an attribute as a byte alignment value.
75 unsigned Attributes::getAlignment() const {
76   if (!hasAttribute(Attributes::Alignment))
77     return 0;
78   return 1U << ((Attrs->getAlignment() >> 16) - 1);
79 }
80
81 /// This returns the stack alignment field of an attribute as a byte alignment
82 /// value.
83 unsigned Attributes::getStackAlignment() const {
84   if (!hasAttribute(Attributes::StackAlignment))
85     return 0;
86   return 1U << ((Attrs->getStackAlignment() >> 26) - 1);
87 }
88
89 uint64_t Attributes::Raw() const {
90   return Attrs ? Attrs->Bits : 0; // FIXME: Don't access this directly!
91 }
92
93 Attributes Attributes::typeIncompatible(Type *Ty) {
94   Attributes::Builder Incompatible;
95   
96   if (!Ty->isIntegerTy())
97     // Attributes that only apply to integers.
98     Incompatible.addAttribute(Attributes::SExt)
99       .addAttribute(Attributes::ZExt);
100   
101   if (!Ty->isPointerTy())
102     // Attributes that only apply to pointers.
103     Incompatible.addAttribute(Attributes::ByVal)
104       .addAttribute(Attributes::Nest)
105       .addAttribute(Attributes::NoAlias)
106       .addAttribute(Attributes::NoCapture)
107       .addAttribute(Attributes::StructRet);
108   
109   return Attributes::get(Ty->getContext(), Incompatible);
110 }
111
112 std::string Attributes::getAsString() const {
113   std::string Result;
114   if (hasAttribute(Attributes::ZExt))
115     Result += "zeroext ";
116   if (hasAttribute(Attributes::SExt))
117     Result += "signext ";
118   if (hasAttribute(Attributes::NoReturn))
119     Result += "noreturn ";
120   if (hasAttribute(Attributes::NoUnwind))
121     Result += "nounwind ";
122   if (hasAttribute(Attributes::UWTable))
123     Result += "uwtable ";
124   if (hasAttribute(Attributes::ReturnsTwice))
125     Result += "returns_twice ";
126   if (hasAttribute(Attributes::InReg))
127     Result += "inreg ";
128   if (hasAttribute(Attributes::NoAlias))
129     Result += "noalias ";
130   if (hasAttribute(Attributes::NoCapture))
131     Result += "nocapture ";
132   if (hasAttribute(Attributes::StructRet))
133     Result += "sret ";
134   if (hasAttribute(Attributes::ByVal))
135     Result += "byval ";
136   if (hasAttribute(Attributes::Nest))
137     Result += "nest ";
138   if (hasAttribute(Attributes::ReadNone))
139     Result += "readnone ";
140   if (hasAttribute(Attributes::ReadOnly))
141     Result += "readonly ";
142   if (hasAttribute(Attributes::OptimizeForSize))
143     Result += "optsize ";
144   if (hasAttribute(Attributes::NoInline))
145     Result += "noinline ";
146   if (hasAttribute(Attributes::InlineHint))
147     Result += "inlinehint ";
148   if (hasAttribute(Attributes::AlwaysInline))
149     Result += "alwaysinline ";
150   if (hasAttribute(Attributes::StackProtect))
151     Result += "ssp ";
152   if (hasAttribute(Attributes::StackProtectReq))
153     Result += "sspreq ";
154   if (hasAttribute(Attributes::NoRedZone))
155     Result += "noredzone ";
156   if (hasAttribute(Attributes::NoImplicitFloat))
157     Result += "noimplicitfloat ";
158   if (hasAttribute(Attributes::Naked))
159     Result += "naked ";
160   if (hasAttribute(Attributes::NonLazyBind))
161     Result += "nonlazybind ";
162   if (hasAttribute(Attributes::AddressSafety))
163     Result += "address_safety ";
164   if (hasAttribute(Attributes::StackAlignment)) {
165     Result += "alignstack(";
166     Result += utostr(getStackAlignment());
167     Result += ") ";
168   }
169   if (hasAttribute(Attributes::Alignment)) {
170     Result += "align ";
171     Result += utostr(getAlignment());
172     Result += " ";
173   }
174   // Trim the trailing space.
175   assert(!Result.empty() && "Unknown attribute!");
176   Result.erase(Result.end()-1);
177   return Result;
178 }
179
180 //===----------------------------------------------------------------------===//
181 // Attributes::Builder Implementation
182 //===----------------------------------------------------------------------===//
183
184 Attributes::Builder &Attributes::Builder::
185 addAttribute(Attributes::AttrVal Val) {
186   Bits |= AttributesImpl::getAttrMask(Val);
187   return *this;
188 }
189
190 Attributes::Builder &Attributes::Builder::addRawValue(uint64_t Val) {
191   Bits |= Val;
192   return *this;
193 }
194
195 Attributes::Builder &Attributes::Builder::addAlignmentAttr(unsigned Align) {
196   if (Align == 0) return *this;
197   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
198   assert(Align <= 0x40000000 && "Alignment too large.");
199   Bits |= (Log2_32(Align) + 1) << 16;
200   return *this;
201 }
202 Attributes::Builder &Attributes::Builder::addStackAlignmentAttr(unsigned Align){
203   // Default alignment, allow the target to define how to align it.
204   if (Align == 0) return *this;
205   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
206   assert(Align <= 0x100 && "Alignment too large.");
207   Bits |= (Log2_32(Align) + 1) << 26;
208   return *this;
209 }
210
211 Attributes::Builder &Attributes::Builder::
212 removeAttribute(Attributes::AttrVal Val) {
213   Bits &= ~AttributesImpl::getAttrMask(Val);
214   return *this;
215 }
216
217 Attributes::Builder &Attributes::Builder::addAttributes(const Attributes &A) {
218   Bits |= A.Raw();
219   return *this;
220 }
221
222 Attributes::Builder &Attributes::Builder::removeAttributes(const Attributes &A){
223   Bits &= ~A.Raw();
224   return *this;
225 }
226
227 bool Attributes::Builder::hasAttribute(Attributes::AttrVal A) const {
228   return Bits & AttributesImpl::getAttrMask(A);
229 }
230
231 bool Attributes::Builder::hasAttributes() const {
232   return Bits != 0;
233 }
234 bool Attributes::Builder::hasAttributes(const Attributes &A) const {
235   return Bits & A.Raw();
236 }
237 bool Attributes::Builder::hasAlignmentAttr() const {
238   return Bits & AttributesImpl::getAttrMask(Attributes::Alignment);
239 }
240
241 uint64_t Attributes::Builder::getAlignment() const {
242   if (!hasAlignmentAttr())
243     return 0;
244   return 1U <<
245     (((Bits & AttributesImpl::getAttrMask(Attributes::Alignment)) >> 16) - 1);
246 }
247
248 uint64_t Attributes::Builder::getStackAlignment() const {
249   if (!hasAlignmentAttr())
250     return 0;
251   return 1U <<
252     (((Bits & AttributesImpl::getAttrMask(Attributes::StackAlignment))>>26)-1);
253 }
254
255 //===----------------------------------------------------------------------===//
256 // AttributeImpl Definition
257 //===----------------------------------------------------------------------===//
258
259 uint64_t AttributesImpl::getAttrMask(uint64_t Val) {
260   switch (Val) {
261   case Attributes::None:            return 0;
262   case Attributes::ZExt:            return 1 << 0;
263   case Attributes::SExt:            return 1 << 1;
264   case Attributes::NoReturn:        return 1 << 2;
265   case Attributes::InReg:           return 1 << 3;
266   case Attributes::StructRet:       return 1 << 4;
267   case Attributes::NoUnwind:        return 1 << 5;
268   case Attributes::NoAlias:         return 1 << 6;
269   case Attributes::ByVal:           return 1 << 7;
270   case Attributes::Nest:            return 1 << 8;
271   case Attributes::ReadNone:        return 1 << 9;
272   case Attributes::ReadOnly:        return 1 << 10;
273   case Attributes::NoInline:        return 1 << 11;
274   case Attributes::AlwaysInline:    return 1 << 12;
275   case Attributes::OptimizeForSize: return 1 << 13;
276   case Attributes::StackProtect:    return 1 << 14;
277   case Attributes::StackProtectReq: return 1 << 15;
278   case Attributes::Alignment:       return 31 << 16;
279   case Attributes::NoCapture:       return 1 << 21;
280   case Attributes::NoRedZone:       return 1 << 22;
281   case Attributes::NoImplicitFloat: return 1 << 23;
282   case Attributes::Naked:           return 1 << 24;
283   case Attributes::InlineHint:      return 1 << 25;
284   case Attributes::StackAlignment:  return 7 << 26;
285   case Attributes::ReturnsTwice:    return 1 << 29;
286   case Attributes::UWTable:         return 1 << 30;
287   case Attributes::NonLazyBind:     return 1U << 31;
288   case Attributes::AddressSafety:   return 1ULL << 32;
289   }
290   llvm_unreachable("Unsupported attribute type");
291 }
292
293 bool AttributesImpl::hasAttribute(uint64_t A) const {
294   return (Bits & getAttrMask(A)) != 0;
295 }
296
297 bool AttributesImpl::hasAttributes() const {
298   return Bits != 0;
299 }
300
301 bool AttributesImpl::hasAttributes(const Attributes &A) const {
302   return Bits & A.Raw();        // FIXME: Raw() won't work here in the future.
303 }
304
305 uint64_t AttributesImpl::getAlignment() const {
306   return Bits & getAttrMask(Attributes::Alignment);
307 }
308
309 uint64_t AttributesImpl::getStackAlignment() const {
310   return Bits & getAttrMask(Attributes::StackAlignment);
311 }
312
313 //===----------------------------------------------------------------------===//
314 // AttributeListImpl Definition
315 //===----------------------------------------------------------------------===//
316
317 namespace llvm {
318   class AttributeListImpl;
319 }
320
321 static ManagedStatic<FoldingSet<AttributeListImpl> > AttributesLists;
322
323 namespace llvm {
324 static ManagedStatic<sys::SmartMutex<true> > ALMutex;
325
326 class AttributeListImpl : public FoldingSetNode {
327   sys::cas_flag RefCount;
328   
329   // AttributesList is uniqued, these should not be publicly available.
330   void operator=(const AttributeListImpl &) LLVM_DELETED_FUNCTION;
331   AttributeListImpl(const AttributeListImpl &) LLVM_DELETED_FUNCTION;
332   ~AttributeListImpl();                        // Private implementation
333 public:
334   SmallVector<AttributeWithIndex, 4> Attrs;
335   
336   AttributeListImpl(ArrayRef<AttributeWithIndex> attrs)
337     : Attrs(attrs.begin(), attrs.end()) {
338     RefCount = 0;
339   }
340   
341   void AddRef() {
342     sys::SmartScopedLock<true> Lock(*ALMutex);
343     ++RefCount;
344   }
345   void DropRef() {
346     sys::SmartScopedLock<true> Lock(*ALMutex);
347     if (!AttributesLists.isConstructed())
348       return;
349     sys::cas_flag new_val = --RefCount;
350     if (new_val == 0)
351       delete this;
352   }
353   
354   void Profile(FoldingSetNodeID &ID) const {
355     Profile(ID, Attrs);
356   }
357   static void Profile(FoldingSetNodeID &ID, ArrayRef<AttributeWithIndex> Attrs){
358     for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
359       ID.AddInteger(Attrs[i].Attrs.Raw());
360       ID.AddInteger(Attrs[i].Index);
361     }
362   }
363 };
364 }
365
366 AttributeListImpl::~AttributeListImpl() {
367   // NOTE: Lock must be acquired by caller.
368   AttributesLists->RemoveNode(this);
369 }
370
371
372 AttrListPtr AttrListPtr::get(ArrayRef<AttributeWithIndex> Attrs) {
373   // If there are no attributes then return a null AttributesList pointer.
374   if (Attrs.empty())
375     return AttrListPtr();
376   
377 #ifndef NDEBUG
378   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
379     assert(Attrs[i].Attrs.hasAttributes() && 
380            "Pointless attribute!");
381     assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
382            "Misordered AttributesList!");
383   }
384 #endif
385   
386   // Otherwise, build a key to look up the existing attributes.
387   FoldingSetNodeID ID;
388   AttributeListImpl::Profile(ID, Attrs);
389   void *InsertPos;
390   
391   sys::SmartScopedLock<true> Lock(*ALMutex);
392   
393   AttributeListImpl *PAL =
394     AttributesLists->FindNodeOrInsertPos(ID, InsertPos);
395   
396   // If we didn't find any existing attributes of the same shape then
397   // create a new one and insert it.
398   if (!PAL) {
399     PAL = new AttributeListImpl(Attrs);
400     AttributesLists->InsertNode(PAL, InsertPos);
401   }
402   
403   // Return the AttributesList that we found or created.
404   return AttrListPtr(PAL);
405 }
406
407
408 //===----------------------------------------------------------------------===//
409 // AttrListPtr Method Implementations
410 //===----------------------------------------------------------------------===//
411
412 AttrListPtr::AttrListPtr(AttributeListImpl *LI) : AttrList(LI) {
413   if (LI) LI->AddRef();
414 }
415
416 AttrListPtr::AttrListPtr(const AttrListPtr &P) : AttrList(P.AttrList) {
417   if (AttrList) AttrList->AddRef();  
418 }
419
420 const AttrListPtr &AttrListPtr::operator=(const AttrListPtr &RHS) {
421   sys::SmartScopedLock<true> Lock(*ALMutex);
422   if (AttrList == RHS.AttrList) return *this;
423   if (AttrList) AttrList->DropRef();
424   AttrList = RHS.AttrList;
425   if (AttrList) AttrList->AddRef();
426   return *this;
427 }
428
429 AttrListPtr::~AttrListPtr() {
430   if (AttrList) AttrList->DropRef();
431 }
432
433 /// getNumSlots - Return the number of slots used in this attribute list. 
434 /// This is the number of arguments that have an attribute set on them
435 /// (including the function itself).
436 unsigned AttrListPtr::getNumSlots() const {
437   return AttrList ? AttrList->Attrs.size() : 0;
438 }
439
440 /// getSlot - Return the AttributeWithIndex at the specified slot.  This
441 /// holds a number plus a set of attributes.
442 const AttributeWithIndex &AttrListPtr::getSlot(unsigned Slot) const {
443   assert(AttrList && Slot < AttrList->Attrs.size() && "Slot # out of range!");
444   return AttrList->Attrs[Slot];
445 }
446
447
448 /// getAttributes - The attributes for the specified index are
449 /// returned.  Attributes for the result are denoted with Idx = 0.
450 /// Function notes are denoted with idx = ~0.
451 Attributes AttrListPtr::getAttributes(unsigned Idx) const {
452   if (AttrList == 0) return Attributes();
453   
454   const SmallVector<AttributeWithIndex, 4> &Attrs = AttrList->Attrs;
455   for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
456     if (Attrs[i].Index == Idx)
457       return Attrs[i].Attrs;
458
459   return Attributes();
460 }
461
462 /// hasAttrSomewhere - Return true if the specified attribute is set for at
463 /// least one parameter or for the return value.
464 bool AttrListPtr::hasAttrSomewhere(Attributes::AttrVal Attr) const {
465   if (AttrList == 0) return false;
466
467   const SmallVector<AttributeWithIndex, 4> &Attrs = AttrList->Attrs;
468   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
469     if (Attrs[i].Attrs.hasAttribute(Attr))
470       return true;
471   return false;
472 }
473
474 unsigned AttrListPtr::getNumAttrs() const {
475   return AttrList ? AttrList->Attrs.size() : 0;
476 }
477
478 Attributes &AttrListPtr::getAttributesAtIndex(unsigned i) const {
479   assert(AttrList && "Trying to get an attribute from an empty list!");
480   assert(i < AttrList->Attrs.size() && "Index out of range!");
481   return AttrList->Attrs[i].Attrs;
482 }
483
484 AttrListPtr AttrListPtr::addAttr(LLVMContext &C, unsigned Idx,
485                                  Attributes Attrs) const {
486   Attributes OldAttrs = getAttributes(Idx);
487 #ifndef NDEBUG
488   // FIXME it is not obvious how this should work for alignment.
489   // For now, say we can't change a known alignment.
490   unsigned OldAlign = OldAttrs.getAlignment();
491   unsigned NewAlign = Attrs.getAlignment();
492   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
493          "Attempt to change alignment!");
494 #endif
495   
496   Attributes::Builder NewAttrs =
497     Attributes::Builder(OldAttrs).addAttributes(Attrs);
498   if (NewAttrs == Attributes::Builder(OldAttrs))
499     return *this;
500   
501   SmallVector<AttributeWithIndex, 8> NewAttrList;
502   if (AttrList == 0)
503     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
504   else {
505     const SmallVector<AttributeWithIndex, 4> &OldAttrList = AttrList->Attrs;
506     unsigned i = 0, e = OldAttrList.size();
507     // Copy attributes for arguments before this one.
508     for (; i != e && OldAttrList[i].Index < Idx; ++i)
509       NewAttrList.push_back(OldAttrList[i]);
510
511     // If there are attributes already at this index, merge them in.
512     if (i != e && OldAttrList[i].Index == Idx) {
513       Attrs =
514         Attributes::get(C, Attributes::Builder(Attrs).
515                         addAttributes(OldAttrList[i].Attrs));
516       ++i;
517     }
518     
519     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
520     
521     // Copy attributes for arguments after this one.
522     NewAttrList.insert(NewAttrList.end(), 
523                        OldAttrList.begin()+i, OldAttrList.end());
524   }
525   
526   return get(NewAttrList);
527 }
528
529 AttrListPtr AttrListPtr::removeAttr(LLVMContext &C, unsigned Idx,
530                                     Attributes Attrs) const {
531 #ifndef NDEBUG
532   // FIXME it is not obvious how this should work for alignment.
533   // For now, say we can't pass in alignment, which no current use does.
534   assert(!Attrs.hasAttribute(Attributes::Alignment) &&
535          "Attempt to exclude alignment!");
536 #endif
537   if (AttrList == 0) return AttrListPtr();
538   
539   Attributes OldAttrs = getAttributes(Idx);
540   Attributes::Builder NewAttrs =
541     Attributes::Builder(OldAttrs).removeAttributes(Attrs);
542   if (NewAttrs == Attributes::Builder(OldAttrs))
543     return *this;
544
545   SmallVector<AttributeWithIndex, 8> NewAttrList;
546   const SmallVector<AttributeWithIndex, 4> &OldAttrList = AttrList->Attrs;
547   unsigned i = 0, e = OldAttrList.size();
548   
549   // Copy attributes for arguments before this one.
550   for (; i != e && OldAttrList[i].Index < Idx; ++i)
551     NewAttrList.push_back(OldAttrList[i]);
552   
553   // If there are attributes already at this index, merge them in.
554   assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
555   Attrs = Attributes::get(C, Attributes::Builder(OldAttrList[i].Attrs).
556                           removeAttributes(Attrs));
557   ++i;
558   if (Attrs.hasAttributes()) // If any attributes left for this param, add them.
559     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
560   
561   // Copy attributes for arguments after this one.
562   NewAttrList.insert(NewAttrList.end(), 
563                      OldAttrList.begin()+i, OldAttrList.end());
564   
565   return get(NewAttrList);
566 }
567
568 void AttrListPtr::dump() const {
569   dbgs() << "PAL[ ";
570   for (unsigned i = 0; i < getNumSlots(); ++i) {
571     const AttributeWithIndex &PAWI = getSlot(i);
572     dbgs() << "{" << PAWI.Index << "," << PAWI.Attrs.getAsString() << "} ";
573   }
574   
575   dbgs() << "]\n";
576 }