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