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