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