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