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