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