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