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