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