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