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