964a404bffc78b1274dd636686578e9f9dea967f
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attribute.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 Attribute, AttributeImpl, AttrBuilder,
11 // AttributeSetImpl, and AttributeSet classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/Attributes.h"
16 #include "AttributeImpl.h"
17 #include "LLVMContextImpl.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/Support/Atomic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // Attribute Implementation
30 //===----------------------------------------------------------------------===//
31
32 Attribute Attribute::get(LLVMContext &Context, ArrayRef<AttrKind> Vals) {
33   AttrBuilder B;
34   for (ArrayRef<AttrKind>::iterator I = Vals.begin(), E = Vals.end();
35        I != E; ++I)
36     B.addAttribute(*I);
37   return Attribute::get(Context, B);
38 }
39
40 Attribute Attribute::get(LLVMContext &Context, AttrBuilder &B) {
41   // If there are no attributes, return an empty Attribute class.
42   if (!B.hasAttributes())
43     return Attribute();
44
45   // Otherwise, build a key to look up the existing attributes.
46   LLVMContextImpl *pImpl = Context.pImpl;
47   FoldingSetNodeID ID;
48   ID.AddInteger(B.Raw());
49
50   void *InsertPoint;
51   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
52
53   if (!PA) {
54     // If we didn't find any existing attributes of the same shape then create a
55     // new one and insert it.
56     PA = new AttributeImpl(Context, B.Raw());
57     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
58   }
59
60   // Return the AttributesList that we found or created.
61   return Attribute(PA);
62 }
63
64 bool Attribute::hasAttribute(AttrKind Val) const {
65   return pImpl && pImpl->hasAttribute(Val);
66 }
67
68 bool Attribute::hasAttributes() const {
69   return pImpl && pImpl->hasAttributes();
70 }
71
72 /// This returns the alignment field of an attribute as a byte alignment value.
73 unsigned Attribute::getAlignment() const {
74   if (!hasAttribute(Attribute::Alignment))
75     return 0;
76   return 1U << ((pImpl->getAlignment() >> 16) - 1);
77 }
78
79 void Attribute::setAlignment(unsigned Align) {
80   assert(hasAttribute(Attribute::Alignment) &&
81          "Trying to set the alignment on a non-alignment attribute!");
82   pImpl->setAlignment(Align);
83 }
84
85 /// This returns the stack alignment field of an attribute as a byte alignment
86 /// value.
87 unsigned Attribute::getStackAlignment() const {
88   if (!hasAttribute(Attribute::StackAlignment))
89     return 0;
90   return 1U << ((pImpl->getStackAlignment() >> 26) - 1);
91 }
92
93 void Attribute::setStackAlignment(unsigned Align) {
94   assert(hasAttribute(Attribute::StackAlignment) &&
95          "Trying to set the stack alignment on a non-alignment attribute!");
96   pImpl->setStackAlignment(Align);
97 }
98
99 bool Attribute::operator==(AttrKind K) const {
100   return pImpl && *pImpl == K;
101 }
102 bool Attribute::operator!=(AttrKind K) const {
103   return !(*this == K);
104 }
105
106 uint64_t Attribute::Raw() const {
107   return pImpl ? pImpl->Raw() : 0;
108 }
109
110 Attribute Attribute::typeIncompatible(Type *Ty) {
111   AttrBuilder Incompatible;
112
113   if (!Ty->isIntegerTy())
114     // Attribute that only apply to integers.
115     Incompatible.addAttribute(Attribute::SExt)
116       .addAttribute(Attribute::ZExt);
117
118   if (!Ty->isPointerTy())
119     // Attribute that only apply to pointers.
120     Incompatible.addAttribute(Attribute::ByVal)
121       .addAttribute(Attribute::Nest)
122       .addAttribute(Attribute::NoAlias)
123       .addAttribute(Attribute::NoCapture)
124       .addAttribute(Attribute::StructRet);
125
126   return Attribute::get(Ty->getContext(), Incompatible);
127 }
128
129 /// encodeLLVMAttributesForBitcode - This returns an integer containing an
130 /// encoding of all the LLVM attributes found in the given attribute bitset.
131 /// Any change to this encoding is a breaking change to bitcode compatibility.
132 uint64_t Attribute::encodeLLVMAttributesForBitcode(Attribute Attrs) {
133   // FIXME: It doesn't make sense to store the alignment information as an
134   // expanded out value, we should store it as a log2 value.  However, we can't
135   // just change that here without breaking bitcode compatibility.  If this ever
136   // becomes a problem in practice, we should introduce new tag numbers in the
137   // bitcode file and have those tags use a more efficiently encoded alignment
138   // field.
139
140   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
141   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
142   uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
143   if (Attrs.hasAttribute(Attribute::Alignment))
144     EncodedAttrs |= Attrs.getAlignment() << 16;
145   EncodedAttrs |= (Attrs.Raw() & (0xffffULL << 21)) << 11;
146   return EncodedAttrs;
147 }
148
149 /// decodeLLVMAttributesForBitcode - This returns an attribute bitset containing
150 /// the LLVM attributes that have been decoded from the given integer.  This
151 /// function must stay in sync with 'encodeLLVMAttributesForBitcode'.
152 Attribute Attribute::decodeLLVMAttributesForBitcode(LLVMContext &C,
153                                                     uint64_t EncodedAttrs) {
154   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
155   // the bits above 31 down by 11 bits.
156   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
157   assert((!Alignment || isPowerOf2_32(Alignment)) &&
158          "Alignment must be a power of two.");
159
160   AttrBuilder B(EncodedAttrs & 0xffff);
161   if (Alignment)
162     B.addAlignmentAttr(Alignment);
163   B.addRawValue((EncodedAttrs & (0xffffULL << 32)) >> 11);
164   return Attribute::get(C, B);
165 }
166
167 std::string Attribute::getAsString() const {
168   std::string Result;
169   if (hasAttribute(Attribute::ZExt))
170     Result += "zeroext ";
171   if (hasAttribute(Attribute::SExt))
172     Result += "signext ";
173   if (hasAttribute(Attribute::NoReturn))
174     Result += "noreturn ";
175   if (hasAttribute(Attribute::NoUnwind))
176     Result += "nounwind ";
177   if (hasAttribute(Attribute::UWTable))
178     Result += "uwtable ";
179   if (hasAttribute(Attribute::ReturnsTwice))
180     Result += "returns_twice ";
181   if (hasAttribute(Attribute::InReg))
182     Result += "inreg ";
183   if (hasAttribute(Attribute::NoAlias))
184     Result += "noalias ";
185   if (hasAttribute(Attribute::NoCapture))
186     Result += "nocapture ";
187   if (hasAttribute(Attribute::StructRet))
188     Result += "sret ";
189   if (hasAttribute(Attribute::ByVal))
190     Result += "byval ";
191   if (hasAttribute(Attribute::Nest))
192     Result += "nest ";
193   if (hasAttribute(Attribute::ReadNone))
194     Result += "readnone ";
195   if (hasAttribute(Attribute::ReadOnly))
196     Result += "readonly ";
197   if (hasAttribute(Attribute::OptimizeForSize))
198     Result += "optsize ";
199   if (hasAttribute(Attribute::NoInline))
200     Result += "noinline ";
201   if (hasAttribute(Attribute::InlineHint))
202     Result += "inlinehint ";
203   if (hasAttribute(Attribute::AlwaysInline))
204     Result += "alwaysinline ";
205   if (hasAttribute(Attribute::StackProtect))
206     Result += "ssp ";
207   if (hasAttribute(Attribute::StackProtectReq))
208     Result += "sspreq ";
209   if (hasAttribute(Attribute::StackProtectStrong))
210     Result += "sspstrong ";
211   if (hasAttribute(Attribute::NoRedZone))
212     Result += "noredzone ";
213   if (hasAttribute(Attribute::NoImplicitFloat))
214     Result += "noimplicitfloat ";
215   if (hasAttribute(Attribute::Naked))
216     Result += "naked ";
217   if (hasAttribute(Attribute::NonLazyBind))
218     Result += "nonlazybind ";
219   if (hasAttribute(Attribute::AddressSafety))
220     Result += "address_safety ";
221   if (hasAttribute(Attribute::MinSize))
222     Result += "minsize ";
223   if (hasAttribute(Attribute::StackAlignment)) {
224     Result += "alignstack(";
225     Result += utostr(getStackAlignment());
226     Result += ") ";
227   }
228   if (hasAttribute(Attribute::Alignment)) {
229     Result += "align ";
230     Result += utostr(getAlignment());
231     Result += " ";
232   }
233   if (hasAttribute(Attribute::NoDuplicate))
234     Result += "noduplicate ";
235   // Trim the trailing space.
236   assert(!Result.empty() && "Unknown attribute!");
237   Result.erase(Result.end()-1);
238   return Result;
239 }
240
241 //===----------------------------------------------------------------------===//
242 // AttrBuilder Method Implementations
243 //===----------------------------------------------------------------------===//
244
245 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
246   : Alignment(0), StackAlignment(0) {
247   AttributeSetImpl *pImpl = AS.AttrList;
248   if (!pImpl) return;
249
250   ArrayRef<AttributeWithIndex> AttrList = pImpl->getAttributes();
251   const AttributeWithIndex *AWI = 0;
252   for (unsigned I = 0, E = AttrList.size(); I != E; ++I)
253     if (AttrList[I].Index == Idx) {
254       AWI = &AttrList[I];
255       break;
256     }
257
258   if (!AWI) return;
259
260   uint64_t Mask = AWI->Attrs.Raw();
261
262   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
263        I = Attribute::AttrKind(I + 1)) {
264     if (uint64_t A = (Mask & AttributeImpl::getAttrMask(I))) {
265       Attrs.insert(I);
266
267       if (I == Attribute::Alignment)
268         Alignment = 1ULL << ((A >> 16) - 1);
269       else if (I == Attribute::StackAlignment)
270         StackAlignment = 1ULL << ((A >> 26)-1);
271     }
272   }
273 }
274
275 void AttrBuilder::clear() {
276   Attrs.clear();
277   Alignment = StackAlignment = 0;
278 }
279
280 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
281   Attrs.insert(Val);
282   return *this;
283 }
284
285 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
286   Attrs.erase(Val);
287   if (Val == Attribute::Alignment)
288     Alignment = 0;
289   else if (Val == Attribute::StackAlignment)
290     StackAlignment = 0;
291
292   return *this;
293 }
294
295 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
296   if (Align == 0) return *this;
297
298   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
299   assert(Align <= 0x40000000 && "Alignment too large.");
300
301   Attrs.insert(Attribute::Alignment);
302   Alignment = Align;
303   return *this;
304 }
305
306 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
307   // Default alignment, allow the target to define how to align it.
308   if (Align == 0) return *this;
309
310   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
311   assert(Align <= 0x100 && "Alignment too large.");
312
313   Attrs.insert(Attribute::StackAlignment);
314   StackAlignment = Align;
315   return *this;
316 }
317
318 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
319   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
320        I = Attribute::AttrKind(I + 1)) {
321     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
322       Attrs.insert(I);
323  
324       if (I == Attribute::Alignment)
325         Alignment = 1ULL << ((A >> 16) - 1);
326       else if (I == Attribute::StackAlignment)
327         StackAlignment = 1ULL << ((A >> 26)-1);
328     }
329   }
330  
331   return *this;
332 }
333
334 AttrBuilder &AttrBuilder::addAttributes(const Attribute &Attr) {
335   uint64_t Mask = Attr.Raw();
336
337   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
338        I = Attribute::AttrKind(I + 1))
339     if ((Mask & AttributeImpl::getAttrMask(I)) != 0)
340       Attrs.insert(I);
341
342   if (Attr.getAlignment())
343     Alignment = Attr.getAlignment();
344   if (Attr.getStackAlignment())
345     StackAlignment = Attr.getStackAlignment();
346   return *this;
347 }
348
349 AttrBuilder &AttrBuilder::removeAttributes(const Attribute &A){
350   uint64_t Mask = A.Raw();
351
352   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
353        I = Attribute::AttrKind(I + 1)) {
354     if (Mask & AttributeImpl::getAttrMask(I)) {
355       Attrs.erase(I);
356
357       if (I == Attribute::Alignment)
358         Alignment = 0;
359       else if (I == Attribute::StackAlignment)
360         StackAlignment = 0;
361     }
362   }
363
364   return *this;
365 }
366
367 bool AttrBuilder::contains(Attribute::AttrKind A) const {
368   return Attrs.count(A);
369 }
370
371 bool AttrBuilder::hasAttributes() const {
372   return !Attrs.empty();
373 }
374
375 bool AttrBuilder::hasAttributes(const Attribute &A) const {
376   return Raw() & A.Raw();
377 }
378
379 bool AttrBuilder::hasAlignmentAttr() const {
380   return Alignment != 0;
381 }
382
383 uint64_t AttrBuilder::Raw() const {
384   uint64_t Mask = 0;
385
386   for (DenseSet<Attribute::AttrKind>::const_iterator I = Attrs.begin(),
387          E = Attrs.end(); I != E; ++I) {
388     Attribute::AttrKind Kind = *I;
389
390     if (Kind == Attribute::Alignment)
391       Mask |= (Log2_32(Alignment) + 1) << 16;
392     else if (Kind == Attribute::StackAlignment)
393       Mask |= (Log2_32(StackAlignment) + 1) << 26;
394     else
395       Mask |= AttributeImpl::getAttrMask(Kind);
396   }
397
398   return Mask;
399 }
400
401 bool AttrBuilder::operator==(const AttrBuilder &B) {
402   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
403   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
404   return This == That;
405 }
406
407 //===----------------------------------------------------------------------===//
408 // AttributeImpl Definition
409 //===----------------------------------------------------------------------===//
410
411 AttributeImpl::AttributeImpl(LLVMContext &C, uint64_t data)
412   : Context(C) {
413   Data = ConstantInt::get(Type::getInt64Ty(C), data);
414 }
415 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data)
416   : Context(C) {
417   Data = ConstantInt::get(Type::getInt64Ty(C), data);
418 }
419 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data,
420                              ArrayRef<Constant*> values)
421   : Context(C) {
422   Data = ConstantInt::get(Type::getInt64Ty(C), data);
423   Vals.reserve(values.size());
424   Vals.append(values.begin(), values.end());
425 }
426 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef data)
427   : Context(C) {
428   Data = ConstantDataArray::getString(C, data);
429 }
430
431 bool AttributeImpl::operator==(Attribute::AttrKind Kind) const {
432   if (ConstantInt *CI = dyn_cast<ConstantInt>(Data))
433     return CI->getZExtValue() == Kind;
434   return false;
435 }
436 bool AttributeImpl::operator!=(Attribute::AttrKind Kind) const {
437   return !(*this == Kind);
438 }
439
440 bool AttributeImpl::operator==(StringRef Kind) const {
441   if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Data))
442     if (CDA->isString())
443       return CDA->getAsString() == Kind;
444   return false;
445 }
446 bool AttributeImpl::operator!=(StringRef Kind) const {
447   return !(*this == Kind);
448 }
449
450 uint64_t AttributeImpl::Raw() const {
451   // FIXME: Remove this.
452   return cast<ConstantInt>(Data)->getZExtValue();
453 }
454
455 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
456   switch (Val) {
457   case Attribute::EndAttrKinds:
458   case Attribute::AttrKindEmptyKey:
459   case Attribute::AttrKindTombstoneKey:
460     llvm_unreachable("Synthetic enumerators which should never get here");
461
462   case Attribute::None:            return 0;
463   case Attribute::ZExt:            return 1 << 0;
464   case Attribute::SExt:            return 1 << 1;
465   case Attribute::NoReturn:        return 1 << 2;
466   case Attribute::InReg:           return 1 << 3;
467   case Attribute::StructRet:       return 1 << 4;
468   case Attribute::NoUnwind:        return 1 << 5;
469   case Attribute::NoAlias:         return 1 << 6;
470   case Attribute::ByVal:           return 1 << 7;
471   case Attribute::Nest:            return 1 << 8;
472   case Attribute::ReadNone:        return 1 << 9;
473   case Attribute::ReadOnly:        return 1 << 10;
474   case Attribute::NoInline:        return 1 << 11;
475   case Attribute::AlwaysInline:    return 1 << 12;
476   case Attribute::OptimizeForSize: return 1 << 13;
477   case Attribute::StackProtect:    return 1 << 14;
478   case Attribute::StackProtectReq: return 1 << 15;
479   case Attribute::Alignment:       return 31 << 16;
480   case Attribute::NoCapture:       return 1 << 21;
481   case Attribute::NoRedZone:       return 1 << 22;
482   case Attribute::NoImplicitFloat: return 1 << 23;
483   case Attribute::Naked:           return 1 << 24;
484   case Attribute::InlineHint:      return 1 << 25;
485   case Attribute::StackAlignment:  return 7 << 26;
486   case Attribute::ReturnsTwice:    return 1 << 29;
487   case Attribute::UWTable:         return 1 << 30;
488   case Attribute::NonLazyBind:     return 1U << 31;
489   case Attribute::AddressSafety:   return 1ULL << 32;
490   case Attribute::MinSize:         return 1ULL << 33;
491   case Attribute::NoDuplicate:     return 1ULL << 34;
492   case Attribute::StackProtectStrong: return 1ULL << 35;
493   }
494   llvm_unreachable("Unsupported attribute type");
495 }
496
497 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
498   return (Raw() & getAttrMask(A)) != 0;
499 }
500
501 bool AttributeImpl::hasAttributes() const {
502   return Raw() != 0;
503 }
504
505 uint64_t AttributeImpl::getAlignment() const {
506   return Raw() & getAttrMask(Attribute::Alignment);
507 }
508
509 void AttributeImpl::setAlignment(unsigned Align) {
510   Vals.push_back(ConstantInt::get(Type::getInt64Ty(Context), Align));
511 }
512
513 uint64_t AttributeImpl::getStackAlignment() const {
514   return Raw() & getAttrMask(Attribute::StackAlignment);
515 }
516
517 void AttributeImpl::setStackAlignment(unsigned Align) {
518   Vals.push_back(ConstantInt::get(Type::getInt64Ty(Context), Align));
519 }
520
521 void AttributeImpl::Profile(FoldingSetNodeID &ID, Constant *Data,
522                             ArrayRef<Constant*> Vals) {
523   ID.AddInteger(cast<ConstantInt>(Data)->getZExtValue());
524 #if 0
525   // FIXME: Not yet supported.
526   for (ArrayRef<Constant*>::iterator I = Vals.begin(), E = Vals.end();
527        I != E; ++I)
528     ID.AddPointer(*I);
529 #endif
530 }
531
532 //===----------------------------------------------------------------------===//
533 // AttributeWithIndex Definition
534 //===----------------------------------------------------------------------===//
535
536 AttributeWithIndex AttributeWithIndex::get(LLVMContext &C, unsigned Idx,
537                                            AttributeSet AS) {
538   // FIXME: This is temporary, but necessary for the conversion.
539   AttrBuilder B(AS, Idx);
540   return get(Idx, Attribute::get(C, B));
541 }
542
543 //===----------------------------------------------------------------------===//
544 // AttributeSetImpl Definition
545 //===----------------------------------------------------------------------===//
546
547 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
548   // FIXME: Remove.
549   return AttrList && hasAttributes(Idx) ?
550     AttributeSet::get(AttrList->getContext(),
551                       AttributeWithIndex::get(Idx, getAttributes(Idx))) :
552     AttributeSet();
553 }
554
555 AttributeSet AttributeSet::getRetAttributes() const {
556   // FIXME: Remove.
557   return AttrList && hasAttributes(ReturnIndex) ?
558     AttributeSet::get(AttrList->getContext(),
559                       AttributeWithIndex::get(ReturnIndex,
560                                               getAttributes(ReturnIndex))) :
561     AttributeSet();
562 }
563
564 AttributeSet AttributeSet::getFnAttributes() const {
565   // FIXME: Remove.
566   return AttrList && hasAttributes(FunctionIndex) ?
567     AttributeSet::get(AttrList->getContext(),
568                       AttributeWithIndex::get(FunctionIndex,
569                                               getAttributes(FunctionIndex))) :
570     AttributeSet();
571 }
572
573 AttributeSet AttributeSet::get(LLVMContext &C,
574                                ArrayRef<AttributeWithIndex> Attrs) {
575   // If there are no attributes then return a null AttributesList pointer.
576   if (Attrs.empty())
577     return AttributeSet();
578
579 #ifndef NDEBUG
580   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
581     assert(Attrs[i].Attrs.hasAttributes() &&
582            "Pointless attribute!");
583     assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
584            "Misordered AttributesList!");
585   }
586 #endif
587
588   // Otherwise, build a key to look up the existing attributes.
589   LLVMContextImpl *pImpl = C.pImpl;
590   FoldingSetNodeID ID;
591   AttributeSetImpl::Profile(ID, Attrs);
592
593   void *InsertPoint;
594   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
595
596   // If we didn't find any existing attributes of the same shape then
597   // create a new one and insert it.
598   if (!PA) {
599     PA = new AttributeSetImpl(C, Attrs);
600     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
601   }
602
603   // Return the AttributesList that we found or created.
604   return AttributeSet(PA);
605 }
606
607 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
608   // FIXME: This should be implemented as a loop that creates the
609   // AttributeWithIndexes that then are used to create the AttributeSet.
610   if (!B.hasAttributes())
611     return AttributeSet();
612   return get(C, AttributeWithIndex::get(Idx, Attribute::get(C, B)));
613 }
614
615 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
616                                Attribute::AttrKind Kind) {
617   return get(C, AttributeWithIndex::get(Idx, Attribute::get(C, Kind)));
618 }
619
620 //===----------------------------------------------------------------------===//
621 // AttributeSet Method Implementations
622 //===----------------------------------------------------------------------===//
623
624 const AttributeSet &AttributeSet::operator=(const AttributeSet &RHS) {
625   AttrList = RHS.AttrList;
626   return *this;
627 }
628
629 /// getNumSlots - Return the number of slots used in this attribute list.
630 /// This is the number of arguments that have an attribute set on them
631 /// (including the function itself).
632 unsigned AttributeSet::getNumSlots() const {
633   return AttrList ? AttrList->getNumAttributes() : 0;
634 }
635
636 /// getSlot - Return the AttributeWithIndex at the specified slot.  This
637 /// holds a number plus a set of attributes.
638 const AttributeWithIndex &AttributeSet::getSlot(unsigned Slot) const {
639   assert(AttrList && Slot < AttrList->getNumAttributes() &&
640          "Slot # out of range!");
641   return AttrList->getAttributes()[Slot];
642 }
643
644 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
645   return getAttributes(Index).hasAttribute(Kind);
646 }
647
648 bool AttributeSet::hasAttributes(unsigned Index) const {
649   return getAttributes(Index).hasAttributes();
650 }
651
652 std::string AttributeSet::getAsString(unsigned Index) const {
653   return getAttributes(Index).getAsString();
654 }
655
656 unsigned AttributeSet::getParamAlignment(unsigned Idx) const {
657   return getAttributes(Idx).getAlignment();
658 }
659
660 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
661   return getAttributes(Index).getStackAlignment();
662 }
663
664 uint64_t AttributeSet::Raw(unsigned Index) const {
665   // FIXME: Remove this.
666   return getAttributes(Index).Raw();
667 }
668
669 /// getAttributes - The attributes for the specified index are returned.
670 Attribute AttributeSet::getAttributes(unsigned Idx) const {
671   if (AttrList == 0) return Attribute();
672
673   ArrayRef<AttributeWithIndex> Attrs = AttrList->getAttributes();
674   for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
675     if (Attrs[i].Index == Idx)
676       return Attrs[i].Attrs;
677
678   return Attribute();
679 }
680
681 /// hasAttrSomewhere - Return true if the specified attribute is set for at
682 /// least one parameter or for the return value.
683 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
684   if (AttrList == 0) return false;
685
686   ArrayRef<AttributeWithIndex> Attrs = AttrList->getAttributes();
687   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
688     if (Attrs[i].Attrs.hasAttribute(Attr))
689       return true;
690
691   return false;
692 }
693
694 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
695                                         Attribute::AttrKind Attr) const {
696   return addAttr(C, Idx, Attribute::get(C, Attr));
697 }
698
699 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
700                                          AttributeSet Attrs) const {
701   return addAttr(C, Idx, Attrs.getAttributes(Idx));
702 }
703
704 AttributeSet AttributeSet::addAttr(LLVMContext &C, unsigned Idx,
705                                    Attribute Attrs) const {
706   Attribute OldAttrs = getAttributes(Idx);
707 #ifndef NDEBUG
708   // FIXME it is not obvious how this should work for alignment.
709   // For now, say we can't change a known alignment.
710   unsigned OldAlign = OldAttrs.getAlignment();
711   unsigned NewAlign = Attrs.getAlignment();
712   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
713          "Attempt to change alignment!");
714 #endif
715
716   AttrBuilder NewAttrs =
717     AttrBuilder(OldAttrs).addAttributes(Attrs);
718   if (NewAttrs == AttrBuilder(OldAttrs))
719     return *this;
720
721   SmallVector<AttributeWithIndex, 8> NewAttrList;
722   if (AttrList == 0)
723     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
724   else {
725     ArrayRef<AttributeWithIndex> OldAttrList = AttrList->getAttributes();
726     unsigned i = 0, e = OldAttrList.size();
727     // Copy attributes for arguments before this one.
728     for (; i != e && OldAttrList[i].Index < Idx; ++i)
729       NewAttrList.push_back(OldAttrList[i]);
730
731     // If there are attributes already at this index, merge them in.
732     if (i != e && OldAttrList[i].Index == Idx) {
733       Attrs =
734         Attribute::get(C, AttrBuilder(Attrs).
735                         addAttributes(OldAttrList[i].Attrs));
736       ++i;
737     }
738
739     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
740
741     // Copy attributes for arguments after this one.
742     NewAttrList.insert(NewAttrList.end(),
743                        OldAttrList.begin()+i, OldAttrList.end());
744   }
745
746   return get(C, NewAttrList);
747 }
748
749 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
750                                            Attribute::AttrKind Attr) const {
751   return removeAttr(C, Idx, Attribute::get(C, Attr));
752 }
753
754 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
755                                             AttributeSet Attrs) const {
756   return removeAttr(C, Idx, Attrs.getAttributes(Idx));
757 }
758
759 AttributeSet AttributeSet::removeAttr(LLVMContext &C, unsigned Idx,
760                                       Attribute Attrs) const {
761 #ifndef NDEBUG
762   // FIXME it is not obvious how this should work for alignment.
763   // For now, say we can't pass in alignment, which no current use does.
764   assert(!Attrs.hasAttribute(Attribute::Alignment) &&
765          "Attempt to exclude alignment!");
766 #endif
767   if (AttrList == 0) return AttributeSet();
768
769   Attribute OldAttrs = getAttributes(Idx);
770   AttrBuilder NewAttrs =
771     AttrBuilder(OldAttrs).removeAttributes(Attrs);
772   if (NewAttrs == AttrBuilder(OldAttrs))
773     return *this;
774
775   SmallVector<AttributeWithIndex, 8> NewAttrList;
776   ArrayRef<AttributeWithIndex> OldAttrList = AttrList->getAttributes();
777   unsigned i = 0, e = OldAttrList.size();
778
779   // Copy attributes for arguments before this one.
780   for (; i != e && OldAttrList[i].Index < Idx; ++i)
781     NewAttrList.push_back(OldAttrList[i]);
782
783   // If there are attributes already at this index, merge them in.
784   assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
785   Attrs = Attribute::get(C, AttrBuilder(OldAttrList[i].Attrs).
786                           removeAttributes(Attrs));
787   ++i;
788   if (Attrs.hasAttributes()) // If any attributes left for this param, add them.
789     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
790
791   // Copy attributes for arguments after this one.
792   NewAttrList.insert(NewAttrList.end(),
793                      OldAttrList.begin()+i, OldAttrList.end());
794
795   return get(C, NewAttrList);
796 }
797
798 void AttributeSet::dump() const {
799   dbgs() << "PAL[ ";
800   for (unsigned i = 0; i < getNumSlots(); ++i) {
801     const AttributeWithIndex &PAWI = getSlot(i);
802     dbgs() << "{ " << PAWI.Index << ", " << PAWI.Attrs.getAsString() << " } ";
803   }
804
805   dbgs() << "]\n";
806 }