Function.h 34 KB

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