Function.h 33 KB

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