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