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