1 //===- Attributes.cpp - Implement AttributesList --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // \file 10 // This file implements the Attribute, AttributeImpl, AttrBuilder, 11 // AttributeListImpl, and AttributeList classes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/IR/Attributes.h" 16 #include "AttributeImpl.h" 17 #include "LLVMContextImpl.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/FoldingSet.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/StringSwitch.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" 36 #include <algorithm> 37 #include <cassert> 38 #include <climits> 39 #include <cstddef> 40 #include <cstdint> 41 #include <limits> 42 #include <string> 43 #include <tuple> 44 #include <utility> 45 46 using namespace llvm; 47 48 //===----------------------------------------------------------------------===// 49 // Attribute Construction Methods 50 //===----------------------------------------------------------------------===// 51 52 // allocsize has two integer arguments, but because they're both 32 bits, we can 53 // pack them into one 64-bit value, at the cost of making said value 54 // nonsensical. 55 // 56 // In order to do this, we need to reserve one value of the second (optional) 57 // allocsize argument to signify "not present." 58 static const unsigned AllocSizeNumElemsNotPresent = -1; 59 60 static uint64_t packAllocSizeArgs(unsigned ElemSizeArg, 61 const Optional<unsigned> &NumElemsArg) { 62 assert((!NumElemsArg.hasValue() || 63 *NumElemsArg != AllocSizeNumElemsNotPresent) && 64 "Attempting to pack a reserved value"); 65 66 return uint64_t(ElemSizeArg) << 32 | 67 NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent); 68 } 69 70 static std::pair<unsigned, Optional<unsigned>> 71 unpackAllocSizeArgs(uint64_t Num) { 72 unsigned NumElems = Num & std::numeric_limits<unsigned>::max(); 73 unsigned ElemSizeArg = Num >> 32; 74 75 Optional<unsigned> NumElemsArg; 76 if (NumElems != AllocSizeNumElemsNotPresent) 77 NumElemsArg = NumElems; 78 return std::make_pair(ElemSizeArg, NumElemsArg); 79 } 80 81 static uint64_t packVScaleRangeArgs(unsigned MinValue, 82 Optional<unsigned> MaxValue) { 83 return uint64_t(MinValue) << 32 | MaxValue.getValueOr(0); 84 } 85 86 static std::pair<unsigned, Optional<unsigned>> 87 unpackVScaleRangeArgs(uint64_t Value) { 88 unsigned MaxValue = Value & std::numeric_limits<unsigned>::max(); 89 unsigned MinValue = Value >> 32; 90 91 return std::make_pair(MinValue, 92 MaxValue > 0 ? MaxValue : Optional<unsigned>()); 93 } 94 95 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, 96 uint64_t Val) { 97 if (Val) 98 assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute"); 99 else 100 assert(Attribute::isEnumAttrKind(Kind) && "Not an enum attribute"); 101 102 LLVMContextImpl *pImpl = Context.pImpl; 103 FoldingSetNodeID ID; 104 ID.AddInteger(Kind); 105 if (Val) ID.AddInteger(Val); 106 107 void *InsertPoint; 108 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 109 110 if (!PA) { 111 // If we didn't find any existing attributes of the same shape then create a 112 // new one and insert it. 113 if (!Val) 114 PA = new (pImpl->Alloc) EnumAttributeImpl(Kind); 115 else 116 PA = new (pImpl->Alloc) IntAttributeImpl(Kind, Val); 117 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 118 } 119 120 // Return the Attribute that we found or created. 121 return Attribute(PA); 122 } 123 124 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) { 125 LLVMContextImpl *pImpl = Context.pImpl; 126 FoldingSetNodeID ID; 127 ID.AddString(Kind); 128 if (!Val.empty()) ID.AddString(Val); 129 130 void *InsertPoint; 131 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 132 133 if (!PA) { 134 // If we didn't find any existing attributes of the same shape then create a 135 // new one and insert it. 136 void *Mem = 137 pImpl->Alloc.Allocate(StringAttributeImpl::totalSizeToAlloc(Kind, Val), 138 alignof(StringAttributeImpl)); 139 PA = new (Mem) StringAttributeImpl(Kind, Val); 140 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 141 } 142 143 // Return the Attribute that we found or created. 144 return Attribute(PA); 145 } 146 147 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, 148 Type *Ty) { 149 assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute"); 150 LLVMContextImpl *pImpl = Context.pImpl; 151 FoldingSetNodeID ID; 152 ID.AddInteger(Kind); 153 ID.AddPointer(Ty); 154 155 void *InsertPoint; 156 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 157 158 if (!PA) { 159 // If we didn't find any existing attributes of the same shape then create a 160 // new one and insert it. 161 PA = new (pImpl->Alloc) TypeAttributeImpl(Kind, Ty); 162 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 163 } 164 165 // Return the Attribute that we found or created. 166 return Attribute(PA); 167 } 168 169 Attribute Attribute::getWithAlignment(LLVMContext &Context, Align A) { 170 assert(A <= llvm::Value::MaximumAlignment && "Alignment too large."); 171 return get(Context, Alignment, A.value()); 172 } 173 174 Attribute Attribute::getWithStackAlignment(LLVMContext &Context, Align A) { 175 assert(A <= 0x100 && "Alignment too large."); 176 return get(Context, StackAlignment, A.value()); 177 } 178 179 Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context, 180 uint64_t Bytes) { 181 assert(Bytes && "Bytes must be non-zero."); 182 return get(Context, Dereferenceable, Bytes); 183 } 184 185 Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context, 186 uint64_t Bytes) { 187 assert(Bytes && "Bytes must be non-zero."); 188 return get(Context, DereferenceableOrNull, Bytes); 189 } 190 191 Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) { 192 return get(Context, ByVal, Ty); 193 } 194 195 Attribute Attribute::getWithStructRetType(LLVMContext &Context, Type *Ty) { 196 return get(Context, StructRet, Ty); 197 } 198 199 Attribute Attribute::getWithByRefType(LLVMContext &Context, Type *Ty) { 200 return get(Context, ByRef, Ty); 201 } 202 203 Attribute Attribute::getWithPreallocatedType(LLVMContext &Context, Type *Ty) { 204 return get(Context, Preallocated, Ty); 205 } 206 207 Attribute Attribute::getWithInAllocaType(LLVMContext &Context, Type *Ty) { 208 return get(Context, InAlloca, Ty); 209 } 210 211 Attribute 212 Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg, 213 const Optional<unsigned> &NumElemsArg) { 214 assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) && 215 "Invalid allocsize arguments -- given allocsize(0, 0)"); 216 return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg)); 217 } 218 219 Attribute Attribute::getWithVScaleRangeArgs(LLVMContext &Context, 220 unsigned MinValue, 221 unsigned MaxValue) { 222 return get(Context, VScaleRange, packVScaleRangeArgs(MinValue, MaxValue)); 223 } 224 225 Attribute::AttrKind Attribute::getAttrKindFromName(StringRef AttrName) { 226 return StringSwitch<Attribute::AttrKind>(AttrName) 227 #define GET_ATTR_NAMES 228 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 229 .Case(#DISPLAY_NAME, Attribute::ENUM_NAME) 230 #include "llvm/IR/Attributes.inc" 231 .Default(Attribute::None); 232 } 233 234 StringRef Attribute::getNameFromAttrKind(Attribute::AttrKind AttrKind) { 235 switch (AttrKind) { 236 #define GET_ATTR_NAMES 237 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 238 case Attribute::ENUM_NAME: \ 239 return #DISPLAY_NAME; 240 #include "llvm/IR/Attributes.inc" 241 case Attribute::None: 242 return "none"; 243 default: 244 llvm_unreachable("invalid Kind"); 245 } 246 } 247 248 bool Attribute::isExistingAttribute(StringRef Name) { 249 return StringSwitch<bool>(Name) 250 #define GET_ATTR_NAMES 251 #define ATTRIBUTE_ALL(ENUM_NAME, DISPLAY_NAME) .Case(#DISPLAY_NAME, true) 252 #include "llvm/IR/Attributes.inc" 253 .Default(false); 254 } 255 256 //===----------------------------------------------------------------------===// 257 // Attribute Accessor Methods 258 //===----------------------------------------------------------------------===// 259 260 bool Attribute::isEnumAttribute() const { 261 return pImpl && pImpl->isEnumAttribute(); 262 } 263 264 bool Attribute::isIntAttribute() const { 265 return pImpl && pImpl->isIntAttribute(); 266 } 267 268 bool Attribute::isStringAttribute() const { 269 return pImpl && pImpl->isStringAttribute(); 270 } 271 272 bool Attribute::isTypeAttribute() const { 273 return pImpl && pImpl->isTypeAttribute(); 274 } 275 276 Attribute::AttrKind Attribute::getKindAsEnum() const { 277 if (!pImpl) return None; 278 assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) && 279 "Invalid attribute type to get the kind as an enum!"); 280 return pImpl->getKindAsEnum(); 281 } 282 283 uint64_t Attribute::getValueAsInt() const { 284 if (!pImpl) return 0; 285 assert(isIntAttribute() && 286 "Expected the attribute to be an integer attribute!"); 287 return pImpl->getValueAsInt(); 288 } 289 290 bool Attribute::getValueAsBool() const { 291 if (!pImpl) return false; 292 assert(isStringAttribute() && 293 "Expected the attribute to be a string attribute!"); 294 return pImpl->getValueAsBool(); 295 } 296 297 StringRef Attribute::getKindAsString() const { 298 if (!pImpl) return {}; 299 assert(isStringAttribute() && 300 "Invalid attribute type to get the kind as a string!"); 301 return pImpl->getKindAsString(); 302 } 303 304 StringRef Attribute::getValueAsString() const { 305 if (!pImpl) return {}; 306 assert(isStringAttribute() && 307 "Invalid attribute type to get the value as a string!"); 308 return pImpl->getValueAsString(); 309 } 310 311 Type *Attribute::getValueAsType() const { 312 if (!pImpl) return {}; 313 assert(isTypeAttribute() && 314 "Invalid attribute type to get the value as a type!"); 315 return pImpl->getValueAsType(); 316 } 317 318 319 bool Attribute::hasAttribute(AttrKind Kind) const { 320 return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None); 321 } 322 323 bool Attribute::hasAttribute(StringRef Kind) const { 324 if (!isStringAttribute()) return false; 325 return pImpl && pImpl->hasAttribute(Kind); 326 } 327 328 MaybeAlign Attribute::getAlignment() const { 329 assert(hasAttribute(Attribute::Alignment) && 330 "Trying to get alignment from non-alignment attribute!"); 331 return MaybeAlign(pImpl->getValueAsInt()); 332 } 333 334 MaybeAlign Attribute::getStackAlignment() const { 335 assert(hasAttribute(Attribute::StackAlignment) && 336 "Trying to get alignment from non-alignment attribute!"); 337 return MaybeAlign(pImpl->getValueAsInt()); 338 } 339 340 uint64_t Attribute::getDereferenceableBytes() const { 341 assert(hasAttribute(Attribute::Dereferenceable) && 342 "Trying to get dereferenceable bytes from " 343 "non-dereferenceable attribute!"); 344 return pImpl->getValueAsInt(); 345 } 346 347 uint64_t Attribute::getDereferenceableOrNullBytes() const { 348 assert(hasAttribute(Attribute::DereferenceableOrNull) && 349 "Trying to get dereferenceable bytes from " 350 "non-dereferenceable attribute!"); 351 return pImpl->getValueAsInt(); 352 } 353 354 std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const { 355 assert(hasAttribute(Attribute::AllocSize) && 356 "Trying to get allocsize args from non-allocsize attribute"); 357 return unpackAllocSizeArgs(pImpl->getValueAsInt()); 358 } 359 360 unsigned Attribute::getVScaleRangeMin() const { 361 assert(hasAttribute(Attribute::VScaleRange) && 362 "Trying to get vscale args from non-vscale attribute"); 363 return unpackVScaleRangeArgs(pImpl->getValueAsInt()).first; 364 } 365 366 Optional<unsigned> Attribute::getVScaleRangeMax() const { 367 assert(hasAttribute(Attribute::VScaleRange) && 368 "Trying to get vscale args from non-vscale attribute"); 369 return unpackVScaleRangeArgs(pImpl->getValueAsInt()).second; 370 } 371 372 std::string Attribute::getAsString(bool InAttrGrp) const { 373 if (!pImpl) return {}; 374 375 if (isEnumAttribute()) 376 return getNameFromAttrKind(getKindAsEnum()).str(); 377 378 if (isTypeAttribute()) { 379 std::string Result = getNameFromAttrKind(getKindAsEnum()).str(); 380 Result += '('; 381 raw_string_ostream OS(Result); 382 getValueAsType()->print(OS, false, true); 383 OS.flush(); 384 Result += ')'; 385 return Result; 386 } 387 388 // FIXME: These should be output like this: 389 // 390 // align=4 391 // alignstack=8 392 // 393 if (hasAttribute(Attribute::Alignment)) { 394 std::string Result; 395 Result += "align"; 396 Result += (InAttrGrp) ? "=" : " "; 397 Result += utostr(getValueAsInt()); 398 return Result; 399 } 400 401 auto AttrWithBytesToString = [&](const char *Name) { 402 std::string Result; 403 Result += Name; 404 if (InAttrGrp) { 405 Result += "="; 406 Result += utostr(getValueAsInt()); 407 } else { 408 Result += "("; 409 Result += utostr(getValueAsInt()); 410 Result += ")"; 411 } 412 return Result; 413 }; 414 415 if (hasAttribute(Attribute::StackAlignment)) 416 return AttrWithBytesToString("alignstack"); 417 418 if (hasAttribute(Attribute::Dereferenceable)) 419 return AttrWithBytesToString("dereferenceable"); 420 421 if (hasAttribute(Attribute::DereferenceableOrNull)) 422 return AttrWithBytesToString("dereferenceable_or_null"); 423 424 if (hasAttribute(Attribute::AllocSize)) { 425 unsigned ElemSize; 426 Optional<unsigned> NumElems; 427 std::tie(ElemSize, NumElems) = getAllocSizeArgs(); 428 429 std::string Result = "allocsize("; 430 Result += utostr(ElemSize); 431 if (NumElems.hasValue()) { 432 Result += ','; 433 Result += utostr(*NumElems); 434 } 435 Result += ')'; 436 return Result; 437 } 438 439 if (hasAttribute(Attribute::VScaleRange)) { 440 unsigned MinValue = getVScaleRangeMin(); 441 Optional<unsigned> MaxValue = getVScaleRangeMax(); 442 443 std::string Result = "vscale_range("; 444 Result += utostr(MinValue); 445 Result += ','; 446 Result += utostr(MaxValue.getValueOr(0)); 447 Result += ')'; 448 return Result; 449 } 450 451 // Convert target-dependent attributes to strings of the form: 452 // 453 // "kind" 454 // "kind" = "value" 455 // 456 if (isStringAttribute()) { 457 std::string Result; 458 { 459 raw_string_ostream OS(Result); 460 OS << '"' << getKindAsString() << '"'; 461 462 // Since some attribute strings contain special characters that cannot be 463 // printable, those have to be escaped to make the attribute value 464 // printable as is. e.g. "\01__gnu_mcount_nc" 465 const auto &AttrVal = pImpl->getValueAsString(); 466 if (!AttrVal.empty()) { 467 OS << "=\""; 468 printEscapedString(AttrVal, OS); 469 OS << "\""; 470 } 471 } 472 return Result; 473 } 474 475 llvm_unreachable("Unknown attribute"); 476 } 477 478 bool Attribute::hasParentContext(LLVMContext &C) const { 479 assert(isValid() && "invalid Attribute doesn't refer to any context"); 480 FoldingSetNodeID ID; 481 pImpl->Profile(ID); 482 void *Unused; 483 return C.pImpl->AttrsSet.FindNodeOrInsertPos(ID, Unused) == pImpl; 484 } 485 486 bool Attribute::operator<(Attribute A) const { 487 if (!pImpl && !A.pImpl) return false; 488 if (!pImpl) return true; 489 if (!A.pImpl) return false; 490 return *pImpl < *A.pImpl; 491 } 492 493 void Attribute::Profile(FoldingSetNodeID &ID) const { 494 ID.AddPointer(pImpl); 495 } 496 497 enum AttributeProperty { 498 FnAttr = (1 << 0), 499 ParamAttr = (1 << 1), 500 RetAttr = (1 << 2), 501 }; 502 503 #define GET_ATTR_PROP_TABLE 504 #include "llvm/IR/Attributes.inc" 505 506 static bool hasAttributeProperty(Attribute::AttrKind Kind, 507 AttributeProperty Prop) { 508 unsigned Index = Kind - 1; 509 assert(Index < sizeof(AttrPropTable) / sizeof(AttrPropTable[0]) && 510 "Invalid attribute kind"); 511 return AttrPropTable[Index] & Prop; 512 } 513 514 bool Attribute::canUseAsFnAttr(AttrKind Kind) { 515 return hasAttributeProperty(Kind, AttributeProperty::FnAttr); 516 } 517 518 bool Attribute::canUseAsParamAttr(AttrKind Kind) { 519 return hasAttributeProperty(Kind, AttributeProperty::ParamAttr); 520 } 521 522 bool Attribute::canUseAsRetAttr(AttrKind Kind) { 523 return hasAttributeProperty(Kind, AttributeProperty::RetAttr); 524 } 525 526 //===----------------------------------------------------------------------===// 527 // AttributeImpl Definition 528 //===----------------------------------------------------------------------===// 529 530 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const { 531 if (isStringAttribute()) return false; 532 return getKindAsEnum() == A; 533 } 534 535 bool AttributeImpl::hasAttribute(StringRef Kind) const { 536 if (!isStringAttribute()) return false; 537 return getKindAsString() == Kind; 538 } 539 540 Attribute::AttrKind AttributeImpl::getKindAsEnum() const { 541 assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute()); 542 return static_cast<const EnumAttributeImpl *>(this)->getEnumKind(); 543 } 544 545 uint64_t AttributeImpl::getValueAsInt() const { 546 assert(isIntAttribute()); 547 return static_cast<const IntAttributeImpl *>(this)->getValue(); 548 } 549 550 bool AttributeImpl::getValueAsBool() const { 551 assert(getValueAsString().empty() || getValueAsString() == "false" || getValueAsString() == "true"); 552 return getValueAsString() == "true"; 553 } 554 555 StringRef AttributeImpl::getKindAsString() const { 556 assert(isStringAttribute()); 557 return static_cast<const StringAttributeImpl *>(this)->getStringKind(); 558 } 559 560 StringRef AttributeImpl::getValueAsString() const { 561 assert(isStringAttribute()); 562 return static_cast<const StringAttributeImpl *>(this)->getStringValue(); 563 } 564 565 Type *AttributeImpl::getValueAsType() const { 566 assert(isTypeAttribute()); 567 return static_cast<const TypeAttributeImpl *>(this)->getTypeValue(); 568 } 569 570 bool AttributeImpl::operator<(const AttributeImpl &AI) const { 571 if (this == &AI) 572 return false; 573 574 // This sorts the attributes with Attribute::AttrKinds coming first (sorted 575 // relative to their enum value) and then strings. 576 if (!isStringAttribute()) { 577 if (AI.isStringAttribute()) 578 return true; 579 if (getKindAsEnum() != AI.getKindAsEnum()) 580 return getKindAsEnum() < AI.getKindAsEnum(); 581 assert(!AI.isEnumAttribute() && "Non-unique attribute"); 582 assert(!AI.isTypeAttribute() && "Comparison of types would be unstable"); 583 // TODO: Is this actually needed? 584 assert(AI.isIntAttribute() && "Only possibility left"); 585 return getValueAsInt() < AI.getValueAsInt(); 586 } 587 588 if (!AI.isStringAttribute()) 589 return false; 590 if (getKindAsString() == AI.getKindAsString()) 591 return getValueAsString() < AI.getValueAsString(); 592 return getKindAsString() < AI.getKindAsString(); 593 } 594 595 //===----------------------------------------------------------------------===// 596 // AttributeSet Definition 597 //===----------------------------------------------------------------------===// 598 599 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) { 600 return AttributeSet(AttributeSetNode::get(C, B)); 601 } 602 603 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) { 604 return AttributeSet(AttributeSetNode::get(C, Attrs)); 605 } 606 607 AttributeSet AttributeSet::addAttribute(LLVMContext &C, 608 Attribute::AttrKind Kind) const { 609 if (hasAttribute(Kind)) return *this; 610 AttrBuilder B; 611 B.addAttribute(Kind); 612 return addAttributes(C, AttributeSet::get(C, B)); 613 } 614 615 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind, 616 StringRef Value) const { 617 AttrBuilder B; 618 B.addAttribute(Kind, Value); 619 return addAttributes(C, AttributeSet::get(C, B)); 620 } 621 622 AttributeSet AttributeSet::addAttributes(LLVMContext &C, 623 const AttributeSet AS) const { 624 if (!hasAttributes()) 625 return AS; 626 627 if (!AS.hasAttributes()) 628 return *this; 629 630 AttrBuilder B(AS); 631 for (const auto &I : *this) 632 B.addAttribute(I); 633 634 return get(C, B); 635 } 636 637 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, 638 Attribute::AttrKind Kind) const { 639 if (!hasAttribute(Kind)) return *this; 640 AttrBuilder B(*this); 641 B.removeAttribute(Kind); 642 return get(C, B); 643 } 644 645 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, 646 StringRef Kind) const { 647 if (!hasAttribute(Kind)) return *this; 648 AttrBuilder B(*this); 649 B.removeAttribute(Kind); 650 return get(C, B); 651 } 652 653 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, 654 const AttrBuilder &Attrs) const { 655 AttrBuilder B(*this); 656 // If there is nothing to remove, directly return the original set. 657 if (!B.overlaps(Attrs)) 658 return *this; 659 660 B.remove(Attrs); 661 return get(C, B); 662 } 663 664 unsigned AttributeSet::getNumAttributes() const { 665 return SetNode ? SetNode->getNumAttributes() : 0; 666 } 667 668 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const { 669 return SetNode ? SetNode->hasAttribute(Kind) : false; 670 } 671 672 bool AttributeSet::hasAttribute(StringRef Kind) const { 673 return SetNode ? SetNode->hasAttribute(Kind) : false; 674 } 675 676 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const { 677 return SetNode ? SetNode->getAttribute(Kind) : Attribute(); 678 } 679 680 Attribute AttributeSet::getAttribute(StringRef Kind) const { 681 return SetNode ? SetNode->getAttribute(Kind) : Attribute(); 682 } 683 684 MaybeAlign AttributeSet::getAlignment() const { 685 return SetNode ? SetNode->getAlignment() : None; 686 } 687 688 MaybeAlign AttributeSet::getStackAlignment() const { 689 return SetNode ? SetNode->getStackAlignment() : None; 690 } 691 692 uint64_t AttributeSet::getDereferenceableBytes() const { 693 return SetNode ? SetNode->getDereferenceableBytes() : 0; 694 } 695 696 uint64_t AttributeSet::getDereferenceableOrNullBytes() const { 697 return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0; 698 } 699 700 Type *AttributeSet::getByRefType() const { 701 return SetNode ? SetNode->getAttributeType(Attribute::ByRef) : nullptr; 702 } 703 704 Type *AttributeSet::getByValType() const { 705 return SetNode ? SetNode->getAttributeType(Attribute::ByVal) : nullptr; 706 } 707 708 Type *AttributeSet::getStructRetType() const { 709 return SetNode ? SetNode->getAttributeType(Attribute::StructRet) : nullptr; 710 } 711 712 Type *AttributeSet::getPreallocatedType() const { 713 return SetNode ? SetNode->getAttributeType(Attribute::Preallocated) : nullptr; 714 } 715 716 Type *AttributeSet::getInAllocaType() const { 717 return SetNode ? SetNode->getAttributeType(Attribute::InAlloca) : nullptr; 718 } 719 720 Type *AttributeSet::getElementType() const { 721 return SetNode ? SetNode->getAttributeType(Attribute::ElementType) : nullptr; 722 } 723 724 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const { 725 return SetNode ? SetNode->getAllocSizeArgs() 726 : std::pair<unsigned, Optional<unsigned>>(0, 0); 727 } 728 729 unsigned AttributeSet::getVScaleRangeMin() const { 730 return SetNode ? SetNode->getVScaleRangeMin() : 1; 731 } 732 733 Optional<unsigned> AttributeSet::getVScaleRangeMax() const { 734 return SetNode ? SetNode->getVScaleRangeMax() : None; 735 } 736 737 std::string AttributeSet::getAsString(bool InAttrGrp) const { 738 return SetNode ? SetNode->getAsString(InAttrGrp) : ""; 739 } 740 741 bool AttributeSet::hasParentContext(LLVMContext &C) const { 742 assert(hasAttributes() && "empty AttributeSet doesn't refer to any context"); 743 FoldingSetNodeID ID; 744 SetNode->Profile(ID); 745 void *Unused; 746 return C.pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, Unused) == SetNode; 747 } 748 749 AttributeSet::iterator AttributeSet::begin() const { 750 return SetNode ? SetNode->begin() : nullptr; 751 } 752 753 AttributeSet::iterator AttributeSet::end() const { 754 return SetNode ? SetNode->end() : nullptr; 755 } 756 757 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 758 LLVM_DUMP_METHOD void AttributeSet::dump() const { 759 dbgs() << "AS =\n"; 760 dbgs() << " { "; 761 dbgs() << getAsString(true) << " }\n"; 762 } 763 #endif 764 765 //===----------------------------------------------------------------------===// 766 // AttributeSetNode Definition 767 //===----------------------------------------------------------------------===// 768 769 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs) 770 : NumAttrs(Attrs.size()) { 771 // There's memory after the node where we can store the entries in. 772 llvm::copy(Attrs, getTrailingObjects<Attribute>()); 773 774 for (const auto &I : *this) { 775 if (I.isStringAttribute()) 776 StringAttrs.insert({ I.getKindAsString(), I }); 777 else 778 AvailableAttrs.addAttribute(I.getKindAsEnum()); 779 } 780 } 781 782 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, 783 ArrayRef<Attribute> Attrs) { 784 SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end()); 785 llvm::sort(SortedAttrs); 786 return getSorted(C, SortedAttrs); 787 } 788 789 AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C, 790 ArrayRef<Attribute> SortedAttrs) { 791 if (SortedAttrs.empty()) 792 return nullptr; 793 794 // Build a key to look up the existing attributes. 795 LLVMContextImpl *pImpl = C.pImpl; 796 FoldingSetNodeID ID; 797 798 assert(llvm::is_sorted(SortedAttrs) && "Expected sorted attributes!"); 799 for (const auto &Attr : SortedAttrs) 800 Attr.Profile(ID); 801 802 void *InsertPoint; 803 AttributeSetNode *PA = 804 pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint); 805 806 // If we didn't find any existing attributes of the same shape then create a 807 // new one and insert it. 808 if (!PA) { 809 // Coallocate entries after the AttributeSetNode itself. 810 void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size())); 811 PA = new (Mem) AttributeSetNode(SortedAttrs); 812 pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint); 813 } 814 815 // Return the AttributeSetNode that we found or created. 816 return PA; 817 } 818 819 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) { 820 // Add target-independent attributes. 821 SmallVector<Attribute, 8> Attrs; 822 for (Attribute::AttrKind Kind = Attribute::None; 823 Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) { 824 if (!B.contains(Kind)) 825 continue; 826 827 Attribute Attr; 828 if (Attribute::isTypeAttrKind(Kind)) 829 Attr = Attribute::get(C, Kind, B.getTypeAttr(Kind)); 830 else if (Attribute::isIntAttrKind(Kind)) 831 Attr = Attribute::get(C, Kind, B.getRawIntAttr(Kind)); 832 else 833 Attr = Attribute::get(C, Kind); 834 Attrs.push_back(Attr); 835 } 836 837 // Add target-dependent (string) attributes. 838 for (const auto &TDA : B.td_attrs()) 839 Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second)); 840 841 return getSorted(C, Attrs); 842 } 843 844 bool AttributeSetNode::hasAttribute(StringRef Kind) const { 845 return StringAttrs.count(Kind); 846 } 847 848 Optional<Attribute> 849 AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const { 850 // Do a quick presence check. 851 if (!hasAttribute(Kind)) 852 return None; 853 854 // Attributes in a set are sorted by enum value, followed by string 855 // attributes. Binary search the one we want. 856 const Attribute *I = 857 std::lower_bound(begin(), end() - StringAttrs.size(), Kind, 858 [](Attribute A, Attribute::AttrKind Kind) { 859 return A.getKindAsEnum() < Kind; 860 }); 861 assert(I != end() && I->hasAttribute(Kind) && "Presence check failed?"); 862 return *I; 863 } 864 865 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const { 866 if (auto A = findEnumAttribute(Kind)) 867 return *A; 868 return {}; 869 } 870 871 Attribute AttributeSetNode::getAttribute(StringRef Kind) const { 872 return StringAttrs.lookup(Kind); 873 } 874 875 MaybeAlign AttributeSetNode::getAlignment() const { 876 if (auto A = findEnumAttribute(Attribute::Alignment)) 877 return A->getAlignment(); 878 return None; 879 } 880 881 MaybeAlign AttributeSetNode::getStackAlignment() const { 882 if (auto A = findEnumAttribute(Attribute::StackAlignment)) 883 return A->getStackAlignment(); 884 return None; 885 } 886 887 Type *AttributeSetNode::getAttributeType(Attribute::AttrKind Kind) const { 888 if (auto A = findEnumAttribute(Kind)) 889 return A->getValueAsType(); 890 return nullptr; 891 } 892 893 uint64_t AttributeSetNode::getDereferenceableBytes() const { 894 if (auto A = findEnumAttribute(Attribute::Dereferenceable)) 895 return A->getDereferenceableBytes(); 896 return 0; 897 } 898 899 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const { 900 if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull)) 901 return A->getDereferenceableOrNullBytes(); 902 return 0; 903 } 904 905 std::pair<unsigned, Optional<unsigned>> 906 AttributeSetNode::getAllocSizeArgs() const { 907 if (auto A = findEnumAttribute(Attribute::AllocSize)) 908 return A->getAllocSizeArgs(); 909 return std::make_pair(0, 0); 910 } 911 912 unsigned AttributeSetNode::getVScaleRangeMin() const { 913 if (auto A = findEnumAttribute(Attribute::VScaleRange)) 914 return A->getVScaleRangeMin(); 915 return 1; 916 } 917 918 Optional<unsigned> AttributeSetNode::getVScaleRangeMax() const { 919 if (auto A = findEnumAttribute(Attribute::VScaleRange)) 920 return A->getVScaleRangeMax(); 921 return None; 922 } 923 924 std::string AttributeSetNode::getAsString(bool InAttrGrp) const { 925 std::string Str; 926 for (iterator I = begin(), E = end(); I != E; ++I) { 927 if (I != begin()) 928 Str += ' '; 929 Str += I->getAsString(InAttrGrp); 930 } 931 return Str; 932 } 933 934 //===----------------------------------------------------------------------===// 935 // AttributeListImpl Definition 936 //===----------------------------------------------------------------------===// 937 938 /// Map from AttributeList index to the internal array index. Adding one happens 939 /// to work, because -1 wraps around to 0. 940 static unsigned attrIdxToArrayIdx(unsigned Index) { 941 return Index + 1; 942 } 943 944 AttributeListImpl::AttributeListImpl(ArrayRef<AttributeSet> Sets) 945 : NumAttrSets(Sets.size()) { 946 assert(!Sets.empty() && "pointless AttributeListImpl"); 947 948 // There's memory after the node where we can store the entries in. 949 llvm::copy(Sets, getTrailingObjects<AttributeSet>()); 950 951 // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs 952 // summary bitsets. 953 for (const auto &I : Sets[attrIdxToArrayIdx(AttributeList::FunctionIndex)]) 954 if (!I.isStringAttribute()) 955 AvailableFunctionAttrs.addAttribute(I.getKindAsEnum()); 956 957 for (const auto &Set : Sets) 958 for (const auto &I : Set) 959 if (!I.isStringAttribute()) 960 AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum()); 961 } 962 963 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const { 964 Profile(ID, makeArrayRef(begin(), end())); 965 } 966 967 void AttributeListImpl::Profile(FoldingSetNodeID &ID, 968 ArrayRef<AttributeSet> Sets) { 969 for (const auto &Set : Sets) 970 ID.AddPointer(Set.SetNode); 971 } 972 973 bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind, 974 unsigned *Index) const { 975 if (!AvailableSomewhereAttrs.hasAttribute(Kind)) 976 return false; 977 978 if (Index) { 979 for (unsigned I = 0, E = NumAttrSets; I != E; ++I) { 980 if (begin()[I].hasAttribute(Kind)) { 981 *Index = I - 1; 982 break; 983 } 984 } 985 } 986 987 return true; 988 } 989 990 991 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 992 LLVM_DUMP_METHOD void AttributeListImpl::dump() const { 993 AttributeList(const_cast<AttributeListImpl *>(this)).dump(); 994 } 995 #endif 996 997 //===----------------------------------------------------------------------===// 998 // AttributeList Construction and Mutation Methods 999 //===----------------------------------------------------------------------===// 1000 1001 AttributeList AttributeList::getImpl(LLVMContext &C, 1002 ArrayRef<AttributeSet> AttrSets) { 1003 assert(!AttrSets.empty() && "pointless AttributeListImpl"); 1004 1005 LLVMContextImpl *pImpl = C.pImpl; 1006 FoldingSetNodeID ID; 1007 AttributeListImpl::Profile(ID, AttrSets); 1008 1009 void *InsertPoint; 1010 AttributeListImpl *PA = 1011 pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint); 1012 1013 // If we didn't find any existing attributes of the same shape then 1014 // create a new one and insert it. 1015 if (!PA) { 1016 // Coallocate entries after the AttributeListImpl itself. 1017 void *Mem = pImpl->Alloc.Allocate( 1018 AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()), 1019 alignof(AttributeListImpl)); 1020 PA = new (Mem) AttributeListImpl(AttrSets); 1021 pImpl->AttrsLists.InsertNode(PA, InsertPoint); 1022 } 1023 1024 // Return the AttributesList that we found or created. 1025 return AttributeList(PA); 1026 } 1027 1028 AttributeList 1029 AttributeList::get(LLVMContext &C, 1030 ArrayRef<std::pair<unsigned, Attribute>> Attrs) { 1031 // If there are no attributes then return a null AttributesList pointer. 1032 if (Attrs.empty()) 1033 return {}; 1034 1035 assert(llvm::is_sorted(Attrs, 1036 [](const std::pair<unsigned, Attribute> &LHS, 1037 const std::pair<unsigned, Attribute> &RHS) { 1038 return LHS.first < RHS.first; 1039 }) && 1040 "Misordered Attributes list!"); 1041 assert(llvm::all_of(Attrs, 1042 [](const std::pair<unsigned, Attribute> &Pair) { 1043 return Pair.second.isValid(); 1044 }) && 1045 "Pointless attribute!"); 1046 1047 // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes 1048 // list. 1049 SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec; 1050 for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(), 1051 E = Attrs.end(); I != E; ) { 1052 unsigned Index = I->first; 1053 SmallVector<Attribute, 4> AttrVec; 1054 while (I != E && I->first == Index) { 1055 AttrVec.push_back(I->second); 1056 ++I; 1057 } 1058 1059 AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec)); 1060 } 1061 1062 return get(C, AttrPairVec); 1063 } 1064 1065 AttributeList 1066 AttributeList::get(LLVMContext &C, 1067 ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) { 1068 // If there are no attributes then return a null AttributesList pointer. 1069 if (Attrs.empty()) 1070 return {}; 1071 1072 assert(llvm::is_sorted(Attrs, 1073 [](const std::pair<unsigned, AttributeSet> &LHS, 1074 const std::pair<unsigned, AttributeSet> &RHS) { 1075 return LHS.first < RHS.first; 1076 }) && 1077 "Misordered Attributes list!"); 1078 assert(llvm::none_of(Attrs, 1079 [](const std::pair<unsigned, AttributeSet> &Pair) { 1080 return !Pair.second.hasAttributes(); 1081 }) && 1082 "Pointless attribute!"); 1083 1084 unsigned MaxIndex = Attrs.back().first; 1085 // If the MaxIndex is FunctionIndex and there are other indices in front 1086 // of it, we need to use the largest of those to get the right size. 1087 if (MaxIndex == FunctionIndex && Attrs.size() > 1) 1088 MaxIndex = Attrs[Attrs.size() - 2].first; 1089 1090 SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1); 1091 for (const auto &Pair : Attrs) 1092 AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second; 1093 1094 return getImpl(C, AttrVec); 1095 } 1096 1097 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs, 1098 AttributeSet RetAttrs, 1099 ArrayRef<AttributeSet> ArgAttrs) { 1100 // Scan from the end to find the last argument with attributes. Most 1101 // arguments don't have attributes, so it's nice if we can have fewer unique 1102 // AttributeListImpls by dropping empty attribute sets at the end of the list. 1103 unsigned NumSets = 0; 1104 for (size_t I = ArgAttrs.size(); I != 0; --I) { 1105 if (ArgAttrs[I - 1].hasAttributes()) { 1106 NumSets = I + 2; 1107 break; 1108 } 1109 } 1110 if (NumSets == 0) { 1111 // Check function and return attributes if we didn't have argument 1112 // attributes. 1113 if (RetAttrs.hasAttributes()) 1114 NumSets = 2; 1115 else if (FnAttrs.hasAttributes()) 1116 NumSets = 1; 1117 } 1118 1119 // If all attribute sets were empty, we can use the empty attribute list. 1120 if (NumSets == 0) 1121 return {}; 1122 1123 SmallVector<AttributeSet, 8> AttrSets; 1124 AttrSets.reserve(NumSets); 1125 // If we have any attributes, we always have function attributes. 1126 AttrSets.push_back(FnAttrs); 1127 if (NumSets > 1) 1128 AttrSets.push_back(RetAttrs); 1129 if (NumSets > 2) { 1130 // Drop the empty argument attribute sets at the end. 1131 ArgAttrs = ArgAttrs.take_front(NumSets - 2); 1132 llvm::append_range(AttrSets, ArgAttrs); 1133 } 1134 1135 return getImpl(C, AttrSets); 1136 } 1137 1138 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1139 const AttrBuilder &B) { 1140 if (!B.hasAttributes()) 1141 return {}; 1142 Index = attrIdxToArrayIdx(Index); 1143 SmallVector<AttributeSet, 8> AttrSets(Index + 1); 1144 AttrSets[Index] = AttributeSet::get(C, B); 1145 return getImpl(C, AttrSets); 1146 } 1147 1148 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1149 ArrayRef<Attribute::AttrKind> Kinds) { 1150 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1151 for (const auto K : Kinds) 1152 Attrs.emplace_back(Index, Attribute::get(C, K)); 1153 return get(C, Attrs); 1154 } 1155 1156 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1157 ArrayRef<Attribute::AttrKind> Kinds, 1158 ArrayRef<uint64_t> Values) { 1159 assert(Kinds.size() == Values.size() && "Mismatched attribute values."); 1160 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1161 auto VI = Values.begin(); 1162 for (const auto K : Kinds) 1163 Attrs.emplace_back(Index, Attribute::get(C, K, *VI++)); 1164 return get(C, Attrs); 1165 } 1166 1167 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1168 ArrayRef<StringRef> Kinds) { 1169 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1170 for (const auto &K : Kinds) 1171 Attrs.emplace_back(Index, Attribute::get(C, K)); 1172 return get(C, Attrs); 1173 } 1174 1175 AttributeList AttributeList::get(LLVMContext &C, 1176 ArrayRef<AttributeList> Attrs) { 1177 if (Attrs.empty()) 1178 return {}; 1179 if (Attrs.size() == 1) 1180 return Attrs[0]; 1181 1182 unsigned MaxSize = 0; 1183 for (const auto &List : Attrs) 1184 MaxSize = std::max(MaxSize, List.getNumAttrSets()); 1185 1186 // If every list was empty, there is no point in merging the lists. 1187 if (MaxSize == 0) 1188 return {}; 1189 1190 SmallVector<AttributeSet, 8> NewAttrSets(MaxSize); 1191 for (unsigned I = 0; I < MaxSize; ++I) { 1192 AttrBuilder CurBuilder; 1193 for (const auto &List : Attrs) 1194 CurBuilder.merge(List.getAttributes(I - 1)); 1195 NewAttrSets[I] = AttributeSet::get(C, CurBuilder); 1196 } 1197 1198 return getImpl(C, NewAttrSets); 1199 } 1200 1201 AttributeList 1202 AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1203 Attribute::AttrKind Kind) const { 1204 if (hasAttributeAtIndex(Index, Kind)) 1205 return *this; 1206 AttributeSet Attrs = getAttributes(Index); 1207 // TODO: Insert at correct position and avoid sort. 1208 SmallVector<Attribute, 8> NewAttrs(Attrs.begin(), Attrs.end()); 1209 NewAttrs.push_back(Attribute::get(C, Kind)); 1210 return setAttributesAtIndex(C, Index, AttributeSet::get(C, NewAttrs)); 1211 } 1212 1213 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1214 StringRef Kind, 1215 StringRef Value) const { 1216 AttrBuilder B; 1217 B.addAttribute(Kind, Value); 1218 return addAttributesAtIndex(C, Index, B); 1219 } 1220 1221 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1222 Attribute A) const { 1223 AttrBuilder B; 1224 B.addAttribute(A); 1225 return addAttributesAtIndex(C, Index, B); 1226 } 1227 1228 AttributeList AttributeList::setAttributesAtIndex(LLVMContext &C, 1229 unsigned Index, 1230 AttributeSet Attrs) const { 1231 Index = attrIdxToArrayIdx(Index); 1232 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1233 if (Index >= AttrSets.size()) 1234 AttrSets.resize(Index + 1); 1235 AttrSets[Index] = Attrs; 1236 return AttributeList::getImpl(C, AttrSets); 1237 } 1238 1239 AttributeList AttributeList::addAttributesAtIndex(LLVMContext &C, 1240 unsigned Index, 1241 const AttrBuilder &B) const { 1242 if (!B.hasAttributes()) 1243 return *this; 1244 1245 if (!pImpl) 1246 return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}}); 1247 1248 #ifndef NDEBUG 1249 // FIXME it is not obvious how this should work for alignment. For now, say 1250 // we can't change a known alignment. 1251 const MaybeAlign OldAlign = getAttributes(Index).getAlignment(); 1252 const MaybeAlign NewAlign = B.getAlignment(); 1253 assert((!OldAlign || !NewAlign || OldAlign == NewAlign) && 1254 "Attempt to change alignment!"); 1255 #endif 1256 1257 AttrBuilder Merged(getAttributes(Index)); 1258 Merged.merge(B); 1259 return setAttributesAtIndex(C, Index, AttributeSet::get(C, Merged)); 1260 } 1261 1262 AttributeList AttributeList::addParamAttribute(LLVMContext &C, 1263 ArrayRef<unsigned> ArgNos, 1264 Attribute A) const { 1265 assert(llvm::is_sorted(ArgNos)); 1266 1267 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1268 unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex); 1269 if (MaxIndex >= AttrSets.size()) 1270 AttrSets.resize(MaxIndex + 1); 1271 1272 for (unsigned ArgNo : ArgNos) { 1273 unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex); 1274 AttrBuilder B(AttrSets[Index]); 1275 B.addAttribute(A); 1276 AttrSets[Index] = AttributeSet::get(C, B); 1277 } 1278 1279 return getImpl(C, AttrSets); 1280 } 1281 1282 AttributeList 1283 AttributeList::removeAttributeAtIndex(LLVMContext &C, unsigned Index, 1284 Attribute::AttrKind Kind) const { 1285 if (!hasAttributeAtIndex(Index, Kind)) 1286 return *this; 1287 1288 Index = attrIdxToArrayIdx(Index); 1289 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1290 assert(Index < AttrSets.size()); 1291 1292 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); 1293 1294 return getImpl(C, AttrSets); 1295 } 1296 1297 AttributeList AttributeList::removeAttributeAtIndex(LLVMContext &C, 1298 unsigned Index, 1299 StringRef Kind) const { 1300 if (!hasAttributeAtIndex(Index, Kind)) 1301 return *this; 1302 1303 Index = attrIdxToArrayIdx(Index); 1304 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1305 assert(Index < AttrSets.size()); 1306 1307 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); 1308 1309 return getImpl(C, AttrSets); 1310 } 1311 1312 AttributeList 1313 AttributeList::removeAttributesAtIndex(LLVMContext &C, unsigned Index, 1314 const AttrBuilder &AttrsToRemove) const { 1315 AttributeSet Attrs = getAttributes(Index); 1316 AttributeSet NewAttrs = Attrs.removeAttributes(C, AttrsToRemove); 1317 // If nothing was removed, return the original list. 1318 if (Attrs == NewAttrs) 1319 return *this; 1320 return setAttributesAtIndex(C, Index, NewAttrs); 1321 } 1322 1323 AttributeList 1324 AttributeList::removeAttributesAtIndex(LLVMContext &C, 1325 unsigned WithoutIndex) const { 1326 if (!pImpl) 1327 return {}; 1328 WithoutIndex = attrIdxToArrayIdx(WithoutIndex); 1329 if (WithoutIndex >= getNumAttrSets()) 1330 return *this; 1331 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1332 AttrSets[WithoutIndex] = AttributeSet(); 1333 return getImpl(C, AttrSets); 1334 } 1335 1336 AttributeList AttributeList::addDereferenceableRetAttr(LLVMContext &C, 1337 uint64_t Bytes) const { 1338 AttrBuilder B; 1339 B.addDereferenceableAttr(Bytes); 1340 return addRetAttributes(C, B); 1341 } 1342 1343 AttributeList AttributeList::addDereferenceableParamAttr(LLVMContext &C, 1344 unsigned Index, 1345 uint64_t Bytes) const { 1346 AttrBuilder B; 1347 B.addDereferenceableAttr(Bytes); 1348 return addParamAttributes(C, Index, B); 1349 } 1350 1351 AttributeList 1352 AttributeList::addDereferenceableOrNullParamAttr(LLVMContext &C, unsigned Index, 1353 uint64_t Bytes) const { 1354 AttrBuilder B; 1355 B.addDereferenceableOrNullAttr(Bytes); 1356 return addParamAttributes(C, Index, B); 1357 } 1358 1359 AttributeList 1360 AttributeList::addAllocSizeParamAttr(LLVMContext &C, unsigned Index, 1361 unsigned ElemSizeArg, 1362 const Optional<unsigned> &NumElemsArg) { 1363 AttrBuilder B; 1364 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1365 return addParamAttributes(C, Index, B); 1366 } 1367 1368 //===----------------------------------------------------------------------===// 1369 // AttributeList Accessor Methods 1370 //===----------------------------------------------------------------------===// 1371 1372 AttributeSet AttributeList::getParamAttrs(unsigned ArgNo) const { 1373 return getAttributes(ArgNo + FirstArgIndex); 1374 } 1375 1376 AttributeSet AttributeList::getRetAttrs() const { 1377 return getAttributes(ReturnIndex); 1378 } 1379 1380 AttributeSet AttributeList::getFnAttrs() const { 1381 return getAttributes(FunctionIndex); 1382 } 1383 1384 bool AttributeList::hasAttributeAtIndex(unsigned Index, 1385 Attribute::AttrKind Kind) const { 1386 return getAttributes(Index).hasAttribute(Kind); 1387 } 1388 1389 bool AttributeList::hasAttributeAtIndex(unsigned Index, StringRef Kind) const { 1390 return getAttributes(Index).hasAttribute(Kind); 1391 } 1392 1393 bool AttributeList::hasAttributesAtIndex(unsigned Index) const { 1394 return getAttributes(Index).hasAttributes(); 1395 } 1396 1397 bool AttributeList::hasFnAttr(Attribute::AttrKind Kind) const { 1398 return pImpl && pImpl->hasFnAttribute(Kind); 1399 } 1400 1401 bool AttributeList::hasFnAttr(StringRef Kind) const { 1402 return hasAttributeAtIndex(AttributeList::FunctionIndex, Kind); 1403 } 1404 1405 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr, 1406 unsigned *Index) const { 1407 return pImpl && pImpl->hasAttrSomewhere(Attr, Index); 1408 } 1409 1410 Attribute AttributeList::getAttributeAtIndex(unsigned Index, 1411 Attribute::AttrKind Kind) const { 1412 return getAttributes(Index).getAttribute(Kind); 1413 } 1414 1415 Attribute AttributeList::getAttributeAtIndex(unsigned Index, 1416 StringRef Kind) const { 1417 return getAttributes(Index).getAttribute(Kind); 1418 } 1419 1420 MaybeAlign AttributeList::getRetAlignment() const { 1421 return getAttributes(ReturnIndex).getAlignment(); 1422 } 1423 1424 MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const { 1425 return getAttributes(ArgNo + FirstArgIndex).getAlignment(); 1426 } 1427 1428 MaybeAlign AttributeList::getParamStackAlignment(unsigned ArgNo) const { 1429 return getAttributes(ArgNo + FirstArgIndex).getStackAlignment(); 1430 } 1431 1432 Type *AttributeList::getParamByValType(unsigned Index) const { 1433 return getAttributes(Index+FirstArgIndex).getByValType(); 1434 } 1435 1436 Type *AttributeList::getParamStructRetType(unsigned Index) const { 1437 return getAttributes(Index + FirstArgIndex).getStructRetType(); 1438 } 1439 1440 Type *AttributeList::getParamByRefType(unsigned Index) const { 1441 return getAttributes(Index + FirstArgIndex).getByRefType(); 1442 } 1443 1444 Type *AttributeList::getParamPreallocatedType(unsigned Index) const { 1445 return getAttributes(Index + FirstArgIndex).getPreallocatedType(); 1446 } 1447 1448 Type *AttributeList::getParamInAllocaType(unsigned Index) const { 1449 return getAttributes(Index + FirstArgIndex).getInAllocaType(); 1450 } 1451 1452 Type *AttributeList::getParamElementType(unsigned Index) const { 1453 return getAttributes(Index + FirstArgIndex).getElementType(); 1454 } 1455 1456 MaybeAlign AttributeList::getFnStackAlignment() const { 1457 return getFnAttrs().getStackAlignment(); 1458 } 1459 1460 MaybeAlign AttributeList::getRetStackAlignment() const { 1461 return getRetAttrs().getStackAlignment(); 1462 } 1463 1464 uint64_t AttributeList::getRetDereferenceableBytes() const { 1465 return getRetAttrs().getDereferenceableBytes(); 1466 } 1467 1468 uint64_t AttributeList::getParamDereferenceableBytes(unsigned Index) const { 1469 return getParamAttrs(Index).getDereferenceableBytes(); 1470 } 1471 1472 uint64_t AttributeList::getRetDereferenceableOrNullBytes() const { 1473 return getRetAttrs().getDereferenceableOrNullBytes(); 1474 } 1475 1476 uint64_t 1477 AttributeList::getParamDereferenceableOrNullBytes(unsigned Index) const { 1478 return getParamAttrs(Index).getDereferenceableOrNullBytes(); 1479 } 1480 1481 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const { 1482 return getAttributes(Index).getAsString(InAttrGrp); 1483 } 1484 1485 AttributeSet AttributeList::getAttributes(unsigned Index) const { 1486 Index = attrIdxToArrayIdx(Index); 1487 if (!pImpl || Index >= getNumAttrSets()) 1488 return {}; 1489 return pImpl->begin()[Index]; 1490 } 1491 1492 bool AttributeList::hasParentContext(LLVMContext &C) const { 1493 assert(!isEmpty() && "an empty attribute list has no parent context"); 1494 FoldingSetNodeID ID; 1495 pImpl->Profile(ID); 1496 void *Unused; 1497 return C.pImpl->AttrsLists.FindNodeOrInsertPos(ID, Unused) == pImpl; 1498 } 1499 1500 AttributeList::iterator AttributeList::begin() const { 1501 return pImpl ? pImpl->begin() : nullptr; 1502 } 1503 1504 AttributeList::iterator AttributeList::end() const { 1505 return pImpl ? pImpl->end() : nullptr; 1506 } 1507 1508 //===----------------------------------------------------------------------===// 1509 // AttributeList Introspection Methods 1510 //===----------------------------------------------------------------------===// 1511 1512 unsigned AttributeList::getNumAttrSets() const { 1513 return pImpl ? pImpl->NumAttrSets : 0; 1514 } 1515 1516 void AttributeList::print(raw_ostream &O) const { 1517 O << "AttributeList[\n"; 1518 1519 for (unsigned i : indexes()) { 1520 if (!getAttributes(i).hasAttributes()) 1521 continue; 1522 O << " { "; 1523 switch (i) { 1524 case AttrIndex::ReturnIndex: 1525 O << "return"; 1526 break; 1527 case AttrIndex::FunctionIndex: 1528 O << "function"; 1529 break; 1530 default: 1531 O << "arg(" << i - AttrIndex::FirstArgIndex << ")"; 1532 } 1533 O << " => " << getAsString(i) << " }\n"; 1534 } 1535 1536 O << "]\n"; 1537 } 1538 1539 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1540 LLVM_DUMP_METHOD void AttributeList::dump() const { print(dbgs()); } 1541 #endif 1542 1543 //===----------------------------------------------------------------------===// 1544 // AttrBuilder Method Implementations 1545 //===----------------------------------------------------------------------===// 1546 1547 // FIXME: Remove this ctor, use AttributeSet. 1548 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) { 1549 AttributeSet AS = AL.getAttributes(Index); 1550 for (const auto &A : AS) 1551 addAttribute(A); 1552 } 1553 1554 AttrBuilder::AttrBuilder(AttributeSet AS) { 1555 for (const auto &A : AS) 1556 addAttribute(A); 1557 } 1558 1559 void AttrBuilder::clear() { 1560 Attrs.reset(); 1561 TargetDepAttrs.clear(); 1562 IntAttrs = {}; 1563 TypeAttrs = {}; 1564 } 1565 1566 Optional<unsigned> 1567 AttrBuilder::kindToIntIndex(Attribute::AttrKind Kind) const { 1568 if (Attribute::isIntAttrKind(Kind)) 1569 return Kind - Attribute::FirstIntAttr; 1570 return None; 1571 } 1572 1573 Optional<unsigned> 1574 AttrBuilder::kindToTypeIndex(Attribute::AttrKind Kind) const { 1575 if (Attribute::isTypeAttrKind(Kind)) 1576 return Kind - Attribute::FirstTypeAttr; 1577 return None; 1578 } 1579 1580 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) { 1581 if (Attr.isStringAttribute()) { 1582 addAttribute(Attr.getKindAsString(), Attr.getValueAsString()); 1583 return *this; 1584 } 1585 1586 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 1587 Attrs[Kind] = true; 1588 1589 if (Optional<unsigned> TypeIndex = kindToTypeIndex(Kind)) 1590 TypeAttrs[*TypeIndex] = Attr.getValueAsType(); 1591 else if (Optional<unsigned> IntIndex = kindToIntIndex(Kind)) 1592 IntAttrs[*IntIndex] = Attr.getValueAsInt(); 1593 1594 return *this; 1595 } 1596 1597 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) { 1598 TargetDepAttrs[A] = V; 1599 return *this; 1600 } 1601 1602 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) { 1603 assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!"); 1604 Attrs[Val] = false; 1605 1606 if (Optional<unsigned> TypeIndex = kindToTypeIndex(Val)) 1607 TypeAttrs[*TypeIndex] = nullptr; 1608 else if (Optional<unsigned> IntIndex = kindToIntIndex(Val)) 1609 IntAttrs[*IntIndex] = 0; 1610 1611 return *this; 1612 } 1613 1614 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) { 1615 remove(A.getAttributes(Index)); 1616 return *this; 1617 } 1618 1619 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) { 1620 TargetDepAttrs.erase(A); 1621 return *this; 1622 } 1623 1624 uint64_t AttrBuilder::getRawIntAttr(Attribute::AttrKind Kind) const { 1625 Optional<unsigned> IntIndex = kindToIntIndex(Kind); 1626 assert(IntIndex && "Not an int attribute"); 1627 return IntAttrs[*IntIndex]; 1628 } 1629 1630 AttrBuilder &AttrBuilder::addRawIntAttr(Attribute::AttrKind Kind, 1631 uint64_t Value) { 1632 Optional<unsigned> IntIndex = kindToIntIndex(Kind); 1633 assert(IntIndex && "Not an int attribute"); 1634 assert(Value && "Value cannot be zero"); 1635 Attrs[Kind] = true; 1636 IntAttrs[*IntIndex] = Value; 1637 return *this; 1638 } 1639 1640 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const { 1641 return unpackAllocSizeArgs(getRawIntAttr(Attribute::AllocSize)); 1642 } 1643 1644 unsigned AttrBuilder::getVScaleRangeMin() const { 1645 return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).first; 1646 } 1647 1648 Optional<unsigned> AttrBuilder::getVScaleRangeMax() const { 1649 return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).second; 1650 } 1651 1652 AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) { 1653 if (!Align) 1654 return *this; 1655 1656 assert(*Align <= llvm::Value::MaximumAlignment && "Alignment too large."); 1657 return addRawIntAttr(Attribute::Alignment, Align->value()); 1658 } 1659 1660 AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) { 1661 // Default alignment, allow the target to define how to align it. 1662 if (!Align) 1663 return *this; 1664 1665 assert(*Align <= 0x100 && "Alignment too large."); 1666 return addRawIntAttr(Attribute::StackAlignment, Align->value()); 1667 } 1668 1669 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) { 1670 if (Bytes == 0) return *this; 1671 1672 return addRawIntAttr(Attribute::Dereferenceable, Bytes); 1673 } 1674 1675 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) { 1676 if (Bytes == 0) 1677 return *this; 1678 1679 return addRawIntAttr(Attribute::DereferenceableOrNull, Bytes); 1680 } 1681 1682 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize, 1683 const Optional<unsigned> &NumElems) { 1684 return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems)); 1685 } 1686 1687 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) { 1688 // (0, 0) is our "not present" value, so we need to check for it here. 1689 assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)"); 1690 return addRawIntAttr(Attribute::AllocSize, RawArgs); 1691 } 1692 1693 AttrBuilder &AttrBuilder::addVScaleRangeAttr(unsigned MinValue, 1694 Optional<unsigned> MaxValue) { 1695 return addVScaleRangeAttrFromRawRepr(packVScaleRangeArgs(MinValue, MaxValue)); 1696 } 1697 1698 AttrBuilder &AttrBuilder::addVScaleRangeAttrFromRawRepr(uint64_t RawArgs) { 1699 // (0, 0) is not present hence ignore this case 1700 if (RawArgs == 0) 1701 return *this; 1702 1703 return addRawIntAttr(Attribute::VScaleRange, RawArgs); 1704 } 1705 1706 Type *AttrBuilder::getTypeAttr(Attribute::AttrKind Kind) const { 1707 Optional<unsigned> TypeIndex = kindToTypeIndex(Kind); 1708 assert(TypeIndex && "Not a type attribute"); 1709 return TypeAttrs[*TypeIndex]; 1710 } 1711 1712 AttrBuilder &AttrBuilder::addTypeAttr(Attribute::AttrKind Kind, Type *Ty) { 1713 Optional<unsigned> TypeIndex = kindToTypeIndex(Kind); 1714 assert(TypeIndex && "Not a type attribute"); 1715 Attrs[Kind] = true; 1716 TypeAttrs[*TypeIndex] = Ty; 1717 return *this; 1718 } 1719 1720 AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) { 1721 return addTypeAttr(Attribute::ByVal, Ty); 1722 } 1723 1724 AttrBuilder &AttrBuilder::addStructRetAttr(Type *Ty) { 1725 return addTypeAttr(Attribute::StructRet, Ty); 1726 } 1727 1728 AttrBuilder &AttrBuilder::addByRefAttr(Type *Ty) { 1729 return addTypeAttr(Attribute::ByRef, Ty); 1730 } 1731 1732 AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) { 1733 return addTypeAttr(Attribute::Preallocated, Ty); 1734 } 1735 1736 AttrBuilder &AttrBuilder::addInAllocaAttr(Type *Ty) { 1737 return addTypeAttr(Attribute::InAlloca, Ty); 1738 } 1739 1740 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) { 1741 // FIXME: What if both have an int/type attribute, but they don't match?! 1742 for (unsigned Index = 0; Index < Attribute::NumIntAttrKinds; ++Index) 1743 if (!IntAttrs[Index]) 1744 IntAttrs[Index] = B.IntAttrs[Index]; 1745 1746 for (unsigned Index = 0; Index < Attribute::NumTypeAttrKinds; ++Index) 1747 if (!TypeAttrs[Index]) 1748 TypeAttrs[Index] = B.TypeAttrs[Index]; 1749 1750 Attrs |= B.Attrs; 1751 1752 for (const auto &I : B.td_attrs()) 1753 TargetDepAttrs[I.first] = I.second; 1754 1755 return *this; 1756 } 1757 1758 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) { 1759 // FIXME: What if both have an int/type attribute, but they don't match?! 1760 for (unsigned Index = 0; Index < Attribute::NumIntAttrKinds; ++Index) 1761 if (B.IntAttrs[Index]) 1762 IntAttrs[Index] = 0; 1763 1764 for (unsigned Index = 0; Index < Attribute::NumTypeAttrKinds; ++Index) 1765 if (B.TypeAttrs[Index]) 1766 TypeAttrs[Index] = nullptr; 1767 1768 Attrs &= ~B.Attrs; 1769 1770 for (const auto &I : B.td_attrs()) 1771 TargetDepAttrs.erase(I.first); 1772 1773 return *this; 1774 } 1775 1776 bool AttrBuilder::overlaps(const AttrBuilder &B) const { 1777 // First check if any of the target independent attributes overlap. 1778 if ((Attrs & B.Attrs).any()) 1779 return true; 1780 1781 // Then check if any target dependent ones do. 1782 for (const auto &I : td_attrs()) 1783 if (B.contains(I.first)) 1784 return true; 1785 1786 return false; 1787 } 1788 1789 bool AttrBuilder::contains(StringRef A) const { 1790 return TargetDepAttrs.find(A) != TargetDepAttrs.end(); 1791 } 1792 1793 bool AttrBuilder::hasAttributes() const { 1794 return !Attrs.none() || !TargetDepAttrs.empty(); 1795 } 1796 1797 bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const { 1798 AttributeSet AS = AL.getAttributes(Index); 1799 1800 for (const auto &Attr : AS) { 1801 if (Attr.isEnumAttribute() || Attr.isIntAttribute()) { 1802 if (contains(Attr.getKindAsEnum())) 1803 return true; 1804 } else { 1805 assert(Attr.isStringAttribute() && "Invalid attribute kind!"); 1806 return contains(Attr.getKindAsString()); 1807 } 1808 } 1809 1810 return false; 1811 } 1812 1813 bool AttrBuilder::hasAlignmentAttr() const { 1814 return getRawIntAttr(Attribute::Alignment) != 0; 1815 } 1816 1817 bool AttrBuilder::operator==(const AttrBuilder &B) const { 1818 if (Attrs != B.Attrs) 1819 return false; 1820 1821 for (const auto &TDA : TargetDepAttrs) 1822 if (B.TargetDepAttrs.find(TDA.first) == B.TargetDepAttrs.end()) 1823 return false; 1824 1825 return IntAttrs == B.IntAttrs && TypeAttrs == B.TypeAttrs; 1826 } 1827 1828 //===----------------------------------------------------------------------===// 1829 // AttributeFuncs Function Defintions 1830 //===----------------------------------------------------------------------===// 1831 1832 /// Which attributes cannot be applied to a type. 1833 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) { 1834 AttrBuilder Incompatible; 1835 1836 if (!Ty->isIntegerTy()) 1837 // Attribute that only apply to integers. 1838 Incompatible.addAttribute(Attribute::SExt) 1839 .addAttribute(Attribute::ZExt); 1840 1841 if (!Ty->isPointerTy()) 1842 // Attribute that only apply to pointers. 1843 Incompatible.addAttribute(Attribute::Nest) 1844 .addAttribute(Attribute::NoAlias) 1845 .addAttribute(Attribute::NoCapture) 1846 .addAttribute(Attribute::NonNull) 1847 .addAttribute(Attribute::ReadNone) 1848 .addAttribute(Attribute::ReadOnly) 1849 .addAttribute(Attribute::SwiftError) 1850 .addAlignmentAttr(1) // the int here is ignored 1851 .addDereferenceableAttr(1) // the int here is ignored 1852 .addDereferenceableOrNullAttr(1) // the int here is ignored 1853 .addPreallocatedAttr(Ty) 1854 .addInAllocaAttr(Ty) 1855 .addByValAttr(Ty) 1856 .addStructRetAttr(Ty) 1857 .addByRefAttr(Ty) 1858 .addTypeAttr(Attribute::ElementType, Ty); 1859 1860 // Some attributes can apply to all "values" but there are no `void` values. 1861 if (Ty->isVoidTy()) 1862 Incompatible.addAttribute(Attribute::NoUndef); 1863 1864 return Incompatible; 1865 } 1866 1867 AttrBuilder AttributeFuncs::getUBImplyingAttributes() { 1868 AttrBuilder B; 1869 B.addAttribute(Attribute::NoUndef); 1870 B.addDereferenceableAttr(1); 1871 B.addDereferenceableOrNullAttr(1); 1872 return B; 1873 } 1874 1875 template<typename AttrClass> 1876 static bool isEqual(const Function &Caller, const Function &Callee) { 1877 return Caller.getFnAttribute(AttrClass::getKind()) == 1878 Callee.getFnAttribute(AttrClass::getKind()); 1879 } 1880 1881 /// Compute the logical AND of the attributes of the caller and the 1882 /// callee. 1883 /// 1884 /// This function sets the caller's attribute to false if the callee's attribute 1885 /// is false. 1886 template<typename AttrClass> 1887 static void setAND(Function &Caller, const Function &Callee) { 1888 if (AttrClass::isSet(Caller, AttrClass::getKind()) && 1889 !AttrClass::isSet(Callee, AttrClass::getKind())) 1890 AttrClass::set(Caller, AttrClass::getKind(), false); 1891 } 1892 1893 /// Compute the logical OR of the attributes of the caller and the 1894 /// callee. 1895 /// 1896 /// This function sets the caller's attribute to true if the callee's attribute 1897 /// is true. 1898 template<typename AttrClass> 1899 static void setOR(Function &Caller, const Function &Callee) { 1900 if (!AttrClass::isSet(Caller, AttrClass::getKind()) && 1901 AttrClass::isSet(Callee, AttrClass::getKind())) 1902 AttrClass::set(Caller, AttrClass::getKind(), true); 1903 } 1904 1905 /// If the inlined function had a higher stack protection level than the 1906 /// calling function, then bump up the caller's stack protection level. 1907 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) { 1908 // If upgrading the SSP attribute, clear out the old SSP Attributes first. 1909 // Having multiple SSP attributes doesn't actually hurt, but it adds useless 1910 // clutter to the IR. 1911 AttrBuilder OldSSPAttr; 1912 OldSSPAttr.addAttribute(Attribute::StackProtect) 1913 .addAttribute(Attribute::StackProtectStrong) 1914 .addAttribute(Attribute::StackProtectReq); 1915 1916 if (Callee.hasFnAttribute(Attribute::StackProtectReq)) { 1917 Caller.removeFnAttrs(OldSSPAttr); 1918 Caller.addFnAttr(Attribute::StackProtectReq); 1919 } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) && 1920 !Caller.hasFnAttribute(Attribute::StackProtectReq)) { 1921 Caller.removeFnAttrs(OldSSPAttr); 1922 Caller.addFnAttr(Attribute::StackProtectStrong); 1923 } else if (Callee.hasFnAttribute(Attribute::StackProtect) && 1924 !Caller.hasFnAttribute(Attribute::StackProtectReq) && 1925 !Caller.hasFnAttribute(Attribute::StackProtectStrong)) 1926 Caller.addFnAttr(Attribute::StackProtect); 1927 } 1928 1929 /// If the inlined function required stack probes, then ensure that 1930 /// the calling function has those too. 1931 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) { 1932 if (!Caller.hasFnAttribute("probe-stack") && 1933 Callee.hasFnAttribute("probe-stack")) { 1934 Caller.addFnAttr(Callee.getFnAttribute("probe-stack")); 1935 } 1936 } 1937 1938 /// If the inlined function defines the size of guard region 1939 /// on the stack, then ensure that the calling function defines a guard region 1940 /// that is no larger. 1941 static void 1942 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) { 1943 Attribute CalleeAttr = Callee.getFnAttribute("stack-probe-size"); 1944 if (CalleeAttr.isValid()) { 1945 Attribute CallerAttr = Caller.getFnAttribute("stack-probe-size"); 1946 if (CallerAttr.isValid()) { 1947 uint64_t CallerStackProbeSize, CalleeStackProbeSize; 1948 CallerAttr.getValueAsString().getAsInteger(0, CallerStackProbeSize); 1949 CalleeAttr.getValueAsString().getAsInteger(0, CalleeStackProbeSize); 1950 1951 if (CallerStackProbeSize > CalleeStackProbeSize) { 1952 Caller.addFnAttr(CalleeAttr); 1953 } 1954 } else { 1955 Caller.addFnAttr(CalleeAttr); 1956 } 1957 } 1958 } 1959 1960 /// If the inlined function defines a min legal vector width, then ensure 1961 /// the calling function has the same or larger min legal vector width. If the 1962 /// caller has the attribute, but the callee doesn't, we need to remove the 1963 /// attribute from the caller since we can't make any guarantees about the 1964 /// caller's requirements. 1965 /// This function is called after the inlining decision has been made so we have 1966 /// to merge the attribute this way. Heuristics that would use 1967 /// min-legal-vector-width to determine inline compatibility would need to be 1968 /// handled as part of inline cost analysis. 1969 static void 1970 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) { 1971 Attribute CallerAttr = Caller.getFnAttribute("min-legal-vector-width"); 1972 if (CallerAttr.isValid()) { 1973 Attribute CalleeAttr = Callee.getFnAttribute("min-legal-vector-width"); 1974 if (CalleeAttr.isValid()) { 1975 uint64_t CallerVectorWidth, CalleeVectorWidth; 1976 CallerAttr.getValueAsString().getAsInteger(0, CallerVectorWidth); 1977 CalleeAttr.getValueAsString().getAsInteger(0, CalleeVectorWidth); 1978 if (CallerVectorWidth < CalleeVectorWidth) 1979 Caller.addFnAttr(CalleeAttr); 1980 } else { 1981 // If the callee doesn't have the attribute then we don't know anything 1982 // and must drop the attribute from the caller. 1983 Caller.removeFnAttr("min-legal-vector-width"); 1984 } 1985 } 1986 } 1987 1988 /// If the inlined function has null_pointer_is_valid attribute, 1989 /// set this attribute in the caller post inlining. 1990 static void 1991 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) { 1992 if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) { 1993 Caller.addFnAttr(Attribute::NullPointerIsValid); 1994 } 1995 } 1996 1997 struct EnumAttr { 1998 static bool isSet(const Function &Fn, 1999 Attribute::AttrKind Kind) { 2000 return Fn.hasFnAttribute(Kind); 2001 } 2002 2003 static void set(Function &Fn, 2004 Attribute::AttrKind Kind, bool Val) { 2005 if (Val) 2006 Fn.addFnAttr(Kind); 2007 else 2008 Fn.removeFnAttr(Kind); 2009 } 2010 }; 2011 2012 struct StrBoolAttr { 2013 static bool isSet(const Function &Fn, 2014 StringRef Kind) { 2015 auto A = Fn.getFnAttribute(Kind); 2016 return A.getValueAsString().equals("true"); 2017 } 2018 2019 static void set(Function &Fn, 2020 StringRef Kind, bool Val) { 2021 Fn.addFnAttr(Kind, Val ? "true" : "false"); 2022 } 2023 }; 2024 2025 #define GET_ATTR_NAMES 2026 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 2027 struct ENUM_NAME##Attr : EnumAttr { \ 2028 static enum Attribute::AttrKind getKind() { \ 2029 return llvm::Attribute::ENUM_NAME; \ 2030 } \ 2031 }; 2032 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \ 2033 struct ENUM_NAME##Attr : StrBoolAttr { \ 2034 static StringRef getKind() { return #DISPLAY_NAME; } \ 2035 }; 2036 #include "llvm/IR/Attributes.inc" 2037 2038 #define GET_ATTR_COMPAT_FUNC 2039 #include "llvm/IR/Attributes.inc" 2040 2041 bool AttributeFuncs::areInlineCompatible(const Function &Caller, 2042 const Function &Callee) { 2043 return hasCompatibleFnAttrs(Caller, Callee); 2044 } 2045 2046 bool AttributeFuncs::areOutlineCompatible(const Function &A, 2047 const Function &B) { 2048 return hasCompatibleFnAttrs(A, B); 2049 } 2050 2051 void AttributeFuncs::mergeAttributesForInlining(Function &Caller, 2052 const Function &Callee) { 2053 mergeFnAttrs(Caller, Callee); 2054 } 2055 2056 void AttributeFuncs::mergeAttributesForOutlining(Function &Base, 2057 const Function &ToMerge) { 2058 2059 // We merge functions so that they meet the most general case. 2060 // For example, if the NoNansFPMathAttr is set in one function, but not in 2061 // the other, in the merged function we can say that the NoNansFPMathAttr 2062 // is not set. 2063 // However if we have the SpeculativeLoadHardeningAttr set true in one 2064 // function, but not the other, we make sure that the function retains 2065 // that aspect in the merged function. 2066 mergeFnAttrs(Base, ToMerge); 2067 } 2068