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