xref: /llvm-project/llvm/lib/IR/Function.cpp (revision c16a58b36caebbc34dfa0f788a019d041e5484df)
1 //===- Function.cpp - Implement the Global object classes -----------------===//
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 implements the Function class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Function.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/AbstractCallSite.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/IntrinsicsAArch64.h"
35 #include "llvm/IR/IntrinsicsAMDGPU.h"
36 #include "llvm/IR/IntrinsicsARM.h"
37 #include "llvm/IR/IntrinsicsBPF.h"
38 #include "llvm/IR/IntrinsicsDirectX.h"
39 #include "llvm/IR/IntrinsicsHexagon.h"
40 #include "llvm/IR/IntrinsicsMips.h"
41 #include "llvm/IR/IntrinsicsNVPTX.h"
42 #include "llvm/IR/IntrinsicsPowerPC.h"
43 #include "llvm/IR/IntrinsicsR600.h"
44 #include "llvm/IR/IntrinsicsRISCV.h"
45 #include "llvm/IR/IntrinsicsS390.h"
46 #include "llvm/IR/IntrinsicsVE.h"
47 #include "llvm/IR/IntrinsicsWebAssembly.h"
48 #include "llvm/IR/IntrinsicsX86.h"
49 #include "llvm/IR/IntrinsicsXCore.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/MDBuilder.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/Operator.h"
55 #include "llvm/IR/SymbolTableListTraits.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Use.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/IR/ValueSymbolTable.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Compiler.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/ModRef.h"
66 #include <cassert>
67 #include <cstddef>
68 #include <cstdint>
69 #include <cstring>
70 #include <string>
71 
72 using namespace llvm;
73 using ProfileCount = Function::ProfileCount;
74 
75 // Explicit instantiations of SymbolTableListTraits since some of the methods
76 // are not in the public header file...
77 template class llvm::SymbolTableListTraits<BasicBlock>;
78 
79 static cl::opt<unsigned> NonGlobalValueMaxNameSize(
80     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
81     cl::desc("Maximum size for the name of non-global values."));
82 
83 //===----------------------------------------------------------------------===//
84 // Argument Implementation
85 //===----------------------------------------------------------------------===//
86 
87 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
88     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
89   setName(Name);
90 }
91 
92 void Argument::setParent(Function *parent) {
93   Parent = parent;
94 }
95 
96 bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
97   if (!getType()->isPointerTy()) return false;
98   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
99       (AllowUndefOrPoison ||
100        getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
101     return true;
102   else if (getDereferenceableBytes() > 0 &&
103            !NullPointerIsDefined(getParent(),
104                                  getType()->getPointerAddressSpace()))
105     return true;
106   return false;
107 }
108 
109 bool Argument::hasByValAttr() const {
110   if (!getType()->isPointerTy()) return false;
111   return hasAttribute(Attribute::ByVal);
112 }
113 
114 bool Argument::hasByRefAttr() const {
115   if (!getType()->isPointerTy())
116     return false;
117   return hasAttribute(Attribute::ByRef);
118 }
119 
120 bool Argument::hasSwiftSelfAttr() const {
121   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
122 }
123 
124 bool Argument::hasSwiftErrorAttr() const {
125   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
126 }
127 
128 bool Argument::hasInAllocaAttr() const {
129   if (!getType()->isPointerTy()) return false;
130   return hasAttribute(Attribute::InAlloca);
131 }
132 
133 bool Argument::hasPreallocatedAttr() const {
134   if (!getType()->isPointerTy())
135     return false;
136   return hasAttribute(Attribute::Preallocated);
137 }
138 
139 bool Argument::hasPassPointeeByValueCopyAttr() const {
140   if (!getType()->isPointerTy()) return false;
141   AttributeList Attrs = getParent()->getAttributes();
142   return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
143          Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
144          Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);
145 }
146 
147 bool Argument::hasPointeeInMemoryValueAttr() const {
148   if (!getType()->isPointerTy())
149     return false;
150   AttributeList Attrs = getParent()->getAttributes();
151   return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
152          Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||
153          Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
154          Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||
155          Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);
156 }
157 
158 /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
159 /// parameter type.
160 static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
161   // FIXME: All the type carrying attributes are mutually exclusive, so there
162   // should be a single query to get the stored type that handles any of them.
163   if (Type *ByValTy = ParamAttrs.getByValType())
164     return ByValTy;
165   if (Type *ByRefTy = ParamAttrs.getByRefType())
166     return ByRefTy;
167   if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
168     return PreAllocTy;
169   if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
170     return InAllocaTy;
171   if (Type *SRetTy = ParamAttrs.getStructRetType())
172     return SRetTy;
173 
174   return nullptr;
175 }
176 
177 uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
178   AttributeSet ParamAttrs =
179       getParent()->getAttributes().getParamAttrs(getArgNo());
180   if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))
181     return DL.getTypeAllocSize(MemTy);
182   return 0;
183 }
184 
185 Type *Argument::getPointeeInMemoryValueType() const {
186   AttributeSet ParamAttrs =
187       getParent()->getAttributes().getParamAttrs(getArgNo());
188   return getMemoryParamAllocType(ParamAttrs);
189 }
190 
191 uint64_t Argument::getParamAlignment() const {
192   assert(getType()->isPointerTy() && "Only pointers have alignments");
193   return getParent()->getParamAlignment(getArgNo());
194 }
195 
196 MaybeAlign Argument::getParamAlign() const {
197   assert(getType()->isPointerTy() && "Only pointers have alignments");
198   return getParent()->getParamAlign(getArgNo());
199 }
200 
201 MaybeAlign Argument::getParamStackAlign() const {
202   return getParent()->getParamStackAlign(getArgNo());
203 }
204 
205 Type *Argument::getParamByValType() const {
206   assert(getType()->isPointerTy() && "Only pointers have byval types");
207   return getParent()->getParamByValType(getArgNo());
208 }
209 
210 Type *Argument::getParamStructRetType() const {
211   assert(getType()->isPointerTy() && "Only pointers have sret types");
212   return getParent()->getParamStructRetType(getArgNo());
213 }
214 
215 Type *Argument::getParamByRefType() const {
216   assert(getType()->isPointerTy() && "Only pointers have byref types");
217   return getParent()->getParamByRefType(getArgNo());
218 }
219 
220 Type *Argument::getParamInAllocaType() const {
221   assert(getType()->isPointerTy() && "Only pointers have inalloca types");
222   return getParent()->getParamInAllocaType(getArgNo());
223 }
224 
225 uint64_t Argument::getDereferenceableBytes() const {
226   assert(getType()->isPointerTy() &&
227          "Only pointers have dereferenceable bytes");
228   return getParent()->getParamDereferenceableBytes(getArgNo());
229 }
230 
231 uint64_t Argument::getDereferenceableOrNullBytes() const {
232   assert(getType()->isPointerTy() &&
233          "Only pointers have dereferenceable bytes");
234   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
235 }
236 
237 bool Argument::hasNestAttr() const {
238   if (!getType()->isPointerTy()) return false;
239   return hasAttribute(Attribute::Nest);
240 }
241 
242 bool Argument::hasNoAliasAttr() const {
243   if (!getType()->isPointerTy()) return false;
244   return hasAttribute(Attribute::NoAlias);
245 }
246 
247 bool Argument::hasNoCaptureAttr() const {
248   if (!getType()->isPointerTy()) return false;
249   return hasAttribute(Attribute::NoCapture);
250 }
251 
252 bool Argument::hasNoFreeAttr() const {
253   if (!getType()->isPointerTy()) return false;
254   return hasAttribute(Attribute::NoFree);
255 }
256 
257 bool Argument::hasStructRetAttr() const {
258   if (!getType()->isPointerTy()) return false;
259   return hasAttribute(Attribute::StructRet);
260 }
261 
262 bool Argument::hasInRegAttr() const {
263   return hasAttribute(Attribute::InReg);
264 }
265 
266 bool Argument::hasReturnedAttr() const {
267   return hasAttribute(Attribute::Returned);
268 }
269 
270 bool Argument::hasZExtAttr() const {
271   return hasAttribute(Attribute::ZExt);
272 }
273 
274 bool Argument::hasSExtAttr() const {
275   return hasAttribute(Attribute::SExt);
276 }
277 
278 bool Argument::onlyReadsMemory() const {
279   AttributeList Attrs = getParent()->getAttributes();
280   return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||
281          Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);
282 }
283 
284 void Argument::addAttrs(AttrBuilder &B) {
285   AttributeList AL = getParent()->getAttributes();
286   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
287   getParent()->setAttributes(AL);
288 }
289 
290 void Argument::addAttr(Attribute::AttrKind Kind) {
291   getParent()->addParamAttr(getArgNo(), Kind);
292 }
293 
294 void Argument::addAttr(Attribute Attr) {
295   getParent()->addParamAttr(getArgNo(), Attr);
296 }
297 
298 void Argument::removeAttr(Attribute::AttrKind Kind) {
299   getParent()->removeParamAttr(getArgNo(), Kind);
300 }
301 
302 void Argument::removeAttrs(const AttributeMask &AM) {
303   AttributeList AL = getParent()->getAttributes();
304   AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
305   getParent()->setAttributes(AL);
306 }
307 
308 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
309   return getParent()->hasParamAttribute(getArgNo(), Kind);
310 }
311 
312 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
313   return getParent()->getParamAttribute(getArgNo(), Kind);
314 }
315 
316 //===----------------------------------------------------------------------===//
317 // Helper Methods in Function
318 //===----------------------------------------------------------------------===//
319 
320 LLVMContext &Function::getContext() const {
321   return getType()->getContext();
322 }
323 
324 unsigned Function::getInstructionCount() const {
325   unsigned NumInstrs = 0;
326   for (const BasicBlock &BB : BasicBlocks)
327     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
328                                BB.instructionsWithoutDebug().end());
329   return NumInstrs;
330 }
331 
332 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
333                            const Twine &N, Module &M) {
334   return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
335 }
336 
337 Function *Function::createWithDefaultAttr(FunctionType *Ty,
338                                           LinkageTypes Linkage,
339                                           unsigned AddrSpace, const Twine &N,
340                                           Module *M) {
341   auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
342   AttrBuilder B(F->getContext());
343   UWTableKind UWTable = M->getUwtable();
344   if (UWTable != UWTableKind::None)
345     B.addUWTableAttr(UWTable);
346   switch (M->getFramePointer()) {
347   case FramePointerKind::None:
348     // 0 ("none") is the default.
349     break;
350   case FramePointerKind::NonLeaf:
351     B.addAttribute("frame-pointer", "non-leaf");
352     break;
353   case FramePointerKind::All:
354     B.addAttribute("frame-pointer", "all");
355     break;
356   }
357   if (M->getModuleFlag("function_return_thunk_extern"))
358     B.addAttribute(Attribute::FnRetThunkExtern);
359   F->addFnAttrs(B);
360   return F;
361 }
362 
363 void Function::removeFromParent() {
364   getParent()->getFunctionList().remove(getIterator());
365 }
366 
367 void Function::eraseFromParent() {
368   getParent()->getFunctionList().erase(getIterator());
369 }
370 
371 //===----------------------------------------------------------------------===//
372 // Function Implementation
373 //===----------------------------------------------------------------------===//
374 
375 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
376   // If AS == -1 and we are passed a valid module pointer we place the function
377   // in the program address space. Otherwise we default to AS0.
378   if (AddrSpace == static_cast<unsigned>(-1))
379     return M ? M->getDataLayout().getProgramAddressSpace() : 0;
380   return AddrSpace;
381 }
382 
383 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
384                    const Twine &name, Module *ParentModule)
385     : GlobalObject(Ty, Value::FunctionVal,
386                    OperandTraits<Function>::op_begin(this), 0, Linkage, name,
387                    computeAddrSpace(AddrSpace, ParentModule)),
388       NumArgs(Ty->getNumParams()) {
389   assert(FunctionType::isValidReturnType(getReturnType()) &&
390          "invalid return type");
391   setGlobalObjectSubClassData(0);
392 
393   // We only need a symbol table for a function if the context keeps value names
394   if (!getContext().shouldDiscardValueNames())
395     SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
396 
397   // If the function has arguments, mark them as lazily built.
398   if (Ty->getNumParams())
399     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
400 
401   if (ParentModule)
402     ParentModule->getFunctionList().push_back(this);
403 
404   HasLLVMReservedName = getName().startswith("llvm.");
405   // Ensure intrinsics have the right parameter attributes.
406   // Note, the IntID field will have been set in Value::setName if this function
407   // name is a valid intrinsic ID.
408   if (IntID)
409     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
410 }
411 
412 Function::~Function() {
413   dropAllReferences();    // After this it is safe to delete instructions.
414 
415   // Delete all of the method arguments and unlink from symbol table...
416   if (Arguments)
417     clearArguments();
418 
419   // Remove the function from the on-the-side GC table.
420   clearGC();
421 }
422 
423 void Function::BuildLazyArguments() const {
424   // Create the arguments vector, all arguments start out unnamed.
425   auto *FT = getFunctionType();
426   if (NumArgs > 0) {
427     Arguments = std::allocator<Argument>().allocate(NumArgs);
428     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
429       Type *ArgTy = FT->getParamType(i);
430       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
431       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
432     }
433   }
434 
435   // Clear the lazy arguments bit.
436   unsigned SDC = getSubclassDataFromValue();
437   SDC &= ~(1 << 0);
438   const_cast<Function*>(this)->setValueSubclassData(SDC);
439   assert(!hasLazyArguments());
440 }
441 
442 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
443   return MutableArrayRef<Argument>(Args, Count);
444 }
445 
446 bool Function::isConstrainedFPIntrinsic() const {
447   switch (getIntrinsicID()) {
448 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
449   case Intrinsic::INTRINSIC:
450 #include "llvm/IR/ConstrainedOps.def"
451     return true;
452 #undef INSTRUCTION
453   default:
454     return false;
455   }
456 }
457 
458 void Function::clearArguments() {
459   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
460     A.setName("");
461     A.~Argument();
462   }
463   std::allocator<Argument>().deallocate(Arguments, NumArgs);
464   Arguments = nullptr;
465 }
466 
467 void Function::stealArgumentListFrom(Function &Src) {
468   assert(isDeclaration() && "Expected no references to current arguments");
469 
470   // Drop the current arguments, if any, and set the lazy argument bit.
471   if (!hasLazyArguments()) {
472     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
473                         [](const Argument &A) { return A.use_empty(); }) &&
474            "Expected arguments to be unused in declaration");
475     clearArguments();
476     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
477   }
478 
479   // Nothing to steal if Src has lazy arguments.
480   if (Src.hasLazyArguments())
481     return;
482 
483   // Steal arguments from Src, and fix the lazy argument bits.
484   assert(arg_size() == Src.arg_size());
485   Arguments = Src.Arguments;
486   Src.Arguments = nullptr;
487   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
488     // FIXME: This does the work of transferNodesFromList inefficiently.
489     SmallString<128> Name;
490     if (A.hasName())
491       Name = A.getName();
492     if (!Name.empty())
493       A.setName("");
494     A.setParent(this);
495     if (!Name.empty())
496       A.setName(Name);
497   }
498 
499   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
500   assert(!hasLazyArguments());
501   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
502 }
503 
504 // dropAllReferences() - This function causes all the subinstructions to "let
505 // go" of all references that they are maintaining.  This allows one to
506 // 'delete' a whole class at a time, even though there may be circular
507 // references... first all references are dropped, and all use counts go to
508 // zero.  Then everything is deleted for real.  Note that no operations are
509 // valid on an object that has "dropped all references", except operator
510 // delete.
511 //
512 void Function::dropAllReferences() {
513   setIsMaterializable(false);
514 
515   for (BasicBlock &BB : *this)
516     BB.dropAllReferences();
517 
518   // Delete all basic blocks. They are now unused, except possibly by
519   // blockaddresses, but BasicBlock's destructor takes care of those.
520   while (!BasicBlocks.empty())
521     BasicBlocks.begin()->eraseFromParent();
522 
523   // Drop uses of any optional data (real or placeholder).
524   if (getNumOperands()) {
525     User::dropAllReferences();
526     setNumHungOffUseOperands(0);
527     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
528   }
529 
530   // Metadata is stored in a side-table.
531   clearMetadata();
532 }
533 
534 void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
535   AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
536 }
537 
538 void Function::addFnAttr(Attribute::AttrKind Kind) {
539   AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
540 }
541 
542 void Function::addFnAttr(StringRef Kind, StringRef Val) {
543   AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
544 }
545 
546 void Function::addFnAttr(Attribute Attr) {
547   AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
548 }
549 
550 void Function::addFnAttrs(const AttrBuilder &Attrs) {
551   AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
552 }
553 
554 void Function::addRetAttr(Attribute::AttrKind Kind) {
555   AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
556 }
557 
558 void Function::addRetAttr(Attribute Attr) {
559   AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
560 }
561 
562 void Function::addRetAttrs(const AttrBuilder &Attrs) {
563   AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
564 }
565 
566 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
567   AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
568 }
569 
570 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
571   AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
572 }
573 
574 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
575   AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
576 }
577 
578 void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
579   AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
580 }
581 
582 void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
583   AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
584 }
585 
586 void Function::removeFnAttr(Attribute::AttrKind Kind) {
587   AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
588 }
589 
590 void Function::removeFnAttr(StringRef Kind) {
591   AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
592 }
593 
594 void Function::removeFnAttrs(const AttributeMask &AM) {
595   AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
596 }
597 
598 void Function::removeRetAttr(Attribute::AttrKind Kind) {
599   AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
600 }
601 
602 void Function::removeRetAttr(StringRef Kind) {
603   AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
604 }
605 
606 void Function::removeRetAttrs(const AttributeMask &Attrs) {
607   AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
608 }
609 
610 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
611   AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
612 }
613 
614 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
615   AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
616 }
617 
618 void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
619   AttributeSets =
620       AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
621 }
622 
623 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
624   AttributeSets =
625       AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
626 }
627 
628 bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {
629   return AttributeSets.hasFnAttr(Kind);
630 }
631 
632 bool Function::hasFnAttribute(StringRef Kind) const {
633   return AttributeSets.hasFnAttr(Kind);
634 }
635 
636 bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {
637   return AttributeSets.hasRetAttr(Kind);
638 }
639 
640 bool Function::hasParamAttribute(unsigned ArgNo,
641                                  Attribute::AttrKind Kind) const {
642   return AttributeSets.hasParamAttr(ArgNo, Kind);
643 }
644 
645 Attribute Function::getAttributeAtIndex(unsigned i,
646                                         Attribute::AttrKind Kind) const {
647   return AttributeSets.getAttributeAtIndex(i, Kind);
648 }
649 
650 Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
651   return AttributeSets.getAttributeAtIndex(i, Kind);
652 }
653 
654 Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
655   return AttributeSets.getFnAttr(Kind);
656 }
657 
658 Attribute Function::getFnAttribute(StringRef Kind) const {
659   return AttributeSets.getFnAttr(Kind);
660 }
661 
662 uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name,
663                                                  uint64_t Default) const {
664   Attribute A = getFnAttribute(Name);
665   uint64_t Result = Default;
666   if (A.isStringAttribute()) {
667     StringRef Str = A.getValueAsString();
668     if (Str.getAsInteger(0, Result))
669       getContext().emitError("cannot parse integer attribute " + Name);
670   }
671 
672   return Result;
673 }
674 
675 /// gets the specified attribute from the list of attributes.
676 Attribute Function::getParamAttribute(unsigned ArgNo,
677                                       Attribute::AttrKind Kind) const {
678   return AttributeSets.getParamAttr(ArgNo, Kind);
679 }
680 
681 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
682                                                  uint64_t Bytes) {
683   AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
684                                                                   ArgNo, Bytes);
685 }
686 
687 DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
688   if (&FPType == &APFloat::IEEEsingle()) {
689     Attribute Attr = getFnAttribute("denormal-fp-math-f32");
690     StringRef Val = Attr.getValueAsString();
691     if (!Val.empty())
692       return parseDenormalFPAttribute(Val);
693 
694     // If the f32 variant of the attribute isn't specified, try to use the
695     // generic one.
696   }
697 
698   Attribute Attr = getFnAttribute("denormal-fp-math");
699   return parseDenormalFPAttribute(Attr.getValueAsString());
700 }
701 
702 const std::string &Function::getGC() const {
703   assert(hasGC() && "Function has no collector");
704   return getContext().getGC(*this);
705 }
706 
707 void Function::setGC(std::string Str) {
708   setValueSubclassDataBit(14, !Str.empty());
709   getContext().setGC(*this, std::move(Str));
710 }
711 
712 void Function::clearGC() {
713   if (!hasGC())
714     return;
715   getContext().deleteGC(*this);
716   setValueSubclassDataBit(14, false);
717 }
718 
719 bool Function::hasStackProtectorFnAttr() const {
720   return hasFnAttribute(Attribute::StackProtect) ||
721          hasFnAttribute(Attribute::StackProtectStrong) ||
722          hasFnAttribute(Attribute::StackProtectReq);
723 }
724 
725 /// Copy all additional attributes (those not needed to create a Function) from
726 /// the Function Src to this one.
727 void Function::copyAttributesFrom(const Function *Src) {
728   GlobalObject::copyAttributesFrom(Src);
729   setCallingConv(Src->getCallingConv());
730   setAttributes(Src->getAttributes());
731   if (Src->hasGC())
732     setGC(Src->getGC());
733   else
734     clearGC();
735   if (Src->hasPersonalityFn())
736     setPersonalityFn(Src->getPersonalityFn());
737   if (Src->hasPrefixData())
738     setPrefixData(Src->getPrefixData());
739   if (Src->hasPrologueData())
740     setPrologueData(Src->getPrologueData());
741 }
742 
743 MemoryEffects Function::getMemoryEffects() const {
744   return getAttributes().getMemoryEffects();
745 }
746 void Function::setMemoryEffects(MemoryEffects ME) {
747   addFnAttr(Attribute::getWithMemoryEffects(getContext(), ME));
748 }
749 
750 /// Determine if the function does not access memory.
751 bool Function::doesNotAccessMemory() const {
752   return getMemoryEffects().doesNotAccessMemory();
753 }
754 void Function::setDoesNotAccessMemory() {
755   setMemoryEffects(MemoryEffects::none());
756 }
757 
758 /// Determine if the function does not access or only reads memory.
759 bool Function::onlyReadsMemory() const {
760   return getMemoryEffects().onlyReadsMemory();
761 }
762 void Function::setOnlyReadsMemory() {
763   setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
764 }
765 
766 /// Determine if the function does not access or only writes memory.
767 bool Function::onlyWritesMemory() const {
768   return getMemoryEffects().onlyWritesMemory();
769 }
770 void Function::setOnlyWritesMemory() {
771   setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
772 }
773 
774 /// Determine if the call can access memmory only using pointers based
775 /// on its arguments.
776 bool Function::onlyAccessesArgMemory() const {
777   return getMemoryEffects().onlyAccessesArgPointees();
778 }
779 void Function::setOnlyAccessesArgMemory() {
780   setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
781 }
782 
783 /// Determine if the function may only access memory that is
784 ///  inaccessible from the IR.
785 bool Function::onlyAccessesInaccessibleMemory() const {
786   return getMemoryEffects().onlyAccessesInaccessibleMem();
787 }
788 void Function::setOnlyAccessesInaccessibleMemory() {
789   setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly());
790 }
791 
792 /// Determine if the function may only access memory that is
793 ///  either inaccessible from the IR or pointed to by its arguments.
794 bool Function::onlyAccessesInaccessibleMemOrArgMem() const {
795   return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
796 }
797 void Function::setOnlyAccessesInaccessibleMemOrArgMem() {
798   setMemoryEffects(getMemoryEffects() &
799                    MemoryEffects::inaccessibleOrArgMemOnly());
800 }
801 
802 /// Table of string intrinsic names indexed by enum value.
803 static const char * const IntrinsicNameTable[] = {
804   "not_intrinsic",
805 #define GET_INTRINSIC_NAME_TABLE
806 #include "llvm/IR/IntrinsicImpl.inc"
807 #undef GET_INTRINSIC_NAME_TABLE
808 };
809 
810 /// Table of per-target intrinsic name tables.
811 #define GET_INTRINSIC_TARGET_DATA
812 #include "llvm/IR/IntrinsicImpl.inc"
813 #undef GET_INTRINSIC_TARGET_DATA
814 
815 bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
816   return IID > TargetInfos[0].Count;
817 }
818 
819 bool Function::isTargetIntrinsic() const {
820   return isTargetIntrinsic(IntID);
821 }
822 
823 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
824 /// target as \c Name, or the generic table if \c Name is not target specific.
825 ///
826 /// Returns the relevant slice of \c IntrinsicNameTable
827 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
828   assert(Name.startswith("llvm."));
829 
830   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
831   // Drop "llvm." and take the first dotted component. That will be the target
832   // if this is target specific.
833   StringRef Target = Name.drop_front(5).split('.').first;
834   auto It = partition_point(
835       Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
836   // We've either found the target or just fall back to the generic set, which
837   // is always first.
838   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
839   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
840 }
841 
842 /// This does the actual lookup of an intrinsic ID which
843 /// matches the given function name.
844 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
845   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
846   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
847   if (Idx == -1)
848     return Intrinsic::not_intrinsic;
849 
850   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
851   // an index into a sub-table.
852   int Adjust = NameTable.data() - IntrinsicNameTable;
853   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
854 
855   // If the intrinsic is not overloaded, require an exact match. If it is
856   // overloaded, require either exact or prefix match.
857   const auto MatchSize = strlen(NameTable[Idx]);
858   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
859   bool IsExactMatch = Name.size() == MatchSize;
860   return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
861                                                      : Intrinsic::not_intrinsic;
862 }
863 
864 void Function::recalculateIntrinsicID() {
865   StringRef Name = getName();
866   if (!Name.startswith("llvm.")) {
867     HasLLVMReservedName = false;
868     IntID = Intrinsic::not_intrinsic;
869     return;
870   }
871   HasLLVMReservedName = true;
872   IntID = lookupIntrinsicID(Name);
873 }
874 
875 /// Returns a stable mangling for the type specified for use in the name
876 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
877 /// of named types is simply their name.  Manglings for unnamed types consist
878 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
879 /// combined with the mangling of their component types.  A vararg function
880 /// type will have a suffix of 'vararg'.  Since function types can contain
881 /// other function types, we close a function type mangling with suffix 'f'
882 /// which can't be confused with it's prefix.  This ensures we don't have
883 /// collisions between two unrelated function types. Otherwise, you might
884 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
885 /// The HasUnnamedType boolean is set if an unnamed type was encountered,
886 /// indicating that extra care must be taken to ensure a unique name.
887 static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
888   std::string Result;
889   if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
890     Result += "p" + utostr(PTyp->getAddressSpace());
891     // Opaque pointer doesn't have pointee type information, so we just mangle
892     // address space for opaque pointer.
893     if (!PTyp->isOpaque())
894       Result += getMangledTypeStr(PTyp->getNonOpaquePointerElementType(),
895                                   HasUnnamedType);
896   } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
897     Result += "a" + utostr(ATyp->getNumElements()) +
898               getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
899   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
900     if (!STyp->isLiteral()) {
901       Result += "s_";
902       if (STyp->hasName())
903         Result += STyp->getName();
904       else
905         HasUnnamedType = true;
906     } else {
907       Result += "sl_";
908       for (auto *Elem : STyp->elements())
909         Result += getMangledTypeStr(Elem, HasUnnamedType);
910     }
911     // Ensure nested structs are distinguishable.
912     Result += "s";
913   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
914     Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
915     for (size_t i = 0; i < FT->getNumParams(); i++)
916       Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
917     if (FT->isVarArg())
918       Result += "vararg";
919     // Ensure nested function types are distinguishable.
920     Result += "f";
921   } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
922     ElementCount EC = VTy->getElementCount();
923     if (EC.isScalable())
924       Result += "nx";
925     Result += "v" + utostr(EC.getKnownMinValue()) +
926               getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
927   } else if (Ty) {
928     switch (Ty->getTypeID()) {
929     default: llvm_unreachable("Unhandled type");
930     case Type::VoidTyID:      Result += "isVoid";   break;
931     case Type::MetadataTyID:  Result += "Metadata"; break;
932     case Type::HalfTyID:      Result += "f16";      break;
933     case Type::BFloatTyID:    Result += "bf16";     break;
934     case Type::FloatTyID:     Result += "f32";      break;
935     case Type::DoubleTyID:    Result += "f64";      break;
936     case Type::X86_FP80TyID:  Result += "f80";      break;
937     case Type::FP128TyID:     Result += "f128";     break;
938     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
939     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
940     case Type::X86_AMXTyID:   Result += "x86amx";   break;
941     case Type::IntegerTyID:
942       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
943       break;
944     }
945   }
946   return Result;
947 }
948 
949 StringRef Intrinsic::getBaseName(ID id) {
950   assert(id < num_intrinsics && "Invalid intrinsic ID!");
951   return IntrinsicNameTable[id];
952 }
953 
954 StringRef Intrinsic::getName(ID id) {
955   assert(id < num_intrinsics && "Invalid intrinsic ID!");
956   assert(!Intrinsic::isOverloaded(id) &&
957          "This version of getName does not support overloading");
958   return getBaseName(id);
959 }
960 
961 static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,
962                                         Module *M, FunctionType *FT,
963                                         bool EarlyModuleCheck) {
964 
965   assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
966   assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&
967          "This version of getName is for overloaded intrinsics only");
968   (void)EarlyModuleCheck;
969   assert((!EarlyModuleCheck || M ||
970           !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&
971          "Intrinsic overloading on pointer types need to provide a Module");
972   bool HasUnnamedType = false;
973   std::string Result(Intrinsic::getBaseName(Id));
974   for (Type *Ty : Tys)
975     Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
976   if (HasUnnamedType) {
977     assert(M && "unnamed types need a module");
978     if (!FT)
979       FT = Intrinsic::getType(M->getContext(), Id, Tys);
980     else
981       assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&
982              "Provided FunctionType must match arguments");
983     return M->getUniqueIntrinsicName(Result, Id, FT);
984   }
985   return Result;
986 }
987 
988 std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
989                                FunctionType *FT) {
990   assert(M && "We need to have a Module");
991   return getIntrinsicNameImpl(Id, Tys, M, FT, true);
992 }
993 
994 std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {
995   return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false);
996 }
997 
998 /// IIT_Info - These are enumerators that describe the entries returned by the
999 /// getIntrinsicInfoTableEntries function.
1000 ///
1001 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
1002 enum IIT_Info {
1003   // Common values should be encoded with 0-15.
1004   IIT_Done = 0,
1005   IIT_I1 = 1,
1006   IIT_I8 = 2,
1007   IIT_I16 = 3,
1008   IIT_I32 = 4,
1009   IIT_I64 = 5,
1010   IIT_F16 = 6,
1011   IIT_F32 = 7,
1012   IIT_F64 = 8,
1013   IIT_V2 = 9,
1014   IIT_V4 = 10,
1015   IIT_V8 = 11,
1016   IIT_V16 = 12,
1017   IIT_V32 = 13,
1018   IIT_PTR = 14,
1019   IIT_ARG = 15,
1020 
1021   // Values from 16+ are only encodable with the inefficient encoding.
1022   IIT_V64 = 16,
1023   IIT_MMX = 17,
1024   IIT_TOKEN = 18,
1025   IIT_METADATA = 19,
1026   IIT_EMPTYSTRUCT = 20,
1027   IIT_STRUCT2 = 21,
1028   IIT_STRUCT3 = 22,
1029   IIT_STRUCT4 = 23,
1030   IIT_STRUCT5 = 24,
1031   IIT_EXTEND_ARG = 25,
1032   IIT_TRUNC_ARG = 26,
1033   IIT_ANYPTR = 27,
1034   IIT_V1 = 28,
1035   IIT_VARARG = 29,
1036   IIT_HALF_VEC_ARG = 30,
1037   IIT_SAME_VEC_WIDTH_ARG = 31,
1038   IIT_PTR_TO_ARG = 32,
1039   IIT_PTR_TO_ELT = 33,
1040   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
1041   IIT_I128 = 35,
1042   IIT_V512 = 36,
1043   IIT_V1024 = 37,
1044   IIT_STRUCT6 = 38,
1045   IIT_STRUCT7 = 39,
1046   IIT_STRUCT8 = 40,
1047   IIT_F128 = 41,
1048   IIT_VEC_ELEMENT = 42,
1049   IIT_SCALABLE_VEC = 43,
1050   IIT_SUBDIVIDE2_ARG = 44,
1051   IIT_SUBDIVIDE4_ARG = 45,
1052   IIT_VEC_OF_BITCASTS_TO_INT = 46,
1053   IIT_V128 = 47,
1054   IIT_BF16 = 48,
1055   IIT_STRUCT9 = 49,
1056   IIT_V256 = 50,
1057   IIT_AMX = 51,
1058   IIT_PPCF128 = 52,
1059   IIT_V3 = 53,
1060   IIT_EXTERNREF = 54,
1061   IIT_FUNCREF = 55,
1062   IIT_ANYPTR_TO_ELT = 56,
1063   IIT_I2 = 57,
1064   IIT_I4 = 58,
1065 };
1066 
1067 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
1068                       IIT_Info LastInfo,
1069                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
1070   using namespace Intrinsic;
1071 
1072   bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
1073 
1074   IIT_Info Info = IIT_Info(Infos[NextElt++]);
1075   unsigned StructElts = 2;
1076 
1077   switch (Info) {
1078   case IIT_Done:
1079     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
1080     return;
1081   case IIT_VARARG:
1082     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
1083     return;
1084   case IIT_MMX:
1085     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
1086     return;
1087   case IIT_AMX:
1088     OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
1089     return;
1090   case IIT_TOKEN:
1091     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
1092     return;
1093   case IIT_METADATA:
1094     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
1095     return;
1096   case IIT_F16:
1097     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
1098     return;
1099   case IIT_BF16:
1100     OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
1101     return;
1102   case IIT_F32:
1103     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
1104     return;
1105   case IIT_F64:
1106     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
1107     return;
1108   case IIT_F128:
1109     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
1110     return;
1111   case IIT_PPCF128:
1112     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));
1113     return;
1114   case IIT_I1:
1115     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
1116     return;
1117   case IIT_I2:
1118     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2));
1119     return;
1120   case IIT_I4:
1121     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4));
1122     return;
1123   case IIT_I8:
1124     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
1125     return;
1126   case IIT_I16:
1127     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
1128     return;
1129   case IIT_I32:
1130     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
1131     return;
1132   case IIT_I64:
1133     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
1134     return;
1135   case IIT_I128:
1136     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
1137     return;
1138   case IIT_V1:
1139     OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
1140     DecodeIITType(NextElt, Infos, Info, OutputTable);
1141     return;
1142   case IIT_V2:
1143     OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
1144     DecodeIITType(NextElt, Infos, Info, OutputTable);
1145     return;
1146   case IIT_V3:
1147     OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector));
1148     DecodeIITType(NextElt, Infos, Info, OutputTable);
1149     return;
1150   case IIT_V4:
1151     OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
1152     DecodeIITType(NextElt, Infos, Info, OutputTable);
1153     return;
1154   case IIT_V8:
1155     OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
1156     DecodeIITType(NextElt, Infos, Info, OutputTable);
1157     return;
1158   case IIT_V16:
1159     OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
1160     DecodeIITType(NextElt, Infos, Info, OutputTable);
1161     return;
1162   case IIT_V32:
1163     OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
1164     DecodeIITType(NextElt, Infos, Info, OutputTable);
1165     return;
1166   case IIT_V64:
1167     OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
1168     DecodeIITType(NextElt, Infos, Info, OutputTable);
1169     return;
1170   case IIT_V128:
1171     OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
1172     DecodeIITType(NextElt, Infos, Info, OutputTable);
1173     return;
1174   case IIT_V256:
1175     OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
1176     DecodeIITType(NextElt, Infos, Info, OutputTable);
1177     return;
1178   case IIT_V512:
1179     OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
1180     DecodeIITType(NextElt, Infos, Info, OutputTable);
1181     return;
1182   case IIT_V1024:
1183     OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
1184     DecodeIITType(NextElt, Infos, Info, OutputTable);
1185     return;
1186   case IIT_EXTERNREF:
1187     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));
1188     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
1189     return;
1190   case IIT_FUNCREF:
1191     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));
1192     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
1193     return;
1194   case IIT_PTR:
1195     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
1196     DecodeIITType(NextElt, Infos, Info, OutputTable);
1197     return;
1198   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
1199     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
1200                                              Infos[NextElt++]));
1201     DecodeIITType(NextElt, Infos, Info, OutputTable);
1202     return;
1203   }
1204   case IIT_ARG: {
1205     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1206     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
1207     return;
1208   }
1209   case IIT_EXTEND_ARG: {
1210     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1211     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
1212                                              ArgInfo));
1213     return;
1214   }
1215   case IIT_TRUNC_ARG: {
1216     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1217     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
1218                                              ArgInfo));
1219     return;
1220   }
1221   case IIT_HALF_VEC_ARG: {
1222     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1223     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
1224                                              ArgInfo));
1225     return;
1226   }
1227   case IIT_SAME_VEC_WIDTH_ARG: {
1228     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1229     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
1230                                              ArgInfo));
1231     return;
1232   }
1233   case IIT_PTR_TO_ARG: {
1234     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1235     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
1236                                              ArgInfo));
1237     return;
1238   }
1239   case IIT_PTR_TO_ELT: {
1240     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1241     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
1242     return;
1243   }
1244   case IIT_ANYPTR_TO_ELT: {
1245     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1246     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1247     OutputTable.push_back(
1248         IITDescriptor::get(IITDescriptor::AnyPtrToElt, ArgNo, RefNo));
1249     return;
1250   }
1251   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
1252     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1253     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1254     OutputTable.push_back(
1255         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
1256     return;
1257   }
1258   case IIT_EMPTYSTRUCT:
1259     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
1260     return;
1261   case IIT_STRUCT9: ++StructElts; [[fallthrough]];
1262   case IIT_STRUCT8: ++StructElts; [[fallthrough]];
1263   case IIT_STRUCT7: ++StructElts; [[fallthrough]];
1264   case IIT_STRUCT6: ++StructElts; [[fallthrough]];
1265   case IIT_STRUCT5: ++StructElts; [[fallthrough]];
1266   case IIT_STRUCT4: ++StructElts; [[fallthrough]];
1267   case IIT_STRUCT3: ++StructElts; [[fallthrough]];
1268   case IIT_STRUCT2: {
1269     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
1270 
1271     for (unsigned i = 0; i != StructElts; ++i)
1272       DecodeIITType(NextElt, Infos, Info, OutputTable);
1273     return;
1274   }
1275   case IIT_SUBDIVIDE2_ARG: {
1276     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1277     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
1278                                              ArgInfo));
1279     return;
1280   }
1281   case IIT_SUBDIVIDE4_ARG: {
1282     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1283     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
1284                                              ArgInfo));
1285     return;
1286   }
1287   case IIT_VEC_ELEMENT: {
1288     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1289     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
1290                                              ArgInfo));
1291     return;
1292   }
1293   case IIT_SCALABLE_VEC: {
1294     DecodeIITType(NextElt, Infos, Info, OutputTable);
1295     return;
1296   }
1297   case IIT_VEC_OF_BITCASTS_TO_INT: {
1298     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1299     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
1300                                              ArgInfo));
1301     return;
1302   }
1303   }
1304   llvm_unreachable("unhandled");
1305 }
1306 
1307 #define GET_INTRINSIC_GENERATOR_GLOBAL
1308 #include "llvm/IR/IntrinsicImpl.inc"
1309 #undef GET_INTRINSIC_GENERATOR_GLOBAL
1310 
1311 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
1312                                              SmallVectorImpl<IITDescriptor> &T){
1313   // Check to see if the intrinsic's type was expressible by the table.
1314   unsigned TableVal = IIT_Table[id-1];
1315 
1316   // Decode the TableVal into an array of IITValues.
1317   SmallVector<unsigned char, 8> IITValues;
1318   ArrayRef<unsigned char> IITEntries;
1319   unsigned NextElt = 0;
1320   if ((TableVal >> 31) != 0) {
1321     // This is an offset into the IIT_LongEncodingTable.
1322     IITEntries = IIT_LongEncodingTable;
1323 
1324     // Strip sentinel bit.
1325     NextElt = (TableVal << 1) >> 1;
1326   } else {
1327     // Decode the TableVal into an array of IITValues.  If the entry was encoded
1328     // into a single word in the table itself, decode it now.
1329     do {
1330       IITValues.push_back(TableVal & 0xF);
1331       TableVal >>= 4;
1332     } while (TableVal);
1333 
1334     IITEntries = IITValues;
1335     NextElt = 0;
1336   }
1337 
1338   // Okay, decode the table into the output vector of IITDescriptors.
1339   DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1340   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1341     DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1342 }
1343 
1344 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1345                              ArrayRef<Type*> Tys, LLVMContext &Context) {
1346   using namespace Intrinsic;
1347 
1348   IITDescriptor D = Infos.front();
1349   Infos = Infos.slice(1);
1350 
1351   switch (D.Kind) {
1352   case IITDescriptor::Void: return Type::getVoidTy(Context);
1353   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1354   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1355   case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
1356   case IITDescriptor::Token: return Type::getTokenTy(Context);
1357   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1358   case IITDescriptor::Half: return Type::getHalfTy(Context);
1359   case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1360   case IITDescriptor::Float: return Type::getFloatTy(Context);
1361   case IITDescriptor::Double: return Type::getDoubleTy(Context);
1362   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1363   case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context);
1364 
1365   case IITDescriptor::Integer:
1366     return IntegerType::get(Context, D.Integer_Width);
1367   case IITDescriptor::Vector:
1368     return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1369                            D.Vector_Width);
1370   case IITDescriptor::Pointer:
1371     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1372                             D.Pointer_AddressSpace);
1373   case IITDescriptor::Struct: {
1374     SmallVector<Type *, 8> Elts;
1375     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1376       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1377     return StructType::get(Context, Elts);
1378   }
1379   case IITDescriptor::Argument:
1380     return Tys[D.getArgumentNumber()];
1381   case IITDescriptor::ExtendArgument: {
1382     Type *Ty = Tys[D.getArgumentNumber()];
1383     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1384       return VectorType::getExtendedElementVectorType(VTy);
1385 
1386     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1387   }
1388   case IITDescriptor::TruncArgument: {
1389     Type *Ty = Tys[D.getArgumentNumber()];
1390     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1391       return VectorType::getTruncatedElementVectorType(VTy);
1392 
1393     IntegerType *ITy = cast<IntegerType>(Ty);
1394     assert(ITy->getBitWidth() % 2 == 0);
1395     return IntegerType::get(Context, ITy->getBitWidth() / 2);
1396   }
1397   case IITDescriptor::Subdivide2Argument:
1398   case IITDescriptor::Subdivide4Argument: {
1399     Type *Ty = Tys[D.getArgumentNumber()];
1400     VectorType *VTy = dyn_cast<VectorType>(Ty);
1401     assert(VTy && "Expected an argument of Vector Type");
1402     int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1403     return VectorType::getSubdividedVectorType(VTy, SubDivs);
1404   }
1405   case IITDescriptor::HalfVecArgument:
1406     return VectorType::getHalfElementsVectorType(cast<VectorType>(
1407                                                   Tys[D.getArgumentNumber()]));
1408   case IITDescriptor::SameVecWidthArgument: {
1409     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1410     Type *Ty = Tys[D.getArgumentNumber()];
1411     if (auto *VTy = dyn_cast<VectorType>(Ty))
1412       return VectorType::get(EltTy, VTy->getElementCount());
1413     return EltTy;
1414   }
1415   case IITDescriptor::PtrToArgument: {
1416     Type *Ty = Tys[D.getArgumentNumber()];
1417     return PointerType::getUnqual(Ty);
1418   }
1419   case IITDescriptor::PtrToElt: {
1420     Type *Ty = Tys[D.getArgumentNumber()];
1421     VectorType *VTy = dyn_cast<VectorType>(Ty);
1422     if (!VTy)
1423       llvm_unreachable("Expected an argument of Vector Type");
1424     Type *EltTy = VTy->getElementType();
1425     return PointerType::getUnqual(EltTy);
1426   }
1427   case IITDescriptor::VecElementArgument: {
1428     Type *Ty = Tys[D.getArgumentNumber()];
1429     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1430       return VTy->getElementType();
1431     llvm_unreachable("Expected an argument of Vector Type");
1432   }
1433   case IITDescriptor::VecOfBitcastsToInt: {
1434     Type *Ty = Tys[D.getArgumentNumber()];
1435     VectorType *VTy = dyn_cast<VectorType>(Ty);
1436     assert(VTy && "Expected an argument of Vector Type");
1437     return VectorType::getInteger(VTy);
1438   }
1439   case IITDescriptor::VecOfAnyPtrsToElt:
1440     // Return the overloaded type (which determines the pointers address space)
1441     return Tys[D.getOverloadArgNumber()];
1442   case IITDescriptor::AnyPtrToElt:
1443     // Return the overloaded type (which determines the pointers address space)
1444     return Tys[D.getOverloadArgNumber()];
1445   }
1446   llvm_unreachable("unhandled");
1447 }
1448 
1449 FunctionType *Intrinsic::getType(LLVMContext &Context,
1450                                  ID id, ArrayRef<Type*> Tys) {
1451   SmallVector<IITDescriptor, 8> Table;
1452   getIntrinsicInfoTableEntries(id, Table);
1453 
1454   ArrayRef<IITDescriptor> TableRef = Table;
1455   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
1456 
1457   SmallVector<Type*, 8> ArgTys;
1458   while (!TableRef.empty())
1459     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1460 
1461   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1462   // If we see void type as the type of the last argument, it is vararg intrinsic
1463   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1464     ArgTys.pop_back();
1465     return FunctionType::get(ResultTy, ArgTys, true);
1466   }
1467   return FunctionType::get(ResultTy, ArgTys, false);
1468 }
1469 
1470 bool Intrinsic::isOverloaded(ID id) {
1471 #define GET_INTRINSIC_OVERLOAD_TABLE
1472 #include "llvm/IR/IntrinsicImpl.inc"
1473 #undef GET_INTRINSIC_OVERLOAD_TABLE
1474 }
1475 
1476 bool Intrinsic::isLeaf(ID id) {
1477   switch (id) {
1478   default:
1479     return true;
1480 
1481   case Intrinsic::experimental_gc_statepoint:
1482   case Intrinsic::experimental_patchpoint_void:
1483   case Intrinsic::experimental_patchpoint_i64:
1484     return false;
1485   }
1486 }
1487 
1488 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1489 #define GET_INTRINSIC_ATTRIBUTES
1490 #include "llvm/IR/IntrinsicImpl.inc"
1491 #undef GET_INTRINSIC_ATTRIBUTES
1492 
1493 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1494   // There can never be multiple globals with the same name of different types,
1495   // because intrinsics must be a specific type.
1496   auto *FT = getType(M->getContext(), id, Tys);
1497   return cast<Function>(
1498       M->getOrInsertFunction(
1499            Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT)
1500           .getCallee());
1501 }
1502 
1503 // This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.
1504 #define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
1505 #include "llvm/IR/IntrinsicImpl.inc"
1506 #undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
1507 
1508 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1509 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1510 #include "llvm/IR/IntrinsicImpl.inc"
1511 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1512 
1513 using DeferredIntrinsicMatchPair =
1514     std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1515 
1516 static bool matchIntrinsicType(
1517     Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1518     SmallVectorImpl<Type *> &ArgTys,
1519     SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1520     bool IsDeferredCheck) {
1521   using namespace Intrinsic;
1522 
1523   // If we ran out of descriptors, there are too many arguments.
1524   if (Infos.empty()) return true;
1525 
1526   // Do this before slicing off the 'front' part
1527   auto InfosRef = Infos;
1528   auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1529     DeferredChecks.emplace_back(T, InfosRef);
1530     return false;
1531   };
1532 
1533   IITDescriptor D = Infos.front();
1534   Infos = Infos.slice(1);
1535 
1536   switch (D.Kind) {
1537     case IITDescriptor::Void: return !Ty->isVoidTy();
1538     case IITDescriptor::VarArg: return true;
1539     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1540     case IITDescriptor::AMX:  return !Ty->isX86_AMXTy();
1541     case IITDescriptor::Token: return !Ty->isTokenTy();
1542     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1543     case IITDescriptor::Half: return !Ty->isHalfTy();
1544     case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1545     case IITDescriptor::Float: return !Ty->isFloatTy();
1546     case IITDescriptor::Double: return !Ty->isDoubleTy();
1547     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1548     case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty();
1549     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1550     case IITDescriptor::Vector: {
1551       VectorType *VT = dyn_cast<VectorType>(Ty);
1552       return !VT || VT->getElementCount() != D.Vector_Width ||
1553              matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1554                                 DeferredChecks, IsDeferredCheck);
1555     }
1556     case IITDescriptor::Pointer: {
1557       PointerType *PT = dyn_cast<PointerType>(Ty);
1558       if (!PT || PT->getAddressSpace() != D.Pointer_AddressSpace)
1559         return true;
1560       if (!PT->isOpaque()) {
1561         /* Manually consume a pointer to empty struct descriptor, which is
1562          * used for externref. We don't want to enforce that the struct is
1563          * anonymous in this case. (This renders externref intrinsics
1564          * non-unique, but this will go away with opaque pointers anyway.) */
1565         if (Infos.front().Kind == IITDescriptor::Struct &&
1566             Infos.front().Struct_NumElements == 0) {
1567           Infos = Infos.slice(1);
1568           return false;
1569         }
1570         return matchIntrinsicType(PT->getNonOpaquePointerElementType(), Infos,
1571                                   ArgTys, DeferredChecks, IsDeferredCheck);
1572       }
1573       // Consume IIT descriptors relating to the pointer element type.
1574       // FIXME: Intrinsic type matching of nested single value types or even
1575       // aggregates doesn't work properly with opaque pointers but hopefully
1576       // doesn't happen in practice.
1577       while (Infos.front().Kind == IITDescriptor::Pointer ||
1578              Infos.front().Kind == IITDescriptor::Vector)
1579         Infos = Infos.slice(1);
1580       assert((Infos.front().Kind != IITDescriptor::Argument ||
1581               Infos.front().getArgumentKind() == IITDescriptor::AK_MatchType) &&
1582              "Unsupported polymorphic pointer type with opaque pointer");
1583       Infos = Infos.slice(1);
1584       return false;
1585     }
1586 
1587     case IITDescriptor::Struct: {
1588       StructType *ST = dyn_cast<StructType>(Ty);
1589       if (!ST || !ST->isLiteral() || ST->isPacked() ||
1590           ST->getNumElements() != D.Struct_NumElements)
1591         return true;
1592 
1593       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1594         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1595                                DeferredChecks, IsDeferredCheck))
1596           return true;
1597       return false;
1598     }
1599 
1600     case IITDescriptor::Argument:
1601       // If this is the second occurrence of an argument,
1602       // verify that the later instance matches the previous instance.
1603       if (D.getArgumentNumber() < ArgTys.size())
1604         return Ty != ArgTys[D.getArgumentNumber()];
1605 
1606       if (D.getArgumentNumber() > ArgTys.size() ||
1607           D.getArgumentKind() == IITDescriptor::AK_MatchType)
1608         return IsDeferredCheck || DeferCheck(Ty);
1609 
1610       assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
1611              "Table consistency error");
1612       ArgTys.push_back(Ty);
1613 
1614       switch (D.getArgumentKind()) {
1615         case IITDescriptor::AK_Any:        return false; // Success
1616         case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1617         case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1618         case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1619         case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1620         default:                           break;
1621       }
1622       llvm_unreachable("all argument kinds not covered");
1623 
1624     case IITDescriptor::ExtendArgument: {
1625       // If this is a forward reference, defer the check for later.
1626       if (D.getArgumentNumber() >= ArgTys.size())
1627         return IsDeferredCheck || DeferCheck(Ty);
1628 
1629       Type *NewTy = ArgTys[D.getArgumentNumber()];
1630       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1631         NewTy = VectorType::getExtendedElementVectorType(VTy);
1632       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1633         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1634       else
1635         return true;
1636 
1637       return Ty != NewTy;
1638     }
1639     case IITDescriptor::TruncArgument: {
1640       // If this is a forward reference, defer the check for later.
1641       if (D.getArgumentNumber() >= ArgTys.size())
1642         return IsDeferredCheck || DeferCheck(Ty);
1643 
1644       Type *NewTy = ArgTys[D.getArgumentNumber()];
1645       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1646         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1647       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1648         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1649       else
1650         return true;
1651 
1652       return Ty != NewTy;
1653     }
1654     case IITDescriptor::HalfVecArgument:
1655       // If this is a forward reference, defer the check for later.
1656       if (D.getArgumentNumber() >= ArgTys.size())
1657         return IsDeferredCheck || DeferCheck(Ty);
1658       return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1659              VectorType::getHalfElementsVectorType(
1660                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1661     case IITDescriptor::SameVecWidthArgument: {
1662       if (D.getArgumentNumber() >= ArgTys.size()) {
1663         // Defer check and subsequent check for the vector element type.
1664         Infos = Infos.slice(1);
1665         return IsDeferredCheck || DeferCheck(Ty);
1666       }
1667       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1668       auto *ThisArgType = dyn_cast<VectorType>(Ty);
1669       // Both must be vectors of the same number of elements or neither.
1670       if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1671         return true;
1672       Type *EltTy = Ty;
1673       if (ThisArgType) {
1674         if (ReferenceType->getElementCount() !=
1675             ThisArgType->getElementCount())
1676           return true;
1677         EltTy = ThisArgType->getElementType();
1678       }
1679       return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1680                                 IsDeferredCheck);
1681     }
1682     case IITDescriptor::PtrToArgument: {
1683       if (D.getArgumentNumber() >= ArgTys.size())
1684         return IsDeferredCheck || DeferCheck(Ty);
1685       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1686       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1687       return (!ThisArgType ||
1688               !ThisArgType->isOpaqueOrPointeeTypeMatches(ReferenceType));
1689     }
1690     case IITDescriptor::PtrToElt: {
1691       if (D.getArgumentNumber() >= ArgTys.size())
1692         return IsDeferredCheck || DeferCheck(Ty);
1693       VectorType * ReferenceType =
1694         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1695       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1696 
1697       if (!ThisArgType || !ReferenceType)
1698         return true;
1699       return !ThisArgType->isOpaqueOrPointeeTypeMatches(
1700           ReferenceType->getElementType());
1701     }
1702     case IITDescriptor::AnyPtrToElt: {
1703       unsigned RefArgNumber = D.getRefArgNumber();
1704       if (RefArgNumber >= ArgTys.size()) {
1705         if (IsDeferredCheck)
1706           return true;
1707         // If forward referencing, already add the pointer type and
1708         // defer the checks for later.
1709         ArgTys.push_back(Ty);
1710         return DeferCheck(Ty);
1711       }
1712 
1713       if (!IsDeferredCheck) {
1714         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1715                "Table consistency error");
1716         ArgTys.push_back(Ty);
1717       }
1718 
1719       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1720       auto *ThisArgType = dyn_cast<PointerType>(Ty);
1721       if (!ThisArgType || !ReferenceType)
1722         return true;
1723       return !ThisArgType->isOpaqueOrPointeeTypeMatches(
1724           ReferenceType->getElementType());
1725     }
1726     case IITDescriptor::VecOfAnyPtrsToElt: {
1727       unsigned RefArgNumber = D.getRefArgNumber();
1728       if (RefArgNumber >= ArgTys.size()) {
1729         if (IsDeferredCheck)
1730           return true;
1731         // If forward referencing, already add the pointer-vector type and
1732         // defer the checks for later.
1733         ArgTys.push_back(Ty);
1734         return DeferCheck(Ty);
1735       }
1736 
1737       if (!IsDeferredCheck){
1738         assert(D.getOverloadArgNumber() == ArgTys.size() &&
1739                "Table consistency error");
1740         ArgTys.push_back(Ty);
1741       }
1742 
1743       // Verify the overloaded type "matches" the Ref type.
1744       // i.e. Ty is a vector with the same width as Ref.
1745       // Composed of pointers to the same element type as Ref.
1746       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1747       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1748       if (!ThisArgVecTy || !ReferenceType ||
1749           (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1750         return true;
1751       PointerType *ThisArgEltTy =
1752           dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1753       if (!ThisArgEltTy)
1754         return true;
1755       return !ThisArgEltTy->isOpaqueOrPointeeTypeMatches(
1756           ReferenceType->getElementType());
1757     }
1758     case IITDescriptor::VecElementArgument: {
1759       if (D.getArgumentNumber() >= ArgTys.size())
1760         return IsDeferredCheck ? true : DeferCheck(Ty);
1761       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1762       return !ReferenceType || Ty != ReferenceType->getElementType();
1763     }
1764     case IITDescriptor::Subdivide2Argument:
1765     case IITDescriptor::Subdivide4Argument: {
1766       // If this is a forward reference, defer the check for later.
1767       if (D.getArgumentNumber() >= ArgTys.size())
1768         return IsDeferredCheck || DeferCheck(Ty);
1769 
1770       Type *NewTy = ArgTys[D.getArgumentNumber()];
1771       if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1772         int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1773         NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1774         return Ty != NewTy;
1775       }
1776       return true;
1777     }
1778     case IITDescriptor::VecOfBitcastsToInt: {
1779       if (D.getArgumentNumber() >= ArgTys.size())
1780         return IsDeferredCheck || DeferCheck(Ty);
1781       auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1782       auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1783       if (!ThisArgVecTy || !ReferenceType)
1784         return true;
1785       return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1786     }
1787   }
1788   llvm_unreachable("unhandled");
1789 }
1790 
1791 Intrinsic::MatchIntrinsicTypesResult
1792 Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1793                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1794                                    SmallVectorImpl<Type *> &ArgTys) {
1795   SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1796   if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1797                          false))
1798     return MatchIntrinsicTypes_NoMatchRet;
1799 
1800   unsigned NumDeferredReturnChecks = DeferredChecks.size();
1801 
1802   for (auto *Ty : FTy->params())
1803     if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1804       return MatchIntrinsicTypes_NoMatchArg;
1805 
1806   for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1807     DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1808     if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1809                            true))
1810       return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1811                                          : MatchIntrinsicTypes_NoMatchArg;
1812   }
1813 
1814   return MatchIntrinsicTypes_Match;
1815 }
1816 
1817 bool
1818 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1819                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1820   // If there are no descriptors left, then it can't be a vararg.
1821   if (Infos.empty())
1822     return isVarArg;
1823 
1824   // There should be only one descriptor remaining at this point.
1825   if (Infos.size() != 1)
1826     return true;
1827 
1828   // Check and verify the descriptor.
1829   IITDescriptor D = Infos.front();
1830   Infos = Infos.slice(1);
1831   if (D.Kind == IITDescriptor::VarArg)
1832     return !isVarArg;
1833 
1834   return true;
1835 }
1836 
1837 bool Intrinsic::getIntrinsicSignature(Function *F,
1838                                       SmallVectorImpl<Type *> &ArgTys) {
1839   Intrinsic::ID ID = F->getIntrinsicID();
1840   if (!ID)
1841     return false;
1842 
1843   SmallVector<Intrinsic::IITDescriptor, 8> Table;
1844   getIntrinsicInfoTableEntries(ID, Table);
1845   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1846 
1847   if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
1848                                          ArgTys) !=
1849       Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1850     return false;
1851   }
1852   if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
1853                                       TableRef))
1854     return false;
1855   return true;
1856 }
1857 
1858 std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1859   SmallVector<Type *, 4> ArgTys;
1860   if (!getIntrinsicSignature(F, ArgTys))
1861     return std::nullopt;
1862 
1863   Intrinsic::ID ID = F->getIntrinsicID();
1864   StringRef Name = F->getName();
1865   std::string WantedName =
1866       Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType());
1867   if (Name == WantedName)
1868     return std::nullopt;
1869 
1870   Function *NewDecl = [&] {
1871     if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
1872       if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
1873         if (ExistingF->getFunctionType() == F->getFunctionType())
1874           return ExistingF;
1875 
1876       // The name already exists, but is not a function or has the wrong
1877       // prototype. Make place for the new one by renaming the old version.
1878       // Either this old version will be removed later on or the module is
1879       // invalid and we'll get an error.
1880       ExistingGV->setName(WantedName + ".renamed");
1881     }
1882     return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1883   }();
1884 
1885   NewDecl->setCallingConv(F->getCallingConv());
1886   assert(NewDecl->getFunctionType() == F->getFunctionType() &&
1887          "Shouldn't change the signature");
1888   return NewDecl;
1889 }
1890 
1891 static bool isPointerCastOperator(const User *U) {
1892   return isa<AddrSpaceCastOperator>(U) || isa<BitCastOperator>(U);
1893 }
1894 
1895 /// hasAddressTaken - returns true if there are any uses of this function
1896 /// other than direct calls or invokes to it. Optionally ignores callback
1897 /// uses, assume like pointer annotation calls, and references in llvm.used
1898 /// and llvm.compiler.used variables.
1899 bool Function::hasAddressTaken(const User **PutOffender,
1900                                bool IgnoreCallbackUses,
1901                                bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
1902                                bool IgnoreARCAttachedCall) const {
1903   for (const Use &U : uses()) {
1904     const User *FU = U.getUser();
1905     if (isa<BlockAddress>(FU))
1906       continue;
1907 
1908     if (IgnoreCallbackUses) {
1909       AbstractCallSite ACS(&U);
1910       if (ACS && ACS.isCallbackCall())
1911         continue;
1912     }
1913 
1914     const auto *Call = dyn_cast<CallBase>(FU);
1915     if (!Call) {
1916       if (IgnoreAssumeLikeCalls && isPointerCastOperator(FU) &&
1917           all_of(FU->users(), [](const User *U) {
1918             if (const auto *I = dyn_cast<IntrinsicInst>(U))
1919               return I->isAssumeLikeIntrinsic();
1920             return false;
1921           })) {
1922         continue;
1923       }
1924 
1925       if (IgnoreLLVMUsed && !FU->user_empty()) {
1926         const User *FUU = FU;
1927         if (isa<BitCastOperator>(FU) && FU->hasOneUse() &&
1928             !FU->user_begin()->user_empty())
1929           FUU = *FU->user_begin();
1930         if (llvm::all_of(FUU->users(), [](const User *U) {
1931               if (const auto *GV = dyn_cast<GlobalVariable>(U))
1932                 return GV->hasName() &&
1933                        (GV->getName().equals("llvm.compiler.used") ||
1934                         GV->getName().equals("llvm.used"));
1935               return false;
1936             }))
1937           continue;
1938       }
1939       if (PutOffender)
1940         *PutOffender = FU;
1941       return true;
1942     }
1943 
1944     if (IgnoreAssumeLikeCalls) {
1945       if (const auto *I = dyn_cast<IntrinsicInst>(Call))
1946         if (I->isAssumeLikeIntrinsic())
1947           continue;
1948     }
1949 
1950     if (!Call->isCallee(&U) || Call->getFunctionType() != getFunctionType()) {
1951       if (IgnoreARCAttachedCall &&
1952           Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
1953                                       U.getOperandNo()))
1954         continue;
1955 
1956       if (PutOffender)
1957         *PutOffender = FU;
1958       return true;
1959     }
1960   }
1961   return false;
1962 }
1963 
1964 bool Function::isDefTriviallyDead() const {
1965   // Check the linkage
1966   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1967       !hasAvailableExternallyLinkage())
1968     return false;
1969 
1970   // Check if the function is used by anything other than a blockaddress.
1971   for (const User *U : users())
1972     if (!isa<BlockAddress>(U))
1973       return false;
1974 
1975   return true;
1976 }
1977 
1978 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1979 /// setjmp or other function that gcc recognizes as "returning twice".
1980 bool Function::callsFunctionThatReturnsTwice() const {
1981   for (const Instruction &I : instructions(this))
1982     if (const auto *Call = dyn_cast<CallBase>(&I))
1983       if (Call->hasFnAttr(Attribute::ReturnsTwice))
1984         return true;
1985 
1986   return false;
1987 }
1988 
1989 Constant *Function::getPersonalityFn() const {
1990   assert(hasPersonalityFn() && getNumOperands());
1991   return cast<Constant>(Op<0>());
1992 }
1993 
1994 void Function::setPersonalityFn(Constant *Fn) {
1995   setHungoffOperand<0>(Fn);
1996   setValueSubclassDataBit(3, Fn != nullptr);
1997 }
1998 
1999 Constant *Function::getPrefixData() const {
2000   assert(hasPrefixData() && getNumOperands());
2001   return cast<Constant>(Op<1>());
2002 }
2003 
2004 void Function::setPrefixData(Constant *PrefixData) {
2005   setHungoffOperand<1>(PrefixData);
2006   setValueSubclassDataBit(1, PrefixData != nullptr);
2007 }
2008 
2009 Constant *Function::getPrologueData() const {
2010   assert(hasPrologueData() && getNumOperands());
2011   return cast<Constant>(Op<2>());
2012 }
2013 
2014 void Function::setPrologueData(Constant *PrologueData) {
2015   setHungoffOperand<2>(PrologueData);
2016   setValueSubclassDataBit(2, PrologueData != nullptr);
2017 }
2018 
2019 void Function::allocHungoffUselist() {
2020   // If we've already allocated a uselist, stop here.
2021   if (getNumOperands())
2022     return;
2023 
2024   allocHungoffUses(3, /*IsPhi=*/ false);
2025   setNumHungOffUseOperands(3);
2026 
2027   // Initialize the uselist with placeholder operands to allow traversal.
2028   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
2029   Op<0>().set(CPN);
2030   Op<1>().set(CPN);
2031   Op<2>().set(CPN);
2032 }
2033 
2034 template <int Idx>
2035 void Function::setHungoffOperand(Constant *C) {
2036   if (C) {
2037     allocHungoffUselist();
2038     Op<Idx>().set(C);
2039   } else if (getNumOperands()) {
2040     Op<Idx>().set(
2041         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
2042   }
2043 }
2044 
2045 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
2046   assert(Bit < 16 && "SubclassData contains only 16 bits");
2047   if (On)
2048     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
2049   else
2050     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
2051 }
2052 
2053 void Function::setEntryCount(ProfileCount Count,
2054                              const DenseSet<GlobalValue::GUID> *S) {
2055 #if !defined(NDEBUG)
2056   auto PrevCount = getEntryCount();
2057   assert(!PrevCount || PrevCount->getType() == Count.getType());
2058 #endif
2059 
2060   auto ImportGUIDs = getImportGUIDs();
2061   if (S == nullptr && ImportGUIDs.size())
2062     S = &ImportGUIDs;
2063 
2064   MDBuilder MDB(getContext());
2065   setMetadata(
2066       LLVMContext::MD_prof,
2067       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
2068 }
2069 
2070 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
2071                              const DenseSet<GlobalValue::GUID> *Imports) {
2072   setEntryCount(ProfileCount(Count, Type), Imports);
2073 }
2074 
2075 std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
2076   MDNode *MD = getMetadata(LLVMContext::MD_prof);
2077   if (MD && MD->getOperand(0))
2078     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
2079       if (MDS->getString().equals("function_entry_count")) {
2080         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
2081         uint64_t Count = CI->getValue().getZExtValue();
2082         // A value of -1 is used for SamplePGO when there were no samples.
2083         // Treat this the same as unknown.
2084         if (Count == (uint64_t)-1)
2085           return std::nullopt;
2086         return ProfileCount(Count, PCT_Real);
2087       } else if (AllowSynthetic &&
2088                  MDS->getString().equals("synthetic_function_entry_count")) {
2089         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
2090         uint64_t Count = CI->getValue().getZExtValue();
2091         return ProfileCount(Count, PCT_Synthetic);
2092       }
2093     }
2094   return std::nullopt;
2095 }
2096 
2097 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
2098   DenseSet<GlobalValue::GUID> R;
2099   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
2100     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
2101       if (MDS->getString().equals("function_entry_count"))
2102         for (unsigned i = 2; i < MD->getNumOperands(); i++)
2103           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
2104                        ->getValue()
2105                        .getZExtValue());
2106   return R;
2107 }
2108 
2109 void Function::setSectionPrefix(StringRef Prefix) {
2110   MDBuilder MDB(getContext());
2111   setMetadata(LLVMContext::MD_section_prefix,
2112               MDB.createFunctionSectionPrefix(Prefix));
2113 }
2114 
2115 std::optional<StringRef> Function::getSectionPrefix() const {
2116   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
2117     assert(cast<MDString>(MD->getOperand(0))
2118                ->getString()
2119                .equals("function_section_prefix") &&
2120            "Metadata not match");
2121     return cast<MDString>(MD->getOperand(1))->getString();
2122   }
2123   return std::nullopt;
2124 }
2125 
2126 bool Function::nullPointerIsDefined() const {
2127   return hasFnAttribute(Attribute::NullPointerIsValid);
2128 }
2129 
2130 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
2131   if (F && F->nullPointerIsDefined())
2132     return true;
2133 
2134   if (AS != 0)
2135     return true;
2136 
2137   return false;
2138 }
2139