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