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