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