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