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