Debian Codegraph @

suite/synctools/tablegen/include/llvm/IR/Function.h

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