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