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