xref: /freebsd-src/contrib/llvm-project/llvm/lib/IR/Attributes.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===- Attributes.cpp - Implement AttributesList --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // \file
10 // This file implements the Attribute, AttributeImpl, AttrBuilder,
11 // AttributeListImpl, and AttributeList classes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/Attributes.h"
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/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/llvm-config.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 <climits>
39 #include <cstddef>
40 #include <cstdint>
41 #include <limits>
42 #include <string>
43 #include <tuple>
44 #include <utility>
45 
46 using namespace llvm;
47 
48 //===----------------------------------------------------------------------===//
49 // Attribute Construction Methods
50 //===----------------------------------------------------------------------===//
51 
52 // allocsize has two integer arguments, but because they're both 32 bits, we can
53 // pack them into one 64-bit value, at the cost of making said value
54 // nonsensical.
55 //
56 // In order to do this, we need to reserve one value of the second (optional)
57 // allocsize argument to signify "not present."
58 static const unsigned AllocSizeNumElemsNotPresent = -1;
59 
60 static uint64_t packAllocSizeArgs(unsigned ElemSizeArg,
61                                   const Optional<unsigned> &NumElemsArg) {
62   assert((!NumElemsArg.hasValue() ||
63           *NumElemsArg != AllocSizeNumElemsNotPresent) &&
64          "Attempting to pack a reserved value");
65 
66   return uint64_t(ElemSizeArg) << 32 |
67          NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent);
68 }
69 
70 static std::pair<unsigned, Optional<unsigned>>
71 unpackAllocSizeArgs(uint64_t Num) {
72   unsigned NumElems = Num & std::numeric_limits<unsigned>::max();
73   unsigned ElemSizeArg = Num >> 32;
74 
75   Optional<unsigned> NumElemsArg;
76   if (NumElems != AllocSizeNumElemsNotPresent)
77     NumElemsArg = NumElems;
78   return std::make_pair(ElemSizeArg, NumElemsArg);
79 }
80 
81 static uint64_t packVScaleRangeArgs(unsigned MinValue,
82                                     Optional<unsigned> MaxValue) {
83   return uint64_t(MinValue) << 32 | MaxValue.getValueOr(0);
84 }
85 
86 static std::pair<unsigned, Optional<unsigned>>
87 unpackVScaleRangeArgs(uint64_t Value) {
88   unsigned MaxValue = Value & std::numeric_limits<unsigned>::max();
89   unsigned MinValue = Value >> 32;
90 
91   return std::make_pair(MinValue,
92                         MaxValue > 0 ? MaxValue : Optional<unsigned>());
93 }
94 
95 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
96                          uint64_t Val) {
97   if (Val)
98     assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute");
99   else
100     assert(Attribute::isEnumAttrKind(Kind) && "Not an enum attribute");
101 
102   LLVMContextImpl *pImpl = Context.pImpl;
103   FoldingSetNodeID ID;
104   ID.AddInteger(Kind);
105   if (Val) ID.AddInteger(Val);
106 
107   void *InsertPoint;
108   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
109 
110   if (!PA) {
111     // If we didn't find any existing attributes of the same shape then create a
112     // new one and insert it.
113     if (!Val)
114       PA = new (pImpl->Alloc) EnumAttributeImpl(Kind);
115     else
116       PA = new (pImpl->Alloc) IntAttributeImpl(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::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
125   LLVMContextImpl *pImpl = Context.pImpl;
126   FoldingSetNodeID ID;
127   ID.AddString(Kind);
128   if (!Val.empty()) ID.AddString(Val);
129 
130   void *InsertPoint;
131   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
132 
133   if (!PA) {
134     // If we didn't find any existing attributes of the same shape then create a
135     // new one and insert it.
136     void *Mem =
137         pImpl->Alloc.Allocate(StringAttributeImpl::totalSizeToAlloc(Kind, Val),
138                               alignof(StringAttributeImpl));
139     PA = new (Mem) StringAttributeImpl(Kind, Val);
140     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
141   }
142 
143   // Return the Attribute that we found or created.
144   return Attribute(PA);
145 }
146 
147 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
148                          Type *Ty) {
149   assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute");
150   LLVMContextImpl *pImpl = Context.pImpl;
151   FoldingSetNodeID ID;
152   ID.AddInteger(Kind);
153   ID.AddPointer(Ty);
154 
155   void *InsertPoint;
156   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
157 
158   if (!PA) {
159     // If we didn't find any existing attributes of the same shape then create a
160     // new one and insert it.
161     PA = new (pImpl->Alloc) TypeAttributeImpl(Kind, Ty);
162     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
163   }
164 
165   // Return the Attribute that we found or created.
166   return Attribute(PA);
167 }
168 
169 Attribute Attribute::getWithAlignment(LLVMContext &Context, Align A) {
170   assert(A <= llvm::Value::MaximumAlignment && "Alignment too large.");
171   return get(Context, Alignment, A.value());
172 }
173 
174 Attribute Attribute::getWithStackAlignment(LLVMContext &Context, Align A) {
175   assert(A <= 0x100 && "Alignment too large.");
176   return get(Context, StackAlignment, A.value());
177 }
178 
179 Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context,
180                                                 uint64_t Bytes) {
181   assert(Bytes && "Bytes must be non-zero.");
182   return get(Context, Dereferenceable, Bytes);
183 }
184 
185 Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context,
186                                                        uint64_t Bytes) {
187   assert(Bytes && "Bytes must be non-zero.");
188   return get(Context, DereferenceableOrNull, Bytes);
189 }
190 
191 Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) {
192   return get(Context, ByVal, Ty);
193 }
194 
195 Attribute Attribute::getWithStructRetType(LLVMContext &Context, Type *Ty) {
196   return get(Context, StructRet, Ty);
197 }
198 
199 Attribute Attribute::getWithByRefType(LLVMContext &Context, Type *Ty) {
200   return get(Context, ByRef, Ty);
201 }
202 
203 Attribute Attribute::getWithPreallocatedType(LLVMContext &Context, Type *Ty) {
204   return get(Context, Preallocated, Ty);
205 }
206 
207 Attribute Attribute::getWithInAllocaType(LLVMContext &Context, Type *Ty) {
208   return get(Context, InAlloca, Ty);
209 }
210 
211 Attribute
212 Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg,
213                                 const Optional<unsigned> &NumElemsArg) {
214   assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) &&
215          "Invalid allocsize arguments -- given allocsize(0, 0)");
216   return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg));
217 }
218 
219 Attribute Attribute::getWithVScaleRangeArgs(LLVMContext &Context,
220                                             unsigned MinValue,
221                                             unsigned MaxValue) {
222   return get(Context, VScaleRange, packVScaleRangeArgs(MinValue, MaxValue));
223 }
224 
225 Attribute::AttrKind Attribute::getAttrKindFromName(StringRef AttrName) {
226   return StringSwitch<Attribute::AttrKind>(AttrName)
227 #define GET_ATTR_NAMES
228 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)                                \
229   .Case(#DISPLAY_NAME, Attribute::ENUM_NAME)
230 #include "llvm/IR/Attributes.inc"
231       .Default(Attribute::None);
232 }
233 
234 StringRef Attribute::getNameFromAttrKind(Attribute::AttrKind AttrKind) {
235   switch (AttrKind) {
236 #define GET_ATTR_NAMES
237 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)                                \
238   case Attribute::ENUM_NAME:                                                   \
239     return #DISPLAY_NAME;
240 #include "llvm/IR/Attributes.inc"
241   case Attribute::None:
242     return "none";
243   default:
244     llvm_unreachable("invalid Kind");
245   }
246 }
247 
248 bool Attribute::isExistingAttribute(StringRef Name) {
249   return StringSwitch<bool>(Name)
250 #define GET_ATTR_NAMES
251 #define ATTRIBUTE_ALL(ENUM_NAME, DISPLAY_NAME) .Case(#DISPLAY_NAME, true)
252 #include "llvm/IR/Attributes.inc"
253       .Default(false);
254 }
255 
256 //===----------------------------------------------------------------------===//
257 // Attribute Accessor Methods
258 //===----------------------------------------------------------------------===//
259 
260 bool Attribute::isEnumAttribute() const {
261   return pImpl && pImpl->isEnumAttribute();
262 }
263 
264 bool Attribute::isIntAttribute() const {
265   return pImpl && pImpl->isIntAttribute();
266 }
267 
268 bool Attribute::isStringAttribute() const {
269   return pImpl && pImpl->isStringAttribute();
270 }
271 
272 bool Attribute::isTypeAttribute() const {
273   return pImpl && pImpl->isTypeAttribute();
274 }
275 
276 Attribute::AttrKind Attribute::getKindAsEnum() const {
277   if (!pImpl) return None;
278   assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) &&
279          "Invalid attribute type to get the kind as an enum!");
280   return pImpl->getKindAsEnum();
281 }
282 
283 uint64_t Attribute::getValueAsInt() const {
284   if (!pImpl) return 0;
285   assert(isIntAttribute() &&
286          "Expected the attribute to be an integer attribute!");
287   return pImpl->getValueAsInt();
288 }
289 
290 bool Attribute::getValueAsBool() const {
291   if (!pImpl) return false;
292   assert(isStringAttribute() &&
293          "Expected the attribute to be a string attribute!");
294   return pImpl->getValueAsBool();
295 }
296 
297 StringRef Attribute::getKindAsString() const {
298   if (!pImpl) return {};
299   assert(isStringAttribute() &&
300          "Invalid attribute type to get the kind as a string!");
301   return pImpl->getKindAsString();
302 }
303 
304 StringRef Attribute::getValueAsString() const {
305   if (!pImpl) return {};
306   assert(isStringAttribute() &&
307          "Invalid attribute type to get the value as a string!");
308   return pImpl->getValueAsString();
309 }
310 
311 Type *Attribute::getValueAsType() const {
312   if (!pImpl) return {};
313   assert(isTypeAttribute() &&
314          "Invalid attribute type to get the value as a type!");
315   return pImpl->getValueAsType();
316 }
317 
318 
319 bool Attribute::hasAttribute(AttrKind Kind) const {
320   return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
321 }
322 
323 bool Attribute::hasAttribute(StringRef Kind) const {
324   if (!isStringAttribute()) return false;
325   return pImpl && pImpl->hasAttribute(Kind);
326 }
327 
328 MaybeAlign Attribute::getAlignment() const {
329   assert(hasAttribute(Attribute::Alignment) &&
330          "Trying to get alignment from non-alignment attribute!");
331   return MaybeAlign(pImpl->getValueAsInt());
332 }
333 
334 MaybeAlign Attribute::getStackAlignment() const {
335   assert(hasAttribute(Attribute::StackAlignment) &&
336          "Trying to get alignment from non-alignment attribute!");
337   return MaybeAlign(pImpl->getValueAsInt());
338 }
339 
340 uint64_t Attribute::getDereferenceableBytes() const {
341   assert(hasAttribute(Attribute::Dereferenceable) &&
342          "Trying to get dereferenceable bytes from "
343          "non-dereferenceable attribute!");
344   return pImpl->getValueAsInt();
345 }
346 
347 uint64_t Attribute::getDereferenceableOrNullBytes() const {
348   assert(hasAttribute(Attribute::DereferenceableOrNull) &&
349          "Trying to get dereferenceable bytes from "
350          "non-dereferenceable attribute!");
351   return pImpl->getValueAsInt();
352 }
353 
354 std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const {
355   assert(hasAttribute(Attribute::AllocSize) &&
356          "Trying to get allocsize args from non-allocsize attribute");
357   return unpackAllocSizeArgs(pImpl->getValueAsInt());
358 }
359 
360 unsigned Attribute::getVScaleRangeMin() const {
361   assert(hasAttribute(Attribute::VScaleRange) &&
362          "Trying to get vscale args from non-vscale attribute");
363   return unpackVScaleRangeArgs(pImpl->getValueAsInt()).first;
364 }
365 
366 Optional<unsigned> Attribute::getVScaleRangeMax() const {
367   assert(hasAttribute(Attribute::VScaleRange) &&
368          "Trying to get vscale args from non-vscale attribute");
369   return unpackVScaleRangeArgs(pImpl->getValueAsInt()).second;
370 }
371 
372 std::string Attribute::getAsString(bool InAttrGrp) const {
373   if (!pImpl) return {};
374 
375   if (isEnumAttribute())
376     return getNameFromAttrKind(getKindAsEnum()).str();
377 
378   if (isTypeAttribute()) {
379     std::string Result = getNameFromAttrKind(getKindAsEnum()).str();
380     Result += '(';
381     raw_string_ostream OS(Result);
382     getValueAsType()->print(OS, false, true);
383     OS.flush();
384     Result += ')';
385     return Result;
386   }
387 
388   // FIXME: These should be output like this:
389   //
390   //   align=4
391   //   alignstack=8
392   //
393   if (hasAttribute(Attribute::Alignment)) {
394     std::string Result;
395     Result += "align";
396     Result += (InAttrGrp) ? "=" : " ";
397     Result += utostr(getValueAsInt());
398     return Result;
399   }
400 
401   auto AttrWithBytesToString = [&](const char *Name) {
402     std::string Result;
403     Result += Name;
404     if (InAttrGrp) {
405       Result += "=";
406       Result += utostr(getValueAsInt());
407     } else {
408       Result += "(";
409       Result += utostr(getValueAsInt());
410       Result += ")";
411     }
412     return Result;
413   };
414 
415   if (hasAttribute(Attribute::StackAlignment))
416     return AttrWithBytesToString("alignstack");
417 
418   if (hasAttribute(Attribute::Dereferenceable))
419     return AttrWithBytesToString("dereferenceable");
420 
421   if (hasAttribute(Attribute::DereferenceableOrNull))
422     return AttrWithBytesToString("dereferenceable_or_null");
423 
424   if (hasAttribute(Attribute::AllocSize)) {
425     unsigned ElemSize;
426     Optional<unsigned> NumElems;
427     std::tie(ElemSize, NumElems) = getAllocSizeArgs();
428 
429     std::string Result = "allocsize(";
430     Result += utostr(ElemSize);
431     if (NumElems.hasValue()) {
432       Result += ',';
433       Result += utostr(*NumElems);
434     }
435     Result += ')';
436     return Result;
437   }
438 
439   if (hasAttribute(Attribute::VScaleRange)) {
440     unsigned MinValue = getVScaleRangeMin();
441     Optional<unsigned> MaxValue = getVScaleRangeMax();
442 
443     std::string Result = "vscale_range(";
444     Result += utostr(MinValue);
445     Result += ',';
446     Result += utostr(MaxValue.getValueOr(0));
447     Result += ')';
448     return Result;
449   }
450 
451   // Convert target-dependent attributes to strings of the form:
452   //
453   //   "kind"
454   //   "kind" = "value"
455   //
456   if (isStringAttribute()) {
457     std::string Result;
458     {
459       raw_string_ostream OS(Result);
460       OS << '"' << getKindAsString() << '"';
461 
462       // Since some attribute strings contain special characters that cannot be
463       // printable, those have to be escaped to make the attribute value
464       // printable as is.  e.g. "\01__gnu_mcount_nc"
465       const auto &AttrVal = pImpl->getValueAsString();
466       if (!AttrVal.empty()) {
467         OS << "=\"";
468         printEscapedString(AttrVal, OS);
469         OS << "\"";
470       }
471     }
472     return Result;
473   }
474 
475   llvm_unreachable("Unknown attribute");
476 }
477 
478 bool Attribute::hasParentContext(LLVMContext &C) const {
479   assert(isValid() && "invalid Attribute doesn't refer to any context");
480   FoldingSetNodeID ID;
481   pImpl->Profile(ID);
482   void *Unused;
483   return C.pImpl->AttrsSet.FindNodeOrInsertPos(ID, Unused) == pImpl;
484 }
485 
486 bool Attribute::operator<(Attribute A) const {
487   if (!pImpl && !A.pImpl) return false;
488   if (!pImpl) return true;
489   if (!A.pImpl) return false;
490   return *pImpl < *A.pImpl;
491 }
492 
493 void Attribute::Profile(FoldingSetNodeID &ID) const {
494   ID.AddPointer(pImpl);
495 }
496 
497 enum AttributeProperty {
498   FnAttr = (1 << 0),
499   ParamAttr = (1 << 1),
500   RetAttr = (1 << 2),
501 };
502 
503 #define GET_ATTR_PROP_TABLE
504 #include "llvm/IR/Attributes.inc"
505 
506 static bool hasAttributeProperty(Attribute::AttrKind Kind,
507                                  AttributeProperty Prop) {
508   unsigned Index = Kind - 1;
509   assert(Index < sizeof(AttrPropTable) / sizeof(AttrPropTable[0]) &&
510          "Invalid attribute kind");
511   return AttrPropTable[Index] & Prop;
512 }
513 
514 bool Attribute::canUseAsFnAttr(AttrKind Kind) {
515   return hasAttributeProperty(Kind, AttributeProperty::FnAttr);
516 }
517 
518 bool Attribute::canUseAsParamAttr(AttrKind Kind) {
519   return hasAttributeProperty(Kind, AttributeProperty::ParamAttr);
520 }
521 
522 bool Attribute::canUseAsRetAttr(AttrKind Kind) {
523   return hasAttributeProperty(Kind, AttributeProperty::RetAttr);
524 }
525 
526 //===----------------------------------------------------------------------===//
527 // AttributeImpl Definition
528 //===----------------------------------------------------------------------===//
529 
530 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
531   if (isStringAttribute()) return false;
532   return getKindAsEnum() == A;
533 }
534 
535 bool AttributeImpl::hasAttribute(StringRef Kind) const {
536   if (!isStringAttribute()) return false;
537   return getKindAsString() == Kind;
538 }
539 
540 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
541   assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute());
542   return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
543 }
544 
545 uint64_t AttributeImpl::getValueAsInt() const {
546   assert(isIntAttribute());
547   return static_cast<const IntAttributeImpl *>(this)->getValue();
548 }
549 
550 bool AttributeImpl::getValueAsBool() const {
551   assert(getValueAsString().empty() || getValueAsString() == "false" || getValueAsString() == "true");
552   return getValueAsString() == "true";
553 }
554 
555 StringRef AttributeImpl::getKindAsString() const {
556   assert(isStringAttribute());
557   return static_cast<const StringAttributeImpl *>(this)->getStringKind();
558 }
559 
560 StringRef AttributeImpl::getValueAsString() const {
561   assert(isStringAttribute());
562   return static_cast<const StringAttributeImpl *>(this)->getStringValue();
563 }
564 
565 Type *AttributeImpl::getValueAsType() const {
566   assert(isTypeAttribute());
567   return static_cast<const TypeAttributeImpl *>(this)->getTypeValue();
568 }
569 
570 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
571   if (this == &AI)
572     return false;
573 
574   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
575   // relative to their enum value) and then strings.
576   if (!isStringAttribute()) {
577     if (AI.isStringAttribute())
578       return true;
579     if (getKindAsEnum() != AI.getKindAsEnum())
580       return getKindAsEnum() < AI.getKindAsEnum();
581     assert(!AI.isEnumAttribute() && "Non-unique attribute");
582     assert(!AI.isTypeAttribute() && "Comparison of types would be unstable");
583     // TODO: Is this actually needed?
584     assert(AI.isIntAttribute() && "Only possibility left");
585     return getValueAsInt() < AI.getValueAsInt();
586   }
587 
588   if (!AI.isStringAttribute())
589     return false;
590   if (getKindAsString() == AI.getKindAsString())
591     return getValueAsString() < AI.getValueAsString();
592   return getKindAsString() < AI.getKindAsString();
593 }
594 
595 //===----------------------------------------------------------------------===//
596 // AttributeSet Definition
597 //===----------------------------------------------------------------------===//
598 
599 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) {
600   return AttributeSet(AttributeSetNode::get(C, B));
601 }
602 
603 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) {
604   return AttributeSet(AttributeSetNode::get(C, Attrs));
605 }
606 
607 AttributeSet AttributeSet::addAttribute(LLVMContext &C,
608                                         Attribute::AttrKind Kind) const {
609   if (hasAttribute(Kind)) return *this;
610   AttrBuilder B;
611   B.addAttribute(Kind);
612   return addAttributes(C, AttributeSet::get(C, B));
613 }
614 
615 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind,
616                                         StringRef Value) const {
617   AttrBuilder B;
618   B.addAttribute(Kind, Value);
619   return addAttributes(C, AttributeSet::get(C, B));
620 }
621 
622 AttributeSet AttributeSet::addAttributes(LLVMContext &C,
623                                          const AttributeSet AS) const {
624   if (!hasAttributes())
625     return AS;
626 
627   if (!AS.hasAttributes())
628     return *this;
629 
630   AttrBuilder B(AS);
631   for (const auto &I : *this)
632     B.addAttribute(I);
633 
634  return get(C, B);
635 }
636 
637 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
638                                              Attribute::AttrKind Kind) const {
639   if (!hasAttribute(Kind)) return *this;
640   AttrBuilder B(*this);
641   B.removeAttribute(Kind);
642   return get(C, B);
643 }
644 
645 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
646                                              StringRef Kind) const {
647   if (!hasAttribute(Kind)) return *this;
648   AttrBuilder B(*this);
649   B.removeAttribute(Kind);
650   return get(C, B);
651 }
652 
653 AttributeSet AttributeSet::removeAttributes(LLVMContext &C,
654                                             const AttrBuilder &Attrs) const {
655   AttrBuilder B(*this);
656   // If there is nothing to remove, directly return the original set.
657   if (!B.overlaps(Attrs))
658     return *this;
659 
660   B.remove(Attrs);
661   return get(C, B);
662 }
663 
664 unsigned AttributeSet::getNumAttributes() const {
665   return SetNode ? SetNode->getNumAttributes() : 0;
666 }
667 
668 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const {
669   return SetNode ? SetNode->hasAttribute(Kind) : false;
670 }
671 
672 bool AttributeSet::hasAttribute(StringRef Kind) const {
673   return SetNode ? SetNode->hasAttribute(Kind) : false;
674 }
675 
676 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const {
677   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
678 }
679 
680 Attribute AttributeSet::getAttribute(StringRef Kind) const {
681   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
682 }
683 
684 MaybeAlign AttributeSet::getAlignment() const {
685   return SetNode ? SetNode->getAlignment() : None;
686 }
687 
688 MaybeAlign AttributeSet::getStackAlignment() const {
689   return SetNode ? SetNode->getStackAlignment() : None;
690 }
691 
692 uint64_t AttributeSet::getDereferenceableBytes() const {
693   return SetNode ? SetNode->getDereferenceableBytes() : 0;
694 }
695 
696 uint64_t AttributeSet::getDereferenceableOrNullBytes() const {
697   return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0;
698 }
699 
700 Type *AttributeSet::getByRefType() const {
701   return SetNode ? SetNode->getAttributeType(Attribute::ByRef) : nullptr;
702 }
703 
704 Type *AttributeSet::getByValType() const {
705   return SetNode ? SetNode->getAttributeType(Attribute::ByVal) : nullptr;
706 }
707 
708 Type *AttributeSet::getStructRetType() const {
709   return SetNode ? SetNode->getAttributeType(Attribute::StructRet) : nullptr;
710 }
711 
712 Type *AttributeSet::getPreallocatedType() const {
713   return SetNode ? SetNode->getAttributeType(Attribute::Preallocated) : nullptr;
714 }
715 
716 Type *AttributeSet::getInAllocaType() const {
717   return SetNode ? SetNode->getAttributeType(Attribute::InAlloca) : nullptr;
718 }
719 
720 Type *AttributeSet::getElementType() const {
721   return SetNode ? SetNode->getAttributeType(Attribute::ElementType) : nullptr;
722 }
723 
724 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const {
725   return SetNode ? SetNode->getAllocSizeArgs()
726                  : std::pair<unsigned, Optional<unsigned>>(0, 0);
727 }
728 
729 unsigned AttributeSet::getVScaleRangeMin() const {
730   return SetNode ? SetNode->getVScaleRangeMin() : 1;
731 }
732 
733 Optional<unsigned> AttributeSet::getVScaleRangeMax() const {
734   return SetNode ? SetNode->getVScaleRangeMax() : None;
735 }
736 
737 std::string AttributeSet::getAsString(bool InAttrGrp) const {
738   return SetNode ? SetNode->getAsString(InAttrGrp) : "";
739 }
740 
741 bool AttributeSet::hasParentContext(LLVMContext &C) const {
742   assert(hasAttributes() && "empty AttributeSet doesn't refer to any context");
743   FoldingSetNodeID ID;
744   SetNode->Profile(ID);
745   void *Unused;
746   return C.pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, Unused) == SetNode;
747 }
748 
749 AttributeSet::iterator AttributeSet::begin() const {
750   return SetNode ? SetNode->begin() : nullptr;
751 }
752 
753 AttributeSet::iterator AttributeSet::end() const {
754   return SetNode ? SetNode->end() : nullptr;
755 }
756 
757 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
758 LLVM_DUMP_METHOD void AttributeSet::dump() const {
759   dbgs() << "AS =\n";
760     dbgs() << "  { ";
761     dbgs() << getAsString(true) << " }\n";
762 }
763 #endif
764 
765 //===----------------------------------------------------------------------===//
766 // AttributeSetNode Definition
767 //===----------------------------------------------------------------------===//
768 
769 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs)
770     : NumAttrs(Attrs.size()) {
771   // There's memory after the node where we can store the entries in.
772   llvm::copy(Attrs, getTrailingObjects<Attribute>());
773 
774   for (const auto &I : *this) {
775     if (I.isStringAttribute())
776       StringAttrs.insert({ I.getKindAsString(), I });
777     else
778       AvailableAttrs.addAttribute(I.getKindAsEnum());
779   }
780 }
781 
782 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
783                                         ArrayRef<Attribute> Attrs) {
784   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
785   llvm::sort(SortedAttrs);
786   return getSorted(C, SortedAttrs);
787 }
788 
789 AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C,
790                                               ArrayRef<Attribute> SortedAttrs) {
791   if (SortedAttrs.empty())
792     return nullptr;
793 
794   // Build a key to look up the existing attributes.
795   LLVMContextImpl *pImpl = C.pImpl;
796   FoldingSetNodeID ID;
797 
798   assert(llvm::is_sorted(SortedAttrs) && "Expected sorted attributes!");
799   for (const auto &Attr : SortedAttrs)
800     Attr.Profile(ID);
801 
802   void *InsertPoint;
803   AttributeSetNode *PA =
804     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
805 
806   // If we didn't find any existing attributes of the same shape then create a
807   // new one and insert it.
808   if (!PA) {
809     // Coallocate entries after the AttributeSetNode itself.
810     void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size()));
811     PA = new (Mem) AttributeSetNode(SortedAttrs);
812     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
813   }
814 
815   // Return the AttributeSetNode that we found or created.
816   return PA;
817 }
818 
819 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) {
820   // Add target-independent attributes.
821   SmallVector<Attribute, 8> Attrs;
822   for (Attribute::AttrKind Kind = Attribute::None;
823        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
824     if (!B.contains(Kind))
825       continue;
826 
827     Attribute Attr;
828     if (Attribute::isTypeAttrKind(Kind))
829       Attr = Attribute::get(C, Kind, B.getTypeAttr(Kind));
830     else if (Attribute::isIntAttrKind(Kind))
831       Attr = Attribute::get(C, Kind, B.getRawIntAttr(Kind));
832     else
833       Attr = Attribute::get(C, Kind);
834     Attrs.push_back(Attr);
835   }
836 
837   // Add target-dependent (string) attributes.
838   for (const auto &TDA : B.td_attrs())
839     Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second));
840 
841   return getSorted(C, Attrs);
842 }
843 
844 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
845   return StringAttrs.count(Kind);
846 }
847 
848 Optional<Attribute>
849 AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const {
850   // Do a quick presence check.
851   if (!hasAttribute(Kind))
852     return None;
853 
854   // Attributes in a set are sorted by enum value, followed by string
855   // attributes. Binary search the one we want.
856   const Attribute *I =
857       std::lower_bound(begin(), end() - StringAttrs.size(), Kind,
858                        [](Attribute A, Attribute::AttrKind Kind) {
859                          return A.getKindAsEnum() < Kind;
860                        });
861   assert(I != end() && I->hasAttribute(Kind) && "Presence check failed?");
862   return *I;
863 }
864 
865 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
866   if (auto A = findEnumAttribute(Kind))
867     return *A;
868   return {};
869 }
870 
871 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
872   return StringAttrs.lookup(Kind);
873 }
874 
875 MaybeAlign AttributeSetNode::getAlignment() const {
876   if (auto A = findEnumAttribute(Attribute::Alignment))
877     return A->getAlignment();
878   return None;
879 }
880 
881 MaybeAlign AttributeSetNode::getStackAlignment() const {
882   if (auto A = findEnumAttribute(Attribute::StackAlignment))
883     return A->getStackAlignment();
884   return None;
885 }
886 
887 Type *AttributeSetNode::getAttributeType(Attribute::AttrKind Kind) const {
888   if (auto A = findEnumAttribute(Kind))
889     return A->getValueAsType();
890   return nullptr;
891 }
892 
893 uint64_t AttributeSetNode::getDereferenceableBytes() const {
894   if (auto A = findEnumAttribute(Attribute::Dereferenceable))
895     return A->getDereferenceableBytes();
896   return 0;
897 }
898 
899 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
900   if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull))
901     return A->getDereferenceableOrNullBytes();
902   return 0;
903 }
904 
905 std::pair<unsigned, Optional<unsigned>>
906 AttributeSetNode::getAllocSizeArgs() const {
907   if (auto A = findEnumAttribute(Attribute::AllocSize))
908     return A->getAllocSizeArgs();
909   return std::make_pair(0, 0);
910 }
911 
912 unsigned AttributeSetNode::getVScaleRangeMin() const {
913   if (auto A = findEnumAttribute(Attribute::VScaleRange))
914     return A->getVScaleRangeMin();
915   return 1;
916 }
917 
918 Optional<unsigned> AttributeSetNode::getVScaleRangeMax() const {
919   if (auto A = findEnumAttribute(Attribute::VScaleRange))
920     return A->getVScaleRangeMax();
921   return None;
922 }
923 
924 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
925   std::string Str;
926   for (iterator I = begin(), E = end(); I != E; ++I) {
927     if (I != begin())
928       Str += ' ';
929     Str += I->getAsString(InAttrGrp);
930   }
931   return Str;
932 }
933 
934 //===----------------------------------------------------------------------===//
935 // AttributeListImpl Definition
936 //===----------------------------------------------------------------------===//
937 
938 /// Map from AttributeList index to the internal array index. Adding one happens
939 /// to work, because -1 wraps around to 0.
940 static unsigned attrIdxToArrayIdx(unsigned Index) {
941   return Index + 1;
942 }
943 
944 AttributeListImpl::AttributeListImpl(ArrayRef<AttributeSet> Sets)
945     : NumAttrSets(Sets.size()) {
946   assert(!Sets.empty() && "pointless AttributeListImpl");
947 
948   // There's memory after the node where we can store the entries in.
949   llvm::copy(Sets, getTrailingObjects<AttributeSet>());
950 
951   // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs
952   // summary bitsets.
953   for (const auto &I : Sets[attrIdxToArrayIdx(AttributeList::FunctionIndex)])
954     if (!I.isStringAttribute())
955       AvailableFunctionAttrs.addAttribute(I.getKindAsEnum());
956 
957   for (const auto &Set : Sets)
958     for (const auto &I : Set)
959       if (!I.isStringAttribute())
960         AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum());
961 }
962 
963 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
964   Profile(ID, makeArrayRef(begin(), end()));
965 }
966 
967 void AttributeListImpl::Profile(FoldingSetNodeID &ID,
968                                 ArrayRef<AttributeSet> Sets) {
969   for (const auto &Set : Sets)
970     ID.AddPointer(Set.SetNode);
971 }
972 
973 bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind,
974                                         unsigned *Index) const {
975   if (!AvailableSomewhereAttrs.hasAttribute(Kind))
976     return false;
977 
978   if (Index) {
979     for (unsigned I = 0, E = NumAttrSets; I != E; ++I) {
980       if (begin()[I].hasAttribute(Kind)) {
981         *Index = I - 1;
982         break;
983       }
984     }
985   }
986 
987   return true;
988 }
989 
990 
991 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
992 LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
993   AttributeList(const_cast<AttributeListImpl *>(this)).dump();
994 }
995 #endif
996 
997 //===----------------------------------------------------------------------===//
998 // AttributeList Construction and Mutation Methods
999 //===----------------------------------------------------------------------===//
1000 
1001 AttributeList AttributeList::getImpl(LLVMContext &C,
1002                                      ArrayRef<AttributeSet> AttrSets) {
1003   assert(!AttrSets.empty() && "pointless AttributeListImpl");
1004 
1005   LLVMContextImpl *pImpl = C.pImpl;
1006   FoldingSetNodeID ID;
1007   AttributeListImpl::Profile(ID, AttrSets);
1008 
1009   void *InsertPoint;
1010   AttributeListImpl *PA =
1011       pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
1012 
1013   // If we didn't find any existing attributes of the same shape then
1014   // create a new one and insert it.
1015   if (!PA) {
1016     // Coallocate entries after the AttributeListImpl itself.
1017     void *Mem = pImpl->Alloc.Allocate(
1018         AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()),
1019         alignof(AttributeListImpl));
1020     PA = new (Mem) AttributeListImpl(AttrSets);
1021     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
1022   }
1023 
1024   // Return the AttributesList that we found or created.
1025   return AttributeList(PA);
1026 }
1027 
1028 AttributeList
1029 AttributeList::get(LLVMContext &C,
1030                    ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
1031   // If there are no attributes then return a null AttributesList pointer.
1032   if (Attrs.empty())
1033     return {};
1034 
1035   assert(llvm::is_sorted(Attrs,
1036                          [](const std::pair<unsigned, Attribute> &LHS,
1037                             const std::pair<unsigned, Attribute> &RHS) {
1038                            return LHS.first < RHS.first;
1039                          }) &&
1040          "Misordered Attributes list!");
1041   assert(llvm::all_of(Attrs,
1042                       [](const std::pair<unsigned, Attribute> &Pair) {
1043                         return Pair.second.isValid();
1044                       }) &&
1045          "Pointless attribute!");
1046 
1047   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
1048   // list.
1049   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
1050   for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
1051          E = Attrs.end(); I != E; ) {
1052     unsigned Index = I->first;
1053     SmallVector<Attribute, 4> AttrVec;
1054     while (I != E && I->first == Index) {
1055       AttrVec.push_back(I->second);
1056       ++I;
1057     }
1058 
1059     AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
1060   }
1061 
1062   return get(C, AttrPairVec);
1063 }
1064 
1065 AttributeList
1066 AttributeList::get(LLVMContext &C,
1067                    ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
1068   // If there are no attributes then return a null AttributesList pointer.
1069   if (Attrs.empty())
1070     return {};
1071 
1072   assert(llvm::is_sorted(Attrs,
1073                          [](const std::pair<unsigned, AttributeSet> &LHS,
1074                             const std::pair<unsigned, AttributeSet> &RHS) {
1075                            return LHS.first < RHS.first;
1076                          }) &&
1077          "Misordered Attributes list!");
1078   assert(llvm::none_of(Attrs,
1079                        [](const std::pair<unsigned, AttributeSet> &Pair) {
1080                          return !Pair.second.hasAttributes();
1081                        }) &&
1082          "Pointless attribute!");
1083 
1084   unsigned MaxIndex = Attrs.back().first;
1085   // If the MaxIndex is FunctionIndex and there are other indices in front
1086   // of it, we need to use the largest of those to get the right size.
1087   if (MaxIndex == FunctionIndex && Attrs.size() > 1)
1088     MaxIndex = Attrs[Attrs.size() - 2].first;
1089 
1090   SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1);
1091   for (const auto &Pair : Attrs)
1092     AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second;
1093 
1094   return getImpl(C, AttrVec);
1095 }
1096 
1097 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs,
1098                                  AttributeSet RetAttrs,
1099                                  ArrayRef<AttributeSet> ArgAttrs) {
1100   // Scan from the end to find the last argument with attributes.  Most
1101   // arguments don't have attributes, so it's nice if we can have fewer unique
1102   // AttributeListImpls by dropping empty attribute sets at the end of the list.
1103   unsigned NumSets = 0;
1104   for (size_t I = ArgAttrs.size(); I != 0; --I) {
1105     if (ArgAttrs[I - 1].hasAttributes()) {
1106       NumSets = I + 2;
1107       break;
1108     }
1109   }
1110   if (NumSets == 0) {
1111     // Check function and return attributes if we didn't have argument
1112     // attributes.
1113     if (RetAttrs.hasAttributes())
1114       NumSets = 2;
1115     else if (FnAttrs.hasAttributes())
1116       NumSets = 1;
1117   }
1118 
1119   // If all attribute sets were empty, we can use the empty attribute list.
1120   if (NumSets == 0)
1121     return {};
1122 
1123   SmallVector<AttributeSet, 8> AttrSets;
1124   AttrSets.reserve(NumSets);
1125   // If we have any attributes, we always have function attributes.
1126   AttrSets.push_back(FnAttrs);
1127   if (NumSets > 1)
1128     AttrSets.push_back(RetAttrs);
1129   if (NumSets > 2) {
1130     // Drop the empty argument attribute sets at the end.
1131     ArgAttrs = ArgAttrs.take_front(NumSets - 2);
1132     llvm::append_range(AttrSets, ArgAttrs);
1133   }
1134 
1135   return getImpl(C, AttrSets);
1136 }
1137 
1138 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1139                                  AttributeSet Attrs) {
1140   if (!Attrs.hasAttributes())
1141     return {};
1142   Index = attrIdxToArrayIdx(Index);
1143   SmallVector<AttributeSet, 8> AttrSets(Index + 1);
1144   AttrSets[Index] = Attrs;
1145   return getImpl(C, AttrSets);
1146 }
1147 
1148 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1149                                  const AttrBuilder &B) {
1150   return get(C, Index, AttributeSet::get(C, B));
1151 }
1152 
1153 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1154                                  ArrayRef<Attribute::AttrKind> Kinds) {
1155   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1156   for (const auto K : Kinds)
1157     Attrs.emplace_back(Index, Attribute::get(C, K));
1158   return get(C, Attrs);
1159 }
1160 
1161 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1162                                  ArrayRef<Attribute::AttrKind> Kinds,
1163                                  ArrayRef<uint64_t> Values) {
1164   assert(Kinds.size() == Values.size() && "Mismatched attribute values.");
1165   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1166   auto VI = Values.begin();
1167   for (const auto K : Kinds)
1168     Attrs.emplace_back(Index, Attribute::get(C, K, *VI++));
1169   return get(C, Attrs);
1170 }
1171 
1172 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1173                                  ArrayRef<StringRef> Kinds) {
1174   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1175   for (const auto &K : Kinds)
1176     Attrs.emplace_back(Index, Attribute::get(C, K));
1177   return get(C, Attrs);
1178 }
1179 
1180 AttributeList AttributeList::get(LLVMContext &C,
1181                                  ArrayRef<AttributeList> Attrs) {
1182   if (Attrs.empty())
1183     return {};
1184   if (Attrs.size() == 1)
1185     return Attrs[0];
1186 
1187   unsigned MaxSize = 0;
1188   for (const auto &List : Attrs)
1189     MaxSize = std::max(MaxSize, List.getNumAttrSets());
1190 
1191   // If every list was empty, there is no point in merging the lists.
1192   if (MaxSize == 0)
1193     return {};
1194 
1195   SmallVector<AttributeSet, 8> NewAttrSets(MaxSize);
1196   for (unsigned I = 0; I < MaxSize; ++I) {
1197     AttrBuilder CurBuilder;
1198     for (const auto &List : Attrs)
1199       CurBuilder.merge(List.getAttributes(I - 1));
1200     NewAttrSets[I] = AttributeSet::get(C, CurBuilder);
1201   }
1202 
1203   return getImpl(C, NewAttrSets);
1204 }
1205 
1206 AttributeList
1207 AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
1208                                    Attribute::AttrKind Kind) const {
1209   if (hasAttributeAtIndex(Index, Kind))
1210     return *this;
1211   AttributeSet Attrs = getAttributes(Index);
1212   // TODO: Insert at correct position and avoid sort.
1213   SmallVector<Attribute, 8> NewAttrs(Attrs.begin(), Attrs.end());
1214   NewAttrs.push_back(Attribute::get(C, Kind));
1215   return setAttributesAtIndex(C, Index, AttributeSet::get(C, NewAttrs));
1216 }
1217 
1218 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
1219                                                  StringRef Kind,
1220                                                  StringRef Value) const {
1221   AttrBuilder B;
1222   B.addAttribute(Kind, Value);
1223   return addAttributesAtIndex(C, Index, B);
1224 }
1225 
1226 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index,
1227                                                  Attribute A) const {
1228   AttrBuilder B;
1229   B.addAttribute(A);
1230   return addAttributesAtIndex(C, Index, B);
1231 }
1232 
1233 AttributeList AttributeList::setAttributesAtIndex(LLVMContext &C,
1234                                                   unsigned Index,
1235                                                   AttributeSet Attrs) const {
1236   Index = attrIdxToArrayIdx(Index);
1237   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1238   if (Index >= AttrSets.size())
1239     AttrSets.resize(Index + 1);
1240   AttrSets[Index] = Attrs;
1241   return AttributeList::getImpl(C, AttrSets);
1242 }
1243 
1244 AttributeList AttributeList::addAttributesAtIndex(LLVMContext &C,
1245                                                   unsigned Index,
1246                                                   const AttrBuilder &B) const {
1247   if (!B.hasAttributes())
1248     return *this;
1249 
1250   if (!pImpl)
1251     return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}});
1252 
1253 #ifndef NDEBUG
1254   // FIXME it is not obvious how this should work for alignment. For now, say
1255   // we can't change a known alignment.
1256   const MaybeAlign OldAlign = getAttributes(Index).getAlignment();
1257   const MaybeAlign NewAlign = B.getAlignment();
1258   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
1259          "Attempt to change alignment!");
1260 #endif
1261 
1262   AttrBuilder Merged(getAttributes(Index));
1263   Merged.merge(B);
1264   return setAttributesAtIndex(C, Index, AttributeSet::get(C, Merged));
1265 }
1266 
1267 AttributeList AttributeList::addParamAttribute(LLVMContext &C,
1268                                                ArrayRef<unsigned> ArgNos,
1269                                                Attribute A) const {
1270   assert(llvm::is_sorted(ArgNos));
1271 
1272   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1273   unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex);
1274   if (MaxIndex >= AttrSets.size())
1275     AttrSets.resize(MaxIndex + 1);
1276 
1277   for (unsigned ArgNo : ArgNos) {
1278     unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex);
1279     AttrBuilder B(AttrSets[Index]);
1280     B.addAttribute(A);
1281     AttrSets[Index] = AttributeSet::get(C, B);
1282   }
1283 
1284   return getImpl(C, AttrSets);
1285 }
1286 
1287 AttributeList
1288 AttributeList::removeAttributeAtIndex(LLVMContext &C, unsigned Index,
1289                                       Attribute::AttrKind Kind) const {
1290   if (!hasAttributeAtIndex(Index, Kind))
1291     return *this;
1292 
1293   Index = attrIdxToArrayIdx(Index);
1294   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1295   assert(Index < AttrSets.size());
1296 
1297   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1298 
1299   return getImpl(C, AttrSets);
1300 }
1301 
1302 AttributeList AttributeList::removeAttributeAtIndex(LLVMContext &C,
1303                                                     unsigned Index,
1304                                                     StringRef Kind) const {
1305   if (!hasAttributeAtIndex(Index, Kind))
1306     return *this;
1307 
1308   Index = attrIdxToArrayIdx(Index);
1309   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1310   assert(Index < AttrSets.size());
1311 
1312   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1313 
1314   return getImpl(C, AttrSets);
1315 }
1316 
1317 AttributeList
1318 AttributeList::removeAttributesAtIndex(LLVMContext &C, unsigned Index,
1319                                        const AttrBuilder &AttrsToRemove) const {
1320   AttributeSet Attrs = getAttributes(Index);
1321   AttributeSet NewAttrs = Attrs.removeAttributes(C, AttrsToRemove);
1322   // If nothing was removed, return the original list.
1323   if (Attrs == NewAttrs)
1324     return *this;
1325   return setAttributesAtIndex(C, Index, NewAttrs);
1326 }
1327 
1328 AttributeList
1329 AttributeList::removeAttributesAtIndex(LLVMContext &C,
1330                                        unsigned WithoutIndex) const {
1331   if (!pImpl)
1332     return {};
1333   WithoutIndex = attrIdxToArrayIdx(WithoutIndex);
1334   if (WithoutIndex >= getNumAttrSets())
1335     return *this;
1336   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1337   AttrSets[WithoutIndex] = AttributeSet();
1338   return getImpl(C, AttrSets);
1339 }
1340 
1341 AttributeList AttributeList::addDereferenceableRetAttr(LLVMContext &C,
1342                                                        uint64_t Bytes) const {
1343   AttrBuilder B;
1344   B.addDereferenceableAttr(Bytes);
1345   return addRetAttributes(C, B);
1346 }
1347 
1348 AttributeList AttributeList::addDereferenceableParamAttr(LLVMContext &C,
1349                                                          unsigned Index,
1350                                                          uint64_t Bytes) const {
1351   AttrBuilder B;
1352   B.addDereferenceableAttr(Bytes);
1353   return addParamAttributes(C, Index, B);
1354 }
1355 
1356 AttributeList
1357 AttributeList::addDereferenceableOrNullParamAttr(LLVMContext &C, unsigned Index,
1358                                                  uint64_t Bytes) const {
1359   AttrBuilder B;
1360   B.addDereferenceableOrNullAttr(Bytes);
1361   return addParamAttributes(C, Index, B);
1362 }
1363 
1364 AttributeList
1365 AttributeList::addAllocSizeParamAttr(LLVMContext &C, unsigned Index,
1366                                      unsigned ElemSizeArg,
1367                                      const Optional<unsigned> &NumElemsArg) {
1368   AttrBuilder B;
1369   B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1370   return addParamAttributes(C, Index, B);
1371 }
1372 
1373 //===----------------------------------------------------------------------===//
1374 // AttributeList Accessor Methods
1375 //===----------------------------------------------------------------------===//
1376 
1377 AttributeSet AttributeList::getParamAttrs(unsigned ArgNo) const {
1378   return getAttributes(ArgNo + FirstArgIndex);
1379 }
1380 
1381 AttributeSet AttributeList::getRetAttrs() const {
1382   return getAttributes(ReturnIndex);
1383 }
1384 
1385 AttributeSet AttributeList::getFnAttrs() const {
1386   return getAttributes(FunctionIndex);
1387 }
1388 
1389 bool AttributeList::hasAttributeAtIndex(unsigned Index,
1390                                         Attribute::AttrKind Kind) const {
1391   return getAttributes(Index).hasAttribute(Kind);
1392 }
1393 
1394 bool AttributeList::hasAttributeAtIndex(unsigned Index, StringRef Kind) const {
1395   return getAttributes(Index).hasAttribute(Kind);
1396 }
1397 
1398 bool AttributeList::hasAttributesAtIndex(unsigned Index) const {
1399   return getAttributes(Index).hasAttributes();
1400 }
1401 
1402 bool AttributeList::hasFnAttr(Attribute::AttrKind Kind) const {
1403   return pImpl && pImpl->hasFnAttribute(Kind);
1404 }
1405 
1406 bool AttributeList::hasFnAttr(StringRef Kind) const {
1407   return hasAttributeAtIndex(AttributeList::FunctionIndex, Kind);
1408 }
1409 
1410 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
1411                                      unsigned *Index) const {
1412   return pImpl && pImpl->hasAttrSomewhere(Attr, Index);
1413 }
1414 
1415 Attribute AttributeList::getAttributeAtIndex(unsigned Index,
1416                                              Attribute::AttrKind Kind) const {
1417   return getAttributes(Index).getAttribute(Kind);
1418 }
1419 
1420 Attribute AttributeList::getAttributeAtIndex(unsigned Index,
1421                                              StringRef Kind) const {
1422   return getAttributes(Index).getAttribute(Kind);
1423 }
1424 
1425 MaybeAlign AttributeList::getRetAlignment() const {
1426   return getAttributes(ReturnIndex).getAlignment();
1427 }
1428 
1429 MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const {
1430   return getAttributes(ArgNo + FirstArgIndex).getAlignment();
1431 }
1432 
1433 MaybeAlign AttributeList::getParamStackAlignment(unsigned ArgNo) const {
1434   return getAttributes(ArgNo + FirstArgIndex).getStackAlignment();
1435 }
1436 
1437 Type *AttributeList::getParamByValType(unsigned Index) const {
1438   return getAttributes(Index+FirstArgIndex).getByValType();
1439 }
1440 
1441 Type *AttributeList::getParamStructRetType(unsigned Index) const {
1442   return getAttributes(Index + FirstArgIndex).getStructRetType();
1443 }
1444 
1445 Type *AttributeList::getParamByRefType(unsigned Index) const {
1446   return getAttributes(Index + FirstArgIndex).getByRefType();
1447 }
1448 
1449 Type *AttributeList::getParamPreallocatedType(unsigned Index) const {
1450   return getAttributes(Index + FirstArgIndex).getPreallocatedType();
1451 }
1452 
1453 Type *AttributeList::getParamInAllocaType(unsigned Index) const {
1454   return getAttributes(Index + FirstArgIndex).getInAllocaType();
1455 }
1456 
1457 Type *AttributeList::getParamElementType(unsigned Index) const {
1458   return getAttributes(Index + FirstArgIndex).getElementType();
1459 }
1460 
1461 MaybeAlign AttributeList::getFnStackAlignment() const {
1462   return getFnAttrs().getStackAlignment();
1463 }
1464 
1465 MaybeAlign AttributeList::getRetStackAlignment() const {
1466   return getRetAttrs().getStackAlignment();
1467 }
1468 
1469 uint64_t AttributeList::getRetDereferenceableBytes() const {
1470   return getRetAttrs().getDereferenceableBytes();
1471 }
1472 
1473 uint64_t AttributeList::getParamDereferenceableBytes(unsigned Index) const {
1474   return getParamAttrs(Index).getDereferenceableBytes();
1475 }
1476 
1477 uint64_t AttributeList::getRetDereferenceableOrNullBytes() const {
1478   return getRetAttrs().getDereferenceableOrNullBytes();
1479 }
1480 
1481 uint64_t
1482 AttributeList::getParamDereferenceableOrNullBytes(unsigned Index) const {
1483   return getParamAttrs(Index).getDereferenceableOrNullBytes();
1484 }
1485 
1486 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
1487   return getAttributes(Index).getAsString(InAttrGrp);
1488 }
1489 
1490 AttributeSet AttributeList::getAttributes(unsigned Index) const {
1491   Index = attrIdxToArrayIdx(Index);
1492   if (!pImpl || Index >= getNumAttrSets())
1493     return {};
1494   return pImpl->begin()[Index];
1495 }
1496 
1497 bool AttributeList::hasParentContext(LLVMContext &C) const {
1498   assert(!isEmpty() && "an empty attribute list has no parent context");
1499   FoldingSetNodeID ID;
1500   pImpl->Profile(ID);
1501   void *Unused;
1502   return C.pImpl->AttrsLists.FindNodeOrInsertPos(ID, Unused) == pImpl;
1503 }
1504 
1505 AttributeList::iterator AttributeList::begin() const {
1506   return pImpl ? pImpl->begin() : nullptr;
1507 }
1508 
1509 AttributeList::iterator AttributeList::end() const {
1510   return pImpl ? pImpl->end() : nullptr;
1511 }
1512 
1513 //===----------------------------------------------------------------------===//
1514 // AttributeList Introspection Methods
1515 //===----------------------------------------------------------------------===//
1516 
1517 unsigned AttributeList::getNumAttrSets() const {
1518   return pImpl ? pImpl->NumAttrSets : 0;
1519 }
1520 
1521 void AttributeList::print(raw_ostream &O) const {
1522   O << "AttributeList[\n";
1523 
1524   for (unsigned i : indexes()) {
1525     if (!getAttributes(i).hasAttributes())
1526       continue;
1527     O << "  { ";
1528     switch (i) {
1529     case AttrIndex::ReturnIndex:
1530       O << "return";
1531       break;
1532     case AttrIndex::FunctionIndex:
1533       O << "function";
1534       break;
1535     default:
1536       O << "arg(" << i - AttrIndex::FirstArgIndex << ")";
1537     }
1538     O << " => " << getAsString(i) << " }\n";
1539   }
1540 
1541   O << "]\n";
1542 }
1543 
1544 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1545 LLVM_DUMP_METHOD void AttributeList::dump() const { print(dbgs()); }
1546 #endif
1547 
1548 //===----------------------------------------------------------------------===//
1549 // AttrBuilder Method Implementations
1550 //===----------------------------------------------------------------------===//
1551 
1552 // FIXME: Remove this ctor, use AttributeSet.
1553 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) {
1554   AttributeSet AS = AL.getAttributes(Index);
1555   for (const auto &A : AS)
1556     addAttribute(A);
1557 }
1558 
1559 AttrBuilder::AttrBuilder(AttributeSet AS) {
1560   for (const auto &A : AS)
1561     addAttribute(A);
1562 }
1563 
1564 void AttrBuilder::clear() {
1565   Attrs.reset();
1566   TargetDepAttrs.clear();
1567   IntAttrs = {};
1568   TypeAttrs = {};
1569 }
1570 
1571 Optional<unsigned>
1572 AttrBuilder::kindToIntIndex(Attribute::AttrKind Kind) const {
1573   if (Attribute::isIntAttrKind(Kind))
1574     return Kind - Attribute::FirstIntAttr;
1575   return None;
1576 }
1577 
1578 Optional<unsigned>
1579 AttrBuilder::kindToTypeIndex(Attribute::AttrKind Kind) const {
1580   if (Attribute::isTypeAttrKind(Kind))
1581     return Kind - Attribute::FirstTypeAttr;
1582   return None;
1583 }
1584 
1585 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
1586   if (Attr.isStringAttribute()) {
1587     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
1588     return *this;
1589   }
1590 
1591   Attribute::AttrKind Kind = Attr.getKindAsEnum();
1592   Attrs[Kind] = true;
1593 
1594   if (Optional<unsigned> TypeIndex = kindToTypeIndex(Kind))
1595     TypeAttrs[*TypeIndex] = Attr.getValueAsType();
1596   else if (Optional<unsigned> IntIndex = kindToIntIndex(Kind))
1597     IntAttrs[*IntIndex] = Attr.getValueAsInt();
1598 
1599   return *this;
1600 }
1601 
1602 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
1603   TargetDepAttrs[A] = V;
1604   return *this;
1605 }
1606 
1607 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1608   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1609   Attrs[Val] = false;
1610 
1611   if (Optional<unsigned> TypeIndex = kindToTypeIndex(Val))
1612     TypeAttrs[*TypeIndex] = nullptr;
1613   else if (Optional<unsigned> IntIndex = kindToIntIndex(Val))
1614     IntAttrs[*IntIndex] = 0;
1615 
1616   return *this;
1617 }
1618 
1619 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) {
1620   remove(A.getAttributes(Index));
1621   return *this;
1622 }
1623 
1624 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1625   TargetDepAttrs.erase(A);
1626   return *this;
1627 }
1628 
1629 uint64_t AttrBuilder::getRawIntAttr(Attribute::AttrKind Kind) const {
1630   Optional<unsigned> IntIndex = kindToIntIndex(Kind);
1631   assert(IntIndex && "Not an int attribute");
1632   return IntAttrs[*IntIndex];
1633 }
1634 
1635 AttrBuilder &AttrBuilder::addRawIntAttr(Attribute::AttrKind Kind,
1636                                         uint64_t Value) {
1637   Optional<unsigned> IntIndex = kindToIntIndex(Kind);
1638   assert(IntIndex && "Not an int attribute");
1639   assert(Value && "Value cannot be zero");
1640   Attrs[Kind] = true;
1641   IntAttrs[*IntIndex] = Value;
1642   return *this;
1643 }
1644 
1645 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
1646   return unpackAllocSizeArgs(getRawIntAttr(Attribute::AllocSize));
1647 }
1648 
1649 unsigned AttrBuilder::getVScaleRangeMin() const {
1650   return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).first;
1651 }
1652 
1653 Optional<unsigned> AttrBuilder::getVScaleRangeMax() const {
1654   return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).second;
1655 }
1656 
1657 AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) {
1658   if (!Align)
1659     return *this;
1660 
1661   assert(*Align <= llvm::Value::MaximumAlignment && "Alignment too large.");
1662   return addRawIntAttr(Attribute::Alignment, Align->value());
1663 }
1664 
1665 AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) {
1666   // Default alignment, allow the target to define how to align it.
1667   if (!Align)
1668     return *this;
1669 
1670   assert(*Align <= 0x100 && "Alignment too large.");
1671   return addRawIntAttr(Attribute::StackAlignment, Align->value());
1672 }
1673 
1674 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
1675   if (Bytes == 0) return *this;
1676 
1677   return addRawIntAttr(Attribute::Dereferenceable, Bytes);
1678 }
1679 
1680 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
1681   if (Bytes == 0)
1682     return *this;
1683 
1684   return addRawIntAttr(Attribute::DereferenceableOrNull, Bytes);
1685 }
1686 
1687 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
1688                                            const Optional<unsigned> &NumElems) {
1689   return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
1690 }
1691 
1692 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
1693   // (0, 0) is our "not present" value, so we need to check for it here.
1694   assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
1695   return addRawIntAttr(Attribute::AllocSize, RawArgs);
1696 }
1697 
1698 AttrBuilder &AttrBuilder::addVScaleRangeAttr(unsigned MinValue,
1699                                              Optional<unsigned> MaxValue) {
1700   return addVScaleRangeAttrFromRawRepr(packVScaleRangeArgs(MinValue, MaxValue));
1701 }
1702 
1703 AttrBuilder &AttrBuilder::addVScaleRangeAttrFromRawRepr(uint64_t RawArgs) {
1704   // (0, 0) is not present hence ignore this case
1705   if (RawArgs == 0)
1706     return *this;
1707 
1708   return addRawIntAttr(Attribute::VScaleRange, RawArgs);
1709 }
1710 
1711 Type *AttrBuilder::getTypeAttr(Attribute::AttrKind Kind) const {
1712   Optional<unsigned> TypeIndex = kindToTypeIndex(Kind);
1713   assert(TypeIndex && "Not a type attribute");
1714   return TypeAttrs[*TypeIndex];
1715 }
1716 
1717 AttrBuilder &AttrBuilder::addTypeAttr(Attribute::AttrKind Kind, Type *Ty) {
1718   Optional<unsigned> TypeIndex = kindToTypeIndex(Kind);
1719   assert(TypeIndex && "Not a type attribute");
1720   Attrs[Kind] = true;
1721   TypeAttrs[*TypeIndex] = Ty;
1722   return *this;
1723 }
1724 
1725 AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) {
1726   return addTypeAttr(Attribute::ByVal, Ty);
1727 }
1728 
1729 AttrBuilder &AttrBuilder::addStructRetAttr(Type *Ty) {
1730   return addTypeAttr(Attribute::StructRet, Ty);
1731 }
1732 
1733 AttrBuilder &AttrBuilder::addByRefAttr(Type *Ty) {
1734   return addTypeAttr(Attribute::ByRef, Ty);
1735 }
1736 
1737 AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) {
1738   return addTypeAttr(Attribute::Preallocated, Ty);
1739 }
1740 
1741 AttrBuilder &AttrBuilder::addInAllocaAttr(Type *Ty) {
1742   return addTypeAttr(Attribute::InAlloca, Ty);
1743 }
1744 
1745 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1746   // FIXME: What if both have an int/type attribute, but they don't match?!
1747   for (unsigned Index = 0; Index < Attribute::NumIntAttrKinds; ++Index)
1748     if (!IntAttrs[Index])
1749       IntAttrs[Index] = B.IntAttrs[Index];
1750 
1751   for (unsigned Index = 0; Index < Attribute::NumTypeAttrKinds; ++Index)
1752     if (!TypeAttrs[Index])
1753       TypeAttrs[Index] = B.TypeAttrs[Index];
1754 
1755   Attrs |= B.Attrs;
1756 
1757   for (const auto &I : B.td_attrs())
1758     TargetDepAttrs[I.first] = I.second;
1759 
1760   return *this;
1761 }
1762 
1763 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
1764   // FIXME: What if both have an int/type attribute, but they don't match?!
1765   for (unsigned Index = 0; Index < Attribute::NumIntAttrKinds; ++Index)
1766     if (B.IntAttrs[Index])
1767       IntAttrs[Index] = 0;
1768 
1769   for (unsigned Index = 0; Index < Attribute::NumTypeAttrKinds; ++Index)
1770     if (B.TypeAttrs[Index])
1771       TypeAttrs[Index] = nullptr;
1772 
1773   Attrs &= ~B.Attrs;
1774 
1775   for (const auto &I : B.td_attrs())
1776     TargetDepAttrs.erase(I.first);
1777 
1778   return *this;
1779 }
1780 
1781 bool AttrBuilder::overlaps(const AttrBuilder &B) const {
1782   // First check if any of the target independent attributes overlap.
1783   if ((Attrs & B.Attrs).any())
1784     return true;
1785 
1786   // Then check if any target dependent ones do.
1787   for (const auto &I : td_attrs())
1788     if (B.contains(I.first))
1789       return true;
1790 
1791   return false;
1792 }
1793 
1794 bool AttrBuilder::contains(StringRef A) const {
1795   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1796 }
1797 
1798 bool AttrBuilder::hasAttributes() const {
1799   return !Attrs.none() || !TargetDepAttrs.empty();
1800 }
1801 
1802 bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const {
1803   AttributeSet AS = AL.getAttributes(Index);
1804 
1805   for (const auto &Attr : AS) {
1806     if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1807       if (contains(Attr.getKindAsEnum()))
1808         return true;
1809     } else {
1810       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1811       return contains(Attr.getKindAsString());
1812     }
1813   }
1814 
1815   return false;
1816 }
1817 
1818 bool AttrBuilder::hasAlignmentAttr() const {
1819   return getRawIntAttr(Attribute::Alignment) != 0;
1820 }
1821 
1822 bool AttrBuilder::operator==(const AttrBuilder &B) const {
1823   if (Attrs != B.Attrs)
1824     return false;
1825 
1826   for (const auto &TDA : TargetDepAttrs)
1827     if (B.TargetDepAttrs.find(TDA.first) == B.TargetDepAttrs.end())
1828       return false;
1829 
1830   return IntAttrs == B.IntAttrs && TypeAttrs == B.TypeAttrs;
1831 }
1832 
1833 //===----------------------------------------------------------------------===//
1834 // AttributeFuncs Function Defintions
1835 //===----------------------------------------------------------------------===//
1836 
1837 /// Which attributes cannot be applied to a type.
1838 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) {
1839   AttrBuilder Incompatible;
1840 
1841   if (!Ty->isIntegerTy())
1842     // Attribute that only apply to integers.
1843     Incompatible.addAttribute(Attribute::SExt)
1844       .addAttribute(Attribute::ZExt);
1845 
1846   if (!Ty->isPointerTy())
1847     // Attribute that only apply to pointers.
1848     Incompatible.addAttribute(Attribute::Nest)
1849         .addAttribute(Attribute::NoAlias)
1850         .addAttribute(Attribute::NoCapture)
1851         .addAttribute(Attribute::NonNull)
1852         .addAttribute(Attribute::ReadNone)
1853         .addAttribute(Attribute::ReadOnly)
1854         .addAttribute(Attribute::SwiftError)
1855         .addAlignmentAttr(1)             // the int here is ignored
1856         .addDereferenceableAttr(1)       // the int here is ignored
1857         .addDereferenceableOrNullAttr(1) // the int here is ignored
1858         .addPreallocatedAttr(Ty)
1859         .addInAllocaAttr(Ty)
1860         .addByValAttr(Ty)
1861         .addStructRetAttr(Ty)
1862         .addByRefAttr(Ty)
1863         .addTypeAttr(Attribute::ElementType, Ty);
1864 
1865   // Some attributes can apply to all "values" but there are no `void` values.
1866   if (Ty->isVoidTy())
1867     Incompatible.addAttribute(Attribute::NoUndef);
1868 
1869   return Incompatible;
1870 }
1871 
1872 AttrBuilder AttributeFuncs::getUBImplyingAttributes() {
1873   AttrBuilder B;
1874   B.addAttribute(Attribute::NoUndef);
1875   B.addDereferenceableAttr(1);
1876   B.addDereferenceableOrNullAttr(1);
1877   return B;
1878 }
1879 
1880 template<typename AttrClass>
1881 static bool isEqual(const Function &Caller, const Function &Callee) {
1882   return Caller.getFnAttribute(AttrClass::getKind()) ==
1883          Callee.getFnAttribute(AttrClass::getKind());
1884 }
1885 
1886 /// Compute the logical AND of the attributes of the caller and the
1887 /// callee.
1888 ///
1889 /// This function sets the caller's attribute to false if the callee's attribute
1890 /// is false.
1891 template<typename AttrClass>
1892 static void setAND(Function &Caller, const Function &Callee) {
1893   if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
1894       !AttrClass::isSet(Callee, AttrClass::getKind()))
1895     AttrClass::set(Caller, AttrClass::getKind(), false);
1896 }
1897 
1898 /// Compute the logical OR of the attributes of the caller and the
1899 /// callee.
1900 ///
1901 /// This function sets the caller's attribute to true if the callee's attribute
1902 /// is true.
1903 template<typename AttrClass>
1904 static void setOR(Function &Caller, const Function &Callee) {
1905   if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
1906       AttrClass::isSet(Callee, AttrClass::getKind()))
1907     AttrClass::set(Caller, AttrClass::getKind(), true);
1908 }
1909 
1910 /// If the inlined function had a higher stack protection level than the
1911 /// calling function, then bump up the caller's stack protection level.
1912 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
1913   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
1914   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
1915   // clutter to the IR.
1916   AttrBuilder OldSSPAttr;
1917   OldSSPAttr.addAttribute(Attribute::StackProtect)
1918       .addAttribute(Attribute::StackProtectStrong)
1919       .addAttribute(Attribute::StackProtectReq);
1920 
1921   if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
1922     Caller.removeFnAttrs(OldSSPAttr);
1923     Caller.addFnAttr(Attribute::StackProtectReq);
1924   } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
1925              !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
1926     Caller.removeFnAttrs(OldSSPAttr);
1927     Caller.addFnAttr(Attribute::StackProtectStrong);
1928   } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
1929              !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
1930              !Caller.hasFnAttribute(Attribute::StackProtectStrong))
1931     Caller.addFnAttr(Attribute::StackProtect);
1932 }
1933 
1934 /// If the inlined function required stack probes, then ensure that
1935 /// the calling function has those too.
1936 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) {
1937   if (!Caller.hasFnAttribute("probe-stack") &&
1938       Callee.hasFnAttribute("probe-stack")) {
1939     Caller.addFnAttr(Callee.getFnAttribute("probe-stack"));
1940   }
1941 }
1942 
1943 /// If the inlined function defines the size of guard region
1944 /// on the stack, then ensure that the calling function defines a guard region
1945 /// that is no larger.
1946 static void
1947 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) {
1948   Attribute CalleeAttr = Callee.getFnAttribute("stack-probe-size");
1949   if (CalleeAttr.isValid()) {
1950     Attribute CallerAttr = Caller.getFnAttribute("stack-probe-size");
1951     if (CallerAttr.isValid()) {
1952       uint64_t CallerStackProbeSize, CalleeStackProbeSize;
1953       CallerAttr.getValueAsString().getAsInteger(0, CallerStackProbeSize);
1954       CalleeAttr.getValueAsString().getAsInteger(0, CalleeStackProbeSize);
1955 
1956       if (CallerStackProbeSize > CalleeStackProbeSize) {
1957         Caller.addFnAttr(CalleeAttr);
1958       }
1959     } else {
1960       Caller.addFnAttr(CalleeAttr);
1961     }
1962   }
1963 }
1964 
1965 /// If the inlined function defines a min legal vector width, then ensure
1966 /// the calling function has the same or larger min legal vector width. If the
1967 /// caller has the attribute, but the callee doesn't, we need to remove the
1968 /// attribute from the caller since we can't make any guarantees about the
1969 /// caller's requirements.
1970 /// This function is called after the inlining decision has been made so we have
1971 /// to merge the attribute this way. Heuristics that would use
1972 /// min-legal-vector-width to determine inline compatibility would need to be
1973 /// handled as part of inline cost analysis.
1974 static void
1975 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) {
1976   Attribute CallerAttr = Caller.getFnAttribute("min-legal-vector-width");
1977   if (CallerAttr.isValid()) {
1978     Attribute CalleeAttr = Callee.getFnAttribute("min-legal-vector-width");
1979     if (CalleeAttr.isValid()) {
1980       uint64_t CallerVectorWidth, CalleeVectorWidth;
1981       CallerAttr.getValueAsString().getAsInteger(0, CallerVectorWidth);
1982       CalleeAttr.getValueAsString().getAsInteger(0, CalleeVectorWidth);
1983       if (CallerVectorWidth < CalleeVectorWidth)
1984         Caller.addFnAttr(CalleeAttr);
1985     } else {
1986       // If the callee doesn't have the attribute then we don't know anything
1987       // and must drop the attribute from the caller.
1988       Caller.removeFnAttr("min-legal-vector-width");
1989     }
1990   }
1991 }
1992 
1993 /// If the inlined function has null_pointer_is_valid attribute,
1994 /// set this attribute in the caller post inlining.
1995 static void
1996 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) {
1997   if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) {
1998     Caller.addFnAttr(Attribute::NullPointerIsValid);
1999   }
2000 }
2001 
2002 struct EnumAttr {
2003   static bool isSet(const Function &Fn,
2004                     Attribute::AttrKind Kind) {
2005     return Fn.hasFnAttribute(Kind);
2006   }
2007 
2008   static void set(Function &Fn,
2009                   Attribute::AttrKind Kind, bool Val) {
2010     if (Val)
2011       Fn.addFnAttr(Kind);
2012     else
2013       Fn.removeFnAttr(Kind);
2014   }
2015 };
2016 
2017 struct StrBoolAttr {
2018   static bool isSet(const Function &Fn,
2019                     StringRef Kind) {
2020     auto A = Fn.getFnAttribute(Kind);
2021     return A.getValueAsString().equals("true");
2022   }
2023 
2024   static void set(Function &Fn,
2025                   StringRef Kind, bool Val) {
2026     Fn.addFnAttr(Kind, Val ? "true" : "false");
2027   }
2028 };
2029 
2030 #define GET_ATTR_NAMES
2031 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)                                \
2032   struct ENUM_NAME##Attr : EnumAttr {                                          \
2033     static enum Attribute::AttrKind getKind() {                                \
2034       return llvm::Attribute::ENUM_NAME;                                       \
2035     }                                                                          \
2036   };
2037 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
2038   struct ENUM_NAME##Attr : StrBoolAttr {                                       \
2039     static StringRef getKind() { return #DISPLAY_NAME; }                       \
2040   };
2041 #include "llvm/IR/Attributes.inc"
2042 
2043 #define GET_ATTR_COMPAT_FUNC
2044 #include "llvm/IR/Attributes.inc"
2045 
2046 bool AttributeFuncs::areInlineCompatible(const Function &Caller,
2047                                          const Function &Callee) {
2048   return hasCompatibleFnAttrs(Caller, Callee);
2049 }
2050 
2051 bool AttributeFuncs::areOutlineCompatible(const Function &A,
2052                                           const Function &B) {
2053   return hasCompatibleFnAttrs(A, B);
2054 }
2055 
2056 void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
2057                                                 const Function &Callee) {
2058   mergeFnAttrs(Caller, Callee);
2059 }
2060 
2061 void AttributeFuncs::mergeAttributesForOutlining(Function &Base,
2062                                                 const Function &ToMerge) {
2063 
2064   // We merge functions so that they meet the most general case.
2065   // For example, if the NoNansFPMathAttr is set in one function, but not in
2066   // the other, in the merged function we can say that the NoNansFPMathAttr
2067   // is not set.
2068   // However if we have the SpeculativeLoadHardeningAttr set true in one
2069   // function, but not the other, we make sure that the function retains
2070   // that aspect in the merged function.
2071   mergeFnAttrs(Base, ToMerge);
2072 }
2073