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