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