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 /// A function will have the "coroutine.presplit" attribute if it's 272 /// a coroutine and has not gone through full CoroSplit pass. isPresplitCoroutine()273 bool isPresplitCoroutine() const { 274 return hasFnAttribute("coroutine.presplit"); 275 } 276 277 enum ProfileCountType { PCT_Invalid, PCT_Real, PCT_Synthetic }; 278 279 /// Class to represent profile counts. 280 /// 281 /// This class represents both real and synthetic profile counts. 282 class ProfileCount { 283 private: 284 uint64_t Count; 285 ProfileCountType PCT; 286 static ProfileCount Invalid; 287 288 public: ProfileCount()289 ProfileCount() : Count(-1), PCT(PCT_Invalid) {} ProfileCount(uint64_t Count,ProfileCountType PCT)290 ProfileCount(uint64_t Count, ProfileCountType PCT) 291 : Count(Count), PCT(PCT) {} hasValue()292 bool hasValue() const { return PCT != PCT_Invalid; } getCount()293 uint64_t getCount() const { return Count; } getType()294 ProfileCountType getType() const { return PCT; } isSynthetic()295 bool isSynthetic() const { return PCT == PCT_Synthetic; } 296 explicit operator bool() { return hasValue(); } 297 bool operator!() const { return !hasValue(); } 298 // Update the count retaining the same profile count type. setCount(uint64_t C)299 ProfileCount &setCount(uint64_t C) { 300 Count = C; 301 return *this; 302 } getInvalid()303 static ProfileCount getInvalid() { return ProfileCount(-1, PCT_Invalid); } 304 }; 305 306 /// Set the entry count for this function. 307 /// 308 /// Entry count is the number of times this function was executed based on 309 /// pgo data. \p Imports points to a set of GUIDs that needs to 310 /// be imported by the function for sample PGO, to enable the same inlines as 311 /// the profiled optimized binary. 312 void setEntryCount(ProfileCount Count, 313 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 314 315 /// A convenience wrapper for setting entry count 316 void setEntryCount(uint64_t Count, ProfileCountType Type = PCT_Real, 317 const DenseSet<GlobalValue::GUID> *Imports = nullptr); 318 319 /// Get the entry count for this function. 320 /// 321 /// Entry count is the number of times the function was executed. 322 /// When AllowSynthetic is false, only pgo_data will be returned. 323 ProfileCount getEntryCount(bool AllowSynthetic = false) const; 324 325 /// Return true if the function is annotated with profile data. 326 /// 327 /// Presence of entry counts from a profile run implies the function has 328 /// profile annotations. If IncludeSynthetic is false, only return true 329 /// when the profile data is real. 330 bool hasProfileData(bool IncludeSynthetic = false) const { 331 return getEntryCount(IncludeSynthetic).hasValue(); 332 } 333 334 /// Returns the set of GUIDs that needs to be imported to the function for 335 /// sample PGO, to enable the same inlines as the profiled optimized binary. 336 DenseSet<GlobalValue::GUID> getImportGUIDs() const; 337 338 /// Set the section prefix for this function. 339 void setSectionPrefix(StringRef Prefix); 340 341 /// Get the section prefix for this function. 342 Optional<StringRef> getSectionPrefix() const; 343 344 /// Return true if the function has the attribute. hasFnAttribute(Attribute::AttrKind Kind)345 bool hasFnAttribute(Attribute::AttrKind Kind) const { 346 return AttributeSets.hasFnAttribute(Kind); 347 } 348 349 /// Return true if the function has the attribute. hasFnAttribute(StringRef Kind)350 bool hasFnAttribute(StringRef Kind) const { 351 return AttributeSets.hasFnAttribute(Kind); 352 } 353 354 /// Return the attribute for the given attribute kind. getFnAttribute(Attribute::AttrKind Kind)355 Attribute getFnAttribute(Attribute::AttrKind Kind) const { 356 return getAttribute(AttributeList::FunctionIndex, Kind); 357 } 358 359 /// Return the attribute for the given attribute kind. getFnAttribute(StringRef Kind)360 Attribute getFnAttribute(StringRef Kind) const { 361 return getAttribute(AttributeList::FunctionIndex, Kind); 362 } 363 364 /// Return the stack alignment for the function. getFnStackAlignment()365 unsigned getFnStackAlignment() const { 366 if (!hasFnAttribute(Attribute::StackAlignment)) 367 return 0; 368 if (const auto MA = 369 AttributeSets.getStackAlignment(AttributeList::FunctionIndex)) 370 return MA->value(); 371 return 0; 372 } 373 374 /// Return the stack alignment for the function. getFnStackAlign()375 MaybeAlign getFnStackAlign() const { 376 if (!hasFnAttribute(Attribute::StackAlignment)) 377 return None; 378 return AttributeSets.getStackAlignment(AttributeList::FunctionIndex); 379 } 380 381 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm 382 /// to use during code generation. hasGC()383 bool hasGC() const { 384 return getSubclassDataFromValue() & (1<<14); 385 } 386 const std::string &getGC() const; 387 void setGC(std::string Str); 388 void clearGC(); 389 390 /// Returns true if the function has ssp, sspstrong, or sspreq fn attrs. 391 bool hasStackProtectorFnAttr() const; 392 393 /// adds the attribute to the list of attributes. 394 void addAttribute(unsigned i, Attribute::AttrKind Kind); 395 396 /// adds the attribute to the list of attributes. 397 void addAttribute(unsigned i, Attribute Attr); 398 399 /// adds the attributes to the list of attributes. 400 void addAttributes(unsigned i, const AttrBuilder &Attrs); 401 402 /// adds the attribute to the list of attributes for the given arg. 403 void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 404 405 /// adds the attribute to the list of attributes for the given arg. 406 void addParamAttr(unsigned ArgNo, Attribute Attr); 407 408 /// adds the attributes to the list of attributes for the given arg. 409 void addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 410 411 /// removes the attribute from the list of attributes. 412 void removeAttribute(unsigned i, Attribute::AttrKind Kind); 413 414 /// removes the attribute from the list of attributes. 415 void removeAttribute(unsigned i, StringRef Kind); 416 417 /// removes the attributes from the list of attributes. 418 void removeAttributes(unsigned i, const AttrBuilder &Attrs); 419 420 /// removes the attribute from the list of attributes. 421 void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind); 422 423 /// removes the attribute from the list of attributes. 424 void removeParamAttr(unsigned ArgNo, StringRef Kind); 425 426 /// removes the attribute from the list of attributes. 427 void removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs); 428 429 /// check if an attributes is in the list of attributes. hasAttribute(unsigned i,Attribute::AttrKind Kind)430 bool hasAttribute(unsigned i, Attribute::AttrKind Kind) const { 431 return getAttributes().hasAttribute(i, Kind); 432 } 433 434 /// check if an attributes is in the list of attributes. hasParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)435 bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { 436 return getAttributes().hasParamAttribute(ArgNo, Kind); 437 } 438 439 /// gets the specified attribute from the list of attributes. getParamAttribute(unsigned ArgNo,Attribute::AttrKind Kind)440 Attribute getParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { 441 return getAttributes().getParamAttr(ArgNo, Kind); 442 } 443 444 /// gets the attribute from the list of attributes. getAttribute(unsigned i,Attribute::AttrKind Kind)445 Attribute getAttribute(unsigned i, Attribute::AttrKind Kind) const { 446 return AttributeSets.getAttribute(i, Kind); 447 } 448 449 /// gets the attribute from the list of attributes. getAttribute(unsigned i,StringRef Kind)450 Attribute getAttribute(unsigned i, StringRef Kind) const { 451 return AttributeSets.getAttribute(i, Kind); 452 } 453 454 /// adds the dereferenceable attribute to the list of attributes. 455 void addDereferenceableAttr(unsigned i, uint64_t Bytes); 456 457 /// adds the dereferenceable attribute to the list of attributes for 458 /// the given arg. 459 void addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes); 460 461 /// adds the dereferenceable_or_null attribute to the list of 462 /// attributes. 463 void addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes); 464 465 /// adds the dereferenceable_or_null attribute to the list of 466 /// attributes for the given arg. 467 void addDereferenceableOrNullParamAttr(unsigned ArgNo, uint64_t Bytes); 468 469 /// Extract the alignment for a call or parameter (0=unknown). 470 /// FIXME: Remove this function once transition to Align is over. 471 /// Use getParamAlign() instead. getParamAlignment(unsigned ArgNo)472 unsigned getParamAlignment(unsigned ArgNo) const { 473 if (const auto MA = getParamAlign(ArgNo)) 474 return MA->value(); 475 return 0; 476 } 477 getParamAlign(unsigned ArgNo)478 MaybeAlign getParamAlign(unsigned ArgNo) const { 479 return AttributeSets.getParamAlignment(ArgNo); 480 } 481 482 /// Extract the byval type for a parameter. getParamByValType(unsigned ArgNo)483 Type *getParamByValType(unsigned ArgNo) const { 484 return AttributeSets.getParamByValType(ArgNo); 485 } 486 487 /// Extract the sret type for a parameter. getParamStructRetType(unsigned ArgNo)488 Type *getParamStructRetType(unsigned ArgNo) const { 489 return AttributeSets.getParamStructRetType(ArgNo); 490 } 491 492 /// Extract the byref type for a parameter. getParamByRefType(unsigned ArgNo)493 Type *getParamByRefType(unsigned ArgNo) const { 494 return AttributeSets.getParamByRefType(ArgNo); 495 } 496 497 /// Extract the number of dereferenceable bytes for a call or 498 /// parameter (0=unknown). 499 /// @param i AttributeList index, referring to a return value or argument. getDereferenceableBytes(unsigned i)500 uint64_t getDereferenceableBytes(unsigned i) const { 501 return AttributeSets.getDereferenceableBytes(i); 502 } 503 504 /// Extract the number of dereferenceable bytes for a parameter. 505 /// @param ArgNo Index of an argument, with 0 being the first function arg. getParamDereferenceableBytes(unsigned ArgNo)506 uint64_t getParamDereferenceableBytes(unsigned ArgNo) const { 507 return AttributeSets.getParamDereferenceableBytes(ArgNo); 508 } 509 510 /// Extract the number of dereferenceable_or_null bytes for a call or 511 /// parameter (0=unknown). 512 /// @param i AttributeList index, referring to a return value or argument. getDereferenceableOrNullBytes(unsigned i)513 uint64_t getDereferenceableOrNullBytes(unsigned i) const { 514 return AttributeSets.getDereferenceableOrNullBytes(i); 515 } 516 517 /// Extract the number of dereferenceable_or_null bytes for a 518 /// parameter. 519 /// @param ArgNo AttributeList ArgNo, referring to an argument. getParamDereferenceableOrNullBytes(unsigned ArgNo)520 uint64_t getParamDereferenceableOrNullBytes(unsigned ArgNo) const { 521 return AttributeSets.getParamDereferenceableOrNullBytes(ArgNo); 522 } 523 524 /// Determine if the function does not access memory. doesNotAccessMemory()525 bool doesNotAccessMemory() const { 526 return hasFnAttribute(Attribute::ReadNone); 527 } setDoesNotAccessMemory()528 void setDoesNotAccessMemory() { 529 addFnAttr(Attribute::ReadNone); 530 } 531 532 /// Determine if the function does not access or only reads memory. onlyReadsMemory()533 bool onlyReadsMemory() const { 534 return doesNotAccessMemory() || hasFnAttribute(Attribute::ReadOnly); 535 } setOnlyReadsMemory()536 void setOnlyReadsMemory() { 537 addFnAttr(Attribute::ReadOnly); 538 } 539 540 /// Determine if the function does not access or only writes memory. doesNotReadMemory()541 bool doesNotReadMemory() const { 542 return doesNotAccessMemory() || hasFnAttribute(Attribute::WriteOnly); 543 } setDoesNotReadMemory()544 void setDoesNotReadMemory() { 545 addFnAttr(Attribute::WriteOnly); 546 } 547 548 /// Determine if the call can access memmory only using pointers based 549 /// on its arguments. onlyAccessesArgMemory()550 bool onlyAccessesArgMemory() const { 551 return hasFnAttribute(Attribute::ArgMemOnly); 552 } setOnlyAccessesArgMemory()553 void setOnlyAccessesArgMemory() { addFnAttr(Attribute::ArgMemOnly); } 554 555 /// Determine if the function may only access memory that is 556 /// inaccessible from the IR. onlyAccessesInaccessibleMemory()557 bool onlyAccessesInaccessibleMemory() const { 558 return hasFnAttribute(Attribute::InaccessibleMemOnly); 559 } setOnlyAccessesInaccessibleMemory()560 void setOnlyAccessesInaccessibleMemory() { 561 addFnAttr(Attribute::InaccessibleMemOnly); 562 } 563 564 /// Determine if the function may only access memory that is 565 /// either inaccessible from the IR or pointed to by its arguments. onlyAccessesInaccessibleMemOrArgMem()566 bool onlyAccessesInaccessibleMemOrArgMem() const { 567 return hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly); 568 } setOnlyAccessesInaccessibleMemOrArgMem()569 void setOnlyAccessesInaccessibleMemOrArgMem() { 570 addFnAttr(Attribute::InaccessibleMemOrArgMemOnly); 571 } 572 573 /// Determine if the function cannot return. doesNotReturn()574 bool doesNotReturn() const { 575 return hasFnAttribute(Attribute::NoReturn); 576 } setDoesNotReturn()577 void setDoesNotReturn() { 578 addFnAttr(Attribute::NoReturn); 579 } 580 581 /// Determine if the function should not perform indirect branch tracking. doesNoCfCheck()582 bool doesNoCfCheck() const { return hasFnAttribute(Attribute::NoCfCheck); } 583 584 /// Determine if the function cannot unwind. doesNotThrow()585 bool doesNotThrow() const { 586 return hasFnAttribute(Attribute::NoUnwind); 587 } setDoesNotThrow()588 void setDoesNotThrow() { 589 addFnAttr(Attribute::NoUnwind); 590 } 591 592 /// Determine if the call cannot be duplicated. cannotDuplicate()593 bool cannotDuplicate() const { 594 return hasFnAttribute(Attribute::NoDuplicate); 595 } setCannotDuplicate()596 void setCannotDuplicate() { 597 addFnAttr(Attribute::NoDuplicate); 598 } 599 600 /// Determine if the call is convergent. isConvergent()601 bool isConvergent() const { 602 return hasFnAttribute(Attribute::Convergent); 603 } setConvergent()604 void setConvergent() { 605 addFnAttr(Attribute::Convergent); 606 } setNotConvergent()607 void setNotConvergent() { 608 removeFnAttr(Attribute::Convergent); 609 } 610 611 /// Determine if the call has sideeffects. isSpeculatable()612 bool isSpeculatable() const { 613 return hasFnAttribute(Attribute::Speculatable); 614 } setSpeculatable()615 void setSpeculatable() { 616 addFnAttr(Attribute::Speculatable); 617 } 618 619 /// Determine if the call might deallocate memory. doesNotFreeMemory()620 bool doesNotFreeMemory() const { 621 return onlyReadsMemory() || hasFnAttribute(Attribute::NoFree); 622 } setDoesNotFreeMemory()623 void setDoesNotFreeMemory() { 624 addFnAttr(Attribute::NoFree); 625 } 626 627 /// Determine if the function is known not to recurse, directly or 628 /// indirectly. doesNotRecurse()629 bool doesNotRecurse() const { 630 return hasFnAttribute(Attribute::NoRecurse); 631 } setDoesNotRecurse()632 void setDoesNotRecurse() { 633 addFnAttr(Attribute::NoRecurse); 634 } 635 636 /// Determine if the function is required to make forward progress. mustProgress()637 bool mustProgress() const { 638 return hasFnAttribute(Attribute::MustProgress) || 639 hasFnAttribute(Attribute::WillReturn); 640 } setMustProgress()641 void setMustProgress() { addFnAttr(Attribute::MustProgress); } 642 643 /// Determine if the function will return. willReturn()644 bool willReturn() const { return hasFnAttribute(Attribute::WillReturn); } setWillReturn()645 void setWillReturn() { addFnAttr(Attribute::WillReturn); } 646 647 /// True if the ABI mandates (or the user requested) that this 648 /// function be in a unwind table. hasUWTable()649 bool hasUWTable() const { 650 return hasFnAttribute(Attribute::UWTable); 651 } setHasUWTable()652 void setHasUWTable() { 653 addFnAttr(Attribute::UWTable); 654 } 655 656 /// True if this function needs an unwind table. needsUnwindTableEntry()657 bool needsUnwindTableEntry() const { 658 return hasUWTable() || !doesNotThrow() || hasPersonalityFn(); 659 } 660 661 /// Determine if the function returns a structure through first 662 /// or second pointer argument. hasStructRetAttr()663 bool hasStructRetAttr() const { 664 return AttributeSets.hasParamAttribute(0, Attribute::StructRet) || 665 AttributeSets.hasParamAttribute(1, Attribute::StructRet); 666 } 667 668 /// Determine if the parameter or return value is marked with NoAlias 669 /// attribute. returnDoesNotAlias()670 bool returnDoesNotAlias() const { 671 return AttributeSets.hasAttribute(AttributeList::ReturnIndex, 672 Attribute::NoAlias); 673 } setReturnDoesNotAlias()674 void setReturnDoesNotAlias() { 675 addAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 676 } 677 678 /// Do not optimize this function (-O0). hasOptNone()679 bool hasOptNone() const { return hasFnAttribute(Attribute::OptimizeNone); } 680 681 /// Optimize this function for minimum size (-Oz). hasMinSize()682 bool hasMinSize() const { return hasFnAttribute(Attribute::MinSize); } 683 684 /// Optimize this function for size (-Os) or minimum size (-Oz). hasOptSize()685 bool hasOptSize() const { 686 return hasFnAttribute(Attribute::OptimizeForSize) || hasMinSize(); 687 } 688 689 /// Returns the denormal handling type for the default rounding mode of the 690 /// function. 691 DenormalMode getDenormalMode(const fltSemantics &FPType) const; 692 693 /// copyAttributesFrom - copy all additional attributes (those not needed to 694 /// create a Function) from the Function Src to this one. 695 void copyAttributesFrom(const Function *Src); 696 697 /// deleteBody - This method deletes the body of the function, and converts 698 /// the linkage to external. 699 /// deleteBody()700 void deleteBody() { 701 dropAllReferences(); 702 setLinkage(ExternalLinkage); 703 } 704 705 /// removeFromParent - This method unlinks 'this' from the containing module, 706 /// but does not delete it. 707 /// 708 void removeFromParent(); 709 710 /// eraseFromParent - This method unlinks 'this' from the containing module 711 /// and deletes it. 712 /// 713 void eraseFromParent(); 714 715 /// Steal arguments from another function. 716 /// 717 /// Drop this function's arguments and splice in the ones from \c Src. 718 /// Requires that this has no function body. 719 void stealArgumentListFrom(Function &Src); 720 721 /// Get the underlying elements of the Function... the basic block list is 722 /// empty for external functions. 723 /// getBasicBlockList()724 const BasicBlockListType &getBasicBlockList() const { return BasicBlocks; } getBasicBlockList()725 BasicBlockListType &getBasicBlockList() { return BasicBlocks; } 726 getSublistAccess(BasicBlock *)727 static BasicBlockListType Function::*getSublistAccess(BasicBlock*) { 728 return &Function::BasicBlocks; 729 } 730 getEntryBlock()731 const BasicBlock &getEntryBlock() const { return front(); } getEntryBlock()732 BasicBlock &getEntryBlock() { return front(); } 733 734 //===--------------------------------------------------------------------===// 735 // Symbol Table Accessing functions... 736 737 /// getSymbolTable() - Return the symbol table if any, otherwise nullptr. 738 /// getValueSymbolTable()739 inline ValueSymbolTable *getValueSymbolTable() { return SymTab.get(); } getValueSymbolTable()740 inline const ValueSymbolTable *getValueSymbolTable() const { 741 return SymTab.get(); 742 } 743 744 //===--------------------------------------------------------------------===// 745 // BasicBlock iterator forwarding functions 746 // begin()747 iterator begin() { return BasicBlocks.begin(); } begin()748 const_iterator begin() const { return BasicBlocks.begin(); } end()749 iterator end () { return BasicBlocks.end(); } end()750 const_iterator end () const { return BasicBlocks.end(); } 751 size()752 size_t size() const { return BasicBlocks.size(); } empty()753 bool empty() const { return BasicBlocks.empty(); } front()754 const BasicBlock &front() const { return BasicBlocks.front(); } front()755 BasicBlock &front() { return BasicBlocks.front(); } back()756 const BasicBlock &back() const { return BasicBlocks.back(); } back()757 BasicBlock &back() { return BasicBlocks.back(); } 758 759 /// @name Function Argument Iteration 760 /// @{ 761 arg_begin()762 arg_iterator arg_begin() { 763 CheckLazyArguments(); 764 return Arguments; 765 } arg_begin()766 const_arg_iterator arg_begin() const { 767 CheckLazyArguments(); 768 return Arguments; 769 } 770 arg_end()771 arg_iterator arg_end() { 772 CheckLazyArguments(); 773 return Arguments + NumArgs; 774 } arg_end()775 const_arg_iterator arg_end() const { 776 CheckLazyArguments(); 777 return Arguments + NumArgs; 778 } 779 getArg(unsigned i)780 Argument* getArg(unsigned i) const { 781 assert (i < NumArgs && "getArg() out of range!"); 782 CheckLazyArguments(); 783 return Arguments + i; 784 } 785 args()786 iterator_range<arg_iterator> args() { 787 return make_range(arg_begin(), arg_end()); 788 } args()789 iterator_range<const_arg_iterator> args() const { 790 return make_range(arg_begin(), arg_end()); 791 } 792 793 /// @} 794 arg_size()795 size_t arg_size() const { return NumArgs; } arg_empty()796 bool arg_empty() const { return arg_size() == 0; } 797 798 /// Check whether this function has a personality function. hasPersonalityFn()799 bool hasPersonalityFn() const { 800 return getSubclassDataFromValue() & (1<<3); 801 } 802 803 /// Get the personality function associated with this function. 804 Constant *getPersonalityFn() const; 805 void setPersonalityFn(Constant *Fn); 806 807 /// Check whether this function has prefix data. hasPrefixData()808 bool hasPrefixData() const { 809 return getSubclassDataFromValue() & (1<<1); 810 } 811 812 /// Get the prefix data associated with this function. 813 Constant *getPrefixData() const; 814 void setPrefixData(Constant *PrefixData); 815 816 /// Check whether this function has prologue data. hasPrologueData()817 bool hasPrologueData() const { 818 return getSubclassDataFromValue() & (1<<2); 819 } 820 821 /// Get the prologue data associated with this function. 822 Constant *getPrologueData() const; 823 void setPrologueData(Constant *PrologueData); 824 825 /// Print the function to an output stream with an optional 826 /// AssemblyAnnotationWriter. 827 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr, 828 bool ShouldPreserveUseListOrder = false, 829 bool IsForDebug = false) const; 830 831 /// viewCFG - This function is meant for use from the debugger. You can just 832 /// say 'call F->viewCFG()' and a ghostview window should pop up from the 833 /// program, displaying the CFG of the current function with the code for each 834 /// basic block inside. This depends on there being a 'dot' and 'gv' program 835 /// in your path. 836 /// 837 void viewCFG() const; 838 839 /// Extended form to print edge weights. 840 void viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI, 841 const BranchProbabilityInfo *BPI) const; 842 843 /// viewCFGOnly - This function is meant for use from the debugger. It works 844 /// just like viewCFG, but it does not include the contents of basic blocks 845 /// into the nodes, just the label. If you are only interested in the CFG 846 /// this can make the graph smaller. 847 /// 848 void viewCFGOnly() const; 849 850 /// Extended form to print edge weights. 851 void viewCFGOnly(const BlockFrequencyInfo *BFI, 852 const BranchProbabilityInfo *BPI) const; 853 854 /// Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)855 static bool classof(const Value *V) { 856 return V->getValueID() == Value::FunctionVal; 857 } 858 859 /// dropAllReferences() - This method causes all the subinstructions to "let 860 /// go" of all references that they are maintaining. This allows one to 861 /// 'delete' a whole module at a time, even though there may be circular 862 /// references... first all references are dropped, and all use counts go to 863 /// zero. Then everything is deleted for real. Note that no operations are 864 /// valid on an object that has "dropped all references", except operator 865 /// delete. 866 /// 867 /// Since no other object in the module can have references into the body of a 868 /// function, dropping all references deletes the entire body of the function, 869 /// including any contained basic blocks. 870 /// 871 void dropAllReferences(); 872 873 /// hasAddressTaken - returns true if there are any uses of this function 874 /// other than direct calls or invokes to it, or blockaddress expressions. 875 /// Optionally passes back an offending user for diagnostic purposes and 876 /// ignores callback uses. 877 /// 878 bool hasAddressTaken(const User ** = nullptr, 879 bool IgnoreCallbackUses = false) const; 880 881 /// isDefTriviallyDead - Return true if it is trivially safe to remove 882 /// this function definition from the module (because it isn't externally 883 /// visible, does not have its address taken, and has no callers). To make 884 /// this more accurate, call removeDeadConstantUsers first. 885 bool isDefTriviallyDead() const; 886 887 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 888 /// setjmp or other function that gcc recognizes as "returning twice". 889 bool callsFunctionThatReturnsTwice() const; 890 891 /// Set the attached subprogram. 892 /// 893 /// Calls \a setMetadata() with \a LLVMContext::MD_dbg. 894 void setSubprogram(DISubprogram *SP); 895 896 /// Get the attached subprogram. 897 /// 898 /// Calls \a getMetadata() with \a LLVMContext::MD_dbg and casts the result 899 /// to \a DISubprogram. 900 DISubprogram *getSubprogram() const; 901 902 /// Returns true if we should emit debug info for profiling. 903 bool isDebugInfoForProfiling() const; 904 905 /// Check if null pointer dereferencing is considered undefined behavior for 906 /// the function. 907 /// Return value: false => null pointer dereference is undefined. 908 /// Return value: true => null pointer dereference is not undefined. 909 bool nullPointerIsDefined() const; 910 911 private: 912 void allocHungoffUselist(); 913 template<int Idx> void setHungoffOperand(Constant *C); 914 915 /// Shadow Value::setValueSubclassData with a private forwarding method so 916 /// that subclasses cannot accidentally use it. setValueSubclassData(unsigned short D)917 void setValueSubclassData(unsigned short D) { 918 Value::setValueSubclassData(D); 919 } 920 void setValueSubclassDataBit(unsigned Bit, bool On); 921 }; 922 923 /// Check whether null pointer dereferencing is considered undefined behavior 924 /// for a given function or an address space. 925 /// Null pointer access in non-zero address space is not considered undefined. 926 /// Return value: false => null pointer dereference is undefined. 927 /// Return value: true => null pointer dereference is not undefined. 928 bool NullPointerIsDefined(const Function *F, unsigned AS = 0); 929 930 template <> 931 struct OperandTraits<Function> : public HungoffOperandTraits<3> {}; 932 933 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(Function, Value) 934 935 } // end namespace llvm 936 937 #endif // LLVM_IR_FUNCTION_H 938