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   if (this == &AI)
601     return false;
602   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
603   // relative to their enum value) and then strings.
604   if (isEnumAttribute()) {
605     if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
606     if (AI.isIntAttribute()) return true;
607     if (AI.isStringAttribute()) return true;
608     if (AI.isTypeAttribute()) return true;
609   }
610 
611   if (isTypeAttribute()) {
612     if (AI.isEnumAttribute()) return false;
613     if (AI.isTypeAttribute()) {
614       assert(getKindAsEnum() != AI.getKindAsEnum() &&
615              "Comparison of types would be unstable");
616       return getKindAsEnum() < AI.getKindAsEnum();
617     }
618     if (AI.isIntAttribute()) return true;
619     if (AI.isStringAttribute()) return true;
620   }
621 
622   if (isIntAttribute()) {
623     if (AI.isEnumAttribute()) return false;
624     if (AI.isTypeAttribute()) return false;
625     if (AI.isIntAttribute()) {
626       if (getKindAsEnum() == AI.getKindAsEnum())
627         return getValueAsInt() < AI.getValueAsInt();
628       return getKindAsEnum() < AI.getKindAsEnum();
629     }
630     if (AI.isStringAttribute()) return true;
631   }
632 
633   assert(isStringAttribute());
634   if (AI.isEnumAttribute()) return false;
635   if (AI.isTypeAttribute()) return false;
636   if (AI.isIntAttribute()) return false;
637   if (getKindAsString() == AI.getKindAsString())
638     return getValueAsString() < AI.getValueAsString();
639   return getKindAsString() < AI.getKindAsString();
640 }
641 
642 //===----------------------------------------------------------------------===//
643 // AttributeSet Definition
644 //===----------------------------------------------------------------------===//
645 
646 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) {
647   return AttributeSet(AttributeSetNode::get(C, B));
648 }
649 
650 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) {
651   return AttributeSet(AttributeSetNode::get(C, Attrs));
652 }
653 
654 AttributeSet AttributeSet::addAttribute(LLVMContext &C,
655                                         Attribute::AttrKind Kind) const {
656   if (hasAttribute(Kind)) return *this;
657   AttrBuilder B;
658   B.addAttribute(Kind);
659   return addAttributes(C, AttributeSet::get(C, B));
660 }
661 
662 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind,
663                                         StringRef Value) const {
664   AttrBuilder B;
665   B.addAttribute(Kind, Value);
666   return addAttributes(C, AttributeSet::get(C, B));
667 }
668 
669 AttributeSet AttributeSet::addAttributes(LLVMContext &C,
670                                          const AttributeSet AS) const {
671   if (!hasAttributes())
672     return AS;
673 
674   if (!AS.hasAttributes())
675     return *this;
676 
677   AttrBuilder B(AS);
678   for (const auto &I : *this)
679     B.addAttribute(I);
680 
681  return get(C, B);
682 }
683 
684 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
685                                              Attribute::AttrKind Kind) const {
686   if (!hasAttribute(Kind)) return *this;
687   AttrBuilder B(*this);
688   B.removeAttribute(Kind);
689   return get(C, B);
690 }
691 
692 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
693                                              StringRef Kind) const {
694   if (!hasAttribute(Kind)) return *this;
695   AttrBuilder B(*this);
696   B.removeAttribute(Kind);
697   return get(C, B);
698 }
699 
700 AttributeSet AttributeSet::removeAttributes(LLVMContext &C,
701                                               const AttrBuilder &Attrs) const {
702   AttrBuilder B(*this);
703   B.remove(Attrs);
704   return get(C, B);
705 }
706 
707 unsigned AttributeSet::getNumAttributes() const {
708   return SetNode ? SetNode->getNumAttributes() : 0;
709 }
710 
711 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const {
712   return SetNode ? SetNode->hasAttribute(Kind) : false;
713 }
714 
715 bool AttributeSet::hasAttribute(StringRef Kind) const {
716   return SetNode ? SetNode->hasAttribute(Kind) : false;
717 }
718 
719 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const {
720   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
721 }
722 
723 Attribute AttributeSet::getAttribute(StringRef Kind) const {
724   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
725 }
726 
727 MaybeAlign AttributeSet::getAlignment() const {
728   return SetNode ? SetNode->getAlignment() : None;
729 }
730 
731 MaybeAlign AttributeSet::getStackAlignment() const {
732   return SetNode ? SetNode->getStackAlignment() : None;
733 }
734 
735 uint64_t AttributeSet::getDereferenceableBytes() const {
736   return SetNode ? SetNode->getDereferenceableBytes() : 0;
737 }
738 
739 uint64_t AttributeSet::getDereferenceableOrNullBytes() const {
740   return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0;
741 }
742 
743 Type *AttributeSet::getByValType() const {
744   return SetNode ? SetNode->getByValType() : nullptr;
745 }
746 
747 Type *AttributeSet::getPreallocatedType() const {
748   return SetNode ? SetNode->getPreallocatedType() : nullptr;
749 }
750 
751 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const {
752   return SetNode ? SetNode->getAllocSizeArgs()
753                  : std::pair<unsigned, Optional<unsigned>>(0, 0);
754 }
755 
756 std::string AttributeSet::getAsString(bool InAttrGrp) const {
757   return SetNode ? SetNode->getAsString(InAttrGrp) : "";
758 }
759 
760 AttributeSet::iterator AttributeSet::begin() const {
761   return SetNode ? SetNode->begin() : nullptr;
762 }
763 
764 AttributeSet::iterator AttributeSet::end() const {
765   return SetNode ? SetNode->end() : nullptr;
766 }
767 
768 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
769 LLVM_DUMP_METHOD void AttributeSet::dump() const {
770   dbgs() << "AS =\n";
771     dbgs() << "  { ";
772     dbgs() << getAsString(true) << " }\n";
773 }
774 #endif
775 
776 //===----------------------------------------------------------------------===//
777 // AttributeSetNode Definition
778 //===----------------------------------------------------------------------===//
779 
780 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs)
781     : NumAttrs(Attrs.size()) {
782   // There's memory after the node where we can store the entries in.
783   llvm::copy(Attrs, getTrailingObjects<Attribute>());
784 
785   for (const auto &I : *this) {
786     if (I.isStringAttribute())
787       StringAttrs.insert({ I.getKindAsString(), I });
788     else
789       AvailableAttrs.addAttribute(I.getKindAsEnum());
790   }
791 }
792 
793 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
794                                         ArrayRef<Attribute> Attrs) {
795   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
796   llvm::sort(SortedAttrs);
797   return getSorted(C, SortedAttrs);
798 }
799 
800 AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C,
801                                               ArrayRef<Attribute> SortedAttrs) {
802   if (SortedAttrs.empty())
803     return nullptr;
804 
805   // Build a key to look up the existing attributes.
806   LLVMContextImpl *pImpl = C.pImpl;
807   FoldingSetNodeID ID;
808 
809   assert(llvm::is_sorted(SortedAttrs) && "Expected sorted attributes!");
810   for (const auto &Attr : SortedAttrs)
811     Attr.Profile(ID);
812 
813   void *InsertPoint;
814   AttributeSetNode *PA =
815     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
816 
817   // If we didn't find any existing attributes of the same shape then create a
818   // new one and insert it.
819   if (!PA) {
820     // Coallocate entries after the AttributeSetNode itself.
821     void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size()));
822     PA = new (Mem) AttributeSetNode(SortedAttrs);
823     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
824   }
825 
826   // Return the AttributeSetNode that we found or created.
827   return PA;
828 }
829 
830 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) {
831   // Add target-independent attributes.
832   SmallVector<Attribute, 8> Attrs;
833   for (Attribute::AttrKind Kind = Attribute::None;
834        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
835     if (!B.contains(Kind))
836       continue;
837 
838     Attribute Attr;
839     switch (Kind) {
840     case Attribute::ByVal:
841       Attr = Attribute::getWithByValType(C, B.getByValType());
842       break;
843     case Attribute::Preallocated:
844       Attr = Attribute::getWithPreallocatedType(C, B.getPreallocatedType());
845       break;
846     case Attribute::Alignment:
847       assert(B.getAlignment() && "Alignment must be set");
848       Attr = Attribute::getWithAlignment(C, *B.getAlignment());
849       break;
850     case Attribute::StackAlignment:
851       assert(B.getStackAlignment() && "StackAlignment must be set");
852       Attr = Attribute::getWithStackAlignment(C, *B.getStackAlignment());
853       break;
854     case Attribute::Dereferenceable:
855       Attr = Attribute::getWithDereferenceableBytes(
856           C, B.getDereferenceableBytes());
857       break;
858     case Attribute::DereferenceableOrNull:
859       Attr = Attribute::getWithDereferenceableOrNullBytes(
860           C, B.getDereferenceableOrNullBytes());
861       break;
862     case Attribute::AllocSize: {
863       auto A = B.getAllocSizeArgs();
864       Attr = Attribute::getWithAllocSizeArgs(C, A.first, A.second);
865       break;
866     }
867     default:
868       Attr = Attribute::get(C, Kind);
869     }
870     Attrs.push_back(Attr);
871   }
872 
873   // Add target-dependent (string) attributes.
874   for (const auto &TDA : B.td_attrs())
875     Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second));
876 
877   return getSorted(C, Attrs);
878 }
879 
880 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
881   return StringAttrs.count(Kind);
882 }
883 
884 Optional<Attribute>
885 AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const {
886   // Do a quick presence check.
887   if (!hasAttribute(Kind))
888     return None;
889 
890   // Attributes in a set are sorted by enum value, followed by string
891   // attributes. Binary search the one we want.
892   const Attribute *I =
893       std::lower_bound(begin(), end() - StringAttrs.size(), Kind,
894                        [](Attribute A, Attribute::AttrKind Kind) {
895                          return A.getKindAsEnum() < Kind;
896                        });
897   assert(I != end() && I->hasAttribute(Kind) && "Presence check failed?");
898   return *I;
899 }
900 
901 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
902   if (auto A = findEnumAttribute(Kind))
903     return *A;
904   return {};
905 }
906 
907 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
908   return StringAttrs.lookup(Kind);
909 }
910 
911 MaybeAlign AttributeSetNode::getAlignment() const {
912   if (auto A = findEnumAttribute(Attribute::Alignment))
913     return A->getAlignment();
914   return None;
915 }
916 
917 MaybeAlign AttributeSetNode::getStackAlignment() const {
918   if (auto A = findEnumAttribute(Attribute::StackAlignment))
919     return A->getStackAlignment();
920   return None;
921 }
922 
923 Type *AttributeSetNode::getByValType() const {
924   if (auto A = findEnumAttribute(Attribute::ByVal))
925     return A->getValueAsType();
926   return 0;
927 }
928 
929 Type *AttributeSetNode::getPreallocatedType() const {
930   for (const auto &I : *this)
931     if (I.hasAttribute(Attribute::Preallocated))
932       return I.getValueAsType();
933   return 0;
934 }
935 
936 uint64_t AttributeSetNode::getDereferenceableBytes() const {
937   if (auto A = findEnumAttribute(Attribute::Dereferenceable))
938     return A->getDereferenceableBytes();
939   return 0;
940 }
941 
942 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
943   if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull))
944     return A->getDereferenceableOrNullBytes();
945   return 0;
946 }
947 
948 std::pair<unsigned, Optional<unsigned>>
949 AttributeSetNode::getAllocSizeArgs() const {
950   if (auto A = findEnumAttribute(Attribute::AllocSize))
951     return A->getAllocSizeArgs();
952   return std::make_pair(0, 0);
953 }
954 
955 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
956   std::string Str;
957   for (iterator I = begin(), E = end(); I != E; ++I) {
958     if (I != begin())
959       Str += ' ';
960     Str += I->getAsString(InAttrGrp);
961   }
962   return Str;
963 }
964 
965 //===----------------------------------------------------------------------===//
966 // AttributeListImpl Definition
967 //===----------------------------------------------------------------------===//
968 
969 /// Map from AttributeList index to the internal array index. Adding one happens
970 /// to work, because -1 wraps around to 0.
971 static constexpr unsigned attrIdxToArrayIdx(unsigned Index) {
972   return Index + 1;
973 }
974 
975 AttributeListImpl::AttributeListImpl(ArrayRef<AttributeSet> Sets)
976     : NumAttrSets(Sets.size()) {
977   assert(!Sets.empty() && "pointless AttributeListImpl");
978 
979   // There's memory after the node where we can store the entries in.
980   llvm::copy(Sets, getTrailingObjects<AttributeSet>());
981 
982   // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs
983   // summary bitsets.
984   static_assert(attrIdxToArrayIdx(AttributeList::FunctionIndex) == 0U,
985                 "function should be stored in slot 0");
986   for (const auto &I : Sets[0])
987     if (!I.isStringAttribute())
988       AvailableFunctionAttrs.addAttribute(I.getKindAsEnum());
989 
990   for (const auto &Set : Sets)
991     for (const auto &I : Set)
992       if (!I.isStringAttribute())
993         AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum());
994 }
995 
996 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
997   Profile(ID, makeArrayRef(begin(), end()));
998 }
999 
1000 void AttributeListImpl::Profile(FoldingSetNodeID &ID,
1001                                 ArrayRef<AttributeSet> Sets) {
1002   for (const auto &Set : Sets)
1003     ID.AddPointer(Set.SetNode);
1004 }
1005 
1006 bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind,
1007                                         unsigned *Index) const {
1008   if (!AvailableSomewhereAttrs.hasAttribute(Kind))
1009     return false;
1010 
1011   if (Index) {
1012     for (unsigned I = 0, E = NumAttrSets; I != E; ++I) {
1013       if (begin()[I].hasAttribute(Kind)) {
1014         *Index = I - 1;
1015         break;
1016       }
1017     }
1018   }
1019 
1020   return true;
1021 }
1022 
1023 
1024 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1025 LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
1026   AttributeList(const_cast<AttributeListImpl *>(this)).dump();
1027 }
1028 #endif
1029 
1030 //===----------------------------------------------------------------------===//
1031 // AttributeList Construction and Mutation Methods
1032 //===----------------------------------------------------------------------===//
1033 
1034 AttributeList AttributeList::getImpl(LLVMContext &C,
1035                                      ArrayRef<AttributeSet> AttrSets) {
1036   assert(!AttrSets.empty() && "pointless AttributeListImpl");
1037 
1038   LLVMContextImpl *pImpl = C.pImpl;
1039   FoldingSetNodeID ID;
1040   AttributeListImpl::Profile(ID, AttrSets);
1041 
1042   void *InsertPoint;
1043   AttributeListImpl *PA =
1044       pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
1045 
1046   // If we didn't find any existing attributes of the same shape then
1047   // create a new one and insert it.
1048   if (!PA) {
1049     // Coallocate entries after the AttributeListImpl itself.
1050     void *Mem = pImpl->Alloc.Allocate(
1051         AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()),
1052         alignof(AttributeListImpl));
1053     PA = new (Mem) AttributeListImpl(AttrSets);
1054     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
1055   }
1056 
1057   // Return the AttributesList that we found or created.
1058   return AttributeList(PA);
1059 }
1060 
1061 AttributeList
1062 AttributeList::get(LLVMContext &C,
1063                    ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
1064   // If there are no attributes then return a null AttributesList pointer.
1065   if (Attrs.empty())
1066     return {};
1067 
1068   assert(llvm::is_sorted(Attrs,
1069                          [](const std::pair<unsigned, Attribute> &LHS,
1070                             const std::pair<unsigned, Attribute> &RHS) {
1071                            return LHS.first < RHS.first;
1072                          }) &&
1073          "Misordered Attributes list!");
1074   assert(llvm::none_of(Attrs,
1075                        [](const std::pair<unsigned, Attribute> &Pair) {
1076                          return Pair.second.hasAttribute(Attribute::None);
1077                        }) &&
1078          "Pointless attribute!");
1079 
1080   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
1081   // list.
1082   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
1083   for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
1084          E = Attrs.end(); I != E; ) {
1085     unsigned Index = I->first;
1086     SmallVector<Attribute, 4> AttrVec;
1087     while (I != E && I->first == Index) {
1088       AttrVec.push_back(I->second);
1089       ++I;
1090     }
1091 
1092     AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
1093   }
1094 
1095   return get(C, AttrPairVec);
1096 }
1097 
1098 AttributeList
1099 AttributeList::get(LLVMContext &C,
1100                    ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
1101   // If there are no attributes then return a null AttributesList pointer.
1102   if (Attrs.empty())
1103     return {};
1104 
1105   assert(llvm::is_sorted(Attrs,
1106                          [](const std::pair<unsigned, AttributeSet> &LHS,
1107                             const std::pair<unsigned, AttributeSet> &RHS) {
1108                            return LHS.first < RHS.first;
1109                          }) &&
1110          "Misordered Attributes list!");
1111   assert(llvm::none_of(Attrs,
1112                        [](const std::pair<unsigned, AttributeSet> &Pair) {
1113                          return !Pair.second.hasAttributes();
1114                        }) &&
1115          "Pointless attribute!");
1116 
1117   unsigned MaxIndex = Attrs.back().first;
1118   // If the MaxIndex is FunctionIndex and there are other indices in front
1119   // of it, we need to use the largest of those to get the right size.
1120   if (MaxIndex == FunctionIndex && Attrs.size() > 1)
1121     MaxIndex = Attrs[Attrs.size() - 2].first;
1122 
1123   SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1);
1124   for (const auto &Pair : Attrs)
1125     AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second;
1126 
1127   return getImpl(C, AttrVec);
1128 }
1129 
1130 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs,
1131                                  AttributeSet RetAttrs,
1132                                  ArrayRef<AttributeSet> ArgAttrs) {
1133   // Scan from the end to find the last argument with attributes.  Most
1134   // arguments don't have attributes, so it's nice if we can have fewer unique
1135   // AttributeListImpls by dropping empty attribute sets at the end of the list.
1136   unsigned NumSets = 0;
1137   for (size_t I = ArgAttrs.size(); I != 0; --I) {
1138     if (ArgAttrs[I - 1].hasAttributes()) {
1139       NumSets = I + 2;
1140       break;
1141     }
1142   }
1143   if (NumSets == 0) {
1144     // Check function and return attributes if we didn't have argument
1145     // attributes.
1146     if (RetAttrs.hasAttributes())
1147       NumSets = 2;
1148     else if (FnAttrs.hasAttributes())
1149       NumSets = 1;
1150   }
1151 
1152   // If all attribute sets were empty, we can use the empty attribute list.
1153   if (NumSets == 0)
1154     return {};
1155 
1156   SmallVector<AttributeSet, 8> AttrSets;
1157   AttrSets.reserve(NumSets);
1158   // If we have any attributes, we always have function attributes.
1159   AttrSets.push_back(FnAttrs);
1160   if (NumSets > 1)
1161     AttrSets.push_back(RetAttrs);
1162   if (NumSets > 2) {
1163     // Drop the empty argument attribute sets at the end.
1164     ArgAttrs = ArgAttrs.take_front(NumSets - 2);
1165     AttrSets.insert(AttrSets.end(), ArgAttrs.begin(), ArgAttrs.end());
1166   }
1167 
1168   return getImpl(C, AttrSets);
1169 }
1170 
1171 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1172                                  const AttrBuilder &B) {
1173   if (!B.hasAttributes())
1174     return {};
1175   Index = attrIdxToArrayIdx(Index);
1176   SmallVector<AttributeSet, 8> AttrSets(Index + 1);
1177   AttrSets[Index] = AttributeSet::get(C, B);
1178   return getImpl(C, AttrSets);
1179 }
1180 
1181 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1182                                  ArrayRef<Attribute::AttrKind> Kinds) {
1183   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1184   for (const auto K : Kinds)
1185     Attrs.emplace_back(Index, Attribute::get(C, K));
1186   return get(C, Attrs);
1187 }
1188 
1189 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1190                                  ArrayRef<Attribute::AttrKind> Kinds,
1191                                  ArrayRef<uint64_t> Values) {
1192   assert(Kinds.size() == Values.size() && "Mismatched attribute values.");
1193   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1194   auto VI = Values.begin();
1195   for (const auto K : Kinds)
1196     Attrs.emplace_back(Index, Attribute::get(C, K, *VI++));
1197   return get(C, Attrs);
1198 }
1199 
1200 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1201                                  ArrayRef<StringRef> Kinds) {
1202   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1203   for (const auto &K : Kinds)
1204     Attrs.emplace_back(Index, Attribute::get(C, K));
1205   return get(C, Attrs);
1206 }
1207 
1208 AttributeList AttributeList::get(LLVMContext &C,
1209                                  ArrayRef<AttributeList> Attrs) {
1210   if (Attrs.empty())
1211     return {};
1212   if (Attrs.size() == 1)
1213     return Attrs[0];
1214 
1215   unsigned MaxSize = 0;
1216   for (const auto &List : Attrs)
1217     MaxSize = std::max(MaxSize, List.getNumAttrSets());
1218 
1219   // If every list was empty, there is no point in merging the lists.
1220   if (MaxSize == 0)
1221     return {};
1222 
1223   SmallVector<AttributeSet, 8> NewAttrSets(MaxSize);
1224   for (unsigned I = 0; I < MaxSize; ++I) {
1225     AttrBuilder CurBuilder;
1226     for (const auto &List : Attrs)
1227       CurBuilder.merge(List.getAttributes(I - 1));
1228     NewAttrSets[I] = AttributeSet::get(C, CurBuilder);
1229   }
1230 
1231   return getImpl(C, NewAttrSets);
1232 }
1233 
1234 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1235                                           Attribute::AttrKind Kind) const {
1236   if (hasAttribute(Index, Kind)) return *this;
1237   AttrBuilder B;
1238   B.addAttribute(Kind);
1239   return addAttributes(C, Index, B);
1240 }
1241 
1242 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1243                                           StringRef Kind,
1244                                           StringRef Value) const {
1245   AttrBuilder B;
1246   B.addAttribute(Kind, Value);
1247   return addAttributes(C, Index, B);
1248 }
1249 
1250 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1251                                           Attribute A) const {
1252   AttrBuilder B;
1253   B.addAttribute(A);
1254   return addAttributes(C, Index, B);
1255 }
1256 
1257 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
1258                                            const AttrBuilder &B) const {
1259   if (!B.hasAttributes())
1260     return *this;
1261 
1262   if (!pImpl)
1263     return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}});
1264 
1265 #ifndef NDEBUG
1266   // FIXME it is not obvious how this should work for alignment. For now, say
1267   // we can't change a known alignment.
1268   const MaybeAlign OldAlign = getAttributes(Index).getAlignment();
1269   const MaybeAlign NewAlign = B.getAlignment();
1270   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
1271          "Attempt to change alignment!");
1272 #endif
1273 
1274   Index = attrIdxToArrayIdx(Index);
1275   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1276   if (Index >= AttrSets.size())
1277     AttrSets.resize(Index + 1);
1278 
1279   AttrBuilder Merged(AttrSets[Index]);
1280   Merged.merge(B);
1281   AttrSets[Index] = AttributeSet::get(C, Merged);
1282 
1283   return getImpl(C, AttrSets);
1284 }
1285 
1286 AttributeList AttributeList::addParamAttribute(LLVMContext &C,
1287                                                ArrayRef<unsigned> ArgNos,
1288                                                Attribute A) const {
1289   assert(llvm::is_sorted(ArgNos));
1290 
1291   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1292   unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex);
1293   if (MaxIndex >= AttrSets.size())
1294     AttrSets.resize(MaxIndex + 1);
1295 
1296   for (unsigned ArgNo : ArgNos) {
1297     unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex);
1298     AttrBuilder B(AttrSets[Index]);
1299     B.addAttribute(A);
1300     AttrSets[Index] = AttributeSet::get(C, B);
1301   }
1302 
1303   return getImpl(C, AttrSets);
1304 }
1305 
1306 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1307                                              Attribute::AttrKind Kind) const {
1308   if (!hasAttribute(Index, Kind)) return *this;
1309 
1310   Index = attrIdxToArrayIdx(Index);
1311   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1312   assert(Index < AttrSets.size());
1313 
1314   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1315 
1316   return getImpl(C, AttrSets);
1317 }
1318 
1319 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1320                                              StringRef Kind) const {
1321   if (!hasAttribute(Index, Kind)) return *this;
1322 
1323   Index = attrIdxToArrayIdx(Index);
1324   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1325   assert(Index < AttrSets.size());
1326 
1327   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1328 
1329   return getImpl(C, AttrSets);
1330 }
1331 
1332 AttributeList
1333 AttributeList::removeAttributes(LLVMContext &C, unsigned Index,
1334                                 const AttrBuilder &AttrsToRemove) const {
1335   if (!pImpl)
1336     return {};
1337 
1338   Index = attrIdxToArrayIdx(Index);
1339   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1340   if (Index >= AttrSets.size())
1341     AttrSets.resize(Index + 1);
1342 
1343   AttrSets[Index] = AttrSets[Index].removeAttributes(C, AttrsToRemove);
1344 
1345   return getImpl(C, AttrSets);
1346 }
1347 
1348 AttributeList AttributeList::removeAttributes(LLVMContext &C,
1349                                               unsigned WithoutIndex) const {
1350   if (!pImpl)
1351     return {};
1352   WithoutIndex = attrIdxToArrayIdx(WithoutIndex);
1353   if (WithoutIndex >= getNumAttrSets())
1354     return *this;
1355   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1356   AttrSets[WithoutIndex] = AttributeSet();
1357   return getImpl(C, AttrSets);
1358 }
1359 
1360 AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C,
1361                                                     unsigned Index,
1362                                                     uint64_t Bytes) const {
1363   AttrBuilder B;
1364   B.addDereferenceableAttr(Bytes);
1365   return addAttributes(C, Index, B);
1366 }
1367 
1368 AttributeList
1369 AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
1370                                             uint64_t Bytes) const {
1371   AttrBuilder B;
1372   B.addDereferenceableOrNullAttr(Bytes);
1373   return addAttributes(C, Index, B);
1374 }
1375 
1376 AttributeList
1377 AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index,
1378                                 unsigned ElemSizeArg,
1379                                 const Optional<unsigned> &NumElemsArg) {
1380   AttrBuilder B;
1381   B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1382   return addAttributes(C, Index, B);
1383 }
1384 
1385 //===----------------------------------------------------------------------===//
1386 // AttributeList Accessor Methods
1387 //===----------------------------------------------------------------------===//
1388 
1389 AttributeSet AttributeList::getParamAttributes(unsigned ArgNo) const {
1390   return getAttributes(ArgNo + FirstArgIndex);
1391 }
1392 
1393 AttributeSet AttributeList::getRetAttributes() const {
1394   return getAttributes(ReturnIndex);
1395 }
1396 
1397 AttributeSet AttributeList::getFnAttributes() const {
1398   return getAttributes(FunctionIndex);
1399 }
1400 
1401 bool AttributeList::hasAttribute(unsigned Index,
1402                                  Attribute::AttrKind Kind) const {
1403   return getAttributes(Index).hasAttribute(Kind);
1404 }
1405 
1406 bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const {
1407   return getAttributes(Index).hasAttribute(Kind);
1408 }
1409 
1410 bool AttributeList::hasAttributes(unsigned Index) const {
1411   return getAttributes(Index).hasAttributes();
1412 }
1413 
1414 bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const {
1415   return pImpl && pImpl->hasFnAttribute(Kind);
1416 }
1417 
1418 bool AttributeList::hasFnAttribute(StringRef Kind) const {
1419   return hasAttribute(AttributeList::FunctionIndex, Kind);
1420 }
1421 
1422 bool AttributeList::hasParamAttribute(unsigned ArgNo,
1423                                       Attribute::AttrKind Kind) const {
1424   return hasAttribute(ArgNo + FirstArgIndex, Kind);
1425 }
1426 
1427 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
1428                                      unsigned *Index) const {
1429   return pImpl && pImpl->hasAttrSomewhere(Attr, Index);
1430 }
1431 
1432 Attribute AttributeList::getAttribute(unsigned Index,
1433                                       Attribute::AttrKind Kind) const {
1434   return getAttributes(Index).getAttribute(Kind);
1435 }
1436 
1437 Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const {
1438   return getAttributes(Index).getAttribute(Kind);
1439 }
1440 
1441 MaybeAlign AttributeList::getRetAlignment() const {
1442   return getAttributes(ReturnIndex).getAlignment();
1443 }
1444 
1445 MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const {
1446   return getAttributes(ArgNo + FirstArgIndex).getAlignment();
1447 }
1448 
1449 Type *AttributeList::getParamByValType(unsigned Index) const {
1450   return getAttributes(Index+FirstArgIndex).getByValType();
1451 }
1452 
1453 Type *AttributeList::getParamPreallocatedType(unsigned Index) const {
1454   return getAttributes(Index + FirstArgIndex).getPreallocatedType();
1455 }
1456 
1457 MaybeAlign AttributeList::getStackAlignment(unsigned Index) const {
1458   return getAttributes(Index).getStackAlignment();
1459 }
1460 
1461 uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const {
1462   return getAttributes(Index).getDereferenceableBytes();
1463 }
1464 
1465 uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const {
1466   return getAttributes(Index).getDereferenceableOrNullBytes();
1467 }
1468 
1469 std::pair<unsigned, Optional<unsigned>>
1470 AttributeList::getAllocSizeArgs(unsigned Index) const {
1471   return getAttributes(Index).getAllocSizeArgs();
1472 }
1473 
1474 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
1475   return getAttributes(Index).getAsString(InAttrGrp);
1476 }
1477 
1478 AttributeSet AttributeList::getAttributes(unsigned Index) const {
1479   Index = attrIdxToArrayIdx(Index);
1480   if (!pImpl || Index >= getNumAttrSets())
1481     return {};
1482   return pImpl->begin()[Index];
1483 }
1484 
1485 AttributeList::iterator AttributeList::begin() const {
1486   return pImpl ? pImpl->begin() : nullptr;
1487 }
1488 
1489 AttributeList::iterator AttributeList::end() const {
1490   return pImpl ? pImpl->end() : nullptr;
1491 }
1492 
1493 //===----------------------------------------------------------------------===//
1494 // AttributeList Introspection Methods
1495 //===----------------------------------------------------------------------===//
1496 
1497 unsigned AttributeList::getNumAttrSets() const {
1498   return pImpl ? pImpl->NumAttrSets : 0;
1499 }
1500 
1501 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1502 LLVM_DUMP_METHOD void AttributeList::dump() const {
1503   dbgs() << "PAL[\n";
1504 
1505   for (unsigned i = index_begin(), e = index_end(); i != e; ++i) {
1506     if (getAttributes(i).hasAttributes())
1507       dbgs() << "  { " << i << " => " << getAsString(i) << " }\n";
1508   }
1509 
1510   dbgs() << "]\n";
1511 }
1512 #endif
1513 
1514 //===----------------------------------------------------------------------===//
1515 // AttrBuilder Method Implementations
1516 //===----------------------------------------------------------------------===//
1517 
1518 // FIXME: Remove this ctor, use AttributeSet.
1519 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) {
1520   AttributeSet AS = AL.getAttributes(Index);
1521   for (const auto &A : AS)
1522     addAttribute(A);
1523 }
1524 
1525 AttrBuilder::AttrBuilder(AttributeSet AS) {
1526   for (const auto &A : AS)
1527     addAttribute(A);
1528 }
1529 
1530 void AttrBuilder::clear() {
1531   Attrs.reset();
1532   TargetDepAttrs.clear();
1533   Alignment.reset();
1534   StackAlignment.reset();
1535   DerefBytes = DerefOrNullBytes = 0;
1536   AllocSizeArgs = 0;
1537   ByValType = nullptr;
1538   PreallocatedType = nullptr;
1539 }
1540 
1541 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
1542   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1543   assert(!Attribute::doesAttrKindHaveArgument(Val) &&
1544          "Adding integer attribute without adding a value!");
1545   Attrs[Val] = true;
1546   return *this;
1547 }
1548 
1549 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
1550   if (Attr.isStringAttribute()) {
1551     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
1552     return *this;
1553   }
1554 
1555   Attribute::AttrKind Kind = Attr.getKindAsEnum();
1556   Attrs[Kind] = true;
1557 
1558   if (Kind == Attribute::Alignment)
1559     Alignment = Attr.getAlignment();
1560   else if (Kind == Attribute::StackAlignment)
1561     StackAlignment = Attr.getStackAlignment();
1562   else if (Kind == Attribute::ByVal)
1563     ByValType = Attr.getValueAsType();
1564   else if (Kind == Attribute::Preallocated)
1565     PreallocatedType = Attr.getValueAsType();
1566   else if (Kind == Attribute::Dereferenceable)
1567     DerefBytes = Attr.getDereferenceableBytes();
1568   else if (Kind == Attribute::DereferenceableOrNull)
1569     DerefOrNullBytes = Attr.getDereferenceableOrNullBytes();
1570   else if (Kind == Attribute::AllocSize)
1571     AllocSizeArgs = Attr.getValueAsInt();
1572   return *this;
1573 }
1574 
1575 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
1576   TargetDepAttrs[std::string(A)] = std::string(V);
1577   return *this;
1578 }
1579 
1580 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1581   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1582   Attrs[Val] = false;
1583 
1584   if (Val == Attribute::Alignment)
1585     Alignment.reset();
1586   else if (Val == Attribute::StackAlignment)
1587     StackAlignment.reset();
1588   else if (Val == Attribute::ByVal)
1589     ByValType = nullptr;
1590   else if (Val == Attribute::Preallocated)
1591     PreallocatedType = nullptr;
1592   else if (Val == Attribute::Dereferenceable)
1593     DerefBytes = 0;
1594   else if (Val == Attribute::DereferenceableOrNull)
1595     DerefOrNullBytes = 0;
1596   else if (Val == Attribute::AllocSize)
1597     AllocSizeArgs = 0;
1598 
1599   return *this;
1600 }
1601 
1602 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) {
1603   remove(A.getAttributes(Index));
1604   return *this;
1605 }
1606 
1607 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1608   auto I = TargetDepAttrs.find(A);
1609   if (I != TargetDepAttrs.end())
1610     TargetDepAttrs.erase(I);
1611   return *this;
1612 }
1613 
1614 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
1615   return unpackAllocSizeArgs(AllocSizeArgs);
1616 }
1617 
1618 AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) {
1619   if (!Align)
1620     return *this;
1621 
1622   assert(*Align <= llvm::Value::MaximumAlignment && "Alignment too large.");
1623 
1624   Attrs[Attribute::Alignment] = true;
1625   Alignment = Align;
1626   return *this;
1627 }
1628 
1629 AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) {
1630   // Default alignment, allow the target to define how to align it.
1631   if (!Align)
1632     return *this;
1633 
1634   assert(*Align <= 0x100 && "Alignment too large.");
1635 
1636   Attrs[Attribute::StackAlignment] = true;
1637   StackAlignment = Align;
1638   return *this;
1639 }
1640 
1641 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
1642   if (Bytes == 0) return *this;
1643 
1644   Attrs[Attribute::Dereferenceable] = true;
1645   DerefBytes = Bytes;
1646   return *this;
1647 }
1648 
1649 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
1650   if (Bytes == 0)
1651     return *this;
1652 
1653   Attrs[Attribute::DereferenceableOrNull] = true;
1654   DerefOrNullBytes = Bytes;
1655   return *this;
1656 }
1657 
1658 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
1659                                            const Optional<unsigned> &NumElems) {
1660   return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
1661 }
1662 
1663 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
1664   // (0, 0) is our "not present" value, so we need to check for it here.
1665   assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
1666 
1667   Attrs[Attribute::AllocSize] = true;
1668   // Reuse existing machinery to store this as a single 64-bit integer so we can
1669   // save a few bytes over using a pair<unsigned, Optional<unsigned>>.
1670   AllocSizeArgs = RawArgs;
1671   return *this;
1672 }
1673 
1674 AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) {
1675   Attrs[Attribute::ByVal] = true;
1676   ByValType = Ty;
1677   return *this;
1678 }
1679 
1680 AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) {
1681   Attrs[Attribute::Preallocated] = true;
1682   PreallocatedType = Ty;
1683   return *this;
1684 }
1685 
1686 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1687   // FIXME: What if both have alignments, but they don't match?!
1688   if (!Alignment)
1689     Alignment = B.Alignment;
1690 
1691   if (!StackAlignment)
1692     StackAlignment = B.StackAlignment;
1693 
1694   if (!DerefBytes)
1695     DerefBytes = B.DerefBytes;
1696 
1697   if (!DerefOrNullBytes)
1698     DerefOrNullBytes = B.DerefOrNullBytes;
1699 
1700   if (!AllocSizeArgs)
1701     AllocSizeArgs = B.AllocSizeArgs;
1702 
1703   if (!ByValType)
1704     ByValType = B.ByValType;
1705 
1706   if (!PreallocatedType)
1707     PreallocatedType = B.PreallocatedType;
1708 
1709   Attrs |= B.Attrs;
1710 
1711   for (const auto &I : B.td_attrs())
1712     TargetDepAttrs[I.first] = I.second;
1713 
1714   return *this;
1715 }
1716 
1717 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
1718   // FIXME: What if both have alignments, but they don't match?!
1719   if (B.Alignment)
1720     Alignment.reset();
1721 
1722   if (B.StackAlignment)
1723     StackAlignment.reset();
1724 
1725   if (B.DerefBytes)
1726     DerefBytes = 0;
1727 
1728   if (B.DerefOrNullBytes)
1729     DerefOrNullBytes = 0;
1730 
1731   if (B.AllocSizeArgs)
1732     AllocSizeArgs = 0;
1733 
1734   if (B.ByValType)
1735     ByValType = nullptr;
1736 
1737   if (B.PreallocatedType)
1738     PreallocatedType = nullptr;
1739 
1740   Attrs &= ~B.Attrs;
1741 
1742   for (const auto &I : B.td_attrs())
1743     TargetDepAttrs.erase(I.first);
1744 
1745   return *this;
1746 }
1747 
1748 bool AttrBuilder::overlaps(const AttrBuilder &B) const {
1749   // First check if any of the target independent attributes overlap.
1750   if ((Attrs & B.Attrs).any())
1751     return true;
1752 
1753   // Then check if any target dependent ones do.
1754   for (const auto &I : td_attrs())
1755     if (B.contains(I.first))
1756       return true;
1757 
1758   return false;
1759 }
1760 
1761 bool AttrBuilder::contains(StringRef A) const {
1762   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1763 }
1764 
1765 bool AttrBuilder::hasAttributes() const {
1766   return !Attrs.none() || !TargetDepAttrs.empty();
1767 }
1768 
1769 bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const {
1770   AttributeSet AS = AL.getAttributes(Index);
1771 
1772   for (const auto &Attr : AS) {
1773     if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1774       if (contains(Attr.getKindAsEnum()))
1775         return true;
1776     } else {
1777       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1778       return contains(Attr.getKindAsString());
1779     }
1780   }
1781 
1782   return false;
1783 }
1784 
1785 bool AttrBuilder::hasAlignmentAttr() const {
1786   return Alignment != 0;
1787 }
1788 
1789 bool AttrBuilder::operator==(const AttrBuilder &B) {
1790   if (Attrs != B.Attrs)
1791     return false;
1792 
1793   for (td_const_iterator I = TargetDepAttrs.begin(),
1794          E = TargetDepAttrs.end(); I != E; ++I)
1795     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1796       return false;
1797 
1798   return Alignment == B.Alignment && StackAlignment == B.StackAlignment &&
1799          DerefBytes == B.DerefBytes && ByValType == B.ByValType &&
1800          PreallocatedType == B.PreallocatedType;
1801 }
1802 
1803 //===----------------------------------------------------------------------===//
1804 // AttributeFuncs Function Defintions
1805 //===----------------------------------------------------------------------===//
1806 
1807 /// Which attributes cannot be applied to a type.
1808 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) {
1809   AttrBuilder Incompatible;
1810 
1811   if (!Ty->isIntegerTy())
1812     // Attribute that only apply to integers.
1813     Incompatible.addAttribute(Attribute::SExt)
1814       .addAttribute(Attribute::ZExt);
1815 
1816   if (!Ty->isPointerTy())
1817     // Attribute that only apply to pointers.
1818     Incompatible.addAttribute(Attribute::Nest)
1819         .addAttribute(Attribute::NoAlias)
1820         .addAttribute(Attribute::NoCapture)
1821         .addAttribute(Attribute::NonNull)
1822         .addDereferenceableAttr(1)       // the int here is ignored
1823         .addDereferenceableOrNullAttr(1) // the int here is ignored
1824         .addAttribute(Attribute::ReadNone)
1825         .addAttribute(Attribute::ReadOnly)
1826         .addAttribute(Attribute::StructRet)
1827         .addAttribute(Attribute::InAlloca)
1828         .addPreallocatedAttr(Ty)
1829         .addByValAttr(Ty);
1830 
1831   return Incompatible;
1832 }
1833 
1834 template<typename AttrClass>
1835 static bool isEqual(const Function &Caller, const Function &Callee) {
1836   return Caller.getFnAttribute(AttrClass::getKind()) ==
1837          Callee.getFnAttribute(AttrClass::getKind());
1838 }
1839 
1840 /// Compute the logical AND of the attributes of the caller and the
1841 /// callee.
1842 ///
1843 /// This function sets the caller's attribute to false if the callee's attribute
1844 /// is false.
1845 template<typename AttrClass>
1846 static void setAND(Function &Caller, const Function &Callee) {
1847   if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
1848       !AttrClass::isSet(Callee, AttrClass::getKind()))
1849     AttrClass::set(Caller, AttrClass::getKind(), false);
1850 }
1851 
1852 /// Compute the logical OR of the attributes of the caller and the
1853 /// callee.
1854 ///
1855 /// This function sets the caller's attribute to true if the callee's attribute
1856 /// is true.
1857 template<typename AttrClass>
1858 static void setOR(Function &Caller, const Function &Callee) {
1859   if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
1860       AttrClass::isSet(Callee, AttrClass::getKind()))
1861     AttrClass::set(Caller, AttrClass::getKind(), true);
1862 }
1863 
1864 /// If the inlined function had a higher stack protection level than the
1865 /// calling function, then bump up the caller's stack protection level.
1866 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
1867   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
1868   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
1869   // clutter to the IR.
1870   AttrBuilder OldSSPAttr;
1871   OldSSPAttr.addAttribute(Attribute::StackProtect)
1872       .addAttribute(Attribute::StackProtectStrong)
1873       .addAttribute(Attribute::StackProtectReq);
1874 
1875   if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
1876     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1877     Caller.addFnAttr(Attribute::StackProtectReq);
1878   } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
1879              !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
1880     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1881     Caller.addFnAttr(Attribute::StackProtectStrong);
1882   } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
1883              !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
1884              !Caller.hasFnAttribute(Attribute::StackProtectStrong))
1885     Caller.addFnAttr(Attribute::StackProtect);
1886 }
1887 
1888 /// If the inlined function required stack probes, then ensure that
1889 /// the calling function has those too.
1890 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) {
1891   if (!Caller.hasFnAttribute("probe-stack") &&
1892       Callee.hasFnAttribute("probe-stack")) {
1893     Caller.addFnAttr(Callee.getFnAttribute("probe-stack"));
1894   }
1895 }
1896 
1897 /// If the inlined function defines the size of guard region
1898 /// on the stack, then ensure that the calling function defines a guard region
1899 /// that is no larger.
1900 static void
1901 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) {
1902   if (Callee.hasFnAttribute("stack-probe-size")) {
1903     uint64_t CalleeStackProbeSize;
1904     Callee.getFnAttribute("stack-probe-size")
1905           .getValueAsString()
1906           .getAsInteger(0, CalleeStackProbeSize);
1907     if (Caller.hasFnAttribute("stack-probe-size")) {
1908       uint64_t CallerStackProbeSize;
1909       Caller.getFnAttribute("stack-probe-size")
1910             .getValueAsString()
1911             .getAsInteger(0, CallerStackProbeSize);
1912       if (CallerStackProbeSize > CalleeStackProbeSize) {
1913         Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1914       }
1915     } else {
1916       Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1917     }
1918   }
1919 }
1920 
1921 /// If the inlined function defines a min legal vector width, then ensure
1922 /// the calling function has the same or larger min legal vector width. If the
1923 /// caller has the attribute, but the callee doesn't, we need to remove the
1924 /// attribute from the caller since we can't make any guarantees about the
1925 /// caller's requirements.
1926 /// This function is called after the inlining decision has been made so we have
1927 /// to merge the attribute this way. Heuristics that would use
1928 /// min-legal-vector-width to determine inline compatibility would need to be
1929 /// handled as part of inline cost analysis.
1930 static void
1931 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) {
1932   if (Caller.hasFnAttribute("min-legal-vector-width")) {
1933     if (Callee.hasFnAttribute("min-legal-vector-width")) {
1934       uint64_t CallerVectorWidth;
1935       Caller.getFnAttribute("min-legal-vector-width")
1936             .getValueAsString()
1937             .getAsInteger(0, CallerVectorWidth);
1938       uint64_t CalleeVectorWidth;
1939       Callee.getFnAttribute("min-legal-vector-width")
1940             .getValueAsString()
1941             .getAsInteger(0, CalleeVectorWidth);
1942       if (CallerVectorWidth < CalleeVectorWidth)
1943         Caller.addFnAttr(Callee.getFnAttribute("min-legal-vector-width"));
1944     } else {
1945       // If the callee doesn't have the attribute then we don't know anything
1946       // and must drop the attribute from the caller.
1947       Caller.removeFnAttr("min-legal-vector-width");
1948     }
1949   }
1950 }
1951 
1952 /// If the inlined function has null_pointer_is_valid attribute,
1953 /// set this attribute in the caller post inlining.
1954 static void
1955 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) {
1956   if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) {
1957     Caller.addFnAttr(Attribute::NullPointerIsValid);
1958   }
1959 }
1960 
1961 struct EnumAttr {
1962   static bool isSet(const Function &Fn,
1963                     Attribute::AttrKind Kind) {
1964     return Fn.hasFnAttribute(Kind);
1965   }
1966 
1967   static void set(Function &Fn,
1968                   Attribute::AttrKind Kind, bool Val) {
1969     if (Val)
1970       Fn.addFnAttr(Kind);
1971     else
1972       Fn.removeFnAttr(Kind);
1973   }
1974 };
1975 
1976 struct StrBoolAttr {
1977   static bool isSet(const Function &Fn,
1978                     StringRef Kind) {
1979     auto A = Fn.getFnAttribute(Kind);
1980     return A.getValueAsString().equals("true");
1981   }
1982 
1983   static void set(Function &Fn,
1984                   StringRef Kind, bool Val) {
1985     Fn.addFnAttr(Kind, Val ? "true" : "false");
1986   }
1987 };
1988 
1989 #define GET_ATTR_NAMES
1990 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)                                \
1991   struct ENUM_NAME##Attr : EnumAttr {                                          \
1992     static enum Attribute::AttrKind getKind() {                                \
1993       return llvm::Attribute::ENUM_NAME;                                       \
1994     }                                                                          \
1995   };
1996 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1997   struct ENUM_NAME##Attr : StrBoolAttr {                                       \
1998     static StringRef getKind() { return #DISPLAY_NAME; }                       \
1999   };
2000 #include "llvm/IR/Attributes.inc"
2001 
2002 #define GET_ATTR_COMPAT_FUNC
2003 #include "llvm/IR/Attributes.inc"
2004 
2005 bool AttributeFuncs::areInlineCompatible(const Function &Caller,
2006                                          const Function &Callee) {
2007   return hasCompatibleFnAttrs(Caller, Callee);
2008 }
2009 
2010 void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
2011                                                 const Function &Callee) {
2012   mergeFnAttrs(Caller, Callee);
2013 }
2014