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