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