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   assert(!Slots.empty() && "pointless AttributeListImpl");
725   if (Slots.size() >= 2) {
726     auto &PrevPair = Slots.front();
727     for (auto &CurPair : Slots.drop_front()) {
728       assert(PrevPair.first <= CurPair.first && "Attribute set not ordered!");
729     }
730   }
731 #endif
732 
733   // There's memory after the node where we can store the entries in.
734   std::copy(Slots.begin(), Slots.end(), getTrailingObjects<IndexAttrPair>());
735 
736   // Initialize AvailableFunctionAttrs summary bitset.
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 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
753   Profile(ID, makeArrayRef(getSlotPair(0), getNumSlots()));
754 }
755 
756 void AttributeListImpl::Profile(
757     FoldingSetNodeID &ID, ArrayRef<std::pair<unsigned, AttributeSet>> Nodes) {
758   for (const auto &Node : Nodes) {
759     ID.AddInteger(Node.first);
760     ID.AddPointer(Node.second.SetNode);
761   }
762 }
763 
764 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
765 LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
766   AttributeList(const_cast<AttributeListImpl *>(this)).dump();
767 }
768 #endif
769 
770 //===----------------------------------------------------------------------===//
771 // AttributeList Construction and Mutation Methods
772 //===----------------------------------------------------------------------===//
773 
774 AttributeList AttributeList::getImpl(
775     LLVMContext &C, ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
776   assert(!Attrs.empty() && "creating pointless AttributeList");
777 #ifndef NDEBUG
778   unsigned LastIndex = 0;
779   bool IsFirst = true;
780   for (const auto &AttrPair : Attrs) {
781     assert((IsFirst || LastIndex < AttrPair.first) &&
782            "unsorted or duplicate AttributeList indices");
783     assert(AttrPair.second.hasAttributes() && "pointless AttributeList slot");
784     LastIndex = AttrPair.first;
785     IsFirst = false;
786   }
787 #endif
788 
789   LLVMContextImpl *pImpl = C.pImpl;
790   FoldingSetNodeID ID;
791   AttributeListImpl::Profile(ID, Attrs);
792 
793   void *InsertPoint;
794   AttributeListImpl *PA =
795       pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
796 
797   // If we didn't find any existing attributes of the same shape then
798   // create a new one and insert it.
799   if (!PA) {
800     // Coallocate entries after the AttributeListImpl itself.
801     void *Mem = ::operator new(
802         AttributeListImpl::totalSizeToAlloc<IndexAttrPair>(Attrs.size()));
803     PA = new (Mem) AttributeListImpl(C, Attrs);
804     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
805   }
806 
807   // Return the AttributesList that we found or created.
808   return AttributeList(PA);
809 }
810 
811 AttributeList
812 AttributeList::get(LLVMContext &C,
813                    ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
814   // If there are no attributes then return a null AttributesList pointer.
815   if (Attrs.empty())
816     return AttributeList();
817 
818   assert(std::is_sorted(Attrs.begin(), Attrs.end(),
819                         [](const std::pair<unsigned, Attribute> &LHS,
820                            const std::pair<unsigned, Attribute> &RHS) {
821                           return LHS.first < RHS.first;
822                         }) && "Misordered Attributes list!");
823   assert(none_of(Attrs,
824                  [](const std::pair<unsigned, Attribute> &Pair) {
825                    return Pair.second.hasAttribute(Attribute::None);
826                  }) &&
827          "Pointless attribute!");
828 
829   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
830   // list.
831   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
832   for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
833          E = Attrs.end(); I != E; ) {
834     unsigned Index = I->first;
835     SmallVector<Attribute, 4> AttrVec;
836     while (I != E && I->first == Index) {
837       AttrVec.push_back(I->second);
838       ++I;
839     }
840 
841     AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
842   }
843 
844   return getImpl(C, AttrPairVec);
845 }
846 
847 AttributeList
848 AttributeList::get(LLVMContext &C,
849                    ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
850   // If there are no attributes then return a null AttributesList pointer.
851   if (Attrs.empty())
852     return AttributeList();
853 
854   return getImpl(C, Attrs);
855 }
856 
857 AttributeList AttributeList::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
858   assert(Attrs.size() >= 2 &&
859          "should always have function and return attr slots");
860   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairs;
861   size_t Index = 0;
862   for (AttributeSet AS : Attrs) {
863     if (AS.hasAttributes()) {
864       // If this is the last AttributeSetNode, it's for the function.
865       if (Index == Attrs.size() - 1)
866         Index = AttributeList::FunctionIndex;
867       AttrPairs.emplace_back(Index, AS);
868     }
869     ++Index;
870   }
871   if (AttrPairs.empty())
872     return AttributeList();
873   return getImpl(C, AttrPairs);
874 }
875 
876 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
877                                  const AttrBuilder &B) {
878   if (!B.hasAttributes())
879     return AttributeList();
880   AttributeSet AS = AttributeSet::get(C, B);
881   std::pair<unsigned, AttributeSet> Arr[1] = {{Index, AS}};
882   return getImpl(C, Arr);
883 }
884 
885 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
886                                  ArrayRef<Attribute::AttrKind> Kinds) {
887   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
888   for (Attribute::AttrKind K : Kinds)
889     Attrs.emplace_back(Index, Attribute::get(C, K));
890   return get(C, Attrs);
891 }
892 
893 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
894                                  ArrayRef<StringRef> Kinds) {
895   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
896   for (StringRef K : Kinds)
897     Attrs.emplace_back(Index, Attribute::get(C, K));
898   return get(C, Attrs);
899 }
900 
901 AttributeList AttributeList::get(LLVMContext &C,
902                                  ArrayRef<AttributeList> Attrs) {
903   if (Attrs.empty())
904     return AttributeList();
905   if (Attrs.size() == 1) return Attrs[0];
906 
907   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrNodeVec;
908   AttributeListImpl *A0 = Attrs[0].pImpl;
909   if (A0)
910     AttrNodeVec.append(A0->getSlotPair(0), A0->getSlotPair(A0->getNumSlots()));
911   // Copy all attributes from Attrs into AttrNodeVec while keeping AttrNodeVec
912   // ordered by index.  Because we know that each list in Attrs is ordered by
913   // index we only need to merge each successive list in rather than doing a
914   // full sort.
915   for (unsigned I = 1, E = Attrs.size(); I != E; ++I) {
916     AttributeListImpl *ALI = Attrs[I].pImpl;
917     if (!ALI) continue;
918     SmallVector<std::pair<unsigned, AttributeSet>, 8>::iterator
919       ANVI = AttrNodeVec.begin(), ANVE;
920     for (const IndexAttrPair *AI = ALI->getSlotPair(0),
921                              *AE = ALI->getSlotPair(ALI->getNumSlots());
922          AI != AE; ++AI) {
923       ANVE = AttrNodeVec.end();
924       while (ANVI != ANVE && ANVI->first <= AI->first)
925         ++ANVI;
926       ANVI = AttrNodeVec.insert(ANVI, *AI) + 1;
927     }
928   }
929 
930   return getImpl(C, AttrNodeVec);
931 }
932 
933 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
934                                           Attribute::AttrKind Kind) const {
935   if (hasAttribute(Index, Kind)) return *this;
936   return addAttributes(C, Index, AttributeList::get(C, Index, Kind));
937 }
938 
939 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
940                                           StringRef Kind,
941                                           StringRef Value) const {
942   AttrBuilder B;
943   B.addAttribute(Kind, Value);
944   return addAttributes(C, Index, AttributeList::get(C, Index, B));
945 }
946 
947 AttributeList AttributeList::addAttribute(LLVMContext &C,
948                                           ArrayRef<unsigned> Indices,
949                                           Attribute A) const {
950   assert(std::is_sorted(Indices.begin(), Indices.end()));
951 
952   unsigned I = 0, E = pImpl ? pImpl->getNumSlots() : 0;
953   SmallVector<IndexAttrPair, 4> AttrVec;
954   for (unsigned Index : Indices) {
955     // Add all attribute slots before the current index.
956     for (; I < E && getSlotIndex(I) < Index; ++I)
957       AttrVec.emplace_back(getSlotIndex(I), pImpl->getSlotNode(I));
958 
959     // Add the attribute at this index. If we already have attributes at this
960     // index, merge them into a new set.
961     AttrBuilder B;
962     if (I < E && getSlotIndex(I) == Index) {
963       B.merge(AttrBuilder(pImpl->getSlotNode(I)));
964       ++I;
965     }
966     B.addAttribute(A);
967     AttrVec.emplace_back(Index, AttributeSet::get(C, B));
968   }
969 
970   // Add remaining attributes.
971   for (; I < E; ++I)
972     AttrVec.emplace_back(getSlotIndex(I), pImpl->getSlotNode(I));
973 
974   return get(C, AttrVec);
975 }
976 
977 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
978                                            AttributeList Attrs) const {
979   if (!pImpl) return Attrs;
980   if (!Attrs.pImpl) return *this;
981 
982   return addAttributes(C, Index, Attrs.getAttributes(Index));
983 }
984 
985 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
986                                            AttributeSet AS) const {
987   if (!AS.hasAttributes())
988     return *this;
989 
990 #ifndef NDEBUG
991   // FIXME it is not obvious how this should work for alignment. For now, say
992   // we can't change a known alignment.
993   unsigned OldAlign = getParamAlignment(Index);
994   unsigned NewAlign = AS.getAlignment();
995   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
996          "Attempt to change alignment!");
997 #endif
998 
999   SmallVector<std::pair<unsigned, AttributeSet>, 4> AttrSet;
1000   uint64_t NumAttrs = pImpl->getNumSlots();
1001   unsigned I;
1002 
1003   // Add all the attribute slots before the one we need to merge.
1004   for (I = 0; I < NumAttrs; ++I) {
1005     if (getSlotIndex(I) >= Index)
1006       break;
1007     AttrSet.emplace_back(getSlotIndex(I), pImpl->getSlotNode(I));
1008   }
1009 
1010   if (I < NumAttrs && getSlotIndex(I) == Index) {
1011     // We need to merge two AttributeSets.
1012     AttributeSet Merged = AttributeSet::get(
1013         C, AttrBuilder(pImpl->getSlotNode(I)).merge(AttrBuilder(AS)));
1014     AttrSet.emplace_back(Index, Merged);
1015     ++I;
1016   } else {
1017     // Otherwise, there were no attributes at this position in the original
1018     // list. Add the set as is.
1019     AttrSet.emplace_back(Index, AS);
1020   }
1021 
1022   // Add the remaining entries.
1023   for (; I < NumAttrs; ++I)
1024     AttrSet.emplace_back(getSlotIndex(I), pImpl->getSlotNode(I));
1025 
1026   return get(C, AttrSet);
1027 }
1028 
1029 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
1030                                            const AttrBuilder &B) const {
1031   return get(C, Index, AttributeSet::get(C, B));
1032 }
1033 
1034 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1035                                              Attribute::AttrKind Kind) const {
1036   if (!hasAttribute(Index, Kind)) return *this;
1037   return removeAttributes(C, Index, AttributeList::get(C, Index, Kind));
1038 }
1039 
1040 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1041                                              StringRef Kind) const {
1042   if (!hasAttribute(Index, Kind)) return *this;
1043   return removeAttributes(C, Index, AttributeList::get(C, Index, Kind));
1044 }
1045 
1046 AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned Index,
1047                                               AttributeList Attrs) const {
1048   if (!pImpl)
1049     return AttributeList();
1050   if (!Attrs.pImpl) return *this;
1051 
1052   // FIXME it is not obvious how this should work for alignment.
1053   // For now, say we can't pass in alignment, which no current use does.
1054   assert(!Attrs.hasAttribute(Index, Attribute::Alignment) &&
1055          "Attempt to change alignment!");
1056 
1057   // Add the attribute slots before the one we're trying to add.
1058   SmallVector<AttributeList, 4> AttrSet;
1059   uint64_t NumAttrs = pImpl->getNumSlots();
1060   AttributeList AL;
1061   uint64_t LastIndex = 0;
1062   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
1063     if (getSlotIndex(I) >= Index) {
1064       if (getSlotIndex(I) == Index) AL = getSlotAttributes(LastIndex++);
1065       break;
1066     }
1067     LastIndex = I + 1;
1068     AttrSet.push_back(getSlotAttributes(I));
1069   }
1070 
1071   // Now remove the attribute from the correct slot. There may already be an
1072   // AttributeList there.
1073   AttrBuilder B(AL, Index);
1074 
1075   for (unsigned I = 0, E = Attrs.pImpl->getNumSlots(); I != E; ++I)
1076     if (Attrs.getSlotIndex(I) == Index) {
1077       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Index);
1078       break;
1079     }
1080 
1081   AttrSet.push_back(AttributeList::get(C, Index, B));
1082 
1083   // Add the remaining attribute slots.
1084   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
1085     AttrSet.push_back(getSlotAttributes(I));
1086 
1087   return get(C, AttrSet);
1088 }
1089 
1090 AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned Index,
1091                                               const AttrBuilder &Attrs) const {
1092   if (!pImpl)
1093     return AttributeList();
1094 
1095   // FIXME it is not obvious how this should work for alignment.
1096   // For now, say we can't pass in alignment, which no current use does.
1097   assert(!Attrs.hasAlignmentAttr() && "Attempt to change alignment!");
1098 
1099   // Add the attribute slots before the one we're trying to add.
1100   SmallVector<AttributeList, 4> AttrSet;
1101   uint64_t NumAttrs = pImpl->getNumSlots();
1102   AttributeList AL;
1103   uint64_t LastIndex = 0;
1104   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
1105     if (getSlotIndex(I) >= Index) {
1106       if (getSlotIndex(I) == Index) AL = getSlotAttributes(LastIndex++);
1107       break;
1108     }
1109     LastIndex = I + 1;
1110     AttrSet.push_back(getSlotAttributes(I));
1111   }
1112 
1113   // Now remove the attribute from the correct slot. There may already be an
1114   // AttributeList there.
1115   AttrBuilder B(AL, Index);
1116   B.remove(Attrs);
1117 
1118   AttrSet.push_back(AttributeList::get(C, Index, B));
1119 
1120   // Add the remaining attribute slots.
1121   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
1122     AttrSet.push_back(getSlotAttributes(I));
1123 
1124   return get(C, AttrSet);
1125 }
1126 
1127 AttributeList AttributeList::removeAttributes(LLVMContext &C,
1128                                               unsigned WithoutIndex) const {
1129   if (!pImpl)
1130     return AttributeList();
1131 
1132   SmallVector<std::pair<unsigned, AttributeSet>, 4> AttrSet;
1133   for (unsigned I = 0, E = pImpl->getNumSlots(); I != E; ++I) {
1134     unsigned Index = getSlotIndex(I);
1135     if (Index != WithoutIndex)
1136       AttrSet.push_back({Index, pImpl->getSlotNode(I)});
1137   }
1138   return get(C, AttrSet);
1139 }
1140 
1141 AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C,
1142                                                     unsigned Index,
1143                                                     uint64_t Bytes) const {
1144   AttrBuilder B;
1145   B.addDereferenceableAttr(Bytes);
1146   return addAttributes(C, Index, AttributeList::get(C, Index, B));
1147 }
1148 
1149 AttributeList
1150 AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
1151                                             uint64_t Bytes) const {
1152   AttrBuilder B;
1153   B.addDereferenceableOrNullAttr(Bytes);
1154   return addAttributes(C, Index, AttributeList::get(C, Index, B));
1155 }
1156 
1157 AttributeList
1158 AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index,
1159                                 unsigned ElemSizeArg,
1160                                 const Optional<unsigned> &NumElemsArg) {
1161   AttrBuilder B;
1162   B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1163   return addAttributes(C, Index, AttributeList::get(C, Index, B));
1164 }
1165 
1166 //===----------------------------------------------------------------------===//
1167 // AttributeList Accessor Methods
1168 //===----------------------------------------------------------------------===//
1169 
1170 LLVMContext &AttributeList::getContext() const { return pImpl->getContext(); }
1171 
1172 AttributeSet AttributeList::getParamAttributes(unsigned Index) const {
1173   return getAttributes(Index);
1174 }
1175 
1176 AttributeSet AttributeList::getRetAttributes() const {
1177   return getAttributes(ReturnIndex);
1178 }
1179 
1180 AttributeSet AttributeList::getFnAttributes() const {
1181   return getAttributes(FunctionIndex);
1182 }
1183 
1184 bool AttributeList::hasAttribute(unsigned Index,
1185                                  Attribute::AttrKind Kind) const {
1186   return getAttributes(Index).hasAttribute(Kind);
1187 }
1188 
1189 bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const {
1190   return getAttributes(Index).hasAttribute(Kind);
1191 }
1192 
1193 bool AttributeList::hasAttributes(unsigned Index) const {
1194   return getAttributes(Index).hasAttributes();
1195 }
1196 
1197 bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const {
1198   return pImpl && pImpl->hasFnAttribute(Kind);
1199 }
1200 
1201 bool AttributeList::hasFnAttribute(StringRef Kind) const {
1202   return hasAttribute(AttributeList::FunctionIndex, Kind);
1203 }
1204 
1205 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
1206                                      unsigned *Index) const {
1207   if (!pImpl) return false;
1208 
1209   for (unsigned I = 0, E = pImpl->getNumSlots(); I != E; ++I)
1210     for (AttributeListImpl::iterator II = pImpl->begin(I), IE = pImpl->end(I);
1211          II != IE; ++II)
1212       if (II->hasAttribute(Attr)) {
1213         if (Index) *Index = pImpl->getSlotIndex(I);
1214         return true;
1215       }
1216 
1217   return false;
1218 }
1219 
1220 Attribute AttributeList::getAttribute(unsigned Index,
1221                                       Attribute::AttrKind Kind) const {
1222   return getAttributes(Index).getAttribute(Kind);
1223 }
1224 
1225 Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const {
1226   return getAttributes(Index).getAttribute(Kind);
1227 }
1228 
1229 unsigned AttributeList::getParamAlignment(unsigned Index) const {
1230   return getAttributes(Index).getAlignment();
1231 }
1232 
1233 unsigned AttributeList::getStackAlignment(unsigned Index) const {
1234   return getAttributes(Index).getStackAlignment();
1235 }
1236 
1237 uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const {
1238   return getAttributes(Index).getDereferenceableBytes();
1239 }
1240 
1241 uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const {
1242   return getAttributes(Index).getDereferenceableOrNullBytes();
1243 }
1244 
1245 std::pair<unsigned, Optional<unsigned>>
1246 AttributeList::getAllocSizeArgs(unsigned Index) const {
1247   return getAttributes(Index).getAllocSizeArgs();
1248 }
1249 
1250 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
1251   return getAttributes(Index).getAsString(InAttrGrp);
1252 }
1253 
1254 AttributeSet AttributeList::getAttributes(unsigned Index) const {
1255   if (!pImpl) return AttributeSet();
1256 
1257   // Loop through to find the attribute node we want.
1258   for (unsigned I = 0, E = pImpl->getNumSlots(); I != E; ++I)
1259     if (pImpl->getSlotIndex(I) == Index)
1260       return pImpl->getSlotNode(I);
1261 
1262   return AttributeSet();
1263 }
1264 
1265 AttributeList::iterator AttributeList::begin(unsigned Slot) const {
1266   if (!pImpl)
1267     return ArrayRef<Attribute>().begin();
1268   return pImpl->begin(Slot);
1269 }
1270 
1271 AttributeList::iterator AttributeList::end(unsigned Slot) const {
1272   if (!pImpl)
1273     return ArrayRef<Attribute>().end();
1274   return pImpl->end(Slot);
1275 }
1276 
1277 //===----------------------------------------------------------------------===//
1278 // AttributeList Introspection Methods
1279 //===----------------------------------------------------------------------===//
1280 
1281 unsigned AttributeList::getNumSlots() const {
1282   return pImpl ? pImpl->getNumSlots() : 0;
1283 }
1284 
1285 unsigned AttributeList::getSlotIndex(unsigned Slot) const {
1286   assert(pImpl && Slot < pImpl->getNumSlots() &&
1287          "Slot # out of range!");
1288   return pImpl->getSlotIndex(Slot);
1289 }
1290 
1291 AttributeList AttributeList::getSlotAttributes(unsigned Slot) const {
1292   assert(pImpl && Slot < pImpl->getNumSlots() &&
1293          "Slot # out of range!");
1294   return pImpl->getSlotAttributes(Slot);
1295 }
1296 
1297 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1298 LLVM_DUMP_METHOD void AttributeList::dump() const {
1299   dbgs() << "PAL[\n";
1300 
1301   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
1302     uint64_t Index = getSlotIndex(i);
1303     dbgs() << "  { ";
1304     if (Index == ~0U)
1305       dbgs() << "~0U";
1306     else
1307       dbgs() << Index;
1308     dbgs() << " => " << getAsString(Index) << " }\n";
1309   }
1310 
1311   dbgs() << "]\n";
1312 }
1313 #endif
1314 
1315 //===----------------------------------------------------------------------===//
1316 // AttrBuilder Method Implementations
1317 //===----------------------------------------------------------------------===//
1318 
1319 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) {
1320   AttributeListImpl *pImpl = AL.pImpl;
1321   if (!pImpl) return;
1322 
1323   for (unsigned I = 0, E = pImpl->getNumSlots(); I != E; ++I) {
1324     if (pImpl->getSlotIndex(I) != Index) continue;
1325 
1326     for (AttributeListImpl::iterator II = pImpl->begin(I), IE = pImpl->end(I);
1327          II != IE; ++II)
1328       addAttribute(*II);
1329 
1330     break;
1331   }
1332 }
1333 
1334 AttrBuilder::AttrBuilder(AttributeSet AS) {
1335   if (AS.hasAttributes()) {
1336     for (const Attribute &A : AS)
1337       addAttribute(A);
1338   }
1339 }
1340 
1341 void AttrBuilder::clear() {
1342   Attrs.reset();
1343   TargetDepAttrs.clear();
1344   Alignment = StackAlignment = DerefBytes = DerefOrNullBytes = 0;
1345   AllocSizeArgs = 0;
1346 }
1347 
1348 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
1349   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1350   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
1351          Val != Attribute::Dereferenceable && Val != Attribute::AllocSize &&
1352          "Adding integer attribute without adding a value!");
1353   Attrs[Val] = true;
1354   return *this;
1355 }
1356 
1357 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
1358   if (Attr.isStringAttribute()) {
1359     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
1360     return *this;
1361   }
1362 
1363   Attribute::AttrKind Kind = Attr.getKindAsEnum();
1364   Attrs[Kind] = true;
1365 
1366   if (Kind == Attribute::Alignment)
1367     Alignment = Attr.getAlignment();
1368   else if (Kind == Attribute::StackAlignment)
1369     StackAlignment = Attr.getStackAlignment();
1370   else if (Kind == Attribute::Dereferenceable)
1371     DerefBytes = Attr.getDereferenceableBytes();
1372   else if (Kind == Attribute::DereferenceableOrNull)
1373     DerefOrNullBytes = Attr.getDereferenceableOrNullBytes();
1374   else if (Kind == Attribute::AllocSize)
1375     AllocSizeArgs = Attr.getValueAsInt();
1376   return *this;
1377 }
1378 
1379 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
1380   TargetDepAttrs[A] = V;
1381   return *this;
1382 }
1383 
1384 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1385   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1386   Attrs[Val] = false;
1387 
1388   if (Val == Attribute::Alignment)
1389     Alignment = 0;
1390   else if (Val == Attribute::StackAlignment)
1391     StackAlignment = 0;
1392   else if (Val == Attribute::Dereferenceable)
1393     DerefBytes = 0;
1394   else if (Val == Attribute::DereferenceableOrNull)
1395     DerefOrNullBytes = 0;
1396   else if (Val == Attribute::AllocSize)
1397     AllocSizeArgs = 0;
1398 
1399   return *this;
1400 }
1401 
1402 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) {
1403   unsigned Slot = ~0U;
1404   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1405     if (A.getSlotIndex(I) == Index) {
1406       Slot = I;
1407       break;
1408     }
1409 
1410   assert(Slot != ~0U && "Couldn't find index in AttributeList!");
1411 
1412   for (AttributeList::iterator I = A.begin(Slot), E = A.end(Slot); I != E;
1413        ++I) {
1414     Attribute Attr = *I;
1415     if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1416       removeAttribute(Attr.getKindAsEnum());
1417     } else {
1418       assert(Attr.isStringAttribute() && "Invalid attribute type!");
1419       removeAttribute(Attr.getKindAsString());
1420     }
1421   }
1422 
1423   return *this;
1424 }
1425 
1426 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1427   std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
1428   if (I != TargetDepAttrs.end())
1429     TargetDepAttrs.erase(I);
1430   return *this;
1431 }
1432 
1433 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
1434   return unpackAllocSizeArgs(AllocSizeArgs);
1435 }
1436 
1437 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1438   if (Align == 0) return *this;
1439 
1440   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1441   assert(Align <= 0x40000000 && "Alignment too large.");
1442 
1443   Attrs[Attribute::Alignment] = true;
1444   Alignment = Align;
1445   return *this;
1446 }
1447 
1448 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1449   // Default alignment, allow the target to define how to align it.
1450   if (Align == 0) return *this;
1451 
1452   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1453   assert(Align <= 0x100 && "Alignment too large.");
1454 
1455   Attrs[Attribute::StackAlignment] = true;
1456   StackAlignment = Align;
1457   return *this;
1458 }
1459 
1460 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
1461   if (Bytes == 0) return *this;
1462 
1463   Attrs[Attribute::Dereferenceable] = true;
1464   DerefBytes = Bytes;
1465   return *this;
1466 }
1467 
1468 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
1469   if (Bytes == 0)
1470     return *this;
1471 
1472   Attrs[Attribute::DereferenceableOrNull] = true;
1473   DerefOrNullBytes = Bytes;
1474   return *this;
1475 }
1476 
1477 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
1478                                            const Optional<unsigned> &NumElems) {
1479   return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
1480 }
1481 
1482 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
1483   // (0, 0) is our "not present" value, so we need to check for it here.
1484   assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
1485 
1486   Attrs[Attribute::AllocSize] = true;
1487   // Reuse existing machinery to store this as a single 64-bit integer so we can
1488   // save a few bytes over using a pair<unsigned, Optional<unsigned>>.
1489   AllocSizeArgs = RawArgs;
1490   return *this;
1491 }
1492 
1493 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1494   // FIXME: What if both have alignments, but they don't match?!
1495   if (!Alignment)
1496     Alignment = B.Alignment;
1497 
1498   if (!StackAlignment)
1499     StackAlignment = B.StackAlignment;
1500 
1501   if (!DerefBytes)
1502     DerefBytes = B.DerefBytes;
1503 
1504   if (!DerefOrNullBytes)
1505     DerefOrNullBytes = B.DerefOrNullBytes;
1506 
1507   if (!AllocSizeArgs)
1508     AllocSizeArgs = B.AllocSizeArgs;
1509 
1510   Attrs |= B.Attrs;
1511 
1512   for (auto I : B.td_attrs())
1513     TargetDepAttrs[I.first] = I.second;
1514 
1515   return *this;
1516 }
1517 
1518 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
1519   // FIXME: What if both have alignments, but they don't match?!
1520   if (B.Alignment)
1521     Alignment = 0;
1522 
1523   if (B.StackAlignment)
1524     StackAlignment = 0;
1525 
1526   if (B.DerefBytes)
1527     DerefBytes = 0;
1528 
1529   if (B.DerefOrNullBytes)
1530     DerefOrNullBytes = 0;
1531 
1532   if (B.AllocSizeArgs)
1533     AllocSizeArgs = 0;
1534 
1535   Attrs &= ~B.Attrs;
1536 
1537   for (auto I : B.td_attrs())
1538     TargetDepAttrs.erase(I.first);
1539 
1540   return *this;
1541 }
1542 
1543 bool AttrBuilder::overlaps(const AttrBuilder &B) const {
1544   // First check if any of the target independent attributes overlap.
1545   if ((Attrs & B.Attrs).any())
1546     return true;
1547 
1548   // Then check if any target dependent ones do.
1549   for (const auto &I : td_attrs())
1550     if (B.contains(I.first))
1551       return true;
1552 
1553   return false;
1554 }
1555 
1556 bool AttrBuilder::contains(StringRef A) const {
1557   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1558 }
1559 
1560 bool AttrBuilder::hasAttributes() const {
1561   return !Attrs.none() || !TargetDepAttrs.empty();
1562 }
1563 
1564 bool AttrBuilder::hasAttributes(AttributeList A, uint64_t Index) const {
1565   unsigned Slot = ~0U;
1566   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1567     if (A.getSlotIndex(I) == Index) {
1568       Slot = I;
1569       break;
1570     }
1571 
1572   assert(Slot != ~0U && "Couldn't find the index!");
1573 
1574   for (AttributeList::iterator I = A.begin(Slot), E = A.end(Slot); I != E;
1575        ++I) {
1576     Attribute Attr = *I;
1577     if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1578       if (Attrs[I->getKindAsEnum()])
1579         return true;
1580     } else {
1581       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1582       return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
1583     }
1584   }
1585 
1586   return false;
1587 }
1588 
1589 bool AttrBuilder::hasAlignmentAttr() const {
1590   return Alignment != 0;
1591 }
1592 
1593 bool AttrBuilder::operator==(const AttrBuilder &B) {
1594   if (Attrs != B.Attrs)
1595     return false;
1596 
1597   for (td_const_iterator I = TargetDepAttrs.begin(),
1598          E = TargetDepAttrs.end(); I != E; ++I)
1599     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1600       return false;
1601 
1602   return Alignment == B.Alignment && StackAlignment == B.StackAlignment &&
1603          DerefBytes == B.DerefBytes;
1604 }
1605 
1606 //===----------------------------------------------------------------------===//
1607 // AttributeFuncs Function Defintions
1608 //===----------------------------------------------------------------------===//
1609 
1610 /// \brief Which attributes cannot be applied to a type.
1611 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) {
1612   AttrBuilder Incompatible;
1613 
1614   if (!Ty->isIntegerTy())
1615     // Attribute that only apply to integers.
1616     Incompatible.addAttribute(Attribute::SExt)
1617       .addAttribute(Attribute::ZExt);
1618 
1619   if (!Ty->isPointerTy())
1620     // Attribute that only apply to pointers.
1621     Incompatible.addAttribute(Attribute::ByVal)
1622       .addAttribute(Attribute::Nest)
1623       .addAttribute(Attribute::NoAlias)
1624       .addAttribute(Attribute::NoCapture)
1625       .addAttribute(Attribute::NonNull)
1626       .addDereferenceableAttr(1) // the int here is ignored
1627       .addDereferenceableOrNullAttr(1) // the int here is ignored
1628       .addAttribute(Attribute::ReadNone)
1629       .addAttribute(Attribute::ReadOnly)
1630       .addAttribute(Attribute::StructRet)
1631       .addAttribute(Attribute::InAlloca);
1632 
1633   return Incompatible;
1634 }
1635 
1636 template<typename AttrClass>
1637 static bool isEqual(const Function &Caller, const Function &Callee) {
1638   return Caller.getFnAttribute(AttrClass::getKind()) ==
1639          Callee.getFnAttribute(AttrClass::getKind());
1640 }
1641 
1642 /// \brief Compute the logical AND of the attributes of the caller and the
1643 /// callee.
1644 ///
1645 /// This function sets the caller's attribute to false if the callee's attribute
1646 /// is false.
1647 template<typename AttrClass>
1648 static void setAND(Function &Caller, const Function &Callee) {
1649   if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
1650       !AttrClass::isSet(Callee, AttrClass::getKind()))
1651     AttrClass::set(Caller, AttrClass::getKind(), false);
1652 }
1653 
1654 /// \brief Compute the logical OR of the attributes of the caller and the
1655 /// callee.
1656 ///
1657 /// This function sets the caller's attribute to true if the callee's attribute
1658 /// is true.
1659 template<typename AttrClass>
1660 static void setOR(Function &Caller, const Function &Callee) {
1661   if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
1662       AttrClass::isSet(Callee, AttrClass::getKind()))
1663     AttrClass::set(Caller, AttrClass::getKind(), true);
1664 }
1665 
1666 /// \brief If the inlined function had a higher stack protection level than the
1667 /// calling function, then bump up the caller's stack protection level.
1668 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
1669   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
1670   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
1671   // clutter to the IR.
1672   AttrBuilder B;
1673   B.addAttribute(Attribute::StackProtect)
1674     .addAttribute(Attribute::StackProtectStrong)
1675     .addAttribute(Attribute::StackProtectReq);
1676   AttributeList OldSSPAttr =
1677       AttributeList::get(Caller.getContext(), AttributeList::FunctionIndex, B);
1678 
1679   if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
1680     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1681     Caller.addFnAttr(Attribute::StackProtectReq);
1682   } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
1683              !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
1684     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1685     Caller.addFnAttr(Attribute::StackProtectStrong);
1686   } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
1687              !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
1688              !Caller.hasFnAttribute(Attribute::StackProtectStrong))
1689     Caller.addFnAttr(Attribute::StackProtect);
1690 }
1691 
1692 #define GET_ATTR_COMPAT_FUNC
1693 #include "AttributesCompatFunc.inc"
1694 
1695 bool AttributeFuncs::areInlineCompatible(const Function &Caller,
1696                                          const Function &Callee) {
1697   return hasCompatibleFnAttrs(Caller, Callee);
1698 }
1699 
1700 void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
1701                                                 const Function &Callee) {
1702   mergeFnAttrs(Caller, Callee);
1703 }
1704