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