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