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