f8ca9f1f0420ca51c1b5c4411ecff9d645ec01ff
[oota-llvm.git] / lib / IR / 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 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.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 #include <algorithm>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Attribute Construction Methods
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, Constant *Kind, Constant *Val) {
34   LLVMContextImpl *pImpl = Context.pImpl;
35   FoldingSetNodeID ID;
36   ID.AddPointer(Kind);
37   if (Val) ID.AddPointer(Val);
38
39   void *InsertPoint;
40   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
41
42   if (!PA) {
43     // If we didn't find any existing attributes of the same shape then create a
44     // new one and insert it.
45     PA = (!Val) ?
46       new AttributeImpl(Context, Kind) :
47       new AttributeImpl(Context, Kind, Val);
48     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
49   }
50
51   // Return the AttributesList that we found or created.
52   return Attribute(PA);
53 }
54
55 Attribute Attribute::get(LLVMContext &Context, AttrKind Kind, Constant *Val) {
56   ConstantInt *KindVal = ConstantInt::get(Type::getInt64Ty(Context), Kind);
57   return get(Context, KindVal, Val);
58 }
59
60 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
61   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
62   assert(Align <= 0x40000000 && "Alignment too large.");
63   return get(Context, Alignment,
64              ConstantInt::get(Type::getInt64Ty(Context), Align));
65 }
66
67 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
68                                            uint64_t Align) {
69   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
70   assert(Align <= 0x100 && "Alignment too large.");
71   return get(Context, StackAlignment,
72              ConstantInt::get(Type::getInt64Ty(Context), Align));
73 }
74
75 //===----------------------------------------------------------------------===//
76 // Attribute Accessor Methods
77 //===----------------------------------------------------------------------===//
78
79 bool Attribute::hasAttribute(AttrKind Val) const {
80   return pImpl && pImpl->hasAttribute(Val);
81 }
82
83 Constant *Attribute::getAttributeKind() const {
84   return pImpl ? pImpl->getAttributeKind() : 0;
85 }
86
87 Constant *Attribute::getAttributeValues() const {
88   return pImpl ? pImpl->getAttributeValues() : 0;
89 }
90
91 /// This returns the alignment field of an attribute as a byte alignment value.
92 unsigned Attribute::getAlignment() const {
93   assert(hasAttribute(Attribute::Alignment) &&
94          "Trying to get alignment from non-alignment attribute!");
95   return pImpl->getAlignment();
96 }
97
98 /// This returns the stack alignment field of an attribute as a byte alignment
99 /// value.
100 unsigned Attribute::getStackAlignment() const {
101   assert(hasAttribute(Attribute::StackAlignment) &&
102          "Trying to get alignment from non-alignment attribute!");
103   return pImpl->getStackAlignment();
104 }
105
106 std::string Attribute::getAsString() const {
107   if (!pImpl) return "";
108
109   if (hasAttribute(Attribute::AddressSafety))
110     return "address_safety";
111   if (hasAttribute(Attribute::AlwaysInline))
112     return "alwaysinline";
113   if (hasAttribute(Attribute::ByVal))
114     return "byval";
115   if (hasAttribute(Attribute::InlineHint))
116     return "inlinehint";
117   if (hasAttribute(Attribute::InReg))
118     return "inreg";
119   if (hasAttribute(Attribute::MinSize))
120     return "minsize";
121   if (hasAttribute(Attribute::Naked))
122     return "naked";
123   if (hasAttribute(Attribute::Nest))
124     return "nest";
125   if (hasAttribute(Attribute::NoAlias))
126     return "noalias";
127   if (hasAttribute(Attribute::NoCapture))
128     return "nocapture";
129   if (hasAttribute(Attribute::NoDuplicate))
130     return "noduplicate";
131   if (hasAttribute(Attribute::NoImplicitFloat))
132     return "noimplicitfloat";
133   if (hasAttribute(Attribute::NoInline))
134     return "noinline";
135   if (hasAttribute(Attribute::NonLazyBind))
136     return "nonlazybind";
137   if (hasAttribute(Attribute::NoRedZone))
138     return "noredzone";
139   if (hasAttribute(Attribute::NoReturn))
140     return "noreturn";
141   if (hasAttribute(Attribute::NoUnwind))
142     return "nounwind";
143   if (hasAttribute(Attribute::OptimizeForSize))
144     return "optsize";
145   if (hasAttribute(Attribute::ReadNone))
146     return "readnone";
147   if (hasAttribute(Attribute::ReadOnly))
148     return "readonly";
149   if (hasAttribute(Attribute::ReturnsTwice))
150     return "returns_twice";
151   if (hasAttribute(Attribute::SExt))
152     return "signext";
153   if (hasAttribute(Attribute::StackProtect))
154     return "ssp";
155   if (hasAttribute(Attribute::StackProtectReq))
156     return "sspreq";
157   if (hasAttribute(Attribute::StackProtectStrong))
158     return "sspstrong";
159   if (hasAttribute(Attribute::StructRet))
160     return "sret";
161   if (hasAttribute(Attribute::UWTable))
162     return "uwtable";
163   if (hasAttribute(Attribute::ZExt))
164     return "zeroext";
165
166   // FIXME: These should be output like this:
167   //
168   //   align=4
169   //   alignstack=8
170   //
171   if (hasAttribute(Attribute::StackAlignment)) {
172     std::string Result;
173     Result += "alignstack(";
174     Result += utostr(getStackAlignment());
175     Result += ")";
176     return Result;
177   }
178   if (hasAttribute(Attribute::Alignment)) {
179     std::string Result;
180     Result += "align ";
181     Result += utostr(getAlignment());
182     return Result;
183   }
184
185   // Convert target-dependent attributes to strings of the form:
186   //
187   //   "kind"
188   //   "kind" = "value"
189   //   "kind" = ( "value1" "value2" "value3" )
190   //
191   if (ConstantDataArray *CDA =
192       dyn_cast<ConstantDataArray>(pImpl->getAttributeKind())) {
193     std::string Result;
194     Result += '\"' + CDA->getAsString().str() + '"';
195
196     Constant *Vals = pImpl->getAttributeValues();
197     if (!Vals) return Result;
198
199     // FIXME: This should support more than just ConstantDataArrays. Also,
200     // support a vector of attribute values.
201
202     Result += " = ";
203     Result += '\"' + cast<ConstantDataArray>(Vals)->getAsString().str() + '"';
204
205     return Result;
206   }
207
208   llvm_unreachable("Unknown attribute");
209 }
210
211 bool Attribute::operator==(AttrKind K) const {
212   return (pImpl && *pImpl == K) || (!pImpl && K == None);
213 }
214 bool Attribute::operator!=(AttrKind K) const {
215   return !(*this == K);
216 }
217
218 bool Attribute::operator<(Attribute A) const {
219   if (!pImpl && !A.pImpl) return false;
220   if (!pImpl) return true;
221   if (!A.pImpl) return false;
222   return *pImpl < *A.pImpl;
223 }
224
225 //===----------------------------------------------------------------------===//
226 // AttributeImpl Definition
227 //===----------------------------------------------------------------------===//
228
229 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
230   if (ConstantInt *CI = dyn_cast<ConstantInt>(Kind))
231     return CI->getZExtValue() == A;
232   return false;
233 }
234
235 uint64_t AttributeImpl::getAlignment() const {
236   assert(hasAttribute(Attribute::Alignment) &&
237          "Trying to retrieve the alignment from a non-alignment attr!");
238   return cast<ConstantInt>(Values)->getZExtValue();
239 }
240
241 uint64_t AttributeImpl::getStackAlignment() const {
242   assert(hasAttribute(Attribute::StackAlignment) &&
243          "Trying to retrieve the stack alignment from a non-alignment attr!");
244   return cast<ConstantInt>(Values)->getZExtValue();
245 }
246
247 bool AttributeImpl::operator==(Attribute::AttrKind kind) const {
248   if (ConstantInt *CI = dyn_cast<ConstantInt>(Kind))
249     return CI->getZExtValue() == kind;
250   return false;
251 }
252 bool AttributeImpl::operator!=(Attribute::AttrKind kind) const {
253   return !(*this == kind);
254 }
255
256 bool AttributeImpl::operator==(StringRef kind) const {
257   if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Kind))
258     if (CDA->isString())
259       return CDA->getAsString() == kind;
260   return false;
261 }
262
263 bool AttributeImpl::operator!=(StringRef kind) const {
264   return !(*this == kind);
265 }
266
267 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
268   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
269   // relative to their enum value) and then strings.
270
271   if (!Kind && !AI.Kind) return false;
272   if (!Kind && AI.Kind) return true;
273   if (Kind && !AI.Kind) return false;
274
275   ConstantInt *ThisCI = dyn_cast<ConstantInt>(Kind);
276   ConstantInt *ThatCI = dyn_cast<ConstantInt>(AI.Kind);
277
278   ConstantDataArray *ThisCDA = dyn_cast<ConstantDataArray>(Kind);
279   ConstantDataArray *ThatCDA = dyn_cast<ConstantDataArray>(AI.Kind);
280
281   if (ThisCI && ThatCI)
282     return ThisCI->getZExtValue() < ThatCI->getZExtValue();
283
284   if (ThisCI && ThatCDA)
285     return true;
286
287   if (ThisCDA && ThatCI)
288     return false;
289
290   return ThisCDA->getAsString() < ThatCDA->getAsString();
291 }
292
293 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
294   // FIXME: Remove this.
295   switch (Val) {
296   case Attribute::EndAttrKinds:
297   case Attribute::AttrKindEmptyKey:
298   case Attribute::AttrKindTombstoneKey:
299     llvm_unreachable("Synthetic enumerators which should never get here");
300
301   case Attribute::None:            return 0;
302   case Attribute::ZExt:            return 1 << 0;
303   case Attribute::SExt:            return 1 << 1;
304   case Attribute::NoReturn:        return 1 << 2;
305   case Attribute::InReg:           return 1 << 3;
306   case Attribute::StructRet:       return 1 << 4;
307   case Attribute::NoUnwind:        return 1 << 5;
308   case Attribute::NoAlias:         return 1 << 6;
309   case Attribute::ByVal:           return 1 << 7;
310   case Attribute::Nest:            return 1 << 8;
311   case Attribute::ReadNone:        return 1 << 9;
312   case Attribute::ReadOnly:        return 1 << 10;
313   case Attribute::NoInline:        return 1 << 11;
314   case Attribute::AlwaysInline:    return 1 << 12;
315   case Attribute::OptimizeForSize: return 1 << 13;
316   case Attribute::StackProtect:    return 1 << 14;
317   case Attribute::StackProtectReq: return 1 << 15;
318   case Attribute::Alignment:       return 31 << 16;
319   case Attribute::NoCapture:       return 1 << 21;
320   case Attribute::NoRedZone:       return 1 << 22;
321   case Attribute::NoImplicitFloat: return 1 << 23;
322   case Attribute::Naked:           return 1 << 24;
323   case Attribute::InlineHint:      return 1 << 25;
324   case Attribute::StackAlignment:  return 7 << 26;
325   case Attribute::ReturnsTwice:    return 1 << 29;
326   case Attribute::UWTable:         return 1 << 30;
327   case Attribute::NonLazyBind:     return 1U << 31;
328   case Attribute::AddressSafety:   return 1ULL << 32;
329   case Attribute::MinSize:         return 1ULL << 33;
330   case Attribute::NoDuplicate:     return 1ULL << 34;
331   case Attribute::StackProtectStrong: return 1ULL << 35;
332   }
333   llvm_unreachable("Unsupported attribute type");
334 }
335
336 //===----------------------------------------------------------------------===//
337 // AttributeSetNode Definition
338 //===----------------------------------------------------------------------===//
339
340 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
341                                         ArrayRef<Attribute> Attrs) {
342   if (Attrs.empty())
343     return 0;
344
345   // Otherwise, build a key to look up the existing attributes.
346   LLVMContextImpl *pImpl = C.pImpl;
347   FoldingSetNodeID ID;
348
349   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
350   std::sort(SortedAttrs.begin(), SortedAttrs.end());
351
352   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
353          E = SortedAttrs.end(); I != E; ++I)
354     I->Profile(ID);
355
356   void *InsertPoint;
357   AttributeSetNode *PA =
358     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
359
360   // If we didn't find any existing attributes of the same shape then create a
361   // new one and insert it.
362   if (!PA) {
363     PA = new AttributeSetNode(SortedAttrs);
364     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
365   }
366
367   // Return the AttributesListNode that we found or created.
368   return PA;
369 }
370
371 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
372   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
373          E = AttrList.end(); I != E; ++I)
374     if (I->hasAttribute(Kind))
375       return true;
376   return false;
377 }
378
379 unsigned AttributeSetNode::getAlignment() const {
380   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
381          E = AttrList.end(); I != E; ++I)
382     if (I->hasAttribute(Attribute::Alignment))
383       return I->getAlignment();
384   return 0;
385 }
386
387 unsigned AttributeSetNode::getStackAlignment() const {
388   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
389          E = AttrList.end(); I != E; ++I)
390     if (I->hasAttribute(Attribute::StackAlignment))
391       return I->getStackAlignment();
392   return 0;
393 }
394
395 std::string AttributeSetNode::getAsString() const {
396   std::string Str = "";
397   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
398          E = AttrList.end(); I != E; ) {
399     Str += I->getAsString();
400     if (++I != E) Str += " ";
401   }
402   return Str;
403 }
404
405 //===----------------------------------------------------------------------===//
406 // AttributeSetImpl Definition
407 //===----------------------------------------------------------------------===//
408
409 uint64_t AttributeSetImpl::Raw(uint64_t Index) const {
410   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
411     if (getSlotIndex(I) != Index) continue;
412     const AttributeSetNode *ASN = AttrNodes[I].second;
413     AttrBuilder B;
414
415     for (AttributeSetNode::const_iterator II = ASN->begin(),
416            IE = ASN->end(); II != IE; ++II)
417       B.addAttribute(*II);
418     return B.Raw();
419   }
420
421   return 0;
422 }
423
424 //===----------------------------------------------------------------------===//
425 // AttributeSet Construction and Mutation Methods
426 //===----------------------------------------------------------------------===//
427
428 AttributeSet
429 AttributeSet::getImpl(LLVMContext &C,
430                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
431   LLVMContextImpl *pImpl = C.pImpl;
432   FoldingSetNodeID ID;
433   AttributeSetImpl::Profile(ID, Attrs);
434
435   void *InsertPoint;
436   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
437
438   // If we didn't find any existing attributes of the same shape then
439   // create a new one and insert it.
440   if (!PA) {
441     PA = new AttributeSetImpl(C, Attrs);
442     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
443   }
444
445   // Return the AttributesList that we found or created.
446   return AttributeSet(PA);
447 }
448
449 AttributeSet AttributeSet::get(LLVMContext &C,
450                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
451   // If there are no attributes then return a null AttributesList pointer.
452   if (Attrs.empty())
453     return AttributeSet();
454
455 #ifndef NDEBUG
456   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
457     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
458            "Misordered Attributes list!");
459     assert(Attrs[i].second != Attribute::None &&
460            "Pointless attribute!");
461   }
462 #endif
463
464   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
465   // list.
466   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
467   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
468          E = Attrs.end(); I != E; ) {
469     unsigned Index = I->first;
470     SmallVector<Attribute, 4> AttrVec;
471     while (I != E && I->first == Index) {
472       AttrVec.push_back(I->second);
473       ++I;
474     }
475
476     AttrPairVec.push_back(std::make_pair(Index,
477                                          AttributeSetNode::get(C, AttrVec)));
478   }
479
480   return getImpl(C, AttrPairVec);
481 }
482
483 AttributeSet AttributeSet::get(LLVMContext &C,
484                                ArrayRef<std::pair<unsigned,
485                                                   AttributeSetNode*> > Attrs) {
486   // If there are no attributes then return a null AttributesList pointer.
487   if (Attrs.empty())
488     return AttributeSet();
489
490   return getImpl(C, Attrs);
491 }
492
493 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
494   if (!B.hasAttributes())
495     return AttributeSet();
496
497   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
498   for (AttrBuilder::iterator I = B.begin(), E = B.end(); I != E; ++I) {
499     Attribute::AttrKind Kind = *I;
500     if (Kind == Attribute::Alignment)
501       Attrs.push_back(std::make_pair(Idx, Attribute::
502                                      getWithAlignment(C, B.getAlignment())));
503     else if (Kind == Attribute::StackAlignment)
504       Attrs.push_back(std::make_pair(Idx, Attribute::
505                               getWithStackAlignment(C, B.getStackAlignment())));
506     else
507       Attrs.push_back(std::make_pair(Idx, Attribute::get(C, Kind)));
508   }
509
510   return get(C, Attrs);
511 }
512
513 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
514                                ArrayRef<Attribute::AttrKind> Kind) {
515   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
516   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
517          E = Kind.end(); I != E; ++I)
518     Attrs.push_back(std::make_pair(Idx, Attribute::get(C, *I)));
519   return get(C, Attrs);
520 }
521
522 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
523   if (Attrs.empty()) return AttributeSet();
524
525   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
526   for (unsigned I = 0, E = Attrs.size(); I != E; ++I) {
527     AttributeSet AS = Attrs[I];
528     if (!AS.pImpl) continue;
529     AttrNodeVec.append(AS.pImpl->AttrNodes.begin(), AS.pImpl->AttrNodes.end());
530   }
531
532   return getImpl(C, AttrNodeVec);
533 }
534
535 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
536                                         Attribute::AttrKind Attr) const {
537   return addAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
538 }
539
540 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
541                                          AttributeSet Attrs) const {
542   if (!pImpl) return Attrs;
543   if (!Attrs.pImpl) return *this;
544
545 #ifndef NDEBUG
546   // FIXME it is not obvious how this should work for alignment. For now, say
547   // we can't change a known alignment.
548   unsigned OldAlign = getParamAlignment(Idx);
549   unsigned NewAlign = Attrs.getParamAlignment(Idx);
550   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
551          "Attempt to change alignment!");
552 #endif
553
554   // Add the attribute slots before the one we're trying to add.
555   SmallVector<AttributeSet, 4> AttrSet;
556   uint64_t NumAttrs = pImpl->getNumAttributes();
557   AttributeSet AS;
558   uint64_t LastIndex = 0;
559   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
560     if (getSlotIndex(I) >= Idx) {
561       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
562       break;
563     }
564     LastIndex = I + 1;
565     AttrSet.push_back(getSlotAttributes(I));
566   }
567
568   // Now add the attribute into the correct slot. There may already be an
569   // AttributeSet there.
570   AttrBuilder B(AS, Idx);
571
572   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
573     if (Attrs.getSlotIndex(I) == Idx) {
574       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
575              IE = Attrs.pImpl->end(I); II != IE; ++II)
576         B.addAttribute(*II);
577       break;
578     }
579
580   AttrSet.push_back(AttributeSet::get(C, Idx, B));
581
582   // Add the remaining attribute slots.
583   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
584     AttrSet.push_back(getSlotAttributes(I));
585
586   return get(C, AttrSet);
587 }
588
589 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
590                                            Attribute::AttrKind Attr) const {
591   return removeAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
592 }
593
594 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
595                                             AttributeSet Attrs) const {
596   if (!pImpl) return AttributeSet();
597   if (!Attrs.pImpl) return *this;
598
599 #ifndef NDEBUG
600   // FIXME it is not obvious how this should work for alignment.
601   // For now, say we can't pass in alignment, which no current use does.
602   assert(!Attrs.hasAttribute(Idx, Attribute::Alignment) &&
603          "Attempt to change alignment!");
604 #endif
605
606   // Add the attribute slots before the one we're trying to add.
607   SmallVector<AttributeSet, 4> AttrSet;
608   uint64_t NumAttrs = pImpl->getNumAttributes();
609   AttributeSet AS;
610   uint64_t LastIndex = 0;
611   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
612     if (getSlotIndex(I) >= Idx) {
613       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
614       break;
615     }
616     LastIndex = I + 1;
617     AttrSet.push_back(getSlotAttributes(I));
618   }
619
620   // Now remove the attribute from the correct slot. There may already be an
621   // AttributeSet there.
622   AttrBuilder B(AS, Idx);
623
624   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
625     if (Attrs.getSlotIndex(I) == Idx) {
626       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Idx);
627       break;
628     }
629
630   AttrSet.push_back(AttributeSet::get(C, Idx, B));
631
632   // Add the remaining attribute slots.
633   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
634     AttrSet.push_back(getSlotAttributes(I));
635
636   return get(C, AttrSet);
637 }
638
639 //===----------------------------------------------------------------------===//
640 // AttributeSet Accessor Methods
641 //===----------------------------------------------------------------------===//
642
643 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
644   return pImpl && hasAttributes(Idx) ?
645     AttributeSet::get(pImpl->getContext(),
646                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
647                         std::make_pair(Idx, getAttributes(Idx)))) :
648     AttributeSet();
649 }
650
651 AttributeSet AttributeSet::getRetAttributes() const {
652   return pImpl && hasAttributes(ReturnIndex) ?
653     AttributeSet::get(pImpl->getContext(),
654                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
655                         std::make_pair(ReturnIndex,
656                                        getAttributes(ReturnIndex)))) :
657     AttributeSet();
658 }
659
660 AttributeSet AttributeSet::getFnAttributes() const {
661   return pImpl && hasAttributes(FunctionIndex) ?
662     AttributeSet::get(pImpl->getContext(),
663                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
664                         std::make_pair(FunctionIndex,
665                                        getAttributes(FunctionIndex)))) :
666     AttributeSet();
667 }
668
669 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
670   AttributeSetNode *ASN = getAttributes(Index);
671   return ASN ? ASN->hasAttribute(Kind) : false;
672 }
673
674 bool AttributeSet::hasAttributes(unsigned Index) const {
675   AttributeSetNode *ASN = getAttributes(Index);
676   return ASN ? ASN->hasAttributes() : false;
677 }
678
679 /// \brief Return true if the specified attribute is set for at least one
680 /// parameter or for the return value.
681 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
682   if (pImpl == 0) return false;
683
684   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
685     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
686            IE = pImpl->end(I); II != IE; ++II)
687       if (II->hasAttribute(Attr))
688         return true;
689
690   return false;
691 }
692
693 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
694   AttributeSetNode *ASN = getAttributes(Index);
695   return ASN ? ASN->getAlignment() : 0;
696 }
697
698 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
699   AttributeSetNode *ASN = getAttributes(Index);
700   return ASN ? ASN->getStackAlignment() : 0;
701 }
702
703 std::string AttributeSet::getAsString(unsigned Index) const {
704   AttributeSetNode *ASN = getAttributes(Index);
705   return ASN ? ASN->getAsString() : std::string("");
706 }
707
708 /// \brief The attributes for the specified index are returned.
709 AttributeSetNode *AttributeSet::getAttributes(unsigned Idx) const {
710   if (!pImpl) return 0;
711
712   // Loop through to find the attribute node we want.
713   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
714     if (pImpl->getSlotIndex(I) == Idx)
715       return pImpl->getSlotNode(I);
716
717   return 0;
718 }
719
720 AttributeSet::iterator AttributeSet::begin(unsigned Idx) const {
721   if (!pImpl)
722     return ArrayRef<Attribute>().begin();
723   return pImpl->begin(Idx);
724 }
725
726 AttributeSet::iterator AttributeSet::end(unsigned Idx) const {
727   if (!pImpl)
728     return ArrayRef<Attribute>().end();
729   return pImpl->end(Idx);
730 }
731
732 //===----------------------------------------------------------------------===//
733 // AttributeSet Introspection Methods
734 //===----------------------------------------------------------------------===//
735
736 /// \brief Return the number of slots used in this attribute list.  This is the
737 /// number of arguments that have an attribute set on them (including the
738 /// function itself).
739 unsigned AttributeSet::getNumSlots() const {
740   return pImpl ? pImpl->getNumAttributes() : 0;
741 }
742
743 uint64_t AttributeSet::getSlotIndex(unsigned Slot) const {
744   assert(pImpl && Slot < pImpl->getNumAttributes() &&
745          "Slot # out of range!");
746   return pImpl->getSlotIndex(Slot);
747 }
748
749 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
750   assert(pImpl && Slot < pImpl->getNumAttributes() &&
751          "Slot # out of range!");
752   return pImpl->getSlotAttributes(Slot);
753 }
754
755 uint64_t AttributeSet::Raw(unsigned Index) const {
756   // FIXME: Remove this.
757   return pImpl ? pImpl->Raw(Index) : 0;
758 }
759
760 void AttributeSet::dump() const {
761   dbgs() << "PAL[\n";
762
763   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
764     uint64_t Index = getSlotIndex(i);
765     dbgs() << "  { ";
766     if (Index == ~0U)
767       dbgs() << "~0U";
768     else
769       dbgs() << Index;
770     dbgs() << " => " << getAsString(Index) << " }\n";
771   }
772
773   dbgs() << "]\n";
774 }
775
776 //===----------------------------------------------------------------------===//
777 // AttrBuilder Method Implementations
778 //===----------------------------------------------------------------------===//
779
780 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
781   : Alignment(0), StackAlignment(0) {
782   AttributeSetImpl *pImpl = AS.pImpl;
783   if (!pImpl) return;
784
785   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
786     if (pImpl->getSlotIndex(I) != Idx) continue;
787
788     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
789            IE = pImpl->end(I); II != IE; ++II)
790       addAttribute(*II);
791
792     break;
793   }
794 }
795
796 void AttrBuilder::clear() {
797   Attrs.clear();
798   Alignment = StackAlignment = 0;
799 }
800
801 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
802   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
803          "Adding alignment attribute without adding alignment value!");
804   Attrs.insert(Val);
805   return *this;
806 }
807
808 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
809   ConstantInt *Kind = cast<ConstantInt>(Attr.getAttributeKind());
810   Attribute::AttrKind KindVal = Attribute::AttrKind(Kind->getZExtValue());
811   Attrs.insert(KindVal);
812
813   if (KindVal == Attribute::Alignment)
814     Alignment = Attr.getAlignment();
815   else if (KindVal == Attribute::StackAlignment)
816     StackAlignment = Attr.getStackAlignment();
817   return *this;
818 }
819
820 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
821   Attrs.erase(Val);
822
823   if (Val == Attribute::Alignment)
824     Alignment = 0;
825   else if (Val == Attribute::StackAlignment)
826     StackAlignment = 0;
827
828   return *this;
829 }
830
831 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
832   unsigned Idx = ~0U;
833   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
834     if (A.getSlotIndex(I) == Index) {
835       Idx = I;
836       break;
837     }
838
839   assert(Idx != ~0U && "Couldn't find index in AttributeSet!");
840
841   for (AttributeSet::iterator I = A.begin(Idx), E = A.end(Idx); I != E; ++I) {
842     ConstantInt *CI = cast<ConstantInt>(I->getAttributeKind());
843     Attribute::AttrKind Kind = Attribute::AttrKind(CI->getZExtValue());
844     Attrs.erase(Kind);
845
846     if (Kind == Attribute::Alignment)
847       Alignment = 0;
848     else if (Kind == Attribute::StackAlignment)
849       StackAlignment = 0;
850   }
851
852   return *this;
853 }
854
855 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
856   if (Align == 0) return *this;
857
858   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
859   assert(Align <= 0x40000000 && "Alignment too large.");
860
861   Attrs.insert(Attribute::Alignment);
862   Alignment = Align;
863   return *this;
864 }
865
866 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
867   // Default alignment, allow the target to define how to align it.
868   if (Align == 0) return *this;
869
870   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
871   assert(Align <= 0x100 && "Alignment too large.");
872
873   Attrs.insert(Attribute::StackAlignment);
874   StackAlignment = Align;
875   return *this;
876 }
877
878 bool AttrBuilder::contains(Attribute::AttrKind A) const {
879   return Attrs.count(A);
880 }
881
882 bool AttrBuilder::hasAttributes() const {
883   return !Attrs.empty();
884 }
885
886 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
887   return Raw() & A.Raw(Index);
888 }
889
890 bool AttrBuilder::hasAlignmentAttr() const {
891   return Alignment != 0;
892 }
893
894 bool AttrBuilder::operator==(const AttrBuilder &B) {
895   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
896   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
897   return This == That;
898 }
899
900 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
901   if (!Val) return *this;
902
903   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
904        I = Attribute::AttrKind(I + 1)) {
905     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
906       Attrs.insert(I);
907  
908       if (I == Attribute::Alignment)
909         Alignment = 1ULL << ((A >> 16) - 1);
910       else if (I == Attribute::StackAlignment)
911         StackAlignment = 1ULL << ((A >> 26)-1);
912     }
913   }
914  
915   return *this;
916 }
917
918 uint64_t AttrBuilder::Raw() const {
919   uint64_t Mask = 0;
920
921   for (DenseSet<Attribute::AttrKind>::const_iterator I = Attrs.begin(),
922          E = Attrs.end(); I != E; ++I) {
923     Attribute::AttrKind Kind = *I;
924
925     if (Kind == Attribute::Alignment)
926       Mask |= (Log2_32(Alignment) + 1) << 16;
927     else if (Kind == Attribute::StackAlignment)
928       Mask |= (Log2_32(StackAlignment) + 1) << 26;
929     else
930       Mask |= AttributeImpl::getAttrMask(Kind);
931   }
932
933   return Mask;
934 }
935
936 //===----------------------------------------------------------------------===//
937 // AttributeFuncs Function Defintions
938 //===----------------------------------------------------------------------===//
939
940 /// \brief Which attributes cannot be applied to a type.
941 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
942   AttrBuilder Incompatible;
943
944   if (!Ty->isIntegerTy())
945     // Attribute that only apply to integers.
946     Incompatible.addAttribute(Attribute::SExt)
947       .addAttribute(Attribute::ZExt);
948
949   if (!Ty->isPointerTy())
950     // Attribute that only apply to pointers.
951     Incompatible.addAttribute(Attribute::ByVal)
952       .addAttribute(Attribute::Nest)
953       .addAttribute(Attribute::NoAlias)
954       .addAttribute(Attribute::NoCapture)
955       .addAttribute(Attribute::StructRet);
956
957   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
958 }
959
960 /// \brief This returns an integer containing an encoding of all the LLVM
961 /// attributes found in the given attribute bitset.  Any change to this encoding
962 /// is a breaking change to bitcode compatibility.
963 /// N.B. This should be used only by the bitcode reader!
964 uint64_t AttributeFuncs::encodeLLVMAttributesForBitcode(AttributeSet Attrs,
965                                                         unsigned Index) {
966   // FIXME: It doesn't make sense to store the alignment information as an
967   // expanded out value, we should store it as a log2 value.  However, we can't
968   // just change that here without breaking bitcode compatibility.  If this ever
969   // becomes a problem in practice, we should introduce new tag numbers in the
970   // bitcode file and have those tags use a more efficiently encoded alignment
971   // field.
972
973   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
974   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
975   uint64_t EncodedAttrs = Attrs.Raw(Index) & 0xffff;
976   if (Attrs.hasAttribute(Index, Attribute::Alignment))
977     EncodedAttrs |= Attrs.getParamAlignment(Index) << 16;
978   EncodedAttrs |= (Attrs.Raw(Index) & (0xffffULL << 21)) << 11;
979   return EncodedAttrs;
980 }
981
982 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
983 /// been decoded from the given integer. This function must stay in sync with
984 /// 'encodeLLVMAttributesForBitcode'.
985 /// N.B. This should be used only by the bitcode reader!
986 void AttributeFuncs::decodeLLVMAttributesForBitcode(LLVMContext &C,
987                                                     AttrBuilder &B,
988                                                     uint64_t EncodedAttrs) {
989   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
990   // the bits above 31 down by 11 bits.
991   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
992   assert((!Alignment || isPowerOf2_32(Alignment)) &&
993          "Alignment must be a power of two.");
994
995   if (Alignment)
996     B.addAlignmentAttr(Alignment);
997   B.addRawValue(((EncodedAttrs & (0xffffULL << 32)) >> 11) |
998                 (EncodedAttrs & 0xffff));
999 }