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