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