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