Function.h 34 KB

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