1 //===- Attributes.cpp - Implement AttributesList --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 // This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeListImpl, and AttributeList classes.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
48 //===----------------------------------------------------------------------===//
49 // Attribute Construction Methods
50 //===----------------------------------------------------------------------===//
52 // allocsize has two integer arguments, but because they're both 32 bits, we can
53 // pack them into one 64-bit value, at the cost of making said value
56 // In order to do this, we need to reserve one value of the second (optional)
57 // allocsize argument to signify "not present."
58 static const unsigned AllocSizeNumElemsNotPresent = -1;
60 static uint64_t packAllocSizeArgs(unsigned ElemSizeArg,
61 const Optional<unsigned> &NumElemsArg) {
62 assert((!NumElemsArg.hasValue() ||
63 *NumElemsArg != AllocSizeNumElemsNotPresent) &&
64 "Attempting to pack a reserved value");
66 return uint64_t(ElemSizeArg) << 32 |
67 NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent);
70 static std::pair<unsigned, Optional<unsigned>>
71 unpackAllocSizeArgs(uint64_t Num) {
72 unsigned NumElems = Num & std::numeric_limits<unsigned>::max();
73 unsigned ElemSizeArg = Num >> 32;
75 Optional<unsigned> NumElemsArg;
76 if (NumElems != AllocSizeNumElemsNotPresent)
77 NumElemsArg = NumElems;
78 return std::make_pair(ElemSizeArg, NumElemsArg);
81 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
83 LLVMContextImpl *pImpl = Context.pImpl;
86 if (Val) ID.AddInteger(Val);
89 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
92 // If we didn't find any existing attributes of the same shape then create a
93 // new one and insert it.
95 PA = new EnumAttributeImpl(Kind);
97 PA = new IntAttributeImpl(Kind, Val);
98 pImpl->AttrsSet.InsertNode(PA, InsertPoint);
101 // Return the Attribute that we found or created.
102 return Attribute(PA);
105 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
106 LLVMContextImpl *pImpl = Context.pImpl;
109 if (!Val.empty()) ID.AddString(Val);
112 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
115 // If we didn't find any existing attributes of the same shape then create a
116 // new one and insert it.
117 PA = new StringAttributeImpl(Kind, Val);
118 pImpl->AttrsSet.InsertNode(PA, InsertPoint);
121 // Return the Attribute that we found or created.
122 return Attribute(PA);
125 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
126 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
127 assert(Align <= 0x40000000 && "Alignment too large.");
128 return get(Context, Alignment, Align);
131 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
133 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
134 assert(Align <= 0x100 && "Alignment too large.");
135 return get(Context, StackAlignment, Align);
138 Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context,
140 assert(Bytes && "Bytes must be non-zero.");
141 return get(Context, Dereferenceable, Bytes);
144 Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context,
146 assert(Bytes && "Bytes must be non-zero.");
147 return get(Context, DereferenceableOrNull, Bytes);
151 Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg,
152 const Optional<unsigned> &NumElemsArg) {
153 assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) &&
154 "Invalid allocsize arguments -- given allocsize(0, 0)");
155 return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg));
158 //===----------------------------------------------------------------------===//
159 // Attribute Accessor Methods
160 //===----------------------------------------------------------------------===//
162 bool Attribute::isEnumAttribute() const {
163 return pImpl && pImpl->isEnumAttribute();
166 bool Attribute::isIntAttribute() const {
167 return pImpl && pImpl->isIntAttribute();
170 bool Attribute::isStringAttribute() const {
171 return pImpl && pImpl->isStringAttribute();
174 Attribute::AttrKind Attribute::getKindAsEnum() const {
175 if (!pImpl) return None;
176 assert((isEnumAttribute() || isIntAttribute()) &&
177 "Invalid attribute type to get the kind as an enum!");
178 return pImpl->getKindAsEnum();
181 uint64_t Attribute::getValueAsInt() const {
182 if (!pImpl) return 0;
183 assert(isIntAttribute() &&
184 "Expected the attribute to be an integer attribute!");
185 return pImpl->getValueAsInt();
188 StringRef Attribute::getKindAsString() const {
189 if (!pImpl) return {};
190 assert(isStringAttribute() &&
191 "Invalid attribute type to get the kind as a string!");
192 return pImpl->getKindAsString();
195 StringRef Attribute::getValueAsString() const {
196 if (!pImpl) return {};
197 assert(isStringAttribute() &&
198 "Invalid attribute type to get the value as a string!");
199 return pImpl->getValueAsString();
202 bool Attribute::hasAttribute(AttrKind Kind) const {
203 return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
206 bool Attribute::hasAttribute(StringRef Kind) const {
207 if (!isStringAttribute()) return false;
208 return pImpl && pImpl->hasAttribute(Kind);
211 unsigned Attribute::getAlignment() const {
212 assert(hasAttribute(Attribute::Alignment) &&
213 "Trying to get alignment from non-alignment attribute!");
214 return pImpl->getValueAsInt();
217 unsigned Attribute::getStackAlignment() const {
218 assert(hasAttribute(Attribute::StackAlignment) &&
219 "Trying to get alignment from non-alignment attribute!");
220 return pImpl->getValueAsInt();
223 uint64_t Attribute::getDereferenceableBytes() const {
224 assert(hasAttribute(Attribute::Dereferenceable) &&
225 "Trying to get dereferenceable bytes from "
226 "non-dereferenceable attribute!");
227 return pImpl->getValueAsInt();
230 uint64_t Attribute::getDereferenceableOrNullBytes() const {
231 assert(hasAttribute(Attribute::DereferenceableOrNull) &&
232 "Trying to get dereferenceable bytes from "
233 "non-dereferenceable attribute!");
234 return pImpl->getValueAsInt();
237 std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const {
238 assert(hasAttribute(Attribute::AllocSize) &&
239 "Trying to get allocsize args from non-allocsize attribute");
240 return unpackAllocSizeArgs(pImpl->getValueAsInt());
243 std::string Attribute::getAsString(bool InAttrGrp) const {
244 if (!pImpl) return {};
246 if (hasAttribute(Attribute::SanitizeAddress))
247 return "sanitize_address";
248 if (hasAttribute(Attribute::SanitizeHWAddress))
249 return "sanitize_hwaddress";
250 if (hasAttribute(Attribute::AlwaysInline))
251 return "alwaysinline";
252 if (hasAttribute(Attribute::ArgMemOnly))
254 if (hasAttribute(Attribute::Builtin))
256 if (hasAttribute(Attribute::ByVal))
258 if (hasAttribute(Attribute::Convergent))
260 if (hasAttribute(Attribute::SwiftError))
262 if (hasAttribute(Attribute::SwiftSelf))
264 if (hasAttribute(Attribute::InaccessibleMemOnly))
265 return "inaccessiblememonly";
266 if (hasAttribute(Attribute::InaccessibleMemOrArgMemOnly))
267 return "inaccessiblemem_or_argmemonly";
268 if (hasAttribute(Attribute::InAlloca))
270 if (hasAttribute(Attribute::InlineHint))
272 if (hasAttribute(Attribute::InReg))
274 if (hasAttribute(Attribute::JumpTable))
276 if (hasAttribute(Attribute::MinSize))
278 if (hasAttribute(Attribute::Naked))
280 if (hasAttribute(Attribute::Nest))
282 if (hasAttribute(Attribute::NoAlias))
284 if (hasAttribute(Attribute::NoBuiltin))
286 if (hasAttribute(Attribute::NoCapture))
288 if (hasAttribute(Attribute::NoDuplicate))
289 return "noduplicate";
290 if (hasAttribute(Attribute::NoImplicitFloat))
291 return "noimplicitfloat";
292 if (hasAttribute(Attribute::NoInline))
294 if (hasAttribute(Attribute::NonLazyBind))
295 return "nonlazybind";
296 if (hasAttribute(Attribute::NonNull))
298 if (hasAttribute(Attribute::NoRedZone))
300 if (hasAttribute(Attribute::NoReturn))
302 if (hasAttribute(Attribute::NoCfCheck))
304 if (hasAttribute(Attribute::NoRecurse))
306 if (hasAttribute(Attribute::NoUnwind))
308 if (hasAttribute(Attribute::OptForFuzzing))
309 return "optforfuzzing";
310 if (hasAttribute(Attribute::OptimizeNone))
312 if (hasAttribute(Attribute::OptimizeForSize))
314 if (hasAttribute(Attribute::ReadNone))
316 if (hasAttribute(Attribute::ReadOnly))
318 if (hasAttribute(Attribute::WriteOnly))
320 if (hasAttribute(Attribute::Returned))
322 if (hasAttribute(Attribute::ReturnsTwice))
323 return "returns_twice";
324 if (hasAttribute(Attribute::SExt))
326 if (hasAttribute(Attribute::Speculatable))
327 return "speculatable";
328 if (hasAttribute(Attribute::StackProtect))
330 if (hasAttribute(Attribute::StackProtectReq))
332 if (hasAttribute(Attribute::StackProtectStrong))
334 if (hasAttribute(Attribute::SafeStack))
336 if (hasAttribute(Attribute::ShadowCallStack))
337 return "shadowcallstack";
338 if (hasAttribute(Attribute::StrictFP))
340 if (hasAttribute(Attribute::StructRet))
342 if (hasAttribute(Attribute::SanitizeThread))
343 return "sanitize_thread";
344 if (hasAttribute(Attribute::SanitizeMemory))
345 return "sanitize_memory";
346 if (hasAttribute(Attribute::UWTable))
348 if (hasAttribute(Attribute::ZExt))
350 if (hasAttribute(Attribute::Cold))
353 // FIXME: These should be output like this:
358 if (hasAttribute(Attribute::Alignment)) {
361 Result += (InAttrGrp) ? "=" : " ";
362 Result += utostr(getValueAsInt());
366 auto AttrWithBytesToString = [&](const char *Name) {
371 Result += utostr(getValueAsInt());
374 Result += utostr(getValueAsInt());
380 if (hasAttribute(Attribute::StackAlignment))
381 return AttrWithBytesToString("alignstack");
383 if (hasAttribute(Attribute::Dereferenceable))
384 return AttrWithBytesToString("dereferenceable");
386 if (hasAttribute(Attribute::DereferenceableOrNull))
387 return AttrWithBytesToString("dereferenceable_or_null");
389 if (hasAttribute(Attribute::AllocSize)) {
391 Optional<unsigned> NumElems;
392 std::tie(ElemSize, NumElems) = getAllocSizeArgs();
394 std::string Result = "allocsize(";
395 Result += utostr(ElemSize);
396 if (NumElems.hasValue()) {
398 Result += utostr(*NumElems);
404 // Convert target-dependent attributes to strings of the form:
409 if (isStringAttribute()) {
411 Result += (Twine('"') + getKindAsString() + Twine('"')).str();
413 std::string AttrVal = pImpl->getValueAsString();
414 if (AttrVal.empty()) return Result;
416 // Since some attribute strings contain special characters that cannot be
417 // printable, those have to be escaped to make the attribute value printable
418 // as is. e.g. "\01__gnu_mcount_nc"
420 raw_string_ostream OS(Result);
422 printEscapedString(AttrVal, OS);
428 llvm_unreachable("Unknown attribute");
431 bool Attribute::operator<(Attribute A) const {
432 if (!pImpl && !A.pImpl) return false;
433 if (!pImpl) return true;
434 if (!A.pImpl) return false;
435 return *pImpl < *A.pImpl;
438 //===----------------------------------------------------------------------===//
439 // AttributeImpl Definition
440 //===----------------------------------------------------------------------===//
442 // Pin the vtables to this file.
443 AttributeImpl::~AttributeImpl() = default;
445 void EnumAttributeImpl::anchor() {}
447 void IntAttributeImpl::anchor() {}
449 void StringAttributeImpl::anchor() {}
451 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
452 if (isStringAttribute()) return false;
453 return getKindAsEnum() == A;
456 bool AttributeImpl::hasAttribute(StringRef Kind) const {
457 if (!isStringAttribute()) return false;
458 return getKindAsString() == Kind;
461 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
462 assert(isEnumAttribute() || isIntAttribute());
463 return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
466 uint64_t AttributeImpl::getValueAsInt() const {
467 assert(isIntAttribute());
468 return static_cast<const IntAttributeImpl *>(this)->getValue();
471 StringRef AttributeImpl::getKindAsString() const {
472 assert(isStringAttribute());
473 return static_cast<const StringAttributeImpl *>(this)->getStringKind();
476 StringRef AttributeImpl::getValueAsString() const {
477 assert(isStringAttribute());
478 return static_cast<const StringAttributeImpl *>(this)->getStringValue();
481 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
482 // This sorts the attributes with Attribute::AttrKinds coming first (sorted
483 // relative to their enum value) and then strings.
484 if (isEnumAttribute()) {
485 if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
486 if (AI.isIntAttribute()) return true;
487 if (AI.isStringAttribute()) return true;
490 if (isIntAttribute()) {
491 if (AI.isEnumAttribute()) return false;
492 if (AI.isIntAttribute()) {
493 if (getKindAsEnum() == AI.getKindAsEnum())
494 return getValueAsInt() < AI.getValueAsInt();
495 return getKindAsEnum() < AI.getKindAsEnum();
497 if (AI.isStringAttribute()) return true;
500 if (AI.isEnumAttribute()) return false;
501 if (AI.isIntAttribute()) return false;
502 if (getKindAsString() == AI.getKindAsString())
503 return getValueAsString() < AI.getValueAsString();
504 return getKindAsString() < AI.getKindAsString();
507 //===----------------------------------------------------------------------===//
508 // AttributeSet Definition
509 //===----------------------------------------------------------------------===//
511 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) {
512 return AttributeSet(AttributeSetNode::get(C, B));
515 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) {
516 return AttributeSet(AttributeSetNode::get(C, Attrs));
519 AttributeSet AttributeSet::addAttribute(LLVMContext &C,
520 Attribute::AttrKind Kind) const {
521 if (hasAttribute(Kind)) return *this;
523 B.addAttribute(Kind);
524 return addAttributes(C, AttributeSet::get(C, B));
527 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind,
528 StringRef Value) const {
530 B.addAttribute(Kind, Value);
531 return addAttributes(C, AttributeSet::get(C, B));
534 AttributeSet AttributeSet::addAttributes(LLVMContext &C,
535 const AttributeSet AS) const {
536 if (!hasAttributes())
539 if (!AS.hasAttributes())
543 for (const auto I : *this)
549 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
550 Attribute::AttrKind Kind) const {
551 if (!hasAttribute(Kind)) return *this;
552 AttrBuilder B(*this);
553 B.removeAttribute(Kind);
557 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
558 StringRef Kind) const {
559 if (!hasAttribute(Kind)) return *this;
560 AttrBuilder B(*this);
561 B.removeAttribute(Kind);
565 AttributeSet AttributeSet::removeAttributes(LLVMContext &C,
566 const AttrBuilder &Attrs) const {
567 AttrBuilder B(*this);
572 unsigned AttributeSet::getNumAttributes() const {
573 return SetNode ? SetNode->getNumAttributes() : 0;
576 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const {
577 return SetNode ? SetNode->hasAttribute(Kind) : false;
580 bool AttributeSet::hasAttribute(StringRef Kind) const {
581 return SetNode ? SetNode->hasAttribute(Kind) : false;
584 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const {
585 return SetNode ? SetNode->getAttribute(Kind) : Attribute();
588 Attribute AttributeSet::getAttribute(StringRef Kind) const {
589 return SetNode ? SetNode->getAttribute(Kind) : Attribute();
592 unsigned AttributeSet::getAlignment() const {
593 return SetNode ? SetNode->getAlignment() : 0;
596 unsigned AttributeSet::getStackAlignment() const {
597 return SetNode ? SetNode->getStackAlignment() : 0;
600 uint64_t AttributeSet::getDereferenceableBytes() const {
601 return SetNode ? SetNode->getDereferenceableBytes() : 0;
604 uint64_t AttributeSet::getDereferenceableOrNullBytes() const {
605 return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0;
608 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const {
609 return SetNode ? SetNode->getAllocSizeArgs()
610 : std::pair<unsigned, Optional<unsigned>>(0, 0);
613 std::string AttributeSet::getAsString(bool InAttrGrp) const {
614 return SetNode ? SetNode->getAsString(InAttrGrp) : "";
617 AttributeSet::iterator AttributeSet::begin() const {
618 return SetNode ? SetNode->begin() : nullptr;
621 AttributeSet::iterator AttributeSet::end() const {
622 return SetNode ? SetNode->end() : nullptr;
625 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
626 LLVM_DUMP_METHOD void AttributeSet::dump() const {
629 dbgs() << getAsString(true) << " }\n";
633 //===----------------------------------------------------------------------===//
634 // AttributeSetNode Definition
635 //===----------------------------------------------------------------------===//
637 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs)
638 : AvailableAttrs(0), NumAttrs(Attrs.size()) {
639 // There's memory after the node where we can store the entries in.
640 std::copy(Attrs.begin(), Attrs.end(), getTrailingObjects<Attribute>());
642 for (const auto I : *this) {
643 if (!I.isStringAttribute()) {
644 AvailableAttrs |= ((uint64_t)1) << I.getKindAsEnum();
649 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
650 ArrayRef<Attribute> Attrs) {
654 // Otherwise, build a key to look up the existing attributes.
655 LLVMContextImpl *pImpl = C.pImpl;
658 SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
659 llvm::sort(SortedAttrs.begin(), SortedAttrs.end());
661 for (const auto Attr : SortedAttrs)
665 AttributeSetNode *PA =
666 pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
668 // If we didn't find any existing attributes of the same shape then create a
669 // new one and insert it.
671 // Coallocate entries after the AttributeSetNode itself.
672 void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size()));
673 PA = new (Mem) AttributeSetNode(SortedAttrs);
674 pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
677 // Return the AttributeSetNode that we found or created.
681 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) {
682 // Add target-independent attributes.
683 SmallVector<Attribute, 8> Attrs;
684 for (Attribute::AttrKind Kind = Attribute::None;
685 Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
686 if (!B.contains(Kind))
691 case Attribute::Alignment:
692 Attr = Attribute::getWithAlignment(C, B.getAlignment());
694 case Attribute::StackAlignment:
695 Attr = Attribute::getWithStackAlignment(C, B.getStackAlignment());
697 case Attribute::Dereferenceable:
698 Attr = Attribute::getWithDereferenceableBytes(
699 C, B.getDereferenceableBytes());
701 case Attribute::DereferenceableOrNull:
702 Attr = Attribute::getWithDereferenceableOrNullBytes(
703 C, B.getDereferenceableOrNullBytes());
705 case Attribute::AllocSize: {
706 auto A = B.getAllocSizeArgs();
707 Attr = Attribute::getWithAllocSizeArgs(C, A.first, A.second);
711 Attr = Attribute::get(C, Kind);
713 Attrs.push_back(Attr);
716 // Add target-dependent (string) attributes.
717 for (const auto &TDA : B.td_attrs())
718 Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second));
720 return get(C, Attrs);
723 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
724 for (const auto I : *this)
725 if (I.hasAttribute(Kind))
730 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
731 if (hasAttribute(Kind)) {
732 for (const auto I : *this)
733 if (I.hasAttribute(Kind))
739 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
740 for (const auto I : *this)
741 if (I.hasAttribute(Kind))
746 unsigned AttributeSetNode::getAlignment() const {
747 for (const auto I : *this)
748 if (I.hasAttribute(Attribute::Alignment))
749 return I.getAlignment();
753 unsigned AttributeSetNode::getStackAlignment() const {
754 for (const auto I : *this)
755 if (I.hasAttribute(Attribute::StackAlignment))
756 return I.getStackAlignment();
760 uint64_t AttributeSetNode::getDereferenceableBytes() const {
761 for (const auto I : *this)
762 if (I.hasAttribute(Attribute::Dereferenceable))
763 return I.getDereferenceableBytes();
767 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
768 for (const auto I : *this)
769 if (I.hasAttribute(Attribute::DereferenceableOrNull))
770 return I.getDereferenceableOrNullBytes();
774 std::pair<unsigned, Optional<unsigned>>
775 AttributeSetNode::getAllocSizeArgs() const {
776 for (const auto I : *this)
777 if (I.hasAttribute(Attribute::AllocSize))
778 return I.getAllocSizeArgs();
779 return std::make_pair(0, 0);
782 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
784 for (iterator I = begin(), E = end(); I != E; ++I) {
787 Str += I->getAsString(InAttrGrp);
792 //===----------------------------------------------------------------------===//
793 // AttributeListImpl Definition
794 //===----------------------------------------------------------------------===//
796 /// Map from AttributeList index to the internal array index. Adding one happens
797 /// to work, but it relies on unsigned integer wrapping. MSVC warns about
798 /// unsigned wrapping in constexpr functions, so write out the conditional. LLVM
799 /// folds it to add anyway.
800 static constexpr unsigned attrIdxToArrayIdx(unsigned Index) {
801 return Index == AttributeList::FunctionIndex ? 0 : Index + 1;
804 AttributeListImpl::AttributeListImpl(LLVMContext &C,
805 ArrayRef<AttributeSet> Sets)
806 : AvailableFunctionAttrs(0), Context(C), NumAttrSets(Sets.size()) {
807 assert(!Sets.empty() && "pointless AttributeListImpl");
809 // There's memory after the node where we can store the entries in.
810 std::copy(Sets.begin(), Sets.end(), getTrailingObjects<AttributeSet>());
812 // Initialize AvailableFunctionAttrs summary bitset.
813 static_assert(Attribute::EndAttrKinds <=
814 sizeof(AvailableFunctionAttrs) * CHAR_BIT,
815 "Too many attributes");
816 static_assert(attrIdxToArrayIdx(AttributeList::FunctionIndex) == 0U,
817 "function should be stored in slot 0");
818 for (const auto I : Sets[0]) {
819 if (!I.isStringAttribute())
820 AvailableFunctionAttrs |= 1ULL << I.getKindAsEnum();
824 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
825 Profile(ID, makeArrayRef(begin(), end()));
828 void AttributeListImpl::Profile(FoldingSetNodeID &ID,
829 ArrayRef<AttributeSet> Sets) {
830 for (const auto &Set : Sets)
831 ID.AddPointer(Set.SetNode);
834 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
835 LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
836 AttributeList(const_cast<AttributeListImpl *>(this)).dump();
840 //===----------------------------------------------------------------------===//
841 // AttributeList Construction and Mutation Methods
842 //===----------------------------------------------------------------------===//
844 AttributeList AttributeList::getImpl(LLVMContext &C,
845 ArrayRef<AttributeSet> AttrSets) {
846 assert(!AttrSets.empty() && "pointless AttributeListImpl");
848 LLVMContextImpl *pImpl = C.pImpl;
850 AttributeListImpl::Profile(ID, AttrSets);
853 AttributeListImpl *PA =
854 pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
856 // If we didn't find any existing attributes of the same shape then
857 // create a new one and insert it.
859 // Coallocate entries after the AttributeListImpl itself.
860 void *Mem = ::operator new(
861 AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()));
862 PA = new (Mem) AttributeListImpl(C, AttrSets);
863 pImpl->AttrsLists.InsertNode(PA, InsertPoint);
866 // Return the AttributesList that we found or created.
867 return AttributeList(PA);
871 AttributeList::get(LLVMContext &C,
872 ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
873 // If there are no attributes then return a null AttributesList pointer.
877 assert(std::is_sorted(Attrs.begin(), Attrs.end(),
878 [](const std::pair<unsigned, Attribute> &LHS,
879 const std::pair<unsigned, Attribute> &RHS) {
880 return LHS.first < RHS.first;
881 }) && "Misordered Attributes list!");
882 assert(llvm::none_of(Attrs,
883 [](const std::pair<unsigned, Attribute> &Pair) {
884 return Pair.second.hasAttribute(Attribute::None);
886 "Pointless attribute!");
888 // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
890 SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
891 for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
892 E = Attrs.end(); I != E; ) {
893 unsigned Index = I->first;
894 SmallVector<Attribute, 4> AttrVec;
895 while (I != E && I->first == Index) {
896 AttrVec.push_back(I->second);
900 AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
903 return get(C, AttrPairVec);
907 AttributeList::get(LLVMContext &C,
908 ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
909 // If there are no attributes then return a null AttributesList pointer.
913 assert(std::is_sorted(Attrs.begin(), Attrs.end(),
914 [](const std::pair<unsigned, AttributeSet> &LHS,
915 const std::pair<unsigned, AttributeSet> &RHS) {
916 return LHS.first < RHS.first;
918 "Misordered Attributes list!");
919 assert(llvm::none_of(Attrs,
920 [](const std::pair<unsigned, AttributeSet> &Pair) {
921 return !Pair.second.hasAttributes();
923 "Pointless attribute!");
925 unsigned MaxIndex = Attrs.back().first;
926 // If the MaxIndex is FunctionIndex and there are other indices in front
927 // of it, we need to use the largest of those to get the right size.
928 if (MaxIndex == FunctionIndex && Attrs.size() > 1)
929 MaxIndex = Attrs[Attrs.size() - 2].first;
931 SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1);
932 for (const auto Pair : Attrs)
933 AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second;
935 return getImpl(C, AttrVec);
938 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs,
939 AttributeSet RetAttrs,
940 ArrayRef<AttributeSet> ArgAttrs) {
941 // Scan from the end to find the last argument with attributes. Most
942 // arguments don't have attributes, so it's nice if we can have fewer unique
943 // AttributeListImpls by dropping empty attribute sets at the end of the list.
944 unsigned NumSets = 0;
945 for (size_t I = ArgAttrs.size(); I != 0; --I) {
946 if (ArgAttrs[I - 1].hasAttributes()) {
952 // Check function and return attributes if we didn't have argument
954 if (RetAttrs.hasAttributes())
956 else if (FnAttrs.hasAttributes())
960 // If all attribute sets were empty, we can use the empty attribute list.
964 SmallVector<AttributeSet, 8> AttrSets;
965 AttrSets.reserve(NumSets);
966 // If we have any attributes, we always have function attributes.
967 AttrSets.push_back(FnAttrs);
969 AttrSets.push_back(RetAttrs);
971 // Drop the empty argument attribute sets at the end.
972 ArgAttrs = ArgAttrs.take_front(NumSets - 2);
973 AttrSets.insert(AttrSets.end(), ArgAttrs.begin(), ArgAttrs.end());
976 return getImpl(C, AttrSets);
979 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
980 const AttrBuilder &B) {
981 if (!B.hasAttributes())
983 Index = attrIdxToArrayIdx(Index);
984 SmallVector<AttributeSet, 8> AttrSets(Index + 1);
985 AttrSets[Index] = AttributeSet::get(C, B);
986 return getImpl(C, AttrSets);
989 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
990 ArrayRef<Attribute::AttrKind> Kinds) {
991 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
992 for (const auto K : Kinds)
993 Attrs.emplace_back(Index, Attribute::get(C, K));
994 return get(C, Attrs);
997 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
998 ArrayRef<StringRef> Kinds) {
999 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1000 for (const auto K : Kinds)
1001 Attrs.emplace_back(Index, Attribute::get(C, K));
1002 return get(C, Attrs);
1005 AttributeList AttributeList::get(LLVMContext &C,
1006 ArrayRef<AttributeList> Attrs) {
1009 if (Attrs.size() == 1)
1012 unsigned MaxSize = 0;
1013 for (const auto List : Attrs)
1014 MaxSize = std::max(MaxSize, List.getNumAttrSets());
1016 // If every list was empty, there is no point in merging the lists.
1020 SmallVector<AttributeSet, 8> NewAttrSets(MaxSize);
1021 for (unsigned I = 0; I < MaxSize; ++I) {
1022 AttrBuilder CurBuilder;
1023 for (const auto List : Attrs)
1024 CurBuilder.merge(List.getAttributes(I - 1));
1025 NewAttrSets[I] = AttributeSet::get(C, CurBuilder);
1028 return getImpl(C, NewAttrSets);
1031 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1032 Attribute::AttrKind Kind) const {
1033 if (hasAttribute(Index, Kind)) return *this;
1035 B.addAttribute(Kind);
1036 return addAttributes(C, Index, B);
1039 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1041 StringRef Value) const {
1043 B.addAttribute(Kind, Value);
1044 return addAttributes(C, Index, B);
1047 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1048 Attribute A) const {
1051 return addAttributes(C, Index, B);
1054 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
1055 const AttrBuilder &B) const {
1056 if (!B.hasAttributes())
1060 return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}});
1063 // FIXME it is not obvious how this should work for alignment. For now, say
1064 // we can't change a known alignment.
1065 unsigned OldAlign = getAttributes(Index).getAlignment();
1066 unsigned NewAlign = B.getAlignment();
1067 assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
1068 "Attempt to change alignment!");
1071 Index = attrIdxToArrayIdx(Index);
1072 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1073 if (Index >= AttrSets.size())
1074 AttrSets.resize(Index + 1);
1076 AttrBuilder Merged(AttrSets[Index]);
1078 AttrSets[Index] = AttributeSet::get(C, Merged);
1080 return getImpl(C, AttrSets);
1083 AttributeList AttributeList::addParamAttribute(LLVMContext &C,
1084 ArrayRef<unsigned> ArgNos,
1085 Attribute A) const {
1086 assert(std::is_sorted(ArgNos.begin(), ArgNos.end()));
1088 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1089 unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex);
1090 if (MaxIndex >= AttrSets.size())
1091 AttrSets.resize(MaxIndex + 1);
1093 for (unsigned ArgNo : ArgNos) {
1094 unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex);
1095 AttrBuilder B(AttrSets[Index]);
1097 AttrSets[Index] = AttributeSet::get(C, B);
1100 return getImpl(C, AttrSets);
1103 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1104 Attribute::AttrKind Kind) const {
1105 if (!hasAttribute(Index, Kind)) return *this;
1107 Index = attrIdxToArrayIdx(Index);
1108 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1109 assert(Index < AttrSets.size());
1111 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1113 return getImpl(C, AttrSets);
1116 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1117 StringRef Kind) const {
1118 if (!hasAttribute(Index, Kind)) return *this;
1120 Index = attrIdxToArrayIdx(Index);
1121 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1122 assert(Index < AttrSets.size());
1124 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1126 return getImpl(C, AttrSets);
1130 AttributeList::removeAttributes(LLVMContext &C, unsigned Index,
1131 const AttrBuilder &AttrsToRemove) const {
1135 Index = attrIdxToArrayIdx(Index);
1136 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1137 if (Index >= AttrSets.size())
1138 AttrSets.resize(Index + 1);
1140 AttrSets[Index] = AttrSets[Index].removeAttributes(C, AttrsToRemove);
1142 return getImpl(C, AttrSets);
1145 AttributeList AttributeList::removeAttributes(LLVMContext &C,
1146 unsigned WithoutIndex) const {
1149 WithoutIndex = attrIdxToArrayIdx(WithoutIndex);
1150 if (WithoutIndex >= getNumAttrSets())
1152 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1153 AttrSets[WithoutIndex] = AttributeSet();
1154 return getImpl(C, AttrSets);
1157 AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C,
1159 uint64_t Bytes) const {
1161 B.addDereferenceableAttr(Bytes);
1162 return addAttributes(C, Index, B);
1166 AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
1167 uint64_t Bytes) const {
1169 B.addDereferenceableOrNullAttr(Bytes);
1170 return addAttributes(C, Index, B);
1174 AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index,
1175 unsigned ElemSizeArg,
1176 const Optional<unsigned> &NumElemsArg) {
1178 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1179 return addAttributes(C, Index, B);
1182 //===----------------------------------------------------------------------===//
1183 // AttributeList Accessor Methods
1184 //===----------------------------------------------------------------------===//
1186 LLVMContext &AttributeList::getContext() const { return pImpl->getContext(); }
1188 AttributeSet AttributeList::getParamAttributes(unsigned ArgNo) const {
1189 return getAttributes(ArgNo + FirstArgIndex);
1192 AttributeSet AttributeList::getRetAttributes() const {
1193 return getAttributes(ReturnIndex);
1196 AttributeSet AttributeList::getFnAttributes() const {
1197 return getAttributes(FunctionIndex);
1200 bool AttributeList::hasAttribute(unsigned Index,
1201 Attribute::AttrKind Kind) const {
1202 return getAttributes(Index).hasAttribute(Kind);
1205 bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const {
1206 return getAttributes(Index).hasAttribute(Kind);
1209 bool AttributeList::hasAttributes(unsigned Index) const {
1210 return getAttributes(Index).hasAttributes();
1213 bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const {
1214 return pImpl && pImpl->hasFnAttribute(Kind);
1217 bool AttributeList::hasFnAttribute(StringRef Kind) const {
1218 return hasAttribute(AttributeList::FunctionIndex, Kind);
1221 bool AttributeList::hasParamAttribute(unsigned ArgNo,
1222 Attribute::AttrKind Kind) const {
1223 return hasAttribute(ArgNo + FirstArgIndex, Kind);
1226 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
1227 unsigned *Index) const {
1228 if (!pImpl) return false;
1230 for (unsigned I = index_begin(), E = index_end(); I != E; ++I) {
1231 if (hasAttribute(I, Attr)) {
1241 Attribute AttributeList::getAttribute(unsigned Index,
1242 Attribute::AttrKind Kind) const {
1243 return getAttributes(Index).getAttribute(Kind);
1246 Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const {
1247 return getAttributes(Index).getAttribute(Kind);
1250 unsigned AttributeList::getRetAlignment() const {
1251 return getAttributes(ReturnIndex).getAlignment();
1254 unsigned AttributeList::getParamAlignment(unsigned ArgNo) const {
1255 return getAttributes(ArgNo + FirstArgIndex).getAlignment();
1258 unsigned AttributeList::getStackAlignment(unsigned Index) const {
1259 return getAttributes(Index).getStackAlignment();
1262 uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const {
1263 return getAttributes(Index).getDereferenceableBytes();
1266 uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const {
1267 return getAttributes(Index).getDereferenceableOrNullBytes();
1270 std::pair<unsigned, Optional<unsigned>>
1271 AttributeList::getAllocSizeArgs(unsigned Index) const {
1272 return getAttributes(Index).getAllocSizeArgs();
1275 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
1276 return getAttributes(Index).getAsString(InAttrGrp);
1279 AttributeSet AttributeList::getAttributes(unsigned Index) const {
1280 Index = attrIdxToArrayIdx(Index);
1281 if (!pImpl || Index >= getNumAttrSets())
1283 return pImpl->begin()[Index];
1286 AttributeList::iterator AttributeList::begin() const {
1287 return pImpl ? pImpl->begin() : nullptr;
1290 AttributeList::iterator AttributeList::end() const {
1291 return pImpl ? pImpl->end() : nullptr;
1294 //===----------------------------------------------------------------------===//
1295 // AttributeList Introspection Methods
1296 //===----------------------------------------------------------------------===//
1298 unsigned AttributeList::getNumAttrSets() const {
1299 return pImpl ? pImpl->NumAttrSets : 0;
1302 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1303 LLVM_DUMP_METHOD void AttributeList::dump() const {
1306 for (unsigned i = index_begin(), e = index_end(); i != e; ++i) {
1307 if (getAttributes(i).hasAttributes())
1308 dbgs() << " { " << i << " => " << getAsString(i) << " }\n";
1315 //===----------------------------------------------------------------------===//
1316 // AttrBuilder Method Implementations
1317 //===----------------------------------------------------------------------===//
1319 // FIXME: Remove this ctor, use AttributeSet.
1320 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) {
1321 AttributeSet AS = AL.getAttributes(Index);
1322 for (const auto &A : AS)
1326 AttrBuilder::AttrBuilder(AttributeSet AS) {
1327 for (const auto &A : AS)
1331 void AttrBuilder::clear() {
1333 TargetDepAttrs.clear();
1334 Alignment = StackAlignment = DerefBytes = DerefOrNullBytes = 0;
1338 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
1339 assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1340 assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
1341 Val != Attribute::Dereferenceable && Val != Attribute::AllocSize &&
1342 "Adding integer attribute without adding a value!");
1347 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
1348 if (Attr.isStringAttribute()) {
1349 addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
1353 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1356 if (Kind == Attribute::Alignment)
1357 Alignment = Attr.getAlignment();
1358 else if (Kind == Attribute::StackAlignment)
1359 StackAlignment = Attr.getStackAlignment();
1360 else if (Kind == Attribute::Dereferenceable)
1361 DerefBytes = Attr.getDereferenceableBytes();
1362 else if (Kind == Attribute::DereferenceableOrNull)
1363 DerefOrNullBytes = Attr.getDereferenceableOrNullBytes();
1364 else if (Kind == Attribute::AllocSize)
1365 AllocSizeArgs = Attr.getValueAsInt();
1369 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
1370 TargetDepAttrs[A] = V;
1374 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1375 assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1378 if (Val == Attribute::Alignment)
1380 else if (Val == Attribute::StackAlignment)
1382 else if (Val == Attribute::Dereferenceable)
1384 else if (Val == Attribute::DereferenceableOrNull)
1385 DerefOrNullBytes = 0;
1386 else if (Val == Attribute::AllocSize)
1392 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) {
1393 remove(A.getAttributes(Index));
1397 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1398 auto I = TargetDepAttrs.find(A);
1399 if (I != TargetDepAttrs.end())
1400 TargetDepAttrs.erase(I);
1404 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
1405 return unpackAllocSizeArgs(AllocSizeArgs);
1408 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1409 if (Align == 0) return *this;
1411 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1412 assert(Align <= 0x40000000 && "Alignment too large.");
1414 Attrs[Attribute::Alignment] = true;
1419 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1420 // Default alignment, allow the target to define how to align it.
1421 if (Align == 0) return *this;
1423 assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1424 assert(Align <= 0x100 && "Alignment too large.");
1426 Attrs[Attribute::StackAlignment] = true;
1427 StackAlignment = Align;
1431 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
1432 if (Bytes == 0) return *this;
1434 Attrs[Attribute::Dereferenceable] = true;
1439 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
1443 Attrs[Attribute::DereferenceableOrNull] = true;
1444 DerefOrNullBytes = Bytes;
1448 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
1449 const Optional<unsigned> &NumElems) {
1450 return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
1453 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
1454 // (0, 0) is our "not present" value, so we need to check for it here.
1455 assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
1457 Attrs[Attribute::AllocSize] = true;
1458 // Reuse existing machinery to store this as a single 64-bit integer so we can
1459 // save a few bytes over using a pair<unsigned, Optional<unsigned>>.
1460 AllocSizeArgs = RawArgs;
1464 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1465 // FIXME: What if both have alignments, but they don't match?!
1467 Alignment = B.Alignment;
1469 if (!StackAlignment)
1470 StackAlignment = B.StackAlignment;
1473 DerefBytes = B.DerefBytes;
1475 if (!DerefOrNullBytes)
1476 DerefOrNullBytes = B.DerefOrNullBytes;
1479 AllocSizeArgs = B.AllocSizeArgs;
1483 for (auto I : B.td_attrs())
1484 TargetDepAttrs[I.first] = I.second;
1489 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
1490 // FIXME: What if both have alignments, but they don't match?!
1494 if (B.StackAlignment)
1500 if (B.DerefOrNullBytes)
1501 DerefOrNullBytes = 0;
1503 if (B.AllocSizeArgs)
1508 for (auto I : B.td_attrs())
1509 TargetDepAttrs.erase(I.first);
1514 bool AttrBuilder::overlaps(const AttrBuilder &B) const {
1515 // First check if any of the target independent attributes overlap.
1516 if ((Attrs & B.Attrs).any())
1519 // Then check if any target dependent ones do.
1520 for (const auto &I : td_attrs())
1521 if (B.contains(I.first))
1527 bool AttrBuilder::contains(StringRef A) const {
1528 return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1531 bool AttrBuilder::hasAttributes() const {
1532 return !Attrs.none() || !TargetDepAttrs.empty();
1535 bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const {
1536 AttributeSet AS = AL.getAttributes(Index);
1538 for (const auto Attr : AS) {
1539 if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1540 if (contains(Attr.getKindAsEnum()))
1543 assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1544 return contains(Attr.getKindAsString());
1551 bool AttrBuilder::hasAlignmentAttr() const {
1552 return Alignment != 0;
1555 bool AttrBuilder::operator==(const AttrBuilder &B) {
1556 if (Attrs != B.Attrs)
1559 for (td_const_iterator I = TargetDepAttrs.begin(),
1560 E = TargetDepAttrs.end(); I != E; ++I)
1561 if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1564 return Alignment == B.Alignment && StackAlignment == B.StackAlignment &&
1565 DerefBytes == B.DerefBytes;
1568 //===----------------------------------------------------------------------===//
1569 // AttributeFuncs Function Defintions
1570 //===----------------------------------------------------------------------===//
1572 /// Which attributes cannot be applied to a type.
1573 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) {
1574 AttrBuilder Incompatible;
1576 if (!Ty->isIntegerTy())
1577 // Attribute that only apply to integers.
1578 Incompatible.addAttribute(Attribute::SExt)
1579 .addAttribute(Attribute::ZExt);
1581 if (!Ty->isPointerTy())
1582 // Attribute that only apply to pointers.
1583 Incompatible.addAttribute(Attribute::ByVal)
1584 .addAttribute(Attribute::Nest)
1585 .addAttribute(Attribute::NoAlias)
1586 .addAttribute(Attribute::NoCapture)
1587 .addAttribute(Attribute::NonNull)
1588 .addDereferenceableAttr(1) // the int here is ignored
1589 .addDereferenceableOrNullAttr(1) // the int here is ignored
1590 .addAttribute(Attribute::ReadNone)
1591 .addAttribute(Attribute::ReadOnly)
1592 .addAttribute(Attribute::StructRet)
1593 .addAttribute(Attribute::InAlloca);
1595 return Incompatible;
1598 template<typename AttrClass>
1599 static bool isEqual(const Function &Caller, const Function &Callee) {
1600 return Caller.getFnAttribute(AttrClass::getKind()) ==
1601 Callee.getFnAttribute(AttrClass::getKind());
1604 /// Compute the logical AND of the attributes of the caller and the
1607 /// This function sets the caller's attribute to false if the callee's attribute
1609 template<typename AttrClass>
1610 static void setAND(Function &Caller, const Function &Callee) {
1611 if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
1612 !AttrClass::isSet(Callee, AttrClass::getKind()))
1613 AttrClass::set(Caller, AttrClass::getKind(), false);
1616 /// Compute the logical OR of the attributes of the caller and the
1619 /// This function sets the caller's attribute to true if the callee's attribute
1621 template<typename AttrClass>
1622 static void setOR(Function &Caller, const Function &Callee) {
1623 if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
1624 AttrClass::isSet(Callee, AttrClass::getKind()))
1625 AttrClass::set(Caller, AttrClass::getKind(), true);
1628 /// If the inlined function had a higher stack protection level than the
1629 /// calling function, then bump up the caller's stack protection level.
1630 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
1631 // If upgrading the SSP attribute, clear out the old SSP Attributes first.
1632 // Having multiple SSP attributes doesn't actually hurt, but it adds useless
1633 // clutter to the IR.
1634 AttrBuilder OldSSPAttr;
1635 OldSSPAttr.addAttribute(Attribute::StackProtect)
1636 .addAttribute(Attribute::StackProtectStrong)
1637 .addAttribute(Attribute::StackProtectReq);
1639 if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
1640 Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1641 Caller.addFnAttr(Attribute::StackProtectReq);
1642 } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
1643 !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
1644 Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1645 Caller.addFnAttr(Attribute::StackProtectStrong);
1646 } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
1647 !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
1648 !Caller.hasFnAttribute(Attribute::StackProtectStrong))
1649 Caller.addFnAttr(Attribute::StackProtect);
1652 /// If the inlined function required stack probes, then ensure that
1653 /// the calling function has those too.
1654 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) {
1655 if (!Caller.hasFnAttribute("probe-stack") &&
1656 Callee.hasFnAttribute("probe-stack")) {
1657 Caller.addFnAttr(Callee.getFnAttribute("probe-stack"));
1661 /// If the inlined function defines the size of guard region
1662 /// on the stack, then ensure that the calling function defines a guard region
1663 /// that is no larger.
1665 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) {
1666 if (Callee.hasFnAttribute("stack-probe-size")) {
1667 uint64_t CalleeStackProbeSize;
1668 Callee.getFnAttribute("stack-probe-size")
1670 .getAsInteger(0, CalleeStackProbeSize);
1671 if (Caller.hasFnAttribute("stack-probe-size")) {
1672 uint64_t CallerStackProbeSize;
1673 Caller.getFnAttribute("stack-probe-size")
1675 .getAsInteger(0, CallerStackProbeSize);
1676 if (CallerStackProbeSize > CalleeStackProbeSize) {
1677 Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1680 Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1685 /// If the inlined function defines a min legal vector width, then ensure
1686 /// the calling function has the same or larger min legal vector width. This
1687 /// function is called after the inlining decision has been made so we have to
1688 /// merge the attribute this way. Heuristics that would use
1689 /// min-legal-vector-width to determine inline compatibility would need to be
1690 /// handled as part of inline cost analysis.
1692 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) {
1693 if (Callee.hasFnAttribute("min-legal-vector-width")) {
1694 uint64_t CalleeVectorWidth;
1695 Callee.getFnAttribute("min-legal-vector-width")
1697 .getAsInteger(0, CalleeVectorWidth);
1698 if (Caller.hasFnAttribute("min-legal-vector-width")) {
1699 uint64_t CallerVectorWidth;
1700 Caller.getFnAttribute("min-legal-vector-width")
1702 .getAsInteger(0, CallerVectorWidth);
1703 if (CallerVectorWidth < CalleeVectorWidth) {
1704 Caller.addFnAttr(Callee.getFnAttribute("min-legal-vector-width"));
1707 Caller.addFnAttr(Callee.getFnAttribute("min-legal-vector-width"));
1712 /// If the inlined function has "null-pointer-is-valid=true" attribute,
1713 /// set this attribute in the caller post inlining.
1715 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) {
1716 if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) {
1717 Caller.addFnAttr(Callee.getFnAttribute("null-pointer-is-valid"));
1721 #define GET_ATTR_COMPAT_FUNC
1722 #include "AttributesCompatFunc.inc"
1724 bool AttributeFuncs::areInlineCompatible(const Function &Caller,
1725 const Function &Callee) {
1726 return hasCompatibleFnAttrs(Caller, Callee);
1729 void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
1730 const Function &Callee) {
1731 mergeFnAttrs(Caller, Callee);