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