Add a AttributeSetImpl::dump function.
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/Support/Atomic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Attribute Construction Methods
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
34                          uint64_t Val) {
35   LLVMContextImpl *pImpl = Context.pImpl;
36   FoldingSetNodeID ID;
37   ID.AddInteger(Kind);
38   if (Val) ID.AddInteger(Val);
39
40   void *InsertPoint;
41   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
42
43   if (!PA) {
44     // If we didn't find any existing attributes of the same shape then create a
45     // new one and insert it.
46     if (!Val)
47       PA = new EnumAttributeImpl(Kind);
48     else
49       PA = new AlignAttributeImpl(Kind, Val);
50     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
51   }
52
53   // Return the Attribute that we found or created.
54   return Attribute(PA);
55 }
56
57 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
58   LLVMContextImpl *pImpl = Context.pImpl;
59   FoldingSetNodeID ID;
60   ID.AddString(Kind);
61   if (!Val.empty()) ID.AddString(Val);
62
63   void *InsertPoint;
64   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
65
66   if (!PA) {
67     // If we didn't find any existing attributes of the same shape then create a
68     // new one and insert it.
69     PA = new StringAttributeImpl(Kind, Val);
70     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
71   }
72
73   // Return the Attribute that we found or created.
74   return Attribute(PA);
75 }
76
77 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
78   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
79   assert(Align <= 0x40000000 && "Alignment too large.");
80   return get(Context, Alignment, Align);
81 }
82
83 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
84                                            uint64_t Align) {
85   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
86   assert(Align <= 0x100 && "Alignment too large.");
87   return get(Context, StackAlignment, Align);
88 }
89
90 //===----------------------------------------------------------------------===//
91 // Attribute Accessor Methods
92 //===----------------------------------------------------------------------===//
93
94 bool Attribute::isEnumAttribute() const {
95   return pImpl && pImpl->isEnumAttribute();
96 }
97
98 bool Attribute::isAlignAttribute() const {
99   return pImpl && pImpl->isAlignAttribute();
100 }
101
102 bool Attribute::isStringAttribute() const {
103   return pImpl && pImpl->isStringAttribute();
104 }
105
106 Attribute::AttrKind Attribute::getKindAsEnum() const {
107   if (!pImpl) return None;
108   assert((isEnumAttribute() || isAlignAttribute()) &&
109          "Invalid attribute type to get the kind as an enum!");
110   return pImpl ? pImpl->getKindAsEnum() : None;
111 }
112
113 uint64_t Attribute::getValueAsInt() const {
114   if (!pImpl) return 0;
115   assert(isAlignAttribute() &&
116          "Expected the attribute to be an alignment attribute!");
117   return pImpl ? pImpl->getValueAsInt() : 0;
118 }
119
120 StringRef Attribute::getKindAsString() const {
121   if (!pImpl) return StringRef();
122   assert(isStringAttribute() &&
123          "Invalid attribute type to get the kind as a string!");
124   return pImpl ? pImpl->getKindAsString() : StringRef();
125 }
126
127 StringRef Attribute::getValueAsString() const {
128   if (!pImpl) return StringRef();
129   assert(isStringAttribute() &&
130          "Invalid attribute type to get the value as a string!");
131   return pImpl ? pImpl->getValueAsString() : StringRef();
132 }
133
134 bool Attribute::hasAttribute(AttrKind Kind) const {
135   return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
136 }
137
138 bool Attribute::hasAttribute(StringRef Kind) const {
139   if (!isStringAttribute()) return false;
140   return pImpl && pImpl->hasAttribute(Kind);
141 }
142
143 /// This returns the alignment field of an attribute as a byte alignment value.
144 unsigned Attribute::getAlignment() const {
145   assert(hasAttribute(Attribute::Alignment) &&
146          "Trying to get alignment from non-alignment attribute!");
147   return pImpl->getValueAsInt();
148 }
149
150 /// This returns the stack alignment field of an attribute as a byte alignment
151 /// value.
152 unsigned Attribute::getStackAlignment() const {
153   assert(hasAttribute(Attribute::StackAlignment) &&
154          "Trying to get alignment from non-alignment attribute!");
155   return pImpl->getValueAsInt();
156 }
157
158 std::string Attribute::getAsString(bool InAttrGrp) const {
159   if (!pImpl) return "";
160
161   if (hasAttribute(Attribute::SanitizeAddress))
162     return "sanitize_address";
163   if (hasAttribute(Attribute::AlwaysInline))
164     return "alwaysinline";
165   if (hasAttribute(Attribute::Builtin))
166     return "builtin";
167   if (hasAttribute(Attribute::ByVal))
168     return "byval";
169   if (hasAttribute(Attribute::InlineHint))
170     return "inlinehint";
171   if (hasAttribute(Attribute::InReg))
172     return "inreg";
173   if (hasAttribute(Attribute::MinSize))
174     return "minsize";
175   if (hasAttribute(Attribute::Naked))
176     return "naked";
177   if (hasAttribute(Attribute::Nest))
178     return "nest";
179   if (hasAttribute(Attribute::NoAlias))
180     return "noalias";
181   if (hasAttribute(Attribute::NoBuiltin))
182     return "nobuiltin";
183   if (hasAttribute(Attribute::NoCapture))
184     return "nocapture";
185   if (hasAttribute(Attribute::NoDuplicate))
186     return "noduplicate";
187   if (hasAttribute(Attribute::NoImplicitFloat))
188     return "noimplicitfloat";
189   if (hasAttribute(Attribute::NoInline))
190     return "noinline";
191   if (hasAttribute(Attribute::NonLazyBind))
192     return "nonlazybind";
193   if (hasAttribute(Attribute::NoRedZone))
194     return "noredzone";
195   if (hasAttribute(Attribute::NoReturn))
196     return "noreturn";
197   if (hasAttribute(Attribute::NoUnwind))
198     return "nounwind";
199   if (hasAttribute(Attribute::OptimizeForSize))
200     return "optsize";
201   if (hasAttribute(Attribute::ReadNone))
202     return "readnone";
203   if (hasAttribute(Attribute::ReadOnly))
204     return "readonly";
205   if (hasAttribute(Attribute::Returned))
206     return "returned";
207   if (hasAttribute(Attribute::ReturnsTwice))
208     return "returns_twice";
209   if (hasAttribute(Attribute::SExt))
210     return "signext";
211   if (hasAttribute(Attribute::StackProtect))
212     return "ssp";
213   if (hasAttribute(Attribute::StackProtectReq))
214     return "sspreq";
215   if (hasAttribute(Attribute::StackProtectStrong))
216     return "sspstrong";
217   if (hasAttribute(Attribute::StructRet))
218     return "sret";
219   if (hasAttribute(Attribute::SanitizeThread))
220     return "sanitize_thread";
221   if (hasAttribute(Attribute::SanitizeMemory))
222     return "sanitize_memory";
223   if (hasAttribute(Attribute::UWTable))
224     return "uwtable";
225   if (hasAttribute(Attribute::ZExt))
226     return "zeroext";
227   if (hasAttribute(Attribute::Cold))
228     return "cold";
229
230   // FIXME: These should be output like this:
231   //
232   //   align=4
233   //   alignstack=8
234   //
235   if (hasAttribute(Attribute::Alignment)) {
236     std::string Result;
237     Result += "align";
238     Result += (InAttrGrp) ? "=" : " ";
239     Result += utostr(getValueAsInt());
240     return Result;
241   }
242
243   if (hasAttribute(Attribute::StackAlignment)) {
244     std::string Result;
245     Result += "alignstack";
246     if (InAttrGrp) {
247       Result += "=";
248       Result += utostr(getValueAsInt());
249     } else {
250       Result += "(";
251       Result += utostr(getValueAsInt());
252       Result += ")";
253     }
254     return Result;
255   }
256
257   // Convert target-dependent attributes to strings of the form:
258   //
259   //   "kind"
260   //   "kind" = "value"
261   //
262   if (isStringAttribute()) {
263     std::string Result;
264     Result += '\"' + getKindAsString().str() + '"';
265
266     StringRef Val = pImpl->getValueAsString();
267     if (Val.empty()) return Result;
268
269     Result += "=\"" + Val.str() + '"';
270     return Result;
271   }
272
273   llvm_unreachable("Unknown attribute");
274 }
275
276 bool Attribute::operator<(Attribute A) const {
277   if (!pImpl && !A.pImpl) return false;
278   if (!pImpl) return true;
279   if (!A.pImpl) return false;
280   return *pImpl < *A.pImpl;
281 }
282
283 //===----------------------------------------------------------------------===//
284 // AttributeImpl Definition
285 //===----------------------------------------------------------------------===//
286
287 AttributeImpl::~AttributeImpl() {}
288
289 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
290   if (isStringAttribute()) return false;
291   return getKindAsEnum() == A;
292 }
293
294 bool AttributeImpl::hasAttribute(StringRef Kind) const {
295   if (!isStringAttribute()) return false;
296   return getKindAsString() == Kind;
297 }
298
299 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
300   assert(isEnumAttribute() || isAlignAttribute());
301   return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
302 }
303
304 uint64_t AttributeImpl::getValueAsInt() const {
305   assert(isAlignAttribute());
306   return static_cast<const AlignAttributeImpl *>(this)->getAlignment();
307 }
308
309 StringRef AttributeImpl::getKindAsString() const {
310   assert(isStringAttribute());
311   return static_cast<const StringAttributeImpl *>(this)->getStringKind();
312 }
313
314 StringRef AttributeImpl::getValueAsString() const {
315   assert(isStringAttribute());
316   return static_cast<const StringAttributeImpl *>(this)->getStringValue();
317 }
318
319 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
320   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
321   // relative to their enum value) and then strings.
322   if (isEnumAttribute()) {
323     if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
324     if (AI.isAlignAttribute()) return true;
325     if (AI.isStringAttribute()) return true;
326   }
327
328   if (isAlignAttribute()) {
329     if (AI.isEnumAttribute()) return false;
330     if (AI.isAlignAttribute()) return getValueAsInt() < AI.getValueAsInt();
331     if (AI.isStringAttribute()) return true;
332   }
333
334   if (AI.isEnumAttribute()) return false;
335   if (AI.isAlignAttribute()) return false;
336   if (getKindAsString() == AI.getKindAsString())
337     return getValueAsString() < AI.getValueAsString();
338   return getKindAsString() < AI.getKindAsString();
339 }
340
341 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
342   // FIXME: Remove this.
343   switch (Val) {
344   case Attribute::EndAttrKinds:
345     llvm_unreachable("Synthetic enumerators which should never get here");
346
347   case Attribute::None:            return 0;
348   case Attribute::ZExt:            return 1 << 0;
349   case Attribute::SExt:            return 1 << 1;
350   case Attribute::NoReturn:        return 1 << 2;
351   case Attribute::InReg:           return 1 << 3;
352   case Attribute::StructRet:       return 1 << 4;
353   case Attribute::NoUnwind:        return 1 << 5;
354   case Attribute::NoAlias:         return 1 << 6;
355   case Attribute::ByVal:           return 1 << 7;
356   case Attribute::Nest:            return 1 << 8;
357   case Attribute::ReadNone:        return 1 << 9;
358   case Attribute::ReadOnly:        return 1 << 10;
359   case Attribute::NoInline:        return 1 << 11;
360   case Attribute::AlwaysInline:    return 1 << 12;
361   case Attribute::OptimizeForSize: return 1 << 13;
362   case Attribute::StackProtect:    return 1 << 14;
363   case Attribute::StackProtectReq: return 1 << 15;
364   case Attribute::Alignment:       return 31 << 16;
365   case Attribute::NoCapture:       return 1 << 21;
366   case Attribute::NoRedZone:       return 1 << 22;
367   case Attribute::NoImplicitFloat: return 1 << 23;
368   case Attribute::Naked:           return 1 << 24;
369   case Attribute::InlineHint:      return 1 << 25;
370   case Attribute::StackAlignment:  return 7 << 26;
371   case Attribute::ReturnsTwice:    return 1 << 29;
372   case Attribute::UWTable:         return 1 << 30;
373   case Attribute::NonLazyBind:     return 1U << 31;
374   case Attribute::SanitizeAddress: return 1ULL << 32;
375   case Attribute::MinSize:         return 1ULL << 33;
376   case Attribute::NoDuplicate:     return 1ULL << 34;
377   case Attribute::StackProtectStrong: return 1ULL << 35;
378   case Attribute::SanitizeThread:  return 1ULL << 36;
379   case Attribute::SanitizeMemory:  return 1ULL << 37;
380   case Attribute::NoBuiltin:       return 1ULL << 38;
381   case Attribute::Returned:        return 1ULL << 39;
382   case Attribute::Cold:            return 1ULL << 40;
383   case Attribute::Builtin:         return 1ULL << 41;
384   }
385   llvm_unreachable("Unsupported attribute type");
386 }
387
388 //===----------------------------------------------------------------------===//
389 // AttributeSetNode Definition
390 //===----------------------------------------------------------------------===//
391
392 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
393                                         ArrayRef<Attribute> Attrs) {
394   if (Attrs.empty())
395     return 0;
396
397   // Otherwise, build a key to look up the existing attributes.
398   LLVMContextImpl *pImpl = C.pImpl;
399   FoldingSetNodeID ID;
400
401   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
402   array_pod_sort(SortedAttrs.begin(), SortedAttrs.end());
403
404   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
405          E = SortedAttrs.end(); I != E; ++I)
406     I->Profile(ID);
407
408   void *InsertPoint;
409   AttributeSetNode *PA =
410     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
411
412   // If we didn't find any existing attributes of the same shape then create a
413   // new one and insert it.
414   if (!PA) {
415     // Coallocate entries after the AttributeSetNode itself.
416     void *Mem = ::operator new(sizeof(AttributeSetNode) +
417                                sizeof(Attribute) * SortedAttrs.size());
418     PA = new (Mem) AttributeSetNode(SortedAttrs);
419     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
420   }
421
422   // Return the AttributesListNode that we found or created.
423   return PA;
424 }
425
426 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
427   for (iterator I = begin(), E = end(); I != E; ++I)
428     if (I->hasAttribute(Kind))
429       return true;
430   return false;
431 }
432
433 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
434   for (iterator I = begin(), E = end(); I != E; ++I)
435     if (I->hasAttribute(Kind))
436       return true;
437   return false;
438 }
439
440 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
441   for (iterator I = begin(), E = end(); I != E; ++I)
442     if (I->hasAttribute(Kind))
443       return *I;
444   return Attribute();
445 }
446
447 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
448   for (iterator I = begin(), E = end(); I != E; ++I)
449     if (I->hasAttribute(Kind))
450       return *I;
451   return Attribute();
452 }
453
454 unsigned AttributeSetNode::getAlignment() const {
455   for (iterator I = begin(), E = end(); I != E; ++I)
456     if (I->hasAttribute(Attribute::Alignment))
457       return I->getAlignment();
458   return 0;
459 }
460
461 unsigned AttributeSetNode::getStackAlignment() const {
462   for (iterator I = begin(), E = end(); I != E; ++I)
463     if (I->hasAttribute(Attribute::StackAlignment))
464       return I->getStackAlignment();
465   return 0;
466 }
467
468 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
469   std::string Str;
470   for (iterator I = begin(), E = end(); I != E; ++I) {
471     if (I != begin())
472       Str += ' ';
473     Str += I->getAsString(InAttrGrp);
474   }
475   return Str;
476 }
477
478 //===----------------------------------------------------------------------===//
479 // AttributeSetImpl Definition
480 //===----------------------------------------------------------------------===//
481
482 uint64_t AttributeSetImpl::Raw(unsigned Index) const {
483   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
484     if (getSlotIndex(I) != Index) continue;
485     const AttributeSetNode *ASN = getSlotNode(I);
486     uint64_t Mask = 0;
487
488     for (AttributeSetNode::iterator II = ASN->begin(),
489            IE = ASN->end(); II != IE; ++II) {
490       Attribute Attr = *II;
491
492       // This cannot handle string attributes.
493       if (Attr.isStringAttribute()) continue;
494
495       Attribute::AttrKind Kind = Attr.getKindAsEnum();
496
497       if (Kind == Attribute::Alignment)
498         Mask |= (Log2_32(ASN->getAlignment()) + 1) << 16;
499       else if (Kind == Attribute::StackAlignment)
500         Mask |= (Log2_32(ASN->getStackAlignment()) + 1) << 26;
501       else
502         Mask |= AttributeImpl::getAttrMask(Kind);
503     }
504
505     return Mask;
506   }
507
508   return 0;
509 }
510
511 void AttributeSetImpl::dump() const {
512   AttributeSet(const_cast<AttributeSetImpl *>(this)).dump();
513 }
514
515 //===----------------------------------------------------------------------===//
516 // AttributeSet Construction and Mutation Methods
517 //===----------------------------------------------------------------------===//
518
519 AttributeSet
520 AttributeSet::getImpl(LLVMContext &C,
521                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
522   LLVMContextImpl *pImpl = C.pImpl;
523   FoldingSetNodeID ID;
524   AttributeSetImpl::Profile(ID, Attrs);
525
526   void *InsertPoint;
527   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
528
529   // If we didn't find any existing attributes of the same shape then
530   // create a new one and insert it.
531   if (!PA) {
532     // Coallocate entries after the AttributeSetImpl itself.
533     void *Mem = ::operator new(sizeof(AttributeSetImpl) +
534                                sizeof(std::pair<unsigned, AttributeSetNode *>) *
535                                    Attrs.size());
536     PA = new (Mem) AttributeSetImpl(C, Attrs);
537     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
538   }
539
540   // Return the AttributesList that we found or created.
541   return AttributeSet(PA);
542 }
543
544 AttributeSet AttributeSet::get(LLVMContext &C,
545                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
546   // If there are no attributes then return a null AttributesList pointer.
547   if (Attrs.empty())
548     return AttributeSet();
549
550 #ifndef NDEBUG
551   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
552     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
553            "Misordered Attributes list!");
554     assert(!Attrs[i].second.hasAttribute(Attribute::None) &&
555            "Pointless attribute!");
556   }
557 #endif
558
559   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
560   // list.
561   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
562   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
563          E = Attrs.end(); I != E; ) {
564     unsigned Index = I->first;
565     SmallVector<Attribute, 4> AttrVec;
566     while (I != E && I->first == Index) {
567       AttrVec.push_back(I->second);
568       ++I;
569     }
570
571     AttrPairVec.push_back(std::make_pair(Index,
572                                          AttributeSetNode::get(C, AttrVec)));
573   }
574
575   return getImpl(C, AttrPairVec);
576 }
577
578 AttributeSet AttributeSet::get(LLVMContext &C,
579                                ArrayRef<std::pair<unsigned,
580                                                   AttributeSetNode*> > Attrs) {
581   // If there are no attributes then return a null AttributesList pointer.
582   if (Attrs.empty())
583     return AttributeSet();
584
585   return getImpl(C, Attrs);
586 }
587
588 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index, AttrBuilder &B) {
589   if (!B.hasAttributes())
590     return AttributeSet();
591
592   // Add target-independent attributes.
593   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
594   for (Attribute::AttrKind Kind = Attribute::None;
595        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
596     if (!B.contains(Kind))
597       continue;
598
599     if (Kind == Attribute::Alignment)
600       Attrs.push_back(std::make_pair(Index, Attribute::
601                                      getWithAlignment(C, B.getAlignment())));
602     else if (Kind == Attribute::StackAlignment)
603       Attrs.push_back(std::make_pair(Index, Attribute::
604                               getWithStackAlignment(C, B.getStackAlignment())));
605     else
606       Attrs.push_back(std::make_pair(Index, Attribute::get(C, Kind)));
607   }
608
609   // Add target-dependent (string) attributes.
610   for (AttrBuilder::td_iterator I = B.td_begin(), E = B.td_end();
611        I != E; ++I)
612     Attrs.push_back(std::make_pair(Index, Attribute::get(C, I->first,I->second)));
613
614   return get(C, Attrs);
615 }
616
617 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index,
618                                ArrayRef<Attribute::AttrKind> Kind) {
619   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
620   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
621          E = Kind.end(); I != E; ++I)
622     Attrs.push_back(std::make_pair(Index, Attribute::get(C, *I)));
623   return get(C, Attrs);
624 }
625
626 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
627   if (Attrs.empty()) return AttributeSet();
628   if (Attrs.size() == 1) return Attrs[0];
629
630   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
631   AttributeSetImpl *A0 = Attrs[0].pImpl;
632   if (A0)
633     AttrNodeVec.append(A0->getNode(0), A0->getNode(A0->getNumAttributes()));
634   // Copy all attributes from Attrs into AttrNodeVec while keeping AttrNodeVec
635   // ordered by index.  Because we know that each list in Attrs is ordered by
636   // index we only need to merge each successive list in rather than doing a
637   // full sort.
638   for (unsigned I = 1, E = Attrs.size(); I != E; ++I) {
639     AttributeSetImpl *AS = Attrs[I].pImpl;
640     if (!AS) continue;
641     SmallVector<std::pair<unsigned, AttributeSetNode *>, 8>::iterator
642       ANVI = AttrNodeVec.begin(), ANVE;
643     for (const AttributeSetImpl::IndexAttrPair
644              *AI = AS->getNode(0),
645              *AE = AS->getNode(AS->getNumAttributes());
646          AI != AE; ++AI) {
647       ANVE = AttrNodeVec.end();
648       while (ANVI != ANVE && ANVI->first <= AI->first)
649         ++ANVI;
650       ANVI = AttrNodeVec.insert(ANVI, *AI) + 1;
651     }
652   }
653
654   return getImpl(C, AttrNodeVec);
655 }
656
657 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
658                                         Attribute::AttrKind Attr) const {
659   if (hasAttribute(Index, Attr)) return *this;
660   return addAttributes(C, Index, AttributeSet::get(C, Index, Attr));
661 }
662
663 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
664                                         StringRef Kind) const {
665   llvm::AttrBuilder B;
666   B.addAttribute(Kind);
667   return addAttributes(C, Index, AttributeSet::get(C, Index, B));
668 }
669
670 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
671                                         StringRef Kind, StringRef Value) const {
672   llvm::AttrBuilder B;
673   B.addAttribute(Kind, Value);
674   return addAttributes(C, Index, AttributeSet::get(C, Index, B));
675 }
676
677 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Index,
678                                          AttributeSet Attrs) const {
679   if (!pImpl) return Attrs;
680   if (!Attrs.pImpl) return *this;
681
682 #ifndef NDEBUG
683   // FIXME it is not obvious how this should work for alignment. For now, say
684   // we can't change a known alignment.
685   unsigned OldAlign = getParamAlignment(Index);
686   unsigned NewAlign = Attrs.getParamAlignment(Index);
687   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
688          "Attempt to change alignment!");
689 #endif
690
691   // Add the attribute slots before the one we're trying to add.
692   SmallVector<AttributeSet, 4> AttrSet;
693   uint64_t NumAttrs = pImpl->getNumAttributes();
694   AttributeSet AS;
695   uint64_t LastIndex = 0;
696   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
697     if (getSlotIndex(I) >= Index) {
698       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
699       break;
700     }
701     LastIndex = I + 1;
702     AttrSet.push_back(getSlotAttributes(I));
703   }
704
705   // Now add the attribute into the correct slot. There may already be an
706   // AttributeSet there.
707   AttrBuilder B(AS, Index);
708
709   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
710     if (Attrs.getSlotIndex(I) == Index) {
711       for (AttributeSetImpl::iterator II = Attrs.pImpl->begin(I),
712              IE = Attrs.pImpl->end(I); II != IE; ++II)
713         B.addAttribute(*II);
714       break;
715     }
716
717   AttrSet.push_back(AttributeSet::get(C, Index, B));
718
719   // Add the remaining attribute slots.
720   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
721     AttrSet.push_back(getSlotAttributes(I));
722
723   return get(C, AttrSet);
724 }
725
726 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Index,
727                                            Attribute::AttrKind Attr) const {
728   if (!hasAttribute(Index, Attr)) return *this;
729   return removeAttributes(C, Index, AttributeSet::get(C, Index, Attr));
730 }
731
732 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Index,
733                                             AttributeSet Attrs) const {
734   if (!pImpl) return AttributeSet();
735   if (!Attrs.pImpl) return *this;
736
737 #ifndef NDEBUG
738   // FIXME it is not obvious how this should work for alignment.
739   // For now, say we can't pass in alignment, which no current use does.
740   assert(!Attrs.hasAttribute(Index, Attribute::Alignment) &&
741          "Attempt to change alignment!");
742 #endif
743
744   // Add the attribute slots before the one we're trying to add.
745   SmallVector<AttributeSet, 4> AttrSet;
746   uint64_t NumAttrs = pImpl->getNumAttributes();
747   AttributeSet AS;
748   uint64_t LastIndex = 0;
749   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
750     if (getSlotIndex(I) >= Index) {
751       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
752       break;
753     }
754     LastIndex = I + 1;
755     AttrSet.push_back(getSlotAttributes(I));
756   }
757
758   // Now remove the attribute from the correct slot. There may already be an
759   // AttributeSet there.
760   AttrBuilder B(AS, Index);
761
762   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
763     if (Attrs.getSlotIndex(I) == Index) {
764       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Index);
765       break;
766     }
767
768   AttrSet.push_back(AttributeSet::get(C, Index, B));
769
770   // Add the remaining attribute slots.
771   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
772     AttrSet.push_back(getSlotAttributes(I));
773
774   return get(C, AttrSet);
775 }
776
777 //===----------------------------------------------------------------------===//
778 // AttributeSet Accessor Methods
779 //===----------------------------------------------------------------------===//
780
781 LLVMContext &AttributeSet::getContext() const {
782   return pImpl->getContext();
783 }
784
785 AttributeSet AttributeSet::getParamAttributes(unsigned Index) const {
786   return pImpl && hasAttributes(Index) ?
787     AttributeSet::get(pImpl->getContext(),
788                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
789                         std::make_pair(Index, getAttributes(Index)))) :
790     AttributeSet();
791 }
792
793 AttributeSet AttributeSet::getRetAttributes() const {
794   return pImpl && hasAttributes(ReturnIndex) ?
795     AttributeSet::get(pImpl->getContext(),
796                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
797                         std::make_pair(ReturnIndex,
798                                        getAttributes(ReturnIndex)))) :
799     AttributeSet();
800 }
801
802 AttributeSet AttributeSet::getFnAttributes() const {
803   return pImpl && hasAttributes(FunctionIndex) ?
804     AttributeSet::get(pImpl->getContext(),
805                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
806                         std::make_pair(FunctionIndex,
807                                        getAttributes(FunctionIndex)))) :
808     AttributeSet();
809 }
810
811 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
812   AttributeSetNode *ASN = getAttributes(Index);
813   return ASN ? ASN->hasAttribute(Kind) : false;
814 }
815
816 bool AttributeSet::hasAttribute(unsigned Index, StringRef Kind) const {
817   AttributeSetNode *ASN = getAttributes(Index);
818   return ASN ? ASN->hasAttribute(Kind) : false;
819 }
820
821 bool AttributeSet::hasAttributes(unsigned Index) const {
822   AttributeSetNode *ASN = getAttributes(Index);
823   return ASN ? ASN->hasAttributes() : false;
824 }
825
826 /// \brief Return true if the specified attribute is set for at least one
827 /// parameter or for the return value.
828 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
829   if (pImpl == 0) return false;
830
831   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
832     for (AttributeSetImpl::iterator II = pImpl->begin(I),
833            IE = pImpl->end(I); II != IE; ++II)
834       if (II->hasAttribute(Attr))
835         return true;
836
837   return false;
838 }
839
840 Attribute AttributeSet::getAttribute(unsigned Index,
841                                      Attribute::AttrKind Kind) const {
842   AttributeSetNode *ASN = getAttributes(Index);
843   return ASN ? ASN->getAttribute(Kind) : Attribute();
844 }
845
846 Attribute AttributeSet::getAttribute(unsigned Index,
847                                      StringRef Kind) const {
848   AttributeSetNode *ASN = getAttributes(Index);
849   return ASN ? ASN->getAttribute(Kind) : Attribute();
850 }
851
852 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
853   AttributeSetNode *ASN = getAttributes(Index);
854   return ASN ? ASN->getAlignment() : 0;
855 }
856
857 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
858   AttributeSetNode *ASN = getAttributes(Index);
859   return ASN ? ASN->getStackAlignment() : 0;
860 }
861
862 std::string AttributeSet::getAsString(unsigned Index,
863                                       bool InAttrGrp) const {
864   AttributeSetNode *ASN = getAttributes(Index);
865   return ASN ? ASN->getAsString(InAttrGrp) : std::string("");
866 }
867
868 /// \brief The attributes for the specified index are returned.
869 AttributeSetNode *AttributeSet::getAttributes(unsigned Index) const {
870   if (!pImpl) return 0;
871
872   // Loop through to find the attribute node we want.
873   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
874     if (pImpl->getSlotIndex(I) == Index)
875       return pImpl->getSlotNode(I);
876
877   return 0;
878 }
879
880 AttributeSet::iterator AttributeSet::begin(unsigned Slot) const {
881   if (!pImpl)
882     return ArrayRef<Attribute>().begin();
883   return pImpl->begin(Slot);
884 }
885
886 AttributeSet::iterator AttributeSet::end(unsigned Slot) const {
887   if (!pImpl)
888     return ArrayRef<Attribute>().end();
889   return pImpl->end(Slot);
890 }
891
892 //===----------------------------------------------------------------------===//
893 // AttributeSet Introspection Methods
894 //===----------------------------------------------------------------------===//
895
896 /// \brief Return the number of slots used in this attribute list.  This is the
897 /// number of arguments that have an attribute set on them (including the
898 /// function itself).
899 unsigned AttributeSet::getNumSlots() const {
900   return pImpl ? pImpl->getNumAttributes() : 0;
901 }
902
903 unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
904   assert(pImpl && Slot < pImpl->getNumAttributes() &&
905          "Slot # out of range!");
906   return pImpl->getSlotIndex(Slot);
907 }
908
909 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
910   assert(pImpl && Slot < pImpl->getNumAttributes() &&
911          "Slot # out of range!");
912   return pImpl->getSlotAttributes(Slot);
913 }
914
915 uint64_t AttributeSet::Raw(unsigned Index) const {
916   // FIXME: Remove this.
917   return pImpl ? pImpl->Raw(Index) : 0;
918 }
919
920 void AttributeSet::dump() const {
921   dbgs() << "PAL[\n";
922
923   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
924     uint64_t Index = getSlotIndex(i);
925     dbgs() << "  { ";
926     if (Index == ~0U)
927       dbgs() << "~0U";
928     else
929       dbgs() << Index;
930     dbgs() << " => " << getAsString(Index) << " }\n";
931   }
932
933   dbgs() << "]\n";
934 }
935
936 //===----------------------------------------------------------------------===//
937 // AttrBuilder Method Implementations
938 //===----------------------------------------------------------------------===//
939
940 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
941   : Attrs(0), Alignment(0), StackAlignment(0) {
942   AttributeSetImpl *pImpl = AS.pImpl;
943   if (!pImpl) return;
944
945   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
946     if (pImpl->getSlotIndex(I) != Index) continue;
947
948     for (AttributeSetImpl::iterator II = pImpl->begin(I),
949            IE = pImpl->end(I); II != IE; ++II)
950       addAttribute(*II);
951
952     break;
953   }
954 }
955
956 void AttrBuilder::clear() {
957   Attrs.reset();
958   Alignment = StackAlignment = 0;
959 }
960
961 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
962   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
963   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
964          "Adding alignment attribute without adding alignment value!");
965   Attrs[Val] = true;
966   return *this;
967 }
968
969 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
970   if (Attr.isStringAttribute()) {
971     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
972     return *this;
973   }
974
975   Attribute::AttrKind Kind = Attr.getKindAsEnum();
976   Attrs[Kind] = true;
977
978   if (Kind == Attribute::Alignment)
979     Alignment = Attr.getAlignment();
980   else if (Kind == Attribute::StackAlignment)
981     StackAlignment = Attr.getStackAlignment();
982   return *this;
983 }
984
985 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
986   TargetDepAttrs[A] = V;
987   return *this;
988 }
989
990 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
991   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
992   Attrs[Val] = false;
993
994   if (Val == Attribute::Alignment)
995     Alignment = 0;
996   else if (Val == Attribute::StackAlignment)
997     StackAlignment = 0;
998
999   return *this;
1000 }
1001
1002 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
1003   unsigned Slot = ~0U;
1004   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1005     if (A.getSlotIndex(I) == Index) {
1006       Slot = I;
1007       break;
1008     }
1009
1010   assert(Slot != ~0U && "Couldn't find index in AttributeSet!");
1011
1012   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot); I != E; ++I) {
1013     Attribute Attr = *I;
1014     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1015       Attribute::AttrKind Kind = I->getKindAsEnum();
1016       Attrs[Kind] = false;
1017
1018       if (Kind == Attribute::Alignment)
1019         Alignment = 0;
1020       else if (Kind == Attribute::StackAlignment)
1021         StackAlignment = 0;
1022     } else {
1023       assert(Attr.isStringAttribute() && "Invalid attribute type!");
1024       std::map<std::string, std::string>::iterator
1025         Iter = TargetDepAttrs.find(Attr.getKindAsString());
1026       if (Iter != TargetDepAttrs.end())
1027         TargetDepAttrs.erase(Iter);
1028     }
1029   }
1030
1031   return *this;
1032 }
1033
1034 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1035   std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
1036   if (I != TargetDepAttrs.end())
1037     TargetDepAttrs.erase(I);
1038   return *this;
1039 }
1040
1041 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1042   if (Align == 0) return *this;
1043
1044   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1045   assert(Align <= 0x40000000 && "Alignment too large.");
1046
1047   Attrs[Attribute::Alignment] = true;
1048   Alignment = Align;
1049   return *this;
1050 }
1051
1052 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1053   // Default alignment, allow the target to define how to align it.
1054   if (Align == 0) return *this;
1055
1056   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1057   assert(Align <= 0x100 && "Alignment too large.");
1058
1059   Attrs[Attribute::StackAlignment] = true;
1060   StackAlignment = Align;
1061   return *this;
1062 }
1063
1064 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1065   // FIXME: What if both have alignments, but they don't match?!
1066   if (!Alignment)
1067     Alignment = B.Alignment;
1068
1069   if (!StackAlignment)
1070     StackAlignment = B.StackAlignment;
1071
1072   Attrs |= B.Attrs;
1073
1074   for (td_const_iterator I = B.TargetDepAttrs.begin(),
1075          E = B.TargetDepAttrs.end(); I != E; ++I)
1076     TargetDepAttrs[I->first] = I->second;
1077
1078   return *this;
1079 }
1080
1081 bool AttrBuilder::contains(StringRef A) const {
1082   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1083 }
1084
1085 bool AttrBuilder::hasAttributes() const {
1086   return !Attrs.none() || !TargetDepAttrs.empty();
1087 }
1088
1089 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
1090   unsigned Slot = ~0U;
1091   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1092     if (A.getSlotIndex(I) == Index) {
1093       Slot = I;
1094       break;
1095     }
1096
1097   assert(Slot != ~0U && "Couldn't find the index!");
1098
1099   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot);
1100        I != E; ++I) {
1101     Attribute Attr = *I;
1102     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1103       if (Attrs[I->getKindAsEnum()])
1104         return true;
1105     } else {
1106       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1107       return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
1108     }
1109   }
1110
1111   return false;
1112 }
1113
1114 bool AttrBuilder::hasAlignmentAttr() const {
1115   return Alignment != 0;
1116 }
1117
1118 bool AttrBuilder::operator==(const AttrBuilder &B) {
1119   if (Attrs != B.Attrs)
1120     return false;
1121
1122   for (td_const_iterator I = TargetDepAttrs.begin(),
1123          E = TargetDepAttrs.end(); I != E; ++I)
1124     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1125       return false;
1126
1127   return Alignment == B.Alignment && StackAlignment == B.StackAlignment;
1128 }
1129
1130 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
1131   // FIXME: Remove this in 4.0.
1132   if (!Val) return *this;
1133
1134   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1135        I = Attribute::AttrKind(I + 1)) {
1136     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
1137       Attrs[I] = true;
1138  
1139       if (I == Attribute::Alignment)
1140         Alignment = 1ULL << ((A >> 16) - 1);
1141       else if (I == Attribute::StackAlignment)
1142         StackAlignment = 1ULL << ((A >> 26)-1);
1143     }
1144   }
1145  
1146   return *this;
1147 }
1148
1149 //===----------------------------------------------------------------------===//
1150 // AttributeFuncs Function Defintions
1151 //===----------------------------------------------------------------------===//
1152
1153 /// \brief Which attributes cannot be applied to a type.
1154 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
1155   AttrBuilder Incompatible;
1156
1157   if (!Ty->isIntegerTy())
1158     // Attribute that only apply to integers.
1159     Incompatible.addAttribute(Attribute::SExt)
1160       .addAttribute(Attribute::ZExt);
1161
1162   if (!Ty->isPointerTy())
1163     // Attribute that only apply to pointers.
1164     Incompatible.addAttribute(Attribute::ByVal)
1165       .addAttribute(Attribute::Nest)
1166       .addAttribute(Attribute::NoAlias)
1167       .addAttribute(Attribute::NoCapture)
1168       .addAttribute(Attribute::ReadNone)
1169       .addAttribute(Attribute::ReadOnly)
1170       .addAttribute(Attribute::StructRet);
1171
1172   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
1173 }