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