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