1 //===- llvm/Function.h - Class to represent a single function ---*- C++ -*-===// 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 // This file contains the declaration of the Function class, which represents a 10 // single function/procedure in LLVM. 11 // 12 // A function basically consists of a list of basic blocks, a list of arguments, 13 // and a symbol table. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_IR_FUNCTION_H 18 #define LLVM_IR_FUNCTION_H 19 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/ilist_node.h" 24 #include "llvm/ADT/iterator_range.h" 25 #include "llvm/IR/Argument.h" 26 #include "llvm/IR/Attributes.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalObject.h" 31 #include "llvm/IR/GlobalValue.h" 32 #include "llvm/IR/OperandTraits.h" 33 #include "llvm/IR/SymbolTableListTraits.h" 34 #include "llvm/IR/Value.h" 35 #include <cassert> 36 #include <cstddef> 37 #include <cstdint> 38 #include <memory> 39 #include <string> 40 41 namespace llvm { 42 43 namespace Intrinsic { 44 typedef unsigned ID; 45 } 46 47 class AssemblyAnnotationWriter; 48 class Constant; 49 class ConstantRange; 50 struct DenormalMode; 51 class DISubprogram; 52 enum LibFunc : unsigned; 53 class LLVMContext; 54 class Module; 55 class raw_ostream; 56 class TargetLibraryInfoImpl; 57 class Type; 58 class User; 59 class BranchProbabilityInfo; 60 class BlockFrequencyInfo; 61 62 class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject, 63 public ilist_node<Function> { 64 public: 65 using BasicBlockListType = SymbolTableList<BasicBlock>; 66 67 // BasicBlock iterators... 68 using iterator = BasicBlockListType::iterator; 69 using const_iterator = BasicBlockListType::const_iterator; 70 71 using arg_iterator = Argument *; 72 using const_arg_iterator = const Argument *; 73 74 private: 75 // Important things that make up a function! 76 BasicBlockListType BasicBlocks; ///< The basic blocks 77 mutable Argument *Arguments = nullptr; ///< The formal arguments 78 size_t NumArgs; 79 std::unique_ptr<ValueSymbolTable> 80 SymTab; ///< Symbol table of args/instructions 81 AttributeList AttributeSets; ///< Parameter attributes 82 83 /* 84 * Value::SubclassData 85 * 86 * bit 0 : HasLazyArguments 87 * bit 1 : HasPrefixData 88 * bit 2 : HasPrologueData 89 * bit 3 : HasPersonalityFn 90 * bits 4-13 : CallingConvention 91 * bits 14 : HasGC 92 * bits 15 : [reserved] 93 */ 94 95 /// Bits from GlobalObject::GlobalObjectSubclassData. 96 enum { 97 /// Whether this function is materializable. 98 IsMaterializableBit = 0, 99 }; 100 101 friend class SymbolTableListTraits<Function>; 102 103 public: 104 /// Is this function using intrinsics to record the position of debugging 105 /// information, or non-intrinsic records? See IsNewDbgInfoFormat in 106 /// \ref BasicBlock. 107 bool IsNewDbgInfoFormat; 108 109 /// hasLazyArguments/CheckLazyArguments - The argument list of a function is 110 /// built on demand, so that the list isn't allocated until the first client 111 /// needs it. The hasLazyArguments predicate returns true if the arg list 112 /// hasn't been set up yet. hasLazyArguments()113 bool hasLazyArguments() const { 114 return getSubclassDataFromValue() & (1<<0); 115 } 116 117 /// \see BasicBlock::convertToNewDbgValues. 118 void convertToNewDbgValues(); 119 120 /// \see BasicBlock::convertFromNewDbgValues. 121 void convertFromNewDbgValues(); 122 123 void setIsNewDbgInfoFormat(bool NewVal); 124 void setNewDbgInfoFormatFlag(bool NewVal); 125 126 private: 127 friend class TargetLibraryInfoImpl; 128 129 static constexpr LibFunc UnknownLibFunc = LibFunc(-1); 130 131 /// Cache for TLI::getLibFunc() result without prototype validation. 132 /// UnknownLibFunc if uninitialized. NotLibFunc if definitely not lib func. 133 /// Otherwise may be libfunc if prototype validation passes. 134 mutable LibFunc LibFuncCache = UnknownLibFunc; 135 CheckLazyArguments()136 void CheckLazyArguments() const { 137 if (hasLazyArguments()) 138 BuildLazyArguments(); 139 } 140 141 void BuildLazyArguments() const; 142 143 void clearArguments(); 144 145 void deleteBodyImpl(bool ShouldDrop); 146 147 /// Function ctor - If the (optional) Module argument is specified, the 148 /// function is automatically inserted into the end of the function list for 149 /// the module. 150 /// 151 Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 152 const Twine &N = "", Module *M = nullptr); 153 154 public: 155 Function(const Function&) = delete; 156 void operator=(const Function&) = delete; 157 ~Function(); 158 159 // This is here to help easily convert from FunctionT * (Function * or 160 // MachineFunction *) in BlockFrequencyInfoImpl to Function * by calling 161 // FunctionT->getFunction(). getFunction()162 const Function &getFunction() const { return *this; } 163 164 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 165 unsigned AddrSpace, const Twine &N = "", 166 Module *M = nullptr) { 167 return new Function(Ty, Linkage, AddrSpace, N, M); 168 } 169 170 // TODO: remove this once all users have been updated to pass an AddrSpace 171 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 172 const Twine &N = "", Module *M = nullptr) { 173 return new Function(Ty, Linkage, static_cast<unsigned>(-1), N, M); 174 } 175 176 /// Creates a new function and attaches it to a module. 177 /// 178 /// Places the function in the program address space as specified 179 /// by the module's data layout. 180 static Function *Create(FunctionType *Ty, LinkageTypes Linkage, 181 const Twine &N, Module &M); 182 183 /// Creates a function with some attributes recorded in llvm.module.flags 184 /// and the LLVMContext applied. 185 /// 186 /// Use this when synthesizing new functions that need attributes that would 187 /// have been set by command line options. 188 /// 189 /// This function should not be called from backends or the LTO pipeline. If 190 /// it is called from one of those places, some default attributes will not be 191 /// applied to the function. 192 static Function *createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, 193 unsigned AddrSpace, 194 const Twine &N = "", 195 Module *M = nullptr); 196 197 // Provide fast operand accessors. 198 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 199 200 /// Returns the number of non-debug IR instructions in this function. 201 /// This is equivalent to the sum of the sizes of each basic block contained 202 /// within this function. 203 unsigned getInstructionCount() const; 204 205 /// Returns the FunctionType for me. getFunctionType()206 FunctionType *getFunctionType() const { 207 return cast<FunctionType>(getValueType()); 208 } 209 210 /// Returns the type of the ret val. getReturnType()211 Type *getReturnType() const { return getFunctionType()->getReturnType(); } 212 213 /// getContext - Return a reference to the LLVMContext associated with this 214 /// function. 215 LLVMContext &getContext() const; 216 217 /// isVarArg - Return true if this function takes a variable number of 218 /// arguments. isVarArg()219 bool isVarArg() const { return getFunctionType()->isVarArg(); } 220 isMaterializable()221 bool isMaterializable() const { 222 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit); 223 } setIsMaterializable(bool V)224 void setIsMaterializable(bool V) { 225 unsigned Mask = 1 << IsMaterializableBit; 226 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) | 227 (V ? Mask : 0u)); 228 } 229 230 /// getIntrinsicID - This method returns the ID number of the specified 231 /// function, or Intrinsic::not_intrinsic if the function is not an 232 /// intrinsic, or if the pointer is null. This value is always defined to be 233 /// zero to allow easy checking for whether a function is intrinsic or not. 234 /// The particular intrinsic functions which correspond to this value are 235 /// defined in llvm/Intrinsics.h. getIntrinsicID()236 Intrinsic::ID getIntrinsicID() const LLVM_READONLY { return IntID; } 237 238 /// isIntrinsic - Returns true if the function's name starts with "llvm.". 239 /// It's possible for this function to return true while getIntrinsicID() 240 /// returns Intrinsic::not_intrinsic! isIntrinsic()241 bool isIntrinsic() const { return HasLLVMReservedName; } 242 243 /// isTargetIntrinsic - Returns true if IID is an intrinsic specific to a 244 /// certain target. If it is a generic intrinsic false is returned. 245 static bool isTargetIntrinsic(Intrinsic::ID IID); 246 247 /// isTargetIntrinsic - Returns true if this function is an intrinsic and the 248 /// intrinsic is specific to a certain target. If this is not an intrinsic 249 /// or a generic intrinsic, false is returned. 250 bool isTargetIntrinsic() const; 251 252 /// Returns true if the function is one of the "Constrained Floating-Point 253 /// Intrinsics". Returns false if not, and returns false when 254 /// getIntrinsicID() returns Intrinsic::not_intrinsic. 255 bool isConstrainedFPIntrinsic() const; 256 257 static Intrinsic::ID lookupIntrinsicID(StringRef Name); 258 259 /// Update internal caches that depend on the function name (such as the 260 /// intrinsic ID and libcall cache). 261 /// Note, this method does not need to be called directly, as it is called 262 /// from Value::setName() whenever the name of this function changes. 263 void updateAfterNameChange(); 264 265 /// getCallingConv()/setCallingConv(CC) - These method get and set the 266 /// calling convention of this function. The enum values for the known 267 /// calling conventions are defined in CallingConv.h. getCallingConv()268 CallingConv::ID getCallingConv() const { 269 return static_cast<CallingConv::ID>((getSubclassDataFromValue() >> 4) & 270 CallingConv::MaxID); 271 } setCallingConv(CallingConv::ID CC)272 void setCallingConv(CallingConv::ID CC) { 273 auto ID = static_cast<unsigned>(CC); 274 assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention"); 275 setValueSubclassData((getSubclassDataFromValue() & 0xc00f) | (ID << 4)); 276 } 277 278 enum ProfileCountType { PCT_Real, PCT_Synthetic }; 279 280 /// Class to represent profile counts. 281 /// 282 /// This class represents both real and synthetic profile counts. 283 class ProfileCount { 284 private: 285 uint64_t Count = 0; 286 ProfileCountType PCT = PCT_Real; 287 288 public: ProfileCount(uint64_t Count,ProfileCountType PCT)289 ProfileCount(uint64_t Count, ProfileCountType PCT) 290 : Count(Count), PCT(PCT) {} getCount()291 uint64_t getCount() const { return Count; } getType()292 ProfileCountType getType() const { return PCT; } isSynthetic()293 bool isSynthetic() const { return PCT == PCT_Synthetic; } 294 }; 295 296 /// Set the entry count for this function. 297 /// 298 /// Entry count is the number of times this function was executed based on 299 /// pgo data. \p Imports points to a set of GUIDs that needs to 300 /// be imported by the function for sample PGO, to enable the same inlines as 301 /// the profiled optimized binary. 302 void setEntryCount(ProfileCount Count, 303 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 304 305 /// A convenience wrapper for setting entry count 306 void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real, 307 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 308 309 /// Get the entry count for this function. 310 /// 311 /// Entry count is the number of times the function was executed. 312 /// When AllowSynthetic is false, only pgo_data will be returned. 313 std::optional<ProfileCount> getEntryCount(bool AllowSynthetic = false) const; 314 315 /// Return true if the function is annotated with profile data. 316 /// 317 /// Presence of entry counts from a profile run implies the function has 318 /// profile annotations. If IncludeSynthetic is false, only return true 319 /// when the profile data is real. 320 bool hasProfileData(bool IncludeSynthetic = false) const { 321 return getEntryCount(IncludeSynthetic).has_value(); 322 } 323 324 /// Returns the set of GUIDs that needs to be imported to the function for 325 /// sample PGO, to enable the same inlines as the profiled optimized binary. 326 DenseSet<GlobalValue::GUID> getImportGUIDs() const; 327 328 /// Set the section prefix for this function. 329 void setSectionPrefix(StringRef Prefix); 330 331 /// Get the section prefix for this function. 332 std::optional<StringRef> getSectionPrefix() const; 333 334 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm 335 /// to use during code generation. hasGC()336 bool hasGC() const { 337 return getSubclassDataFromValue() & (1<<14); 338 } 339 const std::string &getGC() const; 340 void setGC(std::string Str); 341 void clearGC(); 342 343 /// Return the attribute list for this Function. getAttributes()344 AttributeList getAttributes() const { return AttributeSets; } 345 346 /// Set the attribute list for this Function. setAttributes(AttributeList Attrs)347 void setAttributes(AttributeList Attrs) { AttributeSets = Attrs; } 348 349 // TODO: remove non-AtIndex versions of these methods. 350 /// adds the attribute to the list of attributes. 351 void addAttributeAtIndex(unsigned i, Attribute Attr); 352 353 /// Add function attributes to this function. 354 void addFnAttr(Attribute::AttrKind Kind); 355 356 /// Add function attributes to this function. 357 void addFnAttr(StringRef Kind, StringRef Val = StringRef()); 358 359 /// Add function attributes to this function. 360 void addFnAttr(Attribute Attr); 361 362 /// Add function attributes to this function. 363 void addFnAttrs(const AttrBuilder &Attrs); 364 365 /// Add return value attributes to this function. 366 void addRetAttr(Attribute::AttrKind Kind); 367 368 /// Add return value attributes to this function. 369 void addRetAttr(Attribute Attr); 370 371 /// Add return value attributes to this function. 372 void addRetAttrs(const AttrBuilder &Attrs); 373 374 /// adds the attribute to the list of attributes for the given arg. 375 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 376 377 /// adds the attribute to the list of attributes for the given arg. 378 void addParamAttr(unsigned ArgNo, Attribute Attr); 379 380 /// adds the attributes to the list of attributes for the given arg. 381 void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 382 383 /// removes the attribute from the list of attributes. 384 void removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind); 385 386 /// removes the attribute from the list of attributes. 387 void removeAttributeAtIndex(unsigned i, StringRef Kind); 388 389 /// Remove function attributes from this function. 390 void removeFnAttr(Attribute::AttrKind Kind); 391 392 /// Remove function attribute from this function. 393 void removeFnAttr(StringRef Kind); 394 395 void removeFnAttrs(const AttributeMask &Attrs); 396 397 /// removes the attribute from the return value list of attributes. 398 void removeRetAttr(Attribute::AttrKind Kind); 399 400 /// removes the attribute from the return value list of attributes. 401 void removeRetAttr(StringRef Kind); 402 403 /// removes the attributes from the return value list of attributes. 404 void removeRetAttrs(const AttributeMask &Attrs); 405 406 /// removes the attribute from the list of attributes. 407 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 408 409 /// removes the attribute from the list of attributes. 410 void removeParamAttr(unsigned ArgNo, StringRef Kind); 411 412 /// removes the attribute from the list of attributes. 413 void removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs); 414 415 /// Return true if the function has the attribute. 416 bool hasFnAttribute(Attribute::AttrKind Kind) const; 417 418 /// Return true if the function has the attribute. 419 bool hasFnAttribute(StringRef Kind) const; 420 421 /// check if an attribute is in the list of attributes for the return value. 422 bool hasRetAttribute(Attribute::AttrKind Kind) const; 423 424 /// check if an attributes is in the list of attributes. 425 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const; 426 427 /// gets the attribute from the list of attributes. 428 Attribute getAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) const; 429 430 /// gets the attribute from the list of attributes. 431 Attribute getAttributeAtIndex(unsigned i, StringRef Kind) const; 432 433 /// Return the attribute for the given attribute kind. 434 Attribute getFnAttribute(Attribute::AttrKind Kind) const; 435 436 /// Return the attribute for the given attribute kind. 437 Attribute getFnAttribute(StringRef Kind) const; 438 439 /// Return the attribute for the given attribute kind for the return value. 440 Attribute getRetAttribute(Attribute::AttrKind Kind) const; 441 442 /// For a string attribute \p Kind, parse attribute as an integer. 443 /// 444 /// \returns \p Default if attribute is not present. 445 /// 446 /// \returns \p Default if there is an error parsing the attribute integer, 447 /// and error is emitted to the LLVMContext 448 uint64_t getFnAttributeAsParsedInteger(StringRef Kind, 449 uint64_t Default = 0) const; 450 451 /// gets the specified attribute from the list of attributes. 452 Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const; 453 454 /// Return the stack alignment for the function. getFnStackAlign()455 MaybeAlign getFnStackAlign() const { 456 return AttributeSets.getFnStackAlignment(); 457 } 458 459 /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs. 460 bool hasStackProtectorFnAttr() const; 461 462 /// adds the dereferenceable attribute to the list of attributes for 463 /// the given arg. 464 void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes); 465 466 /// adds the dereferenceable_or_null attribute to the list of 467 /// attributes for the given arg. 468 void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes); 469 470 /// adds the range attribute to the list of attributes for the return value. 471 void addRangeRetAttr(const ConstantRange &CR); 472 getParamAlign(unsigned ArgNo)473 MaybeAlign getParamAlign(unsigned ArgNo) const { 474 return AttributeSets.getParamAlignment(ArgNo); 475 } 476 getParamStackAlign(unsigned ArgNo)477 MaybeAlign getParamStackAlign(unsigned ArgNo) const { 478 return AttributeSets.getParamStackAlignment(ArgNo); 479 } 480 481 /// Extract the byval type for a parameter. getParamByValType(unsigned ArgNo)482 Type *getParamByValType(unsigned ArgNo) const { 483 return AttributeSets.getParamByValType(ArgNo); 484 } 485 486 /// Extract the sret type for a parameter. getParamStructRetType(unsigned ArgNo)487 Type *getParamStructRetType(unsigned ArgNo) const { 488 return AttributeSets.getParamStructRetType(ArgNo); 489 } 490 491 /// Extract the inalloca type for a parameter. getParamInAllocaType(unsigned ArgNo)492 Type *getParamInAllocaType(unsigned ArgNo) const { 493 return AttributeSets.getParamInAllocaType(ArgNo); 494 } 495 496 /// Extract the byref type for a parameter. getParamByRefType(unsigned ArgNo)497 Type *getParamByRefType(unsigned ArgNo) const { 498 return AttributeSets.getParamByRefType(ArgNo); 499 } 500 501 /// Extract the preallocated type for a parameter. getParamPreallocatedType(unsigned ArgNo)502 Type *getParamPreallocatedType(unsigned ArgNo) const { 503 return AttributeSets.getParamPreallocatedType(ArgNo); 504 } 505 506 /// Extract the number of dereferenceable bytes for a parameter. 507 /// @param ArgNo Index of an argument, with 0 being the first function arg. getParamDereferenceableBytes(unsigned ArgNo)508 uint64_t getParamDereferenceableBytes(unsigned ArgNo) const { 509 return AttributeSets.getParamDereferenceableBytes(ArgNo); 510 } 511 512 /// Extract the number of dereferenceable_or_null bytes for a 513 /// parameter. 514 /// @param ArgNo AttributeList ArgNo, referring to an argument. getParamDereferenceableOrNullBytes(unsigned ArgNo)515 uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const { 516 return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo); 517 } 518 519 /// Extract the nofpclass attribute for a parameter. getParamNoFPClass(unsigned ArgNo)520 FPClassTest getParamNoFPClass(unsigned ArgNo) const { 521 return AttributeSets.getParamNoFPClass(ArgNo); 522 } 523 524 /// Determine if the function is presplit coroutine. isPresplitCoroutine()525 bool isPresplitCoroutine() const { 526 return hasFnAttribute(Attribute::PresplitCoroutine); 527 } setPresplitCoroutine()528 void setPresplitCoroutine() { addFnAttr(Attribute::PresplitCoroutine); } setSplittedCoroutine()529 void setSplittedCoroutine() { removeFnAttr(Attribute::PresplitCoroutine); } 530 isCoroOnlyDestroyWhenComplete()531 bool isCoroOnlyDestroyWhenComplete() const { 532 return hasFnAttribute(Attribute::CoroDestroyOnlyWhenComplete); 533 } setCoroDestroyOnlyWhenComplete()534 void setCoroDestroyOnlyWhenComplete() { 535 addFnAttr(Attribute::CoroDestroyOnlyWhenComplete); 536 } 537 538 MemoryEffects getMemoryEffects() const; 539 void setMemoryEffects(MemoryEffects ME); 540 541 /// Determine if the function does not access memory. 542 bool doesNotAccessMemory() const; 543 void setDoesNotAccessMemory(); 544 545 /// Determine if the function does not access or only reads memory. 546 bool onlyReadsMemory() const; 547 void setOnlyReadsMemory(); 548 549 /// Determine if the function does not access or only writes memory. 550 bool onlyWritesMemory() const; 551 void setOnlyWritesMemory(); 552 553 /// Determine if the call can access memmory only using pointers based 554 /// on its arguments. 555 bool onlyAccessesArgMemory() const; 556 void setOnlyAccessesArgMemory(); 557 558 /// Determine if the function may only access memory that is 559 /// inaccessible from the IR. 560 bool onlyAccessesInaccessibleMemory() const; 561 void setOnlyAccessesInaccessibleMemory(); 562 563 /// Determine if the function may only access memory that is 564 /// either inaccessible from the IR or pointed to by its arguments. 565 bool onlyAccessesInaccessibleMemOrArgMem() const; 566 void setOnlyAccessesInaccessibleMemOrArgMem(); 567 568 /// Determine if the function cannot return. doesNotReturn()569 bool doesNotReturn() const { 570 return hasFnAttribute(Attribute::NoReturn); 571 } setDoesNotReturn()572 void setDoesNotReturn() { 573 addFnAttr(Attribute::NoReturn); 574 } 575 576 /// Determine if the function should not perform indirect branch tracking. doesNoCfCheck()577 bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); } 578 579 /// Determine if the function cannot unwind. doesNotThrow()580 bool doesNotThrow() const { 581 return hasFnAttribute(Attribute::NoUnwind); 582 } setDoesNotThrow()583 void setDoesNotThrow() { 584 addFnAttr(Attribute::NoUnwind); 585 } 586 587 /// Determine if the call cannot be duplicated. cannotDuplicate()588 bool cannotDuplicate() const { 589 return hasFnAttribute(Attribute::NoDuplicate); 590 } setCannotDuplicate()591 void setCannotDuplicate() { 592 addFnAttr(Attribute::NoDuplicate); 593 } 594 595 /// Determine if the call is convergent. isConvergent()596 bool isConvergent() const { 597 return hasFnAttribute(Attribute::Convergent); 598 } setConvergent()599 void setConvergent() { 600 addFnAttr(Attribute::Convergent); 601 } setNotConvergent()602 void setNotConvergent() { 603 removeFnAttr(Attribute::Convergent); 604 } 605 606 /// Determine if the call has sideeffects. isSpeculatable()607 bool isSpeculatable() const { 608 return hasFnAttribute(Attribute::Speculatable); 609 } setSpeculatable()610 void setSpeculatable() { 611 addFnAttr(Attribute::Speculatable); 612 } 613 614 /// Determine if the call might deallocate memory. doesNotFreeMemory()615 bool doesNotFreeMemory() const { 616 return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree); 617 } setDoesNotFreeMemory()618 void setDoesNotFreeMemory() { 619 addFnAttr(Attribute::NoFree); 620 } 621 622 /// Determine if the call can synchroize with other threads hasNoSync()623 bool hasNoSync() const { 624 return hasFnAttribute(Attribute::NoSync); 625 } setNoSync()626 void setNoSync() { 627 addFnAttr(Attribute::NoSync); 628 } 629 630 /// Determine if the function is known not to recurse, directly or 631 /// indirectly. doesNotRecurse()632 bool doesNotRecurse() const { 633 return hasFnAttribute(Attribute::NoRecurse); 634 } setDoesNotRecurse()635 void setDoesNotRecurse() { 636 addFnAttr(Attribute::NoRecurse); 637 } 638 639 /// Determine if the function is required to make forward progress. mustProgress()640 bool mustProgress() const { 641 return hasFnAttribute(Attribute::MustProgress) || 642 hasFnAttribute(Attribute::WillReturn); 643 } setMustProgress()644 void setMustProgress() { addFnAttr(Attribute::MustProgress); } 645 646 /// Determine if the function will return. willReturn()647 bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); } setWillReturn()648 void setWillReturn() { addFnAttr(Attribute::WillReturn); } 649 650 /// Get what kind of unwind table entry to generate for this function. getUWTableKind()651 UWTableKind getUWTableKind() const { 652 return AttributeSets.getUWTableKind(); 653 } 654 655 /// True if the ABI mandates (or the user requested) that this 656 /// function be in a unwind table. hasUWTable()657 bool hasUWTable() const { 658 return getUWTableKind() != UWTableKind::None; 659 } setUWTableKind(UWTableKind K)660 void setUWTableKind(UWTableKind K) { 661 addFnAttr(Attribute::getWithUWTableKind(getContext(), K)); 662 } 663 /// True if this function needs an unwind table. needsUnwindTableEntry()664 bool needsUnwindTableEntry() const { 665 return hasUWTable() || !doesNotThrow() || hasPersonalityFn(); 666 } 667 668 /// Determine if the function returns a structure through first 669 /// or second pointer argument. hasStructRetAttr()670 bool hasStructRetAttr() const { 671 return AttributeSets.hasParamAttr(0, Attribute::StructRet) || 672 AttributeSets.hasParamAttr(1, Attribute::StructRet); 673 } 674 675 /// Determine if the parameter or return value is marked with NoAlias 676 /// attribute. returnDoesNotAlias()677 bool returnDoesNotAlias() const { 678 return AttributeSets.hasRetAttr(Attribute::NoAlias); 679 } setReturnDoesNotAlias()680 void setReturnDoesNotAlias() { addRetAttr(Attribute::NoAlias); } 681 682 /// Do not optimize this function (-O0). hasOptNone()683 bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); } 684 685 /// Optimize this function for minimum size (-Oz). hasMinSize()686 bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); } 687 688 /// Optimize this function for size (-Os) or minimum size (-Oz). hasOptSize()689 bool hasOptSize() const { 690 return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize(); 691 } 692 693 /// Returns the denormal handling type for the default rounding mode of the 694 /// function. 695 DenormalMode getDenormalMode(const fltSemantics &FPType) const; 696 697 /// Return the representational value of "denormal-fp-math". Code interested 698 /// in the semantics of the function should use getDenormalMode instead. 699 DenormalMode getDenormalModeRaw() const; 700 701 /// Return the representational value of "denormal-fp-math-f32". Code 702 /// interested in the semantics of the function should use getDenormalMode 703 /// instead. 704 DenormalMode getDenormalModeF32Raw() const; 705 706 /// copyAttributesFrom - copy all additional attributes (those not needed to 707 /// create a Function) from the Function Src to this one. 708 void copyAttributesFrom(const Function *Src); 709 710 /// deleteBody - This method deletes the body of the function, and converts 711 /// the linkage to external. 712 /// deleteBody()713 void deleteBody() { 714 deleteBodyImpl(/*ShouldDrop=*/false); 715 setLinkage(ExternalLinkage); 716 } 717 718 /// removeFromParent - This method unlinks 'this' from the containing module, 719 /// but does not delete it. 720 /// 721 void removeFromParent(); 722 723 /// eraseFromParent - This method unlinks 'this' from the containing module 724 /// and deletes it. 725 /// 726 void eraseFromParent(); 727 728 /// Steal arguments from another function. 729 /// 730 /// Drop this function's arguments and splice in the ones from \c Src. 731 /// Requires that this has no function body. 732 void stealArgumentListFrom(Function &Src); 733 734 /// Insert \p BB in the basic block list at \p Position. \Returns an iterator 735 /// to the newly inserted BB. insert(Function::iterator Position,BasicBlock * BB)736 Function::iterator insert(Function::iterator Position, BasicBlock *BB) { 737 Function::iterator FIt = BasicBlocks.insert(Position, BB); 738 BB->setIsNewDbgInfoFormat(IsNewDbgInfoFormat); 739 return FIt; 740 } 741 742 /// Transfer all blocks from \p FromF to this function at \p ToIt. splice(Function::iterator ToIt,Function * FromF)743 void splice(Function::iterator ToIt, Function *FromF) { 744 splice(ToIt, FromF, FromF->begin(), FromF->end()); 745 } 746 747 /// Transfer one BasicBlock from \p FromF at \p FromIt to this function 748 /// at \p ToIt. splice(Function::iterator ToIt,Function * FromF,Function::iterator FromIt)749 void splice(Function::iterator ToIt, Function *FromF, 750 Function::iterator FromIt) { 751 auto FromItNext = std::next(FromIt); 752 // Single-element splice is a noop if destination == source. 753 if (ToIt == FromIt || ToIt == FromItNext) 754 return; 755 splice(ToIt, FromF, FromIt, FromItNext); 756 } 757 758 /// Transfer a range of basic blocks that belong to \p FromF from \p 759 /// FromBeginIt to \p FromEndIt, to this function at \p ToIt. 760 void splice(Function::iterator ToIt, Function *FromF, 761 Function::iterator FromBeginIt, 762 Function::iterator FromEndIt); 763 764 /// Erases a range of BasicBlocks from \p FromIt to (not including) \p ToIt. 765 /// \Returns \p ToIt. 766 Function::iterator erase(Function::iterator FromIt, Function::iterator ToIt); 767 768 private: 769 // These need access to the underlying BB list. 770 friend void BasicBlock::removeFromParent(); 771 friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent(); 772 template <class BB_t, class BB_i_t, class BI_t, class II_t> 773 friend class InstIterator; 774 friend class llvm::SymbolTableListTraits<llvm::BasicBlock>; 775 friend class llvm::ilist_node_with_parent<llvm::BasicBlock, llvm::Function>; 776 777 /// Get the underlying elements of the Function... the basic block list is 778 /// empty for external functions. 779 /// 780 /// This is deliberately private because we have implemented an adequate set 781 /// of functions to modify the list, including Function::splice(), 782 /// Function::erase(), Function::insert() etc. getBasicBlockList()783 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; } getBasicBlockList()784 BasicBlockListType &getBasicBlockList() { return BasicBlocks; } 785 getSublistAccess(BasicBlock *)786 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) { 787 return &Function::BasicBlocks; 788 } 789 790 public: getEntryBlock()791 const BasicBlock &getEntryBlock() const { return front(); } getEntryBlock()792 BasicBlock &getEntryBlock() { return front(); } 793 794 //===--------------------------------------------------------------------===// 795 // Symbol Table Accessing functions... 796 797 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr. 798 /// getValueSymbolTable()799 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); } getValueSymbolTable()800 inline const ValueSymbolTable *getValueSymbolTable() const { 801 return SymTab.get(); 802 } 803 804 //===--------------------------------------------------------------------===// 805 // BasicBlock iterator forwarding functions 806 // begin()807 iterator begin() { return BasicBlocks.begin(); } begin()808 const_iterator begin() const { return BasicBlocks.begin(); } end()809 iterator end () { return BasicBlocks.end(); } end()810 const_iterator end () const { return BasicBlocks.end(); } 811 size()812 size_t size() const { return BasicBlocks.size(); } empty()813 bool empty() const { return BasicBlocks.empty(); } front()814 const BasicBlock &front() const { return BasicBlocks.front(); } front()815 BasicBlock &front() { return BasicBlocks.front(); } back()816 const BasicBlock &back() const { return BasicBlocks.back(); } back()817 BasicBlock &back() { return BasicBlocks.back(); } 818 819 /// @name Function Argument Iteration 820 /// @{ 821 arg_begin()822 arg_iterator arg_begin() { 823 CheckLazyArguments(); 824 return Arguments; 825 } arg_begin()826 const_arg_iterator arg_begin() const { 827 CheckLazyArguments(); 828 return Arguments; 829 } 830 arg_end()831 arg_iterator arg_end() { 832 CheckLazyArguments(); 833 return Arguments + NumArgs; 834 } arg_end()835 const_arg_iterator arg_end() const { 836 CheckLazyArguments(); 837 return Arguments + NumArgs; 838 } 839 getArg(unsigned i)840 Argument* getArg(unsigned i) const { 841 assert (i < NumArgs && "getArg() out of range!"); 842 CheckLazyArguments(); 843 return Arguments + i; 844 } 845 args()846 iterator_range<arg_iterator> args() { 847 return make_range(arg_begin(), arg_end()); 848 } args()849 iterator_range<const_arg_iterator> args() const { 850 return make_range(arg_begin(), arg_end()); 851 } 852 853 /// @} 854 arg_size()855 size_t arg_size() const { return NumArgs; } arg_empty()856 bool arg_empty() const { return arg_size() == 0; } 857 858 /// Check whether this function has a personality function. hasPersonalityFn()859 bool hasPersonalityFn() const { 860 return getSubclassDataFromValue() & (1<<3); 861 } 862 863 /// Get the personality function associated with this function. 864 Constant *getPersonalityFn() const; 865 void setPersonalityFn(Constant *Fn); 866 867 /// Check whether this function has prefix data. hasPrefixData()868 bool hasPrefixData() const { 869 return getSubclassDataFromValue() & (1<<1); 870 } 871 872 /// Get the prefix data associated with this function. 873 Constant *getPrefixData() const; 874 void setPrefixData(Constant *PrefixData); 875 876 /// Check whether this function has prologue data. hasPrologueData()877 bool hasPrologueData() const { 878 return getSubclassDataFromValue() & (1<<2); 879 } 880 881 /// Get the prologue data associated with this function. 882 Constant *getPrologueData() const; 883 void setPrologueData(Constant *PrologueData); 884 885 /// Print the function to an output stream with an optional 886 /// AssemblyAnnotationWriter. 887 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr, 888 bool ShouldPreserveUseListOrder = false, 889 bool IsForDebug = false) const; 890 891 /// viewCFG - This function is meant for use from the debugger. You can just 892 /// say 'call F->viewCFG()' and a ghostview window should pop up from the 893 /// program, displaying the CFG of the current function with the code for each 894 /// basic block inside. This depends on there being a 'dot' and 'gv' program 895 /// in your path. 896 /// 897 void viewCFG() const; 898 899 /// Extended form to print edge weights. 900 void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI, 901 const BranchProbabilityInfo *BPI) const; 902 903 /// viewCFGOnly - This function is meant for use from the debugger. It works 904 /// just like viewCFG, but it does not include the contents of basic blocks 905 /// into the nodes, just the label. If you are only interested in the CFG 906 /// this can make the graph smaller. 907 /// 908 void viewCFGOnly() const; 909 910 /// Extended form to print edge weights. 911 void viewCFGOnly(const BlockFrequencyInfo *BFI, 912 const BranchProbabilityInfo *BPI) const; 913 914 /// Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)915 static bool classof(const Value *V) { 916 return V->getValueID() == Value::FunctionVal; 917 } 918 919 /// dropAllReferences() - This method causes all the subinstructions to "let 920 /// go" of all references that they are maintaining. This allows one to 921 /// 'delete' a whole module at a time, even though there may be circular 922 /// references... first all references are dropped, and all use counts go to 923 /// zero. Then everything is deleted for real. Note that no operations are 924 /// valid on an object that has "dropped all references", except operator 925 /// delete. 926 /// 927 /// Since no other object in the module can have references into the body of a 928 /// function, dropping all references deletes the entire body of the function, 929 /// including any contained basic blocks. 930 /// dropAllReferences()931 void dropAllReferences() { 932 deleteBodyImpl(/*ShouldDrop=*/true); 933 } 934 935 /// hasAddressTaken - returns true if there are any uses of this function 936 /// other than direct calls or invokes to it, or blockaddress expressions. 937 /// Optionally passes back an offending user for diagnostic purposes, 938 /// ignores callback uses, assume like pointer annotation calls, references in 939 /// llvm.used and llvm.compiler.used variables, operand bundle 940 /// "clang.arc.attachedcall", and direct calls with a different call site 941 /// signature (the function is implicitly casted). 942 bool hasAddressTaken(const User ** = nullptr, bool IgnoreCallbackUses = false, 943 bool IgnoreAssumeLikeCalls = true, 944 bool IngoreLLVMUsed = false, 945 bool IgnoreARCAttachedCall = false, 946 bool IgnoreCastedDirectCall = false) const; 947 948 /// isDefTriviallyDead - Return true if it is trivially safe to remove 949 /// this function definition from the module (because it isn't externally 950 /// visible, does not have its address taken, and has no callers). To make 951 /// this more accurate, call removeDeadConstantUsers first. 952 bool isDefTriviallyDead() const; 953 954 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 955 /// setjmp or other function that gcc recognizes as "returning twice". 956 bool callsFunctionThatReturnsTwice() const; 957 958 /// Set the attached subprogram. 959 /// 960 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg. 961 void setSubprogram(DISubprogram *SP); 962 963 /// Get the attached subprogram. 964 /// 965 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result 966 /// to \a DISubprogram. 967 DISubprogram *getSubprogram() const; 968 969 /// Returns true if we should emit debug info for profiling. 970 bool shouldEmitDebugInfoForProfiling() const; 971 972 /// Check if null pointer dereferencing is considered undefined behavior for 973 /// the function. 974 /// Return value: false => null pointer dereference is undefined. 975 /// Return value: true => null pointer dereference is not undefined. 976 bool nullPointerIsDefined() const; 977 978 private: 979 void allocHungoffUselist(); 980 template<int Idx> void setHungoffOperand(Constant *C); 981 982 /// Shadow Value::setValueSubclassData with a private forwarding method so 983 /// that subclasses cannot accidentally use it. setValueSubclassData(unsigned short D)984 void setValueSubclassData(unsigned short D) { 985 Value::setValueSubclassData(D); 986 } 987 void setValueSubclassDataBit(unsigned Bit, bool On); 988 }; 989 990 /// Check whether null pointer dereferencing is considered undefined behavior 991 /// for a given function or an address space. 992 /// Null pointer access in non-zero address space is not considered undefined. 993 /// Return value: false => null pointer dereference is undefined. 994 /// Return value: true => null pointer dereference is not undefined. 995 bool NullPointerIsDefined(const Function *F, unsigned AS = 0); 996 997 template <> 998 struct OperandTraits<Function> : public HungoffOperandTraits<3> {}; 999 1000 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value) 1001 1002 } // end namespace llvm 1003 1004 #endif // LLVM_IR_FUNCTION_H 1005