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