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