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