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